48c7ab6807d0fcc583b0a0a17037bc805774ccdb
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Streams.h"
27 #include <iosfwd>
28 #include <vector>
29 #include <cassert>
30
31 namespace llvm {
32   class MachineInstr;
33   class MRegisterInfo;
34   struct LiveInterval;
35
36   /// VNInfo - If the value number definition is undefined (e.g. phi
37   /// merge point), it contains ~0u,x. If the value number is not in use, it
38   /// contains ~1u,x to indicate that the value # is not used. 
39   ///   def   - Instruction # of the definition.
40   ///   reg   - Source reg iff val# is defined by a copy; zero otherwise.
41   ///   hasPHIKill - One or more of the kills are PHI nodes.
42   ///   kills - Instruction # of the kills. If a kill is an odd #, it means
43   ///           the kill is a phi join point.
44   struct VNInfo {
45     unsigned id;
46     unsigned def;
47     unsigned reg;
48     bool hasPHIKill;
49     SmallVector<unsigned, 4> kills;
50     VNInfo() : id(~1U), def(~1U), reg(0), hasPHIKill(false) {}
51     VNInfo(unsigned i, unsigned d, unsigned r)
52       : id(i), def(d), reg(r), hasPHIKill(false) {}
53   };
54
55   /// LiveRange structure - This represents a simple register range in the
56   /// program, with an inclusive start point and an exclusive end point.
57   /// These ranges are rendered as [start,end).
58   struct LiveRange {
59     unsigned start;  // Start point of the interval (inclusive)
60     unsigned end;    // End point of the interval (exclusive)
61     VNInfo *valno;   // identifier for the value contained in this interval.
62
63     LiveRange(unsigned S, unsigned E, VNInfo *V) : start(S), end(E), valno(V) {
64       assert(S < E && "Cannot create empty or backwards range");
65     }
66
67     /// contains - Return true if the index is covered by this range.
68     ///
69     bool contains(unsigned I) const {
70       return start <= I && I < end;
71     }
72
73     bool operator<(const LiveRange &LR) const {
74       return start < LR.start || (start == LR.start && end < LR.end);
75     }
76     bool operator==(const LiveRange &LR) const {
77       return start == LR.start && end == LR.end;
78     }
79
80     void dump() const;
81     void print(std::ostream &os) const;
82     void print(std::ostream *os) const { if (os) print(*os); }
83
84   private:
85     LiveRange(); // DO NOT IMPLEMENT
86   };
87
88   std::ostream& operator<<(std::ostream& os, const LiveRange &LR);
89
90
91   inline bool operator<(unsigned V, const LiveRange &LR) {
92     return V < LR.start;
93   }
94
95   inline bool operator<(const LiveRange &LR, unsigned V) {
96     return LR.start < V;
97   }
98
99   /// LiveInterval - This class represents some number of live ranges for a
100   /// register or value.  This class also contains a bit of register allocator
101   /// state.
102   struct LiveInterval {
103     typedef SmallVector<LiveRange,4> Ranges;
104     typedef SmallVector<VNInfo*,4> VNInfoList;
105
106     unsigned reg;        // the register of this interval
107     unsigned preference; // preferred register to allocate for this interval
108     float weight;        // weight of this interval
109     Ranges ranges;       // the ranges in which this register is live
110     VNInfoList valnos;   // value#'s
111
112   public:
113     LiveInterval(unsigned Reg, float Weight)
114       : reg(Reg), preference(0), weight(Weight) {
115     }
116
117     typedef Ranges::iterator iterator;
118     iterator begin() { return ranges.begin(); }
119     iterator end()   { return ranges.end(); }
120
121     typedef Ranges::const_iterator const_iterator;
122     const_iterator begin() const { return ranges.begin(); }
123     const_iterator end() const  { return ranges.end(); }
124
125     typedef VNInfoList::iterator vni_iterator;
126     vni_iterator vni_begin() { return valnos.begin(); }
127     vni_iterator vni_end() { return valnos.end(); }
128
129     typedef VNInfoList::const_iterator const_vni_iterator;
130     const_vni_iterator vni_begin() const { return valnos.begin(); }
131     const_vni_iterator vni_end() const { return valnos.end(); }
132
133     /// advanceTo - Advance the specified iterator to point to the LiveRange
134     /// containing the specified position, or end() if the position is past the
135     /// end of the interval.  If no LiveRange contains this position, but the
136     /// position is in a hole, this method returns an iterator pointing the the
137     /// LiveRange immediately after the hole.
138     iterator advanceTo(iterator I, unsigned Pos) {
139       if (Pos >= endNumber())
140         return end();
141       while (I->end <= Pos) ++I;
142       return I;
143     }
144
145     bool containsOneValue() const { return valnos.size() == 1; }
146
147     unsigned getNumValNums() const { return valnos.size(); }
148     
149     /// getValNumInfo - Returns pointer to the specified val#.
150     ///
151     inline VNInfo *getValNumInfo(unsigned ValNo) {
152       return valnos[ValNo];
153     }
154     inline const VNInfo *getValNumInfo(unsigned ValNo) const {
155       return valnos[ValNo];
156     }
157     
158     /// copyValNumInfo - Copy the value number info for one value number to
159     /// another.
160     void copyValNumInfo(VNInfo *DstValNo, const VNInfo *SrcValNo) {
161       DstValNo->def = SrcValNo->def;
162       DstValNo->reg = SrcValNo->reg;
163       DstValNo->hasPHIKill = SrcValNo->hasPHIKill;
164       DstValNo->kills = SrcValNo->kills;
165     }
166
167     /// getNextValue - Create a new value number and return it.  MIIdx specifies
168     /// the instruction that defines the value number.
169     VNInfo *getNextValue(unsigned MIIdx, unsigned SrcReg,
170                          BumpPtrAllocator &VNInfoAllocator) {
171 #ifdef __GNUC__
172       unsigned Alignment = __alignof__(VNInfo);
173 #else
174       // FIXME: ugly.
175       unsigned Alignment = 8;
176 #endif
177       VNInfo *VNI= static_cast<VNInfo*>(VNInfoAllocator.Allocate(sizeof(VNInfo),
178                                                                  Alignment));
179       new (VNI) VNInfo(valnos.size(), MIIdx, SrcReg);
180       valnos.push_back(VNI);
181       return VNI;
182     }
183
184     /// addKillForValNum - Add a kill instruction index to the specified value
185     /// number.
186     static void addKill(VNInfo *VNI, unsigned KillIdx) {
187       SmallVector<unsigned, 4> &kills = VNI->kills;
188       if (kills.empty()) {
189         kills.push_back(KillIdx);
190       } else {
191         SmallVector<unsigned, 4>::iterator
192           I = std::lower_bound(kills.begin(), kills.end(), KillIdx);
193         kills.insert(I, KillIdx);
194       }
195     }
196
197     /// addKills - Add a number of kills into the VNInfo kill vector. If this
198     /// interval is live at a kill point, then the kill is not added.
199     void addKills(VNInfo *VNI, const SmallVector<unsigned, 4> &kills) {
200       for (unsigned i = 0, e = kills.size(); i != e; ++i) {
201         unsigned KillIdx = kills[i];
202         if (!liveAt(KillIdx)) {
203           SmallVector<unsigned, 4>::iterator
204             I = std::lower_bound(VNI->kills.begin(), VNI->kills.end(), KillIdx);
205           VNI->kills.insert(I, KillIdx);
206         }
207       }
208     }
209
210     /// removeKill - Remove the specified kill from the list of kills of
211     /// the specified val#.
212     static bool removeKill(VNInfo *VNI, unsigned KillIdx) {
213       SmallVector<unsigned, 4> &kills = VNI->kills;
214       SmallVector<unsigned, 4>::iterator
215         I = std::lower_bound(kills.begin(), kills.end(), KillIdx);
216       if (I != kills.end() && *I == KillIdx) {
217         kills.erase(I);
218         return true;
219       }
220       return false;
221     }
222
223     /// removeKills - Remove all the kills in specified range
224     /// [Start, End] of the specified val#.
225     void removeKills(VNInfo *VNI, unsigned Start, unsigned End) {
226       SmallVector<unsigned, 4> &kills = VNI->kills;
227       SmallVector<unsigned, 4>::iterator
228         I = std::lower_bound(kills.begin(), kills.end(), Start);
229       SmallVector<unsigned, 4>::iterator
230         E = std::upper_bound(kills.begin(), kills.end(), End);
231       kills.erase(I, E);
232     }
233     
234     /// MergeValueNumberInto - This method is called when two value nubmers
235     /// are found to be equivalent.  This eliminates V1, replacing all
236     /// LiveRanges with the V1 value number with the V2 value number.  This can
237     /// cause merging of V1/V2 values numbers and compaction of the value space.
238     void MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
239
240     /// MergeInClobberRanges - For any live ranges that are not defined in the
241     /// current interval, but are defined in the Clobbers interval, mark them
242     /// used with an unknown definition value. Caller must pass in reference to
243     /// VNInfoAllocator since it will create a new val#.
244     void MergeInClobberRanges(const LiveInterval &Clobbers,
245                               BumpPtrAllocator &VNInfoAllocator);
246
247     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
248     /// in RHS into this live interval as the specified value number.
249     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
250     /// current interval, it will replace the value numbers of the overlaped
251     /// live ranges with the specified value number.
252     void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
253
254     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
255     /// in RHS into this live interval as the specified value number.
256     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
257     /// current interval, but only if the overlapping LiveRanges have the
258     /// specified value number.
259     void MergeValueInAsValue(const LiveInterval &RHS,
260                              const VNInfo *RHSValNo, VNInfo *LHSValNo);
261
262     /// Copy - Copy the specified live interval. This copies all the fields
263     /// except for the register of the interval.
264     void Copy(const LiveInterval &RHS, BumpPtrAllocator &VNInfoAllocator);
265     
266     bool empty() const { return ranges.empty(); }
267
268     /// beginNumber - Return the lowest numbered slot covered by interval.
269     unsigned beginNumber() const {
270       assert(!empty() && "empty interval for register");
271       return ranges.front().start;
272     }
273
274     /// endNumber - return the maximum point of the interval of the whole,
275     /// exclusive.
276     unsigned endNumber() const {
277       assert(!empty() && "empty interval for register");
278       return ranges.back().end;
279     }
280
281     bool expiredAt(unsigned index) const {
282       return index >= endNumber();
283     }
284
285     bool liveAt(unsigned index) const;
286
287     /// getLiveRangeContaining - Return the live range that contains the
288     /// specified index, or null if there is none.
289     const LiveRange *getLiveRangeContaining(unsigned Idx) const {
290       const_iterator I = FindLiveRangeContaining(Idx);
291       return I == end() ? 0 : &*I;
292     }
293
294     /// FindLiveRangeContaining - Return an iterator to the live range that
295     /// contains the specified index, or end() if there is none.
296     const_iterator FindLiveRangeContaining(unsigned Idx) const;
297
298     /// FindLiveRangeContaining - Return an iterator to the live range that
299     /// contains the specified index, or end() if there is none.
300     iterator FindLiveRangeContaining(unsigned Idx);
301     
302     /// getOverlapingRanges - Given another live interval which is defined as a
303     /// copy from this one, return a list of all of the live ranges where the
304     /// two overlap and have different value numbers.
305     void getOverlapingRanges(const LiveInterval &Other, unsigned CopyIdx,
306                              std::vector<LiveRange*> &Ranges);
307
308     /// overlaps - Return true if the intersection of the two live intervals is
309     /// not empty.
310     bool overlaps(const LiveInterval& other) const {
311       return overlapsFrom(other, other.begin());
312     }
313
314     /// overlapsFrom - Return true if the intersection of the two live intervals
315     /// is not empty.  The specified iterator is a hint that we can begin
316     /// scanning the Other interval starting at I.
317     bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
318
319     /// addRange - Add the specified LiveRange to this interval, merging
320     /// intervals as appropriate.  This returns an iterator to the inserted live
321     /// range (which may have grown since it was inserted.
322     void addRange(LiveRange LR) {
323       addRangeFrom(LR, ranges.begin());
324     }
325
326     /// join - Join two live intervals (this, and other) together.  This applies
327     /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
328     /// the intervals are not joinable, this aborts.
329     void join(LiveInterval &Other, const int *ValNoAssignments,
330               const int *RHSValNoAssignments,
331               SmallVector<VNInfo*, 16> &NewVNInfo);
332
333     /// removeRange - Remove the specified range from this interval.  Note that
334     /// the range must already be in this interval in its entirety.
335     void removeRange(unsigned Start, unsigned End);
336
337     void removeRange(LiveRange LR) {
338       removeRange(LR.start, LR.end);
339     }
340
341     /// getSize - Returns the sum of sizes of all the LiveRange's.
342     ///
343     unsigned getSize() const;
344
345     bool operator<(const LiveInterval& other) const {
346       return beginNumber() < other.beginNumber();
347     }
348
349     void print(std::ostream &OS, const MRegisterInfo *MRI = 0) const;
350     void print(std::ostream *OS, const MRegisterInfo *MRI = 0) const {
351       if (OS) print(*OS, MRI);
352     }
353     void dump() const;
354
355   private:
356     Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
357     void extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd);
358     Ranges::iterator extendIntervalStartTo(Ranges::iterator I, unsigned NewStr);
359     LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
360   };
361
362   inline std::ostream &operator<<(std::ostream &OS, const LiveInterval &LI) {
363     LI.print(OS);
364     return OS;
365   }
366 }
367
368 #endif