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