Convert indentation to 2 spaces.
[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 "LiveIntervalAnalysis.h"
20 #include "llvm/Value.h"
21 #include "llvm/Analysis/LoopInfo.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 "Support/CommandLine.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
33 #include "Support/STLExtras.h"
34 #include "VirtRegMap.h"
35 #include <cmath>
36
37 using namespace llvm;
38
39 namespace {
40   RegisterAnalysis<LiveIntervals> X("liveintervals", "Live Interval Analysis");
41
42   Statistic<> numIntervals
43   ("liveintervals", "Number of original intervals");
44
45   Statistic<> numIntervalsAfter
46   ("liveintervals", "Number of intervals after coalescing");
47
48   Statistic<> numJoins
49   ("liveintervals", "Number of interval joins performed");
50
51   Statistic<> numPeep
52   ("liveintervals", "Number of identity moves eliminated after coalescing");
53
54   Statistic<> numFolded
55   ("liveintervals", "Number of loads/stores folded into instructions");
56
57   cl::opt<bool>
58   EnableJoining("join-liveintervals",
59                 cl::desc("Join compatible live intervals"),
60                 cl::init(true));
61 };
62
63 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
64 {
65   AU.addPreserved<LiveVariables>();
66   AU.addRequired<LiveVariables>();
67   AU.addPreservedID(PHIEliminationID);
68   AU.addRequiredID(PHIEliminationID);
69   AU.addRequiredID(TwoAddressInstructionPassID);
70   AU.addRequired<LoopInfo>();
71   MachineFunctionPass::getAnalysisUsage(AU);
72 }
73
74 void LiveIntervals::releaseMemory()
75 {
76   mi2iMap_.clear();
77   i2miMap_.clear();
78   r2iMap_.clear();
79   r2rMap_.clear();
80 }
81
82
83 /// runOnMachineFunction - Register allocate the whole function
84 ///
85 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
86   mf_ = &fn;
87   tm_ = &fn.getTarget();
88   mri_ = tm_->getRegisterInfo();
89   lv_ = &getAnalysis<LiveVariables>();
90
91   // number MachineInstrs
92   unsigned miIndex = 0;
93   for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
94        mbb != mbbEnd; ++mbb)
95     for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
96          mi != miEnd; ++mi) {
97       bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
98       assert(inserted && "multiple MachineInstr -> index mappings");
99       i2miMap_.push_back(mi);
100       miIndex += InstrSlots::NUM;
101     }
102
103   computeIntervals();
104
105   numIntervals += getNumIntervals();
106
107 #if 1
108   DEBUG(std::cerr << "********** INTERVALS **********\n");
109   DEBUG(for (iterator I = begin(), E = end(); I != E; ++I)
110         std::cerr << I->second << "\n");
111 #endif
112
113   // join intervals if requested
114   if (EnableJoining) joinIntervals();
115
116   numIntervalsAfter += getNumIntervals();
117
118   // perform a final pass over the instructions and compute spill
119   // weights, coalesce virtual registers and remove identity moves
120   const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
121   const TargetInstrInfo& tii = *tm_->getInstrInfo();
122
123   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
124        mbbi != mbbe; ++mbbi) {
125     MachineBasicBlock* mbb = mbbi;
126     unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
127
128     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
129          mii != mie; ) {
130       // if the move will be an identity move delete it
131       unsigned srcReg, dstReg, RegRep;
132       if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
133           (RegRep = rep(srcReg)) == rep(dstReg)) {
134         // remove from def list
135         LiveInterval &interval = getOrCreateInterval(RegRep);
136         // remove index -> MachineInstr and
137         // MachineInstr -> index mappings
138         Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
139         if (mi2i != mi2iMap_.end()) {
140           i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
141           mi2iMap_.erase(mi2i);
142         }
143         mii = mbbi->erase(mii);
144         ++numPeep;
145       }
146       else {
147         for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
148           const MachineOperand& mop = mii->getOperand(i);
149           if (mop.isRegister() && mop.getReg() &&
150               MRegisterInfo::isVirtualRegister(mop.getReg())) {
151             // replace register with representative register
152             unsigned reg = rep(mop.getReg());
153             mii->SetMachineOperandReg(i, reg);
154
155             LiveInterval &RegInt = getInterval(reg);
156             RegInt.weight +=
157               (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
158           }
159         }
160         ++mii;
161       }
162     }
163   }
164
165   DEBUG(std::cerr << "********** INTERVALS **********\n");
166   DEBUG (for (iterator I = begin(), E = end(); I != E; ++I)
167          std::cerr << I->second << "\n");
168   DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
169   DEBUG(
170     for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
171          mbbi != mbbe; ++mbbi) {
172       std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
173       for (MachineBasicBlock::iterator mii = mbbi->begin(),
174              mie = mbbi->end(); mii != mie; ++mii) {
175         std::cerr << getInstructionIndex(mii) << '\t';
176         mii->print(std::cerr, tm_);
177       }
178     });
179
180   return true;
181 }
182
183 std::vector<LiveInterval*> LiveIntervals::addIntervalsForSpills(
184   const LiveInterval& li,
185   VirtRegMap& vrm,
186   int slot)
187 {
188   std::vector<LiveInterval*> added;
189
190   assert(li.weight != HUGE_VAL &&
191          "attempt to spill already spilled interval!");
192
193   DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
194         << li << '\n');
195
196   const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
197
198   for (LiveInterval::Ranges::const_iterator
199          i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
200     unsigned index = getBaseIndex(i->start);
201     unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
202     for (; index != end; index += InstrSlots::NUM) {
203       // skip deleted instructions
204       while (index != end && !getInstructionFromIndex(index))
205         index += InstrSlots::NUM;
206       if (index == end) break;
207
208       MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
209
210     for_operand:
211       for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
212         MachineOperand& mop = mi->getOperand(i);
213         if (mop.isRegister() && mop.getReg() == li.reg) {
214           if (MachineInstr* fmi =
215               mri_->foldMemoryOperand(mi, i, slot)) {
216             lv_->instructionChanged(mi, fmi);
217             vrm.virtFolded(li.reg, mi, fmi);
218             mi2iMap_.erase(mi);
219             i2miMap_[index/InstrSlots::NUM] = fmi;
220             mi2iMap_[fmi] = index;
221             MachineBasicBlock& mbb = *mi->getParent();
222             mi = mbb.insert(mbb.erase(mi), fmi);
223             ++numFolded;
224             goto for_operand;
225           }
226           else {
227             // This is tricky. We need to add information in
228             // the interval about the spill code so we have to
229             // use our extra load/store slots.
230             //
231             // If we have a use we are going to have a load so
232             // we start the interval from the load slot
233             // onwards. Otherwise we start from the def slot.
234             unsigned start = (mop.isUse() ?
235                               getLoadIndex(index) :
236                               getDefIndex(index));
237             // If we have a def we are going to have a store
238             // right after it so we end the interval after the
239             // use of the next instruction. Otherwise we end
240             // after the use of this instruction.
241             unsigned end = 1 + (mop.isDef() ?
242                                 getStoreIndex(index) :
243                                 getUseIndex(index));
244
245             // create a new register for this spill
246             unsigned nReg =
247               mf_->getSSARegMap()->createVirtualRegister(rc);
248             mi->SetMachineOperandReg(i, nReg);
249             vrm.grow();
250             vrm.assignVirt2StackSlot(nReg, slot);
251             LiveInterval& nI = getOrCreateInterval(nReg);
252             assert(nI.empty());
253             // the spill weight is now infinity as it
254             // cannot be spilled again
255             nI.weight = HUGE_VAL;
256             LiveRange LR(start, end, nI.getNextValue());
257             DEBUG(std::cerr << " +" << LR);
258             nI.addRange(LR);
259             added.push_back(&nI);
260             // update live variables
261             lv_->addVirtualRegisterKilled(nReg, mi);
262             DEBUG(std::cerr << "\t\t\t\tadded new interval: "
263                   << nI << '\n');
264           }
265         }
266       }
267     }
268   }
269
270   return added;
271 }
272
273 void LiveIntervals::printRegName(unsigned reg) const
274 {
275   if (MRegisterInfo::isPhysicalRegister(reg))
276     std::cerr << mri_->getName(reg);
277   else
278     std::cerr << "%reg" << reg;
279 }
280
281 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
282                                              MachineBasicBlock::iterator mi,
283                                              LiveInterval& interval)
284 {
285   DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
286   LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
287
288   // Virtual registers may be defined multiple times (due to phi 
289   // elimination and 2-addr elimination).  Much of what we do only has to be 
290   // done once for the vreg.  We use an empty interval to detect the first 
291   // time we see a vreg.
292   if (interval.empty()) {
293     // Get the Idx of the defining instructions.
294     unsigned defIndex = getDefIndex(getInstructionIndex(mi));
295
296     unsigned ValNum = interval.getNextValue();
297     assert(ValNum == 0 && "First value in interval is not 0?");
298     ValNum = 0;  // Clue in the optimizer.
299
300     // Loop over all of the blocks that the vreg is defined in.  There are
301     // two cases we have to handle here.  The most common case is a vreg
302     // whose lifetime is contained within a basic block.  In this case there
303     // will be a single kill, in MBB, which comes after the definition.
304     if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
305       // FIXME: what about dead vars?
306       unsigned killIdx;
307       if (vi.Kills[0] != mi)
308         killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
309       else
310         killIdx = defIndex+1;
311
312       // If the kill happens after the definition, we have an intra-block
313       // live range.
314       if (killIdx > defIndex) {
315         assert(vi.AliveBlocks.empty() && 
316                "Shouldn't be alive across any blocks!");
317         LiveRange LR(defIndex, killIdx, ValNum);
318         interval.addRange(LR);
319         DEBUG(std::cerr << " +" << LR << "\n");
320         return;
321       }
322     }
323
324     // The other case we handle is when a virtual register lives to the end
325     // of the defining block, potentially live across some blocks, then is
326     // live into some number of blocks, but gets killed.  Start by adding a
327     // range that goes from this definition to the end of the defining block.
328     LiveRange NewLR(defIndex, getInstructionIndex(&mbb->back()) +
329                     InstrSlots::NUM, ValNum);
330     DEBUG(std::cerr << " +" << NewLR);
331     interval.addRange(NewLR);
332
333     // Iterate over all of the blocks that the variable is completely
334     // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
335     // live interval.
336     for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
337       if (vi.AliveBlocks[i]) {
338         MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
339         if (!mbb->empty()) {
340           LiveRange LR(getInstructionIndex(&mbb->front()),
341                        getInstructionIndex(&mbb->back())+InstrSlots::NUM,
342                        ValNum);
343           interval.addRange(LR);
344           DEBUG(std::cerr << " +" << LR);
345         }
346       }
347     }
348
349     // Finally, this virtual register is live from the start of any killing
350     // block to the 'use' slot of the killing instruction.
351     for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
352       MachineInstr *Kill = vi.Kills[i];
353       LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
354                    getUseIndex(getInstructionIndex(Kill))+1, ValNum);
355       interval.addRange(LR);
356       DEBUG(std::cerr << " +" << LR);
357     }
358
359   } else {
360     // If this is the second time we see a virtual register definition, it
361     // must be due to phi elimination or two addr elimination.  If this is
362     // the result of two address elimination, then the vreg is the first
363     // operand, and is a def-and-use.
364     if (mi->getOperand(0).isRegister() && 
365         mi->getOperand(0).getReg() == interval.reg &&
366         mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
367       // If this is a two-address definition, then we have already processed
368       // the live range.  The only problem is that we didn't realize there
369       // are actually two values in the live interval.  Because of this we
370       // need to take the LiveRegion that defines this register and split it
371       // into two values.
372       unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
373       unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
374
375       // Delete the initial value, which should be short and continuous,
376       // becuase the 2-addr copy must be in the same MBB as the redef.
377       interval.removeRange(DefIndex, RedefIndex);
378          
379       LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
380       DEBUG(std::cerr << " replace range with " << LR);
381       interval.addRange(LR);
382
383       // If this redefinition is dead, we need to add a dummy unit live
384       // range covering the def slot.
385       for (LiveVariables::killed_iterator KI = lv_->dead_begin(mi),
386              E = lv_->dead_end(mi); KI != E; ++KI)
387         if (KI->second == interval.reg) {
388           interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
389           break;
390         }
391
392       DEBUG(std::cerr << "RESULT: " << interval);
393
394     } else {
395       // Otherwise, this must be because of phi elimination.  If this is the
396       // first redefinition of the vreg that we have seen, go back and change
397       // the live range in the PHI block to be a different value number.
398       if (interval.containsOneValue()) {
399         assert(vi.Kills.size() == 1 &&
400                "PHI elimination vreg should have one kill, the PHI itself!");
401
402         // Remove the old range that we now know has an incorrect number.
403         MachineInstr *Killer = vi.Kills[0];
404         unsigned Start = getInstructionIndex(Killer->getParent()->begin());
405         unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
406         DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
407               << interval << "\n");
408         interval.removeRange(Start, End);
409         DEBUG(std::cerr << "RESULT: " << interval);
410
411         // Replace the interval with one of a NEW value number.
412         LiveRange LR(Start, End, interval.getNextValue());
413         DEBUG(std::cerr << " replace range with " << LR);
414         interval.addRange(LR);
415         DEBUG(std::cerr << "RESULT: " << interval);
416       }
417
418       // In the case of PHI elimination, each variable definition is only
419       // live until the end of the block.  We've already taken care of the
420       // rest of the live range.
421       unsigned defIndex = getDefIndex(getInstructionIndex(mi));
422       LiveRange LR(defIndex, 
423                    getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
424                    interval.getNextValue());
425       interval.addRange(LR);
426       DEBUG(std::cerr << " +" << LR);
427     }
428   }
429
430   DEBUG(std::cerr << '\n');
431 }
432
433 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
434                                               MachineBasicBlock::iterator mi,
435                                               LiveInterval& interval)
436 {
437   // A physical register cannot be live across basic block, so its
438   // lifetime must end somewhere in its defining basic block.
439   DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
440   typedef LiveVariables::killed_iterator KillIter;
441
442   unsigned baseIndex = getInstructionIndex(mi);
443   unsigned start = getDefIndex(baseIndex);
444   unsigned end = start;
445
446   // If it is not used after definition, it is considered dead at
447   // the instruction defining it. Hence its interval is:
448   // [defSlot(def), defSlot(def)+1)
449   for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
450        ki != ke; ++ki) {
451     if (interval.reg == ki->second) {
452       DEBUG(std::cerr << " dead");
453       end = getDefIndex(start) + 1;
454       goto exit;
455     }
456   }
457
458   // If it is not dead on definition, it must be killed by a
459   // subsequent instruction. Hence its interval is:
460   // [defSlot(def), useSlot(kill)+1)
461   while (true) {
462     ++mi;
463     assert(mi != MBB->end() && "physreg was not killed in defining block!");
464     baseIndex += InstrSlots::NUM;
465     for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
466          ki != ke; ++ki) {
467       if (interval.reg == ki->second) {
468         DEBUG(std::cerr << " killed");
469         end = getUseIndex(baseIndex) + 1;
470         goto exit;
471       }
472     }
473   }
474
475 exit:
476   assert(start < end && "did not find end of interval?");
477   LiveRange LR(start, end, interval.getNextValue());
478   interval.addRange(LR);
479   DEBUG(std::cerr << " +" << LR << '\n');
480 }
481
482 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
483                                       MachineBasicBlock::iterator MI,
484                                       unsigned reg) {
485   if (MRegisterInfo::isVirtualRegister(reg))
486     handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
487   else if (lv_->getAllocatablePhysicalRegisters()[reg]) {
488     handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg));
489     for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
490       handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS));
491   }
492 }
493
494 /// computeIntervals - computes the live intervals for virtual
495 /// registers. for some ordering of the machine instructions [1,N] a
496 /// live interval is an interval [i, j) where 1 <= i <= j < N for
497 /// which a variable is live
498 void LiveIntervals::computeIntervals()
499 {
500   DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
501   DEBUG(std::cerr << "********** Function: "
502         << ((Value*)mf_->getFunction())->getName() << '\n');
503
504   for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); 
505        I != E; ++I) {
506     MachineBasicBlock* mbb = I;
507     DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
508
509     for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
510          mi != miEnd; ++mi) {
511       const TargetInstrDescriptor& tid =
512         tm_->getInstrInfo()->get(mi->getOpcode());
513       DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
514             mi->print(std::cerr, tm_));
515
516       // handle implicit defs
517       for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
518         handleRegisterDef(mbb, mi, *id);
519
520       // handle explicit defs
521       for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
522         MachineOperand& mop = mi->getOperand(i);
523         // handle register defs - build intervals
524         if (mop.isRegister() && mop.getReg() && mop.isDef())
525           handleRegisterDef(mbb, mi, mop.getReg());
526       }
527     }
528   }
529 }
530
531 void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
532   DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
533   const TargetInstrInfo &TII = *tm_->getInstrInfo();
534
535   for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
536        mi != mie; ++mi) {
537     DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
538
539     // we only join virtual registers with allocatable
540     // physical registers since we do not have liveness information
541     // on not allocatable physical registers
542     unsigned regA, regB;
543     if (TII.isMoveInstr(*mi, regA, regB) &&
544         (MRegisterInfo::isVirtualRegister(regA) ||
545          lv_->getAllocatablePhysicalRegisters()[regA]) &&
546         (MRegisterInfo::isVirtualRegister(regB) ||
547          lv_->getAllocatablePhysicalRegisters()[regB])) {
548       
549       // Get representative registers.
550       regA = rep(regA);
551       regB = rep(regB);
552       
553       // If they are already joined we continue.
554       if (regA == regB)
555         continue;
556             
557       // If they are both physical registers, we cannot join them.
558       if (MRegisterInfo::isPhysicalRegister(regA) && 
559           MRegisterInfo::isPhysicalRegister(regB))
560         continue;
561
562       // If they are not of the same register class, we cannot join them.
563       if (differingRegisterClasses(regA, regB))
564         continue;
565
566       LiveInterval &IntA = getInterval(regA);
567       LiveInterval &IntB = getInterval(regB);
568       assert(IntA.reg == regA && IntB.reg == regB &&
569              "Register mapping is horribly broken!");
570
571       DEBUG(std::cerr << "\t\tInspecting " << IntA << " and " << IntB << ": ");
572
573       // If two intervals contain a single value and are joined by a copy, it
574       // does not matter if the intervals overlap, they can always be joined.
575       bool TriviallyJoinable =
576         IntA.containsOneValue() && IntB.containsOneValue();
577
578       unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
579       if ((TriviallyJoinable || IntB.joinable(IntA, MIDefIdx)) &&
580           !overlapsAliases(&IntA, &IntB)) {
581         IntB.join(IntA, MIDefIdx);
582
583         if (!MRegisterInfo::isPhysicalRegister(regA)) {
584           r2iMap_.erase(regA);
585           r2rMap_[regA] = regB;
586         } else {
587           // Otherwise merge the data structures the other way so we don't lose
588           // the physreg information.
589           r2rMap_[regB] = regA;
590           IntB.reg = regA;
591           IntA.swap(IntB);
592           r2iMap_.erase(regB);
593         }
594         DEBUG(std::cerr << "Joined.  Result = " << IntB << "\n");
595         ++numJoins;
596       } else {
597         DEBUG(std::cerr << "Interference!\n");
598       }
599     }
600   }
601 }
602
603 namespace {
604   // DepthMBBCompare - Comparison predicate that sort first based on the loop
605   // depth of the basic block (the unsigned), and then on the MBB number.
606   struct DepthMBBCompare {
607     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
608     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
609       if (LHS.first > RHS.first) return true;   // Deeper loops first
610       return LHS.first == RHS.first && 
611         LHS.second->getNumber() < RHS.second->getNumber();
612     }
613   };
614 }
615
616 void LiveIntervals::joinIntervals() {
617   DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
618
619   const LoopInfo &LI = getAnalysis<LoopInfo>();
620   if (LI.begin() == LI.end()) {
621     // If there are no loops in the function, join intervals in function order.
622     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
623          I != E; ++I)
624       joinIntervalsInMachineBB(I);
625   } else {
626     // Otherwise, join intervals in inner loops before other intervals.
627     // Unfortunately we can't just iterate over loop hierarchy here because
628     // there may be more MBB's than BB's.  Collect MBB's for sorting.
629     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
630     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
631          I != E; ++I)
632       MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
633
634     // Sort by loop depth.
635     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
636
637     // Finally, join intervals in loop nest order. 
638     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
639       joinIntervalsInMachineBB(MBBs[i].second);
640   }
641
642   DEBUG(std::cerr << "*** Register mapping ***\n");
643   DEBUG(for (std::map<unsigned, unsigned>::iterator I = r2rMap_.begin(),
644                E = r2rMap_.end(); I != E; ++I)
645         std::cerr << "  reg " << I->first << " -> reg " << I->second << "\n";);
646 }
647
648 /// Return true if the two specified registers belong to different register
649 /// classes.  The registers may be either phys or virt regs.
650 bool LiveIntervals::differingRegisterClasses(unsigned RegA,
651                                              unsigned RegB) const {
652   const TargetRegisterClass *RegClass;
653
654   // Get the register classes for the first reg.
655   if (MRegisterInfo::isVirtualRegister(RegA))
656     RegClass = mf_->getSSARegMap()->getRegClass(RegA);
657   else
658     RegClass = mri_->getRegClass(RegA);
659
660   // Compare against the regclass for the second reg.
661   if (MRegisterInfo::isVirtualRegister(RegB))
662     return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
663   else
664     return RegClass != mri_->getRegClass(RegB);
665 }
666
667 bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
668                                     const LiveInterval *RHS) const {
669   if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
670     if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
671       return false;   // vreg-vreg merge has no aliases!
672     std::swap(LHS, RHS);
673   }
674
675   assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
676          MRegisterInfo::isVirtualRegister(RHS->reg) &&
677          "first interval must describe a physical register");
678
679   for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
680     if (RHS->overlaps(getInterval(*AS)))
681       return true;
682
683   return false;
684 }
685
686 LiveInterval LiveIntervals::createInterval(unsigned reg) {
687   float Weight = MRegisterInfo::isPhysicalRegister(reg) ?  HUGE_VAL :0.0F;
688   return LiveInterval(reg, Weight);
689 }
690