Pasto
[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/Analysis/LoopInfo.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/MRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include <algorithm>
36 #include <cmath>
37 using namespace llvm;
38
39 STATISTIC(numIntervals, "Number of original intervals");
40 STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
41 STATISTIC(numJoins    , "Number of interval joins performed");
42 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
43 STATISTIC(numFolded   , "Number of loads/stores folded into instructions");
44
45 namespace {
46   RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
47
48   static cl::opt<bool>
49   EnableJoining("join-liveintervals",
50                 cl::desc("Coallesce copies (default=true)"),
51                 cl::init(true));
52 }
53
54 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
55   AU.addRequired<LiveVariables>();
56   AU.addPreservedID(PHIEliminationID);
57   AU.addRequiredID(PHIEliminationID);
58   AU.addRequiredID(TwoAddressInstructionPassID);
59   AU.addRequired<LoopInfo>();
60   MachineFunctionPass::getAnalysisUsage(AU);
61 }
62
63 void LiveIntervals::releaseMemory() {
64   mi2iMap_.clear();
65   i2miMap_.clear();
66   r2iMap_.clear();
67   r2rMap_.clear();
68 }
69
70
71 static bool isZeroLengthInterval(LiveInterval *li) {
72   for (LiveInterval::Ranges::const_iterator
73          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
74     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
75       return false;
76   return true;
77 }
78
79
80 /// runOnMachineFunction - Register allocate the whole function
81 ///
82 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
83   mf_ = &fn;
84   tm_ = &fn.getTarget();
85   mri_ = tm_->getRegisterInfo();
86   tii_ = tm_->getInstrInfo();
87   lv_ = &getAnalysis<LiveVariables>();
88   allocatableRegs_ = mri_->getAllocatableSet(fn);
89   r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
90
91   // If this function has any live ins, insert a dummy instruction at the
92   // beginning of the function that we will pretend "defines" the values.  This
93   // is to make the interval analysis simpler by providing a number.
94   if (fn.livein_begin() != fn.livein_end()) {
95     unsigned FirstLiveIn = fn.livein_begin()->first;
96
97     // Find a reg class that contains this live in.
98     const TargetRegisterClass *RC = 0;
99     for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
100            E = mri_->regclass_end(); RCI != E; ++RCI)
101       if ((*RCI)->contains(FirstLiveIn)) {
102         RC = *RCI;
103         break;
104       }
105
106     MachineInstr *OldFirstMI = fn.begin()->begin();
107     mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
108                        FirstLiveIn, FirstLiveIn, RC);
109     assert(OldFirstMI != fn.begin()->begin() &&
110            "copyRetToReg didn't insert anything!");
111   }
112
113   // Number MachineInstrs and MachineBasicBlocks.
114   // Initialize MBB indexes to a sentinal.
115   MBB2IdxMap.resize(mf_->getNumBlockIDs(), ~0U);
116   
117   unsigned MIIndex = 0;
118   for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
119        MBB != E; ++MBB) {
120     // Set the MBB2IdxMap entry for this MBB.
121     MBB2IdxMap[MBB->getNumber()] = MIIndex;
122     
123     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
124          I != E; ++I) {
125       bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
126       assert(inserted && "multiple MachineInstr -> index mappings");
127       i2miMap_.push_back(I);
128       MIIndex += InstrSlots::NUM;
129     }
130   }
131
132   // Note intervals due to live-in values.
133   if (fn.livein_begin() != fn.livein_end()) {
134     MachineBasicBlock *Entry = fn.begin();
135     for (MachineFunction::livein_iterator I = fn.livein_begin(),
136            E = fn.livein_end(); I != E; ++I) {
137       handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
138                                 getOrCreateInterval(I->first), 0);
139       for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
140         handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
141                                   getOrCreateInterval(*AS), 0);
142     }
143   }
144
145   computeIntervals();
146
147   numIntervals += getNumIntervals();
148
149   DOUT << "********** INTERVALS **********\n";
150   for (iterator I = begin(), E = end(); I != E; ++I) {
151     I->second.print(DOUT, mri_);
152     DOUT << "\n";
153   }
154
155   // Join (coallesce) intervals if requested.
156   if (EnableJoining) joinIntervals();
157
158   numIntervalsAfter += getNumIntervals();
159   
160
161   // perform a final pass over the instructions and compute spill
162   // weights, coalesce virtual registers and remove identity moves.
163   const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
164
165   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
166        mbbi != mbbe; ++mbbi) {
167     MachineBasicBlock* mbb = mbbi;
168     unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
169
170     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
171          mii != mie; ) {
172       // if the move will be an identity move delete it
173       unsigned srcReg, dstReg, RegRep;
174       if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
175           (RegRep = rep(srcReg)) == rep(dstReg)) {
176         // remove from def list
177         getOrCreateInterval(RegRep);
178         RemoveMachineInstrFromMaps(mii);
179         mii = mbbi->erase(mii);
180         ++numPeep;
181       }
182       else {
183         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
184           const MachineOperand &mop = mii->getOperand(i);
185           if (mop.isRegister() && mop.getReg() &&
186               MRegisterInfo::isVirtualRegister(mop.getReg())) {
187             // replace register with representative register
188             unsigned reg = rep(mop.getReg());
189             mii->getOperand(i).setReg(reg);
190
191             LiveInterval &RegInt = getInterval(reg);
192             RegInt.weight +=
193               (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
194           }
195         }
196         ++mii;
197       }
198     }
199   }
200
201   
202   for (iterator I = begin(), E = end(); I != E; ++I) {
203     LiveInterval &LI = I->second;
204     if (MRegisterInfo::isVirtualRegister(LI.reg)) {
205       // If the live interval length is essentially zero, i.e. in every live
206       // range the use follows def immediately, it doesn't make sense to spill
207       // it and hope it will be easier to allocate for this li.
208       if (isZeroLengthInterval(&LI))
209         LI.weight = HUGE_VALF;
210       
211       // Divide the weight of the interval by its size.  This encourages 
212       // spilling of intervals that are large and have few uses, and
213       // discourages spilling of small intervals with many uses.
214       unsigned Size = 0;
215       for (LiveInterval::iterator II = LI.begin(), E = LI.end(); II != E;++II)
216         Size += II->end - II->start;
217       
218       LI.weight /= Size;
219     }
220   }
221
222   DEBUG(dump());
223   return true;
224 }
225
226 /// print - Implement the dump method.
227 void LiveIntervals::print(std::ostream &O, const Module* ) const {
228   O << "********** INTERVALS **********\n";
229   for (const_iterator I = begin(), E = end(); I != E; ++I) {
230     I->second.print(DOUT, mri_);
231     DOUT << "\n";
232   }
233
234   O << "********** MACHINEINSTRS **********\n";
235   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
236        mbbi != mbbe; ++mbbi) {
237     O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
238     for (MachineBasicBlock::iterator mii = mbbi->begin(),
239            mie = mbbi->end(); mii != mie; ++mii) {
240       O << getInstructionIndex(mii) << '\t' << *mii;
241     }
242   }
243 }
244
245 /// CreateNewLiveInterval - Create a new live interval with the given live
246 /// ranges. The new live interval will have an infinite spill weight.
247 LiveInterval&
248 LiveIntervals::CreateNewLiveInterval(const LiveInterval *LI,
249                                      const std::vector<LiveRange> &LRs) {
250   const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(LI->reg);
251
252   // Create a new virtual register for the spill interval.
253   unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(RC);
254
255   // Replace the old virtual registers in the machine operands with the shiny
256   // new one.
257   for (std::vector<LiveRange>::const_iterator
258          I = LRs.begin(), E = LRs.end(); I != E; ++I) {
259     unsigned Index = getBaseIndex(I->start);
260     unsigned End = getBaseIndex(I->end - 1) + InstrSlots::NUM;
261
262     for (; Index != End; Index += InstrSlots::NUM) {
263       // Skip deleted instructions
264       while (Index != End && !getInstructionFromIndex(Index))
265         Index += InstrSlots::NUM;
266
267       if (Index == End) break;
268
269       MachineInstr *MI = getInstructionFromIndex(Index);
270
271       for (unsigned J = 0, e = MI->getNumOperands(); J != e; ++J) {
272         MachineOperand &MOp = MI->getOperand(J);
273         if (MOp.isRegister() && rep(MOp.getReg()) == LI->reg)
274           MOp.setReg(NewVReg);
275       }
276     }
277   }
278
279   LiveInterval &NewLI = getOrCreateInterval(NewVReg);
280
281   // The spill weight is now infinity as it cannot be spilled again
282   NewLI.weight = float(HUGE_VAL);
283
284   for (std::vector<LiveRange>::const_iterator
285          I = LRs.begin(), E = LRs.end(); I != E; ++I) {
286     DOUT << "  Adding live range " << *I << " to new interval\n";
287     NewLI.addRange(*I);
288   }
289             
290   DOUT << "Created new live interval " << NewLI << "\n";
291   return NewLI;
292 }
293
294 std::vector<LiveInterval*> LiveIntervals::
295 addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
296   // since this is called after the analysis is done we don't know if
297   // LiveVariables is available
298   lv_ = getAnalysisToUpdate<LiveVariables>();
299
300   std::vector<LiveInterval*> added;
301
302   assert(li.weight != HUGE_VALF &&
303          "attempt to spill already spilled interval!");
304
305   DOUT << "\t\t\t\tadding intervals for spills for interval: ";
306   li.print(DOUT, mri_);
307   DOUT << '\n';
308
309   const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
310
311   for (LiveInterval::Ranges::const_iterator
312          i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
313     unsigned index = getBaseIndex(i->start);
314     unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
315     for (; index != end; index += InstrSlots::NUM) {
316       // skip deleted instructions
317       while (index != end && !getInstructionFromIndex(index))
318         index += InstrSlots::NUM;
319       if (index == end) break;
320
321       MachineInstr *MI = getInstructionFromIndex(index);
322
323     RestartInstruction:
324       for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
325         MachineOperand& mop = MI->getOperand(i);
326         if (mop.isRegister() && mop.getReg() == li.reg) {
327           if (MachineInstr *fmi = mri_->foldMemoryOperand(MI, i, slot)) {
328             // Attempt to fold the memory reference into the instruction.  If we
329             // can do this, we don't need to insert spill code.
330             if (lv_)
331               lv_->instructionChanged(MI, fmi);
332             MachineBasicBlock &MBB = *MI->getParent();
333             vrm.virtFolded(li.reg, MI, i, fmi);
334             mi2iMap_.erase(MI);
335             i2miMap_[index/InstrSlots::NUM] = fmi;
336             mi2iMap_[fmi] = index;
337             MI = MBB.insert(MBB.erase(MI), fmi);
338             ++numFolded;
339             // Folding the load/store can completely change the instruction in
340             // unpredictable ways, rescan it from the beginning.
341             goto RestartInstruction;
342           } else {
343             // Create a new virtual register for the spill interval.
344             unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(rc);
345             
346             // Scan all of the operands of this instruction rewriting operands
347             // to use NewVReg instead of li.reg as appropriate.  We do this for
348             // two reasons:
349             //
350             //   1. If the instr reads the same spilled vreg multiple times, we
351             //      want to reuse the NewVReg.
352             //   2. If the instr is a two-addr instruction, we are required to
353             //      keep the src/dst regs pinned.
354             //
355             // Keep track of whether we replace a use and/or def so that we can
356             // create the spill interval with the appropriate range. 
357             mop.setReg(NewVReg);
358             
359             bool HasUse = mop.isUse();
360             bool HasDef = mop.isDef();
361             for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
362               if (MI->getOperand(j).isReg() &&
363                   MI->getOperand(j).getReg() == li.reg) {
364                 MI->getOperand(j).setReg(NewVReg);
365                 HasUse |= MI->getOperand(j).isUse();
366                 HasDef |= MI->getOperand(j).isDef();
367               }
368             }
369
370             // create a new register for this spill
371             vrm.grow();
372             vrm.assignVirt2StackSlot(NewVReg, slot);
373             LiveInterval &nI = getOrCreateInterval(NewVReg);
374             assert(nI.empty());
375
376             // the spill weight is now infinity as it
377             // cannot be spilled again
378             nI.weight = HUGE_VALF;
379
380             if (HasUse) {
381               LiveRange LR(getLoadIndex(index), getUseIndex(index),
382                            nI.getNextValue(~0U, 0));
383               DOUT << " +" << LR;
384               nI.addRange(LR);
385             }
386             if (HasDef) {
387               LiveRange LR(getDefIndex(index), getStoreIndex(index),
388                            nI.getNextValue(~0U, 0));
389               DOUT << " +" << LR;
390               nI.addRange(LR);
391             }
392             
393             added.push_back(&nI);
394
395             // update live variables if it is available
396             if (lv_)
397               lv_->addVirtualRegisterKilled(NewVReg, MI);
398             
399             DOUT << "\t\t\t\tadded new interval: ";
400             nI.print(DOUT, mri_);
401             DOUT << '\n';
402           }
403         }
404       }
405     }
406   }
407
408   return added;
409 }
410
411 void LiveIntervals::printRegName(unsigned reg) const {
412   if (MRegisterInfo::isPhysicalRegister(reg))
413     cerr << mri_->getName(reg);
414   else
415     cerr << "%reg" << reg;
416 }
417
418 /// isReDefinedByTwoAddr - Returns true if the Reg re-definition is due to
419 /// two addr elimination.
420 static bool isReDefinedByTwoAddr(MachineInstr *MI, unsigned Reg,
421                                 const TargetInstrInfo *TII) {
422   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
423     MachineOperand &MO1 = MI->getOperand(i);
424     if (MO1.isRegister() && MO1.isDef() && MO1.getReg() == Reg) {
425       for (unsigned j = i+1; j < e; ++j) {
426         MachineOperand &MO2 = MI->getOperand(j);
427         if (MO2.isRegister() && MO2.isUse() && MO2.getReg() == Reg &&
428             MI->getInstrDescriptor()->
429             getOperandConstraint(j, TOI::TIED_TO) == (int)i)
430           return true;
431       }
432     }
433   }
434   return false;
435 }
436
437 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
438                                              MachineBasicBlock::iterator mi,
439                                              unsigned MIIdx,
440                                              LiveInterval &interval) {
441   DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
442   LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
443
444   // Virtual registers may be defined multiple times (due to phi
445   // elimination and 2-addr elimination).  Much of what we do only has to be
446   // done once for the vreg.  We use an empty interval to detect the first
447   // time we see a vreg.
448   if (interval.empty()) {
449     // Get the Idx of the defining instructions.
450     unsigned defIndex = getDefIndex(MIIdx);
451
452     unsigned ValNum;
453     unsigned SrcReg, DstReg;
454     if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
455       ValNum = interval.getNextValue(~0U, 0);
456     else
457       ValNum = interval.getNextValue(defIndex, SrcReg);
458     
459     assert(ValNum == 0 && "First value in interval is not 0?");
460     ValNum = 0;  // Clue in the optimizer.
461
462     // Loop over all of the blocks that the vreg is defined in.  There are
463     // two cases we have to handle here.  The most common case is a vreg
464     // whose lifetime is contained within a basic block.  In this case there
465     // will be a single kill, in MBB, which comes after the definition.
466     if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
467       // FIXME: what about dead vars?
468       unsigned killIdx;
469       if (vi.Kills[0] != mi)
470         killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
471       else
472         killIdx = defIndex+1;
473
474       // If the kill happens after the definition, we have an intra-block
475       // live range.
476       if (killIdx > defIndex) {
477         assert(vi.AliveBlocks.empty() &&
478                "Shouldn't be alive across any blocks!");
479         LiveRange LR(defIndex, killIdx, ValNum);
480         interval.addRange(LR);
481         DOUT << " +" << LR << "\n";
482         return;
483       }
484     }
485
486     // The other case we handle is when a virtual register lives to the end
487     // of the defining block, potentially live across some blocks, then is
488     // live into some number of blocks, but gets killed.  Start by adding a
489     // range that goes from this definition to the end of the defining block.
490     LiveRange NewLR(defIndex,
491                     getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
492                     ValNum);
493     DOUT << " +" << NewLR;
494     interval.addRange(NewLR);
495
496     // Iterate over all of the blocks that the variable is completely
497     // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
498     // live interval.
499     for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
500       if (vi.AliveBlocks[i]) {
501         MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
502         if (!MBB->empty()) {
503           LiveRange LR(getMBBStartIdx(i),
504                        getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
505                        ValNum);
506           interval.addRange(LR);
507           DOUT << " +" << LR;
508         }
509       }
510     }
511
512     // Finally, this virtual register is live from the start of any killing
513     // block to the 'use' slot of the killing instruction.
514     for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
515       MachineInstr *Kill = vi.Kills[i];
516       LiveRange LR(getMBBStartIdx(Kill->getParent()),
517                    getUseIndex(getInstructionIndex(Kill))+1,
518                    ValNum);
519       interval.addRange(LR);
520       DOUT << " +" << LR;
521     }
522
523   } else {
524     // If this is the second time we see a virtual register definition, it
525     // must be due to phi elimination or two addr elimination.  If this is
526     // the result of two address elimination, then the vreg is one of the
527     // def-and-use register operand.
528     if (isReDefinedByTwoAddr(mi, interval.reg, tii_)) {
529       // If this is a two-address definition, then we have already processed
530       // the live range.  The only problem is that we didn't realize there
531       // are actually two values in the live interval.  Because of this we
532       // need to take the LiveRegion that defines this register and split it
533       // into two values.
534       unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
535       unsigned RedefIndex = getDefIndex(MIIdx);
536
537       // Delete the initial value, which should be short and continuous,
538       // because the 2-addr copy must be in the same MBB as the redef.
539       interval.removeRange(DefIndex, RedefIndex);
540
541       // Two-address vregs should always only be redefined once.  This means
542       // that at this point, there should be exactly one value number in it.
543       assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
544
545       // The new value number (#1) is defined by the instruction we claimed
546       // defined value #0.
547       unsigned ValNo = interval.getNextValue(0, 0);
548       interval.setValueNumberInfo(1, interval.getValNumInfo(0));
549       
550       // Value#0 is now defined by the 2-addr instruction.
551       interval.setValueNumberInfo(0, std::make_pair(~0U, 0U));
552       
553       // Add the new live interval which replaces the range for the input copy.
554       LiveRange LR(DefIndex, RedefIndex, ValNo);
555       DOUT << " replace range with " << LR;
556       interval.addRange(LR);
557
558       // If this redefinition is dead, we need to add a dummy unit live
559       // range covering the def slot.
560       if (lv_->RegisterDefIsDead(mi, interval.reg))
561         interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
562
563       DOUT << "RESULT: ";
564       interval.print(DOUT, mri_);
565
566     } else {
567       // Otherwise, this must be because of phi elimination.  If this is the
568       // first redefinition of the vreg that we have seen, go back and change
569       // the live range in the PHI block to be a different value number.
570       if (interval.containsOneValue()) {
571         assert(vi.Kills.size() == 1 &&
572                "PHI elimination vreg should have one kill, the PHI itself!");
573
574         // Remove the old range that we now know has an incorrect number.
575         MachineInstr *Killer = vi.Kills[0];
576         unsigned Start = getMBBStartIdx(Killer->getParent());
577         unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
578         DOUT << "Removing [" << Start << "," << End << "] from: ";
579         interval.print(DOUT, mri_); DOUT << "\n";
580         interval.removeRange(Start, End);
581         DOUT << "RESULT: "; interval.print(DOUT, mri_);
582
583         // Replace the interval with one of a NEW value number.  Note that this
584         // value number isn't actually defined by an instruction, weird huh? :)
585         LiveRange LR(Start, End, interval.getNextValue(~0U, 0));
586         DOUT << " replace range with " << LR;
587         interval.addRange(LR);
588         DOUT << "RESULT: "; interval.print(DOUT, mri_);
589       }
590
591       // In the case of PHI elimination, each variable definition is only
592       // live until the end of the block.  We've already taken care of the
593       // rest of the live range.
594       unsigned defIndex = getDefIndex(MIIdx);
595       
596       unsigned ValNum;
597       unsigned SrcReg, DstReg;
598       if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
599         ValNum = interval.getNextValue(~0U, 0);
600       else
601         ValNum = interval.getNextValue(defIndex, SrcReg);
602       
603       LiveRange LR(defIndex,
604                    getInstructionIndex(&mbb->back()) + InstrSlots::NUM, ValNum);
605       interval.addRange(LR);
606       DOUT << " +" << LR;
607     }
608   }
609
610   DOUT << '\n';
611 }
612
613 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
614                                               MachineBasicBlock::iterator mi,
615                                               unsigned MIIdx,
616                                               LiveInterval &interval,
617                                               unsigned SrcReg) {
618   // A physical register cannot be live across basic block, so its
619   // lifetime must end somewhere in its defining basic block.
620   DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
621
622   unsigned baseIndex = MIIdx;
623   unsigned start = getDefIndex(baseIndex);
624   unsigned end = start;
625
626   // If it is not used after definition, it is considered dead at
627   // the instruction defining it. Hence its interval is:
628   // [defSlot(def), defSlot(def)+1)
629   if (lv_->RegisterDefIsDead(mi, interval.reg)) {
630     DOUT << " dead";
631     end = getDefIndex(start) + 1;
632     goto exit;
633   }
634
635   // If it is not dead on definition, it must be killed by a
636   // subsequent instruction. Hence its interval is:
637   // [defSlot(def), useSlot(kill)+1)
638   while (++mi != MBB->end()) {
639     baseIndex += InstrSlots::NUM;
640     if (lv_->KillsRegister(mi, interval.reg)) {
641       DOUT << " killed";
642       end = getUseIndex(baseIndex) + 1;
643       goto exit;
644     } else if (lv_->ModifiesRegister(mi, interval.reg)) {
645       // Another instruction redefines the register before it is ever read.
646       // Then the register is essentially dead at the instruction that defines
647       // it. Hence its interval is:
648       // [defSlot(def), defSlot(def)+1)
649       DOUT << " dead";
650       end = getDefIndex(start) + 1;
651       goto exit;
652     }
653   }
654   
655   // The only case we should have a dead physreg here without a killing or
656   // instruction where we know it's dead is if it is live-in to the function
657   // and never used.
658   assert(!SrcReg && "physreg was not killed in defining block!");
659   end = getDefIndex(start) + 1;  // It's dead.
660
661 exit:
662   assert(start < end && "did not find end of interval?");
663
664   LiveRange LR(start, end, interval.getNextValue(SrcReg != 0 ? start : ~0U,
665                                                  SrcReg));
666   interval.addRange(LR);
667   DOUT << " +" << LR << '\n';
668 }
669
670 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
671                                       MachineBasicBlock::iterator MI,
672                                       unsigned MIIdx,
673                                       unsigned reg) {
674   if (MRegisterInfo::isVirtualRegister(reg))
675     handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
676   else if (allocatableRegs_[reg]) {
677     unsigned SrcReg, DstReg;
678     if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
679       SrcReg = 0;
680     handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
681     for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
682       handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
683   }
684 }
685
686 /// computeIntervals - computes the live intervals for virtual
687 /// registers. for some ordering of the machine instructions [1,N] a
688 /// live interval is an interval [i, j) where 1 <= i <= j < N for
689 /// which a variable is live
690 void LiveIntervals::computeIntervals() {
691   DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
692        << "********** Function: "
693        << ((Value*)mf_->getFunction())->getName() << '\n';
694   bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
695
696   // Track the index of the current machine instr.
697   unsigned MIIndex = 0;
698   for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
699        MBBI != E; ++MBBI) {
700     MachineBasicBlock *MBB = MBBI;
701     DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
702
703     MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
704     if (IgnoreFirstInstr) {
705       ++MI;
706       IgnoreFirstInstr = false;
707       MIIndex += InstrSlots::NUM;
708     }
709     
710     for (; MI != miEnd; ++MI) {
711       DOUT << MIIndex << "\t" << *MI;
712
713       // Handle defs.
714       for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
715         MachineOperand &MO = MI->getOperand(i);
716         // handle register defs - build intervals
717         if (MO.isRegister() && MO.getReg() && MO.isDef())
718           handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
719       }
720       
721       MIIndex += InstrSlots::NUM;
722     }
723   }
724 }
725
726 /// AdjustCopiesBackFrom - We found a non-trivially-coallescable copy with IntA
727 /// being the source and IntB being the dest, thus this defines a value number
728 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
729 /// see if we can merge these two pieces of B into a single value number,
730 /// eliminating a copy.  For example:
731 ///
732 ///  A3 = B0
733 ///    ...
734 ///  B1 = A3      <- this copy
735 ///
736 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
737 /// value number to be replaced with B0 (which simplifies the B liveinterval).
738 ///
739 /// This returns true if an interval was modified.
740 ///
741 bool LiveIntervals::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
742                                          MachineInstr *CopyMI) {
743   unsigned CopyIdx = getDefIndex(getInstructionIndex(CopyMI));
744
745   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
746   // the example above.
747   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
748   unsigned BValNo = BLR->ValId;
749   
750   // Get the location that B is defined at.  Two options: either this value has
751   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
752   // can't process it.
753   unsigned BValNoDefIdx = IntB.getInstForValNum(BValNo);
754   if (BValNoDefIdx == ~0U) return false;
755   assert(BValNoDefIdx == CopyIdx &&
756          "Copy doesn't define the value?");
757   
758   // AValNo is the value number in A that defines the copy, A0 in the example.
759   LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
760   unsigned AValNo = AValLR->ValId;
761   
762   // If AValNo is defined as a copy from IntB, we can potentially process this.
763   
764   // Get the instruction that defines this value number.
765   unsigned SrcReg = IntA.getSrcRegForValNum(AValNo);
766   if (!SrcReg) return false;  // Not defined by a copy.
767     
768   // If the value number is not defined by a copy instruction, ignore it.
769     
770   // If the source register comes from an interval other than IntB, we can't
771   // handle this.
772   if (rep(SrcReg) != IntB.reg) return false;
773   
774   // Get the LiveRange in IntB that this value number starts with.
775   unsigned AValNoInstIdx = IntA.getInstForValNum(AValNo);
776   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNoInstIdx-1);
777   
778   // Make sure that the end of the live range is inside the same block as
779   // CopyMI.
780   MachineInstr *ValLREndInst = getInstructionFromIndex(ValLR->end-1);
781   if (!ValLREndInst || 
782       ValLREndInst->getParent() != CopyMI->getParent()) return false;
783
784   // Okay, we now know that ValLR ends in the same block that the CopyMI
785   // live-range starts.  If there are no intervening live ranges between them in
786   // IntB, we can merge them.
787   if (ValLR+1 != BLR) return false;
788   
789   DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
790   
791   // We are about to delete CopyMI, so need to remove it as the 'instruction
792   // that defines this value #'.
793   IntB.setValueNumberInfo(BValNo, std::make_pair(~0U, 0));
794   
795   // Okay, we can merge them.  We need to insert a new liverange:
796   // [ValLR.end, BLR.begin) of either value number, then we merge the
797   // two value numbers.
798   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
799   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
800
801   // If the IntB live range is assigned to a physical register, and if that
802   // physreg has aliases, 
803   if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
804     for (const unsigned *AS = mri_->getAliasSet(IntB.reg); *AS; ++AS) {
805       LiveInterval &AliasLI = getInterval(*AS);
806       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
807                                  AliasLI.getNextValue(~0U, 0)));
808     }
809   }
810
811   // Okay, merge "B1" into the same value number as "B0".
812   if (BValNo != ValLR->ValId)
813     IntB.MergeValueNumberInto(BValNo, ValLR->ValId);
814   DOUT << "   result = "; IntB.print(DOUT, mri_);
815   DOUT << "\n";
816   
817   // Finally, delete the copy instruction.
818   RemoveMachineInstrFromMaps(CopyMI);
819   CopyMI->eraseFromParent();
820   ++numPeep;
821   return true;
822 }
823
824
825 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
826 /// which are the src/dst of the copy instruction CopyMI.  This returns true
827 /// if the copy was successfully coallesced away, or if it is never possible
828 /// to coallesce these this copy, due to register constraints.  It returns
829 /// false if it is not currently possible to coallesce this interval, but
830 /// it may be possible if other things get coallesced.
831 bool LiveIntervals::JoinCopy(MachineInstr *CopyMI,
832                              unsigned SrcReg, unsigned DstReg) {
833   DOUT << getInstructionIndex(CopyMI) << '\t' << *CopyMI;
834   
835   // Get representative registers.
836   SrcReg = rep(SrcReg);
837   DstReg = rep(DstReg);
838   
839   // If they are already joined we continue.
840   if (SrcReg == DstReg) {
841     DOUT << "\tCopy already coallesced.\n";
842     return true;  // Not coallescable.
843   }
844   
845   // If they are both physical registers, we cannot join them.
846   if (MRegisterInfo::isPhysicalRegister(SrcReg) &&
847       MRegisterInfo::isPhysicalRegister(DstReg)) {
848     DOUT << "\tCan not coallesce physregs.\n";
849     return true;  // Not coallescable.
850   }
851   
852   // We only join virtual registers with allocatable physical registers.
853   if (MRegisterInfo::isPhysicalRegister(SrcReg) && !allocatableRegs_[SrcReg]){
854     DOUT << "\tSrc reg is unallocatable physreg.\n";
855     return true;  // Not coallescable.
856   }
857   if (MRegisterInfo::isPhysicalRegister(DstReg) && !allocatableRegs_[DstReg]){
858     DOUT << "\tDst reg is unallocatable physreg.\n";
859     return true;  // Not coallescable.
860   }
861   
862   // If they are not of the same register class, we cannot join them.
863   if (differingRegisterClasses(SrcReg, DstReg)) {
864     DOUT << "\tSrc/Dest are different register classes.\n";
865     return true;  // Not coallescable.
866   }
867   
868   LiveInterval &SrcInt = getInterval(SrcReg);
869   LiveInterval &DestInt = getInterval(DstReg);
870   assert(SrcInt.reg == SrcReg && DestInt.reg == DstReg &&
871          "Register mapping is horribly broken!");
872   
873   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
874   DOUT << " and "; DestInt.print(DOUT, mri_);
875   DOUT << ": ";
876     
877   // Okay, attempt to join these two intervals.  On failure, this returns false.
878   // Otherwise, if one of the intervals being joined is a physreg, this method
879   // always canonicalizes DestInt to be it.  The output "SrcInt" will not have
880   // been modified, so we can use this information below to update aliases.
881   if (!JoinIntervals(DestInt, SrcInt)) {
882     // Coallescing failed.
883     
884     // If we can eliminate the copy without merging the live ranges, do so now.
885     if (AdjustCopiesBackFrom(SrcInt, DestInt, CopyMI))
886       return true;
887
888     // Otherwise, we are unable to join the intervals.
889     DOUT << "Interference!\n";
890     return false;
891   }
892
893   bool Swapped = SrcReg == DestInt.reg;
894   if (Swapped)
895     std::swap(SrcReg, DstReg);
896   assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
897          "LiveInterval::join didn't work right!");
898                                
899   // If we're about to merge live ranges into a physical register live range,
900   // we have to update any aliased register's live ranges to indicate that they
901   // have clobbered values for this range.
902   if (MRegisterInfo::isPhysicalRegister(DstReg)) {
903     for (const unsigned *AS = mri_->getAliasSet(DstReg); *AS; ++AS)
904       getInterval(*AS).MergeInClobberRanges(SrcInt);
905   }
906
907   DOUT << "\n\t\tJoined.  Result = "; DestInt.print(DOUT, mri_);
908   DOUT << "\n";
909   
910   // If the intervals were swapped by Join, swap them back so that the register
911   // mapping (in the r2i map) is correct.
912   if (Swapped) SrcInt.swap(DestInt);
913   r2iMap_.erase(SrcReg);
914   r2rMap_[SrcReg] = DstReg;
915
916   // Finally, delete the copy instruction.
917   RemoveMachineInstrFromMaps(CopyMI);
918   CopyMI->eraseFromParent();
919   ++numPeep;
920   ++numJoins;
921   return true;
922 }
923
924 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
925 /// compute what the resultant value numbers for each value in the input two
926 /// ranges will be.  This is complicated by copies between the two which can
927 /// and will commonly cause multiple value numbers to be merged into one.
928 ///
929 /// VN is the value number that we're trying to resolve.  InstDefiningValue
930 /// keeps track of the new InstDefiningValue assignment for the result
931 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
932 /// whether a value in this or other is a copy from the opposite set.
933 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
934 /// already been assigned.
935 ///
936 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
937 /// contains the value number the copy is from.
938 ///
939 static unsigned ComputeUltimateVN(unsigned VN,
940                                   SmallVector<std::pair<unsigned,
941                                                 unsigned>, 16> &ValueNumberInfo,
942                                   SmallVector<int, 16> &ThisFromOther,
943                                   SmallVector<int, 16> &OtherFromThis,
944                                   SmallVector<int, 16> &ThisValNoAssignments,
945                                   SmallVector<int, 16> &OtherValNoAssignments,
946                                   LiveInterval &ThisLI, LiveInterval &OtherLI) {
947   // If the VN has already been computed, just return it.
948   if (ThisValNoAssignments[VN] >= 0)
949     return ThisValNoAssignments[VN];
950 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
951   
952   // If this val is not a copy from the other val, then it must be a new value
953   // number in the destination.
954   int OtherValNo = ThisFromOther[VN];
955   if (OtherValNo == -1) {
956     ValueNumberInfo.push_back(ThisLI.getValNumInfo(VN));
957     return ThisValNoAssignments[VN] = ValueNumberInfo.size()-1;
958   }
959
960   // Otherwise, this *is* a copy from the RHS.  If the other side has already
961   // been computed, return it.
962   if (OtherValNoAssignments[OtherValNo] >= 0)
963     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo];
964   
965   // Mark this value number as currently being computed, then ask what the
966   // ultimate value # of the other value is.
967   ThisValNoAssignments[VN] = -2;
968   unsigned UltimateVN =
969     ComputeUltimateVN(OtherValNo, ValueNumberInfo,
970                       OtherFromThis, ThisFromOther,
971                       OtherValNoAssignments, ThisValNoAssignments,
972                       OtherLI, ThisLI);
973   return ThisValNoAssignments[VN] = UltimateVN;
974 }
975
976 static bool InVector(unsigned Val, const SmallVector<unsigned, 8> &V) {
977   return std::find(V.begin(), V.end(), Val) != V.end();
978 }
979
980 /// SimpleJoin - Attempt to joint the specified interval into this one. The
981 /// caller of this method must guarantee that the RHS only contains a single
982 /// value number and that the RHS is not defined by a copy from this
983 /// interval.  This returns false if the intervals are not joinable, or it
984 /// joins them and returns true.
985 bool LiveIntervals::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
986   assert(RHS.containsOneValue());
987   
988   // Some number (potentially more than one) value numbers in the current
989   // interval may be defined as copies from the RHS.  Scan the overlapping
990   // portions of the LHS and RHS, keeping track of this and looking for
991   // overlapping live ranges that are NOT defined as copies.  If these exist, we
992   // cannot coallesce.
993   
994   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
995   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
996   
997   if (LHSIt->start < RHSIt->start) {
998     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
999     if (LHSIt != LHS.begin()) --LHSIt;
1000   } else if (RHSIt->start < LHSIt->start) {
1001     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1002     if (RHSIt != RHS.begin()) --RHSIt;
1003   }
1004   
1005   SmallVector<unsigned, 8> EliminatedLHSVals;
1006   
1007   while (1) {
1008     // Determine if these live intervals overlap.
1009     bool Overlaps = false;
1010     if (LHSIt->start <= RHSIt->start)
1011       Overlaps = LHSIt->end > RHSIt->start;
1012     else
1013       Overlaps = RHSIt->end > LHSIt->start;
1014     
1015     // If the live intervals overlap, there are two interesting cases: if the
1016     // LHS interval is defined by a copy from the RHS, it's ok and we record
1017     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1018     // coallesce these live ranges and we bail out.
1019     if (Overlaps) {
1020       // If we haven't already recorded that this value # is safe, check it.
1021       if (!InVector(LHSIt->ValId, EliminatedLHSVals)) {
1022         // Copy from the RHS?
1023         unsigned SrcReg = LHS.getSrcRegForValNum(LHSIt->ValId);
1024         if (rep(SrcReg) != RHS.reg)
1025           return false;    // Nope, bail out.
1026         
1027         EliminatedLHSVals.push_back(LHSIt->ValId);
1028       }
1029       
1030       // We know this entire LHS live range is okay, so skip it now.
1031       if (++LHSIt == LHSEnd) break;
1032       continue;
1033     }
1034     
1035     if (LHSIt->end < RHSIt->end) {
1036       if (++LHSIt == LHSEnd) break;
1037     } else {
1038       // One interesting case to check here.  It's possible that we have
1039       // something like "X3 = Y" which defines a new value number in the LHS,
1040       // and is the last use of this liverange of the RHS.  In this case, we
1041       // want to notice this copy (so that it gets coallesced away) even though
1042       // the live ranges don't actually overlap.
1043       if (LHSIt->start == RHSIt->end) {
1044         if (InVector(LHSIt->ValId, EliminatedLHSVals)) {
1045           // We already know that this value number is going to be merged in
1046           // if coallescing succeeds.  Just skip the liverange.
1047           if (++LHSIt == LHSEnd) break;
1048         } else {
1049           // Otherwise, if this is a copy from the RHS, mark it as being merged
1050           // in.
1051           if (rep(LHS.getSrcRegForValNum(LHSIt->ValId)) == RHS.reg) {
1052             EliminatedLHSVals.push_back(LHSIt->ValId);
1053
1054             // We know this entire LHS live range is okay, so skip it now.
1055             if (++LHSIt == LHSEnd) break;
1056           }
1057         }
1058       }
1059       
1060       if (++RHSIt == RHSEnd) break;
1061     }
1062   }
1063   
1064   // If we got here, we know that the coallescing will be successful and that
1065   // the value numbers in EliminatedLHSVals will all be merged together.  Since
1066   // the most common case is that EliminatedLHSVals has a single number, we
1067   // optimize for it: if there is more than one value, we merge them all into
1068   // the lowest numbered one, then handle the interval as if we were merging
1069   // with one value number.
1070   unsigned LHSValNo;
1071   if (EliminatedLHSVals.size() > 1) {
1072     // Loop through all the equal value numbers merging them into the smallest
1073     // one.
1074     unsigned Smallest = EliminatedLHSVals[0];
1075     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1076       if (EliminatedLHSVals[i] < Smallest) {
1077         // Merge the current notion of the smallest into the smaller one.
1078         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1079         Smallest = EliminatedLHSVals[i];
1080       } else {
1081         // Merge into the smallest.
1082         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1083       }
1084     }
1085     LHSValNo = Smallest;
1086   } else {
1087     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1088     LHSValNo = EliminatedLHSVals[0];
1089   }
1090   
1091   // Okay, now that there is a single LHS value number that we're merging the
1092   // RHS into, update the value number info for the LHS to indicate that the
1093   // value number is defined where the RHS value number was.
1094   LHS.setValueNumberInfo(LHSValNo, RHS.getValNumInfo(0));
1095   
1096   // Okay, the final step is to loop over the RHS live intervals, adding them to
1097   // the LHS.
1098   LHS.MergeRangesInAsValue(RHS, LHSValNo);
1099   LHS.weight += RHS.weight;
1100   
1101   return true;
1102 }
1103
1104 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1105 /// returns false.  Otherwise, if one of the intervals being joined is a
1106 /// physreg, this method always canonicalizes LHS to be it.  The output
1107 /// "RHS" will not have been modified, so we can use this information
1108 /// below to update aliases.
1109 bool LiveIntervals::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS) {
1110   // Compute the final value assignment, assuming that the live ranges can be
1111   // coallesced.
1112   SmallVector<int, 16> LHSValNoAssignments;
1113   SmallVector<int, 16> RHSValNoAssignments;
1114   SmallVector<std::pair<unsigned,unsigned>, 16> ValueNumberInfo;
1115                           
1116   // Compute ultimate value numbers for the LHS and RHS values.
1117   if (RHS.containsOneValue()) {
1118     // Copies from a liveinterval with a single value are simple to handle and
1119     // very common, handle the special case here.  This is important, because
1120     // often RHS is small and LHS is large (e.g. a physreg).
1121     
1122     // Find out if the RHS is defined as a copy from some value in the LHS.
1123     int RHSValID = -1;
1124     std::pair<unsigned,unsigned> RHSValNoInfo;
1125     unsigned RHSSrcReg = RHS.getSrcRegForValNum(0);
1126     if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
1127       // If RHS is not defined as a copy from the LHS, we can use simpler and
1128       // faster checks to see if the live ranges are coallescable.  This joiner
1129       // can't swap the LHS/RHS intervals though.
1130       if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
1131         return SimpleJoin(LHS, RHS);
1132       } else {
1133         RHSValNoInfo = RHS.getValNumInfo(0);
1134       }
1135     } else {
1136       // It was defined as a copy from the LHS, find out what value # it is.
1137       unsigned ValInst = RHS.getInstForValNum(0);
1138       RHSValID = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1139       RHSValNoInfo = LHS.getValNumInfo(RHSValID);
1140     }
1141     
1142     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1143     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1144     ValueNumberInfo.resize(LHS.getNumValNums());
1145     
1146     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1147     // should now get updated.
1148     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1149       if (unsigned LHSSrcReg = LHS.getSrcRegForValNum(VN)) {
1150         if (rep(LHSSrcReg) != RHS.reg) {
1151           // If this is not a copy from the RHS, its value number will be
1152           // unmodified by the coallescing.
1153           ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1154           LHSValNoAssignments[VN] = VN;
1155         } else if (RHSValID == -1) {
1156           // Otherwise, it is a copy from the RHS, and we don't already have a
1157           // value# for it.  Keep the current value number, but remember it.
1158           LHSValNoAssignments[VN] = RHSValID = VN;
1159           ValueNumberInfo[VN] = RHSValNoInfo;
1160         } else {
1161           // Otherwise, use the specified value #.
1162           LHSValNoAssignments[VN] = RHSValID;
1163           if (VN != (unsigned)RHSValID)
1164             ValueNumberInfo[VN].first = ~1U;
1165           else
1166             ValueNumberInfo[VN] = RHSValNoInfo;
1167         }
1168       } else {
1169         ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1170         LHSValNoAssignments[VN] = VN;
1171       }
1172     }
1173     
1174     assert(RHSValID != -1 && "Didn't find value #?");
1175     RHSValNoAssignments[0] = RHSValID;
1176     
1177   } else {
1178     // Loop over the value numbers of the LHS, seeing if any are defined from
1179     // the RHS.
1180     SmallVector<int, 16> LHSValsDefinedFromRHS;
1181     LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), -1);
1182     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1183       unsigned ValSrcReg = LHS.getSrcRegForValNum(VN);
1184       if (ValSrcReg == 0)  // Src not defined by a copy?
1185         continue;
1186       
1187       // DstReg is known to be a register in the LHS interval.  If the src is
1188       // from the RHS interval, we can use its value #.
1189       if (rep(ValSrcReg) != RHS.reg)
1190         continue;
1191       
1192       // Figure out the value # from the RHS.
1193       unsigned ValInst = LHS.getInstForValNum(VN);
1194       LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(ValInst-1)->ValId;
1195     }
1196     
1197     // Loop over the value numbers of the RHS, seeing if any are defined from
1198     // the LHS.
1199     SmallVector<int, 16> RHSValsDefinedFromLHS;
1200     RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), -1);
1201     for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1202       unsigned ValSrcReg = RHS.getSrcRegForValNum(VN);
1203       if (ValSrcReg == 0)  // Src not defined by a copy?
1204         continue;
1205       
1206       // DstReg is known to be a register in the RHS interval.  If the src is
1207       // from the LHS interval, we can use its value #.
1208       if (rep(ValSrcReg) != LHS.reg)
1209         continue;
1210       
1211       // Figure out the value # from the LHS.
1212       unsigned ValInst = RHS.getInstForValNum(VN);
1213       RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1214     }
1215     
1216     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1217     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1218     ValueNumberInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1219     
1220     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1221       if (LHSValNoAssignments[VN] >= 0 || LHS.getInstForValNum(VN) == ~2U) 
1222         continue;
1223       ComputeUltimateVN(VN, ValueNumberInfo,
1224                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1225                         LHSValNoAssignments, RHSValNoAssignments, LHS, RHS);
1226     }
1227     for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1228       if (RHSValNoAssignments[VN] >= 0 || RHS.getInstForValNum(VN) == ~2U)
1229         continue;
1230       // If this value number isn't a copy from the LHS, it's a new number.
1231       if (RHSValsDefinedFromLHS[VN] == -1) {
1232         ValueNumberInfo.push_back(RHS.getValNumInfo(VN));
1233         RHSValNoAssignments[VN] = ValueNumberInfo.size()-1;
1234         continue;
1235       }
1236       
1237       ComputeUltimateVN(VN, ValueNumberInfo,
1238                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1239                         RHSValNoAssignments, LHSValNoAssignments, RHS, LHS);
1240     }
1241   }
1242   
1243   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1244   // interval lists to see if these intervals are coallescable.
1245   LiveInterval::const_iterator I = LHS.begin();
1246   LiveInterval::const_iterator IE = LHS.end();
1247   LiveInterval::const_iterator J = RHS.begin();
1248   LiveInterval::const_iterator JE = RHS.end();
1249   
1250   // Skip ahead until the first place of potential sharing.
1251   if (I->start < J->start) {
1252     I = std::upper_bound(I, IE, J->start);
1253     if (I != LHS.begin()) --I;
1254   } else if (J->start < I->start) {
1255     J = std::upper_bound(J, JE, I->start);
1256     if (J != RHS.begin()) --J;
1257   }
1258   
1259   while (1) {
1260     // Determine if these two live ranges overlap.
1261     bool Overlaps;
1262     if (I->start < J->start) {
1263       Overlaps = I->end > J->start;
1264     } else {
1265       Overlaps = J->end > I->start;
1266     }
1267
1268     // If so, check value # info to determine if they are really different.
1269     if (Overlaps) {
1270       // If the live range overlap will map to the same value number in the
1271       // result liverange, we can still coallesce them.  If not, we can't.
1272       if (LHSValNoAssignments[I->ValId] != RHSValNoAssignments[J->ValId])
1273         return false;
1274     }
1275     
1276     if (I->end < J->end) {
1277       ++I;
1278       if (I == IE) break;
1279     } else {
1280       ++J;
1281       if (J == JE) break;
1282     }
1283   }
1284
1285   // If we get here, we know that we can coallesce the live ranges.  Ask the
1286   // intervals to coallesce themselves now.
1287   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0],
1288            ValueNumberInfo);
1289   return true;
1290 }
1291
1292
1293 namespace {
1294   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1295   // depth of the basic block (the unsigned), and then on the MBB number.
1296   struct DepthMBBCompare {
1297     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1298     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1299       if (LHS.first > RHS.first) return true;   // Deeper loops first
1300       return LHS.first == RHS.first &&
1301         LHS.second->getNumber() < RHS.second->getNumber();
1302     }
1303   };
1304 }
1305
1306
1307 void LiveIntervals::CopyCoallesceInMBB(MachineBasicBlock *MBB,
1308                                        std::vector<CopyRec> &TryAgain) {
1309   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1310   
1311   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1312        MII != E;) {
1313     MachineInstr *Inst = MII++;
1314     
1315     // If this isn't a copy, we can't join intervals.
1316     unsigned SrcReg, DstReg;
1317     if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
1318     
1319     if (!JoinCopy(Inst, SrcReg, DstReg))
1320       TryAgain.push_back(getCopyRec(Inst, SrcReg, DstReg));
1321   }
1322 }
1323
1324
1325 void LiveIntervals::joinIntervals() {
1326   DOUT << "********** JOINING INTERVALS ***********\n";
1327
1328   std::vector<CopyRec> TryAgainList;
1329   
1330   const LoopInfo &LI = getAnalysis<LoopInfo>();
1331   if (LI.begin() == LI.end()) {
1332     // If there are no loops in the function, join intervals in function order.
1333     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1334          I != E; ++I)
1335       CopyCoallesceInMBB(I, TryAgainList);
1336   } else {
1337     // Otherwise, join intervals in inner loops before other intervals.
1338     // Unfortunately we can't just iterate over loop hierarchy here because
1339     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1340     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1341     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1342          I != E; ++I)
1343       MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
1344
1345     // Sort by loop depth.
1346     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1347
1348     // Finally, join intervals in loop nest order.
1349     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1350       CopyCoallesceInMBB(MBBs[i].second, TryAgainList);
1351   }
1352   
1353   // Joining intervals can allow other intervals to be joined.  Iteratively join
1354   // until we make no progress.
1355   bool ProgressMade = true;
1356   while (ProgressMade) {
1357     ProgressMade = false;
1358
1359     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1360       CopyRec &TheCopy = TryAgainList[i];
1361       if (TheCopy.MI &&
1362           JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
1363         TheCopy.MI = 0;   // Mark this one as done.
1364         ProgressMade = true;
1365       }
1366     }
1367   }
1368   
1369   DOUT << "*** Register mapping ***\n";
1370   for (int i = 0, e = r2rMap_.size(); i != e; ++i)
1371     if (r2rMap_[i]) {
1372       DOUT << "  reg " << i << " -> ";
1373       DEBUG(printRegName(r2rMap_[i]));
1374       DOUT << "\n";
1375     }
1376 }
1377
1378 /// Return true if the two specified registers belong to different register
1379 /// classes.  The registers may be either phys or virt regs.
1380 bool LiveIntervals::differingRegisterClasses(unsigned RegA,
1381                                              unsigned RegB) const {
1382
1383   // Get the register classes for the first reg.
1384   if (MRegisterInfo::isPhysicalRegister(RegA)) {
1385     assert(MRegisterInfo::isVirtualRegister(RegB) &&
1386            "Shouldn't consider two physregs!");
1387     return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
1388   }
1389
1390   // Compare against the regclass for the second reg.
1391   const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1392   if (MRegisterInfo::isVirtualRegister(RegB))
1393     return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1394   else
1395     return !RegClass->contains(RegB);
1396 }
1397
1398 LiveInterval LiveIntervals::createInterval(unsigned reg) {
1399   float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
1400                        HUGE_VALF : 0.0F;
1401   return LiveInterval(reg, Weight);
1402 }