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