Delete some dead code.
[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 "VirtRegMap.h"
21 #include "llvm/Value.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/CalcSpillWeights.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/ProcessImplicitDefs.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/ADT/DepthFirstIterator.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include <algorithm>
46 #include <limits>
47 #include <cmath>
48 using namespace llvm;
49
50 // Hidden options for help debugging.
51 static cl::opt<bool> DisableReMat("disable-rematerialization",
52                                   cl::init(false), cl::Hidden);
53
54 STATISTIC(numIntervals , "Number of original intervals");
55
56 char LiveIntervals::ID = 0;
57 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
58                 "Live Interval Analysis", false, false)
59 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
60 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
61 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
62 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
63 INITIALIZE_PASS_DEPENDENCY(ProcessImplicitDefs)
64 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
65 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
66 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
67                 "Live Interval Analysis", false, false)
68
69 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
70   AU.setPreservesCFG();
71   AU.addRequired<AliasAnalysis>();
72   AU.addPreserved<AliasAnalysis>();
73   AU.addRequired<LiveVariables>();
74   AU.addPreserved<LiveVariables>();
75   AU.addRequired<MachineLoopInfo>();
76   AU.addPreserved<MachineLoopInfo>();
77   AU.addPreservedID(MachineDominatorsID);
78
79   if (!StrongPHIElim) {
80     AU.addPreservedID(PHIEliminationID);
81     AU.addRequiredID(PHIEliminationID);
82   }
83
84   AU.addRequiredID(TwoAddressInstructionPassID);
85   AU.addPreserved<ProcessImplicitDefs>();
86   AU.addRequired<ProcessImplicitDefs>();
87   AU.addPreserved<SlotIndexes>();
88   AU.addRequiredTransitive<SlotIndexes>();
89   MachineFunctionPass::getAnalysisUsage(AU);
90 }
91
92 void LiveIntervals::releaseMemory() {
93   // Free the live intervals themselves.
94   for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
95        E = r2iMap_.end(); I != E; ++I)
96     delete I->second;
97
98   r2iMap_.clear();
99
100   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
101   VNInfoAllocator.Reset();
102 }
103
104 /// runOnMachineFunction - Register allocate the whole function
105 ///
106 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
107   mf_ = &fn;
108   mri_ = &mf_->getRegInfo();
109   tm_ = &fn.getTarget();
110   tri_ = tm_->getRegisterInfo();
111   tii_ = tm_->getInstrInfo();
112   aa_ = &getAnalysis<AliasAnalysis>();
113   lv_ = &getAnalysis<LiveVariables>();
114   indexes_ = &getAnalysis<SlotIndexes>();
115   allocatableRegs_ = tri_->getAllocatableSet(fn);
116
117   computeIntervals();
118
119   numIntervals += getNumIntervals();
120
121   DEBUG(dump());
122   return true;
123 }
124
125 /// print - Implement the dump method.
126 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
127   OS << "********** INTERVALS **********\n";
128   for (const_iterator I = begin(), E = end(); I != E; ++I) {
129     I->second->print(OS, tri_);
130     OS << "\n";
131   }
132
133   printInstrs(OS);
134 }
135
136 void LiveIntervals::printInstrs(raw_ostream &OS) const {
137   OS << "********** MACHINEINSTRS **********\n";
138   mf_->print(OS, indexes_);
139 }
140
141 void LiveIntervals::dumpInstrs() const {
142   printInstrs(dbgs());
143 }
144
145 static
146 bool MultipleDefsBySameMI(const MachineInstr &MI, unsigned MOIdx) {
147   unsigned Reg = MI.getOperand(MOIdx).getReg();
148   for (unsigned i = MOIdx+1, e = MI.getNumOperands(); i < e; ++i) {
149     const MachineOperand &MO = MI.getOperand(i);
150     if (!MO.isReg())
151       continue;
152     if (MO.getReg() == Reg && MO.isDef()) {
153       assert(MI.getOperand(MOIdx).getSubReg() != MO.getSubReg() &&
154              MI.getOperand(MOIdx).getSubReg() &&
155              (MO.getSubReg() || MO.isImplicit()));
156       return true;
157     }
158   }
159   return false;
160 }
161
162 /// isPartialRedef - Return true if the specified def at the specific index is
163 /// partially re-defining the specified live interval. A common case of this is
164 /// a definition of the sub-register.
165 bool LiveIntervals::isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
166                                    LiveInterval &interval) {
167   if (!MO.getSubReg() || MO.isEarlyClobber())
168     return false;
169
170   SlotIndex RedefIndex = MIIdx.getRegSlot();
171   const LiveRange *OldLR =
172     interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
173   MachineInstr *DefMI = getInstructionFromIndex(OldLR->valno->def);
174   if (DefMI != 0) {
175     return DefMI->findRegisterDefOperandIdx(interval.reg) != -1;
176   }
177   return false;
178 }
179
180 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
181                                              MachineBasicBlock::iterator mi,
182                                              SlotIndex MIIdx,
183                                              MachineOperand& MO,
184                                              unsigned MOIdx,
185                                              LiveInterval &interval) {
186   DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, tri_));
187
188   // Virtual registers may be defined multiple times (due to phi
189   // elimination and 2-addr elimination).  Much of what we do only has to be
190   // done once for the vreg.  We use an empty interval to detect the first
191   // time we see a vreg.
192   LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
193   if (interval.empty()) {
194     // Get the Idx of the defining instructions.
195     SlotIndex defIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
196
197     // Make sure the first definition is not a partial redefinition. Add an
198     // <imp-def> of the full register.
199     // FIXME: LiveIntervals shouldn't modify the code like this.  Whoever
200     // created the machine instruction should annotate it with <undef> flags
201     // as needed.  Then we can simply assert here.  The REG_SEQUENCE lowering
202     // is the main suspect.
203     if (MO.getSubReg()) {
204       mi->addRegisterDefined(interval.reg);
205       // Mark all defs of interval.reg on this instruction as reading <undef>.
206       for (unsigned i = MOIdx, e = mi->getNumOperands(); i != e; ++i) {
207         MachineOperand &MO2 = mi->getOperand(i);
208         if (MO2.isReg() && MO2.getReg() == interval.reg && MO2.getSubReg())
209           MO2.setIsUndef();
210       }
211     }
212
213     MachineInstr *CopyMI = NULL;
214     if (mi->isCopyLike()) {
215       CopyMI = mi;
216     }
217
218     VNInfo *ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
219     assert(ValNo->id == 0 && "First value in interval is not 0?");
220
221     // Loop over all of the blocks that the vreg is defined in.  There are
222     // two cases we have to handle here.  The most common case is a vreg
223     // whose lifetime is contained within a basic block.  In this case there
224     // will be a single kill, in MBB, which comes after the definition.
225     if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
226       // FIXME: what about dead vars?
227       SlotIndex killIdx;
228       if (vi.Kills[0] != mi)
229         killIdx = getInstructionIndex(vi.Kills[0]).getRegSlot();
230       else
231         killIdx = defIndex.getDeadSlot();
232
233       // If the kill happens after the definition, we have an intra-block
234       // live range.
235       if (killIdx > defIndex) {
236         assert(vi.AliveBlocks.empty() &&
237                "Shouldn't be alive across any blocks!");
238         LiveRange LR(defIndex, killIdx, ValNo);
239         interval.addRange(LR);
240         DEBUG(dbgs() << " +" << LR << "\n");
241         return;
242       }
243     }
244
245     // The other case we handle is when a virtual register lives to the end
246     // of the defining block, potentially live across some blocks, then is
247     // live into some number of blocks, but gets killed.  Start by adding a
248     // range that goes from this definition to the end of the defining block.
249     LiveRange NewLR(defIndex, getMBBEndIdx(mbb), ValNo);
250     DEBUG(dbgs() << " +" << NewLR);
251     interval.addRange(NewLR);
252
253     bool PHIJoin = lv_->isPHIJoin(interval.reg);
254
255     if (PHIJoin) {
256       // A phi join register is killed at the end of the MBB and revived as a new
257       // valno in the killing blocks.
258       assert(vi.AliveBlocks.empty() && "Phi join can't pass through blocks");
259       DEBUG(dbgs() << " phi-join");
260       ValNo->setHasPHIKill(true);
261     } else {
262       // Iterate over all of the blocks that the variable is completely
263       // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
264       // live interval.
265       for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
266                E = vi.AliveBlocks.end(); I != E; ++I) {
267         MachineBasicBlock *aliveBlock = mf_->getBlockNumbered(*I);
268         LiveRange LR(getMBBStartIdx(aliveBlock), getMBBEndIdx(aliveBlock), ValNo);
269         interval.addRange(LR);
270         DEBUG(dbgs() << " +" << LR);
271       }
272     }
273
274     // Finally, this virtual register is live from the start of any killing
275     // block to the 'use' slot of the killing instruction.
276     for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
277       MachineInstr *Kill = vi.Kills[i];
278       SlotIndex Start = getMBBStartIdx(Kill->getParent());
279       SlotIndex killIdx = getInstructionIndex(Kill).getRegSlot();
280
281       // Create interval with one of a NEW value number.  Note that this value
282       // number isn't actually defined by an instruction, weird huh? :)
283       if (PHIJoin) {
284         assert(getInstructionFromIndex(Start) == 0 &&
285                "PHI def index points at actual instruction.");
286         ValNo = interval.getNextValue(Start, 0, VNInfoAllocator);
287         ValNo->setIsPHIDef(true);
288       }
289       LiveRange LR(Start, killIdx, ValNo);
290       interval.addRange(LR);
291       DEBUG(dbgs() << " +" << LR);
292     }
293
294   } else {
295     if (MultipleDefsBySameMI(*mi, MOIdx))
296       // Multiple defs of the same virtual register by the same instruction.
297       // e.g. %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
298       // This is likely due to elimination of REG_SEQUENCE instructions. Return
299       // here since there is nothing to do.
300       return;
301
302     // If this is the second time we see a virtual register definition, it
303     // must be due to phi elimination or two addr elimination.  If this is
304     // the result of two address elimination, then the vreg is one of the
305     // def-and-use register operand.
306
307     // It may also be partial redef like this:
308     // 80  %reg1041:6<def> = VSHRNv4i16 %reg1034<kill>, 12, pred:14, pred:%reg0
309     // 120 %reg1041:5<def> = VSHRNv4i16 %reg1039<kill>, 12, pred:14, pred:%reg0
310     bool PartReDef = isPartialRedef(MIIdx, MO, interval);
311     if (PartReDef || mi->isRegTiedToUseOperand(MOIdx)) {
312       // If this is a two-address definition, then we have already processed
313       // the live range.  The only problem is that we didn't realize there
314       // are actually two values in the live interval.  Because of this we
315       // need to take the LiveRegion that defines this register and split it
316       // into two values.
317       SlotIndex RedefIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
318
319       const LiveRange *OldLR =
320         interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
321       VNInfo *OldValNo = OldLR->valno;
322       SlotIndex DefIndex = OldValNo->def.getRegSlot();
323
324       // Delete the previous value, which should be short and continuous,
325       // because the 2-addr copy must be in the same MBB as the redef.
326       interval.removeRange(DefIndex, RedefIndex);
327
328       // The new value number (#1) is defined by the instruction we claimed
329       // defined value #0.
330       VNInfo *ValNo = interval.createValueCopy(OldValNo, VNInfoAllocator);
331
332       // Value#0 is now defined by the 2-addr instruction.
333       OldValNo->def  = RedefIndex;
334       OldValNo->setCopy(0);
335
336       // A re-def may be a copy. e.g. %reg1030:6<def> = VMOVD %reg1026, ...
337       if (PartReDef && mi->isCopyLike())
338         OldValNo->setCopy(&*mi);
339
340       // Add the new live interval which replaces the range for the input copy.
341       LiveRange LR(DefIndex, RedefIndex, ValNo);
342       DEBUG(dbgs() << " replace range with " << LR);
343       interval.addRange(LR);
344
345       // If this redefinition is dead, we need to add a dummy unit live
346       // range covering the def slot.
347       if (MO.isDead())
348         interval.addRange(LiveRange(RedefIndex, RedefIndex.getDeadSlot(),
349                                     OldValNo));
350
351       DEBUG({
352           dbgs() << " RESULT: ";
353           interval.print(dbgs(), tri_);
354         });
355     } else if (lv_->isPHIJoin(interval.reg)) {
356       // In the case of PHI elimination, each variable definition is only
357       // live until the end of the block.  We've already taken care of the
358       // rest of the live range.
359
360       SlotIndex defIndex = MIIdx.getRegSlot();
361       if (MO.isEarlyClobber())
362         defIndex = MIIdx.getRegSlot(true);
363
364       VNInfo *ValNo;
365       MachineInstr *CopyMI = NULL;
366       if (mi->isCopyLike())
367         CopyMI = mi;
368       ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
369
370       SlotIndex killIndex = getMBBEndIdx(mbb);
371       LiveRange LR(defIndex, killIndex, ValNo);
372       interval.addRange(LR);
373       ValNo->setHasPHIKill(true);
374       DEBUG(dbgs() << " phi-join +" << LR);
375     } else {
376       llvm_unreachable("Multiply defined register");
377     }
378   }
379
380   DEBUG(dbgs() << '\n');
381 }
382
383 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
384                                               MachineBasicBlock::iterator mi,
385                                               SlotIndex MIIdx,
386                                               MachineOperand& MO,
387                                               LiveInterval &interval,
388                                               MachineInstr *CopyMI) {
389   // A physical register cannot be live across basic block, so its
390   // lifetime must end somewhere in its defining basic block.
391   DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, tri_));
392
393   SlotIndex baseIndex = MIIdx;
394   SlotIndex start = baseIndex.getRegSlot(MO.isEarlyClobber());
395   SlotIndex end = start;
396
397   // If it is not used after definition, it is considered dead at
398   // the instruction defining it. Hence its interval is:
399   // [defSlot(def), defSlot(def)+1)
400   // For earlyclobbers, the defSlot was pushed back one; the extra
401   // advance below compensates.
402   if (MO.isDead()) {
403     DEBUG(dbgs() << " dead");
404     end = start.getDeadSlot();
405     goto exit;
406   }
407
408   // If it is not dead on definition, it must be killed by a
409   // subsequent instruction. Hence its interval is:
410   // [defSlot(def), useSlot(kill)+1)
411   baseIndex = baseIndex.getNextIndex();
412   while (++mi != MBB->end()) {
413
414     if (mi->isDebugValue())
415       continue;
416     if (getInstructionFromIndex(baseIndex) == 0)
417       baseIndex = indexes_->getNextNonNullIndex(baseIndex);
418
419     if (mi->killsRegister(interval.reg, tri_)) {
420       DEBUG(dbgs() << " killed");
421       end = baseIndex.getRegSlot();
422       goto exit;
423     } else {
424       int DefIdx = mi->findRegisterDefOperandIdx(interval.reg,false,false,tri_);
425       if (DefIdx != -1) {
426         if (mi->isRegTiedToUseOperand(DefIdx)) {
427           // Two-address instruction.
428           end = baseIndex.getRegSlot();
429         } else {
430           // Another instruction redefines the register before it is ever read.
431           // Then the register is essentially dead at the instruction that
432           // defines it. Hence its interval is:
433           // [defSlot(def), defSlot(def)+1)
434           DEBUG(dbgs() << " dead");
435           end = start.getDeadSlot();
436         }
437         goto exit;
438       }
439     }
440
441     baseIndex = baseIndex.getNextIndex();
442   }
443
444   // The only case we should have a dead physreg here without a killing or
445   // instruction where we know it's dead is if it is live-in to the function
446   // and never used. Another possible case is the implicit use of the
447   // physical register has been deleted by two-address pass.
448   end = start.getDeadSlot();
449
450 exit:
451   assert(start < end && "did not find end of interval?");
452
453   // Already exists? Extend old live interval.
454   VNInfo *ValNo = interval.getVNInfoAt(start);
455   bool Extend = ValNo != 0;
456   if (!Extend)
457     ValNo = interval.getNextValue(start, CopyMI, VNInfoAllocator);
458   if (Extend && MO.isEarlyClobber())
459     ValNo->setHasRedefByEC(true);
460   LiveRange LR(start, end, ValNo);
461   interval.addRange(LR);
462   DEBUG(dbgs() << " +" << LR << '\n');
463 }
464
465 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
466                                       MachineBasicBlock::iterator MI,
467                                       SlotIndex MIIdx,
468                                       MachineOperand& MO,
469                                       unsigned MOIdx) {
470   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
471     handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
472                              getOrCreateInterval(MO.getReg()));
473   else {
474     MachineInstr *CopyMI = NULL;
475     if (MI->isCopyLike())
476       CopyMI = MI;
477     handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
478                               getOrCreateInterval(MO.getReg()), CopyMI);
479   }
480 }
481
482 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
483                                          SlotIndex MIIdx,
484                                          LiveInterval &interval, bool isAlias) {
485   DEBUG(dbgs() << "\t\tlivein register: " << PrintReg(interval.reg, tri_));
486
487   // Look for kills, if it reaches a def before it's killed, then it shouldn't
488   // be considered a livein.
489   MachineBasicBlock::iterator mi = MBB->begin();
490   MachineBasicBlock::iterator E = MBB->end();
491   // Skip over DBG_VALUE at the start of the MBB.
492   if (mi != E && mi->isDebugValue()) {
493     while (++mi != E && mi->isDebugValue())
494       ;
495     if (mi == E)
496       // MBB is empty except for DBG_VALUE's.
497       return;
498   }
499
500   SlotIndex baseIndex = MIIdx;
501   SlotIndex start = baseIndex;
502   if (getInstructionFromIndex(baseIndex) == 0)
503     baseIndex = indexes_->getNextNonNullIndex(baseIndex);
504
505   SlotIndex end = baseIndex;
506   bool SeenDefUse = false;
507
508   while (mi != E) {
509     if (mi->killsRegister(interval.reg, tri_)) {
510       DEBUG(dbgs() << " killed");
511       end = baseIndex.getRegSlot();
512       SeenDefUse = true;
513       break;
514     } else if (mi->definesRegister(interval.reg, tri_)) {
515       // Another instruction redefines the register before it is ever read.
516       // Then the register is essentially dead at the instruction that defines
517       // it. Hence its interval is:
518       // [defSlot(def), defSlot(def)+1)
519       DEBUG(dbgs() << " dead");
520       end = start.getDeadSlot();
521       SeenDefUse = true;
522       break;
523     }
524
525     while (++mi != E && mi->isDebugValue())
526       // Skip over DBG_VALUE.
527       ;
528     if (mi != E)
529       baseIndex = indexes_->getNextNonNullIndex(baseIndex);
530   }
531
532   // Live-in register might not be used at all.
533   if (!SeenDefUse) {
534     if (isAlias) {
535       DEBUG(dbgs() << " dead");
536       end = MIIdx.getDeadSlot();
537     } else {
538       DEBUG(dbgs() << " live through");
539       end = getMBBEndIdx(MBB);
540     }
541   }
542
543   SlotIndex defIdx = getMBBStartIdx(MBB);
544   assert(getInstructionFromIndex(defIdx) == 0 &&
545          "PHI def index points at actual instruction.");
546   VNInfo *vni =
547     interval.getNextValue(defIdx, 0, VNInfoAllocator);
548   vni->setIsPHIDef(true);
549   LiveRange LR(start, end, vni);
550
551   interval.addRange(LR);
552   DEBUG(dbgs() << " +" << LR << '\n');
553 }
554
555 /// computeIntervals - computes the live intervals for virtual
556 /// registers. for some ordering of the machine instructions [1,N] a
557 /// live interval is an interval [i, j) where 1 <= i <= j < N for
558 /// which a variable is live
559 void LiveIntervals::computeIntervals() {
560   DEBUG(dbgs() << "********** COMPUTING LIVE INTERVALS **********\n"
561                << "********** Function: "
562                << ((Value*)mf_->getFunction())->getName() << '\n');
563
564   SmallVector<unsigned, 8> UndefUses;
565   for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
566        MBBI != E; ++MBBI) {
567     MachineBasicBlock *MBB = MBBI;
568     if (MBB->empty())
569       continue;
570
571     // Track the index of the current machine instr.
572     SlotIndex MIIndex = getMBBStartIdx(MBB);
573     DEBUG(dbgs() << "BB#" << MBB->getNumber()
574           << ":\t\t# derived from " << MBB->getName() << "\n");
575
576     // Create intervals for live-ins to this BB first.
577     for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
578            LE = MBB->livein_end(); LI != LE; ++LI) {
579       handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
580     }
581
582     // Skip over empty initial indices.
583     if (getInstructionFromIndex(MIIndex) == 0)
584       MIIndex = indexes_->getNextNonNullIndex(MIIndex);
585
586     for (MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
587          MI != miEnd; ++MI) {
588       DEBUG(dbgs() << MIIndex << "\t" << *MI);
589       if (MI->isDebugValue())
590         continue;
591
592       // Handle defs.
593       for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
594         MachineOperand &MO = MI->getOperand(i);
595         if (!MO.isReg() || !MO.getReg())
596           continue;
597
598         // handle register defs - build intervals
599         if (MO.isDef())
600           handleRegisterDef(MBB, MI, MIIndex, MO, i);
601         else if (MO.isUndef())
602           UndefUses.push_back(MO.getReg());
603       }
604
605       // Move to the next instr slot.
606       MIIndex = indexes_->getNextNonNullIndex(MIIndex);
607     }
608   }
609
610   // Create empty intervals for registers defined by implicit_def's (except
611   // for those implicit_def that define values which are liveout of their
612   // blocks.
613   for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
614     unsigned UndefReg = UndefUses[i];
615     (void)getOrCreateInterval(UndefReg);
616   }
617 }
618
619 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
620   float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
621   return new LiveInterval(reg, Weight);
622 }
623
624 /// dupInterval - Duplicate a live interval. The caller is responsible for
625 /// managing the allocated memory.
626 LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
627   LiveInterval *NewLI = createInterval(li->reg);
628   NewLI->Copy(*li, mri_, getVNInfoAllocator());
629   return NewLI;
630 }
631
632 /// shrinkToUses - After removing some uses of a register, shrink its live
633 /// range to just the remaining uses. This method does not compute reaching
634 /// defs for new uses, and it doesn't remove dead defs.
635 bool LiveIntervals::shrinkToUses(LiveInterval *li,
636                                  SmallVectorImpl<MachineInstr*> *dead) {
637   DEBUG(dbgs() << "Shrink: " << *li << '\n');
638   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
639          && "Can only shrink virtual registers");
640   // Find all the values used, including PHI kills.
641   SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
642
643   // Blocks that have already been added to WorkList as live-out.
644   SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
645
646   // Visit all instructions reading li->reg.
647   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li->reg);
648        MachineInstr *UseMI = I.skipInstruction();) {
649     if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
650       continue;
651     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
652     // Note: This intentionally picks up the wrong VNI in case of an EC redef.
653     // See below.
654     VNInfo *VNI = li->getVNInfoBefore(Idx);
655     if (!VNI) {
656       // This shouldn't happen: readsVirtualRegister returns true, but there is
657       // no live value. It is likely caused by a target getting <undef> flags
658       // wrong.
659       DEBUG(dbgs() << Idx << '\t' << *UseMI
660                    << "Warning: Instr claims to read non-existent value in "
661                     << *li << '\n');
662       continue;
663     }
664     // Special case: An early-clobber tied operand reads and writes the
665     // register one slot early.  The getVNInfoBefore call above would have
666     // picked up the value defined by UseMI.  Adjust the kill slot and value.
667     if (SlotIndex::isSameInstr(VNI->def, Idx)) {
668       Idx = VNI->def;
669       VNI = li->getVNInfoBefore(Idx);
670       assert(VNI && "Early-clobber tied value not available");
671     }
672     WorkList.push_back(std::make_pair(Idx, VNI));
673   }
674
675   // Create a new live interval with only minimal live segments per def.
676   LiveInterval NewLI(li->reg, 0);
677   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
678        I != E; ++I) {
679     VNInfo *VNI = *I;
680     if (VNI->isUnused())
681       continue;
682     NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
683   }
684
685   // Keep track of the PHIs that are in use.
686   SmallPtrSet<VNInfo*, 8> UsedPHIs;
687
688   // Extend intervals to reach all uses in WorkList.
689   while (!WorkList.empty()) {
690     SlotIndex Idx = WorkList.back().first;
691     VNInfo *VNI = WorkList.back().second;
692     WorkList.pop_back();
693     const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
694     SlotIndex BlockStart = getMBBStartIdx(MBB);
695
696     // Extend the live range for VNI to be live at Idx.
697     if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
698       (void)ExtVNI;
699       assert(ExtVNI == VNI && "Unexpected existing value number");
700       // Is this a PHIDef we haven't seen before?
701       if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
702         continue;
703       // The PHI is live, make sure the predecessors are live-out.
704       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
705            PE = MBB->pred_end(); PI != PE; ++PI) {
706         if (!LiveOut.insert(*PI))
707           continue;
708         SlotIndex Stop = getMBBEndIdx(*PI);
709         // A predecessor is not required to have a live-out value for a PHI.
710         if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
711           WorkList.push_back(std::make_pair(Stop, PVNI));
712       }
713       continue;
714     }
715
716     // VNI is live-in to MBB.
717     DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
718     NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
719
720     // Make sure VNI is live-out from the predecessors.
721     for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
722          PE = MBB->pred_end(); PI != PE; ++PI) {
723       if (!LiveOut.insert(*PI))
724         continue;
725       SlotIndex Stop = getMBBEndIdx(*PI);
726       assert(li->getVNInfoBefore(Stop) == VNI &&
727              "Wrong value out of predecessor");
728       WorkList.push_back(std::make_pair(Stop, VNI));
729     }
730   }
731
732   // Handle dead values.
733   bool CanSeparate = false;
734   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
735        I != E; ++I) {
736     VNInfo *VNI = *I;
737     if (VNI->isUnused())
738       continue;
739     LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
740     assert(LII != NewLI.end() && "Missing live range for PHI");
741     if (LII->end != VNI->def.getDeadSlot())
742       continue;
743     if (VNI->isPHIDef()) {
744       // This is a dead PHI. Remove it.
745       VNI->setIsUnused(true);
746       NewLI.removeRange(*LII);
747       DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
748       CanSeparate = true;
749     } else {
750       // This is a dead def. Make sure the instruction knows.
751       MachineInstr *MI = getInstructionFromIndex(VNI->def);
752       assert(MI && "No instruction defining live value");
753       MI->addRegisterDead(li->reg, tri_);
754       if (dead && MI->allDefsAreDead()) {
755         DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
756         dead->push_back(MI);
757       }
758     }
759   }
760
761   // Move the trimmed ranges back.
762   li->ranges.swap(NewLI.ranges);
763   DEBUG(dbgs() << "Shrunk: " << *li << '\n');
764   return CanSeparate;
765 }
766
767
768 //===----------------------------------------------------------------------===//
769 // Register allocator hooks.
770 //
771
772 void LiveIntervals::addKillFlags() {
773   for (iterator I = begin(), E = end(); I != E; ++I) {
774     unsigned Reg = I->first;
775     if (TargetRegisterInfo::isPhysicalRegister(Reg))
776       continue;
777     if (mri_->reg_nodbg_empty(Reg))
778       continue;
779     LiveInterval *LI = I->second;
780
781     // Every instruction that kills Reg corresponds to a live range end point.
782     for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
783          ++RI) {
784       // A block index indicates an MBB edge.
785       if (RI->end.isBlock())
786         continue;
787       MachineInstr *MI = getInstructionFromIndex(RI->end);
788       if (!MI)
789         continue;
790       MI->addRegisterKilled(Reg, NULL);
791     }
792   }
793 }
794
795 #ifndef NDEBUG
796 static bool intervalRangesSane(const LiveInterval& li) {
797   if (li.empty()) {
798     return true;
799   }
800
801   SlotIndex lastEnd = li.begin()->start;
802   for (LiveInterval::const_iterator lrItr = li.begin(), lrEnd = li.end();
803        lrItr != lrEnd; ++lrItr) {
804     const LiveRange& lr = *lrItr;
805     if (lastEnd > lr.start || lr.start >= lr.end)
806       return false;
807     lastEnd = lr.end;
808   }
809
810   return true;
811 }
812 #endif
813
814 template <typename DefSetT>
815 static void handleMoveDefs(LiveIntervals& lis, SlotIndex origIdx,
816                            SlotIndex miIdx, const DefSetT& defs) {
817   for (typename DefSetT::const_iterator defItr = defs.begin(),
818                                         defEnd = defs.end();
819        defItr != defEnd; ++defItr) {
820     unsigned def = *defItr;
821     LiveInterval& li = lis.getInterval(def);
822     LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
823     assert(lr != 0 && "No range for def?");
824     lr->start = miIdx.getRegSlot();
825     lr->valno->def = miIdx.getRegSlot();
826     assert(intervalRangesSane(li) && "Broke live interval moving def.");
827   }
828 }
829
830 template <typename DeadDefSetT>
831 static void handleMoveDeadDefs(LiveIntervals& lis, SlotIndex origIdx,
832                                SlotIndex miIdx, const DeadDefSetT& deadDefs) {
833   for (typename DeadDefSetT::const_iterator deadDefItr = deadDefs.begin(),
834                                             deadDefEnd = deadDefs.end();
835        deadDefItr != deadDefEnd; ++deadDefItr) {
836     unsigned deadDef = *deadDefItr;
837     LiveInterval& li = lis.getInterval(deadDef);
838     LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
839     assert(lr != 0 && "No range for dead def?");
840     assert(lr->start == origIdx.getRegSlot() && "Bad dead range start?");
841     assert(lr->end == origIdx.getDeadSlot() && "Bad dead range end?");
842     assert(lr->valno->def == origIdx.getRegSlot() && "Bad dead valno def.");
843     LiveRange t(*lr);
844     t.start = miIdx.getRegSlot();
845     t.valno->def = miIdx.getRegSlot();
846     t.end = miIdx.getDeadSlot();
847     li.removeRange(*lr);
848     li.addRange(t);
849     assert(intervalRangesSane(li) && "Broke live interval moving dead def.");
850   }
851 }
852
853 template <typename ECSetT>
854 static void handleMoveECs(LiveIntervals& lis, SlotIndex origIdx,
855                           SlotIndex miIdx, const ECSetT& ecs) {
856   for (typename ECSetT::const_iterator ecItr = ecs.begin(), ecEnd = ecs.end();
857        ecItr != ecEnd; ++ecItr) {
858     unsigned ec = *ecItr;
859     LiveInterval& li = lis.getInterval(ec);
860     LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot(true));
861     assert(lr != 0 && "No range for early clobber?");
862     assert(lr->start == origIdx.getRegSlot(true) && "Bad EC range start?");
863     assert(lr->end == origIdx.getRegSlot() && "Bad EC range end.");
864     assert(lr->valno->def == origIdx.getRegSlot(true) && "Bad EC valno def.");
865     LiveRange t(*lr);
866     t.start = miIdx.getRegSlot(true);
867     t.valno->def = miIdx.getRegSlot(true);
868     t.end = miIdx.getRegSlot();
869     li.removeRange(*lr);
870     li.addRange(t);
871     assert(intervalRangesSane(li) && "Broke live interval moving EC.");
872   }
873 }
874
875 template <typename UseSetT>
876 static void handleMoveUses(const MachineBasicBlock *mbb,
877                            const MachineRegisterInfo& mri,
878                            const BitVector& reservedRegs, LiveIntervals &lis,
879                            SlotIndex origIdx, SlotIndex miIdx,
880                            const UseSetT &uses) {
881   bool movingUp = miIdx < origIdx;
882   for (typename UseSetT::const_iterator usesItr = uses.begin(),
883                                         usesEnd = uses.end();
884        usesItr != usesEnd; ++usesItr) {
885     unsigned use = *usesItr;
886     if (!lis.hasInterval(use))
887       continue;
888     if (TargetRegisterInfo::isPhysicalRegister(use) && reservedRegs.test(use))
889       continue;
890     LiveInterval& li = lis.getInterval(use);
891     LiveRange* lr = li.getLiveRangeBefore(origIdx.getRegSlot());
892     assert(lr != 0 && "No range for use?");
893     bool liveThrough = lr->end > origIdx.getRegSlot();
894
895     if (movingUp) {
896       // If moving up and liveThrough - nothing to do.
897       // If not live through we need to extend the range to the last use
898       // between the old location and the new one.
899       if (!liveThrough) {
900         SlotIndex lastUseInRange = miIdx.getRegSlot();
901         for (MachineRegisterInfo::use_iterator useI = mri.use_begin(use),
902                                                useE = mri.use_end();
903              useI != useE; ++useI) {
904           const MachineInstr* mopI = &*useI;
905           const MachineOperand& mop = useI.getOperand();
906           SlotIndex instSlot = lis.getSlotIndexes()->getInstructionIndex(mopI);
907           SlotIndex opSlot = instSlot.getRegSlot(mop.isEarlyClobber());
908           if (opSlot >= lastUseInRange && opSlot < origIdx) {
909             lastUseInRange = opSlot;
910           }
911         }
912         lr->end = lastUseInRange;
913       }
914     } else {
915       // Moving down is easy - the existing live range end tells us where
916       // the last kill is.
917       if (!liveThrough) {
918         // Easy fix - just update the range endpoint.
919         lr->end = miIdx.getRegSlot();
920       } else {
921         bool liveOut = lr->end >= lis.getSlotIndexes()->getMBBEndIdx(mbb);
922         if (!liveOut && miIdx.getRegSlot() > lr->end) {
923           lr->end = miIdx.getRegSlot();
924         }
925       }
926     }
927     assert(intervalRangesSane(li) && "Broke live interval moving use.");
928   }
929 }
930
931 void LiveIntervals::moveInstr(MachineBasicBlock::iterator insertPt,
932                               MachineInstr *mi) {
933   MachineBasicBlock* mbb = mi->getParent();
934   assert((insertPt == mbb->end() || insertPt->getParent() == mbb) &&
935          "Cannot handle moves across basic block boundaries.");
936   assert(&*insertPt != mi && "No-op move requested?");
937   assert(!mi->isInsideBundle() && "Can't handle bundled instructions yet.");
938
939   // Grab the original instruction index.
940   SlotIndex origIdx = indexes_->getInstructionIndex(mi);
941
942   // Move the machine instr and obtain its new index.
943   indexes_->removeMachineInstrFromMaps(mi);
944   mbb->remove(mi);
945   mbb->insert(insertPt, mi);
946   SlotIndex miIdx = indexes_->insertMachineInstrInMaps(mi);
947
948   // Pick the direction.
949   bool movingUp = miIdx < origIdx;
950
951   // Collect the operands.
952   DenseSet<unsigned> uses, defs, deadDefs, ecs;
953   for (MachineInstr::mop_iterator mopItr = mi->operands_begin(),
954          mopEnd = mi->operands_end();
955        mopItr != mopEnd; ++mopItr) {
956     const MachineOperand& mop = *mopItr;
957
958     if (!mop.isReg() || mop.getReg() == 0)
959       continue;
960     unsigned reg = mop.getReg();
961     if (mop.isUse()) {
962       assert(mop.readsReg());
963     }
964
965     if (mop.readsReg() && !ecs.count(reg)) {
966       uses.insert(reg);
967     }
968     if (mop.isDef()) {
969       if (mop.isDead()) {
970         assert(!defs.count(reg) && "Can't mix defs with dead-defs.");
971         deadDefs.insert(reg);
972       } else if (mop.isEarlyClobber()) {
973         uses.erase(reg);
974         ecs.insert(reg);
975       } else {
976         assert(!deadDefs.count(reg) && "Can't mix defs with dead-defs.");
977         defs.insert(reg);
978       }
979     }
980   }
981
982   BitVector reservedRegs(tri_->getReservedRegs(*mbb->getParent()));
983
984   if (movingUp) {
985     handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
986     handleMoveECs(*this, origIdx, miIdx, ecs);
987     handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
988     handleMoveDefs(*this, origIdx, miIdx, defs);
989   } else {
990     handleMoveDefs(*this, origIdx, miIdx, defs);
991     handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
992     handleMoveECs(*this, origIdx, miIdx, ecs);
993     handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
994   }
995 }
996
997 /// getReMatImplicitUse - If the remat definition MI has one (for now, we only
998 /// allow one) virtual register operand, then its uses are implicitly using
999 /// the register. Returns the virtual register.
1000 unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
1001                                             MachineInstr *MI) const {
1002   unsigned RegOp = 0;
1003   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1004     MachineOperand &MO = MI->getOperand(i);
1005     if (!MO.isReg() || !MO.isUse())
1006       continue;
1007     unsigned Reg = MO.getReg();
1008     if (Reg == 0 || Reg == li.reg)
1009       continue;
1010
1011     if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
1012         !allocatableRegs_[Reg])
1013       continue;
1014     RegOp = MO.getReg();
1015     break; // Found vreg operand - leave the loop.
1016   }
1017   return RegOp;
1018 }
1019
1020 /// isValNoAvailableAt - Return true if the val# of the specified interval
1021 /// which reaches the given instruction also reaches the specified use index.
1022 bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
1023                                        SlotIndex UseIdx) const {
1024   VNInfo *UValNo = li.getVNInfoAt(UseIdx);
1025   return UValNo && UValNo == li.getVNInfoAt(getInstructionIndex(MI));
1026 }
1027
1028 /// isReMaterializable - Returns true if the definition MI of the specified
1029 /// val# of the specified interval is re-materializable.
1030 bool
1031 LiveIntervals::isReMaterializable(const LiveInterval &li,
1032                                   const VNInfo *ValNo, MachineInstr *MI,
1033                                   const SmallVectorImpl<LiveInterval*> *SpillIs,
1034                                   bool &isLoad) {
1035   if (DisableReMat)
1036     return false;
1037
1038   if (!tii_->isTriviallyReMaterializable(MI, aa_))
1039     return false;
1040
1041   // Target-specific code can mark an instruction as being rematerializable
1042   // if it has one virtual reg use, though it had better be something like
1043   // a PIC base register which is likely to be live everywhere.
1044   unsigned ImpUse = getReMatImplicitUse(li, MI);
1045   if (ImpUse) {
1046     const LiveInterval &ImpLi = getInterval(ImpUse);
1047     for (MachineRegisterInfo::use_nodbg_iterator
1048            ri = mri_->use_nodbg_begin(li.reg), re = mri_->use_nodbg_end();
1049          ri != re; ++ri) {
1050       MachineInstr *UseMI = &*ri;
1051       SlotIndex UseIdx = getInstructionIndex(UseMI);
1052       if (li.getVNInfoAt(UseIdx) != ValNo)
1053         continue;
1054       if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1055         return false;
1056     }
1057
1058     // If a register operand of the re-materialized instruction is going to
1059     // be spilled next, then it's not legal to re-materialize this instruction.
1060     if (SpillIs)
1061       for (unsigned i = 0, e = SpillIs->size(); i != e; ++i)
1062         if (ImpUse == (*SpillIs)[i]->reg)
1063           return false;
1064   }
1065   return true;
1066 }
1067
1068 /// isReMaterializable - Returns true if every definition of MI of every
1069 /// val# of the specified interval is re-materializable.
1070 bool
1071 LiveIntervals::isReMaterializable(const LiveInterval &li,
1072                                   const SmallVectorImpl<LiveInterval*> *SpillIs,
1073                                   bool &isLoad) {
1074   isLoad = false;
1075   for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1076        i != e; ++i) {
1077     const VNInfo *VNI = *i;
1078     if (VNI->isUnused())
1079       continue; // Dead val#.
1080     // Is the def for the val# rematerializable?
1081     MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
1082     if (!ReMatDefMI)
1083       return false;
1084     bool DefIsLoad = false;
1085     if (!ReMatDefMI ||
1086         !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
1087       return false;
1088     isLoad |= DefIsLoad;
1089   }
1090   return true;
1091 }
1092
1093 bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1094   LiveInterval::Ranges::const_iterator itr = li.ranges.begin();
1095
1096   MachineBasicBlock *mbb =  indexes_->getMBBCoveringRange(itr->start, itr->end);
1097
1098   if (mbb == 0)
1099     return false;
1100
1101   for (++itr; itr != li.ranges.end(); ++itr) {
1102     MachineBasicBlock *mbb2 =
1103       indexes_->getMBBCoveringRange(itr->start, itr->end);
1104
1105     if (mbb2 != mbb)
1106       return false;
1107   }
1108
1109   return true;
1110 }
1111
1112 float
1113 LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
1114   // Limit the loop depth ridiculousness.
1115   if (loopDepth > 200)
1116     loopDepth = 200;
1117
1118   // The loop depth is used to roughly estimate the number of times the
1119   // instruction is executed. Something like 10^d is simple, but will quickly
1120   // overflow a float. This expression behaves like 10^d for small d, but is
1121   // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
1122   // headroom before overflow.
1123   // By the way, powf() might be unavailable here. For consistency,
1124   // We may take pow(double,double).
1125   float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
1126
1127   return (isDef + isUse) * lc;
1128 }
1129
1130 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1131                                                   MachineInstr* startInst) {
1132   LiveInterval& Interval = getOrCreateInterval(reg);
1133   VNInfo* VN = Interval.getNextValue(
1134     SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1135     startInst, getVNInfoAllocator());
1136   VN->setHasPHIKill(true);
1137   LiveRange LR(
1138      SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1139      getMBBEndIdx(startInst->getParent()), VN);
1140   Interval.addRange(LR);
1141
1142   return LR;
1143 }