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