Extend -new-coalescer SSA update to handle mapped values as well.
[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 "llvm/Value.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "LiveRangeCalc.h"
37 #include "VirtRegMap.h"
38 #include <algorithm>
39 #include <limits>
40 #include <cmath>
41 using namespace llvm;
42
43 // Switch to the new experimental algorithm for computing live intervals.
44 static cl::opt<bool>
45 NewLiveIntervals("new-live-intervals", cl::Hidden,
46                  cl::desc("Use new algorithm forcomputing live intervals"));
47
48 char LiveIntervals::ID = 0;
49 char &llvm::LiveIntervalsID = LiveIntervals::ID;
50 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
51                 "Live Interval Analysis", false, false)
52 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
53 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
54 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
55 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
56 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
57                 "Live Interval Analysis", false, false)
58
59 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
60   AU.setPreservesCFG();
61   AU.addRequired<AliasAnalysis>();
62   AU.addPreserved<AliasAnalysis>();
63   AU.addRequired<LiveVariables>();
64   AU.addPreserved<LiveVariables>();
65   AU.addPreservedID(MachineLoopInfoID);
66   AU.addRequiredTransitiveID(MachineDominatorsID);
67   AU.addPreservedID(MachineDominatorsID);
68   AU.addPreserved<SlotIndexes>();
69   AU.addRequiredTransitive<SlotIndexes>();
70   MachineFunctionPass::getAnalysisUsage(AU);
71 }
72
73 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
74   DomTree(0), LRCalc(0) {
75   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
76 }
77
78 LiveIntervals::~LiveIntervals() {
79   delete LRCalc;
80 }
81
82 void LiveIntervals::releaseMemory() {
83   // Free the live intervals themselves.
84   for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
85     delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
86   VirtRegIntervals.clear();
87   RegMaskSlots.clear();
88   RegMaskBits.clear();
89   RegMaskBlocks.clear();
90
91   for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
92     delete RegUnitIntervals[i];
93   RegUnitIntervals.clear();
94
95   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
96   VNInfoAllocator.Reset();
97 }
98
99 /// runOnMachineFunction - Register allocate the whole function
100 ///
101 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
102   MF = &fn;
103   MRI = &MF->getRegInfo();
104   TM = &fn.getTarget();
105   TRI = TM->getRegisterInfo();
106   TII = TM->getInstrInfo();
107   AA = &getAnalysis<AliasAnalysis>();
108   LV = &getAnalysis<LiveVariables>();
109   Indexes = &getAnalysis<SlotIndexes>();
110   DomTree = &getAnalysis<MachineDominatorTree>();
111   if (!LRCalc)
112     LRCalc = new LiveRangeCalc();
113   AllocatableRegs = TRI->getAllocatableSet(fn);
114   ReservedRegs = TRI->getReservedRegs(fn);
115
116   // Allocate space for all virtual registers.
117   VirtRegIntervals.resize(MRI->getNumVirtRegs());
118
119   if (NewLiveIntervals) {
120     // This is the new way of computing live intervals.
121     // It is independent of LiveVariables, and it can run at any time.
122     computeVirtRegs();
123     computeRegMasks();
124   } else {
125     // This is the old way of computing live intervals.
126     // It depends on LiveVariables.
127     computeIntervals();
128   }
129   computeLiveInRegUnits();
130
131   DEBUG(dump());
132   return true;
133 }
134
135 /// print - Implement the dump method.
136 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
137   OS << "********** INTERVALS **********\n";
138
139   // Dump the regunits.
140   for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
141     if (LiveInterval *LI = RegUnitIntervals[i])
142       OS << PrintRegUnit(i, TRI) << " = " << *LI << '\n';
143
144   // Dump the virtregs.
145   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
146     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
147     if (hasInterval(Reg))
148       OS << PrintReg(Reg) << " = " << getInterval(Reg) << '\n';
149   }
150
151   printInstrs(OS);
152 }
153
154 void LiveIntervals::printInstrs(raw_ostream &OS) const {
155   OS << "********** MACHINEINSTRS **********\n";
156   MF->print(OS, Indexes);
157 }
158
159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160 void LiveIntervals::dumpInstrs() const {
161   printInstrs(dbgs());
162 }
163 #endif
164
165 static
166 bool MultipleDefsBySameMI(const MachineInstr &MI, unsigned MOIdx) {
167   unsigned Reg = MI.getOperand(MOIdx).getReg();
168   for (unsigned i = MOIdx+1, e = MI.getNumOperands(); i < e; ++i) {
169     const MachineOperand &MO = MI.getOperand(i);
170     if (!MO.isReg())
171       continue;
172     if (MO.getReg() == Reg && MO.isDef()) {
173       assert(MI.getOperand(MOIdx).getSubReg() != MO.getSubReg() &&
174              MI.getOperand(MOIdx).getSubReg() &&
175              (MO.getSubReg() || MO.isImplicit()));
176       return true;
177     }
178   }
179   return false;
180 }
181
182 /// isPartialRedef - Return true if the specified def at the specific index is
183 /// partially re-defining the specified live interval. A common case of this is
184 /// a definition of the sub-register.
185 bool LiveIntervals::isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
186                                    LiveInterval &interval) {
187   if (!MO.getSubReg() || MO.isEarlyClobber())
188     return false;
189
190   SlotIndex RedefIndex = MIIdx.getRegSlot();
191   const LiveRange *OldLR =
192     interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
193   MachineInstr *DefMI = getInstructionFromIndex(OldLR->valno->def);
194   if (DefMI != 0) {
195     return DefMI->findRegisterDefOperandIdx(interval.reg) != -1;
196   }
197   return false;
198 }
199
200 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
201                                              MachineBasicBlock::iterator mi,
202                                              SlotIndex MIIdx,
203                                              MachineOperand& MO,
204                                              unsigned MOIdx,
205                                              LiveInterval &interval) {
206   DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, TRI));
207
208   // Virtual registers may be defined multiple times (due to phi
209   // elimination and 2-addr elimination).  Much of what we do only has to be
210   // done once for the vreg.  We use an empty interval to detect the first
211   // time we see a vreg.
212   LiveVariables::VarInfo& vi = LV->getVarInfo(interval.reg);
213   if (interval.empty()) {
214     // Get the Idx of the defining instructions.
215     SlotIndex defIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
216
217     // Make sure the first definition is not a partial redefinition.
218     assert(!MO.readsReg() && "First def cannot also read virtual register "
219            "missing <undef> flag?");
220
221     VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
222     assert(ValNo->id == 0 && "First value in interval is not 0?");
223
224     // Loop over all of the blocks that the vreg is defined in.  There are
225     // two cases we have to handle here.  The most common case is a vreg
226     // whose lifetime is contained within a basic block.  In this case there
227     // will be a single kill, in MBB, which comes after the definition.
228     if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
229       // FIXME: what about dead vars?
230       SlotIndex killIdx;
231       if (vi.Kills[0] != mi)
232         killIdx = getInstructionIndex(vi.Kills[0]).getRegSlot();
233       else
234         killIdx = defIndex.getDeadSlot();
235
236       // If the kill happens after the definition, we have an intra-block
237       // live range.
238       if (killIdx > defIndex) {
239         assert(vi.AliveBlocks.empty() &&
240                "Shouldn't be alive across any blocks!");
241         LiveRange LR(defIndex, killIdx, ValNo);
242         interval.addRange(LR);
243         DEBUG(dbgs() << " +" << LR << "\n");
244         return;
245       }
246     }
247
248     // The other case we handle is when a virtual register lives to the end
249     // of the defining block, potentially live across some blocks, then is
250     // live into some number of blocks, but gets killed.  Start by adding a
251     // range that goes from this definition to the end of the defining block.
252     LiveRange NewLR(defIndex, getMBBEndIdx(mbb), ValNo);
253     DEBUG(dbgs() << " +" << NewLR);
254     interval.addRange(NewLR);
255
256     bool PHIJoin = LV->isPHIJoin(interval.reg);
257
258     if (PHIJoin) {
259       // A phi join register is killed at the end of the MBB and revived as a
260       // new valno in the killing blocks.
261       assert(vi.AliveBlocks.empty() && "Phi join can't pass through blocks");
262       DEBUG(dbgs() << " phi-join");
263     } else {
264       // Iterate over all of the blocks that the variable is completely
265       // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
266       // live interval.
267       for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
268                E = vi.AliveBlocks.end(); I != E; ++I) {
269         MachineBasicBlock *aliveBlock = MF->getBlockNumbered(*I);
270         LiveRange LR(getMBBStartIdx(aliveBlock), getMBBEndIdx(aliveBlock),
271                      ValNo);
272         interval.addRange(LR);
273         DEBUG(dbgs() << " +" << LR);
274       }
275     }
276
277     // Finally, this virtual register is live from the start of any killing
278     // block to the 'use' slot of the killing instruction.
279     for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
280       MachineInstr *Kill = vi.Kills[i];
281       SlotIndex Start = getMBBStartIdx(Kill->getParent());
282       SlotIndex killIdx = getInstructionIndex(Kill).getRegSlot();
283
284       // Create interval with one of a NEW value number.  Note that this value
285       // number isn't actually defined by an instruction, weird huh? :)
286       if (PHIJoin) {
287         assert(getInstructionFromIndex(Start) == 0 &&
288                "PHI def index points at actual instruction.");
289         ValNo = interval.getNextValue(Start, VNInfoAllocator);
290       }
291       LiveRange LR(Start, killIdx, ValNo);
292       interval.addRange(LR);
293       DEBUG(dbgs() << " +" << LR);
294     }
295
296   } else {
297     if (MultipleDefsBySameMI(*mi, MOIdx))
298       // Multiple defs of the same virtual register by the same instruction.
299       // e.g. %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
300       // This is likely due to elimination of REG_SEQUENCE instructions. Return
301       // here since there is nothing to do.
302       return;
303
304     // If this is the second time we see a virtual register definition, it
305     // must be due to phi elimination or two addr elimination.  If this is
306     // the result of two address elimination, then the vreg is one of the
307     // def-and-use register operand.
308
309     // It may also be partial redef like this:
310     // 80  %reg1041:6<def> = VSHRNv4i16 %reg1034<kill>, 12, pred:14, pred:%reg0
311     // 120 %reg1041:5<def> = VSHRNv4i16 %reg1039<kill>, 12, pred:14, pred:%reg0
312     bool PartReDef = isPartialRedef(MIIdx, MO, interval);
313     if (PartReDef || mi->isRegTiedToUseOperand(MOIdx)) {
314       // If this is a two-address definition, then we have already processed
315       // the live range.  The only problem is that we didn't realize there
316       // are actually two values in the live interval.  Because of this we
317       // need to take the LiveRegion that defines this register and split it
318       // into two values.
319       SlotIndex RedefIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
320
321       const LiveRange *OldLR =
322         interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
323       VNInfo *OldValNo = OldLR->valno;
324       SlotIndex DefIndex = OldValNo->def.getRegSlot();
325
326       // Delete the previous value, which should be short and continuous,
327       // because the 2-addr copy must be in the same MBB as the redef.
328       interval.removeRange(DefIndex, RedefIndex);
329
330       // The new value number (#1) is defined by the instruction we claimed
331       // defined value #0.
332       VNInfo *ValNo = interval.createValueCopy(OldValNo, VNInfoAllocator);
333
334       // Value#0 is now defined by the 2-addr instruction.
335       OldValNo->def = RedefIndex;
336
337       // Add the new live interval which replaces the range for the input copy.
338       LiveRange LR(DefIndex, RedefIndex, ValNo);
339       DEBUG(dbgs() << " replace range with " << LR);
340       interval.addRange(LR);
341
342       // If this redefinition is dead, we need to add a dummy unit live
343       // range covering the def slot.
344       if (MO.isDead())
345         interval.addRange(LiveRange(RedefIndex, RedefIndex.getDeadSlot(),
346                                     OldValNo));
347
348       DEBUG(dbgs() << " RESULT: " << interval);
349     } else if (LV->isPHIJoin(interval.reg)) {
350       // In the case of PHI elimination, each variable definition is only
351       // live until the end of the block.  We've already taken care of the
352       // rest of the live range.
353
354       SlotIndex defIndex = MIIdx.getRegSlot();
355       if (MO.isEarlyClobber())
356         defIndex = MIIdx.getRegSlot(true);
357
358       VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
359
360       SlotIndex killIndex = getMBBEndIdx(mbb);
361       LiveRange LR(defIndex, killIndex, ValNo);
362       interval.addRange(LR);
363       DEBUG(dbgs() << " phi-join +" << LR);
364     } else {
365       llvm_unreachable("Multiply defined register");
366     }
367   }
368
369   DEBUG(dbgs() << '\n');
370 }
371
372 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
373                                       MachineBasicBlock::iterator MI,
374                                       SlotIndex MIIdx,
375                                       MachineOperand& MO,
376                                       unsigned MOIdx) {
377   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
378     handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
379                              getOrCreateInterval(MO.getReg()));
380 }
381
382 /// computeIntervals - computes the live intervals for virtual
383 /// registers. for some ordering of the machine instructions [1,N] a
384 /// live interval is an interval [i, j) where 1 <= i <= j < N for
385 /// which a variable is live
386 void LiveIntervals::computeIntervals() {
387   DEBUG(dbgs() << "********** COMPUTING LIVE INTERVALS **********\n"
388                << "********** Function: " << MF->getName() << '\n');
389
390   RegMaskBlocks.resize(MF->getNumBlockIDs());
391
392   SmallVector<unsigned, 8> UndefUses;
393   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
394        MBBI != E; ++MBBI) {
395     MachineBasicBlock *MBB = MBBI;
396     RegMaskBlocks[MBB->getNumber()].first = RegMaskSlots.size();
397
398     if (MBB->empty())
399       continue;
400
401     // Track the index of the current machine instr.
402     SlotIndex MIIndex = getMBBStartIdx(MBB);
403     DEBUG(dbgs() << "BB#" << MBB->getNumber()
404           << ":\t\t# derived from " << MBB->getName() << "\n");
405
406     // Skip over empty initial indices.
407     if (getInstructionFromIndex(MIIndex) == 0)
408       MIIndex = Indexes->getNextNonNullIndex(MIIndex);
409
410     for (MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
411          MI != miEnd; ++MI) {
412       DEBUG(dbgs() << MIIndex << "\t" << *MI);
413       if (MI->isDebugValue())
414         continue;
415       assert(Indexes->getInstructionFromIndex(MIIndex) == MI &&
416              "Lost SlotIndex synchronization");
417
418       // Handle defs.
419       for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
420         MachineOperand &MO = MI->getOperand(i);
421
422         // Collect register masks.
423         if (MO.isRegMask()) {
424           RegMaskSlots.push_back(MIIndex.getRegSlot());
425           RegMaskBits.push_back(MO.getRegMask());
426           continue;
427         }
428
429         if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
430           continue;
431
432         // handle register defs - build intervals
433         if (MO.isDef())
434           handleRegisterDef(MBB, MI, MIIndex, MO, i);
435         else if (MO.isUndef())
436           UndefUses.push_back(MO.getReg());
437       }
438
439       // Move to the next instr slot.
440       MIIndex = Indexes->getNextNonNullIndex(MIIndex);
441     }
442
443     // Compute the number of register mask instructions in this block.
444     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
445     RMB.second = RegMaskSlots.size() - RMB.first;
446   }
447
448   // Create empty intervals for registers defined by implicit_def's (except
449   // for those implicit_def that define values which are liveout of their
450   // blocks.
451   for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
452     unsigned UndefReg = UndefUses[i];
453     (void)getOrCreateInterval(UndefReg);
454   }
455 }
456
457 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
458   float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
459   return new LiveInterval(reg, Weight);
460 }
461
462
463 /// computeVirtRegInterval - Compute the live interval of a virtual register,
464 /// based on defs and uses.
465 void LiveIntervals::computeVirtRegInterval(LiveInterval *LI) {
466   assert(LRCalc && "LRCalc not initialized.");
467   assert(LI->empty() && "Should only compute empty intervals.");
468   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
469   LRCalc->createDeadDefs(LI);
470   LRCalc->extendToUses(LI);
471 }
472
473 void LiveIntervals::computeVirtRegs() {
474   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
475     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
476     if (MRI->reg_nodbg_empty(Reg))
477       continue;
478     LiveInterval *LI = createInterval(Reg);
479     VirtRegIntervals[Reg] = LI;
480     computeVirtRegInterval(LI);
481   }
482 }
483
484 void LiveIntervals::computeRegMasks() {
485   RegMaskBlocks.resize(MF->getNumBlockIDs());
486
487   // Find all instructions with regmask operands.
488   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
489        MBBI != E; ++MBBI) {
490     MachineBasicBlock *MBB = MBBI;
491     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
492     RMB.first = RegMaskSlots.size();
493     for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
494          MI != ME; ++MI)
495       for (MIOperands MO(MI); MO.isValid(); ++MO) {
496         if (!MO->isRegMask())
497           continue;
498           RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
499           RegMaskBits.push_back(MO->getRegMask());
500       }
501     // Compute the number of register mask instructions in this block.
502     RMB.second = RegMaskSlots.size() - RMB.first;
503   }
504 }
505
506 //===----------------------------------------------------------------------===//
507 //                           Register Unit Liveness
508 //===----------------------------------------------------------------------===//
509 //
510 // Fixed interference typically comes from ABI boundaries: Function arguments
511 // and return values are passed in fixed registers, and so are exception
512 // pointers entering landing pads. Certain instructions require values to be
513 // present in specific registers. That is also represented through fixed
514 // interference.
515 //
516
517 /// computeRegUnitInterval - Compute the live interval of a register unit, based
518 /// on the uses and defs of aliasing registers.  The interval should be empty,
519 /// or contain only dead phi-defs from ABI blocks.
520 void LiveIntervals::computeRegUnitInterval(LiveInterval *LI) {
521   unsigned Unit = LI->reg;
522
523   assert(LRCalc && "LRCalc not initialized.");
524   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
525
526   // The physregs aliasing Unit are the roots and their super-registers.
527   // Create all values as dead defs before extending to uses. Note that roots
528   // may share super-registers. That's OK because createDeadDefs() is
529   // idempotent. It is very rare for a register unit to have multiple roots, so
530   // uniquing super-registers is probably not worthwhile.
531   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
532     unsigned Root = *Roots;
533     if (!MRI->reg_empty(Root))
534       LRCalc->createDeadDefs(LI, Root);
535     for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
536       if (!MRI->reg_empty(*Supers))
537         LRCalc->createDeadDefs(LI, *Supers);
538     }
539   }
540
541   // Now extend LI to reach all uses.
542   // Ignore uses of reserved registers. We only track defs of those.
543   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
544     unsigned Root = *Roots;
545     if (!isReserved(Root) && !MRI->reg_empty(Root))
546       LRCalc->extendToUses(LI, Root);
547     for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
548       unsigned Reg = *Supers;
549       if (!isReserved(Reg) && !MRI->reg_empty(Reg))
550         LRCalc->extendToUses(LI, Reg);
551     }
552   }
553 }
554
555
556 /// computeLiveInRegUnits - Precompute the live ranges of any register units
557 /// that are live-in to an ABI block somewhere. Register values can appear
558 /// without a corresponding def when entering the entry block or a landing pad.
559 ///
560 void LiveIntervals::computeLiveInRegUnits() {
561   RegUnitIntervals.resize(TRI->getNumRegUnits());
562   DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
563
564   // Keep track of the intervals allocated.
565   SmallVector<LiveInterval*, 8> NewIntvs;
566
567   // Check all basic blocks for live-ins.
568   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
569        MFI != MFE; ++MFI) {
570     const MachineBasicBlock *MBB = MFI;
571
572     // We only care about ABI blocks: Entry + landing pads.
573     if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
574       continue;
575
576     // Create phi-defs at Begin for all live-in registers.
577     SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
578     DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
579     for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
580          LIE = MBB->livein_end(); LII != LIE; ++LII) {
581       for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
582         unsigned Unit = *Units;
583         LiveInterval *Intv = RegUnitIntervals[Unit];
584         if (!Intv) {
585           Intv = RegUnitIntervals[Unit] = new LiveInterval(Unit, HUGE_VALF);
586           NewIntvs.push_back(Intv);
587         }
588         VNInfo *VNI = Intv->createDeadDef(Begin, getVNInfoAllocator());
589         (void)VNI;
590         DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
591       }
592     }
593     DEBUG(dbgs() << '\n');
594   }
595   DEBUG(dbgs() << "Created " << NewIntvs.size() << " new intervals.\n");
596
597   // Compute the 'normal' part of the intervals.
598   for (unsigned i = 0, e = NewIntvs.size(); i != e; ++i)
599     computeRegUnitInterval(NewIntvs[i]);
600 }
601
602
603 /// shrinkToUses - After removing some uses of a register, shrink its live
604 /// range to just the remaining uses. This method does not compute reaching
605 /// defs for new uses, and it doesn't remove dead defs.
606 bool LiveIntervals::shrinkToUses(LiveInterval *li,
607                                  SmallVectorImpl<MachineInstr*> *dead) {
608   DEBUG(dbgs() << "Shrink: " << *li << '\n');
609   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
610          && "Can only shrink virtual registers");
611   // Find all the values used, including PHI kills.
612   SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
613
614   // Blocks that have already been added to WorkList as live-out.
615   SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
616
617   // Visit all instructions reading li->reg.
618   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(li->reg);
619        MachineInstr *UseMI = I.skipInstruction();) {
620     if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
621       continue;
622     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
623     LiveRangeQuery LRQ(*li, Idx);
624     VNInfo *VNI = LRQ.valueIn();
625     if (!VNI) {
626       // This shouldn't happen: readsVirtualRegister returns true, but there is
627       // no live value. It is likely caused by a target getting <undef> flags
628       // wrong.
629       DEBUG(dbgs() << Idx << '\t' << *UseMI
630                    << "Warning: Instr claims to read non-existent value in "
631                     << *li << '\n');
632       continue;
633     }
634     // Special case: An early-clobber tied operand reads and writes the
635     // register one slot early.
636     if (VNInfo *DefVNI = LRQ.valueDefined())
637       Idx = DefVNI->def;
638
639     WorkList.push_back(std::make_pair(Idx, VNI));
640   }
641
642   // Create a new live interval with only minimal live segments per def.
643   LiveInterval NewLI(li->reg, 0);
644   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
645        I != E; ++I) {
646     VNInfo *VNI = *I;
647     if (VNI->isUnused())
648       continue;
649     NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
650   }
651
652   // Keep track of the PHIs that are in use.
653   SmallPtrSet<VNInfo*, 8> UsedPHIs;
654
655   // Extend intervals to reach all uses in WorkList.
656   while (!WorkList.empty()) {
657     SlotIndex Idx = WorkList.back().first;
658     VNInfo *VNI = WorkList.back().second;
659     WorkList.pop_back();
660     const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
661     SlotIndex BlockStart = getMBBStartIdx(MBB);
662
663     // Extend the live range for VNI to be live at Idx.
664     if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
665       (void)ExtVNI;
666       assert(ExtVNI == VNI && "Unexpected existing value number");
667       // Is this a PHIDef we haven't seen before?
668       if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
669         continue;
670       // The PHI is live, make sure the predecessors are live-out.
671       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
672            PE = MBB->pred_end(); PI != PE; ++PI) {
673         if (!LiveOut.insert(*PI))
674           continue;
675         SlotIndex Stop = getMBBEndIdx(*PI);
676         // A predecessor is not required to have a live-out value for a PHI.
677         if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
678           WorkList.push_back(std::make_pair(Stop, PVNI));
679       }
680       continue;
681     }
682
683     // VNI is live-in to MBB.
684     DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
685     NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
686
687     // Make sure VNI is live-out from the predecessors.
688     for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
689          PE = MBB->pred_end(); PI != PE; ++PI) {
690       if (!LiveOut.insert(*PI))
691         continue;
692       SlotIndex Stop = getMBBEndIdx(*PI);
693       assert(li->getVNInfoBefore(Stop) == VNI &&
694              "Wrong value out of predecessor");
695       WorkList.push_back(std::make_pair(Stop, VNI));
696     }
697   }
698
699   // Handle dead values.
700   bool CanSeparate = false;
701   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
702        I != E; ++I) {
703     VNInfo *VNI = *I;
704     if (VNI->isUnused())
705       continue;
706     LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
707     assert(LII != NewLI.end() && "Missing live range for PHI");
708     if (LII->end != VNI->def.getDeadSlot())
709       continue;
710     if (VNI->isPHIDef()) {
711       // This is a dead PHI. Remove it.
712       VNI->markUnused();
713       NewLI.removeRange(*LII);
714       DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
715       CanSeparate = true;
716     } else {
717       // This is a dead def. Make sure the instruction knows.
718       MachineInstr *MI = getInstructionFromIndex(VNI->def);
719       assert(MI && "No instruction defining live value");
720       MI->addRegisterDead(li->reg, TRI);
721       if (dead && MI->allDefsAreDead()) {
722         DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
723         dead->push_back(MI);
724       }
725     }
726   }
727
728   // Move the trimmed ranges back.
729   li->ranges.swap(NewLI.ranges);
730   DEBUG(dbgs() << "Shrunk: " << *li << '\n');
731   return CanSeparate;
732 }
733
734 void LiveIntervals::extendToIndices(LiveInterval *LI,
735                                     ArrayRef<SlotIndex> Indices) {
736   assert(LRCalc && "LRCalc not initialized.");
737   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
738   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
739     LRCalc->extend(LI, Indices[i]);
740 }
741
742 void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
743                                SmallVectorImpl<SlotIndex> *EndPoints) {
744   LiveRangeQuery LRQ(*LI, Kill);
745   VNInfo *VNI = LRQ.valueOut();
746   if (!VNI)
747     return;
748
749   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
750   SlotIndex MBBStart, MBBEnd;
751   tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
752
753   // If VNI isn't live out from KillMBB, the value is trivially pruned.
754   if (LRQ.endPoint() < MBBEnd) {
755     LI->removeRange(Kill, LRQ.endPoint());
756     if (EndPoints) EndPoints->push_back(LRQ.endPoint());
757     return;
758   }
759
760   // VNI is live out of KillMBB.
761   LI->removeRange(Kill, MBBEnd);
762   if (EndPoints) EndPoints->push_back(MBBEnd);
763
764   // Find all blocks that are reachable from MBB without leaving VNI's live
765   // range.
766   for (df_iterator<MachineBasicBlock*>
767        I = df_begin(KillMBB), E = df_end(KillMBB); I != E;) {
768     MachineBasicBlock *MBB = *I;
769     // KillMBB itself was already handled.
770     if (MBB == KillMBB) {
771       ++I;
772       continue;
773     }
774
775     // Check if VNI is live in to MBB.
776     tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
777     LiveRangeQuery LRQ(*LI, MBBStart);
778     if (LRQ.valueIn() != VNI) {
779       // This block isn't part of the VNI live range. Prune the search.
780       I.skipChildren();
781       continue;
782     }
783
784     // Prune the search if VNI is killed in MBB.
785     if (LRQ.endPoint() < MBBEnd) {
786       LI->removeRange(MBBStart, LRQ.endPoint());
787       if (EndPoints) EndPoints->push_back(LRQ.endPoint());
788       I.skipChildren();
789       continue;
790     }
791
792     // VNI is live through MBB.
793     LI->removeRange(MBBStart, MBBEnd);
794     if (EndPoints) EndPoints->push_back(MBBEnd);
795     ++I;
796   }
797 }
798
799 //===----------------------------------------------------------------------===//
800 // Register allocator hooks.
801 //
802
803 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
804   // Keep track of regunit ranges.
805   SmallVector<std::pair<LiveInterval*, LiveInterval::iterator>, 8> RU;
806
807   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
808     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
809     if (MRI->reg_nodbg_empty(Reg))
810       continue;
811     LiveInterval *LI = &getInterval(Reg);
812     if (LI->empty())
813       continue;
814
815     // Find the regunit intervals for the assigned register. They may overlap
816     // the virtual register live range, cancelling any kills.
817     RU.clear();
818     for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
819          ++Units) {
820       LiveInterval *RUInt = &getRegUnit(*Units);
821       if (RUInt->empty())
822         continue;
823       RU.push_back(std::make_pair(RUInt, RUInt->find(LI->begin()->end)));
824     }
825
826     // Every instruction that kills Reg corresponds to a live range end point.
827     for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
828          ++RI) {
829       // A block index indicates an MBB edge.
830       if (RI->end.isBlock())
831         continue;
832       MachineInstr *MI = getInstructionFromIndex(RI->end);
833       if (!MI)
834         continue;
835
836       // Check if any of the reguints are live beyond the end of RI. That could
837       // happen when a physreg is defined as a copy of a virtreg:
838       //
839       //   %EAX = COPY %vreg5
840       //   FOO %vreg5         <--- MI, cancel kill because %EAX is live.
841       //   BAR %EAX<kill>
842       //
843       // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
844       bool CancelKill = false;
845       for (unsigned u = 0, e = RU.size(); u != e; ++u) {
846         LiveInterval *RInt = RU[u].first;
847         LiveInterval::iterator &I = RU[u].second;
848         if (I == RInt->end())
849           continue;
850         I = RInt->advanceTo(I, RI->end);
851         if (I == RInt->end() || I->start >= RI->end)
852           continue;
853         // I is overlapping RI.
854         CancelKill = true;
855         break;
856       }
857       if (CancelKill)
858         MI->clearRegisterKills(Reg, NULL);
859       else
860         MI->addRegisterKilled(Reg, NULL);
861     }
862   }
863 }
864
865 MachineBasicBlock*
866 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
867   // A local live range must be fully contained inside the block, meaning it is
868   // defined and killed at instructions, not at block boundaries. It is not
869   // live in or or out of any block.
870   //
871   // It is technically possible to have a PHI-defined live range identical to a
872   // single block, but we are going to return false in that case.
873
874   SlotIndex Start = LI.beginIndex();
875   if (Start.isBlock())
876     return NULL;
877
878   SlotIndex Stop = LI.endIndex();
879   if (Stop.isBlock())
880     return NULL;
881
882   // getMBBFromIndex doesn't need to search the MBB table when both indexes
883   // belong to proper instructions.
884   MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
885   MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
886   return MBB1 == MBB2 ? MBB1 : NULL;
887 }
888
889 bool
890 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
891   for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
892        I != E; ++I) {
893     const VNInfo *PHI = *I;
894     if (PHI->isUnused() || !PHI->isPHIDef())
895       continue;
896     const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
897     // Conservatively return true instead of scanning huge predecessor lists.
898     if (PHIMBB->pred_size() > 100)
899       return true;
900     for (MachineBasicBlock::const_pred_iterator
901          PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
902       if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
903         return true;
904   }
905   return false;
906 }
907
908 float
909 LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
910   // Limit the loop depth ridiculousness.
911   if (loopDepth > 200)
912     loopDepth = 200;
913
914   // The loop depth is used to roughly estimate the number of times the
915   // instruction is executed. Something like 10^d is simple, but will quickly
916   // overflow a float. This expression behaves like 10^d for small d, but is
917   // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
918   // headroom before overflow.
919   // By the way, powf() might be unavailable here. For consistency,
920   // We may take pow(double,double).
921   float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
922
923   return (isDef + isUse) * lc;
924 }
925
926 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
927                                                   MachineInstr* startInst) {
928   LiveInterval& Interval = getOrCreateInterval(reg);
929   VNInfo* VN = Interval.getNextValue(
930     SlotIndex(getInstructionIndex(startInst).getRegSlot()),
931     getVNInfoAllocator());
932   LiveRange LR(
933      SlotIndex(getInstructionIndex(startInst).getRegSlot()),
934      getMBBEndIdx(startInst->getParent()), VN);
935   Interval.addRange(LR);
936
937   return LR;
938 }
939
940
941 //===----------------------------------------------------------------------===//
942 //                          Register mask functions
943 //===----------------------------------------------------------------------===//
944
945 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
946                                              BitVector &UsableRegs) {
947   if (LI.empty())
948     return false;
949   LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
950
951   // Use a smaller arrays for local live ranges.
952   ArrayRef<SlotIndex> Slots;
953   ArrayRef<const uint32_t*> Bits;
954   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
955     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
956     Bits = getRegMaskBitsInBlock(MBB->getNumber());
957   } else {
958     Slots = getRegMaskSlots();
959     Bits = getRegMaskBits();
960   }
961
962   // We are going to enumerate all the register mask slots contained in LI.
963   // Start with a binary search of RegMaskSlots to find a starting point.
964   ArrayRef<SlotIndex>::iterator SlotI =
965     std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
966   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
967
968   // No slots in range, LI begins after the last call.
969   if (SlotI == SlotE)
970     return false;
971
972   bool Found = false;
973   for (;;) {
974     assert(*SlotI >= LiveI->start);
975     // Loop over all slots overlapping this segment.
976     while (*SlotI < LiveI->end) {
977       // *SlotI overlaps LI. Collect mask bits.
978       if (!Found) {
979         // This is the first overlap. Initialize UsableRegs to all ones.
980         UsableRegs.clear();
981         UsableRegs.resize(TRI->getNumRegs(), true);
982         Found = true;
983       }
984       // Remove usable registers clobbered by this mask.
985       UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
986       if (++SlotI == SlotE)
987         return Found;
988     }
989     // *SlotI is beyond the current LI segment.
990     LiveI = LI.advanceTo(LiveI, *SlotI);
991     if (LiveI == LiveE)
992       return Found;
993     // Advance SlotI until it overlaps.
994     while (*SlotI < LiveI->start)
995       if (++SlotI == SlotE)
996         return Found;
997   }
998 }
999
1000 //===----------------------------------------------------------------------===//
1001 //                         IntervalUpdate class.
1002 //===----------------------------------------------------------------------===//
1003
1004 // HMEditor is a toolkit used by handleMove to trim or extend live intervals.
1005 class LiveIntervals::HMEditor {
1006 private:
1007   LiveIntervals& LIS;
1008   const MachineRegisterInfo& MRI;
1009   const TargetRegisterInfo& TRI;
1010   SlotIndex NewIdx;
1011
1012   typedef std::pair<LiveInterval*, LiveRange*> IntRangePair;
1013   typedef DenseSet<IntRangePair> RangeSet;
1014
1015   struct RegRanges {
1016     LiveRange* Use;
1017     LiveRange* EC;
1018     LiveRange* Dead;
1019     LiveRange* Def;
1020     RegRanges() : Use(0), EC(0), Dead(0), Def(0) {}
1021   };
1022   typedef DenseMap<unsigned, RegRanges> BundleRanges;
1023
1024 public:
1025   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
1026            const TargetRegisterInfo& TRI, SlotIndex NewIdx)
1027     : LIS(LIS), MRI(MRI), TRI(TRI), NewIdx(NewIdx) {}
1028
1029   // Update intervals for all operands of MI from OldIdx to NewIdx.
1030   // This assumes that MI used to be at OldIdx, and now resides at
1031   // NewIdx.
1032   void moveAllRangesFrom(MachineInstr* MI, SlotIndex OldIdx) {
1033     assert(NewIdx != OldIdx && "No-op move? That's a bit strange.");
1034
1035     // Collect the operands.
1036     RangeSet Entering, Internal, Exiting;
1037     bool hasRegMaskOp = false;
1038     collectRanges(MI, Entering, Internal, Exiting, hasRegMaskOp, OldIdx);
1039
1040     // To keep the LiveRanges valid within an interval, move the ranges closest
1041     // to the destination first. This prevents ranges from overlapping, to that
1042     // APIs like removeRange still work.
1043     if (NewIdx < OldIdx) {
1044       moveAllEnteringFrom(OldIdx, Entering);
1045       moveAllInternalFrom(OldIdx, Internal);
1046       moveAllExitingFrom(OldIdx, Exiting);
1047     }
1048     else {
1049       moveAllExitingFrom(OldIdx, Exiting);
1050       moveAllInternalFrom(OldIdx, Internal);
1051       moveAllEnteringFrom(OldIdx, Entering);
1052     }
1053
1054     if (hasRegMaskOp)
1055       updateRegMaskSlots(OldIdx);
1056
1057 #ifndef NDEBUG
1058     LIValidator validator;
1059     validator = std::for_each(Entering.begin(), Entering.end(), validator);
1060     validator = std::for_each(Internal.begin(), Internal.end(), validator);
1061     validator = std::for_each(Exiting.begin(), Exiting.end(), validator);
1062     assert(validator.rangesOk() && "moveAllOperandsFrom broke liveness.");
1063 #endif
1064
1065   }
1066
1067   // Update intervals for all operands of MI to refer to BundleStart's
1068   // SlotIndex.
1069   void moveAllRangesInto(MachineInstr* MI, MachineInstr* BundleStart) {
1070     if (MI == BundleStart)
1071       return; // Bundling instr with itself - nothing to do.
1072
1073     SlotIndex OldIdx = LIS.getSlotIndexes()->getInstructionIndex(MI);
1074     assert(LIS.getSlotIndexes()->getInstructionFromIndex(OldIdx) == MI &&
1075            "SlotIndex <-> Instruction mapping broken for MI");
1076
1077     // Collect all ranges already in the bundle.
1078     MachineBasicBlock::instr_iterator BII(BundleStart);
1079     RangeSet Entering, Internal, Exiting;
1080     bool hasRegMaskOp = false;
1081     collectRanges(BII, Entering, Internal, Exiting, hasRegMaskOp, NewIdx);
1082     assert(!hasRegMaskOp && "Can't have RegMask operand in bundle.");
1083     for (++BII; &*BII == MI || BII->isInsideBundle(); ++BII) {
1084       if (&*BII == MI)
1085         continue;
1086       collectRanges(BII, Entering, Internal, Exiting, hasRegMaskOp, NewIdx);
1087       assert(!hasRegMaskOp && "Can't have RegMask operand in bundle.");
1088     }
1089
1090     BundleRanges BR = createBundleRanges(Entering, Internal, Exiting);
1091
1092     Entering.clear();
1093     Internal.clear();
1094     Exiting.clear();
1095     collectRanges(MI, Entering, Internal, Exiting, hasRegMaskOp, OldIdx);
1096     assert(!hasRegMaskOp && "Can't have RegMask operand in bundle.");
1097
1098     DEBUG(dbgs() << "Entering: " << Entering.size() << "\n");
1099     DEBUG(dbgs() << "Internal: " << Internal.size() << "\n");
1100     DEBUG(dbgs() << "Exiting: " << Exiting.size() << "\n");
1101
1102     moveAllEnteringFromInto(OldIdx, Entering, BR);
1103     moveAllInternalFromInto(OldIdx, Internal, BR);
1104     moveAllExitingFromInto(OldIdx, Exiting, BR);
1105
1106
1107 #ifndef NDEBUG
1108     LIValidator validator;
1109     validator = std::for_each(Entering.begin(), Entering.end(), validator);
1110     validator = std::for_each(Internal.begin(), Internal.end(), validator);
1111     validator = std::for_each(Exiting.begin(), Exiting.end(), validator);
1112     assert(validator.rangesOk() && "moveAllOperandsInto broke liveness.");
1113 #endif
1114   }
1115
1116 private:
1117
1118 #ifndef NDEBUG
1119   class LIValidator {
1120   private:
1121     DenseSet<const LiveInterval*> Checked, Bogus;
1122   public:
1123     void operator()(const IntRangePair& P) {
1124       const LiveInterval* LI = P.first;
1125       if (Checked.count(LI))
1126         return;
1127       Checked.insert(LI);
1128       if (LI->empty())
1129         return;
1130       SlotIndex LastEnd = LI->begin()->start;
1131       for (LiveInterval::const_iterator LRI = LI->begin(), LRE = LI->end();
1132            LRI != LRE; ++LRI) {
1133         const LiveRange& LR = *LRI;
1134         if (LastEnd > LR.start || LR.start >= LR.end)
1135           Bogus.insert(LI);
1136         LastEnd = LR.end;
1137       }
1138     }
1139
1140     bool rangesOk() const {
1141       return Bogus.empty();
1142     }
1143   };
1144 #endif
1145
1146   // Collect IntRangePairs for all operands of MI that may need fixing.
1147   // Treat's MI's index as OldIdx (regardless of what it is in SlotIndexes'
1148   // maps).
1149   void collectRanges(MachineInstr* MI, RangeSet& Entering, RangeSet& Internal,
1150                      RangeSet& Exiting, bool& hasRegMaskOp, SlotIndex OldIdx) {
1151     hasRegMaskOp = false;
1152     for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
1153                                     MOE = MI->operands_end();
1154          MOI != MOE; ++MOI) {
1155       const MachineOperand& MO = *MOI;
1156
1157       if (MO.isRegMask()) {
1158         hasRegMaskOp = true;
1159         continue;
1160       }
1161
1162       if (!MO.isReg() || MO.getReg() == 0)
1163         continue;
1164
1165       unsigned Reg = MO.getReg();
1166
1167       // TODO: Currently we're skipping uses that are reserved or have no
1168       // interval, but we're not updating their kills. This should be
1169       // fixed.
1170       if (TargetRegisterInfo::isPhysicalRegister(Reg) && LIS.isReserved(Reg))
1171         continue;
1172
1173       // Collect ranges for register units. These live ranges are computed on
1174       // demand, so just skip any that haven't been computed yet.
1175       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1176         for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
1177           if (LiveInterval *LI = LIS.getCachedRegUnit(*Units))
1178             collectRanges(MO, LI, Entering, Internal, Exiting, OldIdx);
1179       } else {
1180         // Collect ranges for individual virtual registers.
1181         collectRanges(MO, &LIS.getInterval(Reg),
1182                       Entering, Internal, Exiting, OldIdx);
1183       }
1184     }
1185   }
1186
1187   void collectRanges(const MachineOperand &MO, LiveInterval *LI,
1188                      RangeSet &Entering, RangeSet &Internal, RangeSet &Exiting,
1189                      SlotIndex OldIdx) {
1190     if (MO.readsReg()) {
1191       LiveRange* LR = LI->getLiveRangeContaining(OldIdx);
1192       if (LR != 0)
1193         Entering.insert(std::make_pair(LI, LR));
1194     }
1195     if (MO.isDef()) {
1196       LiveRange* LR = LI->getLiveRangeContaining(OldIdx.getRegSlot());
1197       assert(LR != 0 && "No live range for def?");
1198       if (LR->end > OldIdx.getDeadSlot())
1199         Exiting.insert(std::make_pair(LI, LR));
1200       else
1201         Internal.insert(std::make_pair(LI, LR));
1202     }
1203   }
1204
1205   BundleRanges createBundleRanges(RangeSet& Entering,
1206                                   RangeSet& Internal,
1207                                   RangeSet& Exiting) {
1208     BundleRanges BR;
1209
1210     for (RangeSet::iterator EI = Entering.begin(), EE = Entering.end();
1211          EI != EE; ++EI) {
1212       LiveInterval* LI = EI->first;
1213       LiveRange* LR = EI->second;
1214       BR[LI->reg].Use = LR;
1215     }
1216
1217     for (RangeSet::iterator II = Internal.begin(), IE = Internal.end();
1218          II != IE; ++II) {
1219       LiveInterval* LI = II->first;
1220       LiveRange* LR = II->second;
1221       if (LR->end.isDead()) {
1222         BR[LI->reg].Dead = LR;
1223       } else {
1224         BR[LI->reg].EC = LR;
1225       }
1226     }
1227
1228     for (RangeSet::iterator EI = Exiting.begin(), EE = Exiting.end();
1229          EI != EE; ++EI) {
1230       LiveInterval* LI = EI->first;
1231       LiveRange* LR = EI->second;
1232       BR[LI->reg].Def = LR;
1233     }
1234
1235     return BR;
1236   }
1237
1238   void moveKillFlags(unsigned reg, SlotIndex OldIdx, SlotIndex newKillIdx) {
1239     MachineInstr* OldKillMI = LIS.getInstructionFromIndex(OldIdx);
1240     if (!OldKillMI->killsRegister(reg))
1241       return; // Bail out if we don't have kill flags on the old register.
1242     MachineInstr* NewKillMI = LIS.getInstructionFromIndex(newKillIdx);
1243     assert(OldKillMI->killsRegister(reg) && "Old 'kill' instr isn't a kill.");
1244     assert(!NewKillMI->killsRegister(reg) &&
1245            "New kill instr is already a kill.");
1246     OldKillMI->clearRegisterKills(reg, &TRI);
1247     NewKillMI->addRegisterKilled(reg, &TRI);
1248   }
1249
1250   void updateRegMaskSlots(SlotIndex OldIdx) {
1251     SmallVectorImpl<SlotIndex>::iterator RI =
1252       std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
1253                        OldIdx);
1254     assert(*RI == OldIdx && "No RegMask at OldIdx.");
1255     *RI = NewIdx;
1256     assert(*prior(RI) < *RI && *RI < *next(RI) &&
1257            "RegSlots out of order. Did you move one call across another?");
1258   }
1259
1260   // Return the last use of reg between NewIdx and OldIdx.
1261   SlotIndex findLastUseBefore(unsigned Reg, SlotIndex OldIdx) {
1262     SlotIndex LastUse = NewIdx;
1263
1264     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1265       for (MachineRegisterInfo::use_nodbg_iterator
1266              UI = MRI.use_nodbg_begin(Reg),
1267              UE = MRI.use_nodbg_end();
1268            UI != UE; UI.skipInstruction()) {
1269         const MachineInstr* MI = &*UI;
1270         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1271         if (InstSlot > LastUse && InstSlot < OldIdx)
1272           LastUse = InstSlot;
1273       }
1274     } else {
1275       MachineInstr* MI = LIS.getSlotIndexes()->getInstructionFromIndex(NewIdx);
1276       MachineBasicBlock::iterator MII(MI);
1277       ++MII;
1278       MachineBasicBlock* MBB = MI->getParent();
1279       for (; MII != MBB->end() && LIS.getInstructionIndex(MII) < OldIdx; ++MII){
1280         for (MachineInstr::mop_iterator MOI = MII->operands_begin(),
1281                                         MOE = MII->operands_end();
1282              MOI != MOE; ++MOI) {
1283           const MachineOperand& mop = *MOI;
1284           if (!mop.isReg() || mop.getReg() == 0 ||
1285               TargetRegisterInfo::isVirtualRegister(mop.getReg()))
1286             continue;
1287
1288           if (TRI.hasRegUnit(mop.getReg(), Reg))
1289             LastUse = LIS.getInstructionIndex(MII);
1290         }
1291       }
1292     }
1293     return LastUse;
1294   }
1295
1296   void moveEnteringUpFrom(SlotIndex OldIdx, IntRangePair& P) {
1297     LiveInterval* LI = P.first;
1298     LiveRange* LR = P.second;
1299     bool LiveThrough = LR->end > OldIdx.getRegSlot();
1300     if (LiveThrough)
1301       return;
1302     SlotIndex LastUse = findLastUseBefore(LI->reg, OldIdx);
1303     if (LastUse != NewIdx)
1304       moveKillFlags(LI->reg, NewIdx, LastUse);
1305     LR->end = LastUse.getRegSlot(LR->end.isEarlyClobber());
1306   }
1307
1308   void moveEnteringDownFrom(SlotIndex OldIdx, IntRangePair& P) {
1309     LiveInterval* LI = P.first;
1310     LiveRange* LR = P.second;
1311     // Extend the LiveRange if NewIdx is past the end.
1312     if (NewIdx > LR->end) {
1313       // Move kill flags if OldIdx was not originally the end
1314       // (otherwise LR->end points to an invalid slot).
1315       if (LR->end.getRegSlot() != OldIdx.getRegSlot()) {
1316         assert(LR->end > OldIdx && "LiveRange does not cover original slot");
1317         moveKillFlags(LI->reg, LR->end, NewIdx);
1318       }
1319       LR->end = NewIdx.getRegSlot(LR->end.isEarlyClobber());
1320     }
1321   }
1322
1323   void moveAllEnteringFrom(SlotIndex OldIdx, RangeSet& Entering) {
1324     bool GoingUp = NewIdx < OldIdx;
1325
1326     if (GoingUp) {
1327       for (RangeSet::iterator EI = Entering.begin(), EE = Entering.end();
1328            EI != EE; ++EI)
1329         moveEnteringUpFrom(OldIdx, *EI);
1330     } else {
1331       for (RangeSet::iterator EI = Entering.begin(), EE = Entering.end();
1332            EI != EE; ++EI)
1333         moveEnteringDownFrom(OldIdx, *EI);
1334     }
1335   }
1336
1337   void moveInternalFrom(SlotIndex OldIdx, IntRangePair& P) {
1338     LiveInterval* LI = P.first;
1339     LiveRange* LR = P.second;
1340     assert(OldIdx < LR->start && LR->start < OldIdx.getDeadSlot() &&
1341            LR->end <= OldIdx.getDeadSlot() &&
1342            "Range should be internal to OldIdx.");
1343     LiveRange Tmp(*LR);
1344     Tmp.start = NewIdx.getRegSlot(LR->start.isEarlyClobber());
1345     Tmp.valno->def = Tmp.start;
1346     Tmp.end = LR->end.isDead() ? NewIdx.getDeadSlot() : NewIdx.getRegSlot();
1347     LI->removeRange(*LR);
1348     LI->addRange(Tmp);
1349   }
1350
1351   void moveAllInternalFrom(SlotIndex OldIdx, RangeSet& Internal) {
1352     for (RangeSet::iterator II = Internal.begin(), IE = Internal.end();
1353          II != IE; ++II)
1354       moveInternalFrom(OldIdx, *II);
1355   }
1356
1357   void moveExitingFrom(SlotIndex OldIdx, IntRangePair& P) {
1358     LiveRange* LR = P.second;
1359     assert(OldIdx < LR->start && LR->start < OldIdx.getDeadSlot() &&
1360            "Range should start in OldIdx.");
1361     assert(LR->end > OldIdx.getDeadSlot() && "Range should exit OldIdx.");
1362     SlotIndex NewStart = NewIdx.getRegSlot(LR->start.isEarlyClobber());
1363     LR->start = NewStart;
1364     LR->valno->def = NewStart;
1365   }
1366
1367   void moveAllExitingFrom(SlotIndex OldIdx, RangeSet& Exiting) {
1368     for (RangeSet::iterator EI = Exiting.begin(), EE = Exiting.end();
1369          EI != EE; ++EI)
1370       moveExitingFrom(OldIdx, *EI);
1371   }
1372
1373   void moveEnteringUpFromInto(SlotIndex OldIdx, IntRangePair& P,
1374                               BundleRanges& BR) {
1375     LiveInterval* LI = P.first;
1376     LiveRange* LR = P.second;
1377     bool LiveThrough = LR->end > OldIdx.getRegSlot();
1378     if (LiveThrough) {
1379       assert((LR->start < NewIdx || BR[LI->reg].Def == LR) &&
1380              "Def in bundle should be def range.");
1381       assert((BR[LI->reg].Use == 0 || BR[LI->reg].Use == LR) &&
1382              "If bundle has use for this reg it should be LR.");
1383       BR[LI->reg].Use = LR;
1384       return;
1385     }
1386
1387     SlotIndex LastUse = findLastUseBefore(LI->reg, OldIdx);
1388     moveKillFlags(LI->reg, OldIdx, LastUse);
1389
1390     if (LR->start < NewIdx) {
1391       // Becoming a new entering range.
1392       assert(BR[LI->reg].Dead == 0 && BR[LI->reg].Def == 0 &&
1393              "Bundle shouldn't be re-defining reg mid-range.");
1394       assert((BR[LI->reg].Use == 0 || BR[LI->reg].Use == LR) &&
1395              "Bundle shouldn't have different use range for same reg.");
1396       LR->end = LastUse.getRegSlot();
1397       BR[LI->reg].Use = LR;
1398     } else {
1399       // Becoming a new Dead-def.
1400       assert(LR->start == NewIdx.getRegSlot(LR->start.isEarlyClobber()) &&
1401              "Live range starting at unexpected slot.");
1402       assert(BR[LI->reg].Def == LR && "Reg should have def range.");
1403       assert(BR[LI->reg].Dead == 0 &&
1404                "Can't have def and dead def of same reg in a bundle.");
1405       LR->end = LastUse.getDeadSlot();
1406       BR[LI->reg].Dead = BR[LI->reg].Def;
1407       BR[LI->reg].Def = 0;
1408     }
1409   }
1410
1411   void moveEnteringDownFromInto(SlotIndex OldIdx, IntRangePair& P,
1412                                 BundleRanges& BR) {
1413     LiveInterval* LI = P.first;
1414     LiveRange* LR = P.second;
1415     if (NewIdx > LR->end) {
1416       // Range extended to bundle. Add to bundle uses.
1417       // Note: Currently adds kill flags to bundle start.
1418       assert(BR[LI->reg].Use == 0 &&
1419              "Bundle already has use range for reg.");
1420       moveKillFlags(LI->reg, LR->end, NewIdx);
1421       LR->end = NewIdx.getRegSlot();
1422       BR[LI->reg].Use = LR;
1423     } else {
1424       assert(BR[LI->reg].Use != 0 &&
1425              "Bundle should already have a use range for reg.");
1426     }
1427   }
1428
1429   void moveAllEnteringFromInto(SlotIndex OldIdx, RangeSet& Entering,
1430                                BundleRanges& BR) {
1431     bool GoingUp = NewIdx < OldIdx;
1432
1433     if (GoingUp) {
1434       for (RangeSet::iterator EI = Entering.begin(), EE = Entering.end();
1435            EI != EE; ++EI)
1436         moveEnteringUpFromInto(OldIdx, *EI, BR);
1437     } else {
1438       for (RangeSet::iterator EI = Entering.begin(), EE = Entering.end();
1439            EI != EE; ++EI)
1440         moveEnteringDownFromInto(OldIdx, *EI, BR);
1441     }
1442   }
1443
1444   void moveInternalFromInto(SlotIndex OldIdx, IntRangePair& P,
1445                             BundleRanges& BR) {
1446     // TODO: Sane rules for moving ranges into bundles.
1447   }
1448
1449   void moveAllInternalFromInto(SlotIndex OldIdx, RangeSet& Internal,
1450                                BundleRanges& BR) {
1451     for (RangeSet::iterator II = Internal.begin(), IE = Internal.end();
1452          II != IE; ++II)
1453       moveInternalFromInto(OldIdx, *II, BR);
1454   }
1455
1456   void moveExitingFromInto(SlotIndex OldIdx, IntRangePair& P,
1457                            BundleRanges& BR) {
1458     LiveInterval* LI = P.first;
1459     LiveRange* LR = P.second;
1460
1461     assert(LR->start.isRegister() &&
1462            "Don't know how to merge exiting ECs into bundles yet.");
1463
1464     if (LR->end > NewIdx.getDeadSlot()) {
1465       // This range is becoming an exiting range on the bundle.
1466       // If there was an old dead-def of this reg, delete it.
1467       if (BR[LI->reg].Dead != 0) {
1468         LI->removeRange(*BR[LI->reg].Dead);
1469         BR[LI->reg].Dead = 0;
1470       }
1471       assert(BR[LI->reg].Def == 0 &&
1472              "Can't have two defs for the same variable exiting a bundle.");
1473       LR->start = NewIdx.getRegSlot();
1474       LR->valno->def = LR->start;
1475       BR[LI->reg].Def = LR;
1476     } else {
1477       // This range is becoming internal to the bundle.
1478       assert(LR->end == NewIdx.getRegSlot() &&
1479              "Can't bundle def whose kill is before the bundle");
1480       if (BR[LI->reg].Dead || BR[LI->reg].Def) {
1481         // Already have a def for this. Just delete range.
1482         LI->removeRange(*LR);
1483       } else {
1484         // Make range dead, record.
1485         LR->end = NewIdx.getDeadSlot();
1486         BR[LI->reg].Dead = LR;
1487         assert(BR[LI->reg].Use == LR &&
1488                "Range becoming dead should currently be use.");
1489       }
1490       // In both cases the range is no longer a use on the bundle.
1491       BR[LI->reg].Use = 0;
1492     }
1493   }
1494
1495   void moveAllExitingFromInto(SlotIndex OldIdx, RangeSet& Exiting,
1496                               BundleRanges& BR) {
1497     for (RangeSet::iterator EI = Exiting.begin(), EE = Exiting.end();
1498          EI != EE; ++EI)
1499       moveExitingFromInto(OldIdx, *EI, BR);
1500   }
1501
1502 };
1503
1504 void LiveIntervals::handleMove(MachineInstr* MI) {
1505   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1506   Indexes->removeMachineInstrFromMaps(MI);
1507   SlotIndex NewIndex = MI->isInsideBundle() ?
1508                         Indexes->getInstructionIndex(MI) :
1509                         Indexes->insertMachineInstrInMaps(MI);
1510   assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1511          OldIndex < getMBBEndIdx(MI->getParent()) &&
1512          "Cannot handle moves across basic block boundaries.");
1513   assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
1514
1515   HMEditor HME(*this, *MRI, *TRI, NewIndex);
1516   HME.moveAllRangesFrom(MI, OldIndex);
1517 }
1518
1519 void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
1520                                          MachineInstr* BundleStart) {
1521   SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
1522   HMEditor HME(*this, *MRI, *TRI, NewIndex);
1523   HME.moveAllRangesInto(MI, BundleStart);
1524 }