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