LLVM API Documentation

LiveRangeCalc.cpp
Go to the documentation of this file.
00001 //===---- LiveRangeCalc.cpp - Calculate live ranges -----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Implementation of the LiveRangeCalc class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "regalloc"
00015 #include "LiveRangeCalc.h"
00016 #include "llvm/CodeGen/MachineDominators.h"
00017 #include "llvm/CodeGen/MachineRegisterInfo.h"
00018 
00019 using namespace llvm;
00020 
00021 void LiveRangeCalc::reset(const MachineFunction *mf,
00022                           SlotIndexes *SI,
00023                           MachineDominatorTree *MDT,
00024                           VNInfo::Allocator *VNIA) {
00025   MF = mf;
00026   MRI = &MF->getRegInfo();
00027   Indexes = SI;
00028   DomTree = MDT;
00029   Alloc = VNIA;
00030 
00031   unsigned N = MF->getNumBlockIDs();
00032   Seen.clear();
00033   Seen.resize(N);
00034   LiveOut.resize(N);
00035   LiveIn.clear();
00036 }
00037 
00038 
00039 void LiveRangeCalc::createDeadDefs(LiveInterval *LI, unsigned Reg) {
00040   assert(MRI && Indexes && "call reset() first");
00041 
00042   // Visit all def operands. If the same instruction has multiple defs of Reg,
00043   // LI->createDeadDef() will deduplicate.
00044   for (MachineRegisterInfo::def_iterator
00045        I = MRI->def_begin(Reg), E = MRI->def_end(); I != E; ++I) {
00046     const MachineInstr *MI = &*I;
00047     // Find the corresponding slot index.
00048     SlotIndex Idx;
00049     if (MI->isPHI())
00050       // PHI defs begin at the basic block start index.
00051       Idx = Indexes->getMBBStartIdx(MI->getParent());
00052     else
00053       // Instructions are either normal 'r', or early clobber 'e'.
00054       Idx = Indexes->getInstructionIndex(MI)
00055         .getRegSlot(I.getOperand().isEarlyClobber());
00056 
00057     // Create the def in LI. This may find an existing def.
00058     LI->createDeadDef(Idx, *Alloc);
00059   }
00060 }
00061 
00062 
00063 void LiveRangeCalc::extendToUses(LiveInterval *LI, unsigned Reg) {
00064   assert(MRI && Indexes && "call reset() first");
00065 
00066   // Visit all operands that read Reg. This may include partial defs.
00067   for (MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(Reg),
00068        E = MRI->reg_nodbg_end(); I != E; ++I) {
00069     MachineOperand &MO = I.getOperand();
00070     // Clear all kill flags. They will be reinserted after register allocation
00071     // by LiveIntervalAnalysis::addKillFlags().
00072     if (MO.isUse())
00073       MO.setIsKill(false);
00074     if (!MO.readsReg())
00075       continue;
00076     // MI is reading Reg. We may have visited MI before if it happens to be
00077     // reading Reg multiple times. That is OK, extend() is idempotent.
00078     const MachineInstr *MI = &*I;
00079 
00080     // Find the SlotIndex being read.
00081     SlotIndex Idx;
00082     if (MI->isPHI()) {
00083       assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
00084       // PHI operands are paired: (Reg, PredMBB).
00085       // Extend the live range to be live-out from PredMBB.
00086       Idx = Indexes->getMBBEndIdx(MI->getOperand(I.getOperandNo()+1).getMBB());
00087     } else {
00088       // This is a normal instruction.
00089       Idx = Indexes->getInstructionIndex(MI).getRegSlot();
00090       // Check for early-clobber redefs.
00091       unsigned DefIdx;
00092       if (MO.isDef()) {
00093         if (MO.isEarlyClobber())
00094           Idx = Idx.getRegSlot(true);
00095       } else if (MI->isRegTiedToDefOperand(I.getOperandNo(), &DefIdx)) {
00096         // FIXME: This would be a lot easier if tied early-clobber uses also
00097         // had an early-clobber flag.
00098         if (MI->getOperand(DefIdx).isEarlyClobber())
00099           Idx = Idx.getRegSlot(true);
00100       }
00101     }
00102     extend(LI, Idx, Reg);
00103   }
00104 }
00105 
00106 
00107 // Transfer information from the LiveIn vector to the live ranges.
00108 void LiveRangeCalc::updateLiveIns() {
00109   LiveRangeUpdater Updater;
00110   for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(),
00111          E = LiveIn.end(); I != E; ++I) {
00112     if (!I->DomNode)
00113       continue;
00114     MachineBasicBlock *MBB = I->DomNode->getBlock();
00115     assert(I->Value && "No live-in value found");
00116     SlotIndex Start, End;
00117     tie(Start, End) = Indexes->getMBBRange(MBB);
00118 
00119     if (I->Kill.isValid())
00120       // Value is killed inside this block.
00121       End = I->Kill;
00122     else {
00123       // The value is live-through, update LiveOut as well.
00124       // Defer the Domtree lookup until it is needed.
00125       assert(Seen.test(MBB->getNumber()));
00126       LiveOut[MBB] = LiveOutPair(I->Value, (MachineDomTreeNode *)0);
00127     }
00128     Updater.setDest(I->LI);
00129     Updater.add(Start, End, I->Value);
00130   }
00131   LiveIn.clear();
00132 }
00133 
00134 
00135 void LiveRangeCalc::extend(LiveInterval *LI,
00136                            SlotIndex Kill,
00137                            unsigned PhysReg) {
00138   assert(LI && "Missing live range");
00139   assert(Kill.isValid() && "Invalid SlotIndex");
00140   assert(Indexes && "Missing SlotIndexes");
00141   assert(DomTree && "Missing dominator tree");
00142 
00143   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot());
00144   assert(KillMBB && "No MBB at Kill");
00145 
00146   // Is there a def in the same MBB we can extend?
00147   if (LI->extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
00148     return;
00149 
00150   // Find the single reaching def, or determine if Kill is jointly dominated by
00151   // multiple values, and we may need to create even more phi-defs to preserve
00152   // VNInfo SSA form.  Perform a search for all predecessor blocks where we
00153   // know the dominating VNInfo.
00154   if (findReachingDefs(LI, KillMBB, Kill, PhysReg))
00155     return;
00156 
00157   // When there were multiple different values, we may need new PHIs.
00158   calculateValues();
00159 }
00160 
00161 
00162 // This function is called by a client after using the low-level API to add
00163 // live-out and live-in blocks.  The unique value optimization is not
00164 // available, SplitEditor::transferValues handles that case directly anyway.
00165 void LiveRangeCalc::calculateValues() {
00166   assert(Indexes && "Missing SlotIndexes");
00167   assert(DomTree && "Missing dominator tree");
00168   updateSSA();
00169   updateLiveIns();
00170 }
00171 
00172 
00173 bool LiveRangeCalc::findReachingDefs(LiveInterval *LI,
00174                                      MachineBasicBlock *KillMBB,
00175                                      SlotIndex Kill,
00176                                      unsigned PhysReg) {
00177   unsigned KillMBBNum = KillMBB->getNumber();
00178 
00179   // Block numbers where LI should be live-in.
00180   SmallVector<unsigned, 16> WorkList(1, KillMBBNum);
00181 
00182   // Remember if we have seen more than one value.
00183   bool UniqueVNI = true;
00184   VNInfo *TheVNI = 0;
00185 
00186   // Using Seen as a visited set, perform a BFS for all reaching defs.
00187   for (unsigned i = 0; i != WorkList.size(); ++i) {
00188     MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
00189 
00190 #ifndef NDEBUG
00191     if (MBB->pred_empty()) {
00192       MBB->getParent()->verify();
00193       llvm_unreachable("Use not jointly dominated by defs.");
00194     }
00195 
00196     if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
00197         !MBB->isLiveIn(PhysReg)) {
00198       MBB->getParent()->verify();
00199       errs() << "The register needs to be live in to BB#" << MBB->getNumber()
00200              << ", but is missing from the live-in list.\n";
00201       llvm_unreachable("Invalid global physical register");
00202     }
00203 #endif
00204 
00205     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00206            PE = MBB->pred_end(); PI != PE; ++PI) {
00207        MachineBasicBlock *Pred = *PI;
00208 
00209        // Is this a known live-out block?
00210        if (Seen.test(Pred->getNumber())) {
00211          if (VNInfo *VNI = LiveOut[Pred].first) {
00212            if (TheVNI && TheVNI != VNI)
00213              UniqueVNI = false;
00214            TheVNI = VNI;
00215          }
00216          continue;
00217        }
00218 
00219        SlotIndex Start, End;
00220        tie(Start, End) = Indexes->getMBBRange(Pred);
00221 
00222        // First time we see Pred.  Try to determine the live-out value, but set
00223        // it as null if Pred is live-through with an unknown value.
00224        VNInfo *VNI = LI->extendInBlock(Start, End);
00225        setLiveOutValue(Pred, VNI);
00226        if (VNI) {
00227          if (TheVNI && TheVNI != VNI)
00228            UniqueVNI = false;
00229          TheVNI = VNI;
00230          continue;
00231        }
00232 
00233        // No, we need a live-in value for Pred as well
00234        if (Pred != KillMBB)
00235           WorkList.push_back(Pred->getNumber());
00236        else
00237           // Loopback to KillMBB, so value is really live through.
00238          Kill = SlotIndex();
00239     }
00240   }
00241 
00242   LiveIn.clear();
00243 
00244   // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
00245   // neither require it. Skip the sorting overhead for small updates.
00246   if (WorkList.size() > 4)
00247     array_pod_sort(WorkList.begin(), WorkList.end());
00248 
00249   // If a unique reaching def was found, blit in the live ranges immediately.
00250   if (UniqueVNI) {
00251     LiveRangeUpdater Updater(LI);
00252     for (SmallVectorImpl<unsigned>::const_iterator
00253          I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
00254        SlotIndex Start, End;
00255        tie(Start, End) = Indexes->getMBBRange(*I);
00256        // Trim the live range in KillMBB.
00257        if (*I == KillMBBNum && Kill.isValid())
00258          End = Kill;
00259        else
00260          LiveOut[MF->getBlockNumbered(*I)] =
00261            LiveOutPair(TheVNI, (MachineDomTreeNode *)0);
00262        Updater.add(Start, End, TheVNI);
00263     }
00264     return true;
00265   }
00266 
00267   // Multiple values were found, so transfer the work list to the LiveIn array
00268   // where UpdateSSA will use it as a work list.
00269   LiveIn.reserve(WorkList.size());
00270   for (SmallVectorImpl<unsigned>::const_iterator
00271        I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
00272     MachineBasicBlock *MBB = MF->getBlockNumbered(*I);
00273     addLiveInBlock(LI, DomTree->getNode(MBB));
00274     if (MBB == KillMBB)
00275       LiveIn.back().Kill = Kill;
00276   }
00277 
00278   return false;
00279 }
00280 
00281 
00282 // This is essentially the same iterative algorithm that SSAUpdater uses,
00283 // except we already have a dominator tree, so we don't have to recompute it.
00284 void LiveRangeCalc::updateSSA() {
00285   assert(Indexes && "Missing SlotIndexes");
00286   assert(DomTree && "Missing dominator tree");
00287 
00288   // Interate until convergence.
00289   unsigned Changes;
00290   do {
00291     Changes = 0;
00292     // Propagate live-out values down the dominator tree, inserting phi-defs
00293     // when necessary.
00294     for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(),
00295            E = LiveIn.end(); I != E; ++I) {
00296       MachineDomTreeNode *Node = I->DomNode;
00297       // Skip block if the live-in value has already been determined.
00298       if (!Node)
00299         continue;
00300       MachineBasicBlock *MBB = Node->getBlock();
00301       MachineDomTreeNode *IDom = Node->getIDom();
00302       LiveOutPair IDomValue;
00303 
00304       // We need a live-in value to a block with no immediate dominator?
00305       // This is probably an unreachable block that has survived somehow.
00306       bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
00307 
00308       // IDom dominates all of our predecessors, but it may not be their
00309       // immediate dominator. Check if any of them have live-out values that are
00310       // properly dominated by IDom. If so, we need a phi-def here.
00311       if (!needPHI) {
00312         IDomValue = LiveOut[IDom->getBlock()];
00313 
00314         // Cache the DomTree node that defined the value.
00315         if (IDomValue.first && !IDomValue.second)
00316           LiveOut[IDom->getBlock()].second = IDomValue.second =
00317             DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
00318 
00319         for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00320                PE = MBB->pred_end(); PI != PE; ++PI) {
00321           LiveOutPair &Value = LiveOut[*PI];
00322           if (!Value.first || Value.first == IDomValue.first)
00323             continue;
00324 
00325           // Cache the DomTree node that defined the value.
00326           if (!Value.second)
00327             Value.second =
00328               DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
00329 
00330           // This predecessor is carrying something other than IDomValue.
00331           // It could be because IDomValue hasn't propagated yet, or it could be
00332           // because MBB is in the dominance frontier of that value.
00333           if (DomTree->dominates(IDom, Value.second)) {
00334             needPHI = true;
00335             break;
00336           }
00337         }
00338       }
00339 
00340       // The value may be live-through even if Kill is set, as can happen when
00341       // we are called from extendRange. In that case LiveOutSeen is true, and
00342       // LiveOut indicates a foreign or missing value.
00343       LiveOutPair &LOP = LiveOut[MBB];
00344 
00345       // Create a phi-def if required.
00346       if (needPHI) {
00347         ++Changes;
00348         assert(Alloc && "Need VNInfo allocator to create PHI-defs");
00349         SlotIndex Start, End;
00350         tie(Start, End) = Indexes->getMBBRange(MBB);
00351         VNInfo *VNI = I->LI->getNextValue(Start, *Alloc);
00352         I->Value = VNI;
00353         // This block is done, we know the final value.
00354         I->DomNode = 0;
00355 
00356         // Add liveness since updateLiveIns now skips this node.
00357         if (I->Kill.isValid())
00358           I->LI->addRange(LiveRange(Start, I->Kill, VNI));
00359         else {
00360           I->LI->addRange(LiveRange(Start, End, VNI));
00361           LOP = LiveOutPair(VNI, Node);
00362         }
00363       } else if (IDomValue.first) {
00364         // No phi-def here. Remember incoming value.
00365         I->Value = IDomValue.first;
00366 
00367         // If the IDomValue is killed in the block, don't propagate through.
00368         if (I->Kill.isValid())
00369           continue;
00370 
00371         // Propagate IDomValue if it isn't killed:
00372         // MBB is live-out and doesn't define its own value.
00373         if (LOP.first == IDomValue.first)
00374           continue;
00375         ++Changes;
00376         LOP = IDomValue;
00377       }
00378     }
00379   } while (Changes);
00380 }