1 //===-- llvm/CodeGen/LiveInterval.h - Interval representation ---*- C++ -*-===//
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 #ifndef LLVM_CODEGEN_LIVEINTERVAL_H
22 #define LLVM_CODEGEN_LIVEINTERVAL_H
24 #include "llvm/ADT/IntEqClasses.h"
25 #include "llvm/CodeGen/SlotIndexes.h"
26 #include "llvm/Support/AlignOf.h"
27 #include "llvm/Support/Allocator.h"
35 class MachineRegisterInfo;
36 class TargetRegisterInfo;
39 /// VNInfo - Value Number Information.
40 /// This class holds information about a machine level values, including
41 /// definition and use points.
45 typedef BumpPtrAllocator Allocator;
47 /// The ID number of this value.
50 /// The index of the defining instruction.
53 /// VNInfo constructor.
54 VNInfo(unsigned i, SlotIndex d)
58 /// VNInfo construtor, copies values from orig, except for the value number.
59 VNInfo(unsigned i, const VNInfo &orig)
60 : id(i), def(orig.def)
63 /// Copy from the parameter into this VNInfo.
64 void copyFrom(VNInfo &src) {
68 /// Returns true if this value is defined by a PHI instruction (or was,
69 /// PHI instrucions may have been eliminated).
70 /// PHI-defs begin at a block boundary, all other defs begin at register or
72 bool isPHIDef() const { return def.isBlock(); }
74 /// Returns true if this value is unused.
75 bool isUnused() const { return !def.isValid(); }
77 /// Mark this value as unused.
78 void markUnused() { def = SlotIndex(); }
81 /// LiveRange structure - This represents a simple register range in the
82 /// program, with an inclusive start point and an exclusive end point.
83 /// These ranges are rendered as [start,end).
85 SlotIndex start; // Start point of the interval (inclusive)
86 SlotIndex end; // End point of the interval (exclusive)
87 VNInfo *valno; // identifier for the value contained in this interval.
89 LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
90 : start(S), end(E), valno(V) {
92 assert(S < E && "Cannot create empty or backwards range");
95 /// contains - Return true if the index is covered by this range.
97 bool contains(SlotIndex I) const {
98 return start <= I && I < end;
101 /// containsRange - Return true if the given range, [S, E), is covered by
103 bool containsRange(SlotIndex S, SlotIndex E) const {
104 assert((S < E) && "Backwards interval?");
105 return (start <= S && S < end) && (start < E && E <= end);
108 bool operator<(const LiveRange &LR) const {
109 return start < LR.start || (start == LR.start && end < LR.end);
111 bool operator==(const LiveRange &LR) const {
112 return start == LR.start && end == LR.end;
116 void print(raw_ostream &os) const;
119 template <> struct isPodLike<LiveRange> { static const bool value = true; };
121 raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
124 inline bool operator<(SlotIndex V, const LiveRange &LR) {
128 inline bool operator<(const LiveRange &LR, SlotIndex V) {
132 /// LiveInterval - This class represents some number of live ranges for a
133 /// register or value. This class also contains a bit of register allocator
138 typedef SmallVector<LiveRange,4> Ranges;
139 typedef SmallVector<VNInfo*,4> VNInfoList;
141 const unsigned reg; // the register or stack slot of this interval.
142 float weight; // weight of this interval
143 Ranges ranges; // the ranges in which this register is live
144 VNInfoList valnos; // value#'s
157 LiveInterval(unsigned Reg, float Weight)
158 : reg(Reg), weight(Weight) {}
160 typedef Ranges::iterator iterator;
161 iterator begin() { return ranges.begin(); }
162 iterator end() { return ranges.end(); }
164 typedef Ranges::const_iterator const_iterator;
165 const_iterator begin() const { return ranges.begin(); }
166 const_iterator end() const { return ranges.end(); }
168 typedef VNInfoList::iterator vni_iterator;
169 vni_iterator vni_begin() { return valnos.begin(); }
170 vni_iterator vni_end() { return valnos.end(); }
172 typedef VNInfoList::const_iterator const_vni_iterator;
173 const_vni_iterator vni_begin() const { return valnos.begin(); }
174 const_vni_iterator vni_end() const { return valnos.end(); }
176 /// advanceTo - Advance the specified iterator to point to the LiveRange
177 /// containing the specified position, or end() if the position is past the
178 /// end of the interval. If no LiveRange contains this position, but the
179 /// position is in a hole, this method returns an iterator pointing to the
180 /// LiveRange immediately after the hole.
181 iterator advanceTo(iterator I, SlotIndex Pos) {
183 if (Pos >= endIndex())
185 while (I->end <= Pos) ++I;
189 /// find - Return an iterator pointing to the first range that ends after
190 /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
191 /// when searching large intervals.
193 /// If Pos is contained in a LiveRange, that range is returned.
194 /// If Pos is in a hole, the following LiveRange is returned.
195 /// If Pos is beyond endIndex, end() is returned.
196 iterator find(SlotIndex Pos);
198 const_iterator find(SlotIndex Pos) const {
199 return const_cast<LiveInterval*>(this)->find(Pos);
207 bool hasAtLeastOneValue() const { return !valnos.empty(); }
209 bool containsOneValue() const { return valnos.size() == 1; }
211 unsigned getNumValNums() const { return (unsigned)valnos.size(); }
213 /// getValNumInfo - Returns pointer to the specified val#.
215 inline VNInfo *getValNumInfo(unsigned ValNo) {
216 return valnos[ValNo];
218 inline const VNInfo *getValNumInfo(unsigned ValNo) const {
219 return valnos[ValNo];
222 /// containsValue - Returns true if VNI belongs to this interval.
223 bool containsValue(const VNInfo *VNI) const {
224 return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
227 /// getNextValue - Create a new value number and return it. MIIdx specifies
228 /// the instruction that defines the value number.
229 VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
231 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
232 valnos.push_back(VNI);
236 /// createDeadDef - Make sure the interval has a value defined at Def.
237 /// If one already exists, return it. Otherwise allocate a new value and
238 /// add liveness for a dead def.
239 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
241 /// Create a copy of the given value. The new value will be identical except
242 /// for the Value number.
243 VNInfo *createValueCopy(const VNInfo *orig,
244 VNInfo::Allocator &VNInfoAllocator) {
246 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
247 valnos.push_back(VNI);
251 /// RenumberValues - Renumber all values in order of appearance and remove
253 void RenumberValues(LiveIntervals &lis);
255 /// MergeValueNumberInto - This method is called when two value nubmers
256 /// are found to be equivalent. This eliminates V1, replacing all
257 /// LiveRanges with the V1 value number with the V2 value number. This can
258 /// cause merging of V1/V2 values numbers and compaction of the value space.
259 VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
261 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
262 /// in RHS into this live interval as the specified value number.
263 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
264 /// current interval, it will replace the value numbers of the overlaped
265 /// live ranges with the specified value number.
266 void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
268 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
269 /// in RHS into this live interval as the specified value number.
270 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
271 /// current interval, but only if the overlapping LiveRanges have the
272 /// specified value number.
273 void MergeValueInAsValue(const LiveInterval &RHS,
274 const VNInfo *RHSValNo, VNInfo *LHSValNo);
276 bool empty() const { return ranges.empty(); }
278 /// beginIndex - Return the lowest numbered slot covered by interval.
279 SlotIndex beginIndex() const {
280 assert(!empty() && "Call to beginIndex() on empty interval.");
281 return ranges.front().start;
284 /// endNumber - return the maximum point of the interval of the whole,
286 SlotIndex endIndex() const {
287 assert(!empty() && "Call to endIndex() on empty interval.");
288 return ranges.back().end;
291 bool expiredAt(SlotIndex index) const {
292 return index >= endIndex();
295 bool liveAt(SlotIndex index) const {
296 const_iterator r = find(index);
297 return r != end() && r->start <= index;
300 /// killedAt - Return true if a live range ends at index. Note that the kill
301 /// point is not contained in the half-open live range. It is usually the
302 /// getDefIndex() slot following its last use.
303 bool killedAt(SlotIndex index) const {
304 const_iterator r = find(index.getRegSlot(true));
305 return r != end() && r->end == index;
308 /// getLiveRangeContaining - Return the live range that contains the
309 /// specified index, or null if there is none.
310 const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
311 const_iterator I = FindLiveRangeContaining(Idx);
312 return I == end() ? 0 : &*I;
315 /// getLiveRangeContaining - Return the live range that contains the
316 /// specified index, or null if there is none.
317 LiveRange *getLiveRangeContaining(SlotIndex Idx) {
318 iterator I = FindLiveRangeContaining(Idx);
319 return I == end() ? 0 : &*I;
322 /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
323 VNInfo *getVNInfoAt(SlotIndex Idx) const {
324 const_iterator I = FindLiveRangeContaining(Idx);
325 return I == end() ? 0 : I->valno;
328 /// getVNInfoBefore - Return the VNInfo that is live up to but not
329 /// necessarilly including Idx, or NULL. Use this to find the reaching def
330 /// used by an instruction at this SlotIndex position.
331 VNInfo *getVNInfoBefore(SlotIndex Idx) const {
332 const_iterator I = FindLiveRangeContaining(Idx.getPrevSlot());
333 return I == end() ? 0 : I->valno;
336 /// FindLiveRangeContaining - Return an iterator to the live range that
337 /// contains the specified index, or end() if there is none.
338 iterator FindLiveRangeContaining(SlotIndex Idx) {
339 iterator I = find(Idx);
340 return I != end() && I->start <= Idx ? I : end();
343 const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
344 const_iterator I = find(Idx);
345 return I != end() && I->start <= Idx ? I : end();
348 /// overlaps - Return true if the intersection of the two live intervals is
350 bool overlaps(const LiveInterval& other) const {
353 return overlapsFrom(other, other.begin());
356 /// overlaps - Return true if the two intervals have overlapping segments
357 /// that are not coalescable according to CP.
359 /// Overlapping segments where one interval is defined by a coalescable
360 /// copy are allowed.
361 bool overlaps(const LiveInterval &Other, const CoalescerPair &CP,
362 const SlotIndexes&) const;
364 /// overlaps - Return true if the live interval overlaps a range specified
366 bool overlaps(SlotIndex Start, SlotIndex End) const;
368 /// overlapsFrom - Return true if the intersection of the two live intervals
369 /// is not empty. The specified iterator is a hint that we can begin
370 /// scanning the Other interval starting at I.
371 bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
373 /// addRange - Add the specified LiveRange to this interval, merging
374 /// intervals as appropriate. This returns an iterator to the inserted live
375 /// range (which may have grown since it was inserted.
376 void addRange(LiveRange LR) {
377 addRangeFrom(LR, ranges.begin());
380 /// extendInBlock - If this interval is live before Kill in the basic block
381 /// that starts at StartIdx, extend it to be live up to Kill, and return
382 /// the value. If there is no live range before Kill, return NULL.
383 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
385 /// join - Join two live intervals (this, and other) together. This applies
386 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
387 /// the intervals are not joinable, this aborts.
388 void join(LiveInterval &Other,
389 const int *ValNoAssignments,
390 const int *RHSValNoAssignments,
391 SmallVector<VNInfo*, 16> &NewVNInfo,
392 MachineRegisterInfo *MRI);
394 /// isInOneLiveRange - Return true if the range specified is entirely in the
395 /// a single LiveRange of the live interval.
396 bool isInOneLiveRange(SlotIndex Start, SlotIndex End) const {
397 const_iterator r = find(Start);
398 return r != end() && r->containsRange(Start, End);
401 /// removeRange - Remove the specified range from this interval. Note that
402 /// the range must be a single LiveRange in its entirety.
403 void removeRange(SlotIndex Start, SlotIndex End,
404 bool RemoveDeadValNo = false);
406 void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
407 removeRange(LR.start, LR.end, RemoveDeadValNo);
410 /// removeValNo - Remove all the ranges defined by the specified value#.
411 /// Also remove the value# from value# list.
412 void removeValNo(VNInfo *ValNo);
414 /// getSize - Returns the sum of sizes of all the LiveRange's.
416 unsigned getSize() const;
418 /// Returns true if the live interval is zero length, i.e. no live ranges
419 /// span instructions. It doesn't pay to spill such an interval.
420 bool isZeroLength(SlotIndexes *Indexes) const {
421 for (const_iterator i = begin(), e = end(); i != e; ++i)
422 if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
423 i->end.getBaseIndex())
428 /// isSpillable - Can this interval be spilled?
429 bool isSpillable() const {
430 return weight != HUGE_VALF;
433 /// markNotSpillable - Mark interval as not spillable
434 void markNotSpillable() {
438 bool operator<(const LiveInterval& other) const {
439 const SlotIndex &thisIndex = beginIndex();
440 const SlotIndex &otherIndex = other.beginIndex();
441 return (thisIndex < otherIndex ||
442 (thisIndex == otherIndex && reg < other.reg));
445 void print(raw_ostream &OS) const;
448 /// \brief Walk the interval and assert if any invariants fail to hold.
450 /// Note that this is a no-op when asserts are disabled.
452 void verify() const {}
459 Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
460 void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
461 Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
462 void markValNoForDeletion(VNInfo *V);
463 void mergeIntervalRanges(const LiveInterval &RHS,
464 VNInfo *LHSValNo = 0,
465 const VNInfo *RHSValNo = 0);
467 LiveInterval& operator=(const LiveInterval& rhs) LLVM_DELETED_FUNCTION;
471 inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
476 /// LiveRangeQuery - Query information about a live range around a given
477 /// instruction. This class hides the implementation details of live ranges,
478 /// and it should be used as the primary interface for examining live ranges
479 /// around instructions.
481 class LiveRangeQuery {
488 /// Create a LiveRangeQuery for the given live range and instruction index.
489 /// The sub-instruction slot of Idx doesn't matter, only the instruction it
490 /// refers to is considered.
491 LiveRangeQuery(const LiveInterval &LI, SlotIndex Idx)
492 : EarlyVal(0), LateVal(0), Kill(false) {
493 // Find the segment that enters the instruction.
494 LiveInterval::const_iterator I = LI.find(Idx.getBaseIndex());
495 LiveInterval::const_iterator E = LI.end();
498 // Is this an instruction live-in segment?
499 // If Idx is the start index of a basic block, include live-in segments
500 // that start at Idx.getBaseIndex().
501 if (I->start <= Idx.getBaseIndex()) {
504 // Move to the potentially live-out segment.
505 if (SlotIndex::isSameInstr(Idx, I->end)) {
510 // Special case: A PHIDef value can have its def in the middle of a
511 // segment if the value happens to be live out of the layout
513 // Such a value is not live-in.
514 if (EarlyVal->def == Idx.getBaseIndex())
517 // I now points to the segment that may be live-through, or defined by
518 // this instr. Ignore segments starting after the current instr.
519 if (SlotIndex::isEarlierInstr(Idx, I->start))
525 /// Return the value that is live-in to the instruction. This is the value
526 /// that will be read by the instruction's use operands. Return NULL if no
527 /// value is live-in.
528 VNInfo *valueIn() const {
532 /// Return true if the live-in value is killed by this instruction. This
533 /// means that either the live range ends at the instruction, or it changes
535 bool isKill() const {
539 /// Return true if this instruction has a dead def.
540 bool isDeadDef() const {
541 return EndPoint.isDead();
544 /// Return the value leaving the instruction, if any. This can be a
545 /// live-through value, or a live def. A dead def returns NULL.
546 VNInfo *valueOut() const {
547 return isDeadDef() ? 0 : LateVal;
550 /// Return the value defined by this instruction, if any. This includes
551 /// dead defs, it is the value created by the instruction's def operands.
552 VNInfo *valueDefined() const {
553 return EarlyVal == LateVal ? 0 : LateVal;
556 /// Return the end point of the last live range segment to interact with
557 /// the instruction, if any.
559 /// The end point is an invalid SlotIndex only if the live range doesn't
560 /// intersect the instruction at all.
562 /// The end point may be at or past the end of the instruction's basic
563 /// block. That means the value was live out of the block.
564 SlotIndex endPoint() const {
569 /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
570 /// LiveInterval into equivalence clases of connected components. A
571 /// LiveInterval that has multiple connected components can be broken into
572 /// multiple LiveIntervals.
574 /// Given a LiveInterval that may have multiple connected components, run:
576 /// unsigned numComps = ConEQ.Classify(LI);
577 /// if (numComps > 1) {
578 /// // allocate numComps-1 new LiveIntervals into LIS[1..]
579 /// ConEQ.Distribute(LIS);
582 class ConnectedVNInfoEqClasses {
584 IntEqClasses EqClass;
586 // Note that values a and b are connected.
587 void Connect(unsigned a, unsigned b);
592 explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
594 /// Classify - Classify the values in LI into connected components.
595 /// Return the number of connected components.
596 unsigned Classify(const LiveInterval *LI);
598 /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
599 /// the equivalence class assigned the VNI.
600 unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
602 /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
603 /// for each connected component. LIV must have a LiveInterval for each
604 /// connected component. The LiveIntervals in Liv[1..] must be empty.
605 /// Instructions using LIV[0] are rewritten.
606 void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);