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