LLVM API Documentation

LiveIntervalAnalysis.cpp
Go to the documentation of this file.
00001 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
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 // This file implements the LiveInterval analysis pass which is used
00011 // by the Linear Scan Register allocator. This pass linearizes the
00012 // basic blocks of the function in DFS order and uses the
00013 // LiveVariables pass to conservatively compute live intervals for
00014 // each virtual and physical register.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00019 #include "LiveRangeCalc.h"
00020 #include "llvm/ADT/DenseSet.h"
00021 #include "llvm/ADT/STLExtras.h"
00022 #include "llvm/Analysis/AliasAnalysis.h"
00023 #include "llvm/CodeGen/LiveVariables.h"
00024 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
00025 #include "llvm/CodeGen/MachineDominators.h"
00026 #include "llvm/CodeGen/MachineInstr.h"
00027 #include "llvm/CodeGen/MachineRegisterInfo.h"
00028 #include "llvm/CodeGen/Passes.h"
00029 #include "llvm/CodeGen/VirtRegMap.h"
00030 #include "llvm/IR/Value.h"
00031 #include "llvm/Support/BlockFrequency.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/ErrorHandling.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetInstrInfo.h"
00037 #include "llvm/Target/TargetMachine.h"
00038 #include "llvm/Target/TargetRegisterInfo.h"
00039 #include "llvm/Target/TargetSubtargetInfo.h"
00040 #include <algorithm>
00041 #include <cmath>
00042 #include <limits>
00043 using namespace llvm;
00044 
00045 #define DEBUG_TYPE "regalloc"
00046 
00047 char LiveIntervals::ID = 0;
00048 char &llvm::LiveIntervalsID = LiveIntervals::ID;
00049 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
00050                 "Live Interval Analysis", false, false)
00051 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00052 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
00053 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
00054 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
00055 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
00056                 "Live Interval Analysis", false, false)
00057 
00058 #ifndef NDEBUG
00059 static cl::opt<bool> EnablePrecomputePhysRegs(
00060   "precompute-phys-liveness", cl::Hidden,
00061   cl::desc("Eagerly compute live intervals for all physreg units."));
00062 #else
00063 static bool EnablePrecomputePhysRegs = false;
00064 #endif // NDEBUG
00065 
00066 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
00067   AU.setPreservesCFG();
00068   AU.addRequired<AliasAnalysis>();
00069   AU.addPreserved<AliasAnalysis>();
00070   // LiveVariables isn't really required by this analysis, it is only required
00071   // here to make sure it is live during TwoAddressInstructionPass and
00072   // PHIElimination. This is temporary.
00073   AU.addRequired<LiveVariables>();
00074   AU.addPreserved<LiveVariables>();
00075   AU.addPreservedID(MachineLoopInfoID);
00076   AU.addRequiredTransitiveID(MachineDominatorsID);
00077   AU.addPreservedID(MachineDominatorsID);
00078   AU.addPreserved<SlotIndexes>();
00079   AU.addRequiredTransitive<SlotIndexes>();
00080   MachineFunctionPass::getAnalysisUsage(AU);
00081 }
00082 
00083 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
00084   DomTree(nullptr), LRCalc(nullptr) {
00085   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
00086 }
00087 
00088 LiveIntervals::~LiveIntervals() {
00089   delete LRCalc;
00090 }
00091 
00092 void LiveIntervals::releaseMemory() {
00093   // Free the live intervals themselves.
00094   for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
00095     delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
00096   VirtRegIntervals.clear();
00097   RegMaskSlots.clear();
00098   RegMaskBits.clear();
00099   RegMaskBlocks.clear();
00100 
00101   for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
00102     delete RegUnitRanges[i];
00103   RegUnitRanges.clear();
00104 
00105   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
00106   VNInfoAllocator.Reset();
00107 }
00108 
00109 /// runOnMachineFunction - calculates LiveIntervals
00110 ///
00111 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
00112   MF = &fn;
00113   MRI = &MF->getRegInfo();
00114   TM = &fn.getTarget();
00115   TRI = TM->getSubtargetImpl()->getRegisterInfo();
00116   TII = TM->getSubtargetImpl()->getInstrInfo();
00117   AA = &getAnalysis<AliasAnalysis>();
00118   Indexes = &getAnalysis<SlotIndexes>();
00119   DomTree = &getAnalysis<MachineDominatorTree>();
00120   if (!LRCalc)
00121     LRCalc = new LiveRangeCalc();
00122 
00123   // Allocate space for all virtual registers.
00124   VirtRegIntervals.resize(MRI->getNumVirtRegs());
00125 
00126   computeVirtRegs();
00127   computeRegMasks();
00128   computeLiveInRegUnits();
00129 
00130   if (EnablePrecomputePhysRegs) {
00131     // For stress testing, precompute live ranges of all physical register
00132     // units, including reserved registers.
00133     for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
00134       getRegUnit(i);
00135   }
00136   DEBUG(dump());
00137   return true;
00138 }
00139 
00140 /// print - Implement the dump method.
00141 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
00142   OS << "********** INTERVALS **********\n";
00143 
00144   // Dump the regunits.
00145   for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
00146     if (LiveRange *LR = RegUnitRanges[i])
00147       OS << PrintRegUnit(i, TRI) << ' ' << *LR << '\n';
00148 
00149   // Dump the virtregs.
00150   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
00151     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00152     if (hasInterval(Reg))
00153       OS << getInterval(Reg) << '\n';
00154   }
00155 
00156   OS << "RegMasks:";
00157   for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
00158     OS << ' ' << RegMaskSlots[i];
00159   OS << '\n';
00160 
00161   printInstrs(OS);
00162 }
00163 
00164 void LiveIntervals::printInstrs(raw_ostream &OS) const {
00165   OS << "********** MACHINEINSTRS **********\n";
00166   MF->print(OS, Indexes);
00167 }
00168 
00169 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00170 void LiveIntervals::dumpInstrs() const {
00171   printInstrs(dbgs());
00172 }
00173 #endif
00174 
00175 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
00176   float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
00177                   llvm::huge_valf : 0.0F;
00178   return new LiveInterval(reg, Weight);
00179 }
00180 
00181 
00182 /// computeVirtRegInterval - Compute the live interval of a virtual register,
00183 /// based on defs and uses.
00184 void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
00185   assert(LRCalc && "LRCalc not initialized.");
00186   assert(LI.empty() && "Should only compute empty intervals.");
00187   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
00188   LRCalc->createDeadDefs(LI);
00189   LRCalc->extendToUses(LI);
00190   computeDeadValues(&LI, LI, nullptr, nullptr);
00191 }
00192 
00193 void LiveIntervals::computeVirtRegs() {
00194   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
00195     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00196     if (MRI->reg_nodbg_empty(Reg))
00197       continue;
00198     createAndComputeVirtRegInterval(Reg);
00199   }
00200 }
00201 
00202 void LiveIntervals::computeRegMasks() {
00203   RegMaskBlocks.resize(MF->getNumBlockIDs());
00204 
00205   // Find all instructions with regmask operands.
00206   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
00207        MBBI != E; ++MBBI) {
00208     MachineBasicBlock *MBB = MBBI;
00209     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
00210     RMB.first = RegMaskSlots.size();
00211     for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
00212          MI != ME; ++MI)
00213       for (MIOperands MO(MI); MO.isValid(); ++MO) {
00214         if (!MO->isRegMask())
00215           continue;
00216           RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
00217           RegMaskBits.push_back(MO->getRegMask());
00218       }
00219     // Compute the number of register mask instructions in this block.
00220     RMB.second = RegMaskSlots.size() - RMB.first;
00221   }
00222 }
00223 
00224 //===----------------------------------------------------------------------===//
00225 //                           Register Unit Liveness
00226 //===----------------------------------------------------------------------===//
00227 //
00228 // Fixed interference typically comes from ABI boundaries: Function arguments
00229 // and return values are passed in fixed registers, and so are exception
00230 // pointers entering landing pads. Certain instructions require values to be
00231 // present in specific registers. That is also represented through fixed
00232 // interference.
00233 //
00234 
00235 /// computeRegUnitInterval - Compute the live range of a register unit, based
00236 /// on the uses and defs of aliasing registers.  The range should be empty,
00237 /// or contain only dead phi-defs from ABI blocks.
00238 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
00239   assert(LRCalc && "LRCalc not initialized.");
00240   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
00241 
00242   // The physregs aliasing Unit are the roots and their super-registers.
00243   // Create all values as dead defs before extending to uses. Note that roots
00244   // may share super-registers. That's OK because createDeadDefs() is
00245   // idempotent. It is very rare for a register unit to have multiple roots, so
00246   // uniquing super-registers is probably not worthwhile.
00247   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
00248     for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
00249          Supers.isValid(); ++Supers) {
00250       if (!MRI->reg_empty(*Supers))
00251         LRCalc->createDeadDefs(LR, *Supers);
00252     }
00253   }
00254 
00255   // Now extend LR to reach all uses.
00256   // Ignore uses of reserved registers. We only track defs of those.
00257   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
00258     for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
00259          Supers.isValid(); ++Supers) {
00260       unsigned Reg = *Supers;
00261       if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
00262         LRCalc->extendToUses(LR, Reg);
00263     }
00264   }
00265 }
00266 
00267 
00268 /// computeLiveInRegUnits - Precompute the live ranges of any register units
00269 /// that are live-in to an ABI block somewhere. Register values can appear
00270 /// without a corresponding def when entering the entry block or a landing pad.
00271 ///
00272 void LiveIntervals::computeLiveInRegUnits() {
00273   RegUnitRanges.resize(TRI->getNumRegUnits());
00274   DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
00275 
00276   // Keep track of the live range sets allocated.
00277   SmallVector<unsigned, 8> NewRanges;
00278 
00279   // Check all basic blocks for live-ins.
00280   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
00281        MFI != MFE; ++MFI) {
00282     const MachineBasicBlock *MBB = MFI;
00283 
00284     // We only care about ABI blocks: Entry + landing pads.
00285     if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
00286       continue;
00287 
00288     // Create phi-defs at Begin for all live-in registers.
00289     SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
00290     DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
00291     for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
00292          LIE = MBB->livein_end(); LII != LIE; ++LII) {
00293       for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
00294         unsigned Unit = *Units;
00295         LiveRange *LR = RegUnitRanges[Unit];
00296         if (!LR) {
00297           LR = RegUnitRanges[Unit] = new LiveRange();
00298           NewRanges.push_back(Unit);
00299         }
00300         VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
00301         (void)VNI;
00302         DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
00303       }
00304     }
00305     DEBUG(dbgs() << '\n');
00306   }
00307   DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
00308 
00309   // Compute the 'normal' part of the ranges.
00310   for (unsigned i = 0, e = NewRanges.size(); i != e; ++i) {
00311     unsigned Unit = NewRanges[i];
00312     computeRegUnitRange(*RegUnitRanges[Unit], Unit);
00313   }
00314 }
00315 
00316 
00317 /// shrinkToUses - After removing some uses of a register, shrink its live
00318 /// range to just the remaining uses. This method does not compute reaching
00319 /// defs for new uses, and it doesn't remove dead defs.
00320 bool LiveIntervals::shrinkToUses(LiveInterval *li,
00321                                  SmallVectorImpl<MachineInstr*> *dead) {
00322   DEBUG(dbgs() << "Shrink: " << *li << '\n');
00323   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
00324          && "Can only shrink virtual registers");
00325   // Find all the values used, including PHI kills.
00326   SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
00327 
00328   // Blocks that have already been added to WorkList as live-out.
00329   SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
00330 
00331   // Visit all instructions reading li->reg.
00332   for (MachineRegisterInfo::reg_instr_iterator
00333        I = MRI->reg_instr_begin(li->reg), E = MRI->reg_instr_end();
00334        I != E; ) {
00335     MachineInstr *UseMI = &*(I++);
00336     if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
00337       continue;
00338     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
00339     LiveQueryResult LRQ = li->Query(Idx);
00340     VNInfo *VNI = LRQ.valueIn();
00341     if (!VNI) {
00342       // This shouldn't happen: readsVirtualRegister returns true, but there is
00343       // no live value. It is likely caused by a target getting <undef> flags
00344       // wrong.
00345       DEBUG(dbgs() << Idx << '\t' << *UseMI
00346                    << "Warning: Instr claims to read non-existent value in "
00347                     << *li << '\n');
00348       continue;
00349     }
00350     // Special case: An early-clobber tied operand reads and writes the
00351     // register one slot early.
00352     if (VNInfo *DefVNI = LRQ.valueDefined())
00353       Idx = DefVNI->def;
00354 
00355     WorkList.push_back(std::make_pair(Idx, VNI));
00356   }
00357 
00358   // Create new live ranges with only minimal live segments per def.
00359   LiveRange NewLR;
00360   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
00361        I != E; ++I) {
00362     VNInfo *VNI = *I;
00363     if (VNI->isUnused())
00364       continue;
00365     NewLR.addSegment(LiveRange::Segment(VNI->def, VNI->def.getDeadSlot(), VNI));
00366   }
00367 
00368   // Keep track of the PHIs that are in use.
00369   SmallPtrSet<VNInfo*, 8> UsedPHIs;
00370 
00371   // Extend intervals to reach all uses in WorkList.
00372   while (!WorkList.empty()) {
00373     SlotIndex Idx = WorkList.back().first;
00374     VNInfo *VNI = WorkList.back().second;
00375     WorkList.pop_back();
00376     const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
00377     SlotIndex BlockStart = getMBBStartIdx(MBB);
00378 
00379     // Extend the live range for VNI to be live at Idx.
00380     if (VNInfo *ExtVNI = NewLR.extendInBlock(BlockStart, Idx)) {
00381       (void)ExtVNI;
00382       assert(ExtVNI == VNI && "Unexpected existing value number");
00383       // Is this a PHIDef we haven't seen before?
00384       if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
00385         continue;
00386       // The PHI is live, make sure the predecessors are live-out.
00387       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
00388            PE = MBB->pred_end(); PI != PE; ++PI) {
00389         if (!LiveOut.insert(*PI))
00390           continue;
00391         SlotIndex Stop = getMBBEndIdx(*PI);
00392         // A predecessor is not required to have a live-out value for a PHI.
00393         if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
00394           WorkList.push_back(std::make_pair(Stop, PVNI));
00395       }
00396       continue;
00397     }
00398 
00399     // VNI is live-in to MBB.
00400     DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
00401     NewLR.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
00402 
00403     // Make sure VNI is live-out from the predecessors.
00404     for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
00405          PE = MBB->pred_end(); PI != PE; ++PI) {
00406       if (!LiveOut.insert(*PI))
00407         continue;
00408       SlotIndex Stop = getMBBEndIdx(*PI);
00409       assert(li->getVNInfoBefore(Stop) == VNI &&
00410              "Wrong value out of predecessor");
00411       WorkList.push_back(std::make_pair(Stop, VNI));
00412     }
00413   }
00414 
00415   // Handle dead values.
00416   bool CanSeparate = false;
00417   computeDeadValues(li, NewLR, &CanSeparate, dead);
00418 
00419   // Move the trimmed segments back.
00420   li->segments.swap(NewLR.segments);
00421   DEBUG(dbgs() << "Shrunk: " << *li << '\n');
00422   return CanSeparate;
00423 }
00424 
00425 void LiveIntervals::computeDeadValues(LiveInterval *li,
00426                                       LiveRange &LR,
00427                                       bool *CanSeparate,
00428                                       SmallVectorImpl<MachineInstr*> *dead) {
00429   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
00430        I != E; ++I) {
00431     VNInfo *VNI = *I;
00432     if (VNI->isUnused())
00433       continue;
00434     LiveRange::iterator LRI = LR.FindSegmentContaining(VNI->def);
00435     assert(LRI != LR.end() && "Missing segment for PHI");
00436     if (LRI->end != VNI->def.getDeadSlot())
00437       continue;
00438     if (VNI->isPHIDef()) {
00439       // This is a dead PHI. Remove it.
00440       VNI->markUnused();
00441       LR.removeSegment(LRI->start, LRI->end);
00442       DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
00443       if (CanSeparate)
00444         *CanSeparate = true;
00445     } else {
00446       // This is a dead def. Make sure the instruction knows.
00447       MachineInstr *MI = getInstructionFromIndex(VNI->def);
00448       assert(MI && "No instruction defining live value");
00449       MI->addRegisterDead(li->reg, TRI);
00450       if (dead && MI->allDefsAreDead()) {
00451         DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
00452         dead->push_back(MI);
00453       }
00454     }
00455   }
00456 }
00457 
00458 void LiveIntervals::extendToIndices(LiveRange &LR,
00459                                     ArrayRef<SlotIndex> Indices) {
00460   assert(LRCalc && "LRCalc not initialized.");
00461   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
00462   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
00463     LRCalc->extend(LR, Indices[i]);
00464 }
00465 
00466 void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
00467                                SmallVectorImpl<SlotIndex> *EndPoints) {
00468   LiveQueryResult LRQ = LI->Query(Kill);
00469   VNInfo *VNI = LRQ.valueOut();
00470   if (!VNI)
00471     return;
00472 
00473   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
00474   SlotIndex MBBStart, MBBEnd;
00475   std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
00476 
00477   // If VNI isn't live out from KillMBB, the value is trivially pruned.
00478   if (LRQ.endPoint() < MBBEnd) {
00479     LI->removeSegment(Kill, LRQ.endPoint());
00480     if (EndPoints) EndPoints->push_back(LRQ.endPoint());
00481     return;
00482   }
00483 
00484   // VNI is live out of KillMBB.
00485   LI->removeSegment(Kill, MBBEnd);
00486   if (EndPoints) EndPoints->push_back(MBBEnd);
00487 
00488   // Find all blocks that are reachable from KillMBB without leaving VNI's live
00489   // range. It is possible that KillMBB itself is reachable, so start a DFS
00490   // from each successor.
00491   typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
00492   VisitedTy Visited;
00493   for (MachineBasicBlock::succ_iterator
00494        SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
00495        SuccI != SuccE; ++SuccI) {
00496     for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
00497          I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
00498          I != E;) {
00499       MachineBasicBlock *MBB = *I;
00500 
00501       // Check if VNI is live in to MBB.
00502       std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
00503       LiveQueryResult LRQ = LI->Query(MBBStart);
00504       if (LRQ.valueIn() != VNI) {
00505         // This block isn't part of the VNI segment. Prune the search.
00506         I.skipChildren();
00507         continue;
00508       }
00509 
00510       // Prune the search if VNI is killed in MBB.
00511       if (LRQ.endPoint() < MBBEnd) {
00512         LI->removeSegment(MBBStart, LRQ.endPoint());
00513         if (EndPoints) EndPoints->push_back(LRQ.endPoint());
00514         I.skipChildren();
00515         continue;
00516       }
00517 
00518       // VNI is live through MBB.
00519       LI->removeSegment(MBBStart, MBBEnd);
00520       if (EndPoints) EndPoints->push_back(MBBEnd);
00521       ++I;
00522     }
00523   }
00524 }
00525 
00526 //===----------------------------------------------------------------------===//
00527 // Register allocator hooks.
00528 //
00529 
00530 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
00531   // Keep track of regunit ranges.
00532   SmallVector<std::pair<LiveRange*, LiveRange::iterator>, 8> RU;
00533 
00534   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
00535     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00536     if (MRI->reg_nodbg_empty(Reg))
00537       continue;
00538     LiveInterval *LI = &getInterval(Reg);
00539     if (LI->empty())
00540       continue;
00541 
00542     // Find the regunit intervals for the assigned register. They may overlap
00543     // the virtual register live range, cancelling any kills.
00544     RU.clear();
00545     for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
00546          ++Units) {
00547       LiveRange &RURanges = getRegUnit(*Units);
00548       if (RURanges.empty())
00549         continue;
00550       RU.push_back(std::make_pair(&RURanges, RURanges.find(LI->begin()->end)));
00551     }
00552 
00553     // Every instruction that kills Reg corresponds to a segment range end
00554     // point.
00555     for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
00556          ++RI) {
00557       // A block index indicates an MBB edge.
00558       if (RI->end.isBlock())
00559         continue;
00560       MachineInstr *MI = getInstructionFromIndex(RI->end);
00561       if (!MI)
00562         continue;
00563 
00564       // Check if any of the regunits are live beyond the end of RI. That could
00565       // happen when a physreg is defined as a copy of a virtreg:
00566       //
00567       //   %EAX = COPY %vreg5
00568       //   FOO %vreg5         <--- MI, cancel kill because %EAX is live.
00569       //   BAR %EAX<kill>
00570       //
00571       // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
00572       bool CancelKill = false;
00573       for (unsigned u = 0, e = RU.size(); u != e; ++u) {
00574         LiveRange &RRanges = *RU[u].first;
00575         LiveRange::iterator &I = RU[u].second;
00576         if (I == RRanges.end())
00577           continue;
00578         I = RRanges.advanceTo(I, RI->end);
00579         if (I == RRanges.end() || I->start >= RI->end)
00580           continue;
00581         // I is overlapping RI.
00582         CancelKill = true;
00583         break;
00584       }
00585       if (CancelKill)
00586         MI->clearRegisterKills(Reg, nullptr);
00587       else
00588         MI->addRegisterKilled(Reg, nullptr);
00589     }
00590   }
00591 }
00592 
00593 MachineBasicBlock*
00594 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
00595   // A local live range must be fully contained inside the block, meaning it is
00596   // defined and killed at instructions, not at block boundaries. It is not
00597   // live in or or out of any block.
00598   //
00599   // It is technically possible to have a PHI-defined live range identical to a
00600   // single block, but we are going to return false in that case.
00601 
00602   SlotIndex Start = LI.beginIndex();
00603   if (Start.isBlock())
00604     return nullptr;
00605 
00606   SlotIndex Stop = LI.endIndex();
00607   if (Stop.isBlock())
00608     return nullptr;
00609 
00610   // getMBBFromIndex doesn't need to search the MBB table when both indexes
00611   // belong to proper instructions.
00612   MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
00613   MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
00614   return MBB1 == MBB2 ? MBB1 : nullptr;
00615 }
00616 
00617 bool
00618 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
00619   for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
00620        I != E; ++I) {
00621     const VNInfo *PHI = *I;
00622     if (PHI->isUnused() || !PHI->isPHIDef())
00623       continue;
00624     const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
00625     // Conservatively return true instead of scanning huge predecessor lists.
00626     if (PHIMBB->pred_size() > 100)
00627       return true;
00628     for (MachineBasicBlock::const_pred_iterator
00629          PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
00630       if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
00631         return true;
00632   }
00633   return false;
00634 }
00635 
00636 float
00637 LiveIntervals::getSpillWeight(bool isDef, bool isUse,
00638                               const MachineBlockFrequencyInfo *MBFI,
00639                               const MachineInstr *MI) {
00640   BlockFrequency Freq = MBFI->getBlockFreq(MI->getParent());
00641   const float Scale = 1.0f / MBFI->getEntryFreq();
00642   return (isDef + isUse) * (Freq.getFrequency() * Scale);
00643 }
00644 
00645 LiveRange::Segment
00646 LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr* startInst) {
00647   LiveInterval& Interval = createEmptyInterval(reg);
00648   VNInfo* VN = Interval.getNextValue(
00649     SlotIndex(getInstructionIndex(startInst).getRegSlot()),
00650     getVNInfoAllocator());
00651   LiveRange::Segment S(
00652      SlotIndex(getInstructionIndex(startInst).getRegSlot()),
00653      getMBBEndIdx(startInst->getParent()), VN);
00654   Interval.addSegment(S);
00655 
00656   return S;
00657 }
00658 
00659 
00660 //===----------------------------------------------------------------------===//
00661 //                          Register mask functions
00662 //===----------------------------------------------------------------------===//
00663 
00664 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
00665                                              BitVector &UsableRegs) {
00666   if (LI.empty())
00667     return false;
00668   LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
00669 
00670   // Use a smaller arrays for local live ranges.
00671   ArrayRef<SlotIndex> Slots;
00672   ArrayRef<const uint32_t*> Bits;
00673   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
00674     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
00675     Bits = getRegMaskBitsInBlock(MBB->getNumber());
00676   } else {
00677     Slots = getRegMaskSlots();
00678     Bits = getRegMaskBits();
00679   }
00680 
00681   // We are going to enumerate all the register mask slots contained in LI.
00682   // Start with a binary search of RegMaskSlots to find a starting point.
00683   ArrayRef<SlotIndex>::iterator SlotI =
00684     std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
00685   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
00686 
00687   // No slots in range, LI begins after the last call.
00688   if (SlotI == SlotE)
00689     return false;
00690 
00691   bool Found = false;
00692   for (;;) {
00693     assert(*SlotI >= LiveI->start);
00694     // Loop over all slots overlapping this segment.
00695     while (*SlotI < LiveI->end) {
00696       // *SlotI overlaps LI. Collect mask bits.
00697       if (!Found) {
00698         // This is the first overlap. Initialize UsableRegs to all ones.
00699         UsableRegs.clear();
00700         UsableRegs.resize(TRI->getNumRegs(), true);
00701         Found = true;
00702       }
00703       // Remove usable registers clobbered by this mask.
00704       UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
00705       if (++SlotI == SlotE)
00706         return Found;
00707     }
00708     // *SlotI is beyond the current LI segment.
00709     LiveI = LI.advanceTo(LiveI, *SlotI);
00710     if (LiveI == LiveE)
00711       return Found;
00712     // Advance SlotI until it overlaps.
00713     while (*SlotI < LiveI->start)
00714       if (++SlotI == SlotE)
00715         return Found;
00716   }
00717 }
00718 
00719 //===----------------------------------------------------------------------===//
00720 //                         IntervalUpdate class.
00721 //===----------------------------------------------------------------------===//
00722 
00723 // HMEditor is a toolkit used by handleMove to trim or extend live intervals.
00724 class LiveIntervals::HMEditor {
00725 private:
00726   LiveIntervals& LIS;
00727   const MachineRegisterInfo& MRI;
00728   const TargetRegisterInfo& TRI;
00729   SlotIndex OldIdx;
00730   SlotIndex NewIdx;
00731   SmallPtrSet<LiveRange*, 8> Updated;
00732   bool UpdateFlags;
00733 
00734 public:
00735   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
00736            const TargetRegisterInfo& TRI,
00737            SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
00738     : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
00739       UpdateFlags(UpdateFlags) {}
00740 
00741   // FIXME: UpdateFlags is a workaround that creates live intervals for all
00742   // physregs, even those that aren't needed for regalloc, in order to update
00743   // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
00744   // flags, and postRA passes will use a live register utility instead.
00745   LiveRange *getRegUnitLI(unsigned Unit) {
00746     if (UpdateFlags)
00747       return &LIS.getRegUnit(Unit);
00748     return LIS.getCachedRegUnit(Unit);
00749   }
00750 
00751   /// Update all live ranges touched by MI, assuming a move from OldIdx to
00752   /// NewIdx.
00753   void updateAllRanges(MachineInstr *MI) {
00754     DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
00755     bool hasRegMask = false;
00756     for (MIOperands MO(MI); MO.isValid(); ++MO) {
00757       if (MO->isRegMask())
00758         hasRegMask = true;
00759       if (!MO->isReg())
00760         continue;
00761       // Aggressively clear all kill flags.
00762       // They are reinserted by VirtRegRewriter.
00763       if (MO->isUse())
00764         MO->setIsKill(false);
00765 
00766       unsigned Reg = MO->getReg();
00767       if (!Reg)
00768         continue;
00769       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00770         LiveInterval &LI = LIS.getInterval(Reg);
00771         updateRange(LI, Reg);
00772         continue;
00773       }
00774 
00775       // For physregs, only update the regunits that actually have a
00776       // precomputed live range.
00777       for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
00778         if (LiveRange *LR = getRegUnitLI(*Units))
00779           updateRange(*LR, *Units);
00780     }
00781     if (hasRegMask)
00782       updateRegMaskSlots();
00783   }
00784 
00785 private:
00786   /// Update a single live range, assuming an instruction has been moved from
00787   /// OldIdx to NewIdx.
00788   void updateRange(LiveRange &LR, unsigned Reg) {
00789     if (!Updated.insert(&LR))
00790       return;
00791     DEBUG({
00792       dbgs() << "     ";
00793       if (TargetRegisterInfo::isVirtualRegister(Reg))
00794         dbgs() << PrintReg(Reg);
00795       else
00796         dbgs() << PrintRegUnit(Reg, &TRI);
00797       dbgs() << ":\t" << LR << '\n';
00798     });
00799     if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
00800       handleMoveDown(LR);
00801     else
00802       handleMoveUp(LR, Reg);
00803     DEBUG(dbgs() << "        -->\t" << LR << '\n');
00804     LR.verify();
00805   }
00806 
00807   /// Update LR to reflect an instruction has been moved downwards from OldIdx
00808   /// to NewIdx.
00809   ///
00810   /// 1. Live def at OldIdx:
00811   ///    Move def to NewIdx, assert endpoint after NewIdx.
00812   ///
00813   /// 2. Live def at OldIdx, killed at NewIdx:
00814   ///    Change to dead def at NewIdx.
00815   ///    (Happens when bundling def+kill together).
00816   ///
00817   /// 3. Dead def at OldIdx:
00818   ///    Move def to NewIdx, possibly across another live value.
00819   ///
00820   /// 4. Def at OldIdx AND at NewIdx:
00821   ///    Remove segment [OldIdx;NewIdx) and value defined at OldIdx.
00822   ///    (Happens when bundling multiple defs together).
00823   ///
00824   /// 5. Value read at OldIdx, killed before NewIdx:
00825   ///    Extend kill to NewIdx.
00826   ///
00827   void handleMoveDown(LiveRange &LR) {
00828     // First look for a kill at OldIdx.
00829     LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
00830     LiveRange::iterator E = LR.end();
00831     // Is LR even live at OldIdx?
00832     if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
00833       return;
00834 
00835     // Handle a live-in value.
00836     if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
00837       bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
00838       // If the live-in value already extends to NewIdx, there is nothing to do.
00839       if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
00840         return;
00841       // Aggressively remove all kill flags from the old kill point.
00842       // Kill flags shouldn't be used while live intervals exist, they will be
00843       // reinserted by VirtRegRewriter.
00844       if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
00845         for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
00846           if (MO->isReg() && MO->isUse())
00847             MO->setIsKill(false);
00848       // Adjust I->end to reach NewIdx. This may temporarily make LR invalid by
00849       // overlapping ranges. Case 5 above.
00850       I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
00851       // If this was a kill, there may also be a def. Otherwise we're done.
00852       if (!isKill)
00853         return;
00854       ++I;
00855     }
00856 
00857     // Check for a def at OldIdx.
00858     if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
00859       return;
00860     // We have a def at OldIdx.
00861     VNInfo *DefVNI = I->valno;
00862     assert(DefVNI->def == I->start && "Inconsistent def");
00863     DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
00864     // If the defined value extends beyond NewIdx, just move the def down.
00865     // This is case 1 above.
00866     if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
00867       I->start = DefVNI->def;
00868       return;
00869     }
00870     // The remaining possibilities are now:
00871     // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
00872     // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
00873     // In either case, it is possible that there is an existing def at NewIdx.
00874     assert((I->end == OldIdx.getDeadSlot() ||
00875             SlotIndex::isSameInstr(I->end, NewIdx)) &&
00876             "Cannot move def below kill");
00877     LiveRange::iterator NewI = LR.advanceTo(I, NewIdx.getRegSlot());
00878     if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
00879       // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
00880       // coalesced into that value.
00881       assert(NewI->valno != DefVNI && "Multiple defs of value?");
00882       LR.removeValNo(DefVNI);
00883       return;
00884     }
00885     // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
00886     // If the def at OldIdx was dead, we allow it to be moved across other LR
00887     // values. The new range should be placed immediately before NewI, move any
00888     // intermediate ranges up.
00889     assert(NewI != I && "Inconsistent iterators");
00890     std::copy(std::next(I), NewI, I);
00891     *std::prev(NewI)
00892       = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
00893   }
00894 
00895   /// Update LR to reflect an instruction has been moved upwards from OldIdx
00896   /// to NewIdx.
00897   ///
00898   /// 1. Live def at OldIdx:
00899   ///    Hoist def to NewIdx.
00900   ///
00901   /// 2. Dead def at OldIdx:
00902   ///    Hoist def+end to NewIdx, possibly move across other values.
00903   ///
00904   /// 3. Dead def at OldIdx AND existing def at NewIdx:
00905   ///    Remove value defined at OldIdx, coalescing it with existing value.
00906   ///
00907   /// 4. Live def at OldIdx AND existing def at NewIdx:
00908   ///    Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
00909   ///    (Happens when bundling multiple defs together).
00910   ///
00911   /// 5. Value killed at OldIdx:
00912   ///    Hoist kill to NewIdx, then scan for last kill between NewIdx and
00913   ///    OldIdx.
00914   ///
00915   void handleMoveUp(LiveRange &LR, unsigned Reg) {
00916     // First look for a kill at OldIdx.
00917     LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
00918     LiveRange::iterator E = LR.end();
00919     // Is LR even live at OldIdx?
00920     if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
00921       return;
00922 
00923     // Handle a live-in value.
00924     if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
00925       // If the live-in value isn't killed here, there is nothing to do.
00926       if (!SlotIndex::isSameInstr(OldIdx, I->end))
00927         return;
00928       // Adjust I->end to end at NewIdx. If we are hoisting a kill above
00929       // another use, we need to search for that use. Case 5 above.
00930       I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
00931       ++I;
00932       // If OldIdx also defines a value, there couldn't have been another use.
00933       if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
00934         // No def, search for the new kill.
00935         // This can never be an early clobber kill since there is no def.
00936         std::prev(I)->end = findLastUseBefore(Reg).getRegSlot();
00937         return;
00938       }
00939     }
00940 
00941     // Now deal with the def at OldIdx.
00942     assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
00943     VNInfo *DefVNI = I->valno;
00944     assert(DefVNI->def == I->start && "Inconsistent def");
00945     DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
00946 
00947     // Check for an existing def at NewIdx.
00948     LiveRange::iterator NewI = LR.find(NewIdx.getRegSlot());
00949     if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
00950       assert(NewI->valno != DefVNI && "Same value defined more than once?");
00951       // There is an existing def at NewIdx.
00952       if (I->end.isDead()) {
00953         // Case 3: Remove the dead def at OldIdx.
00954         LR.removeValNo(DefVNI);
00955         return;
00956       }
00957       // Case 4: Replace def at NewIdx with live def at OldIdx.
00958       I->start = DefVNI->def;
00959       LR.removeValNo(NewI->valno);
00960       return;
00961     }
00962 
00963     // There is no existing def at NewIdx. Hoist DefVNI.
00964     if (!I->end.isDead()) {
00965       // Leave the end point of a live def.
00966       I->start = DefVNI->def;
00967       return;
00968     }
00969 
00970     // DefVNI is a dead def. It may have been moved across other values in LR,
00971     // so move I up to NewI. Slide [NewI;I) down one position.
00972     std::copy_backward(NewI, I, std::next(I));
00973     *NewI = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
00974   }
00975 
00976   void updateRegMaskSlots() {
00977     SmallVectorImpl<SlotIndex>::iterator RI =
00978       std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
00979                        OldIdx);
00980     assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
00981            "No RegMask at OldIdx.");
00982     *RI = NewIdx.getRegSlot();
00983     assert((RI == LIS.RegMaskSlots.begin() ||
00984             SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
00985            "Cannot move regmask instruction above another call");
00986     assert((std::next(RI) == LIS.RegMaskSlots.end() ||
00987             SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
00988            "Cannot move regmask instruction below another call");
00989   }
00990 
00991   // Return the last use of reg between NewIdx and OldIdx.
00992   SlotIndex findLastUseBefore(unsigned Reg) {
00993 
00994     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00995       SlotIndex LastUse = NewIdx;
00996       for (MachineRegisterInfo::use_instr_nodbg_iterator
00997              UI = MRI.use_instr_nodbg_begin(Reg),
00998              UE = MRI.use_instr_nodbg_end();
00999            UI != UE; ++UI) {
01000         const MachineInstr* MI = &*UI;
01001         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
01002         if (InstSlot > LastUse && InstSlot < OldIdx)
01003           LastUse = InstSlot;
01004       }
01005       return LastUse;
01006     }
01007 
01008     // This is a regunit interval, so scanning the use list could be very
01009     // expensive. Scan upwards from OldIdx instead.
01010     assert(NewIdx < OldIdx && "Expected upwards move");
01011     SlotIndexes *Indexes = LIS.getSlotIndexes();
01012     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
01013 
01014     // OldIdx may not correspond to an instruction any longer, so set MII to
01015     // point to the next instruction after OldIdx, or MBB->end().
01016     MachineBasicBlock::iterator MII = MBB->end();
01017     if (MachineInstr *MI = Indexes->getInstructionFromIndex(
01018                            Indexes->getNextNonNullIndex(OldIdx)))
01019       if (MI->getParent() == MBB)
01020         MII = MI;
01021 
01022     MachineBasicBlock::iterator Begin = MBB->begin();
01023     while (MII != Begin) {
01024       if ((--MII)->isDebugValue())
01025         continue;
01026       SlotIndex Idx = Indexes->getInstructionIndex(MII);
01027 
01028       // Stop searching when NewIdx is reached.
01029       if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
01030         return NewIdx;
01031 
01032       // Check if MII uses Reg.
01033       for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
01034         if (MO->isReg() &&
01035             TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
01036             TRI.hasRegUnit(MO->getReg(), Reg))
01037           return Idx;
01038     }
01039     // Didn't reach NewIdx. It must be the first instruction in the block.
01040     return NewIdx;
01041   }
01042 };
01043 
01044 void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
01045   assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
01046   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
01047   Indexes->removeMachineInstrFromMaps(MI);
01048   SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
01049   assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
01050          OldIndex < getMBBEndIdx(MI->getParent()) &&
01051          "Cannot handle moves across basic block boundaries.");
01052 
01053   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
01054   HME.updateAllRanges(MI);
01055 }
01056 
01057 void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
01058                                          MachineInstr* BundleStart,
01059                                          bool UpdateFlags) {
01060   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
01061   SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
01062   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
01063   HME.updateAllRanges(MI);
01064 }
01065 
01066 void
01067 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
01068                                       MachineBasicBlock::iterator Begin,
01069                                       MachineBasicBlock::iterator End,
01070                                       ArrayRef<unsigned> OrigRegs) {
01071   // Find anchor points, which are at the beginning/end of blocks or at
01072   // instructions that already have indexes.
01073   while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
01074     --Begin;
01075   while (End != MBB->end() && !Indexes->hasIndex(End))
01076     ++End;
01077 
01078   SlotIndex endIdx;
01079   if (End == MBB->end())
01080     endIdx = getMBBEndIdx(MBB).getPrevSlot();
01081   else
01082     endIdx = getInstructionIndex(End);
01083 
01084   Indexes->repairIndexesInRange(MBB, Begin, End);
01085 
01086   for (MachineBasicBlock::iterator I = End; I != Begin;) {
01087     --I;
01088     MachineInstr *MI = I;
01089     if (MI->isDebugValue())
01090       continue;
01091     for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
01092          MOE = MI->operands_end(); MOI != MOE; ++MOI) {
01093       if (MOI->isReg() &&
01094           TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
01095           !hasInterval(MOI->getReg())) {
01096         createAndComputeVirtRegInterval(MOI->getReg());
01097       }
01098     }
01099   }
01100 
01101   for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
01102     unsigned Reg = OrigRegs[i];
01103     if (!TargetRegisterInfo::isVirtualRegister(Reg))
01104       continue;
01105 
01106     LiveInterval &LI = getInterval(Reg);
01107     // FIXME: Should we support undefs that gain defs?
01108     if (!LI.hasAtLeastOneValue())
01109       continue;
01110 
01111     LiveInterval::iterator LII = LI.find(endIdx);
01112     SlotIndex lastUseIdx;
01113     if (LII != LI.end() && LII->start < endIdx)
01114       lastUseIdx = LII->end;
01115     else
01116       --LII;
01117 
01118     for (MachineBasicBlock::iterator I = End; I != Begin;) {
01119       --I;
01120       MachineInstr *MI = I;
01121       if (MI->isDebugValue())
01122         continue;
01123 
01124       SlotIndex instrIdx = getInstructionIndex(MI);
01125       bool isStartValid = getInstructionFromIndex(LII->start);
01126       bool isEndValid = getInstructionFromIndex(LII->end);
01127 
01128       // FIXME: This doesn't currently handle early-clobber or multiple removed
01129       // defs inside of the region to repair.
01130       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
01131            OE = MI->operands_end(); OI != OE; ++OI) {
01132         const MachineOperand &MO = *OI;
01133         if (!MO.isReg() || MO.getReg() != Reg)
01134           continue;
01135 
01136         if (MO.isDef()) {
01137           if (!isStartValid) {
01138             if (LII->end.isDead()) {
01139               SlotIndex prevStart;
01140               if (LII != LI.begin())
01141                 prevStart = std::prev(LII)->start;
01142 
01143               // FIXME: This could be more efficient if there was a
01144               // removeSegment method that returned an iterator.
01145               LI.removeSegment(*LII, true);
01146               if (prevStart.isValid())
01147                 LII = LI.find(prevStart);
01148               else
01149                 LII = LI.begin();
01150             } else {
01151               LII->start = instrIdx.getRegSlot();
01152               LII->valno->def = instrIdx.getRegSlot();
01153               if (MO.getSubReg() && !MO.isUndef())
01154                 lastUseIdx = instrIdx.getRegSlot();
01155               else
01156                 lastUseIdx = SlotIndex();
01157               continue;
01158             }
01159           }
01160 
01161           if (!lastUseIdx.isValid()) {
01162             VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
01163                                           VNInfoAllocator);
01164             LiveRange::Segment S(instrIdx.getRegSlot(),
01165                                  instrIdx.getDeadSlot(), VNI);
01166             LII = LI.addSegment(S);
01167           } else if (LII->start != instrIdx.getRegSlot()) {
01168             VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
01169                                           VNInfoAllocator);
01170             LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
01171             LII = LI.addSegment(S);
01172           }
01173 
01174           if (MO.getSubReg() && !MO.isUndef())
01175             lastUseIdx = instrIdx.getRegSlot();
01176           else
01177             lastUseIdx = SlotIndex();
01178         } else if (MO.isUse()) {
01179           // FIXME: This should probably be handled outside of this branch,
01180           // either as part of the def case (for defs inside of the region) or
01181           // after the loop over the region.
01182           if (!isEndValid && !LII->end.isBlock())
01183             LII->end = instrIdx.getRegSlot();
01184           if (!lastUseIdx.isValid())
01185             lastUseIdx = instrIdx.getRegSlot();
01186         }
01187       }
01188     }
01189   }
01190 }