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