More templatization.
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
1 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "liveintervals"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "VirtRegMap.h"
21 #include "llvm/Value.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.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/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include <algorithm>
35 #include <cmath>
36 using namespace llvm;
37
38 namespace {
39   // Hidden options for help debugging.
40   cl::opt<bool> DisableReMat("disable-rematerialization", 
41                               cl::init(false), cl::Hidden);
42 }
43
44 STATISTIC(numIntervals, "Number of original intervals");
45 STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
46 STATISTIC(numFolded   , "Number of loads/stores folded into instructions");
47
48 char LiveIntervals::ID = 0;
49 namespace {
50   RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
51 }
52
53 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
54   AU.addPreserved<LiveVariables>();
55   AU.addRequired<LiveVariables>();
56   AU.addPreservedID(PHIEliminationID);
57   AU.addRequiredID(PHIEliminationID);
58   AU.addRequiredID(TwoAddressInstructionPassID);
59   MachineFunctionPass::getAnalysisUsage(AU);
60 }
61
62 void LiveIntervals::releaseMemory() {
63   Idx2MBBMap.clear();
64   mi2iMap_.clear();
65   i2miMap_.clear();
66   r2iMap_.clear();
67   // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
68   VNInfoAllocator.Reset();
69   for (unsigned i = 0, e = ClonedMIs.size(); i != e; ++i)
70     delete ClonedMIs[i];
71 }
72
73 namespace llvm {
74   inline bool operator<(unsigned V, const IdxMBBPair &IM) {
75     return V < IM.first;
76   }
77
78   inline bool operator<(const IdxMBBPair &IM, unsigned V) {
79     return IM.first < V;
80   }
81
82   struct Idx2MBBCompare {
83     bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
84       return LHS.first < RHS.first;
85     }
86   };
87 }
88
89 /// runOnMachineFunction - Register allocate the whole function
90 ///
91 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
92   mf_ = &fn;
93   tm_ = &fn.getTarget();
94   mri_ = tm_->getRegisterInfo();
95   tii_ = tm_->getInstrInfo();
96   lv_ = &getAnalysis<LiveVariables>();
97   allocatableRegs_ = mri_->getAllocatableSet(fn);
98
99   // Number MachineInstrs and MachineBasicBlocks.
100   // Initialize MBB indexes to a sentinal.
101   MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
102   
103   unsigned MIIndex = 0;
104   for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
105        MBB != E; ++MBB) {
106     unsigned StartIdx = MIIndex;
107
108     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
109          I != E; ++I) {
110       bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
111       assert(inserted && "multiple MachineInstr -> index mappings");
112       i2miMap_.push_back(I);
113       MIIndex += InstrSlots::NUM;
114     }
115
116     // Set the MBB2IdxMap entry for this MBB.
117     MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
118     Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
119   }
120   std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
121
122   computeIntervals();
123
124   numIntervals += getNumIntervals();
125
126   DOUT << "********** INTERVALS **********\n";
127   for (iterator I = begin(), E = end(); I != E; ++I) {
128     I->second.print(DOUT, mri_);
129     DOUT << "\n";
130   }
131
132   numIntervalsAfter += getNumIntervals();
133   DEBUG(dump());
134   return true;
135 }
136
137 /// print - Implement the dump method.
138 void LiveIntervals::print(std::ostream &O, const Module* ) const {
139   O << "********** INTERVALS **********\n";
140   for (const_iterator I = begin(), E = end(); I != E; ++I) {
141     I->second.print(DOUT, mri_);
142     DOUT << "\n";
143   }
144
145   O << "********** MACHINEINSTRS **********\n";
146   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
147        mbbi != mbbe; ++mbbi) {
148     O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
149     for (MachineBasicBlock::iterator mii = mbbi->begin(),
150            mie = mbbi->end(); mii != mie; ++mii) {
151       O << getInstructionIndex(mii) << '\t' << *mii;
152     }
153   }
154 }
155
156 /// conflictsWithPhysRegDef - Returns true if the specified register
157 /// is defined during the duration of the specified interval.
158 bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
159                                             VirtRegMap &vrm, unsigned reg) {
160   for (LiveInterval::Ranges::const_iterator
161          I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
162     for (unsigned index = getBaseIndex(I->start),
163            end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
164          index += InstrSlots::NUM) {
165       // skip deleted instructions
166       while (index != end && !getInstructionFromIndex(index))
167         index += InstrSlots::NUM;
168       if (index == end) break;
169
170       MachineInstr *MI = getInstructionFromIndex(index);
171       for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
172         MachineOperand& mop = MI->getOperand(i);
173         if (!mop.isRegister() || !mop.isDef())
174           continue;
175         unsigned PhysReg = mop.getReg();
176         if (PhysReg == 0)
177           continue;
178         if (MRegisterInfo::isVirtualRegister(PhysReg))
179           PhysReg = vrm.getPhys(PhysReg);
180         if (PhysReg && mri_->regsOverlap(PhysReg, reg))
181           return true;
182       }
183     }
184   }
185
186   return false;
187 }
188
189 void LiveIntervals::printRegName(unsigned reg) const {
190   if (MRegisterInfo::isPhysicalRegister(reg))
191     cerr << mri_->getName(reg);
192   else
193     cerr << "%reg" << reg;
194 }
195
196 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
197                                              MachineBasicBlock::iterator mi,
198                                              unsigned MIIdx,
199                                              LiveInterval &interval) {
200   DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
201   LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
202
203   // Virtual registers may be defined multiple times (due to phi
204   // elimination and 2-addr elimination).  Much of what we do only has to be
205   // done once for the vreg.  We use an empty interval to detect the first
206   // time we see a vreg.
207   if (interval.empty()) {
208     // Get the Idx of the defining instructions.
209     unsigned defIndex = getDefIndex(MIIdx);
210     VNInfo *ValNo;
211     unsigned SrcReg, DstReg;
212     if (tii_->isMoveInstr(*mi, SrcReg, DstReg))
213       ValNo = interval.getNextValue(defIndex, SrcReg, VNInfoAllocator);
214     else if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
215       ValNo = interval.getNextValue(defIndex, mi->getOperand(1).getReg(),
216                                     VNInfoAllocator);
217     else
218       ValNo = interval.getNextValue(defIndex, 0, VNInfoAllocator);
219
220     assert(ValNo->id == 0 && "First value in interval is not 0?");
221
222     // Loop over all of the blocks that the vreg is defined in.  There are
223     // two cases we have to handle here.  The most common case is a vreg
224     // whose lifetime is contained within a basic block.  In this case there
225     // will be a single kill, in MBB, which comes after the definition.
226     if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
227       // FIXME: what about dead vars?
228       unsigned killIdx;
229       if (vi.Kills[0] != mi)
230         killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
231       else
232         killIdx = defIndex+1;
233
234       // If the kill happens after the definition, we have an intra-block
235       // live range.
236       if (killIdx > defIndex) {
237         assert(vi.AliveBlocks.none() &&
238                "Shouldn't be alive across any blocks!");
239         LiveRange LR(defIndex, killIdx, ValNo);
240         interval.addRange(LR);
241         DOUT << " +" << LR << "\n";
242         interval.addKill(ValNo, killIdx);
243         return;
244       }
245     }
246
247     // The other case we handle is when a virtual register lives to the end
248     // of the defining block, potentially live across some blocks, then is
249     // live into some number of blocks, but gets killed.  Start by adding a
250     // range that goes from this definition to the end of the defining block.
251     LiveRange NewLR(defIndex,
252                     getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
253                     ValNo);
254     DOUT << " +" << NewLR;
255     interval.addRange(NewLR);
256
257     // Iterate over all of the blocks that the variable is completely
258     // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
259     // live interval.
260     for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
261       if (vi.AliveBlocks[i]) {
262         MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
263         if (!MBB->empty()) {
264           LiveRange LR(getMBBStartIdx(i),
265                        getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
266                        ValNo);
267           interval.addRange(LR);
268           DOUT << " +" << LR;
269         }
270       }
271     }
272
273     // Finally, this virtual register is live from the start of any killing
274     // block to the 'use' slot of the killing instruction.
275     for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
276       MachineInstr *Kill = vi.Kills[i];
277       unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
278       LiveRange LR(getMBBStartIdx(Kill->getParent()),
279                    killIdx, ValNo);
280       interval.addRange(LR);
281       interval.addKill(ValNo, killIdx);
282       DOUT << " +" << LR;
283     }
284
285   } else {
286     // If this is the second time we see a virtual register definition, it
287     // must be due to phi elimination or two addr elimination.  If this is
288     // the result of two address elimination, then the vreg is one of the
289     // def-and-use register operand.
290     if (mi->isRegReDefinedByTwoAddr(interval.reg)) {
291       // If this is a two-address definition, then we have already processed
292       // the live range.  The only problem is that we didn't realize there
293       // are actually two values in the live interval.  Because of this we
294       // need to take the LiveRegion that defines this register and split it
295       // into two values.
296       unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
297       unsigned RedefIndex = getDefIndex(MIIdx);
298
299       const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
300       VNInfo *OldValNo = OldLR->valno;
301       unsigned OldEnd = OldLR->end;
302
303       // Delete the initial value, which should be short and continuous,
304       // because the 2-addr copy must be in the same MBB as the redef.
305       interval.removeRange(DefIndex, RedefIndex);
306
307       // Two-address vregs should always only be redefined once.  This means
308       // that at this point, there should be exactly one value number in it.
309       assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
310
311       // The new value number (#1) is defined by the instruction we claimed
312       // defined value #0.
313       VNInfo *ValNo = interval.getNextValue(0, 0, VNInfoAllocator);
314       interval.copyValNumInfo(ValNo, OldValNo);
315       
316       // Value#0 is now defined by the 2-addr instruction.
317       OldValNo->def = RedefIndex;
318       OldValNo->reg = 0;
319       
320       // Add the new live interval which replaces the range for the input copy.
321       LiveRange LR(DefIndex, RedefIndex, ValNo);
322       DOUT << " replace range with " << LR;
323       interval.addRange(LR);
324       interval.addKill(ValNo, RedefIndex);
325       interval.removeKills(ValNo, RedefIndex, OldEnd);
326
327       // If this redefinition is dead, we need to add a dummy unit live
328       // range covering the def slot.
329       if (lv_->RegisterDefIsDead(mi, interval.reg))
330         interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
331
332       DOUT << " RESULT: ";
333       interval.print(DOUT, mri_);
334
335     } else {
336       // Otherwise, this must be because of phi elimination.  If this is the
337       // first redefinition of the vreg that we have seen, go back and change
338       // the live range in the PHI block to be a different value number.
339       if (interval.containsOneValue()) {
340         assert(vi.Kills.size() == 1 &&
341                "PHI elimination vreg should have one kill, the PHI itself!");
342
343         // Remove the old range that we now know has an incorrect number.
344         VNInfo *VNI = interval.getValNumInfo(0);
345         MachineInstr *Killer = vi.Kills[0];
346         unsigned Start = getMBBStartIdx(Killer->getParent());
347         unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
348         DOUT << " Removing [" << Start << "," << End << "] from: ";
349         interval.print(DOUT, mri_); DOUT << "\n";
350         interval.removeRange(Start, End);
351         interval.addKill(VNI, Start+1); // odd # means phi node
352         DOUT << " RESULT: "; interval.print(DOUT, mri_);
353
354         // Replace the interval with one of a NEW value number.  Note that this
355         // value number isn't actually defined by an instruction, weird huh? :)
356         LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
357         DOUT << " replace range with " << LR;
358         interval.addRange(LR);
359         interval.addKill(LR.valno, End);
360         DOUT << " RESULT: "; interval.print(DOUT, mri_);
361       }
362
363       // In the case of PHI elimination, each variable definition is only
364       // live until the end of the block.  We've already taken care of the
365       // rest of the live range.
366       unsigned defIndex = getDefIndex(MIIdx);
367       
368       VNInfo *ValNo;
369       unsigned SrcReg, DstReg;
370       if (tii_->isMoveInstr(*mi, SrcReg, DstReg))
371         ValNo = interval.getNextValue(defIndex, SrcReg, VNInfoAllocator);
372       else if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
373         ValNo = interval.getNextValue(defIndex, mi->getOperand(1).getReg(),
374                                       VNInfoAllocator);
375       else
376         ValNo = interval.getNextValue(defIndex, 0, VNInfoAllocator);
377       
378       unsigned killIndex = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
379       LiveRange LR(defIndex, killIndex, ValNo);
380       interval.addRange(LR);
381       interval.addKill(ValNo, killIndex-1); // odd # means phi node
382       DOUT << " +" << LR;
383     }
384   }
385
386   DOUT << '\n';
387 }
388
389 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
390                                               MachineBasicBlock::iterator mi,
391                                               unsigned MIIdx,
392                                               LiveInterval &interval,
393                                               unsigned SrcReg) {
394   // A physical register cannot be live across basic block, so its
395   // lifetime must end somewhere in its defining basic block.
396   DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
397
398   unsigned baseIndex = MIIdx;
399   unsigned start = getDefIndex(baseIndex);
400   unsigned end = start;
401
402   // If it is not used after definition, it is considered dead at
403   // the instruction defining it. Hence its interval is:
404   // [defSlot(def), defSlot(def)+1)
405   if (lv_->RegisterDefIsDead(mi, interval.reg)) {
406     DOUT << " dead";
407     end = getDefIndex(start) + 1;
408     goto exit;
409   }
410
411   // If it is not dead on definition, it must be killed by a
412   // subsequent instruction. Hence its interval is:
413   // [defSlot(def), useSlot(kill)+1)
414   while (++mi != MBB->end()) {
415     baseIndex += InstrSlots::NUM;
416     if (lv_->KillsRegister(mi, interval.reg)) {
417       DOUT << " killed";
418       end = getUseIndex(baseIndex) + 1;
419       goto exit;
420     } else if (lv_->ModifiesRegister(mi, interval.reg)) {
421       // Another instruction redefines the register before it is ever read.
422       // Then the register is essentially dead at the instruction that defines
423       // it. Hence its interval is:
424       // [defSlot(def), defSlot(def)+1)
425       DOUT << " dead";
426       end = getDefIndex(start) + 1;
427       goto exit;
428     }
429   }
430   
431   // The only case we should have a dead physreg here without a killing or
432   // instruction where we know it's dead is if it is live-in to the function
433   // and never used.
434   assert(!SrcReg && "physreg was not killed in defining block!");
435   end = getDefIndex(start) + 1;  // It's dead.
436
437 exit:
438   assert(start < end && "did not find end of interval?");
439
440   // Already exists? Extend old live interval.
441   LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
442   VNInfo *ValNo = (OldLR != interval.end())
443     ? OldLR->valno : interval.getNextValue(start, SrcReg, VNInfoAllocator);
444   LiveRange LR(start, end, ValNo);
445   interval.addRange(LR);
446   interval.addKill(LR.valno, end);
447   DOUT << " +" << LR << '\n';
448 }
449
450 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
451                                       MachineBasicBlock::iterator MI,
452                                       unsigned MIIdx,
453                                       unsigned reg) {
454   if (MRegisterInfo::isVirtualRegister(reg))
455     handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
456   else if (allocatableRegs_[reg]) {
457     unsigned SrcReg, DstReg;
458     if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
459       SrcReg = MI->getOperand(1).getReg();
460     else if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
461       SrcReg = 0;
462     handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
463     // Def of a register also defines its sub-registers.
464     for (const unsigned* AS = mri_->getSubRegisters(reg); *AS; ++AS)
465       // Avoid processing some defs more than once.
466       if (!MI->findRegisterDefOperand(*AS))
467         handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
468   }
469 }
470
471 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
472                                          unsigned MIIdx,
473                                          LiveInterval &interval, bool isAlias) {
474   DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
475
476   // Look for kills, if it reaches a def before it's killed, then it shouldn't
477   // be considered a livein.
478   MachineBasicBlock::iterator mi = MBB->begin();
479   unsigned baseIndex = MIIdx;
480   unsigned start = baseIndex;
481   unsigned end = start;
482   while (mi != MBB->end()) {
483     if (lv_->KillsRegister(mi, interval.reg)) {
484       DOUT << " killed";
485       end = getUseIndex(baseIndex) + 1;
486       goto exit;
487     } else if (lv_->ModifiesRegister(mi, interval.reg)) {
488       // Another instruction redefines the register before it is ever read.
489       // Then the register is essentially dead at the instruction that defines
490       // it. Hence its interval is:
491       // [defSlot(def), defSlot(def)+1)
492       DOUT << " dead";
493       end = getDefIndex(start) + 1;
494       goto exit;
495     }
496
497     baseIndex += InstrSlots::NUM;
498     ++mi;
499   }
500
501 exit:
502   // Live-in register might not be used at all.
503   if (end == MIIdx) {
504     if (isAlias) {
505       DOUT << " dead";
506       end = getDefIndex(MIIdx) + 1;
507     } else {
508       DOUT << " live through";
509       end = baseIndex;
510     }
511   }
512
513   LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
514   interval.addRange(LR);
515   interval.addKill(LR.valno, end);
516   DOUT << " +" << LR << '\n';
517 }
518
519 /// computeIntervals - computes the live intervals for virtual
520 /// registers. for some ordering of the machine instructions [1,N] a
521 /// live interval is an interval [i, j) where 1 <= i <= j < N for
522 /// which a variable is live
523 void LiveIntervals::computeIntervals() {
524   DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
525        << "********** Function: "
526        << ((Value*)mf_->getFunction())->getName() << '\n';
527   // Track the index of the current machine instr.
528   unsigned MIIndex = 0;
529   for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
530        MBBI != E; ++MBBI) {
531     MachineBasicBlock *MBB = MBBI;
532     DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
533
534     MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
535
536     // Create intervals for live-ins to this BB first.
537     for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
538            LE = MBB->livein_end(); LI != LE; ++LI) {
539       handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
540       // Multiple live-ins can alias the same register.
541       for (const unsigned* AS = mri_->getSubRegisters(*LI); *AS; ++AS)
542         if (!hasInterval(*AS))
543           handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
544                                true);
545     }
546     
547     for (; MI != miEnd; ++MI) {
548       DOUT << MIIndex << "\t" << *MI;
549
550       // Handle defs.
551       for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
552         MachineOperand &MO = MI->getOperand(i);
553         // handle register defs - build intervals
554         if (MO.isRegister() && MO.getReg() && MO.isDef())
555           handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
556       }
557       
558       MIIndex += InstrSlots::NUM;
559     }
560   }
561 }
562
563 bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
564                               SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
565   std::vector<IdxMBBPair>::const_iterator I =
566     std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
567
568   bool ResVal = false;
569   while (I != Idx2MBBMap.end()) {
570     if (LR.end <= I->first)
571       break;
572     MBBs.push_back(I->second);
573     ResVal = true;
574     ++I;
575   }
576   return ResVal;
577 }
578
579
580 LiveInterval LiveIntervals::createInterval(unsigned reg) {
581   float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
582                        HUGE_VALF : 0.0F;
583   return LiveInterval(reg, Weight);
584 }
585
586
587 //===----------------------------------------------------------------------===//
588 // Register allocator hooks.
589 //
590
591 /// isReMaterializable - Returns true if the definition MI of the specified
592 /// val# of the specified interval is re-materializable.
593 bool LiveIntervals::isReMaterializable(const LiveInterval &li,
594                                        const VNInfo *ValNo, MachineInstr *MI) {
595   if (DisableReMat)
596     return false;
597
598   if (tii_->isTriviallyReMaterializable(MI))
599     return true;
600
601   int FrameIdx = 0;
602   if (!tii_->isLoadFromStackSlot(MI, FrameIdx) ||
603       !mf_->getFrameInfo()->isFixedObjectIndex(FrameIdx))
604     return false;
605
606   // This is a load from fixed stack slot. It can be rematerialized unless it's
607   // re-defined by a two-address instruction.
608   for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
609        i != e; ++i) {
610     const VNInfo *VNI = *i;
611     if (VNI == ValNo)
612       continue;
613     unsigned DefIdx = VNI->def;
614     if (DefIdx == ~1U)
615       continue; // Dead val#.
616     MachineInstr *DefMI = (DefIdx == ~0u)
617       ? NULL : getInstructionFromIndex(DefIdx);
618     if (DefMI && DefMI->isRegReDefinedByTwoAddr(li.reg))
619       return false;
620   }
621   return true;
622 }
623
624 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
625 /// slot / to reg or any rematerialized load into ith operand of specified
626 /// MI. If it is successul, MI is updated with the newly created MI and
627 /// returns true.
628 bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
629                                          MachineInstr *DefMI,
630                                          unsigned index, unsigned i,
631                                          bool isSS, int slot, unsigned reg) {
632   MachineInstr *fmi = isSS
633     ? mri_->foldMemoryOperand(MI, i, slot)
634     : mri_->foldMemoryOperand(MI, i, DefMI);
635   if (fmi) {
636     // Attempt to fold the memory reference into the instruction. If
637     // we can do this, we don't need to insert spill code.
638     if (lv_)
639       lv_->instructionChanged(MI, fmi);
640     MachineBasicBlock &MBB = *MI->getParent();
641     vrm.virtFolded(reg, MI, i, fmi);
642     mi2iMap_.erase(MI);
643     i2miMap_[index/InstrSlots::NUM] = fmi;
644     mi2iMap_[fmi] = index;
645     MI = MBB.insert(MBB.erase(MI), fmi);
646     ++numFolded;
647     return true;
648   }
649   return false;
650 }
651
652 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
653 /// for addIntervalsForSpills to rewrite uses / defs for the given live range.
654 void LiveIntervals::
655 rewriteInstructionForSpills(const LiveInterval &li,
656                  unsigned id, unsigned index, unsigned end, 
657                  MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
658                  unsigned Slot, int LdSlot,
659                  bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
660                  VirtRegMap &vrm, SSARegMap *RegMap,
661                  const TargetRegisterClass* rc,
662                  SmallVector<int, 4> &ReMatIds,
663                  std::vector<LiveInterval*> &NewLIs) {
664  RestartInstruction:
665   for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
666     MachineOperand& mop = MI->getOperand(i);
667     if (!mop.isRegister())
668       continue;
669     unsigned Reg = mop.getReg();
670     unsigned RegI = Reg;
671     if (Reg == 0 || MRegisterInfo::isPhysicalRegister(Reg))
672       continue;
673     unsigned SubIdx = mop.getSubReg();
674     bool isSubReg = SubIdx != 0;
675     if (Reg != li.reg)
676       continue;
677
678     bool TryFold = !DefIsReMat;
679     bool FoldSS = true;
680     int FoldSlot = Slot;
681     if (DefIsReMat) {
682       // If this is the rematerializable definition MI itself and
683       // all of its uses are rematerialized, simply delete it.
684       if (MI == OrigDefMI && CanDelete) {
685         RemoveMachineInstrFromMaps(MI);
686         MI->eraseFromParent();
687         break;
688       }
689
690       // If def for this use can't be rematerialized, then try folding.
691       TryFold = !OrigDefMI || (OrigDefMI && (MI == OrigDefMI || isLoad));
692       if (isLoad) {
693         // Try fold loads (from stack slot, constant pool, etc.) into uses.
694         FoldSS = isLoadSS;
695         FoldSlot = LdSlot;
696       }
697     }
698
699     // FIXME: fold subreg use
700     if (!isSubReg && TryFold &&
701         tryFoldMemoryOperand(MI, vrm, DefMI, index, i, FoldSS, FoldSlot, Reg))
702       // Folding the load/store can completely change the instruction in
703       // unpredictable ways, rescan it from the beginning.
704       goto RestartInstruction;
705
706     // Create a new virtual register for the spill interval.
707     unsigned NewVReg = RegMap->createVirtualRegister(rc);
708     vrm.grow();
709             
710     // Scan all of the operands of this instruction rewriting operands
711     // to use NewVReg instead of li.reg as appropriate.  We do this for
712     // two reasons:
713     //
714     //   1. If the instr reads the same spilled vreg multiple times, we
715     //      want to reuse the NewVReg.
716     //   2. If the instr is a two-addr instruction, we are required to
717     //      keep the src/dst regs pinned.
718     //
719     // Keep track of whether we replace a use and/or def so that we can
720     // create the spill interval with the appropriate range. 
721     mop.setReg(NewVReg);
722             
723     bool HasUse = mop.isUse();
724     bool HasDef = mop.isDef();
725     for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
726       if (!MI->getOperand(j).isRegister())
727         continue;
728       unsigned RegJ = MI->getOperand(j).getReg();
729       if (RegJ == 0 || MRegisterInfo::isPhysicalRegister(RegJ))
730         continue;
731       if (RegJ == RegI) {
732         MI->getOperand(j).setReg(NewVReg);
733         HasUse |= MI->getOperand(j).isUse();
734         HasDef |= MI->getOperand(j).isDef();
735       }
736     }
737
738     if (DefIsReMat) {
739       vrm.setVirtIsReMaterialized(NewVReg, DefMI/*, CanDelete*/);
740       if (ReMatIds[id] == VirtRegMap::MAX_STACK_SLOT) {
741         // Each valnum may have its own remat id.
742         ReMatIds[id] = vrm.assignVirtReMatId(NewVReg);
743       } else {
744         vrm.assignVirtReMatId(NewVReg, ReMatIds[id]);
745       }
746       if (!CanDelete || (HasUse && HasDef)) {
747         // If this is a two-addr instruction then its use operands are
748         // rematerializable but its def is not. It should be assigned a
749         // stack slot.
750         vrm.assignVirt2StackSlot(NewVReg, Slot);
751       }
752     } else {
753       vrm.assignVirt2StackSlot(NewVReg, Slot);
754     }
755
756     // create a new register interval for this spill / remat.
757     LiveInterval &nI = getOrCreateInterval(NewVReg);
758     assert(nI.empty());
759     NewLIs.push_back(&nI);
760
761     // the spill weight is now infinity as it
762     // cannot be spilled again
763     nI.weight = HUGE_VALF;
764
765     if (HasUse) {
766       LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
767                    nI.getNextValue(~0U, 0, VNInfoAllocator));
768       DOUT << " +" << LR;
769       nI.addRange(LR);
770     }
771     if (HasDef) {
772       LiveRange LR(getDefIndex(index), getStoreIndex(index),
773                    nI.getNextValue(~0U, 0, VNInfoAllocator));
774       DOUT << " +" << LR;
775       nI.addRange(LR);
776     }
777             
778     // update live variables if it is available
779     if (lv_)
780       lv_->addVirtualRegisterKilled(NewVReg, MI);
781             
782     DOUT << "\t\t\t\tAdded new interval: ";
783     nI.print(DOUT, mri_);
784     DOUT << '\n';
785   }
786 }
787
788 void LiveIntervals::
789 rewriteInstructionsForSpills(const LiveInterval &li,
790                     LiveInterval::Ranges::const_iterator &I,
791                     MachineInstr *OrigDefMI, MachineInstr *DefMI,
792                     unsigned Slot, int LdSlot,
793                     bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
794                     VirtRegMap &vrm, SSARegMap *RegMap,
795                     const TargetRegisterClass* rc,
796                     SmallVector<int, 4> &ReMatIds,
797                     std::vector<LiveInterval*> &NewLIs) {
798   unsigned index = getBaseIndex(I->start);
799   unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
800   for (; index != end; index += InstrSlots::NUM) {
801     // skip deleted instructions
802     while (index != end && !getInstructionFromIndex(index))
803       index += InstrSlots::NUM;
804     if (index == end) break;
805
806     MachineInstr *MI = getInstructionFromIndex(index);
807     rewriteInstructionForSpills(li, I->valno->id, index, end, MI,
808                                 OrigDefMI, DefMI, Slot, LdSlot, isLoad,
809                                 isLoadSS, DefIsReMat, CanDelete, vrm,
810                                 RegMap, rc, ReMatIds, NewLIs);
811   }
812 }
813
814 std::vector<LiveInterval*> LiveIntervals::
815 addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm) {
816   // Since this is called after the analysis is done we don't know if
817   // LiveVariables is available
818   lv_ = getAnalysisToUpdate<LiveVariables>();
819
820   assert(li.weight != HUGE_VALF &&
821          "attempt to spill already spilled interval!");
822
823   DOUT << "\t\t\t\tadding intervals for spills for interval: ";
824   li.print(DOUT, mri_);
825   DOUT << '\n';
826
827   std::vector<LiveInterval*> NewLIs;
828   SSARegMap *RegMap = mf_->getSSARegMap();
829   const TargetRegisterClass* rc = RegMap->getRegClass(li.reg);
830
831   unsigned NumValNums = li.getNumValNums();
832   SmallVector<MachineInstr*, 4> ReMatDefs;
833   ReMatDefs.resize(NumValNums, NULL);
834   SmallVector<MachineInstr*, 4> ReMatOrigDefs;
835   ReMatOrigDefs.resize(NumValNums, NULL);
836   SmallVector<int, 4> ReMatIds;
837   ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
838   BitVector ReMatDelete(NumValNums);
839   unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
840
841   bool NeedStackSlot = false;
842   for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
843        i != e; ++i) {
844     const VNInfo *VNI = *i;
845     unsigned VN = VNI->id;
846     unsigned DefIdx = VNI->def;
847     if (DefIdx == ~1U)
848       continue; // Dead val#.
849     // Is the def for the val# rematerializable?
850     MachineInstr *DefMI = (DefIdx == ~0u) ? 0 : getInstructionFromIndex(DefIdx);
851     if (DefMI && isReMaterializable(li, VNI, DefMI)) {
852       // Remember how to remat the def of this val#.
853       ReMatOrigDefs[VN] = DefMI;
854       // Original def may be modified so we have to make a copy here. vrm must
855       // delete these!
856       ReMatDefs[VN] = DefMI = DefMI->clone();
857       vrm.setVirtIsReMaterialized(li.reg, DefMI);
858
859       bool CanDelete = true;
860       for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
861         unsigned KillIdx = VNI->kills[j];
862         MachineInstr *KillMI = (KillIdx & 1)
863           ? NULL : getInstructionFromIndex(KillIdx);
864         // Kill is a phi node, not all of its uses can be rematerialized.
865         // It must not be deleted.
866         if (!KillMI) {
867           CanDelete = false;
868           // Need a stack slot if there is any live range where uses cannot be
869           // rematerialized.
870           NeedStackSlot = true;
871           break;
872         }
873       }
874
875       if (CanDelete)
876         ReMatDelete.set(VN);
877     } else {
878       // Need a stack slot if there is any live range where uses cannot be
879       // rematerialized.
880       NeedStackSlot = true;
881     }
882   }
883
884   // One stack slot per live interval.
885   if (NeedStackSlot)
886     Slot = vrm.assignVirt2StackSlot(li.reg);
887
888   // Create new intervals and rewrite defs and uses.
889   for (LiveInterval::Ranges::const_iterator
890          I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
891     MachineInstr *DefMI = ReMatDefs[I->valno->id];
892     MachineInstr *OrigDefMI = ReMatOrigDefs[I->valno->id];
893     bool DefIsReMat = DefMI != NULL;
894     bool CanDelete = ReMatDelete[I->valno->id];
895     int LdSlot = 0;
896     bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(DefMI, LdSlot);
897     bool isLoad = isLoadSS ||
898       (DefIsReMat && (DefMI->getInstrDescriptor()->Flags & M_LOAD_FLAG));
899     rewriteInstructionsForSpills(li, I, OrigDefMI, DefMI, Slot, LdSlot,
900                                  isLoad, isLoadSS, DefIsReMat, CanDelete,
901                                  vrm, RegMap, rc, ReMatIds, NewLIs);
902   }
903
904   return NewLIs;
905 }