1 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/SmallSet.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Streams.h"
25 #include "llvm/Target/TargetRegisterInfo.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 // 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.
50 bool LiveInterval::liveBeforeAndAt(unsigned I) const {
51 Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I);
53 if (r == ranges.begin())
61 // I is the start of a live range. Check if the previous live range ends
63 if (r == ranges.begin())
68 // overlaps - Return true if the intersection of the two live intervals is
71 // An example for overlaps():
75 // 8: C = A + B ;; last use of A
77 // The live intervals should look like:
83 // A->overlaps(C) should return false since we want to be able to join
86 bool 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();
93 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
94 StartPos != other.end() && "Bogus start position hint!");
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) {
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;
110 if (j == je) return false;
113 if (i->start > j->start) {
118 if (i->end > j->start)
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
130 void 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;
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!");
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);
144 // Erase any dead ranges.
145 ranges.erase(next(I), MergeTo);
148 removeKills(ValNo, OldEnd, I->end-1);
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) {
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.
163 LiveInterval::Ranges::iterator
164 LiveInterval::extendIntervalStartTo(Ranges::iterator I, unsigned NewStart) {
165 assert(I != ranges.end() && "Not a valid interval!");
166 VNInfo *ValNo = I->valno;
168 // Search for the first interval that we can't merge with.
169 Ranges::iterator MergeTo = I;
171 if (MergeTo == ranges.begin()) {
173 ranges.erase(MergeTo, I);
176 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
178 } while (NewStart <= MergeTo->start);
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;
185 // Otherwise, extend the interval right after.
187 MergeTo->start = NewStart;
188 MergeTo->end = I->end;
191 ranges.erase(next(MergeTo), next(I));
195 LiveInterval::iterator
196 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
197 unsigned Start = LR.start, End = LR.end;
198 iterator it = std::upper_bound(From, ranges.end(), Start);
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);
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?)");
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);
225 // If LR is a complete superset of an interval, we may need to grow its
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);
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");
242 // Otherwise, this is just a new range that doesn't interact with anything.
244 return ranges.insert(it, LR);
248 /// removeRange - Remove the specified range from this interval. Note that
249 /// the range must already be in this interval in its entirety.
250 void LiveInterval::removeRange(unsigned Start, unsigned End,
251 bool RemoveDeadValNo) {
252 // Find the LiveRange containing this span.
253 Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
254 assert(I != ranges.begin() && "Range is not in interval!");
256 assert(I->contains(Start) && I->contains(End-1) &&
257 "Range is not entirely in interval!");
259 // If the span we are removing is at the start of the LiveRange, adjust it.
260 VNInfo *ValNo = I->valno;
261 if (I->start == Start) {
263 removeKills(I->valno, Start, End);
264 if (RemoveDeadValNo) {
265 // Check if val# is dead.
267 for (const_iterator II = begin(), EE = end(); II != EE; ++II)
268 if (II != I && II->valno == ValNo) {
273 // Now that ValNo is dead, remove it. If it is the largest value
274 // number, just nuke it (and any other deleted values neighboring it),
275 // otherwise mark it as ~1U so it can be nuked later.
276 if (ValNo->id == getNumValNums()-1) {
278 VNInfo *VNI = valnos.back();
281 } while (!valnos.empty() && valnos.back()->def == ~1U);
288 ranges.erase(I); // Removed the whole LiveRange.
294 // Otherwise if the span we are removing is at the end of the LiveRange,
295 // adjust the other way.
297 removeKills(ValNo, Start, End);
302 // Otherwise, we are splitting the LiveRange into two pieces.
303 unsigned OldEnd = I->end;
304 I->end = Start; // Trim the old interval.
306 // Insert the new one.
307 ranges.insert(next(I), LiveRange(End, OldEnd, ValNo));
310 /// removeValNo - Remove all the ranges defined by the specified value#.
311 /// Also remove the value# from value# list.
312 void LiveInterval::removeValNo(VNInfo *ValNo) {
314 Ranges::iterator I = ranges.end();
315 Ranges::iterator E = ranges.begin();
318 if (I->valno == ValNo)
321 // Now that ValNo is dead, remove it. If it is the largest value
322 // number, just nuke it (and any other deleted values neighboring it),
323 // otherwise mark it as ~1U so it can be nuked later.
324 if (ValNo->id == getNumValNums()-1) {
326 VNInfo *VNI = valnos.back();
329 } while (!valnos.empty() && valnos.back()->def == ~1U);
335 /// getLiveRangeContaining - Return the live range that contains the
336 /// specified index, or null if there is none.
337 LiveInterval::const_iterator
338 LiveInterval::FindLiveRangeContaining(unsigned Idx) const {
339 const_iterator It = std::upper_bound(begin(), end(), Idx);
340 if (It != ranges.begin()) {
342 if (It->contains(Idx))
349 LiveInterval::iterator
350 LiveInterval::FindLiveRangeContaining(unsigned Idx) {
351 iterator It = std::upper_bound(begin(), end(), Idx);
354 if (It->contains(Idx))
361 /// findDefinedVNInfo - Find the VNInfo that's defined at the specified index
362 /// (register interval) or defined by the specified register (stack inteval).
363 VNInfo *LiveInterval::findDefinedVNInfo(unsigned DefIdxOrReg) const {
365 for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
367 if ((*i)->def == DefIdxOrReg) {
375 /// join - Join two live intervals (this, and other) together. This applies
376 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
377 /// the intervals are not joinable, this aborts.
378 void LiveInterval::join(LiveInterval &Other, const int *LHSValNoAssignments,
379 const int *RHSValNoAssignments,
380 SmallVector<VNInfo*, 16> &NewVNInfo) {
381 // Determine if any of our live range values are mapped. This is uncommon, so
382 // we want to avoid the interval scan if not.
383 bool MustMapCurValNos = false;
384 unsigned NumVals = getNumValNums();
385 unsigned NumNewVals = NewVNInfo.size();
386 for (unsigned i = 0; i != NumVals; ++i) {
387 unsigned LHSValID = LHSValNoAssignments[i];
389 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
390 MustMapCurValNos = true;
393 // If we have to apply a mapping to our base interval assignment, rewrite it
395 if (MustMapCurValNos) {
396 // Map the first live range.
397 iterator OutIt = begin();
398 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
400 for (iterator I = OutIt, E = end(); I != E; ++I) {
401 OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
403 // If this live range has the same value # as its immediate predecessor,
404 // and if they are neighbors, remove one LiveRange. This happens when we
405 // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
406 if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
407 (OutIt-1)->end = OutIt->end;
410 OutIt->start = I->start;
414 // Didn't merge, on to the next one.
419 // If we merge some live ranges, chop off the end.
420 ranges.erase(OutIt, end());
423 // Remember assignements because val# ids are changing.
424 SmallVector<unsigned, 16> OtherAssignments;
425 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
426 OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
428 // Update val# info. Renumber them and make sure they all belong to this
429 // LiveInterval now. Also remove dead val#'s.
430 unsigned NumValNos = 0;
431 for (unsigned i = 0; i < NumNewVals; ++i) {
432 VNInfo *VNI = NewVNInfo[i];
435 valnos.push_back(VNI);
437 valnos[NumValNos] = VNI;
438 VNI->id = NumValNos++; // Renumber val#.
441 if (NumNewVals < NumVals)
442 valnos.resize(NumNewVals); // shrinkify
444 // Okay, now insert the RHS live ranges into the LHS.
445 iterator InsertPos = begin();
446 unsigned RangeNo = 0;
447 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
448 // Map the valno in the other live range to the current live range.
449 I->valno = NewVNInfo[OtherAssignments[RangeNo]];
450 assert(I->valno && "Adding a dead range?");
451 InsertPos = addRangeFrom(*I, InsertPos);
454 weight += Other.weight;
455 if (Other.preference && !preference)
456 preference = Other.preference;
459 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
460 /// interval as the specified value number. The LiveRanges in RHS are
461 /// allowed to overlap with LiveRanges in the current interval, but only if
462 /// the overlapping LiveRanges have the specified value number.
463 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
465 // TODO: Make this more efficient.
466 iterator InsertPos = begin();
467 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
468 // Map the valno in the other live range to the current live range.
470 Tmp.valno = LHSValNo;
471 InsertPos = addRangeFrom(Tmp, InsertPos);
476 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
477 /// in RHS into this live interval as the specified value number.
478 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
479 /// current interval, it will replace the value numbers of the overlaped
480 /// live ranges with the specified value number.
481 void LiveInterval::MergeValueInAsValue(const LiveInterval &RHS,
482 const VNInfo *RHSValNo, VNInfo *LHSValNo) {
483 SmallVector<VNInfo*, 4> ReplacedValNos;
484 iterator IP = begin();
485 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
486 if (I->valno != RHSValNo)
488 unsigned Start = I->start, End = I->end;
489 IP = std::upper_bound(IP, end(), Start);
490 // If the start of this range overlaps with an existing liverange, trim it.
491 if (IP != begin() && IP[-1].end > Start) {
492 if (IP[-1].valno != LHSValNo) {
493 ReplacedValNos.push_back(IP[-1].valno);
494 IP[-1].valno = LHSValNo; // Update val#.
497 // Trimmed away the whole range?
498 if (Start >= End) continue;
500 // If the end of this range overlaps with an existing liverange, trim it.
501 if (IP != end() && End > IP->start) {
502 if (IP->valno != LHSValNo) {
503 ReplacedValNos.push_back(IP->valno);
504 IP->valno = LHSValNo; // Update val#.
507 // If this trimmed away the whole range, ignore it.
508 if (Start == End) continue;
511 // Map the valno in the other live range to the current live range.
512 IP = addRangeFrom(LiveRange(Start, End, LHSValNo), IP);
516 SmallSet<VNInfo*, 4> Seen;
517 for (unsigned i = 0, e = ReplacedValNos.size(); i != e; ++i) {
518 VNInfo *V1 = ReplacedValNos[i];
519 if (Seen.insert(V1)) {
521 for (const_iterator I = begin(), E = end(); I != E; ++I)
522 if (I->valno == V1) {
527 // Now that V1 is dead, remove it. If it is the largest value number,
528 // just nuke it (and any other deleted values neighboring it), otherwise
529 // mark it as ~1U so it can be nuked later.
530 if (V1->id == getNumValNums()-1) {
532 VNInfo *VNI = valnos.back();
535 } while (!valnos.empty() && valnos.back()->def == ~1U);
545 /// MergeInClobberRanges - For any live ranges that are not defined in the
546 /// current interval, but are defined in the Clobbers interval, mark them
547 /// used with an unknown definition value.
548 void LiveInterval::MergeInClobberRanges(const LiveInterval &Clobbers,
549 BumpPtrAllocator &VNInfoAllocator) {
550 if (Clobbers.begin() == Clobbers.end()) return;
552 // Find a value # to use for the clobber ranges. If there is already a value#
553 // for unknown values, use it.
554 // FIXME: Use a single sentinal number for these!
555 VNInfo *ClobberValNo = getNextValue(~0U, 0, VNInfoAllocator);
557 iterator IP = begin();
558 for (const_iterator I = Clobbers.begin(), E = Clobbers.end(); I != E; ++I) {
559 unsigned Start = I->start, End = I->end;
560 IP = std::upper_bound(IP, end(), Start);
562 // If the start of this range overlaps with an existing liverange, trim it.
563 if (IP != begin() && IP[-1].end > Start) {
565 // Trimmed away the whole range?
566 if (Start >= End) continue;
568 // If the end of this range overlaps with an existing liverange, trim it.
569 if (IP != end() && End > IP->start) {
571 // If this trimmed away the whole range, ignore it.
572 if (Start == End) continue;
575 // Insert the clobber interval.
576 IP = addRangeFrom(LiveRange(Start, End, ClobberValNo), IP);
580 /// MergeValueNumberInto - This method is called when two value nubmers
581 /// are found to be equivalent. This eliminates V1, replacing all
582 /// LiveRanges with the V1 value number with the V2 value number. This can
583 /// cause merging of V1/V2 values numbers and compaction of the value space.
584 void LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
585 assert(V1 != V2 && "Identical value#'s are always equivalent!");
587 // This code actually merges the (numerically) larger value number into the
588 // smaller value number, which is likely to allow us to compactify the value
589 // space. The only thing we have to be careful of is to preserve the
590 // instruction that defines the result value.
592 // Make sure V2 is smaller than V1.
593 if (V1->id < V2->id) {
594 copyValNumInfo(V1, V2);
598 // Merge V1 live ranges into V2.
599 for (iterator I = begin(); I != end(); ) {
601 if (LR->valno != V1) continue; // Not a V1 LiveRange.
603 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
606 iterator Prev = LR-1;
607 if (Prev->valno == V2 && Prev->end == LR->start) {
610 // Erase this live-range.
617 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
618 // Ensure that it is a V2 live-range.
621 // If we can merge it into later V2 live ranges, do so now. We ignore any
622 // following V1 live ranges, as they will be merged in subsequent iterations
625 if (I->start == LR->end && I->valno == V2) {
633 // Now that V1 is dead, remove it. If it is the largest value number, just
634 // nuke it (and any other deleted values neighboring it), otherwise mark it as
635 // ~1U so it can be nuked later.
636 if (V1->id == getNumValNums()-1) {
638 VNInfo *VNI = valnos.back();
641 } while (valnos.back()->def == ~1U);
647 void LiveInterval::Copy(const LiveInterval &RHS,
648 BumpPtrAllocator &VNInfoAllocator) {
651 preference = RHS.preference;
653 for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
654 const VNInfo *VNI = RHS.getValNumInfo(i);
655 VNInfo *NewVNI = getNextValue(~0U, 0, VNInfoAllocator);
656 copyValNumInfo(NewVNI, VNI);
658 for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
659 const LiveRange &LR = RHS.ranges[i];
660 addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
664 unsigned LiveInterval::getSize() const {
666 for (const_iterator I = begin(), E = end(); I != E; ++I)
667 Sum += I->end - I->start;
671 std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) {
672 return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
675 void LiveRange::dump() const {
676 cerr << *this << "\n";
679 void LiveInterval::print(std::ostream &OS,
680 const TargetRegisterInfo *TRI) const {
682 OS << "SS#" << getStackSlotIndex();
683 else if (TRI && TargetRegisterInfo::isPhysicalRegister(reg))
684 OS << TRI->getName(reg);
694 for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
695 E = ranges.end(); I != E; ++I)
699 // Print value number info.
700 if (getNumValNums()) {
703 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
705 const VNInfo *vni = *i;
708 if (vni->def == ~1U) {
715 unsigned ee = vni->kills.size();
716 if (ee || vni->hasPHIKill) {
718 for (unsigned j = 0; j != ee; ++j) {
723 if (vni->hasPHIKill) {
735 void LiveInterval::dump() const {
736 cerr << *this << "\n";
740 void LiveRange::print(std::ostream &os) const {