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