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