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