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