Fix the build for MSVC 9 whose upper_bound() wants to compare elements in the sorted...
[oota-llvm.git] / lib / CodeGen / LiveInterval.cpp
1 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LiveRange and LiveInterval classes.  Given some
11 // numbering of each the machine instructions an interval [i, j) is said to be a
12 // live interval for register v if there is no instruction with number j' > j
13 // such that v is live at j' and there is no instruction with number i' < i such
14 // that v is live at i'. In this implementation intervals can have holes,
15 // i.e. an interval might look like [1,20), [50,65), [1000,1001).  Each
16 // individual range is represented as an instance of LiveRange, and the whole
17 // interval is represented as an instance of LiveInterval.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/CodeGen/LiveInterval.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include <algorithm>
31 using namespace llvm;
32
33 // CompEnd - Compare LiveRange ends.
34 namespace {
35 struct CompEnd {
36   bool operator()(SlotIndex A, const LiveRange &B) const {
37     return A < B.end;
38   }
39   bool operator()(const LiveRange &A, SlotIndex B) const {
40     return A.end < B;
41   }
42   bool operator()(const LiveRange &A, const LiveRange &B) const {
43     return A.end < B.end;
44   }
45 };
46 }
47
48 LiveInterval::iterator LiveInterval::find(SlotIndex Pos) {
49   assert(Pos.isValid() && "Cannot search for an invalid index");
50   return std::upper_bound(begin(), end(), Pos, CompEnd());
51 }
52
53 /// killedInRange - Return true if the interval has kills in [Start,End).
54 bool LiveInterval::killedInRange(SlotIndex Start, SlotIndex End) const {
55   Ranges::const_iterator r =
56     std::lower_bound(ranges.begin(), ranges.end(), End);
57
58   // Now r points to the first interval with start >= End, or ranges.end().
59   if (r == ranges.begin())
60     return false;
61
62   --r;
63   // Now r points to the last interval with end <= End.
64   // r->end is the kill point.
65   return r->end >= Start && r->end < End;
66 }
67
68 // overlaps - Return true if the intersection of the two live intervals is
69 // not empty.
70 //
71 // An example for overlaps():
72 //
73 // 0: A = ...
74 // 4: B = ...
75 // 8: C = A + B ;; last use of A
76 //
77 // The live intervals should look like:
78 //
79 // A = [3, 11)
80 // B = [7, x)
81 // C = [11, y)
82 //
83 // A->overlaps(C) should return false since we want to be able to join
84 // A and C.
85 //
86 bool LiveInterval::overlapsFrom(const LiveInterval& other,
87                                 const_iterator StartPos) const {
88   assert(!empty() && "empty interval");
89   const_iterator i = begin();
90   const_iterator ie = end();
91   const_iterator j = StartPos;
92   const_iterator je = other.end();
93
94   assert((StartPos->start <= i->start || StartPos == other.begin()) &&
95          StartPos != other.end() && "Bogus start position hint!");
96
97   if (i->start < j->start) {
98     i = std::upper_bound(i, ie, j->start);
99     if (i != ranges.begin()) --i;
100   } else if (j->start < i->start) {
101     ++StartPos;
102     if (StartPos != other.end() && StartPos->start <= i->start) {
103       assert(StartPos < other.end() && i < end());
104       j = std::upper_bound(j, je, i->start);
105       if (j != other.ranges.begin()) --j;
106     }
107   } else {
108     return true;
109   }
110
111   if (j == je) return false;
112
113   while (i != ie) {
114     if (i->start > j->start) {
115       std::swap(i, j);
116       std::swap(ie, je);
117     }
118
119     if (i->end > j->start)
120       return true;
121     ++i;
122   }
123
124   return false;
125 }
126
127 /// overlaps - Return true if the live interval overlaps a range specified
128 /// by [Start, End).
129 bool LiveInterval::overlaps(SlotIndex Start, SlotIndex End) const {
130   assert(Start < End && "Invalid range");
131   const_iterator I = std::lower_bound(begin(), end(), End);
132   return I != begin() && (--I)->end > Start;
133 }
134
135
136 /// ValNo is dead, remove it.  If it is the largest value number, just nuke it
137 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
138 /// it can be nuked later.
139 void LiveInterval::markValNoForDeletion(VNInfo *ValNo) {
140   if (ValNo->id == getNumValNums()-1) {
141     do {
142       valnos.pop_back();
143     } while (!valnos.empty() && valnos.back()->isUnused());
144   } else {
145     ValNo->setIsUnused(true);
146   }
147 }
148
149 /// RenumberValues - Renumber all values in order of appearance and delete the
150 /// remaining unused values.
151 void LiveInterval::RenumberValues(LiveIntervals &lis) {
152   SmallPtrSet<VNInfo*, 8> Seen;
153   bool seenPHIDef = false;
154   valnos.clear();
155   for (const_iterator I = begin(), E = end(); I != E; ++I) {
156     VNInfo *VNI = I->valno;
157     if (!Seen.insert(VNI))
158       continue;
159     assert(!VNI->isUnused() && "Unused valno used by live range");
160     VNI->id = (unsigned)valnos.size();
161     valnos.push_back(VNI);
162     VNI->setHasPHIKill(false);
163     if (VNI->isPHIDef())
164       seenPHIDef = true;
165   }
166
167   // Recompute phi kill flags.
168   if (!seenPHIDef)
169     return;
170   for (const_vni_iterator I = vni_begin(), E = vni_end(); I != E; ++I) {
171     VNInfo *VNI = *I;
172     if (!VNI->isPHIDef())
173       continue;
174     const MachineBasicBlock *PHIBB = lis.getMBBFromIndex(VNI->def);
175     assert(PHIBB && "No basic block for phi-def");
176     for (MachineBasicBlock::const_pred_iterator PI = PHIBB->pred_begin(),
177          PE = PHIBB->pred_end(); PI != PE; ++PI) {
178       VNInfo *KVNI = getVNInfoAt(lis.getMBBEndIdx(*PI).getPrevSlot());
179       if (KVNI)
180         KVNI->setHasPHIKill(true);
181     }
182   }
183 }
184
185 /// extendIntervalEndTo - This method is used when we want to extend the range
186 /// specified by I to end at the specified endpoint.  To do this, we should
187 /// merge and eliminate all ranges that this will overlap with.  The iterator is
188 /// not invalidated.
189 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) {
190   assert(I != ranges.end() && "Not a valid interval!");
191   VNInfo *ValNo = I->valno;
192
193   // Search for the first interval that we can't merge with.
194   Ranges::iterator MergeTo = llvm::next(I);
195   for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
196     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
197   }
198
199   // If NewEnd was in the middle of an interval, make sure to get its endpoint.
200   I->end = std::max(NewEnd, prior(MergeTo)->end);
201
202   // Erase any dead ranges.
203   ranges.erase(llvm::next(I), MergeTo);
204
205   // If the newly formed range now touches the range after it and if they have
206   // the same value number, merge the two ranges into one range.
207   Ranges::iterator Next = llvm::next(I);
208   if (Next != ranges.end() && Next->start <= I->end && Next->valno == ValNo) {
209     I->end = Next->end;
210     ranges.erase(Next);
211   }
212 }
213
214
215 /// extendIntervalStartTo - This method is used when we want to extend the range
216 /// specified by I to start at the specified endpoint.  To do this, we should
217 /// merge and eliminate all ranges that this will overlap with.
218 LiveInterval::Ranges::iterator
219 LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) {
220   assert(I != ranges.end() && "Not a valid interval!");
221   VNInfo *ValNo = I->valno;
222
223   // Search for the first interval that we can't merge with.
224   Ranges::iterator MergeTo = I;
225   do {
226     if (MergeTo == ranges.begin()) {
227       I->start = NewStart;
228       ranges.erase(MergeTo, I);
229       return I;
230     }
231     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
232     --MergeTo;
233   } while (NewStart <= MergeTo->start);
234
235   // If we start in the middle of another interval, just delete a range and
236   // extend that interval.
237   if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
238     MergeTo->end = I->end;
239   } else {
240     // Otherwise, extend the interval right after.
241     ++MergeTo;
242     MergeTo->start = NewStart;
243     MergeTo->end = I->end;
244   }
245
246   ranges.erase(llvm::next(MergeTo), llvm::next(I));
247   return MergeTo;
248 }
249
250 LiveInterval::iterator
251 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
252   SlotIndex Start = LR.start, End = LR.end;
253   iterator it = std::upper_bound(From, ranges.end(), Start);
254
255   // If the inserted interval starts in the middle or right at the end of
256   // another interval, just extend that interval to contain the range of LR.
257   if (it != ranges.begin()) {
258     iterator B = prior(it);
259     if (LR.valno == B->valno) {
260       if (B->start <= Start && B->end >= Start) {
261         extendIntervalEndTo(B, End);
262         return B;
263       }
264     } else {
265       // Check to make sure that we are not overlapping two live ranges with
266       // different valno's.
267       assert(B->end <= Start &&
268              "Cannot overlap two LiveRanges with differing ValID's"
269              " (did you def the same reg twice in a MachineInstr?)");
270     }
271   }
272
273   // Otherwise, if this range ends in the middle of, or right next to, another
274   // interval, merge it into that interval.
275   if (it != ranges.end()) {
276     if (LR.valno == it->valno) {
277       if (it->start <= End) {
278         it = extendIntervalStartTo(it, Start);
279
280         // If LR is a complete superset of an interval, we may need to grow its
281         // endpoint as well.
282         if (End > it->end)
283           extendIntervalEndTo(it, End);
284         return it;
285       }
286     } else {
287       // Check to make sure that we are not overlapping two live ranges with
288       // different valno's.
289       assert(it->start >= End &&
290              "Cannot overlap two LiveRanges with differing ValID's");
291     }
292   }
293
294   // Otherwise, this is just a new range that doesn't interact with anything.
295   // Insert it.
296   return ranges.insert(it, LR);
297 }
298
299 /// extendInBlock - If this interval is live before UseIdx in the basic
300 /// block that starts at StartIdx, extend it to be live at UseIdx and return
301 /// the value. If there is no live range before UseIdx, return NULL.
302 VNInfo *LiveInterval::extendInBlock(SlotIndex StartIdx, SlotIndex UseIdx) {
303   if (empty())
304     return 0;
305   iterator I = std::upper_bound(begin(), end(), UseIdx);
306   if (I == begin())
307     return 0;
308   --I;
309   if (I->end <= StartIdx)
310     return 0;
311   if (I->end <= UseIdx)
312     extendIntervalEndTo(I, UseIdx.getNextSlot());
313   return I->valno;
314 }
315
316 /// removeRange - Remove the specified range from this interval.  Note that
317 /// the range must be in a single LiveRange in its entirety.
318 void LiveInterval::removeRange(SlotIndex Start, SlotIndex End,
319                                bool RemoveDeadValNo) {
320   // Find the LiveRange containing this span.
321   Ranges::iterator I = find(Start);
322   assert(I != ranges.end() && "Range is not in interval!");
323   assert(I->containsRange(Start, End) && "Range is not entirely in interval!");
324
325   // If the span we are removing is at the start of the LiveRange, adjust it.
326   VNInfo *ValNo = I->valno;
327   if (I->start == Start) {
328     if (I->end == End) {
329       if (RemoveDeadValNo) {
330         // Check if val# is dead.
331         bool isDead = true;
332         for (const_iterator II = begin(), EE = end(); II != EE; ++II)
333           if (II != I && II->valno == ValNo) {
334             isDead = false;
335             break;
336           }
337         if (isDead) {
338           // Now that ValNo is dead, remove it.
339           markValNoForDeletion(ValNo);
340         }
341       }
342
343       ranges.erase(I);  // Removed the whole LiveRange.
344     } else
345       I->start = End;
346     return;
347   }
348
349   // Otherwise if the span we are removing is at the end of the LiveRange,
350   // adjust the other way.
351   if (I->end == End) {
352     I->end = Start;
353     return;
354   }
355
356   // Otherwise, we are splitting the LiveRange into two pieces.
357   SlotIndex OldEnd = I->end;
358   I->end = Start;   // Trim the old interval.
359
360   // Insert the new one.
361   ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo));
362 }
363
364 /// removeValNo - Remove all the ranges defined by the specified value#.
365 /// Also remove the value# from value# list.
366 void LiveInterval::removeValNo(VNInfo *ValNo) {
367   if (empty()) return;
368   Ranges::iterator I = ranges.end();
369   Ranges::iterator E = ranges.begin();
370   do {
371     --I;
372     if (I->valno == ValNo)
373       ranges.erase(I);
374   } while (I != E);
375   // Now that ValNo is dead, remove it.
376   markValNoForDeletion(ValNo);
377 }
378
379 /// findDefinedVNInfo - Find the VNInfo defined by the specified
380 /// index (register interval).
381 VNInfo *LiveInterval::findDefinedVNInfoForRegInt(SlotIndex Idx) const {
382   for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
383        i != e; ++i) {
384     if ((*i)->def == Idx)
385       return *i;
386   }
387
388   return 0;
389 }
390
391 /// join - Join two live intervals (this, and other) together.  This applies
392 /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
393 /// the intervals are not joinable, this aborts.
394 void LiveInterval::join(LiveInterval &Other,
395                         const int *LHSValNoAssignments,
396                         const int *RHSValNoAssignments,
397                         SmallVector<VNInfo*, 16> &NewVNInfo,
398                         MachineRegisterInfo *MRI) {
399   // Determine if any of our live range values are mapped.  This is uncommon, so
400   // we want to avoid the interval scan if not.
401   bool MustMapCurValNos = false;
402   unsigned NumVals = getNumValNums();
403   unsigned NumNewVals = NewVNInfo.size();
404   for (unsigned i = 0; i != NumVals; ++i) {
405     unsigned LHSValID = LHSValNoAssignments[i];
406     if (i != LHSValID ||
407         (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
408       MustMapCurValNos = true;
409   }
410
411   // If we have to apply a mapping to our base interval assignment, rewrite it
412   // now.
413   if (MustMapCurValNos) {
414     // Map the first live range.
415     iterator OutIt = begin();
416     OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
417     ++OutIt;
418     for (iterator I = OutIt, E = end(); I != E; ++I) {
419       OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
420
421       // If this live range has the same value # as its immediate predecessor,
422       // and if they are neighbors, remove one LiveRange.  This happens when we
423       // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
424       if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
425         (OutIt-1)->end = OutIt->end;
426       } else {
427         if (I != OutIt) {
428           OutIt->start = I->start;
429           OutIt->end = I->end;
430         }
431
432         // Didn't merge, on to the next one.
433         ++OutIt;
434       }
435     }
436
437     // If we merge some live ranges, chop off the end.
438     ranges.erase(OutIt, end());
439   }
440
441   // Remember assignements because val# ids are changing.
442   SmallVector<unsigned, 16> OtherAssignments;
443   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
444     OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
445
446   // Update val# info. Renumber them and make sure they all belong to this
447   // LiveInterval now. Also remove dead val#'s.
448   unsigned NumValNos = 0;
449   for (unsigned i = 0; i < NumNewVals; ++i) {
450     VNInfo *VNI = NewVNInfo[i];
451     if (VNI) {
452       if (NumValNos >= NumVals)
453         valnos.push_back(VNI);
454       else
455         valnos[NumValNos] = VNI;
456       VNI->id = NumValNos++;  // Renumber val#.
457     }
458   }
459   if (NumNewVals < NumVals)
460     valnos.resize(NumNewVals);  // shrinkify
461
462   // Okay, now insert the RHS live ranges into the LHS.
463   iterator InsertPos = begin();
464   unsigned RangeNo = 0;
465   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
466     // Map the valno in the other live range to the current live range.
467     I->valno = NewVNInfo[OtherAssignments[RangeNo]];
468     assert(I->valno && "Adding a dead range?");
469     InsertPos = addRangeFrom(*I, InsertPos);
470   }
471
472   ComputeJoinedWeight(Other);
473 }
474
475 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
476 /// interval as the specified value number.  The LiveRanges in RHS are
477 /// allowed to overlap with LiveRanges in the current interval, but only if
478 /// the overlapping LiveRanges have the specified value number.
479 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
480                                         VNInfo *LHSValNo) {
481   // TODO: Make this more efficient.
482   iterator InsertPos = begin();
483   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
484     // Map the valno in the other live range to the current live range.
485     LiveRange Tmp = *I;
486     Tmp.valno = LHSValNo;
487     InsertPos = addRangeFrom(Tmp, InsertPos);
488   }
489 }
490
491
492 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
493 /// in RHS into this live interval as the specified value number.
494 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
495 /// current interval, it will replace the value numbers of the overlaped
496 /// live ranges with the specified value number.
497 void LiveInterval::MergeValueInAsValue(
498                                     const LiveInterval &RHS,
499                                     const VNInfo *RHSValNo, VNInfo *LHSValNo) {
500   SmallVector<VNInfo*, 4> ReplacedValNos;
501   iterator IP = begin();
502   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
503     assert(I->valno == RHS.getValNumInfo(I->valno->id) && "Bad VNInfo");
504     if (I->valno != RHSValNo)
505       continue;
506     SlotIndex Start = I->start, End = I->end;
507     IP = std::upper_bound(IP, end(), Start);
508     // If the start of this range overlaps with an existing liverange, trim it.
509     if (IP != begin() && IP[-1].end > Start) {
510       if (IP[-1].valno != LHSValNo) {
511         ReplacedValNos.push_back(IP[-1].valno);
512         IP[-1].valno = LHSValNo; // Update val#.
513       }
514       Start = IP[-1].end;
515       // Trimmed away the whole range?
516       if (Start >= End) continue;
517     }
518     // If the end of this range overlaps with an existing liverange, trim it.
519     if (IP != end() && End > IP->start) {
520       if (IP->valno != LHSValNo) {
521         ReplacedValNos.push_back(IP->valno);
522         IP->valno = LHSValNo;  // Update val#.
523       }
524       End = IP->start;
525       // If this trimmed away the whole range, ignore it.
526       if (Start == End) continue;
527     }
528
529     // Map the valno in the other live range to the current live range.
530     IP = addRangeFrom(LiveRange(Start, End, LHSValNo), IP);
531   }
532
533
534   SmallSet<VNInfo*, 4> Seen;
535   for (unsigned i = 0, e = ReplacedValNos.size(); i != e; ++i) {
536     VNInfo *V1 = ReplacedValNos[i];
537     if (Seen.insert(V1)) {
538       bool isDead = true;
539       for (const_iterator I = begin(), E = end(); I != E; ++I)
540         if (I->valno == V1) {
541           isDead = false;
542           break;
543         }
544       if (isDead) {
545         // Now that V1 is dead, remove it.
546         markValNoForDeletion(V1);
547       }
548     }
549   }
550 }
551
552
553
554 /// MergeValueNumberInto - This method is called when two value nubmers
555 /// are found to be equivalent.  This eliminates V1, replacing all
556 /// LiveRanges with the V1 value number with the V2 value number.  This can
557 /// cause merging of V1/V2 values numbers and compaction of the value space.
558 VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
559   assert(V1 != V2 && "Identical value#'s are always equivalent!");
560
561   // This code actually merges the (numerically) larger value number into the
562   // smaller value number, which is likely to allow us to compactify the value
563   // space.  The only thing we have to be careful of is to preserve the
564   // instruction that defines the result value.
565
566   // Make sure V2 is smaller than V1.
567   if (V1->id < V2->id) {
568     V1->copyFrom(*V2);
569     std::swap(V1, V2);
570   }
571
572   // Merge V1 live ranges into V2.
573   for (iterator I = begin(); I != end(); ) {
574     iterator LR = I++;
575     if (LR->valno != V1) continue;  // Not a V1 LiveRange.
576
577     // Okay, we found a V1 live range.  If it had a previous, touching, V2 live
578     // range, extend it.
579     if (LR != begin()) {
580       iterator Prev = LR-1;
581       if (Prev->valno == V2 && Prev->end == LR->start) {
582         Prev->end = LR->end;
583
584         // Erase this live-range.
585         ranges.erase(LR);
586         I = Prev+1;
587         LR = Prev;
588       }
589     }
590
591     // Okay, now we have a V1 or V2 live range that is maximally merged forward.
592     // Ensure that it is a V2 live-range.
593     LR->valno = V2;
594
595     // If we can merge it into later V2 live ranges, do so now.  We ignore any
596     // following V1 live ranges, as they will be merged in subsequent iterations
597     // of the loop.
598     if (I != end()) {
599       if (I->start == LR->end && I->valno == V2) {
600         LR->end = I->end;
601         ranges.erase(I);
602         I = LR+1;
603       }
604     }
605   }
606
607   // Merge the relevant flags.
608   V2->mergeFlags(V1);
609
610   // Now that V1 is dead, remove it.
611   markValNoForDeletion(V1);
612
613   return V2;
614 }
615
616 void LiveInterval::Copy(const LiveInterval &RHS,
617                         MachineRegisterInfo *MRI,
618                         VNInfo::Allocator &VNInfoAllocator) {
619   ranges.clear();
620   valnos.clear();
621   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(RHS.reg);
622   MRI->setRegAllocationHint(reg, Hint.first, Hint.second);
623
624   weight = RHS.weight;
625   for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
626     const VNInfo *VNI = RHS.getValNumInfo(i);
627     createValueCopy(VNI, VNInfoAllocator);
628   }
629   for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
630     const LiveRange &LR = RHS.ranges[i];
631     addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
632   }
633 }
634
635 unsigned LiveInterval::getSize() const {
636   unsigned Sum = 0;
637   for (const_iterator I = begin(), E = end(); I != E; ++I)
638     Sum += I->start.distance(I->end);
639   return Sum;
640 }
641
642 /// ComputeJoinedWeight - Set the weight of a live interval Joined
643 /// after Other has been merged into it.
644 void LiveInterval::ComputeJoinedWeight(const LiveInterval &Other) {
645   // If either of these intervals was spilled, the weight is the
646   // weight of the non-spilled interval.  This can only happen with
647   // iterative coalescers.
648
649   if (Other.weight != HUGE_VALF) {
650     weight += Other.weight;
651   }
652   else if (weight == HUGE_VALF &&
653       !TargetRegisterInfo::isPhysicalRegister(reg)) {
654     // Remove this assert if you have an iterative coalescer
655     assert(0 && "Joining to spilled interval");
656     weight = Other.weight;
657   }
658   else {
659     // Otherwise the weight stays the same
660     // Remove this assert if you have an iterative coalescer
661     assert(0 && "Joining from spilled interval");
662   }
663 }
664
665 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) {
666   return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
667 }
668
669 void LiveRange::dump() const {
670   dbgs() << *this << "\n";
671 }
672
673 void LiveInterval::print(raw_ostream &OS, const TargetRegisterInfo *TRI) const {
674   OS << PrintReg(reg, TRI);
675   if (weight != 0)
676     OS << ',' << weight;
677
678   if (empty())
679     OS << " EMPTY";
680   else {
681     OS << " = ";
682     for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
683            E = ranges.end(); I != E; ++I) {
684       OS << *I;
685       assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
686     }
687   }
688
689   // Print value number info.
690   if (getNumValNums()) {
691     OS << "  ";
692     unsigned vnum = 0;
693     for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
694          ++i, ++vnum) {
695       const VNInfo *vni = *i;
696       if (vnum) OS << " ";
697       OS << vnum << "@";
698       if (vni->isUnused()) {
699         OS << "x";
700       } else {
701         OS << vni->def;
702         if (vni->isPHIDef())
703           OS << "-phidef";
704         if (vni->hasPHIKill())
705           OS << "-phikill";
706         if (vni->hasRedefByEC())
707           OS << "-ec";
708       }
709     }
710   }
711 }
712
713 void LiveInterval::dump() const {
714   dbgs() << *this << "\n";
715 }
716
717
718 void LiveRange::print(raw_ostream &os) const {
719   os << *this;
720 }
721
722 unsigned ConnectedVNInfoEqClasses::Classify(const LiveInterval *LI) {
723   // Create initial equivalence classes.
724   eqClass_.clear();
725   eqClass_.grow(LI->getNumValNums());
726
727   const VNInfo *used = 0, *unused = 0;
728
729   // Determine connections.
730   for (LiveInterval::const_vni_iterator I = LI->vni_begin(), E = LI->vni_end();
731        I != E; ++I) {
732     const VNInfo *VNI = *I;
733     // Group all unused values into one class.
734     if (VNI->isUnused()) {
735       if (unused)
736         eqClass_.join(unused->id, VNI->id);
737       unused = VNI;
738       continue;
739     }
740     used = VNI;
741     if (VNI->isPHIDef()) {
742       const MachineBasicBlock *MBB = lis_.getMBBFromIndex(VNI->def);
743       assert(MBB && "Phi-def has no defining MBB");
744       // Connect to values live out of predecessors.
745       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
746            PE = MBB->pred_end(); PI != PE; ++PI)
747         if (const VNInfo *PVNI =
748               LI->getVNInfoAt(lis_.getMBBEndIdx(*PI).getPrevSlot()))
749           eqClass_.join(VNI->id, PVNI->id);
750     } else {
751       // Normal value defined by an instruction. Check for two-addr redef.
752       // FIXME: This could be coincidental. Should we really check for a tied
753       // operand constraint?
754       // Note that VNI->def may be a use slot for an early clobber def.
755       if (const VNInfo *UVNI = LI->getVNInfoAt(VNI->def.getPrevSlot()))
756         eqClass_.join(VNI->id, UVNI->id);
757     }
758   }
759
760   // Lump all the unused values in with the last used value.
761   if (used && unused)
762     eqClass_.join(used->id, unused->id);
763
764   eqClass_.compress();
765   return eqClass_.getNumClasses();
766 }
767
768 void ConnectedVNInfoEqClasses::Distribute(LiveInterval *LIV[]) {
769   assert(LIV[0] && "LIV[0] must be set");
770   LiveInterval &LI = *LIV[0];
771
772   // First move runs to new intervals.
773   LiveInterval::iterator J = LI.begin(), E = LI.end();
774   while (J != E && eqClass_[J->valno->id] == 0)
775     ++J;
776   for (LiveInterval::iterator I = J; I != E; ++I) {
777     if (unsigned eq = eqClass_[I->valno->id]) {
778       assert((LIV[eq]->empty() || LIV[eq]->expiredAt(I->start)) &&
779              "New intervals should be empty");
780       LIV[eq]->ranges.push_back(*I);
781     } else
782       *J++ = *I;
783   }
784   LI.ranges.erase(J, E);
785
786   // Transfer VNInfos to their new owners and renumber them.
787   unsigned j = 0, e = LI.getNumValNums();
788   while (j != e && eqClass_[j] == 0)
789     ++j;
790   for (unsigned i = j; i != e; ++i) {
791     VNInfo *VNI = LI.getValNumInfo(i);
792     if (unsigned eq = eqClass_[i]) {
793       VNI->id = LIV[eq]->getNumValNums();
794       LIV[eq]->valnos.push_back(VNI);
795     } else {
796       VNI->id = j;
797       LI.valnos[j++] = VNI;
798     }
799   }
800   LI.valnos.resize(j);
801 }