Add LiveInterval::find and use it for most LiveRange searching operations
[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/SmallVector.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   /// Care must be taken in interpreting the def index of the value. The
43   /// following rules apply:
44   ///
45   /// If the isDefAccurate() method returns false then def does not contain the
46   /// index of the defining MachineInstr, or even (necessarily) to a
47   /// MachineInstr at all. In general such a def index is not meaningful
48   /// and should not be used. The exception is that, for values originally
49   /// defined by PHI instructions, after PHI elimination def will contain the
50   /// index of the MBB in which the PHI originally existed. This can be used
51   /// to insert code (spills or copies) which deals with the value, which will
52   /// be live in to the block.
53   class VNInfo {
54   private:
55     enum {
56       HAS_PHI_KILL    = 1,
57       REDEF_BY_EC     = 1 << 1,
58       IS_PHI_DEF      = 1 << 2,
59       IS_UNUSED       = 1 << 3,
60       IS_DEF_ACCURATE = 1 << 4
61     };
62
63     MachineInstr *copy;
64     unsigned char flags;
65
66   public:
67     typedef BumpPtrAllocator Allocator;
68
69     /// The ID number of this value.
70     unsigned id;
71
72     /// The index of the defining instruction (if isDefAccurate() returns true).
73     SlotIndex def;
74
75     /// VNInfo constructor.
76     /// d is presumed to point to the actual defining instr. If it doesn't
77     /// setIsDefAccurate(false) should be called after construction.
78     VNInfo(unsigned i, SlotIndex d, MachineInstr *c)
79       : copy(c), flags(IS_DEF_ACCURATE), id(i), def(d)
80     { }
81
82     /// VNInfo construtor, copies values from orig, except for the value number.
83     VNInfo(unsigned i, const VNInfo &orig)
84       : copy(orig.copy), flags(orig.flags), id(i), def(orig.def)
85     { }
86
87     /// Copy from the parameter into this VNInfo.
88     void copyFrom(VNInfo &src) {
89       flags = src.flags;
90       copy = src.copy;
91       def = src.def;
92     }
93
94     /// Used for copying value number info.
95     unsigned getFlags() const { return flags; }
96     void setFlags(unsigned flags) { this->flags = flags; }
97
98     /// For a register interval, if this VN was definied by a copy instr
99     /// getCopy() returns a pointer to it, otherwise returns 0.
100     /// For a stack interval the behaviour of this method is undefined.
101     MachineInstr* getCopy() const { return copy; }
102     /// For a register interval, set the copy member.
103     /// This method should not be called on stack intervals as it may lead to
104     /// undefined behavior.
105     void setCopy(MachineInstr *c) { copy = c; }
106
107     /// Returns true if one or more kills are PHI nodes.
108     bool hasPHIKill() const { return flags & HAS_PHI_KILL; }
109     /// Set the PHI kill flag on this value.
110     void setHasPHIKill(bool hasKill) {
111       if (hasKill)
112         flags |= HAS_PHI_KILL;
113       else
114         flags &= ~HAS_PHI_KILL;
115     }
116
117     /// Returns true if this value is re-defined by an early clobber somewhere
118     /// during the live range.
119     bool hasRedefByEC() const { return flags & REDEF_BY_EC; }
120     /// Set the "redef by early clobber" flag on this value.
121     void setHasRedefByEC(bool hasRedef) {
122       if (hasRedef)
123         flags |= REDEF_BY_EC;
124       else
125         flags &= ~REDEF_BY_EC;
126     }
127
128     /// Returns true if this value is defined by a PHI instruction (or was,
129     /// PHI instrucions may have been eliminated).
130     bool isPHIDef() const { return flags & IS_PHI_DEF; }
131     /// Set the "phi def" flag on this value.
132     void setIsPHIDef(bool phiDef) {
133       if (phiDef)
134         flags |= IS_PHI_DEF;
135       else
136         flags &= ~IS_PHI_DEF;
137     }
138
139     /// Returns true if this value is unused.
140     bool isUnused() const { return flags & IS_UNUSED; }
141     /// Set the "is unused" flag on this value.
142     void setIsUnused(bool unused) {
143       if (unused)
144         flags |= IS_UNUSED;
145       else
146         flags &= ~IS_UNUSED;
147     }
148
149     /// Returns true if the def is accurate.
150     bool isDefAccurate() const { return flags & IS_DEF_ACCURATE; }
151     /// Set the "is def accurate" flag on this value.
152     void setIsDefAccurate(bool defAccurate) {
153       if (defAccurate)
154         flags |= IS_DEF_ACCURATE;
155       else
156         flags &= ~IS_DEF_ACCURATE;
157     }
158   };
159
160   /// LiveRange structure - This represents a simple register range in the
161   /// program, with an inclusive start point and an exclusive end point.
162   /// These ranges are rendered as [start,end).
163   struct LiveRange {
164     SlotIndex start;  // Start point of the interval (inclusive)
165     SlotIndex end;    // End point of the interval (exclusive)
166     VNInfo *valno;   // identifier for the value contained in this interval.
167
168     LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
169       : start(S), end(E), valno(V) {
170
171       assert(S < E && "Cannot create empty or backwards range");
172     }
173
174     /// contains - Return true if the index is covered by this range.
175     ///
176     bool contains(SlotIndex I) const {
177       return start <= I && I < end;
178     }
179
180     /// containsRange - Return true if the given range, [S, E), is covered by
181     /// this range.
182     bool containsRange(SlotIndex S, SlotIndex E) const {
183       assert((S < E) && "Backwards interval?");
184       return (start <= S && S < end) && (start < E && E <= end);
185     }
186
187     bool operator<(const LiveRange &LR) const {
188       return start < LR.start || (start == LR.start && end < LR.end);
189     }
190     bool operator==(const LiveRange &LR) const {
191       return start == LR.start && end == LR.end;
192     }
193
194     void dump() const;
195     void print(raw_ostream &os) const;
196
197   private:
198     LiveRange(); // DO NOT IMPLEMENT
199   };
200
201   template <> struct isPodLike<LiveRange> { static const bool value = true; };
202
203   raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
204
205
206   inline bool operator<(SlotIndex V, const LiveRange &LR) {
207     return V < LR.start;
208   }
209
210   inline bool operator<(const LiveRange &LR, SlotIndex V) {
211     return LR.start < V;
212   }
213
214   /// LiveInterval - This class represents some number of live ranges for a
215   /// register or value.  This class also contains a bit of register allocator
216   /// state.
217   class LiveInterval {
218   public:
219
220     typedef SmallVector<LiveRange,4> Ranges;
221     typedef SmallVector<VNInfo*,4> VNInfoList;
222
223     unsigned reg;        // the register or stack slot of this interval
224                          // if the top bits is set, it represents a stack slot.
225     float weight;        // weight of this interval
226     Ranges ranges;       // the ranges in which this register is live
227     VNInfoList valnos;   // value#'s
228
229     struct InstrSlots {
230       enum {
231         LOAD  = 0,
232         USE   = 1,
233         DEF   = 2,
234         STORE = 3,
235         NUM   = 4
236       };
237
238     };
239
240     LiveInterval(unsigned Reg, float Weight, bool IsSS = false)
241       : reg(Reg), weight(Weight) {
242       if (IsSS)
243         reg = reg | (1U << (sizeof(unsigned)*CHAR_BIT-1));
244     }
245
246     typedef Ranges::iterator iterator;
247     iterator begin() { return ranges.begin(); }
248     iterator end()   { return ranges.end(); }
249
250     typedef Ranges::const_iterator const_iterator;
251     const_iterator begin() const { return ranges.begin(); }
252     const_iterator end() const  { return ranges.end(); }
253
254     typedef VNInfoList::iterator vni_iterator;
255     vni_iterator vni_begin() { return valnos.begin(); }
256     vni_iterator vni_end() { return valnos.end(); }
257
258     typedef VNInfoList::const_iterator const_vni_iterator;
259     const_vni_iterator vni_begin() const { return valnos.begin(); }
260     const_vni_iterator vni_end() const { return valnos.end(); }
261
262     /// advanceTo - Advance the specified iterator to point to the LiveRange
263     /// containing the specified position, or end() if the position is past the
264     /// end of the interval.  If no LiveRange contains this position, but the
265     /// position is in a hole, this method returns an iterator pointing to the
266     /// LiveRange immediately after the hole.
267     iterator advanceTo(iterator I, SlotIndex Pos) {
268       if (Pos >= endIndex())
269         return end();
270       while (I->end <= Pos) ++I;
271       return I;
272     }
273
274     /// find - Return an iterator pointing to the first range that ends after
275     /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
276     /// when searching large intervals.
277     ///
278     /// If Pos is contained in a LiveRange, that range is returned.
279     /// If Pos is in a hole, the following LiveRange is returned.
280     /// If Pos is beyond endIndex, end() is returned.
281     iterator find(SlotIndex Pos);
282
283     const_iterator find(SlotIndex Pos) const {
284       return const_cast<LiveInterval*>(this)->find(Pos);
285     }
286
287     void clear() {
288       valnos.clear();
289       ranges.clear();
290     }
291
292     /// isStackSlot - Return true if this is a stack slot interval.
293     ///
294     bool isStackSlot() const {
295       return reg & (1U << (sizeof(unsigned)*CHAR_BIT-1));
296     }
297
298     /// getStackSlotIndex - Return stack slot index if this is a stack slot
299     /// interval.
300     int getStackSlotIndex() const {
301       assert(isStackSlot() && "Interval is not a stack slot interval!");
302       return reg & ~(1U << (sizeof(unsigned)*CHAR_BIT-1));
303     }
304
305     bool hasAtLeastOneValue() const { return !valnos.empty(); }
306
307     bool containsOneValue() const { return valnos.size() == 1; }
308
309     unsigned getNumValNums() const { return (unsigned)valnos.size(); }
310
311     /// getValNumInfo - Returns pointer to the specified val#.
312     ///
313     inline VNInfo *getValNumInfo(unsigned ValNo) {
314       return valnos[ValNo];
315     }
316     inline const VNInfo *getValNumInfo(unsigned ValNo) const {
317       return valnos[ValNo];
318     }
319
320     /// getNextValue - Create a new value number and return it.  MIIdx specifies
321     /// the instruction that defines the value number.
322     VNInfo *getNextValue(SlotIndex def, MachineInstr *CopyMI,
323                        bool isDefAccurate, VNInfo::Allocator &VNInfoAllocator) {
324       VNInfo *VNI =
325         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def, CopyMI);
326       VNI->setIsDefAccurate(isDefAccurate);
327       valnos.push_back(VNI);
328       return VNI;
329     }
330
331     /// Create a copy of the given value. The new value will be identical except
332     /// for the Value number.
333     VNInfo *createValueCopy(const VNInfo *orig,
334                             VNInfo::Allocator &VNInfoAllocator) {
335       VNInfo *VNI =
336         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
337       valnos.push_back(VNI);
338       return VNI;
339     }
340
341     /// RenumberValues - Renumber all values in order of appearance and remove
342     /// unused values.
343     /// Recalculate phi-kill flags in case any phi-def values were removed.
344     void RenumberValues(LiveIntervals &lis);
345
346     /// isOnlyLROfValNo - Return true if the specified live range is the only
347     /// one defined by the its val#.
348     bool isOnlyLROfValNo(const LiveRange *LR) {
349       for (const_iterator I = begin(), E = end(); I != E; ++I) {
350         const LiveRange *Tmp = I;
351         if (Tmp != LR && Tmp->valno == LR->valno)
352           return false;
353       }
354       return true;
355     }
356
357     /// MergeValueNumberInto - This method is called when two value nubmers
358     /// are found to be equivalent.  This eliminates V1, replacing all
359     /// LiveRanges with the V1 value number with the V2 value number.  This can
360     /// cause merging of V1/V2 values numbers and compaction of the value space.
361     VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
362
363     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
364     /// in RHS into this live interval as the specified value number.
365     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
366     /// current interval, it will replace the value numbers of the overlaped
367     /// live ranges with the specified value number.
368     void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
369
370     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
371     /// in RHS into this live interval as the specified value number.
372     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
373     /// current interval, but only if the overlapping LiveRanges have the
374     /// specified value number.
375     void MergeValueInAsValue(const LiveInterval &RHS,
376                              const VNInfo *RHSValNo, VNInfo *LHSValNo);
377
378     /// Copy - Copy the specified live interval. This copies all the fields
379     /// except for the register of the interval.
380     void Copy(const LiveInterval &RHS, MachineRegisterInfo *MRI,
381               VNInfo::Allocator &VNInfoAllocator);
382
383     bool empty() const { return ranges.empty(); }
384
385     /// beginIndex - Return the lowest numbered slot covered by interval.
386     SlotIndex beginIndex() const {
387       assert(!empty() && "Call to beginIndex() on empty interval.");
388       return ranges.front().start;
389     }
390
391     /// endNumber - return the maximum point of the interval of the whole,
392     /// exclusive.
393     SlotIndex endIndex() const {
394       assert(!empty() && "Call to endIndex() on empty interval.");
395       return ranges.back().end;
396     }
397
398     bool expiredAt(SlotIndex index) const {
399       return index >= endIndex();
400     }
401
402     bool liveAt(SlotIndex index) const {
403       const_iterator r = find(index);
404       return r != end() && r->start <= index;
405     }
406
407     /// killedAt - Return true if a live range ends at index. Note that the kill
408     /// point is not contained in the half-open live range. It is usually the
409     /// getDefIndex() slot following its last use.
410     bool killedAt(SlotIndex index) const {
411       const_iterator r = find(index.getUseIndex());
412       return r != end() && r->end == index;
413     }
414
415     /// killedInRange - Return true if the interval has kills in [Start,End).
416     /// Note that the kill point is considered the end of a live range, so it is
417     /// not contained in the live range. If a live range ends at End, it won't
418     /// be counted as a kill by this method.
419     bool killedInRange(SlotIndex Start, SlotIndex End) const;
420
421     /// getLiveRangeContaining - Return the live range that contains the
422     /// specified index, or null if there is none.
423     const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
424       const_iterator I = FindLiveRangeContaining(Idx);
425       return I == end() ? 0 : &*I;
426     }
427
428     /// getLiveRangeContaining - Return the live range that contains the
429     /// specified index, or null if there is none.
430     LiveRange *getLiveRangeContaining(SlotIndex Idx) {
431       iterator I = FindLiveRangeContaining(Idx);
432       return I == end() ? 0 : &*I;
433     }
434
435     /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
436     VNInfo *getVNInfoAt(SlotIndex Idx) const {
437       const_iterator I = FindLiveRangeContaining(Idx);
438       return I == end() ? 0 : I->valno;
439     }
440
441     /// FindLiveRangeContaining - Return an iterator to the live range that
442     /// contains the specified index, or end() if there is none.
443     iterator FindLiveRangeContaining(SlotIndex Idx) {
444       iterator I = find(Idx);
445       return I != end() && I->start <= Idx ? I : end();
446     }
447
448     const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
449       const_iterator I = find(Idx);
450       return I != end() && I->start <= Idx ? I : end();
451     }
452
453     /// findDefinedVNInfo - Find the by the specified
454     /// index (register interval) or defined
455     VNInfo *findDefinedVNInfoForRegInt(SlotIndex Idx) const;
456
457
458     /// overlaps - Return true if the intersection of the two live intervals is
459     /// not empty.
460     bool overlaps(const LiveInterval& other) const {
461       if (other.empty())
462         return false;
463       return overlapsFrom(other, other.begin());
464     }
465
466     /// overlaps - Return true if the live interval overlaps a range specified
467     /// by [Start, End).
468     bool overlaps(SlotIndex Start, SlotIndex End) const;
469
470     /// overlapsFrom - Return true if the intersection of the two live intervals
471     /// is not empty.  The specified iterator is a hint that we can begin
472     /// scanning the Other interval starting at I.
473     bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
474
475     /// addRange - Add the specified LiveRange to this interval, merging
476     /// intervals as appropriate.  This returns an iterator to the inserted live
477     /// range (which may have grown since it was inserted.
478     void addRange(LiveRange LR) {
479       addRangeFrom(LR, ranges.begin());
480     }
481
482     /// join - Join two live intervals (this, and other) together.  This applies
483     /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
484     /// the intervals are not joinable, this aborts.
485     void join(LiveInterval &Other,
486               const int *ValNoAssignments,
487               const int *RHSValNoAssignments,
488               SmallVector<VNInfo*, 16> &NewVNInfo,
489               MachineRegisterInfo *MRI);
490
491     /// isInOneLiveRange - Return true if the range specified is entirely in the
492     /// a single LiveRange of the live interval.
493     bool isInOneLiveRange(SlotIndex Start, SlotIndex End) const {
494       const_iterator r = find(Start);
495       return r != end() && r->containsRange(Start, End);
496     }
497
498     /// removeRange - Remove the specified range from this interval.  Note that
499     /// the range must be a single LiveRange in its entirety.
500     void removeRange(SlotIndex Start, SlotIndex End,
501                      bool RemoveDeadValNo = false);
502
503     void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
504       removeRange(LR.start, LR.end, RemoveDeadValNo);
505     }
506
507     /// removeValNo - Remove all the ranges defined by the specified value#.
508     /// Also remove the value# from value# list.
509     void removeValNo(VNInfo *ValNo);
510
511     /// getSize - Returns the sum of sizes of all the LiveRange's.
512     ///
513     unsigned getSize() const;
514
515     /// Returns true if the live interval is zero length, i.e. no live ranges
516     /// span instructions. It doesn't pay to spill such an interval.
517     bool isZeroLength() const {
518       for (const_iterator i = begin(), e = end(); i != e; ++i)
519         if (i->end.getPrevIndex() > i->start)
520           return false;
521       return true;
522     }
523
524     /// isSpillable - Can this interval be spilled?
525     bool isSpillable() const {
526       return weight != HUGE_VALF;
527     }
528
529     /// markNotSpillable - Mark interval as not spillable
530     void markNotSpillable() {
531       weight = HUGE_VALF;
532     }
533
534     /// ComputeJoinedWeight - Set the weight of a live interval after
535     /// Other has been merged into it.
536     void ComputeJoinedWeight(const LiveInterval &Other);
537
538     bool operator<(const LiveInterval& other) const {
539       const SlotIndex &thisIndex = beginIndex();
540       const SlotIndex &otherIndex = other.beginIndex();
541       return (thisIndex < otherIndex ||
542               (thisIndex == otherIndex && reg < other.reg));
543     }
544
545     void print(raw_ostream &OS, const TargetRegisterInfo *TRI = 0) const;
546     void dump() const;
547
548   private:
549
550     Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
551     void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
552     Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
553     void markValNoForDeletion(VNInfo *V);
554
555     LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
556
557   };
558
559   inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
560     LI.print(OS);
561     return OS;
562   }
563 }
564
565 #endif