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