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/Support/Allocator.h"
26 #include "llvm/Support/AlignOf.h"
27 #include "llvm/CodeGen/SlotIndexes.h"
34 class MachineRegisterInfo;
35 class TargetRegisterInfo;
38 /// VNInfo - Value Number Information.
39 /// This class holds information about a machine level values, including
40 /// definition and use points.
51 typedef BumpPtrAllocator Allocator;
53 /// The ID number of this value.
56 /// The index of the defining instruction.
59 /// VNInfo constructor.
60 VNInfo(unsigned i, SlotIndex d)
61 : flags(0), id(i), def(d)
64 /// VNInfo construtor, copies values from orig, except for the value number.
65 VNInfo(unsigned i, const VNInfo &orig)
66 : flags(orig.flags), id(i), def(orig.def)
69 /// Copy from the parameter into this VNInfo.
70 void copyFrom(VNInfo &src) {
75 /// Used for copying value number info.
76 unsigned getFlags() const { return flags; }
77 void setFlags(unsigned flags) { this->flags = flags; }
79 /// Merge flags from another VNInfo
80 void mergeFlags(const VNInfo *VNI) {
81 flags = (flags | VNI->flags) & ~IS_UNUSED;
84 /// Returns true if this value is defined by a PHI instruction (or was,
85 /// PHI instrucions may have been eliminated).
86 /// PHI-defs begin at a block boundary, all other defs begin at register or
88 bool isPHIDef() const { return def.isBlock(); }
90 /// Returns true if this value is unused.
91 bool isUnused() const { return flags & IS_UNUSED; }
92 /// Set the "is unused" flag on this value.
93 void setIsUnused(bool unused) {
101 /// LiveRange structure - This represents a simple register range in the
102 /// program, with an inclusive start point and an exclusive end point.
103 /// These ranges are rendered as [start,end).
105 SlotIndex start; // Start point of the interval (inclusive)
106 SlotIndex end; // End point of the interval (exclusive)
107 VNInfo *valno; // identifier for the value contained in this interval.
109 LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
110 : start(S), end(E), valno(V) {
112 assert(S < E && "Cannot create empty or backwards range");
115 /// contains - Return true if the index is covered by this range.
117 bool contains(SlotIndex I) const {
118 return start <= I && I < end;
121 /// containsRange - Return true if the given range, [S, E), is covered by
123 bool containsRange(SlotIndex S, SlotIndex E) const {
124 assert((S < E) && "Backwards interval?");
125 return (start <= S && S < end) && (start < E && E <= end);
128 bool operator<(const LiveRange &LR) const {
129 return start < LR.start || (start == LR.start && end < LR.end);
131 bool operator==(const LiveRange &LR) const {
132 return start == LR.start && end == LR.end;
136 void print(raw_ostream &os) const;
139 LiveRange(); // DO NOT IMPLEMENT
142 template <> struct isPodLike<LiveRange> { static const bool value = true; };
144 raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
147 inline bool operator<(SlotIndex V, const LiveRange &LR) {
151 inline bool operator<(const LiveRange &LR, SlotIndex V) {
155 /// LiveInterval - This class represents some number of live ranges for a
156 /// register or value. This class also contains a bit of register allocator
161 typedef SmallVector<LiveRange,4> Ranges;
162 typedef SmallVector<VNInfo*,4> VNInfoList;
164 const unsigned reg; // the register or stack slot of this interval.
165 float weight; // weight of this interval
166 Ranges ranges; // the ranges in which this register is live
167 VNInfoList valnos; // value#'s
180 LiveInterval(unsigned Reg, float Weight)
181 : reg(Reg), weight(Weight) {}
183 typedef Ranges::iterator iterator;
184 iterator begin() { return ranges.begin(); }
185 iterator end() { return ranges.end(); }
187 typedef Ranges::const_iterator const_iterator;
188 const_iterator begin() const { return ranges.begin(); }
189 const_iterator end() const { return ranges.end(); }
191 typedef VNInfoList::iterator vni_iterator;
192 vni_iterator vni_begin() { return valnos.begin(); }
193 vni_iterator vni_end() { return valnos.end(); }
195 typedef VNInfoList::const_iterator const_vni_iterator;
196 const_vni_iterator vni_begin() const { return valnos.begin(); }
197 const_vni_iterator vni_end() const { return valnos.end(); }
199 /// advanceTo - Advance the specified iterator to point to the LiveRange
200 /// containing the specified position, or end() if the position is past the
201 /// end of the interval. If no LiveRange contains this position, but the
202 /// position is in a hole, this method returns an iterator pointing to the
203 /// LiveRange immediately after the hole.
204 iterator advanceTo(iterator I, SlotIndex Pos) {
206 if (Pos >= endIndex())
208 while (I->end <= Pos) ++I;
212 /// find - Return an iterator pointing to the first range that ends after
213 /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
214 /// when searching large intervals.
216 /// If Pos is contained in a LiveRange, that range is returned.
217 /// If Pos is in a hole, the following LiveRange is returned.
218 /// If Pos is beyond endIndex, end() is returned.
219 iterator find(SlotIndex Pos);
221 const_iterator find(SlotIndex Pos) const {
222 return const_cast<LiveInterval*>(this)->find(Pos);
230 bool hasAtLeastOneValue() const { return !valnos.empty(); }
232 bool containsOneValue() const { return valnos.size() == 1; }
234 unsigned getNumValNums() const { return (unsigned)valnos.size(); }
236 /// getValNumInfo - Returns pointer to the specified val#.
238 inline VNInfo *getValNumInfo(unsigned ValNo) {
239 return valnos[ValNo];
241 inline const VNInfo *getValNumInfo(unsigned ValNo) const {
242 return valnos[ValNo];
245 /// containsValue - Returns true if VNI belongs to this interval.
246 bool containsValue(const VNInfo *VNI) const {
247 return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
250 /// getNextValue - Create a new value number and return it. MIIdx specifies
251 /// the instruction that defines the value number.
252 VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
254 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
255 valnos.push_back(VNI);
259 /// createDeadDef - Make sure the interval has a value defined at Def.
260 /// If one already exists, return it. Otherwise allocate a new value and
261 /// add liveness for a dead def.
262 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
264 /// Create a copy of the given value. The new value will be identical except
265 /// for the Value number.
266 VNInfo *createValueCopy(const VNInfo *orig,
267 VNInfo::Allocator &VNInfoAllocator) {
269 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
270 valnos.push_back(VNI);
274 /// RenumberValues - Renumber all values in order of appearance and remove
276 void RenumberValues(LiveIntervals &lis);
278 /// MergeValueNumberInto - This method is called when two value nubmers
279 /// are found to be equivalent. This eliminates V1, replacing all
280 /// LiveRanges with the V1 value number with the V2 value number. This can
281 /// cause merging of V1/V2 values numbers and compaction of the value space.
282 VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
284 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
285 /// in RHS into this live interval as the specified value number.
286 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
287 /// current interval, it will replace the value numbers of the overlaped
288 /// live ranges with the specified value number.
289 void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
291 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
292 /// in RHS into this live interval as the specified value number.
293 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
294 /// current interval, but only if the overlapping LiveRanges have the
295 /// specified value number.
296 void MergeValueInAsValue(const LiveInterval &RHS,
297 const VNInfo *RHSValNo, VNInfo *LHSValNo);
299 /// Copy - Copy the specified live interval. This copies all the fields
300 /// except for the register of the interval.
301 void Copy(const LiveInterval &RHS, MachineRegisterInfo *MRI,
302 VNInfo::Allocator &VNInfoAllocator);
304 bool empty() const { return ranges.empty(); }
306 /// beginIndex - Return the lowest numbered slot covered by interval.
307 SlotIndex beginIndex() const {
308 assert(!empty() && "Call to beginIndex() on empty interval.");
309 return ranges.front().start;
312 /// endNumber - return the maximum point of the interval of the whole,
314 SlotIndex endIndex() const {
315 assert(!empty() && "Call to endIndex() on empty interval.");
316 return ranges.back().end;
319 bool expiredAt(SlotIndex index) const {
320 return index >= endIndex();
323 bool liveAt(SlotIndex index) const {
324 const_iterator r = find(index);
325 return r != end() && r->start <= index;
328 /// killedAt - Return true if a live range ends at index. Note that the kill
329 /// point is not contained in the half-open live range. It is usually the
330 /// getDefIndex() slot following its last use.
331 bool killedAt(SlotIndex index) const {
332 const_iterator r = find(index.getRegSlot(true));
333 return r != end() && r->end == index;
336 /// killedInRange - Return true if the interval has kills in [Start,End).
337 /// Note that the kill point is considered the end of a live range, so it is
338 /// not contained in the live range. If a live range ends at End, it won't
339 /// be counted as a kill by this method.
340 bool killedInRange(SlotIndex Start, SlotIndex End) const;
342 /// getLiveRangeContaining - Return the live range that contains the
343 /// specified index, or null if there is none.
344 const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
345 const_iterator I = FindLiveRangeContaining(Idx);
346 return I == end() ? 0 : &*I;
349 /// getLiveRangeContaining - Return the live range that contains the
350 /// specified index, or null if there is none.
351 LiveRange *getLiveRangeContaining(SlotIndex Idx) {
352 iterator I = FindLiveRangeContaining(Idx);
353 return I == end() ? 0 : &*I;
356 /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
357 VNInfo *getVNInfoAt(SlotIndex Idx) const {
358 const_iterator I = FindLiveRangeContaining(Idx);
359 return I == end() ? 0 : I->valno;
362 /// getVNInfoBefore - Return the VNInfo that is live up to but not
363 /// necessarilly including Idx, or NULL. Use this to find the reaching def
364 /// used by an instruction at this SlotIndex position.
365 VNInfo *getVNInfoBefore(SlotIndex Idx) const {
366 const_iterator I = FindLiveRangeContaining(Idx.getPrevSlot());
367 return I == end() ? 0 : I->valno;
370 /// FindLiveRangeContaining - Return an iterator to the live range that
371 /// contains the specified index, or end() if there is none.
372 iterator FindLiveRangeContaining(SlotIndex Idx) {
373 iterator I = find(Idx);
374 return I != end() && I->start <= Idx ? I : end();
377 const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
378 const_iterator I = find(Idx);
379 return I != end() && I->start <= Idx ? I : end();
382 /// overlaps - Return true if the intersection of the two live intervals is
384 bool overlaps(const LiveInterval& other) const {
387 return overlapsFrom(other, other.begin());
390 /// overlaps - Return true if the live interval overlaps a range specified
392 bool overlaps(SlotIndex Start, SlotIndex End) const;
394 /// overlapsFrom - Return true if the intersection of the two live intervals
395 /// is not empty. The specified iterator is a hint that we can begin
396 /// scanning the Other interval starting at I.
397 bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
399 /// addRange - Add the specified LiveRange to this interval, merging
400 /// intervals as appropriate. This returns an iterator to the inserted live
401 /// range (which may have grown since it was inserted.
402 void addRange(LiveRange LR) {
403 addRangeFrom(LR, ranges.begin());
406 /// extendInBlock - If this interval is live before Kill in the basic block
407 /// that starts at StartIdx, extend it to be live up to Kill, and return
408 /// the value. If there is no live range before Kill, return NULL.
409 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
411 /// join - Join two live intervals (this, and other) together. This applies
412 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
413 /// the intervals are not joinable, this aborts.
414 void join(LiveInterval &Other,
415 const int *ValNoAssignments,
416 const int *RHSValNoAssignments,
417 SmallVector<VNInfo*, 16> &NewVNInfo,
418 MachineRegisterInfo *MRI);
420 /// isInOneLiveRange - Return true if the range specified is entirely in the
421 /// a single LiveRange of the live interval.
422 bool isInOneLiveRange(SlotIndex Start, SlotIndex End) const {
423 const_iterator r = find(Start);
424 return r != end() && r->containsRange(Start, End);
427 /// removeRange - Remove the specified range from this interval. Note that
428 /// the range must be a single LiveRange in its entirety.
429 void removeRange(SlotIndex Start, SlotIndex End,
430 bool RemoveDeadValNo = false);
432 void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
433 removeRange(LR.start, LR.end, RemoveDeadValNo);
436 /// removeValNo - Remove all the ranges defined by the specified value#.
437 /// Also remove the value# from value# list.
438 void removeValNo(VNInfo *ValNo);
440 /// getSize - Returns the sum of sizes of all the LiveRange's.
442 unsigned getSize() const;
444 /// Returns true if the live interval is zero length, i.e. no live ranges
445 /// span instructions. It doesn't pay to spill such an interval.
446 bool isZeroLength(SlotIndexes *Indexes) const {
447 for (const_iterator i = begin(), e = end(); i != e; ++i)
448 if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
449 i->end.getBaseIndex())
454 /// isSpillable - Can this interval be spilled?
455 bool isSpillable() const {
456 return weight != HUGE_VALF;
459 /// markNotSpillable - Mark interval as not spillable
460 void markNotSpillable() {
464 bool operator<(const LiveInterval& other) const {
465 const SlotIndex &thisIndex = beginIndex();
466 const SlotIndex &otherIndex = other.beginIndex();
467 return (thisIndex < otherIndex ||
468 (thisIndex == otherIndex && reg < other.reg));
471 void print(raw_ostream &OS) const;
474 /// \brief Walk the interval and assert if any invariants fail to hold.
476 /// Note that this is a no-op when asserts are disabled.
478 void verify() const {}
485 Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
486 void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
487 Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
488 void markValNoForDeletion(VNInfo *V);
489 void mergeIntervalRanges(const LiveInterval &RHS,
490 VNInfo *LHSValNo = 0,
491 const VNInfo *RHSValNo = 0);
493 LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
497 inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
502 /// LiveRangeQuery - Query information about a live range around a given
503 /// instruction. This class hides the implementation details of live ranges,
504 /// and it should be used as the primary interface for examining live ranges
505 /// around instructions.
507 class LiveRangeQuery {
514 /// Create a LiveRangeQuery for the given live range and instruction index.
515 /// The sub-instruction slot of Idx doesn't matter, only the instruction it
516 /// refers to is considered.
517 LiveRangeQuery(const LiveInterval &LI, SlotIndex Idx)
518 : EarlyVal(0), LateVal(0), Kill(false) {
519 // Find the segment that enters the instruction.
520 LiveInterval::const_iterator I = LI.find(Idx.getBaseIndex());
521 LiveInterval::const_iterator E = LI.end();
524 // Is this an instruction live-in segment?
525 if (SlotIndex::isEarlierInstr(I->start, Idx)) {
528 // Move to the potentially live-out segment.
529 if (SlotIndex::isSameInstr(Idx, I->end)) {
535 // I now points to the segment that may be live-through, or defined by
536 // this instr. Ignore segments starting after the current instr.
537 if (SlotIndex::isEarlierInstr(Idx, I->start))
543 /// Return the value that is live-in to the instruction. This is the value
544 /// that will be read by the instruction's use operands. Return NULL if no
545 /// value is live-in.
546 VNInfo *valueIn() const {
550 /// Return true if the live-in value is killed by this instruction. This
551 /// means that either the live range ends at the instruction, or it changes
553 bool isKill() const {
557 /// Return true if this instruction has a dead def.
558 bool isDeadDef() const {
559 return EndPoint.isDead();
562 /// Return the value leaving the instruction, if any. This can be a
563 /// live-through value, or a live def. A dead def returns NULL.
564 VNInfo *valueOut() const {
565 return isDeadDef() ? 0 : LateVal;
568 /// Return the value defined by this instruction, if any. This includes
569 /// dead defs, it is the value created by the instruction's def operands.
570 VNInfo *valueDefined() const {
571 return EarlyVal == LateVal ? 0 : LateVal;
574 /// Return the end point of the last live range segment to interact with
575 /// the instruction, if any.
577 /// The end point is an invalid SlotIndex only if the live range doesn't
578 /// intersect the instruction at all.
580 /// The end point may be at or past the end of the instruction's basic
581 /// block. That means the value was live out of the block.
582 SlotIndex endPoint() const {
587 /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
588 /// LiveInterval into equivalence clases of connected components. A
589 /// LiveInterval that has multiple connected components can be broken into
590 /// multiple LiveIntervals.
592 /// Given a LiveInterval that may have multiple connected components, run:
594 /// unsigned numComps = ConEQ.Classify(LI);
595 /// if (numComps > 1) {
596 /// // allocate numComps-1 new LiveIntervals into LIS[1..]
597 /// ConEQ.Distribute(LIS);
600 class ConnectedVNInfoEqClasses {
602 IntEqClasses EqClass;
604 // Note that values a and b are connected.
605 void Connect(unsigned a, unsigned b);
610 explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
612 /// Classify - Classify the values in LI into connected components.
613 /// Return the number of connected components.
614 unsigned Classify(const LiveInterval *LI);
616 /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
617 /// the equivalence class assigned the VNI.
618 unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
620 /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
621 /// for each connected component. LIV must have a LiveInterval for each
622 /// connected component. The LiveIntervals in Liv[1..] must be empty.
623 /// Instructions using LIV[0] are rewritten.
624 void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);