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