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' 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.
19 //===----------------------------------------------------------------------===//
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"
33 // CompEnd - Compare LiveRange ends.
36 bool operator()(const LiveRange &A, const LiveRange &B) const {
42 LiveInterval::iterator LiveInterval::find(SlotIndex Pos) {
43 return std::upper_bound(begin(), end(), LiveRange(SlotIndex(), Pos, 0),
47 /// killedInRange - Return true if the interval has kills in [Start,End).
48 bool LiveInterval::killedInRange(SlotIndex Start, SlotIndex End) const {
49 Ranges::const_iterator r =
50 std::lower_bound(ranges.begin(), ranges.end(), End);
52 // Now r points to the first interval with start >= End, or ranges.end().
53 if (r == ranges.begin())
57 // Now r points to the last interval with end <= End.
58 // r->end is the kill point.
59 return r->end >= Start && r->end < End;
62 // overlaps - Return true if the intersection of the two live intervals is
65 // An example for overlaps():
69 // 8: C = A + B ;; last use of A
71 // The live intervals should look like:
77 // A->overlaps(C) should return false since we want to be able to join
80 bool LiveInterval::overlapsFrom(const LiveInterval& other,
81 const_iterator StartPos) const {
82 assert(!empty() && "empty interval");
83 const_iterator i = begin();
84 const_iterator ie = end();
85 const_iterator j = StartPos;
86 const_iterator je = other.end();
88 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
89 StartPos != other.end() && "Bogus start position hint!");
91 if (i->start < j->start) {
92 i = std::upper_bound(i, ie, j->start);
93 if (i != ranges.begin()) --i;
94 } else if (j->start < i->start) {
96 if (StartPos != other.end() && StartPos->start <= i->start) {
97 assert(StartPos < other.end() && i < end());
98 j = std::upper_bound(j, je, i->start);
99 if (j != other.ranges.begin()) --j;
105 if (j == je) return false;
108 if (i->start > j->start) {
113 if (i->end > j->start)
121 /// overlaps - Return true if the live interval overlaps a range specified
123 bool LiveInterval::overlaps(SlotIndex Start, SlotIndex End) const {
124 assert(Start < End && "Invalid range");
125 const_iterator I = std::lower_bound(begin(), end(), End);
126 return I != begin() && (--I)->end > Start;
130 /// ValNo is dead, remove it. If it is the largest value number, just nuke it
131 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
132 /// it can be nuked later.
133 void LiveInterval::markValNoForDeletion(VNInfo *ValNo) {
134 if (ValNo->id == getNumValNums()-1) {
137 } while (!valnos.empty() && valnos.back()->isUnused());
139 ValNo->setIsUnused(true);
143 /// RenumberValues - Renumber all values in order of appearance and delete the
144 /// remaining unused values.
145 void LiveInterval::RenumberValues(LiveIntervals &lis) {
146 SmallPtrSet<VNInfo*, 8> Seen;
147 bool seenPHIDef = false;
149 for (const_iterator I = begin(), E = end(); I != E; ++I) {
150 VNInfo *VNI = I->valno;
151 if (!Seen.insert(VNI))
153 assert(!VNI->isUnused() && "Unused valno used by live range");
154 VNI->id = (unsigned)valnos.size();
155 valnos.push_back(VNI);
156 VNI->setHasPHIKill(false);
161 // Recompute phi kill flags.
164 for (const_vni_iterator I = vni_begin(), E = vni_end(); I != E; ++I) {
166 if (!VNI->isPHIDef())
168 const MachineBasicBlock *PHIBB = lis.getMBBFromIndex(VNI->def);
169 assert(PHIBB && "No basic block for phi-def");
170 for (MachineBasicBlock::const_pred_iterator PI = PHIBB->pred_begin(),
171 PE = PHIBB->pred_end(); PI != PE; ++PI) {
172 VNInfo *KVNI = getVNInfoAt(lis.getMBBEndIdx(*PI).getPrevSlot());
174 KVNI->setHasPHIKill(true);
179 /// extendIntervalEndTo - This method is used when we want to extend the range
180 /// specified by I to end at the specified endpoint. To do this, we should
181 /// merge and eliminate all ranges that this will overlap with. The iterator is
183 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) {
184 assert(I != ranges.end() && "Not a valid interval!");
185 VNInfo *ValNo = I->valno;
187 // Search for the first interval that we can't merge with.
188 Ranges::iterator MergeTo = llvm::next(I);
189 for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
190 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
193 // If NewEnd was in the middle of an interval, make sure to get its endpoint.
194 I->end = std::max(NewEnd, prior(MergeTo)->end);
196 // Erase any dead ranges.
197 ranges.erase(llvm::next(I), MergeTo);
199 // If the newly formed range now touches the range after it and if they have
200 // the same value number, merge the two ranges into one range.
201 Ranges::iterator Next = llvm::next(I);
202 if (Next != ranges.end() && Next->start <= I->end && Next->valno == ValNo) {
209 /// extendIntervalStartTo - This method is used when we want to extend the range
210 /// specified by I to start at the specified endpoint. To do this, we should
211 /// merge and eliminate all ranges that this will overlap with.
212 LiveInterval::Ranges::iterator
213 LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) {
214 assert(I != ranges.end() && "Not a valid interval!");
215 VNInfo *ValNo = I->valno;
217 // Search for the first interval that we can't merge with.
218 Ranges::iterator MergeTo = I;
220 if (MergeTo == ranges.begin()) {
222 ranges.erase(MergeTo, I);
225 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
227 } while (NewStart <= MergeTo->start);
229 // If we start in the middle of another interval, just delete a range and
230 // extend that interval.
231 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
232 MergeTo->end = I->end;
234 // Otherwise, extend the interval right after.
236 MergeTo->start = NewStart;
237 MergeTo->end = I->end;
240 ranges.erase(llvm::next(MergeTo), llvm::next(I));
244 LiveInterval::iterator
245 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
246 SlotIndex Start = LR.start, End = LR.end;
247 iterator it = std::upper_bound(From, ranges.end(), Start);
249 // If the inserted interval starts in the middle or right at the end of
250 // another interval, just extend that interval to contain the range of LR.
251 if (it != ranges.begin()) {
252 iterator B = prior(it);
253 if (LR.valno == B->valno) {
254 if (B->start <= Start && B->end >= Start) {
255 extendIntervalEndTo(B, End);
259 // Check to make sure that we are not overlapping two live ranges with
260 // different valno's.
261 assert(B->end <= Start &&
262 "Cannot overlap two LiveRanges with differing ValID's"
263 " (did you def the same reg twice in a MachineInstr?)");
267 // Otherwise, if this range ends in the middle of, or right next to, another
268 // interval, merge it into that interval.
269 if (it != ranges.end()) {
270 if (LR.valno == it->valno) {
271 if (it->start <= End) {
272 it = extendIntervalStartTo(it, Start);
274 // If LR is a complete superset of an interval, we may need to grow its
277 extendIntervalEndTo(it, End);
281 // Check to make sure that we are not overlapping two live ranges with
282 // different valno's.
283 assert(it->start >= End &&
284 "Cannot overlap two LiveRanges with differing ValID's");
288 // Otherwise, this is just a new range that doesn't interact with anything.
290 return ranges.insert(it, LR);
294 /// removeRange - Remove the specified range from this interval. Note that
295 /// the range must be in a single LiveRange in its entirety.
296 void LiveInterval::removeRange(SlotIndex Start, SlotIndex End,
297 bool RemoveDeadValNo) {
298 // Find the LiveRange containing this span.
299 Ranges::iterator I = find(Start);
300 assert(I != ranges.end() && "Range is not in interval!");
301 assert(I->containsRange(Start, End) && "Range is not entirely in interval!");
303 // If the span we are removing is at the start of the LiveRange, adjust it.
304 VNInfo *ValNo = I->valno;
305 if (I->start == Start) {
307 if (RemoveDeadValNo) {
308 // Check if val# is dead.
310 for (const_iterator II = begin(), EE = end(); II != EE; ++II)
311 if (II != I && II->valno == ValNo) {
316 // Now that ValNo is dead, remove it.
317 markValNoForDeletion(ValNo);
321 ranges.erase(I); // Removed the whole LiveRange.
327 // Otherwise if the span we are removing is at the end of the LiveRange,
328 // adjust the other way.
334 // Otherwise, we are splitting the LiveRange into two pieces.
335 SlotIndex OldEnd = I->end;
336 I->end = Start; // Trim the old interval.
338 // Insert the new one.
339 ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo));
342 /// removeValNo - Remove all the ranges defined by the specified value#.
343 /// Also remove the value# from value# list.
344 void LiveInterval::removeValNo(VNInfo *ValNo) {
346 Ranges::iterator I = ranges.end();
347 Ranges::iterator E = ranges.begin();
350 if (I->valno == ValNo)
353 // Now that ValNo is dead, remove it.
354 markValNoForDeletion(ValNo);
357 /// findDefinedVNInfo - Find the VNInfo defined by the specified
358 /// index (register interval).
359 VNInfo *LiveInterval::findDefinedVNInfoForRegInt(SlotIndex Idx) const {
360 for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
362 if ((*i)->def == Idx)
369 /// join - Join two live intervals (this, and other) together. This applies
370 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
371 /// the intervals are not joinable, this aborts.
372 void LiveInterval::join(LiveInterval &Other,
373 const int *LHSValNoAssignments,
374 const int *RHSValNoAssignments,
375 SmallVector<VNInfo*, 16> &NewVNInfo,
376 MachineRegisterInfo *MRI) {
377 // Determine if any of our live range values are mapped. This is uncommon, so
378 // we want to avoid the interval scan if not.
379 bool MustMapCurValNos = false;
380 unsigned NumVals = getNumValNums();
381 unsigned NumNewVals = NewVNInfo.size();
382 for (unsigned i = 0; i != NumVals; ++i) {
383 unsigned LHSValID = LHSValNoAssignments[i];
385 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
386 MustMapCurValNos = true;
389 // If we have to apply a mapping to our base interval assignment, rewrite it
391 if (MustMapCurValNos) {
392 // Map the first live range.
393 iterator OutIt = begin();
394 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
396 for (iterator I = OutIt, E = end(); I != E; ++I) {
397 OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
399 // If this live range has the same value # as its immediate predecessor,
400 // and if they are neighbors, remove one LiveRange. This happens when we
401 // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
402 if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
403 (OutIt-1)->end = OutIt->end;
406 OutIt->start = I->start;
410 // Didn't merge, on to the next one.
415 // If we merge some live ranges, chop off the end.
416 ranges.erase(OutIt, end());
419 // Remember assignements because val# ids are changing.
420 SmallVector<unsigned, 16> OtherAssignments;
421 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
422 OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
424 // Update val# info. Renumber them and make sure they all belong to this
425 // LiveInterval now. Also remove dead val#'s.
426 unsigned NumValNos = 0;
427 for (unsigned i = 0; i < NumNewVals; ++i) {
428 VNInfo *VNI = NewVNInfo[i];
430 if (NumValNos >= NumVals)
431 valnos.push_back(VNI);
433 valnos[NumValNos] = VNI;
434 VNI->id = NumValNos++; // Renumber val#.
437 if (NumNewVals < NumVals)
438 valnos.resize(NumNewVals); // shrinkify
440 // Okay, now insert the RHS live ranges into the LHS.
441 iterator InsertPos = begin();
442 unsigned RangeNo = 0;
443 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
444 // Map the valno in the other live range to the current live range.
445 I->valno = NewVNInfo[OtherAssignments[RangeNo]];
446 assert(I->valno && "Adding a dead range?");
447 InsertPos = addRangeFrom(*I, InsertPos);
450 ComputeJoinedWeight(Other);
453 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
454 /// interval as the specified value number. The LiveRanges in RHS are
455 /// allowed to overlap with LiveRanges in the current interval, but only if
456 /// the overlapping LiveRanges have the specified value number.
457 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
459 // TODO: Make this more efficient.
460 iterator InsertPos = begin();
461 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
462 // Map the valno in the other live range to the current live range.
464 Tmp.valno = LHSValNo;
465 InsertPos = addRangeFrom(Tmp, InsertPos);
470 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
471 /// in RHS into this live interval as the specified value number.
472 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
473 /// current interval, it will replace the value numbers of the overlaped
474 /// live ranges with the specified value number.
475 void LiveInterval::MergeValueInAsValue(
476 const LiveInterval &RHS,
477 const VNInfo *RHSValNo, VNInfo *LHSValNo) {
478 SmallVector<VNInfo*, 4> ReplacedValNos;
479 iterator IP = begin();
480 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
481 assert(I->valno == RHS.getValNumInfo(I->valno->id) && "Bad VNInfo");
482 if (I->valno != RHSValNo)
484 SlotIndex Start = I->start, End = I->end;
485 IP = std::upper_bound(IP, end(), Start);
486 // If the start of this range overlaps with an existing liverange, trim it.
487 if (IP != begin() && IP[-1].end > Start) {
488 if (IP[-1].valno != LHSValNo) {
489 ReplacedValNos.push_back(IP[-1].valno);
490 IP[-1].valno = LHSValNo; // Update val#.
493 // Trimmed away the whole range?
494 if (Start >= End) continue;
496 // If the end of this range overlaps with an existing liverange, trim it.
497 if (IP != end() && End > IP->start) {
498 if (IP->valno != LHSValNo) {
499 ReplacedValNos.push_back(IP->valno);
500 IP->valno = LHSValNo; // Update val#.
503 // If this trimmed away the whole range, ignore it.
504 if (Start == End) continue;
507 // Map the valno in the other live range to the current live range.
508 IP = addRangeFrom(LiveRange(Start, End, LHSValNo), IP);
512 SmallSet<VNInfo*, 4> Seen;
513 for (unsigned i = 0, e = ReplacedValNos.size(); i != e; ++i) {
514 VNInfo *V1 = ReplacedValNos[i];
515 if (Seen.insert(V1)) {
517 for (const_iterator I = begin(), E = end(); I != E; ++I)
518 if (I->valno == V1) {
523 // Now that V1 is dead, remove it.
524 markValNoForDeletion(V1);
532 /// MergeValueNumberInto - This method is called when two value nubmers
533 /// are found to be equivalent. This eliminates V1, replacing all
534 /// LiveRanges with the V1 value number with the V2 value number. This can
535 /// cause merging of V1/V2 values numbers and compaction of the value space.
536 VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
537 assert(V1 != V2 && "Identical value#'s are always equivalent!");
539 // This code actually merges the (numerically) larger value number into the
540 // smaller value number, which is likely to allow us to compactify the value
541 // space. The only thing we have to be careful of is to preserve the
542 // instruction that defines the result value.
544 // Make sure V2 is smaller than V1.
545 if (V1->id < V2->id) {
550 // Merge V1 live ranges into V2.
551 for (iterator I = begin(); I != end(); ) {
553 if (LR->valno != V1) continue; // Not a V1 LiveRange.
555 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
558 iterator Prev = LR-1;
559 if (Prev->valno == V2 && Prev->end == LR->start) {
562 // Erase this live-range.
569 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
570 // Ensure that it is a V2 live-range.
573 // If we can merge it into later V2 live ranges, do so now. We ignore any
574 // following V1 live ranges, as they will be merged in subsequent iterations
577 if (I->start == LR->end && I->valno == V2) {
585 // Merge the relevant flags.
588 // Now that V1 is dead, remove it.
589 markValNoForDeletion(V1);
594 void LiveInterval::Copy(const LiveInterval &RHS,
595 MachineRegisterInfo *MRI,
596 VNInfo::Allocator &VNInfoAllocator) {
599 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(RHS.reg);
600 MRI->setRegAllocationHint(reg, Hint.first, Hint.second);
603 for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
604 const VNInfo *VNI = RHS.getValNumInfo(i);
605 createValueCopy(VNI, VNInfoAllocator);
607 for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
608 const LiveRange &LR = RHS.ranges[i];
609 addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
613 unsigned LiveInterval::getSize() const {
615 for (const_iterator I = begin(), E = end(); I != E; ++I)
616 Sum += I->start.distance(I->end);
620 /// ComputeJoinedWeight - Set the weight of a live interval Joined
621 /// after Other has been merged into it.
622 void LiveInterval::ComputeJoinedWeight(const LiveInterval &Other) {
623 // If either of these intervals was spilled, the weight is the
624 // weight of the non-spilled interval. This can only happen with
625 // iterative coalescers.
627 if (Other.weight != HUGE_VALF) {
628 weight += Other.weight;
630 else if (weight == HUGE_VALF &&
631 !TargetRegisterInfo::isPhysicalRegister(reg)) {
632 // Remove this assert if you have an iterative coalescer
633 assert(0 && "Joining to spilled interval");
634 weight = Other.weight;
637 // Otherwise the weight stays the same
638 // Remove this assert if you have an iterative coalescer
639 assert(0 && "Joining from spilled interval");
643 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) {
644 return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
647 void LiveRange::dump() const {
648 dbgs() << *this << "\n";
651 void LiveInterval::print(raw_ostream &OS, const TargetRegisterInfo *TRI) const {
653 OS << "SS#" << getStackSlotIndex();
654 else if (TRI && TargetRegisterInfo::isPhysicalRegister(reg))
655 OS << TRI->getName(reg);
665 for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
666 E = ranges.end(); I != E; ++I) {
668 assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
672 // Print value number info.
673 if (getNumValNums()) {
676 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
678 const VNInfo *vni = *i;
681 if (vni->isUnused()) {
685 if (vni->hasPHIKill())
687 if (vni->hasRedefByEC())
694 void LiveInterval::dump() const {
695 dbgs() << *this << "\n";
699 void LiveRange::print(raw_ostream &os) const {