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.
34 // This argument ordering works for upper_bound.
35 static inline bool compEnd(SlotIndex Pos, const LiveRange &LR) {
39 LiveInterval::iterator LiveInterval::find(SlotIndex Pos) {
40 return std::upper_bound(begin(), end(), Pos, compEnd);
43 /// killedInRange - Return true if the interval has kills in [Start,End).
44 bool LiveInterval::killedInRange(SlotIndex Start, SlotIndex End) const {
45 Ranges::const_iterator r =
46 std::lower_bound(ranges.begin(), ranges.end(), End);
48 // Now r points to the first interval with start >= End, or ranges.end().
49 if (r == ranges.begin())
53 // Now r points to the last interval with end <= End.
54 // r->end is the kill point.
55 return r->end >= Start && r->end < End;
58 // overlaps - Return true if the intersection of the two live intervals is
61 // An example for overlaps():
65 // 8: C = A + B ;; last use of A
67 // The live intervals should look like:
73 // A->overlaps(C) should return false since we want to be able to join
76 bool LiveInterval::overlapsFrom(const LiveInterval& other,
77 const_iterator StartPos) const {
78 assert(!empty() && "empty interval");
79 const_iterator i = begin();
80 const_iterator ie = end();
81 const_iterator j = StartPos;
82 const_iterator je = other.end();
84 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
85 StartPos != other.end() && "Bogus start position hint!");
87 if (i->start < j->start) {
88 i = std::upper_bound(i, ie, j->start);
89 if (i != ranges.begin()) --i;
90 } else if (j->start < i->start) {
92 if (StartPos != other.end() && StartPos->start <= i->start) {
93 assert(StartPos < other.end() && i < end());
94 j = std::upper_bound(j, je, i->start);
95 if (j != other.ranges.begin()) --j;
101 if (j == je) return false;
104 if (i->start > j->start) {
109 if (i->end > j->start)
117 /// overlaps - Return true if the live interval overlaps a range specified
119 bool LiveInterval::overlaps(SlotIndex Start, SlotIndex End) const {
120 assert(Start < End && "Invalid range");
121 const_iterator I = std::lower_bound(begin(), end(), End);
122 return I != begin() && (--I)->end > Start;
126 /// ValNo is dead, remove it. If it is the largest value number, just nuke it
127 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
128 /// it can be nuked later.
129 void LiveInterval::markValNoForDeletion(VNInfo *ValNo) {
130 if (ValNo->id == getNumValNums()-1) {
133 } while (!valnos.empty() && valnos.back()->isUnused());
135 ValNo->setIsUnused(true);
139 /// RenumberValues - Renumber all values in order of appearance and delete the
140 /// remaining unused values.
141 void LiveInterval::RenumberValues(LiveIntervals &lis) {
142 SmallPtrSet<VNInfo*, 8> Seen;
143 bool seenPHIDef = false;
145 for (const_iterator I = begin(), E = end(); I != E; ++I) {
146 VNInfo *VNI = I->valno;
147 if (!Seen.insert(VNI))
149 assert(!VNI->isUnused() && "Unused valno used by live range");
150 VNI->id = (unsigned)valnos.size();
151 valnos.push_back(VNI);
152 VNI->setHasPHIKill(false);
157 // Recompute phi kill flags.
160 for (const_vni_iterator I = vni_begin(), E = vni_end(); I != E; ++I) {
162 if (!VNI->isPHIDef())
164 const MachineBasicBlock *PHIBB = lis.getMBBFromIndex(VNI->def);
165 assert(PHIBB && "No basic block for phi-def");
166 for (MachineBasicBlock::const_pred_iterator PI = PHIBB->pred_begin(),
167 PE = PHIBB->pred_end(); PI != PE; ++PI) {
168 VNInfo *KVNI = getVNInfoAt(lis.getMBBEndIdx(*PI).getPrevSlot());
170 KVNI->setHasPHIKill(true);
175 /// extendIntervalEndTo - This method is used when we want to extend the range
176 /// specified by I to end at the specified endpoint. To do this, we should
177 /// merge and eliminate all ranges that this will overlap with. The iterator is
179 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) {
180 assert(I != ranges.end() && "Not a valid interval!");
181 VNInfo *ValNo = I->valno;
183 // Search for the first interval that we can't merge with.
184 Ranges::iterator MergeTo = llvm::next(I);
185 for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
186 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
189 // If NewEnd was in the middle of an interval, make sure to get its endpoint.
190 I->end = std::max(NewEnd, prior(MergeTo)->end);
192 // Erase any dead ranges.
193 ranges.erase(llvm::next(I), MergeTo);
195 // If the newly formed range now touches the range after it and if they have
196 // the same value number, merge the two ranges into one range.
197 Ranges::iterator Next = llvm::next(I);
198 if (Next != ranges.end() && Next->start <= I->end && Next->valno == ValNo) {
205 /// extendIntervalStartTo - This method is used when we want to extend the range
206 /// specified by I to start at the specified endpoint. To do this, we should
207 /// merge and eliminate all ranges that this will overlap with.
208 LiveInterval::Ranges::iterator
209 LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) {
210 assert(I != ranges.end() && "Not a valid interval!");
211 VNInfo *ValNo = I->valno;
213 // Search for the first interval that we can't merge with.
214 Ranges::iterator MergeTo = I;
216 if (MergeTo == ranges.begin()) {
218 ranges.erase(MergeTo, I);
221 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
223 } while (NewStart <= MergeTo->start);
225 // If we start in the middle of another interval, just delete a range and
226 // extend that interval.
227 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
228 MergeTo->end = I->end;
230 // Otherwise, extend the interval right after.
232 MergeTo->start = NewStart;
233 MergeTo->end = I->end;
236 ranges.erase(llvm::next(MergeTo), llvm::next(I));
240 LiveInterval::iterator
241 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
242 SlotIndex Start = LR.start, End = LR.end;
243 iterator it = std::upper_bound(From, ranges.end(), Start);
245 // If the inserted interval starts in the middle or right at the end of
246 // another interval, just extend that interval to contain the range of LR.
247 if (it != ranges.begin()) {
248 iterator B = prior(it);
249 if (LR.valno == B->valno) {
250 if (B->start <= Start && B->end >= Start) {
251 extendIntervalEndTo(B, End);
255 // Check to make sure that we are not overlapping two live ranges with
256 // different valno's.
257 assert(B->end <= Start &&
258 "Cannot overlap two LiveRanges with differing ValID's"
259 " (did you def the same reg twice in a MachineInstr?)");
263 // Otherwise, if this range ends in the middle of, or right next to, another
264 // interval, merge it into that interval.
265 if (it != ranges.end()) {
266 if (LR.valno == it->valno) {
267 if (it->start <= End) {
268 it = extendIntervalStartTo(it, Start);
270 // If LR is a complete superset of an interval, we may need to grow its
273 extendIntervalEndTo(it, End);
277 // Check to make sure that we are not overlapping two live ranges with
278 // different valno's.
279 assert(it->start >= End &&
280 "Cannot overlap two LiveRanges with differing ValID's");
284 // Otherwise, this is just a new range that doesn't interact with anything.
286 return ranges.insert(it, LR);
290 /// removeRange - Remove the specified range from this interval. Note that
291 /// the range must be in a single LiveRange in its entirety.
292 void LiveInterval::removeRange(SlotIndex Start, SlotIndex End,
293 bool RemoveDeadValNo) {
294 // Find the LiveRange containing this span.
295 Ranges::iterator I = find(Start);
296 assert(I != ranges.end() && "Range is not in interval!");
297 assert(I->containsRange(Start, End) && "Range is not entirely in interval!");
299 // If the span we are removing is at the start of the LiveRange, adjust it.
300 VNInfo *ValNo = I->valno;
301 if (I->start == Start) {
303 if (RemoveDeadValNo) {
304 // Check if val# is dead.
306 for (const_iterator II = begin(), EE = end(); II != EE; ++II)
307 if (II != I && II->valno == ValNo) {
312 // Now that ValNo is dead, remove it.
313 markValNoForDeletion(ValNo);
317 ranges.erase(I); // Removed the whole LiveRange.
323 // Otherwise if the span we are removing is at the end of the LiveRange,
324 // adjust the other way.
330 // Otherwise, we are splitting the LiveRange into two pieces.
331 SlotIndex OldEnd = I->end;
332 I->end = Start; // Trim the old interval.
334 // Insert the new one.
335 ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo));
338 /// removeValNo - Remove all the ranges defined by the specified value#.
339 /// Also remove the value# from value# list.
340 void LiveInterval::removeValNo(VNInfo *ValNo) {
342 Ranges::iterator I = ranges.end();
343 Ranges::iterator E = ranges.begin();
346 if (I->valno == ValNo)
349 // Now that ValNo is dead, remove it.
350 markValNoForDeletion(ValNo);
353 /// findDefinedVNInfo - Find the VNInfo defined by the specified
354 /// index (register interval).
355 VNInfo *LiveInterval::findDefinedVNInfoForRegInt(SlotIndex Idx) const {
356 for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
358 if ((*i)->def == Idx)
365 /// join - Join two live intervals (this, and other) together. This applies
366 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
367 /// the intervals are not joinable, this aborts.
368 void LiveInterval::join(LiveInterval &Other,
369 const int *LHSValNoAssignments,
370 const int *RHSValNoAssignments,
371 SmallVector<VNInfo*, 16> &NewVNInfo,
372 MachineRegisterInfo *MRI) {
373 // Determine if any of our live range values are mapped. This is uncommon, so
374 // we want to avoid the interval scan if not.
375 bool MustMapCurValNos = false;
376 unsigned NumVals = getNumValNums();
377 unsigned NumNewVals = NewVNInfo.size();
378 for (unsigned i = 0; i != NumVals; ++i) {
379 unsigned LHSValID = LHSValNoAssignments[i];
381 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
382 MustMapCurValNos = true;
385 // If we have to apply a mapping to our base interval assignment, rewrite it
387 if (MustMapCurValNos) {
388 // Map the first live range.
389 iterator OutIt = begin();
390 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
392 for (iterator I = OutIt, E = end(); I != E; ++I) {
393 OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
395 // If this live range has the same value # as its immediate predecessor,
396 // and if they are neighbors, remove one LiveRange. This happens when we
397 // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
398 if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
399 (OutIt-1)->end = OutIt->end;
402 OutIt->start = I->start;
406 // Didn't merge, on to the next one.
411 // If we merge some live ranges, chop off the end.
412 ranges.erase(OutIt, end());
415 // Remember assignements because val# ids are changing.
416 SmallVector<unsigned, 16> OtherAssignments;
417 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
418 OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
420 // Update val# info. Renumber them and make sure they all belong to this
421 // LiveInterval now. Also remove dead val#'s.
422 unsigned NumValNos = 0;
423 for (unsigned i = 0; i < NumNewVals; ++i) {
424 VNInfo *VNI = NewVNInfo[i];
426 if (NumValNos >= NumVals)
427 valnos.push_back(VNI);
429 valnos[NumValNos] = VNI;
430 VNI->id = NumValNos++; // Renumber val#.
433 if (NumNewVals < NumVals)
434 valnos.resize(NumNewVals); // shrinkify
436 // Okay, now insert the RHS live ranges into the LHS.
437 iterator InsertPos = begin();
438 unsigned RangeNo = 0;
439 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
440 // Map the valno in the other live range to the current live range.
441 I->valno = NewVNInfo[OtherAssignments[RangeNo]];
442 assert(I->valno && "Adding a dead range?");
443 InsertPos = addRangeFrom(*I, InsertPos);
446 ComputeJoinedWeight(Other);
449 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
450 /// interval as the specified value number. The LiveRanges in RHS are
451 /// allowed to overlap with LiveRanges in the current interval, but only if
452 /// the overlapping LiveRanges have the specified value number.
453 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
455 // TODO: Make this more efficient.
456 iterator InsertPos = begin();
457 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
458 // Map the valno in the other live range to the current live range.
460 Tmp.valno = LHSValNo;
461 InsertPos = addRangeFrom(Tmp, InsertPos);
466 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
467 /// in RHS into this live interval as the specified value number.
468 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
469 /// current interval, it will replace the value numbers of the overlaped
470 /// live ranges with the specified value number.
471 void LiveInterval::MergeValueInAsValue(
472 const LiveInterval &RHS,
473 const VNInfo *RHSValNo, VNInfo *LHSValNo) {
474 SmallVector<VNInfo*, 4> ReplacedValNos;
475 iterator IP = begin();
476 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
477 assert(I->valno == RHS.getValNumInfo(I->valno->id) && "Bad VNInfo");
478 if (I->valno != RHSValNo)
480 SlotIndex Start = I->start, End = I->end;
481 IP = std::upper_bound(IP, end(), Start);
482 // If the start of this range overlaps with an existing liverange, trim it.
483 if (IP != begin() && IP[-1].end > Start) {
484 if (IP[-1].valno != LHSValNo) {
485 ReplacedValNos.push_back(IP[-1].valno);
486 IP[-1].valno = LHSValNo; // Update val#.
489 // Trimmed away the whole range?
490 if (Start >= End) continue;
492 // If the end of this range overlaps with an existing liverange, trim it.
493 if (IP != end() && End > IP->start) {
494 if (IP->valno != LHSValNo) {
495 ReplacedValNos.push_back(IP->valno);
496 IP->valno = LHSValNo; // Update val#.
499 // If this trimmed away the whole range, ignore it.
500 if (Start == End) continue;
503 // Map the valno in the other live range to the current live range.
504 IP = addRangeFrom(LiveRange(Start, End, LHSValNo), IP);
508 SmallSet<VNInfo*, 4> Seen;
509 for (unsigned i = 0, e = ReplacedValNos.size(); i != e; ++i) {
510 VNInfo *V1 = ReplacedValNos[i];
511 if (Seen.insert(V1)) {
513 for (const_iterator I = begin(), E = end(); I != E; ++I)
514 if (I->valno == V1) {
519 // Now that V1 is dead, remove it.
520 markValNoForDeletion(V1);
528 /// MergeValueNumberInto - This method is called when two value nubmers
529 /// are found to be equivalent. This eliminates V1, replacing all
530 /// LiveRanges with the V1 value number with the V2 value number. This can
531 /// cause merging of V1/V2 values numbers and compaction of the value space.
532 VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
533 assert(V1 != V2 && "Identical value#'s are always equivalent!");
535 // This code actually merges the (numerically) larger value number into the
536 // smaller value number, which is likely to allow us to compactify the value
537 // space. The only thing we have to be careful of is to preserve the
538 // instruction that defines the result value.
540 // Make sure V2 is smaller than V1.
541 if (V1->id < V2->id) {
546 // Merge V1 live ranges into V2.
547 for (iterator I = begin(); I != end(); ) {
549 if (LR->valno != V1) continue; // Not a V1 LiveRange.
551 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
554 iterator Prev = LR-1;
555 if (Prev->valno == V2 && Prev->end == LR->start) {
558 // Erase this live-range.
565 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
566 // Ensure that it is a V2 live-range.
569 // If we can merge it into later V2 live ranges, do so now. We ignore any
570 // following V1 live ranges, as they will be merged in subsequent iterations
573 if (I->start == LR->end && I->valno == V2) {
581 // Now that V1 is dead, remove it.
582 markValNoForDeletion(V1);
587 void LiveInterval::Copy(const LiveInterval &RHS,
588 MachineRegisterInfo *MRI,
589 VNInfo::Allocator &VNInfoAllocator) {
592 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(RHS.reg);
593 MRI->setRegAllocationHint(reg, Hint.first, Hint.second);
596 for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
597 const VNInfo *VNI = RHS.getValNumInfo(i);
598 createValueCopy(VNI, VNInfoAllocator);
600 for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
601 const LiveRange &LR = RHS.ranges[i];
602 addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
606 unsigned LiveInterval::getSize() const {
608 for (const_iterator I = begin(), E = end(); I != E; ++I)
609 Sum += I->start.distance(I->end);
613 /// ComputeJoinedWeight - Set the weight of a live interval Joined
614 /// after Other has been merged into it.
615 void LiveInterval::ComputeJoinedWeight(const LiveInterval &Other) {
616 // If either of these intervals was spilled, the weight is the
617 // weight of the non-spilled interval. This can only happen with
618 // iterative coalescers.
620 if (Other.weight != HUGE_VALF) {
621 weight += Other.weight;
623 else if (weight == HUGE_VALF &&
624 !TargetRegisterInfo::isPhysicalRegister(reg)) {
625 // Remove this assert if you have an iterative coalescer
626 assert(0 && "Joining to spilled interval");
627 weight = Other.weight;
630 // Otherwise the weight stays the same
631 // Remove this assert if you have an iterative coalescer
632 assert(0 && "Joining from spilled interval");
636 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) {
637 return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
640 void LiveRange::dump() const {
641 dbgs() << *this << "\n";
644 void LiveInterval::print(raw_ostream &OS, const TargetRegisterInfo *TRI) const {
646 OS << "SS#" << getStackSlotIndex();
647 else if (TRI && TargetRegisterInfo::isPhysicalRegister(reg))
648 OS << TRI->getName(reg);
658 for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
659 E = ranges.end(); I != E; ++I) {
661 assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
665 // Print value number info.
666 if (getNumValNums()) {
669 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
671 const VNInfo *vni = *i;
674 if (vni->isUnused()) {
677 if (!vni->isDefAccurate() && !vni->isPHIDef())
681 if (vni->hasPHIKill())
683 if (vni->hasRedefByEC())
690 void LiveInterval::dump() const {
691 dbgs() << *this << "\n";
695 void LiveRange::print(raw_ostream &os) const {