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