8e99ee7e29f2e822ae6bcf616cc5921337ba40e3
[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
29 namespace llvm {
30   class MachineInstr;
31   class TargetRegisterInfo;
32   struct LiveInterval;
33
34   /// VNInfo - If the value number definition is undefined (e.g. phi
35   /// merge point), it contains ~0u,x. If the value number is not in use, it
36   /// contains ~1u,x to indicate that the value # is not used. 
37   ///   def   - Instruction # of the definition.
38   ///         - or reg # of the definition if it's a stack slot liveinterval.
39   ///   copy  - Copy iff val# is defined by a copy; zero otherwise.
40   ///   hasPHIKill - One or more of the kills are PHI nodes.
41   ///   redefByEC - Re-defined by early clobber somewhere during the live range.
42   ///   kills - Instruction # of the kills.
43   struct VNInfo {
44     unsigned id;
45     unsigned def;
46     MachineInstr *copy;
47     bool hasPHIKill : 1;
48     bool redefByEC : 1;
49     SmallVector<unsigned, 4> kills;
50     VNInfo()
51       : id(~1U), def(~1U), copy(0), hasPHIKill(false), redefByEC(false) {}
52     VNInfo(unsigned i, unsigned d, MachineInstr *c)
53       : id(i), def(d), copy(c), hasPHIKill(false), redefByEC(false) {}
54   };
55
56   /// LiveRange structure - This represents a simple register range in the
57   /// program, with an inclusive start point and an exclusive end point.
58   /// These ranges are rendered as [start,end).
59   struct LiveRange {
60     unsigned start;  // Start point of the interval (inclusive)
61     unsigned end;    // End point of the interval (exclusive)
62     VNInfo *valno;   // identifier for the value contained in this interval.
63
64     LiveRange(unsigned S, unsigned E, VNInfo *V) : start(S), end(E), valno(V) {
65       assert(S < E && "Cannot create empty or backwards range");
66     }
67
68     /// contains - Return true if the index is covered by this range.
69     ///
70     bool contains(unsigned I) const {
71       return start <= I && I < end;
72     }
73
74     bool operator<(const LiveRange &LR) const {
75       return start < LR.start || (start == LR.start && end < LR.end);
76     }
77     bool operator==(const LiveRange &LR) const {
78       return start == LR.start && end == LR.end;
79     }
80
81     void dump() const;
82     void print(std::ostream &os) const;
83     void print(std::ostream *os) const { if (os) print(*os); }
84
85   private:
86     LiveRange(); // DO NOT IMPLEMENT
87   };
88
89   std::ostream& operator<<(std::ostream& os, const LiveRange &LR);
90
91
92   inline bool operator<(unsigned V, const LiveRange &LR) {
93     return V < LR.start;
94   }
95
96   inline bool operator<(const LiveRange &LR, unsigned V) {
97     return LR.start < V;
98   }
99
100   /// LiveInterval - This class represents some number of live ranges for a
101   /// register or value.  This class also contains a bit of register allocator
102   /// state.
103   struct LiveInterval {
104     typedef SmallVector<LiveRange,4> Ranges;
105     typedef SmallVector<VNInfo*,4> VNInfoList;
106
107     unsigned reg;        // the register or stack slot of this interval
108                          // if the top bits is set, it represents a stack slot.
109     float weight;        // weight of this interval
110     unsigned short preference; // preferred register for this interval
111     Ranges ranges;       // the ranges in which this register is live
112     VNInfoList valnos;   // value#'s
113
114   public:
115     LiveInterval(unsigned Reg, float Weight, bool IsSS = false)
116       : reg(Reg), weight(Weight), preference(0)  {
117       if (IsSS)
118         reg = reg | (1U << (sizeof(unsigned)*8-1));
119     }
120
121     typedef Ranges::iterator iterator;
122     iterator begin() { return ranges.begin(); }
123     iterator end()   { return ranges.end(); }
124
125     typedef Ranges::const_iterator const_iterator;
126     const_iterator begin() const { return ranges.begin(); }
127     const_iterator end() const  { return ranges.end(); }
128
129     typedef VNInfoList::iterator vni_iterator;
130     vni_iterator vni_begin() { return valnos.begin(); }
131     vni_iterator vni_end() { return valnos.end(); }
132
133     typedef VNInfoList::const_iterator const_vni_iterator;
134     const_vni_iterator vni_begin() const { return valnos.begin(); }
135     const_vni_iterator vni_end() const { return valnos.end(); }
136
137     /// advanceTo - Advance the specified iterator to point to the LiveRange
138     /// containing the specified position, or end() if the position is past the
139     /// end of the interval.  If no LiveRange contains this position, but the
140     /// position is in a hole, this method returns an iterator pointing the the
141     /// LiveRange immediately after the hole.
142     iterator advanceTo(iterator I, unsigned Pos) {
143       if (Pos >= endNumber())
144         return end();
145       while (I->end <= Pos) ++I;
146       return I;
147     }
148     
149     void clear() {
150       while (!valnos.empty()) {
151         VNInfo *VNI = valnos.back();
152         valnos.pop_back();
153         VNI->~VNInfo();
154       }
155       
156       ranges.clear();
157     }
158
159     /// isStackSlot - Return true if this is a stack slot interval.
160     ///
161     bool isStackSlot() const {
162       return reg & (1U << (sizeof(unsigned)*8-1));
163     }
164
165     /// getStackSlotIndex - Return stack slot index if this is a stack slot
166     /// interval.
167     int getStackSlotIndex() const {
168       assert(isStackSlot() && "Interval is not a stack slot interval!");
169       return reg & ~(1U << (sizeof(unsigned)*8-1));
170     }
171
172     bool hasAtLeastOneValue() const { return !valnos.empty(); }
173
174     bool containsOneValue() const { return valnos.size() == 1; }
175
176     unsigned getNumValNums() const { return (unsigned)valnos.size(); }
177     
178     /// getValNumInfo - Returns pointer to the specified val#.
179     ///
180     inline VNInfo *getValNumInfo(unsigned ValNo) {
181       return valnos[ValNo];
182     }
183     inline const VNInfo *getValNumInfo(unsigned ValNo) const {
184       return valnos[ValNo];
185     }
186     
187     /// copyValNumInfo - Copy the value number info for one value number to
188     /// another.
189     void copyValNumInfo(VNInfo *DstValNo, const VNInfo *SrcValNo) {
190       DstValNo->def = SrcValNo->def;
191       DstValNo->copy = SrcValNo->copy;
192       DstValNo->hasPHIKill = SrcValNo->hasPHIKill;
193       DstValNo->redefByEC = SrcValNo->redefByEC;
194       DstValNo->kills = SrcValNo->kills;
195     }
196
197     /// getNextValue - Create a new value number and return it.  MIIdx specifies
198     /// the instruction that defines the value number.
199     VNInfo *getNextValue(unsigned MIIdx, MachineInstr *CopyMI,
200                          BumpPtrAllocator &VNInfoAllocator) {
201 #ifdef __GNUC__
202       unsigned Alignment = (unsigned)__alignof__(VNInfo);
203 #else
204       // FIXME: ugly.
205       unsigned Alignment = 8;
206 #endif
207       VNInfo *VNI =
208         static_cast<VNInfo*>(VNInfoAllocator.Allocate((unsigned)sizeof(VNInfo),
209                                                       Alignment));
210       new (VNI) VNInfo((unsigned)valnos.size(), MIIdx, CopyMI);
211       valnos.push_back(VNI);
212       return VNI;
213     }
214
215     /// getUnknownValNo - Find a value# for unknown values, if there isn't one
216     /// create a new one.
217     VNInfo *getUnknownValNo(BumpPtrAllocator &VNInfoAllocator);
218
219     /// addKill - Add a kill instruction index to the specified value
220     /// number.
221     static void addKill(VNInfo *VNI, unsigned KillIdx) {
222       SmallVector<unsigned, 4> &kills = VNI->kills;
223       if (kills.empty()) {
224         kills.push_back(KillIdx);
225       } else {
226         SmallVector<unsigned, 4>::iterator
227           I = std::lower_bound(kills.begin(), kills.end(), KillIdx);
228         kills.insert(I, KillIdx);
229       }
230     }
231
232     /// addKills - Add a number of kills into the VNInfo kill vector. If this
233     /// interval is live at a kill point, then the kill is not added.
234     void addKills(VNInfo *VNI, const SmallVector<unsigned, 4> &kills) {
235       for (unsigned i = 0, e = static_cast<unsigned>(kills.size());
236            i != e; ++i) {
237         unsigned KillIdx = kills[i];
238         if (!liveBeforeAndAt(KillIdx)) {
239           SmallVector<unsigned, 4>::iterator
240             I = std::lower_bound(VNI->kills.begin(), VNI->kills.end(), KillIdx);
241           VNI->kills.insert(I, KillIdx);
242         }
243       }
244     }
245
246     /// removeKill - Remove the specified kill from the list of kills of
247     /// the specified val#.
248     static bool removeKill(VNInfo *VNI, unsigned KillIdx) {
249       SmallVector<unsigned, 4> &kills = VNI->kills;
250       SmallVector<unsigned, 4>::iterator
251         I = std::lower_bound(kills.begin(), kills.end(), KillIdx);
252       if (I != kills.end() && *I == KillIdx) {
253         kills.erase(I);
254         return true;
255       }
256       return false;
257     }
258
259     /// removeKills - Remove all the kills in specified range
260     /// [Start, End] of the specified val#.
261     static void removeKills(VNInfo *VNI, unsigned Start, unsigned End) {
262       SmallVector<unsigned, 4> &kills = VNI->kills;
263       SmallVector<unsigned, 4>::iterator
264         I = std::lower_bound(kills.begin(), kills.end(), Start);
265       SmallVector<unsigned, 4>::iterator
266         E = std::upper_bound(kills.begin(), kills.end(), End);
267       kills.erase(I, E);
268     }
269
270     /// isKill - Return true if the specified index is a kill of the
271     /// specified val#.
272     static bool isKill(const VNInfo *VNI, unsigned KillIdx) {
273       const SmallVector<unsigned, 4> &kills = VNI->kills;
274       SmallVector<unsigned, 4>::const_iterator
275         I = std::lower_bound(kills.begin(), kills.end(), KillIdx);
276       return I != kills.end() && *I == KillIdx;
277     }
278
279     /// isOnlyLROfValNo - Return true if the specified live range is the only
280     /// one defined by the its val#.
281     bool isOnlyLROfValNo( const LiveRange *LR) {
282       for (const_iterator I = begin(), E = end(); I != E; ++I) {
283         const LiveRange *Tmp = I;
284         if (Tmp != LR && Tmp->valno == LR->valno)
285           return false;
286       }
287       return true;
288     }
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     /// MergeInClobberRanges - For any live ranges that are not defined in the
297     /// current interval, but are defined in the Clobbers interval, mark them
298     /// used with an unknown definition value. Caller must pass in reference to
299     /// VNInfoAllocator since it will create a new val#.
300     void MergeInClobberRanges(const LiveInterval &Clobbers,
301                               BumpPtrAllocator &VNInfoAllocator);
302
303     /// MergeInClobberRange - Same as MergeInClobberRanges except it merge in a
304     /// single LiveRange only.
305     void MergeInClobberRange(unsigned Start, unsigned End,
306                              BumpPtrAllocator &VNInfoAllocator);
307
308     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
309     /// in RHS into this live interval as the specified value number.
310     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
311     /// current interval, it will replace the value numbers of the overlaped
312     /// live ranges with the specified value number.
313     void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
314
315     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
316     /// in RHS into this live interval as the specified value number.
317     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
318     /// current interval, but only if the overlapping LiveRanges have the
319     /// specified value number.
320     void MergeValueInAsValue(const LiveInterval &RHS,
321                              const VNInfo *RHSValNo, VNInfo *LHSValNo);
322
323     /// Copy - Copy the specified live interval. This copies all the fields
324     /// except for the register of the interval.
325     void Copy(const LiveInterval &RHS, BumpPtrAllocator &VNInfoAllocator);
326     
327     bool empty() const { return ranges.empty(); }
328
329     /// beginNumber - Return the lowest numbered slot covered by interval.
330     unsigned beginNumber() const {
331       if (empty())
332         return 0;
333       return ranges.front().start;
334     }
335
336     /// endNumber - return the maximum point of the interval of the whole,
337     /// exclusive.
338     unsigned endNumber() const {
339       if (empty())
340         return 0;
341       return ranges.back().end;
342     }
343
344     bool expiredAt(unsigned index) const {
345       return index >= endNumber();
346     }
347
348     bool liveAt(unsigned index) const;
349
350     // liveBeforeAndAt - Check if the interval is live at the index and the
351     // index just before it. If index is liveAt, check if it starts a new live
352     // range.If it does, then check if the previous live range ends at index-1.
353     bool liveBeforeAndAt(unsigned index) const;
354
355     /// getLiveRangeContaining - Return the live range that contains the
356     /// specified index, or null if there is none.
357     const LiveRange *getLiveRangeContaining(unsigned Idx) const {
358       const_iterator I = FindLiveRangeContaining(Idx);
359       return I == end() ? 0 : &*I;
360     }
361
362     /// FindLiveRangeContaining - Return an iterator to the live range that
363     /// contains the specified index, or end() if there is none.
364     const_iterator FindLiveRangeContaining(unsigned Idx) const;
365
366     /// FindLiveRangeContaining - Return an iterator to the live range that
367     /// contains the specified index, or end() if there is none.
368     iterator FindLiveRangeContaining(unsigned Idx);
369
370     /// findDefinedVNInfo - Find the VNInfo that's defined at the specified
371     /// index (register interval) or defined by the specified register (stack
372     /// inteval).
373     VNInfo *findDefinedVNInfo(unsigned DefIdxOrReg) const;
374     
375     /// overlaps - Return true if the intersection of the two live intervals is
376     /// not empty.
377     bool overlaps(const LiveInterval& other) const {
378       return overlapsFrom(other, other.begin());
379     }
380
381     /// overlapsFrom - Return true if the intersection of the two live intervals
382     /// is not empty.  The specified iterator is a hint that we can begin
383     /// scanning the Other interval starting at I.
384     bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
385
386     /// addRange - Add the specified LiveRange to this interval, merging
387     /// intervals as appropriate.  This returns an iterator to the inserted live
388     /// range (which may have grown since it was inserted.
389     void addRange(LiveRange LR) {
390       addRangeFrom(LR, ranges.begin());
391     }
392
393     /// join - Join two live intervals (this, and other) together.  This applies
394     /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
395     /// the intervals are not joinable, this aborts.
396     void join(LiveInterval &Other, const int *ValNoAssignments,
397               const int *RHSValNoAssignments,
398               SmallVector<VNInfo*, 16> &NewVNInfo);
399
400     /// isInOneLiveRange - Return true if the range specified is entirely in the
401     /// a single LiveRange of the live interval.
402     bool isInOneLiveRange(unsigned Start, unsigned End);
403
404     /// removeRange - Remove the specified range from this interval.  Note that
405     /// the range must be a single LiveRange in its entirety.
406     void removeRange(unsigned Start, unsigned End, bool RemoveDeadValNo = false);
407
408     void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
409       removeRange(LR.start, LR.end, RemoveDeadValNo);
410     }
411
412     /// removeValNo - Remove all the ranges defined by the specified value#.
413     /// Also remove the value# from value# list.
414     void removeValNo(VNInfo *ValNo);
415
416     /// getSize - Returns the sum of sizes of all the LiveRange's.
417     ///
418     unsigned getSize() const;
419
420     bool operator<(const LiveInterval& other) const {
421       return beginNumber() < other.beginNumber();
422     }
423
424     void print(std::ostream &OS, const TargetRegisterInfo *TRI = 0) const;
425     void print(std::ostream *OS, const TargetRegisterInfo *TRI = 0) const {
426       if (OS) print(*OS, TRI);
427     }
428     void dump() const;
429
430   private:
431     Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
432     void extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd);
433     Ranges::iterator extendIntervalStartTo(Ranges::iterator I, unsigned NewStr);
434     LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
435   };
436
437   inline std::ostream &operator<<(std::ostream &OS, const LiveInterval &LI) {
438     LI.print(OS);
439     return OS;
440   }
441 }
442
443 #endif