LiveIntervalAnalysis.cpp revision fe1630b43ef3e9506fde9780108c2af0431393e9
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
37using namespace llvm;
38
39namespace {
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
64void 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
75void 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///
87bool 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
180std::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->first);
198        unsigned end = getBaseIndex(i->second-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                        nI.addRange(start, end);
254                        added.push_back(&nI);
255                        // update live variables
256                        lv_->addVirtualRegisterKilled(nReg, mi);
257                        DEBUG(std::cerr << "\t\t\t\tadded new interval: "
258                              << nI << '\n');
259                    }
260                }
261            }
262        }
263    }
264
265    return added;
266}
267
268void LiveIntervals::printRegName(unsigned reg) const
269{
270    if (MRegisterInfo::isPhysicalRegister(reg))
271        std::cerr << mri_->getName(reg);
272    else
273        std::cerr << "%reg" << reg;
274}
275
276void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
277                                             MachineBasicBlock::iterator mi,
278                                             LiveInterval& interval)
279{
280    DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
281    LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
282
283    // Virtual registers may be defined multiple times (due to phi
284    // elimination and 2-addr elimination).  Much of what we do only has to be
285    // done once for the vreg.  We use an empty interval to detect the first
286    // time we see a vreg.
287    if (interval.empty()) {
288       // Assume this interval is singly defined until we find otherwise.
289       interval.isDefinedOnce = true;
290
291       // Get the Idx of the defining instructions.
292       unsigned defIndex = getDefIndex(getInstructionIndex(mi));
293
294       // Loop over all of the blocks that the vreg is defined in.  There are
295       // two cases we have to handle here.  The most common case is a vreg
296       // whose lifetime is contained within a basic block.  In this case there
297       // will be a single kill, in MBB, which comes after the definition.
298       if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
299           // FIXME: what about dead vars?
300           unsigned killIdx;
301           if (vi.Kills[0] != mi)
302               killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
303           else
304               killIdx = defIndex+1;
305
306           // If the kill happens after the definition, we have an intra-block
307           // live range.
308           if (killIdx > defIndex) {
309              assert(vi.AliveBlocks.empty() &&
310                     "Shouldn't be alive across any blocks!");
311              interval.addRange(defIndex, killIdx);
312              DEBUG(std::cerr << "\n");
313              return;
314           }
315       }
316
317       // The other case we handle is when a virtual register lives to the end
318       // of the defining block, potentially live across some blocks, then is
319       // live into some number of blocks, but gets killed.  Start by adding a
320       // range that goes from this definition to the end of the defining block.
321       interval.addRange(defIndex,
322                         getInstructionIndex(&mbb->back()) + InstrSlots::NUM);
323
324       // Iterate over all of the blocks that the variable is completely
325       // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
326       // live interval.
327       for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
328           if (vi.AliveBlocks[i]) {
329               MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
330               if (!mbb->empty()) {
331                   interval.addRange(
332                       getInstructionIndex(&mbb->front()),
333                       getInstructionIndex(&mbb->back()) + InstrSlots::NUM);
334               }
335           }
336       }
337
338       // Finally, this virtual register is live from the start of any killing
339       // block to the 'use' slot of the killing instruction.
340       for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
341           MachineInstr *Kill = vi.Kills[i];
342           interval.addRange(getInstructionIndex(Kill->getParent()->begin()),
343                             getUseIndex(getInstructionIndex(Kill))+1);
344       }
345
346    } else {
347       // If this is the second time we see a virtual register definition, it
348       // must be due to phi elimination or two addr elimination.  If this is
349       // the result of two address elimination, then the vreg is the first
350       // operand, and is a def-and-use.
351       if (mi->getOperand(0).isRegister() &&
352           mi->getOperand(0).getReg() == interval.reg &&
353           mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
354         // If this is a two-address definition, just ignore it.
355       } else {
356         // Otherwise, this must be because of phi elimination.  In this case,
357         // the defined value will be live until the end of the basic block it
358         // is defined in.
359         unsigned defIndex = getDefIndex(getInstructionIndex(mi));
360         interval.addRange(defIndex,
361                           getInstructionIndex(&mbb->back()) + InstrSlots::NUM);
362       }
363       interval.isDefinedOnce = false;
364    }
365
366    DEBUG(std::cerr << '\n');
367}
368
369void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
370                                              MachineBasicBlock::iterator mi,
371                                              LiveInterval& interval)
372{
373    // A physical register cannot be live across basic block, so its
374    // lifetime must end somewhere in its defining basic block.
375    DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
376    typedef LiveVariables::killed_iterator KillIter;
377
378    MachineBasicBlock::iterator e = mbb->end();
379    unsigned baseIndex = getInstructionIndex(mi);
380    unsigned start = getDefIndex(baseIndex);
381    unsigned end = start;
382
383    // If it is not used after definition, it is considered dead at
384    // the instruction defining it. Hence its interval is:
385    // [defSlot(def), defSlot(def)+1)
386    for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
387         ki != ke; ++ki) {
388        if (interval.reg == ki->second) {
389            DEBUG(std::cerr << " dead");
390            end = getDefIndex(start) + 1;
391            goto exit;
392        }
393    }
394
395    // If it is not dead on definition, it must be killed by a
396    // subsequent instruction. Hence its interval is:
397    // [defSlot(def), useSlot(kill)+1)
398    do {
399        ++mi;
400        baseIndex += InstrSlots::NUM;
401        for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
402             ki != ke; ++ki) {
403            if (interval.reg == ki->second) {
404                DEBUG(std::cerr << " killed");
405                end = getUseIndex(baseIndex) + 1;
406                goto exit;
407            }
408        }
409    } while (mi != e);
410
411exit:
412    assert(start < end && "did not find end of interval?");
413    interval.addRange(start, end);
414    DEBUG(std::cerr << '\n');
415}
416
417void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
418                                      MachineBasicBlock::iterator mi,
419                                      unsigned reg)
420{
421    if (MRegisterInfo::isPhysicalRegister(reg)) {
422        if (lv_->getAllocatablePhysicalRegisters()[reg]) {
423            handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(reg));
424            for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
425                handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(*as));
426        }
427    }
428    else
429        handleVirtualRegisterDef(mbb, mi, getOrCreateInterval(reg));
430}
431
432unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
433{
434    Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
435    return (it == mi2iMap_.end() ?
436            std::numeric_limits<unsigned>::max() :
437            it->second);
438}
439
440MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const
441{
442    index /= InstrSlots::NUM; // convert index to vector index
443    assert(index < i2miMap_.size() &&
444           "index does not correspond to an instruction");
445    return i2miMap_[index];
446}
447
448/// computeIntervals - computes the live intervals for virtual
449/// registers. for some ordering of the machine instructions [1,N] a
450/// live interval is an interval [i, j) where 1 <= i <= j < N for
451/// which a variable is live
452void LiveIntervals::computeIntervals()
453{
454    DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
455    DEBUG(std::cerr << "********** Function: "
456          << ((Value*)mf_->getFunction())->getName() << '\n');
457
458    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
459         I != E; ++I) {
460        MachineBasicBlock* mbb = I;
461        DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
462
463        for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
464             mi != miEnd; ++mi) {
465            const TargetInstrDescriptor& tid =
466                tm_->getInstrInfo()->get(mi->getOpcode());
467            DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
468                  mi->print(std::cerr, tm_));
469
470            // handle implicit defs
471            for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
472                handleRegisterDef(mbb, mi, *id);
473
474            // handle explicit defs
475            for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
476                MachineOperand& mop = mi->getOperand(i);
477                // handle register defs - build intervals
478                if (mop.isRegister() && mop.getReg() && mop.isDef())
479                    handleRegisterDef(mbb, mi, mop.getReg());
480            }
481        }
482    }
483}
484
485unsigned LiveIntervals::rep(unsigned reg)
486{
487    Reg2RegMap::iterator it = r2rMap_.find(reg);
488    if (it != r2rMap_.end())
489        return it->second = rep(it->second);
490    return reg;
491}
492
493void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
494    DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
495    const TargetInstrInfo& tii = *tm_->getInstrInfo();
496
497    for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
498         mi != mie; ++mi) {
499        const TargetInstrDescriptor& tid = tii.get(mi->getOpcode());
500        DEBUG(std::cerr << getInstructionIndex(mi) << '\t';
501              mi->print(std::cerr, tm_););
502
503        // we only join virtual registers with allocatable
504        // physical registers since we do not have liveness information
505        // on not allocatable physical registers
506        unsigned regA, regB;
507        if (tii.isMoveInstr(*mi, regA, regB) &&
508            (MRegisterInfo::isVirtualRegister(regA) ||
509             lv_->getAllocatablePhysicalRegisters()[regA]) &&
510            (MRegisterInfo::isVirtualRegister(regB) ||
511             lv_->getAllocatablePhysicalRegisters()[regB])) {
512
513            // get representative registers
514            regA = rep(regA);
515            regB = rep(regB);
516
517            // if they are already joined we continue
518            if (regA == regB)
519                continue;
520
521            Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
522            assert(r2iA != r2iMap_.end() &&
523                   "Found unknown vreg in 'isMoveInstr' instruction");
524            Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
525            assert(r2iB != r2iMap_.end() &&
526                   "Found unknown vreg in 'isMoveInstr' instruction");
527
528            Intervals::iterator intA = r2iA->second;
529            Intervals::iterator intB = r2iB->second;
530
531            DEBUG(std::cerr << "\t\tInspecting " << *intA << " and " << *intB
532                            << ": ");
533
534            // both A and B are virtual registers
535            if (MRegisterInfo::isVirtualRegister(intA->reg) &&
536                MRegisterInfo::isVirtualRegister(intB->reg)) {
537
538                const TargetRegisterClass *rcA, *rcB;
539                rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
540                rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
541
542                // if they are not of the same register class we continue
543                if (rcA != rcB) {
544                    DEBUG(std::cerr << "Differing reg classes.\n");
545                    continue;
546                }
547
548                // if their intervals do not overlap we join them
549                if ((intA->isDefinedOnce && intB->isDefinedOnce) ||
550                    !intB->overlaps(*intA)) {
551                    intA->join(*intB);
552                    DEBUG(std::cerr << "Joined.  Result = " << *intA << "\n");
553                    r2iB->second = r2iA->second;
554                    r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
555                    intervals_.erase(intB);
556                } else {
557                    DEBUG(std::cerr << "Interference!\n");
558                }
559            } else if (!MRegisterInfo::isPhysicalRegister(intA->reg) ||
560                       !MRegisterInfo::isPhysicalRegister(intB->reg)) {
561                if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
562                    std::swap(regA, regB);
563                    std::swap(intA, intB);
564                    std::swap(r2iA, r2iB);
565                }
566
567                assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
568                       MRegisterInfo::isVirtualRegister(intB->reg) &&
569                       "A must be physical and B must be virtual");
570
571                const TargetRegisterClass *rcA, *rcB;
572                rcA = mri_->getRegClass(intA->reg);
573                rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
574                // if they are not of the same register class we continue
575                if (rcA != rcB) {
576                    DEBUG(std::cerr << "Differing reg classes.\n");
577                    continue;
578                }
579
580                if (!intA->overlaps(*intB) &&
581                    !overlapsAliases(*intA, *intB)) {
582                    intA->join(*intB);
583                    DEBUG(std::cerr << "Joined.  Result = " << *intA << "\n");
584                    r2iB->second = r2iA->second;
585                    r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
586                    intervals_.erase(intB);
587                } else {
588                    DEBUG(std::cerr << "Interference!\n");
589                }
590            } else {
591                DEBUG(std::cerr << "Cannot join physregs.\n");
592            }
593        }
594    }
595}
596
597namespace {
598  // DepthMBBCompare - Comparison predicate that sort first based on the loop
599  // depth of the basic block (the unsigned), and then on the MBB number.
600  struct DepthMBBCompare {
601    typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
602    bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
603      if (LHS.first > RHS.first) return true;   // Deeper loops first
604      return LHS.first == RHS.first &&
605             LHS.second->getNumber() < RHS.second->getNumber();
606    }
607  };
608}
609
610void LiveIntervals::joinIntervals() {
611  DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
612
613  const LoopInfo &LI = getAnalysis<LoopInfo>();
614  if (LI.begin() == LI.end()) {
615    // If there are no loops in the function, join intervals in function order.
616    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
617         I != E; ++I)
618      joinIntervalsInMachineBB(I);
619  } else {
620    // Otherwise, join intervals in inner loops before other intervals.
621    // Unfortunately we can't just iterate over loop hierarchy here because
622    // there may be more MBB's than BB's.  Collect MBB's for sorting.
623    std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
624    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
625         I != E; ++I)
626      MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
627
628    // Sort by loop depth.
629    std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
630
631    // Finally, join intervals in loop nest order.
632    for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
633      joinIntervalsInMachineBB(MBBs[i].second);
634  }
635}
636
637bool LiveIntervals::overlapsAliases(const LiveInterval& lhs,
638                                    const LiveInterval& rhs) const
639{
640    assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
641           "first interval must describe a physical register");
642
643    for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
644        Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
645        assert(r2i != r2iMap_.end() && "alias does not have interval?");
646        if (rhs.overlaps(*r2i->second))
647            return true;
648    }
649
650    return false;
651}
652
653LiveInterval& LiveIntervals::getOrCreateInterval(unsigned reg)
654{
655    Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
656    if (r2iit == r2iMap_.end() || r2iit->first != reg) {
657        intervals_.push_back(LiveInterval(reg));
658        r2iit = r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
659    }
660
661    return *r2iit->second;
662}
663
664LiveInterval::LiveInterval(unsigned r)
665    : reg(r),
666      weight((MRegisterInfo::isPhysicalRegister(r) ?  HUGE_VAL : 0.0F)),
667      isDefinedOnce(false) {
668}
669
670bool LiveInterval::spilled() const
671{
672    return (weight == HUGE_VAL &&
673            MRegisterInfo::isVirtualRegister(reg));
674}
675
676// An example for liveAt():
677//
678// this = [1,4), liveAt(0) will return false. The instruction defining
679// this spans slots [0,3]. The interval belongs to an spilled
680// definition of the variable it represents. This is because slot 1 is
681// used (def slot) and spans up to slot 3 (store slot).
682//
683bool LiveInterval::liveAt(unsigned index) const
684{
685    Range dummy(index, index+1);
686    Ranges::const_iterator r = std::upper_bound(ranges.begin(),
687                                                ranges.end(),
688                                                dummy);
689    if (r == ranges.begin())
690        return false;
691
692    --r;
693    return index >= r->first && index < r->second;
694}
695
696// An example for overlaps():
697//
698// 0: A = ...
699// 4: B = ...
700// 8: C = A + B ;; last use of A
701//
702// The live intervals should look like:
703//
704// A = [3, 11)
705// B = [7, x)
706// C = [11, y)
707//
708// A->overlaps(C) should return false since we want to be able to join
709// A and C.
710bool LiveInterval::overlaps(const LiveInterval& other) const
711{
712    Ranges::const_iterator i = ranges.begin();
713    Ranges::const_iterator ie = ranges.end();
714    Ranges::const_iterator j = other.ranges.begin();
715    Ranges::const_iterator je = other.ranges.end();
716    if (i->first < j->first) {
717        i = std::upper_bound(i, ie, *j);
718        if (i != ranges.begin()) --i;
719    }
720    else if (j->first < i->first) {
721        j = std::upper_bound(j, je, *i);
722        if (j != other.ranges.begin()) --j;
723    }
724
725    while (i != ie && j != je) {
726        if (i->first == j->first) {
727            return true;
728        }
729        else {
730            if (i->first > j->first) {
731                swap(i, j);
732                swap(ie, je);
733            }
734            assert(i->first < j->first);
735
736            if (i->second > j->first) {
737                return true;
738            }
739            else {
740                ++i;
741            }
742        }
743    }
744
745    return false;
746}
747
748void LiveInterval::addRange(unsigned start, unsigned end)
749{
750    assert(start < end && "Invalid range to add!");
751    DEBUG(std::cerr << " +[" << start << ',' << end << ")");
752    //assert(start < end && "invalid range?");
753    Range range = std::make_pair(start, end);
754    Ranges::iterator it =
755        ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
756                      range);
757
758    it = mergeRangesForward(it);
759    it = mergeRangesBackward(it);
760}
761
762void LiveInterval::join(const LiveInterval& other)
763{
764    Ranges::iterator cur = ranges.begin();
765    isDefinedOnce &= other.isDefinedOnce;
766
767    for (Ranges::const_iterator i = other.ranges.begin(),
768             e = other.ranges.end(); i != e; ++i) {
769        cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
770        cur = mergeRangesForward(cur);
771        cur = mergeRangesBackward(cur);
772    }
773    weight += other.weight;
774    ++numJoins;
775}
776
777LiveInterval::Ranges::iterator LiveInterval::
778mergeRangesForward(Ranges::iterator it)
779{
780    Ranges::iterator n;
781    while ((n = next(it)) != ranges.end()) {
782        if (n->first > it->second)
783            break;
784        it->second = std::max(it->second, n->second);
785        n = ranges.erase(n);
786    }
787    return it;
788}
789
790LiveInterval::Ranges::iterator LiveInterval::
791mergeRangesBackward(Ranges::iterator it)
792{
793    while (it != ranges.begin()) {
794        Ranges::iterator p = prior(it);
795        if (it->first > p->second)
796            break;
797
798        it->first = std::min(it->first, p->first);
799        it->second = std::max(it->second, p->second);
800        it = ranges.erase(p);
801    }
802
803    return it;
804}
805
806std::ostream& llvm::operator<<(std::ostream& os, const LiveInterval& li)
807{
808    os << "%reg" << li.reg << ',' << li.weight;
809    if (li.empty())
810        return os << "EMPTY";
811
812    os << " = ";
813    for (LiveInterval::Ranges::const_iterator
814             i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
815        os << "[" << i->first << "," << i->second << ")";
816    }
817    return os;
818}
819