LiveInterval.cpp revision edf128a7fa90f2b0b7ee24741a04a7ae1ecd6f7e
1//===-- LiveInterval.cpp - Live Interval Representation -------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the 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 "LiveInterval.h"
22#include "llvm/ADT/STLExtras.h"
23#include <algorithm>
24#include <iostream>
25#include <map>
26using namespace llvm;
27
28// An example for liveAt():
29//
30// this = [1,4), liveAt(0) will return false. The instruction defining this
31// spans slots [0,3]. The interval belongs to an spilled definition of the
32// variable it represents. This is because slot 1 is used (def slot) and spans
33// up to slot 3 (store slot).
34//
35bool LiveInterval::liveAt(unsigned I) const {
36  Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I);
37
38  if (r == ranges.begin())
39    return false;
40
41  --r;
42  return r->contains(I);
43}
44
45// overlaps - Return true if the intersection of the two live intervals is
46// not empty.
47//
48// An example for overlaps():
49//
50// 0: A = ...
51// 4: B = ...
52// 8: C = A + B ;; last use of A
53//
54// The live intervals should look like:
55//
56// A = [3, 11)
57// B = [7, x)
58// C = [11, y)
59//
60// A->overlaps(C) should return false since we want to be able to join
61// A and C.
62//
63bool LiveInterval::overlapsFrom(const LiveInterval& other,
64                                const_iterator StartPos) const {
65  const_iterator i = begin();
66  const_iterator ie = end();
67  const_iterator j = StartPos;
68  const_iterator je = other.end();
69
70  assert((StartPos->start <= i->start || StartPos == other.begin()) &&
71         StartPos != other.end() && "Bogus start position hint!");
72
73  if (i->start < j->start) {
74    i = std::upper_bound(i, ie, j->start);
75    if (i != ranges.begin()) --i;
76  } else if (j->start < i->start) {
77    ++StartPos;
78    if (StartPos != other.end() && StartPos->start <= i->start) {
79      assert(StartPos < other.end() && i < end());
80      j = std::upper_bound(j, je, i->start);
81      if (j != other.ranges.begin()) --j;
82    }
83  } else {
84    return true;
85  }
86
87  if (j == je) return false;
88
89  while (i != ie) {
90    if (i->start > j->start) {
91      std::swap(i, j);
92      std::swap(ie, je);
93    }
94
95    if (i->end > j->start)
96      return true;
97    ++i;
98  }
99
100  return false;
101}
102
103/// joinable - Two intervals are joinable if the either don't overlap at all
104/// or if the destination of the copy is a single assignment value, and it
105/// only overlaps with one value in the source interval.
106bool LiveInterval::joinable(const LiveInterval &other, unsigned CopyIdx) const {
107  const LiveRange *SourceLR = other.getLiveRangeContaining(CopyIdx-1);
108  const LiveRange *DestLR = getLiveRangeContaining(CopyIdx);
109  assert(SourceLR && DestLR && "Not joining due to a copy?");
110  unsigned OtherValIdx = SourceLR->ValId;
111  unsigned ThisValIdx = DestLR->ValId;
112
113  Ranges::const_iterator i = ranges.begin();
114  Ranges::const_iterator ie = ranges.end();
115  Ranges::const_iterator j = other.ranges.begin();
116  Ranges::const_iterator je = other.ranges.end();
117
118  if (i->start < j->start) {
119    i = std::upper_bound(i, ie, j->start);
120    if (i != ranges.begin()) --i;
121  } else if (j->start < i->start) {
122    j = std::upper_bound(j, je, i->start);
123    if (j != other.ranges.begin()) --j;
124  }
125
126  while (i != ie && j != je) {
127    if (i->start == j->start) {
128      // If this is not the allowed value merge, we cannot join.
129      if (i->ValId != ThisValIdx || j->ValId != OtherValIdx)
130        return false;
131    } else if (i->start < j->start) {
132      if (i->end > j->start) {
133        if (i->ValId != ThisValIdx || j->ValId != OtherValIdx)
134          return false;
135      }
136    } else {
137      if (j->end > i->start) {
138        if (i->ValId != ThisValIdx || j->ValId != OtherValIdx)
139          return false;
140      }
141    }
142    if (i->end < j->end)
143      ++i;
144    else
145      ++j;
146  }
147
148  return true;
149}
150
151
152/// extendIntervalEndTo - This method is used when we want to extend the range
153/// specified by I to end at the specified endpoint.  To do this, we should
154/// merge and eliminate all ranges that this will overlap with.  The iterator is
155/// not invalidated.
156void LiveInterval::extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd) {
157  assert(I != ranges.end() && "Not a valid interval!");
158  unsigned ValId = I->ValId;
159
160  // Search for the first interval that we can't merge with.
161  Ranges::iterator MergeTo = next(I);
162  for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
163    assert(MergeTo->ValId == ValId && "Cannot merge with differing values!");
164  }
165
166  // If NewEnd was in the middle of an interval, make sure to get its endpoint.
167  I->end = std::max(NewEnd, prior(MergeTo)->end);
168
169  // Erase any dead ranges
170  ranges.erase(next(I), MergeTo);
171}
172
173
174/// extendIntervalStartTo - This method is used when we want to extend the range
175/// specified by I to start at the specified endpoint.  To do this, we should
176/// merge and eliminate all ranges that this will overlap with.
177LiveInterval::Ranges::iterator
178LiveInterval::extendIntervalStartTo(Ranges::iterator I, unsigned NewStart) {
179  assert(I != ranges.end() && "Not a valid interval!");
180  unsigned ValId = I->ValId;
181
182  // Search for the first interval that we can't merge with.
183  Ranges::iterator MergeTo = I;
184  do {
185    if (MergeTo == ranges.begin()) {
186      I->start = NewStart;
187      ranges.erase(MergeTo, I);
188      return I;
189    }
190    assert(MergeTo->ValId == ValId && "Cannot merge with differing values!");
191    --MergeTo;
192  } while (NewStart <= MergeTo->start);
193
194  // If we start in the middle of another interval, just delete a range and
195  // extend that interval.
196  if (MergeTo->end >= NewStart && MergeTo->ValId == ValId) {
197    MergeTo->end = I->end;
198  } else {
199    // Otherwise, extend the interval right after.
200    ++MergeTo;
201    MergeTo->start = NewStart;
202    MergeTo->end = I->end;
203  }
204
205  ranges.erase(next(MergeTo), next(I));
206  return MergeTo;
207}
208
209LiveInterval::Ranges::iterator
210LiveInterval::addRangeFrom(LiveRange LR, Ranges::iterator From) {
211  unsigned Start = LR.start, End = LR.end;
212  Ranges::iterator it = std::upper_bound(From, ranges.end(), Start);
213
214  // If the inserted interval starts in the middle or right at the end of
215  // another interval, just extend that interval to contain the range of LR.
216  if (it != ranges.begin()) {
217    Ranges::iterator B = prior(it);
218    if (LR.ValId == B->ValId) {
219      if (B->start <= Start && B->end >= Start) {
220        extendIntervalEndTo(B, End);
221        return B;
222      }
223    } else {
224      // Check to make sure that we are not overlapping two live ranges with
225      // different ValId's.
226      assert(B->end <= Start &&
227             "Cannot overlap two LiveRanges with differing ValID's"
228             " (did you def the same reg twice in a MachineInstr?)");
229    }
230  }
231
232  // Otherwise, if this range ends in the middle of, or right next to, another
233  // interval, merge it into that interval.
234  if (it != ranges.end())
235    if (LR.ValId == it->ValId) {
236      if (it->start <= End) {
237        it = extendIntervalStartTo(it, Start);
238
239        // If LR is a complete superset of an interval, we may need to grow its
240        // endpoint as well.
241        if (End > it->end)
242          extendIntervalEndTo(it, End);
243        return it;
244      }
245    } else {
246      // Check to make sure that we are not overlapping two live ranges with
247      // different ValId's.
248      assert(it->start >= End &&
249             "Cannot overlap two LiveRanges with differing ValID's");
250    }
251
252  // Otherwise, this is just a new range that doesn't interact with anything.
253  // Insert it.
254  return ranges.insert(it, LR);
255}
256
257
258/// removeRange - Remove the specified range from this interval.  Note that
259/// the range must already be in this interval in its entirety.
260void LiveInterval::removeRange(unsigned Start, unsigned End) {
261  // Find the LiveRange containing this span.
262  Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
263  assert(I != ranges.begin() && "Range is not in interval!");
264  --I;
265  assert(I->contains(Start) && I->contains(End-1) &&
266         "Range is not entirely in interval!");
267
268  // If the span we are removing is at the start of the LiveRange, adjust it.
269  if (I->start == Start) {
270    if (I->end == End)
271      ranges.erase(I);  // Removed the whole LiveRange.
272    else
273      I->start = End;
274    return;
275  }
276
277  // Otherwise if the span we are removing is at the end of the LiveRange,
278  // adjust the other way.
279  if (I->end == End) {
280    I->end = Start;
281    return;
282  }
283
284  // Otherwise, we are splitting the LiveRange into two pieces.
285  unsigned OldEnd = I->end;
286  I->end = Start;   // Trim the old interval.
287
288  // Insert the new one.
289  ranges.insert(next(I), LiveRange(End, OldEnd, I->ValId));
290}
291
292/// getLiveRangeContaining - Return the live range that contains the
293/// specified index, or null if there is none.
294const LiveRange *LiveInterval::getLiveRangeContaining(unsigned Idx) const {
295  Ranges::const_iterator It = std::upper_bound(ranges.begin(),ranges.end(),Idx);
296  if (It != ranges.begin()) {
297    const LiveRange &LR = *prior(It);
298    if (LR.contains(Idx))
299      return &LR;
300  }
301
302  return 0;
303}
304
305
306
307/// join - Join two live intervals (this, and other) together.  This operation
308/// is the result of a copy instruction in the source program, that occurs at
309/// index 'CopyIdx' that copies from 'Other' to 'this'.
310void LiveInterval::join(LiveInterval &Other, unsigned CopyIdx) {
311  const LiveRange *SourceLR = Other.getLiveRangeContaining(CopyIdx-1);
312  const LiveRange *DestLR = getLiveRangeContaining(CopyIdx);
313  assert(SourceLR && DestLR && "Not joining due to a copy?");
314  unsigned MergedSrcValIdx = SourceLR->ValId;
315  unsigned MergedDstValIdx = DestLR->ValId;
316
317  // Try to do the least amount of work possible.  In particular, if there are
318  // more liverange chunks in the other set than there are in the 'this' set,
319  // swap sets to merge the fewest chunks in possible.
320  if (Other.ranges.size() > ranges.size()) {
321    std::swap(MergedSrcValIdx, MergedDstValIdx);
322    std::swap(ranges, Other.ranges);
323    std::swap(NumValues, Other.NumValues);
324  }
325
326  // Join the ranges of other into the ranges of this interval.
327  Ranges::iterator InsertPos = ranges.begin();
328  std::map<unsigned, unsigned> Dst2SrcIdxMap;
329  for (Ranges::iterator I = Other.ranges.begin(),
330         E = Other.ranges.end(); I != E; ++I) {
331    // Map the ValId in the other live range to the current live range.
332    if (I->ValId == MergedSrcValIdx)
333      I->ValId = MergedDstValIdx;
334    else {
335      unsigned &NV = Dst2SrcIdxMap[I->ValId];
336      if (NV == 0) NV = getNextValue();
337      I->ValId = NV;
338    }
339
340    InsertPos = addRangeFrom(*I, InsertPos);
341  }
342
343  weight += Other.weight;
344}
345
346std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) {
347  return os << '[' << LR.start << ',' << LR.end << ':' << LR.ValId << ")";
348}
349
350void LiveRange::dump() const {
351  std::cerr << *this << "\n";
352}
353
354
355std::ostream& llvm::operator<<(std::ostream& os, const LiveInterval& li) {
356  os << "%reg" << li.reg << ',' << li.weight;
357  if (li.empty())
358    return os << "EMPTY";
359
360  os << " = ";
361  for (LiveInterval::Ranges::const_iterator i = li.ranges.begin(),
362         e = li.ranges.end(); i != e; ++i)
363    os << *i;
364  return os;
365}
366
367void LiveInterval::dump() const {
368  std::cerr << *this << "\n";
369}
370