1 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/CodeGen/LiveInterval.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/Streams.h"
24 #include "llvm/Target/MRegisterInfo.h"
30 // An example for liveAt():
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).
37 bool LiveInterval::liveAt(unsigned I) const {
38 Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I);
40 if (r == ranges.begin())
44 return r->contains(I);
47 // overlaps - Return true if the intersection of the two live intervals is
50 // An example for overlaps():
54 // 8: C = A + B ;; last use of A
56 // The live intervals should look like:
62 // A->overlaps(C) should return false since we want to be able to join
65 bool LiveInterval::overlapsFrom(const LiveInterval& other,
66 const_iterator StartPos) const {
67 const_iterator i = begin();
68 const_iterator ie = end();
69 const_iterator j = StartPos;
70 const_iterator je = other.end();
72 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
73 StartPos != other.end() && "Bogus start position hint!");
75 if (i->start < j->start) {
76 i = std::upper_bound(i, ie, j->start);
77 if (i != ranges.begin()) --i;
78 } else if (j->start < i->start) {
80 if (StartPos != other.end() && StartPos->start <= i->start) {
81 assert(StartPos < other.end() && i < end());
82 j = std::upper_bound(j, je, i->start);
83 if (j != other.ranges.begin()) --j;
89 if (j == je) return false;
92 if (i->start > j->start) {
97 if (i->end > j->start)
105 /// extendIntervalEndTo - This method is used when we want to extend the range
106 /// specified by I to end at the specified endpoint. To do this, we should
107 /// merge and eliminate all ranges that this will overlap with. The iterator is
109 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd) {
110 assert(I != ranges.end() && "Not a valid interval!");
111 VNInfo *ValNo = I->valno;
112 unsigned OldEnd = I->end;
114 // Search for the first interval that we can't merge with.
115 Ranges::iterator MergeTo = next(I);
116 for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
117 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
120 // If NewEnd was in the middle of an interval, make sure to get its endpoint.
121 I->end = std::max(NewEnd, prior(MergeTo)->end);
123 // Erase any dead ranges.
124 ranges.erase(next(I), MergeTo);
127 removeKills(ValNo, OldEnd, I->end-1);
129 // If the newly formed range now touches the range after it and if they have
130 // the same value number, merge the two ranges into one range.
131 Ranges::iterator Next = next(I);
132 if (Next != ranges.end() && Next->start <= I->end && Next->valno == ValNo) {
139 /// extendIntervalStartTo - This method is used when we want to extend the range
140 /// specified by I to start at the specified endpoint. To do this, we should
141 /// merge and eliminate all ranges that this will overlap with.
142 LiveInterval::Ranges::iterator
143 LiveInterval::extendIntervalStartTo(Ranges::iterator I, unsigned NewStart) {
144 assert(I != ranges.end() && "Not a valid interval!");
145 VNInfo *ValNo = I->valno;
147 // Search for the first interval that we can't merge with.
148 Ranges::iterator MergeTo = I;
150 if (MergeTo == ranges.begin()) {
152 ranges.erase(MergeTo, I);
155 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
157 } while (NewStart <= MergeTo->start);
159 // If we start in the middle of another interval, just delete a range and
160 // extend that interval.
161 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
162 MergeTo->end = I->end;
164 // Otherwise, extend the interval right after.
166 MergeTo->start = NewStart;
167 MergeTo->end = I->end;
170 ranges.erase(next(MergeTo), next(I));
174 LiveInterval::iterator
175 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
176 unsigned Start = LR.start, End = LR.end;
177 iterator it = std::upper_bound(From, ranges.end(), Start);
179 // If the inserted interval starts in the middle or right at the end of
180 // another interval, just extend that interval to contain the range of LR.
181 if (it != ranges.begin()) {
182 iterator B = prior(it);
183 if (LR.valno == B->valno) {
184 if (B->start <= Start && B->end >= Start) {
185 extendIntervalEndTo(B, End);
189 // Check to make sure that we are not overlapping two live ranges with
190 // different valno's.
191 assert(B->end <= Start &&
192 "Cannot overlap two LiveRanges with differing ValID's"
193 " (did you def the same reg twice in a MachineInstr?)");
197 // Otherwise, if this range ends in the middle of, or right next to, another
198 // interval, merge it into that interval.
199 if (it != ranges.end())
200 if (LR.valno == it->valno) {
201 if (it->start <= End) {
202 it = extendIntervalStartTo(it, Start);
204 // If LR is a complete superset of an interval, we may need to grow its
207 extendIntervalEndTo(it, End);
211 // Check to make sure that we are not overlapping two live ranges with
212 // different valno's.
213 assert(it->start >= End &&
214 "Cannot overlap two LiveRanges with differing ValID's");
217 // Otherwise, this is just a new range that doesn't interact with anything.
219 return ranges.insert(it, LR);
223 /// removeRange - Remove the specified range from this interval. Note that
224 /// the range must already be in this interval in its entirety.
225 void LiveInterval::removeRange(unsigned Start, unsigned End) {
226 // Find the LiveRange containing this span.
227 Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
228 assert(I != ranges.begin() && "Range is not in interval!");
230 assert(I->contains(Start) && I->contains(End-1) &&
231 "Range is not entirely in interval!");
233 // If the span we are removing is at the start of the LiveRange, adjust it.
234 if (I->start == Start) {
236 removeKills(I->valno, Start, End);
237 ranges.erase(I); // Removed the whole LiveRange.
243 // Otherwise if the span we are removing is at the end of the LiveRange,
244 // adjust the other way.
246 removeKills(I->valno, Start, End);
251 // Otherwise, we are splitting the LiveRange into two pieces.
252 unsigned OldEnd = I->end;
253 I->end = Start; // Trim the old interval.
255 // Insert the new one.
256 ranges.insert(next(I), LiveRange(End, OldEnd, I->valno));
259 /// getLiveRangeContaining - Return the live range that contains the
260 /// specified index, or null if there is none.
261 LiveInterval::const_iterator
262 LiveInterval::FindLiveRangeContaining(unsigned Idx) const {
263 const_iterator It = std::upper_bound(begin(), end(), Idx);
264 if (It != ranges.begin()) {
266 if (It->contains(Idx))
273 LiveInterval::iterator
274 LiveInterval::FindLiveRangeContaining(unsigned Idx) {
275 iterator It = std::upper_bound(begin(), end(), Idx);
278 if (It->contains(Idx))
285 /// join - Join two live intervals (this, and other) together. This applies
286 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
287 /// the intervals are not joinable, this aborts.
288 void LiveInterval::join(LiveInterval &Other, const int *LHSValNoAssignments,
289 const int *RHSValNoAssignments,
290 SmallVector<VNInfo*, 16> &NewVNInfo) {
291 // Determine if any of our live range values are mapped. This is uncommon, so
292 // we want to avoid the interval scan if not.
293 bool MustMapCurValNos = false;
294 unsigned NumVals = getNumValNums();
295 unsigned NumNewVals = NewVNInfo.size();
296 for (unsigned i = 0; i != NumVals; ++i) {
297 unsigned LHSValID = LHSValNoAssignments[i];
299 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
300 MustMapCurValNos = true;
303 // If we have to apply a mapping to our base interval assignment, rewrite it
305 if (MustMapCurValNos) {
306 // Map the first live range.
307 iterator OutIt = begin();
308 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
310 for (iterator I = OutIt, E = end(); I != E; ++I) {
311 OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
313 // If this live range has the same value # as its immediate predecessor,
314 // and if they are neighbors, remove one LiveRange. This happens when we
315 // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
316 if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
317 (OutIt-1)->end = OutIt->end;
320 OutIt->start = I->start;
324 // Didn't merge, on to the next one.
329 // If we merge some live ranges, chop off the end.
330 ranges.erase(OutIt, end());
333 // Remember assignements because val# ids are changing.
334 SmallVector<unsigned, 16> OtherAssignments;
335 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
336 OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
338 // Update val# info. Renumber them and make sure they all belong to this
339 // LiveInterval now. Also remove dead val#'s.
340 unsigned NumValNos = 0;
341 for (unsigned i = 0; i < NumNewVals; ++i) {
342 VNInfo *VNI = NewVNInfo[i];
345 valnos.push_back(VNI);
347 valnos[NumValNos] = VNI;
348 VNI->id = NumValNos++; // Renumber val#.
351 if (NumNewVals < NumVals)
352 valnos.resize(NumNewVals); // shrinkify
354 // Okay, now insert the RHS live ranges into the LHS.
355 iterator InsertPos = begin();
356 unsigned RangeNo = 0;
357 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
358 // Map the valno in the other live range to the current live range.
359 I->valno = NewVNInfo[OtherAssignments[RangeNo]];
360 assert(I->valno && "Adding a dead range?");
361 InsertPos = addRangeFrom(*I, InsertPos);
364 weight += Other.weight;
365 if (Other.preference && !preference)
366 preference = Other.preference;
369 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
370 /// interval as the specified value number. The LiveRanges in RHS are
371 /// allowed to overlap with LiveRanges in the current interval, but only if
372 /// the overlapping LiveRanges have the specified value number.
373 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
375 // TODO: Make this more efficient.
376 iterator InsertPos = begin();
377 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
378 // Map the valno in the other live range to the current live range.
380 Tmp.valno = LHSValNo;
381 InsertPos = addRangeFrom(Tmp, InsertPos);
386 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
387 /// in RHS into this live interval as the specified value number.
388 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
389 /// current interval, but only if the overlapping LiveRanges have the
390 /// specified value number.
391 void LiveInterval::MergeValueInAsValue(const LiveInterval &RHS,
392 VNInfo *RHSValNo, VNInfo *LHSValNo) {
393 // TODO: Make this more efficient.
394 iterator InsertPos = begin();
395 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
396 if (I->valno != RHSValNo)
398 // Map the valno in the other live range to the current live range.
400 Tmp.valno = LHSValNo;
401 InsertPos = addRangeFrom(Tmp, InsertPos);
406 /// MergeInClobberRanges - For any live ranges that are not defined in the
407 /// current interval, but are defined in the Clobbers interval, mark them
408 /// used with an unknown definition value.
409 void LiveInterval::MergeInClobberRanges(const LiveInterval &Clobbers,
410 BumpPtrAllocator &VNInfoAllocator) {
411 if (Clobbers.begin() == Clobbers.end()) return;
413 // Find a value # to use for the clobber ranges. If there is already a value#
414 // for unknown values, use it.
415 // FIXME: Use a single sentinal number for these!
416 VNInfo *ClobberValNo = getNextValue(~0U, 0, VNInfoAllocator);
418 iterator IP = begin();
419 for (const_iterator I = Clobbers.begin(), E = Clobbers.end(); I != E; ++I) {
420 unsigned Start = I->start, End = I->end;
421 IP = std::upper_bound(IP, end(), Start);
423 // If the start of this range overlaps with an existing liverange, trim it.
424 if (IP != begin() && IP[-1].end > Start) {
426 // Trimmed away the whole range?
427 if (Start >= End) continue;
429 // If the end of this range overlaps with an existing liverange, trim it.
430 if (IP != end() && End > IP->start) {
432 // If this trimmed away the whole range, ignore it.
433 if (Start == End) continue;
436 // Insert the clobber interval.
437 IP = addRangeFrom(LiveRange(Start, End, ClobberValNo), IP);
441 /// MergeValueNumberInto - This method is called when two value nubmers
442 /// are found to be equivalent. This eliminates V1, replacing all
443 /// LiveRanges with the V1 value number with the V2 value number. This can
444 /// cause merging of V1/V2 values numbers and compaction of the value space.
445 void LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
446 assert(V1 != V2 && "Identical value#'s are always equivalent!");
448 // This code actually merges the (numerically) larger value number into the
449 // smaller value number, which is likely to allow us to compactify the value
450 // space. The only thing we have to be careful of is to preserve the
451 // instruction that defines the result value.
453 // Make sure V2 is smaller than V1.
454 if (V1->id < V2->id) {
455 copyValNumInfo(V1, V2);
459 // Merge V1 live ranges into V2.
460 for (iterator I = begin(); I != end(); ) {
462 if (LR->valno != V1) continue; // Not a V1 LiveRange.
464 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
467 iterator Prev = LR-1;
468 if (Prev->valno == V2 && Prev->end == LR->start) {
471 // Erase this live-range.
478 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
479 // Ensure that it is a V2 live-range.
482 // If we can merge it into later V2 live ranges, do so now. We ignore any
483 // following V1 live ranges, as they will be merged in subsequent iterations
486 if (I->start == LR->end && I->valno == V2) {
494 // Now that V1 is dead, remove it. If it is the largest value number, just
495 // nuke it (and any other deleted values neighboring it), otherwise mark it as
496 // ~1U so it can be nuked later.
497 if (V1->id == getNumValNums()-1) {
499 VNInfo *VNI = valnos.back();
502 } while (valnos.back()->def == ~1U);
508 void LiveInterval::Copy(const LiveInterval &RHS,
509 BumpPtrAllocator &VNInfoAllocator) {
512 preference = RHS.preference;
514 for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
515 const VNInfo *VNI = RHS.getValNumInfo(i);
516 VNInfo *NewVNI = getNextValue(~0U, 0, VNInfoAllocator);
517 copyValNumInfo(NewVNI, VNI);
519 for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
520 const LiveRange &LR = RHS.ranges[i];
521 addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
525 unsigned LiveInterval::getSize() const {
527 for (const_iterator I = begin(), E = end(); I != E; ++I)
528 Sum += I->end - I->start;
532 std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) {
533 return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
536 void LiveRange::dump() const {
537 cerr << *this << "\n";
540 void LiveInterval::print(std::ostream &OS, const MRegisterInfo *MRI) const {
541 if (MRI && MRegisterInfo::isPhysicalRegister(reg))
542 OS << MRI->getName(reg);
552 for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
553 E = ranges.end(); I != E; ++I)
557 // Print value number info.
558 if (getNumValNums()) {
561 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
563 const VNInfo *vni = *i;
566 if (vni->def == ~1U) {
573 unsigned ee = vni->kills.size();
576 for (unsigned j = 0; j != ee; ++j) {
588 void LiveInterval::dump() const {
589 cerr << *this << "\n";
593 void LiveRange::print(std::ostream &os) const {