• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LiveInterval analysis pass which is used
11 // by the Linear Scan Register allocator. This pass linearizes the
12 // basic blocks of the function in DFS order and uses the
13 // LiveVariables pass to conservatively compute live intervals for
14 // each virtual and physical register.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #define DEBUG_TYPE "regalloc"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "LiveRangeCalc.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include <algorithm>
39 #include <cmath>
40 #include <limits>
41 using namespace llvm;
42 
43 char LiveIntervals::ID = 0;
44 char &llvm::LiveIntervalsID = LiveIntervals::ID;
45 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
46                 "Live Interval Analysis", false, false)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)47 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
48 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
49 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
50 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
51 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
52                 "Live Interval Analysis", false, false)
53 
54 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
55   AU.setPreservesCFG();
56   AU.addRequired<AliasAnalysis>();
57   AU.addPreserved<AliasAnalysis>();
58   // LiveVariables isn't really required by this analysis, it is only required
59   // here to make sure it is live during TwoAddressInstructionPass and
60   // PHIElimination. This is temporary.
61   AU.addRequired<LiveVariables>();
62   AU.addPreserved<LiveVariables>();
63   AU.addPreservedID(MachineLoopInfoID);
64   AU.addRequiredTransitiveID(MachineDominatorsID);
65   AU.addPreservedID(MachineDominatorsID);
66   AU.addPreserved<SlotIndexes>();
67   AU.addRequiredTransitive<SlotIndexes>();
68   MachineFunctionPass::getAnalysisUsage(AU);
69 }
70 
LiveIntervals()71 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
72   DomTree(0), LRCalc(0) {
73   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
74 }
75 
~LiveIntervals()76 LiveIntervals::~LiveIntervals() {
77   delete LRCalc;
78 }
79 
releaseMemory()80 void LiveIntervals::releaseMemory() {
81   // Free the live intervals themselves.
82   for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
83     delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
84   VirtRegIntervals.clear();
85   RegMaskSlots.clear();
86   RegMaskBits.clear();
87   RegMaskBlocks.clear();
88 
89   for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
90     delete RegUnitIntervals[i];
91   RegUnitIntervals.clear();
92 
93   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
94   VNInfoAllocator.Reset();
95 }
96 
97 /// runOnMachineFunction - Register allocate the whole function
98 ///
runOnMachineFunction(MachineFunction & fn)99 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
100   MF = &fn;
101   MRI = &MF->getRegInfo();
102   TM = &fn.getTarget();
103   TRI = TM->getRegisterInfo();
104   TII = TM->getInstrInfo();
105   AA = &getAnalysis<AliasAnalysis>();
106   Indexes = &getAnalysis<SlotIndexes>();
107   DomTree = &getAnalysis<MachineDominatorTree>();
108   if (!LRCalc)
109     LRCalc = new LiveRangeCalc();
110 
111   // Allocate space for all virtual registers.
112   VirtRegIntervals.resize(MRI->getNumVirtRegs());
113 
114   computeVirtRegs();
115   computeRegMasks();
116   computeLiveInRegUnits();
117 
118   DEBUG(dump());
119   return true;
120 }
121 
122 /// print - Implement the dump method.
print(raw_ostream & OS,const Module *) const123 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
124   OS << "********** INTERVALS **********\n";
125 
126   // Dump the regunits.
127   for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
128     if (LiveInterval *LI = RegUnitIntervals[i])
129       OS << PrintRegUnit(i, TRI) << " = " << *LI << '\n';
130 
131   // Dump the virtregs.
132   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
133     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
134     if (hasInterval(Reg))
135       OS << PrintReg(Reg) << " = " << getInterval(Reg) << '\n';
136   }
137 
138   OS << "RegMasks:";
139   for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
140     OS << ' ' << RegMaskSlots[i];
141   OS << '\n';
142 
143   printInstrs(OS);
144 }
145 
printInstrs(raw_ostream & OS) const146 void LiveIntervals::printInstrs(raw_ostream &OS) const {
147   OS << "********** MACHINEINSTRS **********\n";
148   MF->print(OS, Indexes);
149 }
150 
151 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dumpInstrs() const152 void LiveIntervals::dumpInstrs() const {
153   printInstrs(dbgs());
154 }
155 #endif
156 
createInterval(unsigned reg)157 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
158   float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
159   return new LiveInterval(reg, Weight);
160 }
161 
162 
163 /// computeVirtRegInterval - Compute the live interval of a virtual register,
164 /// based on defs and uses.
computeVirtRegInterval(LiveInterval * LI)165 void LiveIntervals::computeVirtRegInterval(LiveInterval *LI) {
166   assert(LRCalc && "LRCalc not initialized.");
167   assert(LI->empty() && "Should only compute empty intervals.");
168   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
169   LRCalc->createDeadDefs(LI);
170   LRCalc->extendToUses(LI);
171 }
172 
computeVirtRegs()173 void LiveIntervals::computeVirtRegs() {
174   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
175     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
176     if (MRI->reg_nodbg_empty(Reg))
177       continue;
178     LiveInterval *LI = createInterval(Reg);
179     VirtRegIntervals[Reg] = LI;
180     computeVirtRegInterval(LI);
181   }
182 }
183 
computeRegMasks()184 void LiveIntervals::computeRegMasks() {
185   RegMaskBlocks.resize(MF->getNumBlockIDs());
186 
187   // Find all instructions with regmask operands.
188   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
189        MBBI != E; ++MBBI) {
190     MachineBasicBlock *MBB = MBBI;
191     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
192     RMB.first = RegMaskSlots.size();
193     for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
194          MI != ME; ++MI)
195       for (MIOperands MO(MI); MO.isValid(); ++MO) {
196         if (!MO->isRegMask())
197           continue;
198           RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
199           RegMaskBits.push_back(MO->getRegMask());
200       }
201     // Compute the number of register mask instructions in this block.
202     RMB.second = RegMaskSlots.size() - RMB.first;
203   }
204 }
205 
206 //===----------------------------------------------------------------------===//
207 //                           Register Unit Liveness
208 //===----------------------------------------------------------------------===//
209 //
210 // Fixed interference typically comes from ABI boundaries: Function arguments
211 // and return values are passed in fixed registers, and so are exception
212 // pointers entering landing pads. Certain instructions require values to be
213 // present in specific registers. That is also represented through fixed
214 // interference.
215 //
216 
217 /// computeRegUnitInterval - Compute the live interval of a register unit, based
218 /// on the uses and defs of aliasing registers.  The interval should be empty,
219 /// or contain only dead phi-defs from ABI blocks.
computeRegUnitInterval(LiveInterval * LI)220 void LiveIntervals::computeRegUnitInterval(LiveInterval *LI) {
221   unsigned Unit = LI->reg;
222 
223   assert(LRCalc && "LRCalc not initialized.");
224   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
225 
226   // The physregs aliasing Unit are the roots and their super-registers.
227   // Create all values as dead defs before extending to uses. Note that roots
228   // may share super-registers. That's OK because createDeadDefs() is
229   // idempotent. It is very rare for a register unit to have multiple roots, so
230   // uniquing super-registers is probably not worthwhile.
231   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
232     unsigned Root = *Roots;
233     if (!MRI->reg_empty(Root))
234       LRCalc->createDeadDefs(LI, Root);
235     for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
236       if (!MRI->reg_empty(*Supers))
237         LRCalc->createDeadDefs(LI, *Supers);
238     }
239   }
240 
241   // Now extend LI to reach all uses.
242   // Ignore uses of reserved registers. We only track defs of those.
243   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
244     unsigned Root = *Roots;
245     if (!MRI->isReserved(Root) && !MRI->reg_empty(Root))
246       LRCalc->extendToUses(LI, Root);
247     for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
248       unsigned Reg = *Supers;
249       if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
250         LRCalc->extendToUses(LI, Reg);
251     }
252   }
253 }
254 
255 
256 /// computeLiveInRegUnits - Precompute the live ranges of any register units
257 /// that are live-in to an ABI block somewhere. Register values can appear
258 /// without a corresponding def when entering the entry block or a landing pad.
259 ///
computeLiveInRegUnits()260 void LiveIntervals::computeLiveInRegUnits() {
261   RegUnitIntervals.resize(TRI->getNumRegUnits());
262   DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
263 
264   // Keep track of the intervals allocated.
265   SmallVector<LiveInterval*, 8> NewIntvs;
266 
267   // Check all basic blocks for live-ins.
268   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
269        MFI != MFE; ++MFI) {
270     const MachineBasicBlock *MBB = MFI;
271 
272     // We only care about ABI blocks: Entry + landing pads.
273     if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
274       continue;
275 
276     // Create phi-defs at Begin for all live-in registers.
277     SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
278     DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
279     for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
280          LIE = MBB->livein_end(); LII != LIE; ++LII) {
281       for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
282         unsigned Unit = *Units;
283         LiveInterval *Intv = RegUnitIntervals[Unit];
284         if (!Intv) {
285           Intv = RegUnitIntervals[Unit] = new LiveInterval(Unit, HUGE_VALF);
286           NewIntvs.push_back(Intv);
287         }
288         VNInfo *VNI = Intv->createDeadDef(Begin, getVNInfoAllocator());
289         (void)VNI;
290         DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
291       }
292     }
293     DEBUG(dbgs() << '\n');
294   }
295   DEBUG(dbgs() << "Created " << NewIntvs.size() << " new intervals.\n");
296 
297   // Compute the 'normal' part of the intervals.
298   for (unsigned i = 0, e = NewIntvs.size(); i != e; ++i)
299     computeRegUnitInterval(NewIntvs[i]);
300 }
301 
302 
303 /// shrinkToUses - After removing some uses of a register, shrink its live
304 /// range to just the remaining uses. This method does not compute reaching
305 /// defs for new uses, and it doesn't remove dead defs.
shrinkToUses(LiveInterval * li,SmallVectorImpl<MachineInstr * > * dead)306 bool LiveIntervals::shrinkToUses(LiveInterval *li,
307                                  SmallVectorImpl<MachineInstr*> *dead) {
308   DEBUG(dbgs() << "Shrink: " << *li << '\n');
309   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
310          && "Can only shrink virtual registers");
311   // Find all the values used, including PHI kills.
312   SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
313 
314   // Blocks that have already been added to WorkList as live-out.
315   SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
316 
317   // Visit all instructions reading li->reg.
318   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(li->reg);
319        MachineInstr *UseMI = I.skipInstruction();) {
320     if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
321       continue;
322     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
323     LiveRangeQuery LRQ(*li, Idx);
324     VNInfo *VNI = LRQ.valueIn();
325     if (!VNI) {
326       // This shouldn't happen: readsVirtualRegister returns true, but there is
327       // no live value. It is likely caused by a target getting <undef> flags
328       // wrong.
329       DEBUG(dbgs() << Idx << '\t' << *UseMI
330                    << "Warning: Instr claims to read non-existent value in "
331                     << *li << '\n');
332       continue;
333     }
334     // Special case: An early-clobber tied operand reads and writes the
335     // register one slot early.
336     if (VNInfo *DefVNI = LRQ.valueDefined())
337       Idx = DefVNI->def;
338 
339     WorkList.push_back(std::make_pair(Idx, VNI));
340   }
341 
342   // Create a new live interval with only minimal live segments per def.
343   LiveInterval NewLI(li->reg, 0);
344   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
345        I != E; ++I) {
346     VNInfo *VNI = *I;
347     if (VNI->isUnused())
348       continue;
349     NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
350   }
351 
352   // Keep track of the PHIs that are in use.
353   SmallPtrSet<VNInfo*, 8> UsedPHIs;
354 
355   // Extend intervals to reach all uses in WorkList.
356   while (!WorkList.empty()) {
357     SlotIndex Idx = WorkList.back().first;
358     VNInfo *VNI = WorkList.back().second;
359     WorkList.pop_back();
360     const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
361     SlotIndex BlockStart = getMBBStartIdx(MBB);
362 
363     // Extend the live range for VNI to be live at Idx.
364     if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
365       (void)ExtVNI;
366       assert(ExtVNI == VNI && "Unexpected existing value number");
367       // Is this a PHIDef we haven't seen before?
368       if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
369         continue;
370       // The PHI is live, make sure the predecessors are live-out.
371       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
372            PE = MBB->pred_end(); PI != PE; ++PI) {
373         if (!LiveOut.insert(*PI))
374           continue;
375         SlotIndex Stop = getMBBEndIdx(*PI);
376         // A predecessor is not required to have a live-out value for a PHI.
377         if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
378           WorkList.push_back(std::make_pair(Stop, PVNI));
379       }
380       continue;
381     }
382 
383     // VNI is live-in to MBB.
384     DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
385     NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
386 
387     // Make sure VNI is live-out from the predecessors.
388     for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
389          PE = MBB->pred_end(); PI != PE; ++PI) {
390       if (!LiveOut.insert(*PI))
391         continue;
392       SlotIndex Stop = getMBBEndIdx(*PI);
393       assert(li->getVNInfoBefore(Stop) == VNI &&
394              "Wrong value out of predecessor");
395       WorkList.push_back(std::make_pair(Stop, VNI));
396     }
397   }
398 
399   // Handle dead values.
400   bool CanSeparate = false;
401   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
402        I != E; ++I) {
403     VNInfo *VNI = *I;
404     if (VNI->isUnused())
405       continue;
406     LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
407     assert(LII != NewLI.end() && "Missing live range for PHI");
408     if (LII->end != VNI->def.getDeadSlot())
409       continue;
410     if (VNI->isPHIDef()) {
411       // This is a dead PHI. Remove it.
412       VNI->markUnused();
413       NewLI.removeRange(*LII);
414       DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
415       CanSeparate = true;
416     } else {
417       // This is a dead def. Make sure the instruction knows.
418       MachineInstr *MI = getInstructionFromIndex(VNI->def);
419       assert(MI && "No instruction defining live value");
420       MI->addRegisterDead(li->reg, TRI);
421       if (dead && MI->allDefsAreDead()) {
422         DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
423         dead->push_back(MI);
424       }
425     }
426   }
427 
428   // Move the trimmed ranges back.
429   li->ranges.swap(NewLI.ranges);
430   DEBUG(dbgs() << "Shrunk: " << *li << '\n');
431   return CanSeparate;
432 }
433 
extendToIndices(LiveInterval * LI,ArrayRef<SlotIndex> Indices)434 void LiveIntervals::extendToIndices(LiveInterval *LI,
435                                     ArrayRef<SlotIndex> Indices) {
436   assert(LRCalc && "LRCalc not initialized.");
437   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
438   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
439     LRCalc->extend(LI, Indices[i]);
440 }
441 
pruneValue(LiveInterval * LI,SlotIndex Kill,SmallVectorImpl<SlotIndex> * EndPoints)442 void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
443                                SmallVectorImpl<SlotIndex> *EndPoints) {
444   LiveRangeQuery LRQ(*LI, Kill);
445   VNInfo *VNI = LRQ.valueOut();
446   if (!VNI)
447     return;
448 
449   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
450   SlotIndex MBBStart, MBBEnd;
451   tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
452 
453   // If VNI isn't live out from KillMBB, the value is trivially pruned.
454   if (LRQ.endPoint() < MBBEnd) {
455     LI->removeRange(Kill, LRQ.endPoint());
456     if (EndPoints) EndPoints->push_back(LRQ.endPoint());
457     return;
458   }
459 
460   // VNI is live out of KillMBB.
461   LI->removeRange(Kill, MBBEnd);
462   if (EndPoints) EndPoints->push_back(MBBEnd);
463 
464   // Find all blocks that are reachable from KillMBB without leaving VNI's live
465   // range. It is possible that KillMBB itself is reachable, so start a DFS
466   // from each successor.
467   typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
468   VisitedTy Visited;
469   for (MachineBasicBlock::succ_iterator
470        SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
471        SuccI != SuccE; ++SuccI) {
472     for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
473          I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
474          I != E;) {
475       MachineBasicBlock *MBB = *I;
476 
477       // Check if VNI is live in to MBB.
478       tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
479       LiveRangeQuery LRQ(*LI, MBBStart);
480       if (LRQ.valueIn() != VNI) {
481         // This block isn't part of the VNI live range. Prune the search.
482         I.skipChildren();
483         continue;
484       }
485 
486       // Prune the search if VNI is killed in MBB.
487       if (LRQ.endPoint() < MBBEnd) {
488         LI->removeRange(MBBStart, LRQ.endPoint());
489         if (EndPoints) EndPoints->push_back(LRQ.endPoint());
490         I.skipChildren();
491         continue;
492       }
493 
494       // VNI is live through MBB.
495       LI->removeRange(MBBStart, MBBEnd);
496       if (EndPoints) EndPoints->push_back(MBBEnd);
497       ++I;
498     }
499   }
500 }
501 
502 //===----------------------------------------------------------------------===//
503 // Register allocator hooks.
504 //
505 
addKillFlags(const VirtRegMap * VRM)506 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
507   // Keep track of regunit ranges.
508   SmallVector<std::pair<LiveInterval*, LiveInterval::iterator>, 8> RU;
509 
510   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
511     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
512     if (MRI->reg_nodbg_empty(Reg))
513       continue;
514     LiveInterval *LI = &getInterval(Reg);
515     if (LI->empty())
516       continue;
517 
518     // Find the regunit intervals for the assigned register. They may overlap
519     // the virtual register live range, cancelling any kills.
520     RU.clear();
521     for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
522          ++Units) {
523       LiveInterval *RUInt = &getRegUnit(*Units);
524       if (RUInt->empty())
525         continue;
526       RU.push_back(std::make_pair(RUInt, RUInt->find(LI->begin()->end)));
527     }
528 
529     // Every instruction that kills Reg corresponds to a live range end point.
530     for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
531          ++RI) {
532       // A block index indicates an MBB edge.
533       if (RI->end.isBlock())
534         continue;
535       MachineInstr *MI = getInstructionFromIndex(RI->end);
536       if (!MI)
537         continue;
538 
539       // Check if any of the reguints are live beyond the end of RI. That could
540       // happen when a physreg is defined as a copy of a virtreg:
541       //
542       //   %EAX = COPY %vreg5
543       //   FOO %vreg5         <--- MI, cancel kill because %EAX is live.
544       //   BAR %EAX<kill>
545       //
546       // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
547       bool CancelKill = false;
548       for (unsigned u = 0, e = RU.size(); u != e; ++u) {
549         LiveInterval *RInt = RU[u].first;
550         LiveInterval::iterator &I = RU[u].second;
551         if (I == RInt->end())
552           continue;
553         I = RInt->advanceTo(I, RI->end);
554         if (I == RInt->end() || I->start >= RI->end)
555           continue;
556         // I is overlapping RI.
557         CancelKill = true;
558         break;
559       }
560       if (CancelKill)
561         MI->clearRegisterKills(Reg, NULL);
562       else
563         MI->addRegisterKilled(Reg, NULL);
564     }
565   }
566 }
567 
568 MachineBasicBlock*
intervalIsInOneMBB(const LiveInterval & LI) const569 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
570   // A local live range must be fully contained inside the block, meaning it is
571   // defined and killed at instructions, not at block boundaries. It is not
572   // live in or or out of any block.
573   //
574   // It is technically possible to have a PHI-defined live range identical to a
575   // single block, but we are going to return false in that case.
576 
577   SlotIndex Start = LI.beginIndex();
578   if (Start.isBlock())
579     return NULL;
580 
581   SlotIndex Stop = LI.endIndex();
582   if (Stop.isBlock())
583     return NULL;
584 
585   // getMBBFromIndex doesn't need to search the MBB table when both indexes
586   // belong to proper instructions.
587   MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
588   MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
589   return MBB1 == MBB2 ? MBB1 : NULL;
590 }
591 
592 bool
hasPHIKill(const LiveInterval & LI,const VNInfo * VNI) const593 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
594   for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
595        I != E; ++I) {
596     const VNInfo *PHI = *I;
597     if (PHI->isUnused() || !PHI->isPHIDef())
598       continue;
599     const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
600     // Conservatively return true instead of scanning huge predecessor lists.
601     if (PHIMBB->pred_size() > 100)
602       return true;
603     for (MachineBasicBlock::const_pred_iterator
604          PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
605       if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
606         return true;
607   }
608   return false;
609 }
610 
611 float
getSpillWeight(bool isDef,bool isUse,unsigned loopDepth)612 LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
613   // Limit the loop depth ridiculousness.
614   if (loopDepth > 200)
615     loopDepth = 200;
616 
617   // The loop depth is used to roughly estimate the number of times the
618   // instruction is executed. Something like 10^d is simple, but will quickly
619   // overflow a float. This expression behaves like 10^d for small d, but is
620   // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
621   // headroom before overflow.
622   // By the way, powf() might be unavailable here. For consistency,
623   // We may take pow(double,double).
624   float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
625 
626   return (isDef + isUse) * lc;
627 }
628 
addLiveRangeToEndOfBlock(unsigned reg,MachineInstr * startInst)629 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
630                                                   MachineInstr* startInst) {
631   LiveInterval& Interval = getOrCreateInterval(reg);
632   VNInfo* VN = Interval.getNextValue(
633     SlotIndex(getInstructionIndex(startInst).getRegSlot()),
634     getVNInfoAllocator());
635   LiveRange LR(
636      SlotIndex(getInstructionIndex(startInst).getRegSlot()),
637      getMBBEndIdx(startInst->getParent()), VN);
638   Interval.addRange(LR);
639 
640   return LR;
641 }
642 
643 
644 //===----------------------------------------------------------------------===//
645 //                          Register mask functions
646 //===----------------------------------------------------------------------===//
647 
checkRegMaskInterference(LiveInterval & LI,BitVector & UsableRegs)648 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
649                                              BitVector &UsableRegs) {
650   if (LI.empty())
651     return false;
652   LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
653 
654   // Use a smaller arrays for local live ranges.
655   ArrayRef<SlotIndex> Slots;
656   ArrayRef<const uint32_t*> Bits;
657   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
658     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
659     Bits = getRegMaskBitsInBlock(MBB->getNumber());
660   } else {
661     Slots = getRegMaskSlots();
662     Bits = getRegMaskBits();
663   }
664 
665   // We are going to enumerate all the register mask slots contained in LI.
666   // Start with a binary search of RegMaskSlots to find a starting point.
667   ArrayRef<SlotIndex>::iterator SlotI =
668     std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
669   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
670 
671   // No slots in range, LI begins after the last call.
672   if (SlotI == SlotE)
673     return false;
674 
675   bool Found = false;
676   for (;;) {
677     assert(*SlotI >= LiveI->start);
678     // Loop over all slots overlapping this segment.
679     while (*SlotI < LiveI->end) {
680       // *SlotI overlaps LI. Collect mask bits.
681       if (!Found) {
682         // This is the first overlap. Initialize UsableRegs to all ones.
683         UsableRegs.clear();
684         UsableRegs.resize(TRI->getNumRegs(), true);
685         Found = true;
686       }
687       // Remove usable registers clobbered by this mask.
688       UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
689       if (++SlotI == SlotE)
690         return Found;
691     }
692     // *SlotI is beyond the current LI segment.
693     LiveI = LI.advanceTo(LiveI, *SlotI);
694     if (LiveI == LiveE)
695       return Found;
696     // Advance SlotI until it overlaps.
697     while (*SlotI < LiveI->start)
698       if (++SlotI == SlotE)
699         return Found;
700   }
701 }
702 
703 //===----------------------------------------------------------------------===//
704 //                         IntervalUpdate class.
705 //===----------------------------------------------------------------------===//
706 
707 // HMEditor is a toolkit used by handleMove to trim or extend live intervals.
708 class LiveIntervals::HMEditor {
709 private:
710   LiveIntervals& LIS;
711   const MachineRegisterInfo& MRI;
712   const TargetRegisterInfo& TRI;
713   SlotIndex OldIdx;
714   SlotIndex NewIdx;
715   SmallPtrSet<LiveInterval*, 8> Updated;
716   bool UpdateFlags;
717 
718 public:
HMEditor(LiveIntervals & LIS,const MachineRegisterInfo & MRI,const TargetRegisterInfo & TRI,SlotIndex OldIdx,SlotIndex NewIdx,bool UpdateFlags)719   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
720            const TargetRegisterInfo& TRI,
721            SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
722     : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
723       UpdateFlags(UpdateFlags) {}
724 
725   // FIXME: UpdateFlags is a workaround that creates live intervals for all
726   // physregs, even those that aren't needed for regalloc, in order to update
727   // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
728   // flags, and postRA passes will use a live register utility instead.
getRegUnitLI(unsigned Unit)729   LiveInterval *getRegUnitLI(unsigned Unit) {
730     if (UpdateFlags)
731       return &LIS.getRegUnit(Unit);
732     return LIS.getCachedRegUnit(Unit);
733   }
734 
735   /// Update all live ranges touched by MI, assuming a move from OldIdx to
736   /// NewIdx.
updateAllRanges(MachineInstr * MI)737   void updateAllRanges(MachineInstr *MI) {
738     DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
739     bool hasRegMask = false;
740     for (MIOperands MO(MI); MO.isValid(); ++MO) {
741       if (MO->isRegMask())
742         hasRegMask = true;
743       if (!MO->isReg())
744         continue;
745       // Aggressively clear all kill flags.
746       // They are reinserted by VirtRegRewriter.
747       if (MO->isUse())
748         MO->setIsKill(false);
749 
750       unsigned Reg = MO->getReg();
751       if (!Reg)
752         continue;
753       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
754         updateRange(LIS.getInterval(Reg));
755         continue;
756       }
757 
758       // For physregs, only update the regunits that actually have a
759       // precomputed live range.
760       for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
761         if (LiveInterval *LI = getRegUnitLI(*Units))
762           updateRange(*LI);
763     }
764     if (hasRegMask)
765       updateRegMaskSlots();
766   }
767 
768 private:
769   /// Update a single live range, assuming an instruction has been moved from
770   /// OldIdx to NewIdx.
updateRange(LiveInterval & LI)771   void updateRange(LiveInterval &LI) {
772     if (!Updated.insert(&LI))
773       return;
774     DEBUG({
775       dbgs() << "     ";
776       if (TargetRegisterInfo::isVirtualRegister(LI.reg))
777         dbgs() << PrintReg(LI.reg);
778       else
779         dbgs() << PrintRegUnit(LI.reg, &TRI);
780       dbgs() << ":\t" << LI << '\n';
781     });
782     if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
783       handleMoveDown(LI);
784     else
785       handleMoveUp(LI);
786     DEBUG(dbgs() << "        -->\t" << LI << '\n');
787     LI.verify();
788   }
789 
790   /// Update LI to reflect an instruction has been moved downwards from OldIdx
791   /// to NewIdx.
792   ///
793   /// 1. Live def at OldIdx:
794   ///    Move def to NewIdx, assert endpoint after NewIdx.
795   ///
796   /// 2. Live def at OldIdx, killed at NewIdx:
797   ///    Change to dead def at NewIdx.
798   ///    (Happens when bundling def+kill together).
799   ///
800   /// 3. Dead def at OldIdx:
801   ///    Move def to NewIdx, possibly across another live value.
802   ///
803   /// 4. Def at OldIdx AND at NewIdx:
804   ///    Remove live range [OldIdx;NewIdx) and value defined at OldIdx.
805   ///    (Happens when bundling multiple defs together).
806   ///
807   /// 5. Value read at OldIdx, killed before NewIdx:
808   ///    Extend kill to NewIdx.
809   ///
handleMoveDown(LiveInterval & LI)810   void handleMoveDown(LiveInterval &LI) {
811     // First look for a kill at OldIdx.
812     LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
813     LiveInterval::iterator E = LI.end();
814     // Is LI even live at OldIdx?
815     if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
816       return;
817 
818     // Handle a live-in value.
819     if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
820       bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
821       // If the live-in value already extends to NewIdx, there is nothing to do.
822       if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
823         return;
824       // Aggressively remove all kill flags from the old kill point.
825       // Kill flags shouldn't be used while live intervals exist, they will be
826       // reinserted by VirtRegRewriter.
827       if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
828         for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
829           if (MO->isReg() && MO->isUse())
830             MO->setIsKill(false);
831       // Adjust I->end to reach NewIdx. This may temporarily make LI invalid by
832       // overlapping ranges. Case 5 above.
833       I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
834       // If this was a kill, there may also be a def. Otherwise we're done.
835       if (!isKill)
836         return;
837       ++I;
838     }
839 
840     // Check for a def at OldIdx.
841     if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
842       return;
843     // We have a def at OldIdx.
844     VNInfo *DefVNI = I->valno;
845     assert(DefVNI->def == I->start && "Inconsistent def");
846     DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
847     // If the defined value extends beyond NewIdx, just move the def down.
848     // This is case 1 above.
849     if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
850       I->start = DefVNI->def;
851       return;
852     }
853     // The remaining possibilities are now:
854     // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
855     // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
856     // In either case, it is possible that there is an existing def at NewIdx.
857     assert((I->end == OldIdx.getDeadSlot() ||
858             SlotIndex::isSameInstr(I->end, NewIdx)) &&
859             "Cannot move def below kill");
860     LiveInterval::iterator NewI = LI.advanceTo(I, NewIdx.getRegSlot());
861     if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
862       // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
863       // coalesced into that value.
864       assert(NewI->valno != DefVNI && "Multiple defs of value?");
865       LI.removeValNo(DefVNI);
866       return;
867     }
868     // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
869     // If the def at OldIdx was dead, we allow it to be moved across other LI
870     // values. The new range should be placed immediately before NewI, move any
871     // intermediate ranges up.
872     assert(NewI != I && "Inconsistent iterators");
873     std::copy(llvm::next(I), NewI, I);
874     *llvm::prior(NewI) = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
875   }
876 
877   /// Update LI to reflect an instruction has been moved upwards from OldIdx
878   /// to NewIdx.
879   ///
880   /// 1. Live def at OldIdx:
881   ///    Hoist def to NewIdx.
882   ///
883   /// 2. Dead def at OldIdx:
884   ///    Hoist def+end to NewIdx, possibly move across other values.
885   ///
886   /// 3. Dead def at OldIdx AND existing def at NewIdx:
887   ///    Remove value defined at OldIdx, coalescing it with existing value.
888   ///
889   /// 4. Live def at OldIdx AND existing def at NewIdx:
890   ///    Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
891   ///    (Happens when bundling multiple defs together).
892   ///
893   /// 5. Value killed at OldIdx:
894   ///    Hoist kill to NewIdx, then scan for last kill between NewIdx and
895   ///    OldIdx.
896   ///
handleMoveUp(LiveInterval & LI)897   void handleMoveUp(LiveInterval &LI) {
898     // First look for a kill at OldIdx.
899     LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
900     LiveInterval::iterator E = LI.end();
901     // Is LI even live at OldIdx?
902     if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
903       return;
904 
905     // Handle a live-in value.
906     if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
907       // If the live-in value isn't killed here, there is nothing to do.
908       if (!SlotIndex::isSameInstr(OldIdx, I->end))
909         return;
910       // Adjust I->end to end at NewIdx. If we are hoisting a kill above
911       // another use, we need to search for that use. Case 5 above.
912       I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
913       ++I;
914       // If OldIdx also defines a value, there couldn't have been another use.
915       if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
916         // No def, search for the new kill.
917         // This can never be an early clobber kill since there is no def.
918         llvm::prior(I)->end = findLastUseBefore(LI.reg).getRegSlot();
919         return;
920       }
921     }
922 
923     // Now deal with the def at OldIdx.
924     assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
925     VNInfo *DefVNI = I->valno;
926     assert(DefVNI->def == I->start && "Inconsistent def");
927     DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
928 
929     // Check for an existing def at NewIdx.
930     LiveInterval::iterator NewI = LI.find(NewIdx.getRegSlot());
931     if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
932       assert(NewI->valno != DefVNI && "Same value defined more than once?");
933       // There is an existing def at NewIdx.
934       if (I->end.isDead()) {
935         // Case 3: Remove the dead def at OldIdx.
936         LI.removeValNo(DefVNI);
937         return;
938       }
939       // Case 4: Replace def at NewIdx with live def at OldIdx.
940       I->start = DefVNI->def;
941       LI.removeValNo(NewI->valno);
942       return;
943     }
944 
945     // There is no existing def at NewIdx. Hoist DefVNI.
946     if (!I->end.isDead()) {
947       // Leave the end point of a live def.
948       I->start = DefVNI->def;
949       return;
950     }
951 
952     // DefVNI is a dead def. It may have been moved across other values in LI,
953     // so move I up to NewI. Slide [NewI;I) down one position.
954     std::copy_backward(NewI, I, llvm::next(I));
955     *NewI = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
956   }
957 
updateRegMaskSlots()958   void updateRegMaskSlots() {
959     SmallVectorImpl<SlotIndex>::iterator RI =
960       std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
961                        OldIdx);
962     assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
963            "No RegMask at OldIdx.");
964     *RI = NewIdx.getRegSlot();
965     assert((RI == LIS.RegMaskSlots.begin() ||
966             SlotIndex::isEarlierInstr(*llvm::prior(RI), *RI)) &&
967             "Cannot move regmask instruction above another call");
968     assert((llvm::next(RI) == LIS.RegMaskSlots.end() ||
969             SlotIndex::isEarlierInstr(*RI, *llvm::next(RI))) &&
970             "Cannot move regmask instruction below another call");
971   }
972 
973   // Return the last use of reg between NewIdx and OldIdx.
findLastUseBefore(unsigned Reg)974   SlotIndex findLastUseBefore(unsigned Reg) {
975 
976     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
977       SlotIndex LastUse = NewIdx;
978       for (MachineRegisterInfo::use_nodbg_iterator
979              UI = MRI.use_nodbg_begin(Reg),
980              UE = MRI.use_nodbg_end();
981            UI != UE; UI.skipInstruction()) {
982         const MachineInstr* MI = &*UI;
983         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
984         if (InstSlot > LastUse && InstSlot < OldIdx)
985           LastUse = InstSlot;
986       }
987       return LastUse;
988     }
989 
990     // This is a regunit interval, so scanning the use list could be very
991     // expensive. Scan upwards from OldIdx instead.
992     assert(NewIdx < OldIdx && "Expected upwards move");
993     SlotIndexes *Indexes = LIS.getSlotIndexes();
994     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
995 
996     // OldIdx may not correspond to an instruction any longer, so set MII to
997     // point to the next instruction after OldIdx, or MBB->end().
998     MachineBasicBlock::iterator MII = MBB->end();
999     if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1000                            Indexes->getNextNonNullIndex(OldIdx)))
1001       if (MI->getParent() == MBB)
1002         MII = MI;
1003 
1004     MachineBasicBlock::iterator Begin = MBB->begin();
1005     while (MII != Begin) {
1006       if ((--MII)->isDebugValue())
1007         continue;
1008       SlotIndex Idx = Indexes->getInstructionIndex(MII);
1009 
1010       // Stop searching when NewIdx is reached.
1011       if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
1012         return NewIdx;
1013 
1014       // Check if MII uses Reg.
1015       for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1016         if (MO->isReg() &&
1017             TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1018             TRI.hasRegUnit(MO->getReg(), Reg))
1019           return Idx;
1020     }
1021     // Didn't reach NewIdx. It must be the first instruction in the block.
1022     return NewIdx;
1023   }
1024 };
1025 
handleMove(MachineInstr * MI,bool UpdateFlags)1026 void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
1027   assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
1028   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1029   Indexes->removeMachineInstrFromMaps(MI);
1030   SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1031   assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1032          OldIndex < getMBBEndIdx(MI->getParent()) &&
1033          "Cannot handle moves across basic block boundaries.");
1034 
1035   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1036   HME.updateAllRanges(MI);
1037 }
1038 
handleMoveIntoBundle(MachineInstr * MI,MachineInstr * BundleStart,bool UpdateFlags)1039 void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
1040                                          MachineInstr* BundleStart,
1041                                          bool UpdateFlags) {
1042   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1043   SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
1044   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1045   HME.updateAllRanges(MI);
1046 }
1047 
1048 void
repairIntervalsInRange(MachineBasicBlock * MBB,MachineBasicBlock::iterator Begin,MachineBasicBlock::iterator End,ArrayRef<unsigned> OrigRegs)1049 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1050                                       MachineBasicBlock::iterator Begin,
1051                                       MachineBasicBlock::iterator End,
1052                                       ArrayRef<unsigned> OrigRegs) {
1053   // Find anchor points, which are at the beginning/end of blocks or at
1054   // instructions that already have indexes.
1055   while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
1056     --Begin;
1057   while (End != MBB->end() && !Indexes->hasIndex(End))
1058     ++End;
1059 
1060   SlotIndex endIdx;
1061   if (End == MBB->end())
1062     endIdx = getMBBEndIdx(MBB).getPrevSlot();
1063   else
1064     endIdx = getInstructionIndex(End);
1065 
1066   Indexes->repairIndexesInRange(MBB, Begin, End);
1067 
1068   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1069     --I;
1070     MachineInstr *MI = I;
1071     if (MI->isDebugValue())
1072       continue;
1073     for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1074          MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1075       if (MOI->isReg() &&
1076           TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1077           !hasInterval(MOI->getReg())) {
1078         LiveInterval &LI = getOrCreateInterval(MOI->getReg());
1079         computeVirtRegInterval(&LI);
1080       }
1081     }
1082   }
1083 
1084   for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1085     unsigned Reg = OrigRegs[i];
1086     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1087       continue;
1088 
1089     LiveInterval &LI = getInterval(Reg);
1090     // FIXME: Should we support undefs that gain defs?
1091     if (!LI.hasAtLeastOneValue())
1092       continue;
1093 
1094     LiveInterval::iterator LII = LI.find(endIdx);
1095     SlotIndex lastUseIdx;
1096     if (LII != LI.end() && LII->start < endIdx)
1097       lastUseIdx = LII->end;
1098     else
1099       --LII;
1100 
1101     for (MachineBasicBlock::iterator I = End; I != Begin;) {
1102       --I;
1103       MachineInstr *MI = I;
1104       if (MI->isDebugValue())
1105         continue;
1106 
1107       SlotIndex instrIdx = getInstructionIndex(MI);
1108       bool isStartValid = getInstructionFromIndex(LII->start);
1109       bool isEndValid = getInstructionFromIndex(LII->end);
1110 
1111       // FIXME: This doesn't currently handle early-clobber or multiple removed
1112       // defs inside of the region to repair.
1113       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1114            OE = MI->operands_end(); OI != OE; ++OI) {
1115         const MachineOperand &MO = *OI;
1116         if (!MO.isReg() || MO.getReg() != Reg)
1117           continue;
1118 
1119         if (MO.isDef()) {
1120           if (!isStartValid) {
1121             if (LII->end.isDead()) {
1122               SlotIndex prevStart;
1123               if (LII != LI.begin())
1124                 prevStart = llvm::prior(LII)->start;
1125 
1126               // FIXME: This could be more efficient if there was a removeRange
1127               // method that returned an iterator.
1128               LI.removeRange(*LII, true);
1129               if (prevStart.isValid())
1130                 LII = LI.find(prevStart);
1131               else
1132                 LII = LI.begin();
1133             } else {
1134               LII->start = instrIdx.getRegSlot();
1135               LII->valno->def = instrIdx.getRegSlot();
1136               if (MO.getSubReg() && !MO.isUndef())
1137                 lastUseIdx = instrIdx.getRegSlot();
1138               else
1139                 lastUseIdx = SlotIndex();
1140               continue;
1141             }
1142           }
1143 
1144           if (!lastUseIdx.isValid()) {
1145             VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1146                                           VNInfoAllocator);
1147             LiveRange LR(instrIdx.getRegSlot(), instrIdx.getDeadSlot(), VNI);
1148             LII = LI.addRange(LR);
1149           } else if (LII->start != instrIdx.getRegSlot()) {
1150             VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1151                                           VNInfoAllocator);
1152             LiveRange LR(instrIdx.getRegSlot(), lastUseIdx, VNI);
1153             LII = LI.addRange(LR);
1154           }
1155 
1156           if (MO.getSubReg() && !MO.isUndef())
1157             lastUseIdx = instrIdx.getRegSlot();
1158           else
1159             lastUseIdx = SlotIndex();
1160         } else if (MO.isUse()) {
1161           // FIXME: This should probably be handled outside of this branch,
1162           // either as part of the def case (for defs inside of the region) or
1163           // after the loop over the region.
1164           if (!isEndValid && !LII->end.isBlock())
1165             LII->end = instrIdx.getRegSlot();
1166           if (!lastUseIdx.isValid())
1167             lastUseIdx = instrIdx.getRegSlot();
1168         }
1169       }
1170     }
1171   }
1172 }
1173