b95272273b1355596be42d228fd8a5d42ef3b8b2
[oota-llvm.git] / include / llvm / CodeGen / LiveInterval.h
1 //===-- llvm/CodeGen/LiveInterval.h - Interval representation ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_CODEGEN_LIVEINTERVAL_H
22 #define LLVM_CODEGEN_LIVEINTERVAL_H
23
24 #include "llvm/ADT/IntEqClasses.h"
25 #include "llvm/Support/Allocator.h"
26 #include "llvm/Support/AlignOf.h"
27 #include "llvm/CodeGen/SlotIndexes.h"
28 #include <cassert>
29 #include <climits>
30
31 namespace llvm {
32   class LiveIntervals;
33   class MachineInstr;
34   class MachineRegisterInfo;
35   class TargetRegisterInfo;
36   class raw_ostream;
37
38   /// VNInfo - Value Number Information.
39   /// This class holds information about a machine level values, including
40   /// definition and use points.
41   ///
42   class VNInfo {
43   private:
44     enum {
45       HAS_PHI_KILL    = 1,
46       IS_UNUSED       = 1 << 1
47     };
48
49     unsigned char flags;
50
51   public:
52     typedef BumpPtrAllocator Allocator;
53
54     /// The ID number of this value.
55     unsigned id;
56
57     /// The index of the defining instruction.
58     SlotIndex def;
59
60     /// VNInfo constructor.
61     VNInfo(unsigned i, SlotIndex d)
62       : flags(0), id(i), def(d)
63     { }
64
65     /// VNInfo construtor, copies values from orig, except for the value number.
66     VNInfo(unsigned i, const VNInfo &orig)
67       : flags(orig.flags), id(i), def(orig.def)
68     { }
69
70     /// Copy from the parameter into this VNInfo.
71     void copyFrom(VNInfo &src) {
72       flags = src.flags;
73       def = src.def;
74     }
75
76     /// Used for copying value number info.
77     unsigned getFlags() const { return flags; }
78     void setFlags(unsigned flags) { this->flags = flags; }
79
80     /// Merge flags from another VNInfo
81     void mergeFlags(const VNInfo *VNI) {
82       flags = (flags | VNI->flags) & ~IS_UNUSED;
83     }
84
85     /// Returns true if one or more kills are PHI nodes.
86     /// Obsolete, do not use!
87     bool hasPHIKill() const { return flags & HAS_PHI_KILL; }
88     /// Set the PHI kill flag on this value.
89     void setHasPHIKill(bool hasKill) {
90       if (hasKill)
91         flags |= HAS_PHI_KILL;
92       else
93         flags &= ~HAS_PHI_KILL;
94     }
95
96     /// Returns true if this value is defined by a PHI instruction (or was,
97     /// PHI instrucions may have been eliminated).
98     /// PHI-defs begin at a block boundary, all other defs begin at register or
99     /// EC slots.
100     bool isPHIDef() const { return def.isBlock(); }
101
102     /// Returns true if this value is unused.
103     bool isUnused() const { return flags & IS_UNUSED; }
104     /// Set the "is unused" flag on this value.
105     void setIsUnused(bool unused) {
106       if (unused)
107         flags |= IS_UNUSED;
108       else
109         flags &= ~IS_UNUSED;
110     }
111   };
112
113   /// LiveRange structure - This represents a simple register range in the
114   /// program, with an inclusive start point and an exclusive end point.
115   /// These ranges are rendered as [start,end).
116   struct LiveRange {
117     SlotIndex start;  // Start point of the interval (inclusive)
118     SlotIndex end;    // End point of the interval (exclusive)
119     VNInfo *valno;   // identifier for the value contained in this interval.
120
121     LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
122       : start(S), end(E), valno(V) {
123
124       assert(S < E && "Cannot create empty or backwards range");
125     }
126
127     /// contains - Return true if the index is covered by this range.
128     ///
129     bool contains(SlotIndex I) const {
130       return start <= I && I < end;
131     }
132
133     /// containsRange - Return true if the given range, [S, E), is covered by
134     /// this range.
135     bool containsRange(SlotIndex S, SlotIndex E) const {
136       assert((S < E) && "Backwards interval?");
137       return (start <= S && S < end) && (start < E && E <= end);
138     }
139
140     bool operator<(const LiveRange &LR) const {
141       return start < LR.start || (start == LR.start && end < LR.end);
142     }
143     bool operator==(const LiveRange &LR) const {
144       return start == LR.start && end == LR.end;
145     }
146
147     void dump() const;
148     void print(raw_ostream &os) const;
149
150   private:
151     LiveRange(); // DO NOT IMPLEMENT
152   };
153
154   template <> struct isPodLike<LiveRange> { static const bool value = true; };
155
156   raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
157
158
159   inline bool operator<(SlotIndex V, const LiveRange &LR) {
160     return V < LR.start;
161   }
162
163   inline bool operator<(const LiveRange &LR, SlotIndex V) {
164     return LR.start < V;
165   }
166
167   /// LiveInterval - This class represents some number of live ranges for a
168   /// register or value.  This class also contains a bit of register allocator
169   /// state.
170   class LiveInterval {
171   public:
172
173     typedef SmallVector<LiveRange,4> Ranges;
174     typedef SmallVector<VNInfo*,4> VNInfoList;
175
176     const unsigned reg;  // the register or stack slot of this interval.
177     float weight;        // weight of this interval
178     Ranges ranges;       // the ranges in which this register is live
179     VNInfoList valnos;   // value#'s
180
181     struct InstrSlots {
182       enum {
183         LOAD  = 0,
184         USE   = 1,
185         DEF   = 2,
186         STORE = 3,
187         NUM   = 4
188       };
189
190     };
191
192     LiveInterval(unsigned Reg, float Weight)
193       : reg(Reg), weight(Weight) {}
194
195     typedef Ranges::iterator iterator;
196     iterator begin() { return ranges.begin(); }
197     iterator end()   { return ranges.end(); }
198
199     typedef Ranges::const_iterator const_iterator;
200     const_iterator begin() const { return ranges.begin(); }
201     const_iterator end() const  { return ranges.end(); }
202
203     typedef VNInfoList::iterator vni_iterator;
204     vni_iterator vni_begin() { return valnos.begin(); }
205     vni_iterator vni_end() { return valnos.end(); }
206
207     typedef VNInfoList::const_iterator const_vni_iterator;
208     const_vni_iterator vni_begin() const { return valnos.begin(); }
209     const_vni_iterator vni_end() const { return valnos.end(); }
210
211     /// advanceTo - Advance the specified iterator to point to the LiveRange
212     /// containing the specified position, or end() if the position is past the
213     /// end of the interval.  If no LiveRange contains this position, but the
214     /// position is in a hole, this method returns an iterator pointing to the
215     /// LiveRange immediately after the hole.
216     iterator advanceTo(iterator I, SlotIndex Pos) {
217       assert(I != end());
218       if (Pos >= endIndex())
219         return end();
220       while (I->end <= Pos) ++I;
221       return I;
222     }
223
224     /// find - Return an iterator pointing to the first range that ends after
225     /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
226     /// when searching large intervals.
227     ///
228     /// If Pos is contained in a LiveRange, that range is returned.
229     /// If Pos is in a hole, the following LiveRange is returned.
230     /// If Pos is beyond endIndex, end() is returned.
231     iterator find(SlotIndex Pos);
232
233     const_iterator find(SlotIndex Pos) const {
234       return const_cast<LiveInterval*>(this)->find(Pos);
235     }
236
237     void clear() {
238       valnos.clear();
239       ranges.clear();
240     }
241
242     bool hasAtLeastOneValue() const { return !valnos.empty(); }
243
244     bool containsOneValue() const { return valnos.size() == 1; }
245
246     unsigned getNumValNums() const { return (unsigned)valnos.size(); }
247
248     /// getValNumInfo - Returns pointer to the specified val#.
249     ///
250     inline VNInfo *getValNumInfo(unsigned ValNo) {
251       return valnos[ValNo];
252     }
253     inline const VNInfo *getValNumInfo(unsigned ValNo) const {
254       return valnos[ValNo];
255     }
256
257     /// containsValue - Returns true if VNI belongs to this interval.
258     bool containsValue(const VNInfo *VNI) const {
259       return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
260     }
261
262     /// getNextValue - Create a new value number and return it.  MIIdx specifies
263     /// the instruction that defines the value number.
264     VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
265       VNInfo *VNI =
266         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
267       valnos.push_back(VNI);
268       return VNI;
269     }
270
271     /// createDeadDef - Make sure the interval has a value defined at Def.
272     /// If one already exists, return it. Otherwise allocate a new value and
273     /// add liveness for a dead def.
274     VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
275
276     /// Create a copy of the given value. The new value will be identical except
277     /// for the Value number.
278     VNInfo *createValueCopy(const VNInfo *orig,
279                             VNInfo::Allocator &VNInfoAllocator) {
280       VNInfo *VNI =
281         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
282       valnos.push_back(VNI);
283       return VNI;
284     }
285
286     /// RenumberValues - Renumber all values in order of appearance and remove
287     /// unused values.
288     void RenumberValues(LiveIntervals &lis);
289
290     /// MergeValueNumberInto - This method is called when two value nubmers
291     /// are found to be equivalent.  This eliminates V1, replacing all
292     /// LiveRanges with the V1 value number with the V2 value number.  This can
293     /// cause merging of V1/V2 values numbers and compaction of the value space.
294     VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
295
296     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
297     /// in RHS into this live interval as the specified value number.
298     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
299     /// current interval, it will replace the value numbers of the overlaped
300     /// live ranges with the specified value number.
301     void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
302
303     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
304     /// in RHS into this live interval as the specified value number.
305     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
306     /// current interval, but only if the overlapping LiveRanges have the
307     /// specified value number.
308     void MergeValueInAsValue(const LiveInterval &RHS,
309                              const VNInfo *RHSValNo, VNInfo *LHSValNo);
310
311     /// Copy - Copy the specified live interval. This copies all the fields
312     /// except for the register of the interval.
313     void Copy(const LiveInterval &RHS, MachineRegisterInfo *MRI,
314               VNInfo::Allocator &VNInfoAllocator);
315
316     bool empty() const { return ranges.empty(); }
317
318     /// beginIndex - Return the lowest numbered slot covered by interval.
319     SlotIndex beginIndex() const {
320       assert(!empty() && "Call to beginIndex() on empty interval.");
321       return ranges.front().start;
322     }
323
324     /// endNumber - return the maximum point of the interval of the whole,
325     /// exclusive.
326     SlotIndex endIndex() const {
327       assert(!empty() && "Call to endIndex() on empty interval.");
328       return ranges.back().end;
329     }
330
331     bool expiredAt(SlotIndex index) const {
332       return index >= endIndex();
333     }
334
335     bool liveAt(SlotIndex index) const {
336       const_iterator r = find(index);
337       return r != end() && r->start <= index;
338     }
339
340     /// killedAt - Return true if a live range ends at index. Note that the kill
341     /// point is not contained in the half-open live range. It is usually the
342     /// getDefIndex() slot following its last use.
343     bool killedAt(SlotIndex index) const {
344       const_iterator r = find(index.getRegSlot(true));
345       return r != end() && r->end == index;
346     }
347
348     /// killedInRange - Return true if the interval has kills in [Start,End).
349     /// Note that the kill point is considered the end of a live range, so it is
350     /// not contained in the live range. If a live range ends at End, it won't
351     /// be counted as a kill by this method.
352     bool killedInRange(SlotIndex Start, SlotIndex End) const;
353
354     /// getLiveRangeContaining - Return the live range that contains the
355     /// specified index, or null if there is none.
356     const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
357       const_iterator I = FindLiveRangeContaining(Idx);
358       return I == end() ? 0 : &*I;
359     }
360
361     /// getLiveRangeContaining - Return the live range that contains the
362     /// specified index, or null if there is none.
363     LiveRange *getLiveRangeContaining(SlotIndex Idx) {
364       iterator I = FindLiveRangeContaining(Idx);
365       return I == end() ? 0 : &*I;
366     }
367
368     /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
369     VNInfo *getVNInfoAt(SlotIndex Idx) const {
370       const_iterator I = FindLiveRangeContaining(Idx);
371       return I == end() ? 0 : I->valno;
372     }
373
374     /// getVNInfoBefore - Return the VNInfo that is live up to but not
375     /// necessarilly including Idx, or NULL. Use this to find the reaching def
376     /// used by an instruction at this SlotIndex position.
377     VNInfo *getVNInfoBefore(SlotIndex Idx) const {
378       const_iterator I = FindLiveRangeContaining(Idx.getPrevSlot());
379       return I == end() ? 0 : I->valno;
380     }
381
382     /// FindLiveRangeContaining - Return an iterator to the live range that
383     /// contains the specified index, or end() if there is none.
384     iterator FindLiveRangeContaining(SlotIndex Idx) {
385       iterator I = find(Idx);
386       return I != end() && I->start <= Idx ? I : end();
387     }
388
389     const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
390       const_iterator I = find(Idx);
391       return I != end() && I->start <= Idx ? I : end();
392     }
393
394     /// overlaps - Return true if the intersection of the two live intervals is
395     /// not empty.
396     bool overlaps(const LiveInterval& other) const {
397       if (other.empty())
398         return false;
399       return overlapsFrom(other, other.begin());
400     }
401
402     /// overlaps - Return true if the live interval overlaps a range specified
403     /// by [Start, End).
404     bool overlaps(SlotIndex Start, SlotIndex End) const;
405
406     /// overlapsFrom - Return true if the intersection of the two live intervals
407     /// is not empty.  The specified iterator is a hint that we can begin
408     /// scanning the Other interval starting at I.
409     bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
410
411     /// addRange - Add the specified LiveRange to this interval, merging
412     /// intervals as appropriate.  This returns an iterator to the inserted live
413     /// range (which may have grown since it was inserted.
414     void addRange(LiveRange LR) {
415       addRangeFrom(LR, ranges.begin());
416     }
417
418     /// extendInBlock - If this interval is live before Kill in the basic block
419     /// that starts at StartIdx, extend it to be live up to Kill, and return
420     /// the value. If there is no live range before Kill, return NULL.
421     VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
422
423     /// join - Join two live intervals (this, and other) together.  This applies
424     /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
425     /// the intervals are not joinable, this aborts.
426     void join(LiveInterval &Other,
427               const int *ValNoAssignments,
428               const int *RHSValNoAssignments,
429               SmallVector<VNInfo*, 16> &NewVNInfo,
430               MachineRegisterInfo *MRI);
431
432     /// isInOneLiveRange - Return true if the range specified is entirely in the
433     /// a single LiveRange of the live interval.
434     bool isInOneLiveRange(SlotIndex Start, SlotIndex End) const {
435       const_iterator r = find(Start);
436       return r != end() && r->containsRange(Start, End);
437     }
438
439     /// removeRange - Remove the specified range from this interval.  Note that
440     /// the range must be a single LiveRange in its entirety.
441     void removeRange(SlotIndex Start, SlotIndex End,
442                      bool RemoveDeadValNo = false);
443
444     void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
445       removeRange(LR.start, LR.end, RemoveDeadValNo);
446     }
447
448     /// removeValNo - Remove all the ranges defined by the specified value#.
449     /// Also remove the value# from value# list.
450     void removeValNo(VNInfo *ValNo);
451
452     /// getSize - Returns the sum of sizes of all the LiveRange's.
453     ///
454     unsigned getSize() const;
455
456     /// Returns true if the live interval is zero length, i.e. no live ranges
457     /// span instructions. It doesn't pay to spill such an interval.
458     bool isZeroLength(SlotIndexes *Indexes) const {
459       for (const_iterator i = begin(), e = end(); i != e; ++i)
460         if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
461             i->end.getBaseIndex())
462           return false;
463       return true;
464     }
465
466     /// isSpillable - Can this interval be spilled?
467     bool isSpillable() const {
468       return weight != HUGE_VALF;
469     }
470
471     /// markNotSpillable - Mark interval as not spillable
472     void markNotSpillable() {
473       weight = HUGE_VALF;
474     }
475
476     bool operator<(const LiveInterval& other) const {
477       const SlotIndex &thisIndex = beginIndex();
478       const SlotIndex &otherIndex = other.beginIndex();
479       return (thisIndex < otherIndex ||
480               (thisIndex == otherIndex && reg < other.reg));
481     }
482
483     void print(raw_ostream &OS) const;
484     void dump() const;
485
486     /// \brief Walk the interval and assert if any invariants fail to hold.
487     ///
488     /// Note that this is a no-op when asserts are disabled.
489 #ifdef NDEBUG
490     void verify() const {}
491 #else
492     void verify() const;
493 #endif
494
495   private:
496
497     Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
498     void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
499     Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
500     void markValNoForDeletion(VNInfo *V);
501     void mergeIntervalRanges(const LiveInterval &RHS,
502                              VNInfo *LHSValNo = 0,
503                              const VNInfo *RHSValNo = 0);
504
505     LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
506
507   };
508
509   inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
510     LI.print(OS);
511     return OS;
512   }
513
514   /// LiveRangeQuery - Query information about a live range around a given
515   /// instruction. This class hides the implementation details of live ranges,
516   /// and it should be used as the primary interface for examining live ranges
517   /// around instructions.
518   ///
519   class LiveRangeQuery {
520     VNInfo *EarlyVal;
521     VNInfo *LateVal;
522     SlotIndex EndPoint;
523     bool Kill;
524
525   public:
526     /// Create a LiveRangeQuery for the given live range and instruction index.
527     /// The sub-instruction slot of Idx doesn't matter, only the instruction it
528     /// refers to is considered.
529     LiveRangeQuery(const LiveInterval &LI, SlotIndex Idx)
530       : EarlyVal(0), LateVal(0), Kill(false) {
531       // Find the segment that enters the instruction.
532       LiveInterval::const_iterator I = LI.find(Idx.getBaseIndex());
533       LiveInterval::const_iterator E = LI.end();
534       if (I == E)
535         return;
536       // Is this an instruction live-in segment?
537       if (SlotIndex::isEarlierInstr(I->start, Idx)) {
538         EarlyVal = I->valno;
539         EndPoint = I->end;
540         // Move to the potentially live-out segment.
541         if (SlotIndex::isSameInstr(Idx, I->end)) {
542           Kill = true;
543           if (++I == E)
544             return;
545         }
546       }
547       // I now points to the segment that may be live-through, or defined by
548       // this instr. Ignore segments starting after the current instr.
549       if (SlotIndex::isEarlierInstr(Idx, I->start))
550         return;
551       LateVal = I->valno;
552       EndPoint = I->end;
553     }
554
555     /// Return the value that is live-in to the instruction. This is the value
556     /// that will be read by the instruction's use operands. Return NULL if no
557     /// value is live-in.
558     VNInfo *valueIn() const {
559       return EarlyVal;
560     }
561
562     /// Return true if the live-in value is killed by this instruction. This
563     /// means that either the live range ends at the instruction, or it changes
564     /// value.
565     bool isKill() const {
566       return Kill;
567     }
568
569     /// Return true if this instruction has a dead def.
570     bool isDeadDef() const {
571       return EndPoint.isDead();
572     }
573
574     /// Return the value leaving the instruction, if any. This can be a
575     /// live-through value, or a live def. A dead def returns NULL.
576     VNInfo *valueOut() const {
577       return isDeadDef() ? 0 : LateVal;
578     }
579
580     /// Return the value defined by this instruction, if any. This includes
581     /// dead defs, it is the value created by the instruction's def operands.
582     VNInfo *valueDefined() const {
583       return EarlyVal == LateVal ? 0 : LateVal;
584     }
585
586     /// Return the end point of the last live range segment to interact with
587     /// the instruction, if any.
588     ///
589     /// The end point is an invalid SlotIndex only if the live range doesn't
590     /// intersect the instruction at all.
591     ///
592     /// The end point may be at or past the end of the instruction's basic
593     /// block. That means the value was live out of the block.
594     SlotIndex endPoint() const {
595       return EndPoint;
596     }
597   };
598
599   /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
600   /// LiveInterval into equivalence clases of connected components. A
601   /// LiveInterval that has multiple connected components can be broken into
602   /// multiple LiveIntervals.
603   ///
604   /// Given a LiveInterval that may have multiple connected components, run:
605   ///
606   ///   unsigned numComps = ConEQ.Classify(LI);
607   ///   if (numComps > 1) {
608   ///     // allocate numComps-1 new LiveIntervals into LIS[1..]
609   ///     ConEQ.Distribute(LIS);
610   /// }
611
612   class ConnectedVNInfoEqClasses {
613     LiveIntervals &LIS;
614     IntEqClasses EqClass;
615
616     // Note that values a and b are connected.
617     void Connect(unsigned a, unsigned b);
618
619     unsigned Renumber();
620
621   public:
622     explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
623
624     /// Classify - Classify the values in LI into connected components.
625     /// Return the number of connected components.
626     unsigned Classify(const LiveInterval *LI);
627
628     /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
629     /// the equivalence class assigned the VNI.
630     unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
631
632     /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
633     /// for each connected component. LIV must have a LiveInterval for each
634     /// connected component. The LiveIntervals in Liv[1..] must be empty.
635     /// Instructions using LIV[0] are rewritten.
636     void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);
637
638   };
639
640 }
641 #endif