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 end to Pos.
36 bool operator()(SlotIndex Pos, const LiveRange &LR) const {
39 bool operator()(const LiveRange &LR, SlotIndex Pos) const {
45 LiveInterval::iterator LiveInterval::find(SlotIndex Pos) {
46 return std::upper_bound(begin(), end(), Pos, CompEnd());
49 /// killedInRange - Return true if the interval has kills in [Start,End).
50 bool LiveInterval::killedInRange(SlotIndex Start, SlotIndex End) const {
51 Ranges::const_iterator r =
52 std::lower_bound(ranges.begin(), ranges.end(), End);
54 // Now r points to the first interval with start >= End, or ranges.end().
55 if (r == ranges.begin())
59 // Now r points to the last interval with end <= End.
60 // r->end is the kill point.
61 return r->end >= Start && r->end < End;
64 // overlaps - Return true if the intersection of the two live intervals is
67 // An example for overlaps():
71 // 8: C = A + B ;; last use of A
73 // The live intervals should look like:
79 // A->overlaps(C) should return false since we want to be able to join
82 bool LiveInterval::overlapsFrom(const LiveInterval& other,
83 const_iterator StartPos) const {
84 assert(!empty() && "empty interval");
85 const_iterator i = begin();
86 const_iterator ie = end();
87 const_iterator j = StartPos;
88 const_iterator je = other.end();
90 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
91 StartPos != other.end() && "Bogus start position hint!");
93 if (i->start < j->start) {
94 i = std::upper_bound(i, ie, j->start);
95 if (i != ranges.begin()) --i;
96 } else if (j->start < i->start) {
98 if (StartPos != other.end() && StartPos->start <= i->start) {
99 assert(StartPos < other.end() && i < end());
100 j = std::upper_bound(j, je, i->start);
101 if (j != other.ranges.begin()) --j;
107 if (j == je) return false;
110 if (i->start > j->start) {
115 if (i->end > j->start)
123 /// overlaps - Return true if the live interval overlaps a range specified
125 bool LiveInterval::overlaps(SlotIndex Start, SlotIndex End) const {
126 assert(Start < End && "Invalid range");
127 const_iterator I = std::lower_bound(begin(), end(), End);
128 return I != begin() && (--I)->end > Start;
132 /// ValNo is dead, remove it. If it is the largest value number, just nuke it
133 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
134 /// it can be nuked later.
135 void LiveInterval::markValNoForDeletion(VNInfo *ValNo) {
136 if (ValNo->id == getNumValNums()-1) {
139 } while (!valnos.empty() && valnos.back()->isUnused());
141 ValNo->setIsUnused(true);
145 /// RenumberValues - Renumber all values in order of appearance and delete the
146 /// remaining unused values.
147 void LiveInterval::RenumberValues(LiveIntervals &lis) {
148 SmallPtrSet<VNInfo*, 8> Seen;
149 bool seenPHIDef = false;
151 for (const_iterator I = begin(), E = end(); I != E; ++I) {
152 VNInfo *VNI = I->valno;
153 if (!Seen.insert(VNI))
155 assert(!VNI->isUnused() && "Unused valno used by live range");
156 VNI->id = (unsigned)valnos.size();
157 valnos.push_back(VNI);
158 VNI->setHasPHIKill(false);
163 // Recompute phi kill flags.
166 for (const_vni_iterator I = vni_begin(), E = vni_end(); I != E; ++I) {
168 if (!VNI->isPHIDef())
170 const MachineBasicBlock *PHIBB = lis.getMBBFromIndex(VNI->def);
171 assert(PHIBB && "No basic block for phi-def");
172 for (MachineBasicBlock::const_pred_iterator PI = PHIBB->pred_begin(),
173 PE = PHIBB->pred_end(); PI != PE; ++PI) {
174 VNInfo *KVNI = getVNInfoAt(lis.getMBBEndIdx(*PI).getPrevSlot());
176 KVNI->setHasPHIKill(true);
181 /// extendIntervalEndTo - This method is used when we want to extend the range
182 /// specified by I to end at the specified endpoint. To do this, we should
183 /// merge and eliminate all ranges that this will overlap with. The iterator is
185 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) {
186 assert(I != ranges.end() && "Not a valid interval!");
187 VNInfo *ValNo = I->valno;
189 // Search for the first interval that we can't merge with.
190 Ranges::iterator MergeTo = llvm::next(I);
191 for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
192 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
195 // If NewEnd was in the middle of an interval, make sure to get its endpoint.
196 I->end = std::max(NewEnd, prior(MergeTo)->end);
198 // Erase any dead ranges.
199 ranges.erase(llvm::next(I), MergeTo);
201 // If the newly formed range now touches the range after it and if they have
202 // the same value number, merge the two ranges into one range.
203 Ranges::iterator Next = llvm::next(I);
204 if (Next != ranges.end() && Next->start <= I->end && Next->valno == ValNo) {
211 /// extendIntervalStartTo - This method is used when we want to extend the range
212 /// specified by I to start at the specified endpoint. To do this, we should
213 /// merge and eliminate all ranges that this will overlap with.
214 LiveInterval::Ranges::iterator
215 LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) {
216 assert(I != ranges.end() && "Not a valid interval!");
217 VNInfo *ValNo = I->valno;
219 // Search for the first interval that we can't merge with.
220 Ranges::iterator MergeTo = I;
222 if (MergeTo == ranges.begin()) {
224 ranges.erase(MergeTo, I);
227 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
229 } while (NewStart <= MergeTo->start);
231 // If we start in the middle of another interval, just delete a range and
232 // extend that interval.
233 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
234 MergeTo->end = I->end;
236 // Otherwise, extend the interval right after.
238 MergeTo->start = NewStart;
239 MergeTo->end = I->end;
242 ranges.erase(llvm::next(MergeTo), llvm::next(I));
246 LiveInterval::iterator
247 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
248 SlotIndex Start = LR.start, End = LR.end;
249 iterator it = std::upper_bound(From, ranges.end(), Start);
251 // If the inserted interval starts in the middle or right at the end of
252 // another interval, just extend that interval to contain the range of LR.
253 if (it != ranges.begin()) {
254 iterator B = prior(it);
255 if (LR.valno == B->valno) {
256 if (B->start <= Start && B->end >= Start) {
257 extendIntervalEndTo(B, End);
261 // Check to make sure that we are not overlapping two live ranges with
262 // different valno's.
263 assert(B->end <= Start &&
264 "Cannot overlap two LiveRanges with differing ValID's"
265 " (did you def the same reg twice in a MachineInstr?)");
269 // Otherwise, if this range ends in the middle of, or right next to, another
270 // interval, merge it into that interval.
271 if (it != ranges.end()) {
272 if (LR.valno == it->valno) {
273 if (it->start <= End) {
274 it = extendIntervalStartTo(it, Start);
276 // If LR is a complete superset of an interval, we may need to grow its
279 extendIntervalEndTo(it, End);
283 // Check to make sure that we are not overlapping two live ranges with
284 // different valno's.
285 assert(it->start >= End &&
286 "Cannot overlap two LiveRanges with differing ValID's");
290 // Otherwise, this is just a new range that doesn't interact with anything.
292 return ranges.insert(it, LR);
296 /// removeRange - Remove the specified range from this interval. Note that
297 /// the range must be in a single LiveRange in its entirety.
298 void LiveInterval::removeRange(SlotIndex Start, SlotIndex End,
299 bool RemoveDeadValNo) {
300 // Find the LiveRange containing this span.
301 Ranges::iterator I = find(Start);
302 assert(I != ranges.end() && "Range is not in interval!");
303 assert(I->containsRange(Start, End) && "Range is not entirely in interval!");
305 // If the span we are removing is at the start of the LiveRange, adjust it.
306 VNInfo *ValNo = I->valno;
307 if (I->start == Start) {
309 if (RemoveDeadValNo) {
310 // Check if val# is dead.
312 for (const_iterator II = begin(), EE = end(); II != EE; ++II)
313 if (II != I && II->valno == ValNo) {
318 // Now that ValNo is dead, remove it.
319 markValNoForDeletion(ValNo);
323 ranges.erase(I); // Removed the whole LiveRange.
329 // Otherwise if the span we are removing is at the end of the LiveRange,
330 // adjust the other way.
336 // Otherwise, we are splitting the LiveRange into two pieces.
337 SlotIndex OldEnd = I->end;
338 I->end = Start; // Trim the old interval.
340 // Insert the new one.
341 ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo));
344 /// removeValNo - Remove all the ranges defined by the specified value#.
345 /// Also remove the value# from value# list.
346 void LiveInterval::removeValNo(VNInfo *ValNo) {
348 Ranges::iterator I = ranges.end();
349 Ranges::iterator E = ranges.begin();
352 if (I->valno == ValNo)
355 // Now that ValNo is dead, remove it.
356 markValNoForDeletion(ValNo);
359 /// findDefinedVNInfo - Find the VNInfo defined by the specified
360 /// index (register interval).
361 VNInfo *LiveInterval::findDefinedVNInfoForRegInt(SlotIndex Idx) const {
362 for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
364 if ((*i)->def == Idx)
371 /// join - Join two live intervals (this, and other) together. This applies
372 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
373 /// the intervals are not joinable, this aborts.
374 void LiveInterval::join(LiveInterval &Other,
375 const int *LHSValNoAssignments,
376 const int *RHSValNoAssignments,
377 SmallVector<VNInfo*, 16> &NewVNInfo,
378 MachineRegisterInfo *MRI) {
379 // Determine if any of our live range values are mapped. This is uncommon, so
380 // we want to avoid the interval scan if not.
381 bool MustMapCurValNos = false;
382 unsigned NumVals = getNumValNums();
383 unsigned NumNewVals = NewVNInfo.size();
384 for (unsigned i = 0; i != NumVals; ++i) {
385 unsigned LHSValID = LHSValNoAssignments[i];
387 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
388 MustMapCurValNos = true;
391 // If we have to apply a mapping to our base interval assignment, rewrite it
393 if (MustMapCurValNos) {
394 // Map the first live range.
395 iterator OutIt = begin();
396 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
398 for (iterator I = OutIt, E = end(); I != E; ++I) {
399 OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
401 // If this live range has the same value # as its immediate predecessor,
402 // and if they are neighbors, remove one LiveRange. This happens when we
403 // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
404 if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
405 (OutIt-1)->end = OutIt->end;
408 OutIt->start = I->start;
412 // Didn't merge, on to the next one.
417 // If we merge some live ranges, chop off the end.
418 ranges.erase(OutIt, end());
421 // Remember assignements because val# ids are changing.
422 SmallVector<unsigned, 16> OtherAssignments;
423 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
424 OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
426 // Update val# info. Renumber them and make sure they all belong to this
427 // LiveInterval now. Also remove dead val#'s.
428 unsigned NumValNos = 0;
429 for (unsigned i = 0; i < NumNewVals; ++i) {
430 VNInfo *VNI = NewVNInfo[i];
432 if (NumValNos >= NumVals)
433 valnos.push_back(VNI);
435 valnos[NumValNos] = VNI;
436 VNI->id = NumValNos++; // Renumber val#.
439 if (NumNewVals < NumVals)
440 valnos.resize(NumNewVals); // shrinkify
442 // Okay, now insert the RHS live ranges into the LHS.
443 iterator InsertPos = begin();
444 unsigned RangeNo = 0;
445 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
446 // Map the valno in the other live range to the current live range.
447 I->valno = NewVNInfo[OtherAssignments[RangeNo]];
448 assert(I->valno && "Adding a dead range?");
449 InsertPos = addRangeFrom(*I, InsertPos);
452 ComputeJoinedWeight(Other);
455 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
456 /// interval as the specified value number. The LiveRanges in RHS are
457 /// allowed to overlap with LiveRanges in the current interval, but only if
458 /// the overlapping LiveRanges have the specified value number.
459 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
461 // TODO: Make this more efficient.
462 iterator InsertPos = begin();
463 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
464 // Map the valno in the other live range to the current live range.
466 Tmp.valno = LHSValNo;
467 InsertPos = addRangeFrom(Tmp, InsertPos);
472 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
473 /// in RHS into this live interval as the specified value number.
474 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
475 /// current interval, it will replace the value numbers of the overlaped
476 /// live ranges with the specified value number.
477 void LiveInterval::MergeValueInAsValue(
478 const LiveInterval &RHS,
479 const VNInfo *RHSValNo, VNInfo *LHSValNo) {
480 SmallVector<VNInfo*, 4> ReplacedValNos;
481 iterator IP = begin();
482 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
483 assert(I->valno == RHS.getValNumInfo(I->valno->id) && "Bad VNInfo");
484 if (I->valno != RHSValNo)
486 SlotIndex Start = I->start, End = I->end;
487 IP = std::upper_bound(IP, end(), Start);
488 // If the start of this range overlaps with an existing liverange, trim it.
489 if (IP != begin() && IP[-1].end > Start) {
490 if (IP[-1].valno != LHSValNo) {
491 ReplacedValNos.push_back(IP[-1].valno);
492 IP[-1].valno = LHSValNo; // Update val#.
495 // Trimmed away the whole range?
496 if (Start >= End) continue;
498 // If the end of this range overlaps with an existing liverange, trim it.
499 if (IP != end() && End > IP->start) {
500 if (IP->valno != LHSValNo) {
501 ReplacedValNos.push_back(IP->valno);
502 IP->valno = LHSValNo; // Update val#.
505 // If this trimmed away the whole range, ignore it.
506 if (Start == End) continue;
509 // Map the valno in the other live range to the current live range.
510 IP = addRangeFrom(LiveRange(Start, End, LHSValNo), IP);
514 SmallSet<VNInfo*, 4> Seen;
515 for (unsigned i = 0, e = ReplacedValNos.size(); i != e; ++i) {
516 VNInfo *V1 = ReplacedValNos[i];
517 if (Seen.insert(V1)) {
519 for (const_iterator I = begin(), E = end(); I != E; ++I)
520 if (I->valno == V1) {
525 // Now that V1 is dead, remove it.
526 markValNoForDeletion(V1);
534 /// MergeValueNumberInto - This method is called when two value nubmers
535 /// are found to be equivalent. This eliminates V1, replacing all
536 /// LiveRanges with the V1 value number with the V2 value number. This can
537 /// cause merging of V1/V2 values numbers and compaction of the value space.
538 VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
539 assert(V1 != V2 && "Identical value#'s are always equivalent!");
541 // This code actually merges the (numerically) larger value number into the
542 // smaller value number, which is likely to allow us to compactify the value
543 // space. The only thing we have to be careful of is to preserve the
544 // instruction that defines the result value.
546 // Make sure V2 is smaller than V1.
547 if (V1->id < V2->id) {
552 // Merge V1 live ranges into V2.
553 for (iterator I = begin(); I != end(); ) {
555 if (LR->valno != V1) continue; // Not a V1 LiveRange.
557 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
560 iterator Prev = LR-1;
561 if (Prev->valno == V2 && Prev->end == LR->start) {
564 // Erase this live-range.
571 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
572 // Ensure that it is a V2 live-range.
575 // If we can merge it into later V2 live ranges, do so now. We ignore any
576 // following V1 live ranges, as they will be merged in subsequent iterations
579 if (I->start == LR->end && I->valno == V2) {
587 // Now that V1 is dead, remove it.
588 markValNoForDeletion(V1);
593 void LiveInterval::Copy(const LiveInterval &RHS,
594 MachineRegisterInfo *MRI,
595 VNInfo::Allocator &VNInfoAllocator) {
598 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(RHS.reg);
599 MRI->setRegAllocationHint(reg, Hint.first, Hint.second);
602 for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
603 const VNInfo *VNI = RHS.getValNumInfo(i);
604 createValueCopy(VNI, VNInfoAllocator);
606 for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
607 const LiveRange &LR = RHS.ranges[i];
608 addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
612 unsigned LiveInterval::getSize() const {
614 for (const_iterator I = begin(), E = end(); I != E; ++I)
615 Sum += I->start.distance(I->end);
619 /// ComputeJoinedWeight - Set the weight of a live interval Joined
620 /// after Other has been merged into it.
621 void LiveInterval::ComputeJoinedWeight(const LiveInterval &Other) {
622 // If either of these intervals was spilled, the weight is the
623 // weight of the non-spilled interval. This can only happen with
624 // iterative coalescers.
626 if (Other.weight != HUGE_VALF) {
627 weight += Other.weight;
629 else if (weight == HUGE_VALF &&
630 !TargetRegisterInfo::isPhysicalRegister(reg)) {
631 // Remove this assert if you have an iterative coalescer
632 assert(0 && "Joining to spilled interval");
633 weight = Other.weight;
636 // Otherwise the weight stays the same
637 // Remove this assert if you have an iterative coalescer
638 assert(0 && "Joining from spilled interval");
642 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) {
643 return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
646 void LiveRange::dump() const {
647 dbgs() << *this << "\n";
650 void LiveInterval::print(raw_ostream &OS, const TargetRegisterInfo *TRI) const {
652 OS << "SS#" << getStackSlotIndex();
653 else if (TRI && TargetRegisterInfo::isPhysicalRegister(reg))
654 OS << TRI->getName(reg);
664 for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
665 E = ranges.end(); I != E; ++I) {
667 assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
671 // Print value number info.
672 if (getNumValNums()) {
675 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
677 const VNInfo *vni = *i;
680 if (vni->isUnused()) {
683 if (!vni->isDefAccurate() && !vni->isPHIDef())
687 if (vni->hasPHIKill())
689 if (vni->hasRedefByEC())
696 void LiveInterval::dump() const {
697 dbgs() << *this << "\n";
701 void LiveRange::print(raw_ostream &os) const {