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