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 #include "LiveRangeCalc.h"
00015 #include "llvm/CodeGen/MachineDominators.h"
00016 #include "llvm/CodeGen/MachineRegisterInfo.h"
00017 
00018 using namespace llvm;
00019 
00020 #define DEBUG_TYPE "regalloc"
00021 
00022 void LiveRangeCalc::resetLiveOutMap() {
00023   unsigned NumBlocks = MF->getNumBlockIDs();
00024   Seen.clear();
00025   Seen.resize(NumBlocks);
00026   Map.resize(NumBlocks);
00027 }
00028 
00029 void LiveRangeCalc::reset(const MachineFunction *mf,
00030                           SlotIndexes *SI,
00031                           MachineDominatorTree *MDT,
00032                           VNInfo::Allocator *VNIA) {
00033   MF = mf;
00034   MRI = &MF->getRegInfo();
00035   Indexes = SI;
00036   DomTree = MDT;
00037   Alloc = VNIA;
00038   resetLiveOutMap();
00039   LiveIn.clear();
00040 }
00041 
00042 
00043 static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc,
00044                           LiveRange &LR, const MachineOperand &MO) {
00045     const MachineInstr *MI = MO.getParent();
00046     SlotIndex DefIdx;
00047     if (MI->isPHI())
00048       DefIdx = Indexes.getMBBStartIdx(MI->getParent());
00049     else
00050       DefIdx = Indexes.getInstructionIndex(MI).getRegSlot(MO.isEarlyClobber());
00051 
00052     // Create the def in LR. This may find an existing def.
00053     LR.createDeadDef(DefIdx, Alloc);
00054 }
00055 
00056 void LiveRangeCalc::calculate(LiveInterval &LI) {
00057   assert(MRI && Indexes && "call reset() first");
00058 
00059   // Step 1: Create minimal live segments for every definition of Reg.
00060   // Visit all def operands. If the same instruction has multiple defs of Reg,
00061   // createDeadDef() will deduplicate.
00062   const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
00063   unsigned Reg = LI.reg;
00064   for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
00065     if (!MO.isDef() && !MO.readsReg())
00066       continue;
00067 
00068     unsigned SubReg = MO.getSubReg();
00069     if (LI.hasSubRanges() || (SubReg != 0 && MRI->tracksSubRegLiveness())) {
00070       unsigned Mask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
00071                                   : MRI->getMaxLaneMaskForVReg(Reg);
00072 
00073       // If this is the first time we see a subregister def, initialize
00074       // subranges by creating a copy of the main range.
00075       if (!LI.hasSubRanges() && !LI.empty()) {
00076         unsigned ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
00077         LI.createSubRangeFrom(*Alloc, ClassMask, LI);
00078       }
00079 
00080       for (LiveInterval::SubRange &S : LI.subranges()) {
00081         // A Mask for subregs common to the existing subrange and current def.
00082         unsigned Common = S.LaneMask & Mask;
00083         if (Common == 0)
00084           continue;
00085         // A Mask for subregs covered by the subrange but not the current def.
00086         unsigned LRest = S.LaneMask & ~Mask;
00087         LiveInterval::SubRange *CommonRange;
00088         if (LRest != 0) {
00089           // Split current subrange into Common and LRest ranges.
00090           S.LaneMask = LRest;
00091           CommonRange = LI.createSubRangeFrom(*Alloc, Common, S);
00092         } else {
00093           assert(Common == S.LaneMask);
00094           CommonRange = &S;
00095         }
00096         if (MO.isDef())
00097           createDeadDef(*Indexes, *Alloc, *CommonRange, MO);
00098         Mask &= ~Common;
00099       }
00100       // Create a new SubRange for subregs we did not cover yet.
00101       if (Mask != 0) {
00102         LiveInterval::SubRange *NewRange = LI.createSubRange(*Alloc, Mask);
00103         if (MO.isDef())
00104           createDeadDef(*Indexes, *Alloc, *NewRange, MO);
00105       }
00106     }
00107 
00108     // Create the def in the main liverange. We do not have to do this if
00109     // subranges are tracked as we recreate the main range later in this case.
00110     if (MO.isDef() && !LI.hasSubRanges())
00111       createDeadDef(*Indexes, *Alloc, LI, MO);
00112   }
00113 
00114   // We may have created empty live ranges for partially undefined uses, we
00115   // can't keep them because we won't find defs in them later.
00116   LI.removeEmptySubRanges();
00117 
00118   // Step 2: Extend live segments to all uses, constructing SSA form as
00119   // necessary.
00120   if (LI.hasSubRanges()) {
00121     for (LiveInterval::SubRange &S : LI.subranges()) {
00122       resetLiveOutMap();
00123       extendToUses(S, Reg, S.LaneMask);
00124     }
00125     LI.clear();
00126     LI.constructMainRangeFromSubranges(*Indexes, *Alloc);
00127   } else {
00128     resetLiveOutMap();
00129     extendToUses(LI, Reg, ~0u);
00130   }
00131 }
00132 
00133 
00134 void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) {
00135   assert(MRI && Indexes && "call reset() first");
00136 
00137   // Visit all def operands. If the same instruction has multiple defs of Reg,
00138   // LR.createDeadDef() will deduplicate.
00139   for (MachineOperand &MO : MRI->def_operands(Reg))
00140     createDeadDef(*Indexes, *Alloc, LR, MO);
00141 }
00142 
00143 
00144 void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg, unsigned Mask) {
00145   // Visit all operands that read Reg. This may include partial defs.
00146   const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
00147   for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
00148     // Clear all kill flags. They will be reinserted after register allocation
00149     // by LiveIntervalAnalysis::addKillFlags().
00150     if (MO.isUse())
00151       MO.setIsKill(false);
00152     else {
00153       // We only care about uses, but on the main range (mask ~0u) this includes
00154       // the "virtual" reads happening for subregister defs.
00155       if (Mask != ~0u)
00156         continue;
00157     }
00158 
00159     if (!MO.readsReg())
00160       continue;
00161     unsigned SubReg = MO.getSubReg();
00162     if (SubReg != 0) {
00163       unsigned SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
00164       // Ignore uses not covering the current subrange.
00165       if ((SubRegMask & Mask) == 0)
00166         continue;
00167     }
00168 
00169     // Determine the actual place of the use.
00170     const MachineInstr *MI = MO.getParent();
00171     unsigned OpNo = (&MO - &MI->getOperand(0));
00172     SlotIndex UseIdx;
00173     if (MI->isPHI()) {
00174       assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
00175       // The actual place where a phi operand is used is the end of the pred
00176       // MBB. PHI operands are paired: (Reg, PredMBB).
00177       UseIdx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
00178     } else {
00179       // Check for early-clobber redefs.
00180       bool isEarlyClobber = false;
00181       unsigned DefIdx;
00182       if (MO.isDef())
00183         isEarlyClobber = MO.isEarlyClobber();
00184       else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
00185         // FIXME: This would be a lot easier if tied early-clobber uses also
00186         // had an early-clobber flag.
00187         isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
00188       }
00189       UseIdx = Indexes->getInstructionIndex(MI).getRegSlot(isEarlyClobber);
00190     }
00191 
00192     // MI is reading Reg. We may have visited MI before if it happens to be
00193     // reading Reg multiple times. That is OK, extend() is idempotent.
00194     extend(LR, UseIdx, Reg);
00195   }
00196 }
00197 
00198 
00199 void LiveRangeCalc::updateFromLiveIns() {
00200   LiveRangeUpdater Updater;
00201   for (const LiveInBlock &I : LiveIn) {
00202     if (!I.DomNode)
00203       continue;
00204     MachineBasicBlock *MBB = I.DomNode->getBlock();
00205     assert(I.Value && "No live-in value found");
00206     SlotIndex Start, End;
00207     std::tie(Start, End) = Indexes->getMBBRange(MBB);
00208 
00209     if (I.Kill.isValid())
00210       // Value is killed inside this block.
00211       End = I.Kill;
00212     else {
00213       // The value is live-through, update LiveOut as well.
00214       // Defer the Domtree lookup until it is needed.
00215       assert(Seen.test(MBB->getNumber()));
00216       Map[MBB] = LiveOutPair(I.Value, nullptr);
00217     }
00218     Updater.setDest(&I.LR);
00219     Updater.add(Start, End, I.Value);
00220   }
00221   LiveIn.clear();
00222 }
00223 
00224 
00225 void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Kill, unsigned PhysReg) {
00226   assert(Kill.isValid() && "Invalid SlotIndex");
00227   assert(Indexes && "Missing SlotIndexes");
00228   assert(DomTree && "Missing dominator tree");
00229 
00230   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot());
00231   assert(KillMBB && "No MBB at Kill");
00232 
00233   // Is there a def in the same MBB we can extend?
00234   if (LR.extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
00235     return;
00236 
00237   // Find the single reaching def, or determine if Kill is jointly dominated by
00238   // multiple values, and we may need to create even more phi-defs to preserve
00239   // VNInfo SSA form.  Perform a search for all predecessor blocks where we
00240   // know the dominating VNInfo.
00241   if (findReachingDefs(LR, *KillMBB, Kill, PhysReg))
00242     return;
00243 
00244   // When there were multiple different values, we may need new PHIs.
00245   calculateValues();
00246 }
00247 
00248 
00249 // This function is called by a client after using the low-level API to add
00250 // live-out and live-in blocks.  The unique value optimization is not
00251 // available, SplitEditor::transferValues handles that case directly anyway.
00252 void LiveRangeCalc::calculateValues() {
00253   assert(Indexes && "Missing SlotIndexes");
00254   assert(DomTree && "Missing dominator tree");
00255   updateSSA();
00256   updateFromLiveIns();
00257 }
00258 
00259 
00260 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &KillMBB,
00261                                      SlotIndex Kill, unsigned PhysReg) {
00262   unsigned KillMBBNum = KillMBB.getNumber();
00263 
00264   // Block numbers where LR should be live-in.
00265   SmallVector<unsigned, 16> WorkList(1, KillMBBNum);
00266 
00267   // Remember if we have seen more than one value.
00268   bool UniqueVNI = true;
00269   VNInfo *TheVNI = nullptr;
00270 
00271   // Using Seen as a visited set, perform a BFS for all reaching defs.
00272   for (unsigned i = 0; i != WorkList.size(); ++i) {
00273     MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
00274 
00275 #ifndef NDEBUG
00276     if (MBB->pred_empty()) {
00277       MBB->getParent()->verify();
00278       llvm_unreachable("Use not jointly dominated by defs.");
00279     }
00280 
00281     if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
00282         !MBB->isLiveIn(PhysReg)) {
00283       MBB->getParent()->verify();
00284       errs() << "The register needs to be live in to BB#" << MBB->getNumber()
00285              << ", but is missing from the live-in list.\n";
00286       llvm_unreachable("Invalid global physical register");
00287     }
00288 #endif
00289 
00290     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00291          PE = MBB->pred_end(); PI != PE; ++PI) {
00292        MachineBasicBlock *Pred = *PI;
00293 
00294        // Is this a known live-out block?
00295        if (Seen.test(Pred->getNumber())) {
00296          if (VNInfo *VNI = Map[Pred].first) {
00297            if (TheVNI && TheVNI != VNI)
00298              UniqueVNI = false;
00299            TheVNI = VNI;
00300          }
00301          continue;
00302        }
00303 
00304        SlotIndex Start, End;
00305        std::tie(Start, End) = Indexes->getMBBRange(Pred);
00306 
00307        // First time we see Pred.  Try to determine the live-out value, but set
00308        // it as null if Pred is live-through with an unknown value.
00309        VNInfo *VNI = LR.extendInBlock(Start, End);
00310        setLiveOutValue(Pred, VNI);
00311        if (VNI) {
00312          if (TheVNI && TheVNI != VNI)
00313            UniqueVNI = false;
00314          TheVNI = VNI;
00315          continue;
00316        }
00317 
00318        // No, we need a live-in value for Pred as well
00319        if (Pred != &KillMBB)
00320           WorkList.push_back(Pred->getNumber());
00321        else
00322           // Loopback to KillMBB, so value is really live through.
00323          Kill = SlotIndex();
00324     }
00325   }
00326 
00327   LiveIn.clear();
00328 
00329   // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
00330   // neither require it. Skip the sorting overhead for small updates.
00331   if (WorkList.size() > 4)
00332     array_pod_sort(WorkList.begin(), WorkList.end());
00333 
00334   // If a unique reaching def was found, blit in the live ranges immediately.
00335   if (UniqueVNI) {
00336     LiveRangeUpdater Updater(&LR);
00337     for (SmallVectorImpl<unsigned>::const_iterator I = WorkList.begin(),
00338          E = WorkList.end(); I != E; ++I) {
00339        SlotIndex Start, End;
00340        std::tie(Start, End) = Indexes->getMBBRange(*I);
00341        // Trim the live range in KillMBB.
00342        if (*I == KillMBBNum && Kill.isValid())
00343          End = Kill;
00344        else
00345          Map[MF->getBlockNumbered(*I)] = LiveOutPair(TheVNI, nullptr);
00346        Updater.add(Start, End, TheVNI);
00347     }
00348     return true;
00349   }
00350 
00351   // Multiple values were found, so transfer the work list to the LiveIn array
00352   // where UpdateSSA will use it as a work list.
00353   LiveIn.reserve(WorkList.size());
00354   for (SmallVectorImpl<unsigned>::const_iterator
00355        I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
00356     MachineBasicBlock *MBB = MF->getBlockNumbered(*I);
00357     addLiveInBlock(LR, DomTree->getNode(MBB));
00358     if (MBB == &KillMBB)
00359       LiveIn.back().Kill = Kill;
00360   }
00361 
00362   return false;
00363 }
00364 
00365 
00366 // This is essentially the same iterative algorithm that SSAUpdater uses,
00367 // except we already have a dominator tree, so we don't have to recompute it.
00368 void LiveRangeCalc::updateSSA() {
00369   assert(Indexes && "Missing SlotIndexes");
00370   assert(DomTree && "Missing dominator tree");
00371 
00372   // Interate until convergence.
00373   unsigned Changes;
00374   do {
00375     Changes = 0;
00376     // Propagate live-out values down the dominator tree, inserting phi-defs
00377     // when necessary.
00378     for (LiveInBlock &I : LiveIn) {
00379       MachineDomTreeNode *Node = I.DomNode;
00380       // Skip block if the live-in value has already been determined.
00381       if (!Node)
00382         continue;
00383       MachineBasicBlock *MBB = Node->getBlock();
00384       MachineDomTreeNode *IDom = Node->getIDom();
00385       LiveOutPair IDomValue;
00386 
00387       // We need a live-in value to a block with no immediate dominator?
00388       // This is probably an unreachable block that has survived somehow.
00389       bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
00390 
00391       // IDom dominates all of our predecessors, but it may not be their
00392       // immediate dominator. Check if any of them have live-out values that are
00393       // properly dominated by IDom. If so, we need a phi-def here.
00394       if (!needPHI) {
00395         IDomValue = Map[IDom->getBlock()];
00396 
00397         // Cache the DomTree node that defined the value.
00398         if (IDomValue.first && !IDomValue.second)
00399           Map[IDom->getBlock()].second = IDomValue.second =
00400             DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
00401 
00402         for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00403                PE = MBB->pred_end(); PI != PE; ++PI) {
00404           LiveOutPair &Value = Map[*PI];
00405           if (!Value.first || Value.first == IDomValue.first)
00406             continue;
00407 
00408           // Cache the DomTree node that defined the value.
00409           if (!Value.second)
00410             Value.second =
00411               DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
00412 
00413           // This predecessor is carrying something other than IDomValue.
00414           // It could be because IDomValue hasn't propagated yet, or it could be
00415           // because MBB is in the dominance frontier of that value.
00416           if (DomTree->dominates(IDom, Value.second)) {
00417             needPHI = true;
00418             break;
00419           }
00420         }
00421       }
00422 
00423       // The value may be live-through even if Kill is set, as can happen when
00424       // we are called from extendRange. In that case LiveOutSeen is true, and
00425       // LiveOut indicates a foreign or missing value.
00426       LiveOutPair &LOP = Map[MBB];
00427 
00428       // Create a phi-def if required.
00429       if (needPHI) {
00430         ++Changes;
00431         assert(Alloc && "Need VNInfo allocator to create PHI-defs");
00432         SlotIndex Start, End;
00433         std::tie(Start, End) = Indexes->getMBBRange(MBB);
00434         LiveRange &LR = I.LR;
00435         VNInfo *VNI = LR.getNextValue(Start, *Alloc);
00436         I.Value = VNI;
00437         // This block is done, we know the final value.
00438         I.DomNode = nullptr;
00439 
00440         // Add liveness since updateFromLiveIns now skips this node.
00441         if (I.Kill.isValid())
00442           LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
00443         else {
00444           LR.addSegment(LiveInterval::Segment(Start, End, VNI));
00445           LOP = LiveOutPair(VNI, Node);
00446         }
00447       } else if (IDomValue.first) {
00448         // No phi-def here. Remember incoming value.
00449         I.Value = IDomValue.first;
00450 
00451         // If the IDomValue is killed in the block, don't propagate through.
00452         if (I.Kill.isValid())
00453           continue;
00454 
00455         // Propagate IDomValue if it isn't killed:
00456         // MBB is live-out and doesn't define its own value.
00457         if (LOP.first == IDomValue.first)
00458           continue;
00459         ++Changes;
00460         LOP = IDomValue;
00461       }
00462     }
00463   } while (Changes);
00464 }