694d2873c16d8a6d0f36af24d1be60d9cf2ae36f
[oota-llvm.git] / include / llvm / CodeGen / RegisterPressure.h
1 //===-- RegisterPressure.h - Dynamic Register Pressure -*- 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 defines the RegisterPressure class which can be used to track
11 // MachineInstr level register pressure.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CODEGEN_REGISTERPRESSURE_H
16 #define LLVM_CODEGEN_REGISTERPRESSURE_H
17
18 #include "llvm/ADT/SparseSet.h"
19 #include "llvm/CodeGen/SlotIndexes.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21
22 namespace llvm {
23
24 class LiveIntervals;
25 class LiveInterval;
26 class RegisterClassInfo;
27 class MachineInstr;
28
29 /// Base class for register pressure results.
30 struct RegisterPressure {
31   /// Map of max reg pressure indexed by pressure set ID, not class ID.
32   std::vector<unsigned> MaxSetPressure;
33
34   /// List of live in virtual registers or physical register units.
35   SmallVector<unsigned,8> LiveInRegs;
36   SmallVector<unsigned,8> LiveOutRegs;
37
38   /// Increase register pressure for each pressure set impacted by this register
39   /// class. Normally called by RegPressureTracker, but may be called manually
40   /// to account for live through (global liveness).
41   ///
42   /// \param Reg is either a virtual register number or register unit number.
43   void increase(unsigned Reg, const TargetRegisterInfo *TRI,
44                 const MachineRegisterInfo *MRI);
45
46   /// Decrease register pressure for each pressure set impacted by this register
47   /// class. This is only useful to account for spilling or rematerialization.
48   ///
49   /// \param Reg is either a virtual register number or register unit number.
50   void decrease(unsigned Reg, const TargetRegisterInfo *TRI,
51                 const MachineRegisterInfo *MRI);
52
53   void dump(const TargetRegisterInfo *TRI) const;
54 };
55
56 /// RegisterPressure computed within a region of instructions delimited by
57 /// TopIdx and BottomIdx.  During pressure computation, the maximum pressure per
58 /// register pressure set is increased. Once pressure within a region is fully
59 /// computed, the live-in and live-out sets are recorded.
60 ///
61 /// This is preferable to RegionPressure when LiveIntervals are available,
62 /// because delimiting regions by SlotIndex is more robust and convenient than
63 /// holding block iterators. The block contents can change without invalidating
64 /// the pressure result.
65 struct IntervalPressure : RegisterPressure {
66   /// Record the boundary of the region being tracked.
67   SlotIndex TopIdx;
68   SlotIndex BottomIdx;
69
70   void reset();
71
72   void openTop(SlotIndex NextTop);
73
74   void openBottom(SlotIndex PrevBottom);
75 };
76
77 /// RegisterPressure computed within a region of instructions delimited by
78 /// TopPos and BottomPos. This is a less precise version of IntervalPressure for
79 /// use when LiveIntervals are unavailable.
80 struct RegionPressure : RegisterPressure {
81   /// Record the boundary of the region being tracked.
82   MachineBasicBlock::const_iterator TopPos;
83   MachineBasicBlock::const_iterator BottomPos;
84
85   void reset();
86
87   void openTop(MachineBasicBlock::const_iterator PrevTop);
88
89   void openBottom(MachineBasicBlock::const_iterator PrevBottom);
90 };
91
92 /// Capture a change in pressure for a single pressure set. UnitInc may be
93 /// expressed in terms of upward or downward pressure depending on the client
94 /// and will be dynamically adjusted for current liveness.
95 ///
96 /// Pressure increments are tiny, typically 1-2 units, and this is only for
97 /// heuristics, so we don't check UnitInc overflow. Instead, we may have a
98 /// higher level assert that pressure is consistent within a region. We also
99 /// effectively ignore dead defs which don't affect heuristics much.
100 class PressureChange {
101   uint16_t PSetID; // ID+1. 0=Invalid.
102   int16_t  UnitInc;
103 public:
104   PressureChange(): PSetID(0), UnitInc(0) {}
105   PressureChange(unsigned id): PSetID(id+1), UnitInc(0) {
106     assert(id < UINT16_MAX && "PSetID overflow.");
107   }
108
109   bool isValid() const { return PSetID > 0; }
110
111   unsigned getPSet() const {
112     assert(isValid() && "invalid PressureChange");
113     return PSetID - 1;
114   }
115   // If PSetID is invalid, return UINT16_MAX to give it lowest priority.
116   unsigned getPSetOrMax() const { return (PSetID - 1) & UINT16_MAX; }
117
118   int getUnitInc() const { return UnitInc; }
119
120   void setUnitInc(int Inc) { UnitInc = Inc; }
121
122   bool operator==(const PressureChange &RHS) const {
123     return PSetID == RHS.PSetID && UnitInc == RHS.UnitInc;
124   }
125 };
126
127 template <> struct isPodLike<PressureChange> {
128    static const bool value = true;
129 };
130
131 /// List of PressureChanges in order of increasing, unique PSetID.
132 ///
133 /// Use a small fixed number, because we can fit more PressureChanges in an
134 /// empty SmallVector than ever need to be tracked per register class. If more
135 /// PSets are affected, then we only track the most constrained.
136 class PressureDiff {
137   // The initial design was for MaxPSets=4, but that requires PSet partitions,
138   // which are not yet implemented. (PSet partitions are equivalent PSets given
139   // the register classes actually in use within the scheduling region.)
140   enum { MaxPSets = 16 };
141
142   PressureChange PressureChanges[MaxPSets];
143 public:
144   typedef PressureChange* iterator;
145   typedef const PressureChange* const_iterator;
146   iterator begin() { return &PressureChanges[0]; }
147   iterator end() { return &PressureChanges[MaxPSets]; }
148
149   void addPressureChange(unsigned RegUnit, bool IsDec,
150                          const MachineRegisterInfo *MRI);
151 };
152
153 /// Array of PressureDiffs.
154 class PressureDiffs {
155   PressureDiff *PDiffArray;
156   unsigned Size;
157   unsigned Max;
158 public:
159   PressureDiffs(): PDiffArray(0), Size(0), Max(0) {}
160   ~PressureDiffs() { free(PDiffArray); }
161
162   void init(unsigned N);
163
164   PressureDiff &operator[](unsigned Idx) {
165     assert(Idx < Size && "PressureDiff index out of bounds");
166     return PDiffArray[Idx];
167   }
168   const PressureDiff &operator[](unsigned Idx) const {
169     return const_cast<PressureDiffs*>(this)->operator[](Idx);
170   }
171 };
172
173 /// Store the effects of a change in pressure on things that MI scheduler cares
174 /// about.
175 ///
176 /// Excess records the value of the largest difference in register units beyond
177 /// the target's pressure limits across the affected pressure sets, where
178 /// largest is defined as the absolute value of the difference. Negative
179 /// ExcessUnits indicates a reduction in pressure that had already exceeded the
180 /// target's limits.
181 ///
182 /// CriticalMax records the largest increase in the tracker's max pressure that
183 /// exceeds the critical limit for some pressure set determined by the client.
184 ///
185 /// CurrentMax records the largest increase in the tracker's max pressure that
186 /// exceeds the current limit for some pressure set determined by the client.
187 struct RegPressureDelta {
188   PressureChange Excess;
189   PressureChange CriticalMax;
190   PressureChange CurrentMax;
191
192   RegPressureDelta() {}
193
194   bool operator==(const RegPressureDelta &RHS) const {
195     return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
196       && CurrentMax == RHS.CurrentMax;
197   }
198   bool operator!=(const RegPressureDelta &RHS) const {
199     return !operator==(RHS);
200   }
201 };
202
203 /// \brief A set of live virtual registers and physical register units.
204 ///
205 /// Virtual and physical register numbers require separate sparse sets, but most
206 /// of the RegisterPressureTracker handles them uniformly.
207 struct LiveRegSet {
208   SparseSet<unsigned> PhysRegs;
209   SparseSet<unsigned, VirtReg2IndexFunctor> VirtRegs;
210
211   bool contains(unsigned Reg) const {
212     if (TargetRegisterInfo::isVirtualRegister(Reg))
213       return VirtRegs.count(Reg);
214     return PhysRegs.count(Reg);
215   }
216
217   bool insert(unsigned Reg) {
218     if (TargetRegisterInfo::isVirtualRegister(Reg))
219       return VirtRegs.insert(Reg).second;
220     return PhysRegs.insert(Reg).second;
221   }
222
223   bool erase(unsigned Reg) {
224     if (TargetRegisterInfo::isVirtualRegister(Reg))
225       return VirtRegs.erase(Reg);
226     return PhysRegs.erase(Reg);
227   }
228 };
229
230 /// Track the current register pressure at some position in the instruction
231 /// stream, and remember the high water mark within the region traversed. This
232 /// does not automatically consider live-through ranges. The client may
233 /// independently adjust for global liveness.
234 ///
235 /// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
236 /// be tracked across a larger region by storing a RegisterPressure result at
237 /// each block boundary and explicitly adjusting pressure to account for block
238 /// live-in and live-out register sets.
239 ///
240 /// RegPressureTracker holds a reference to a RegisterPressure result that it
241 /// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
242 /// is invalid until it reaches the end of the block or closeRegion() is
243 /// explicitly called. Similarly, P.TopIdx is invalid during upward
244 /// tracking. Changing direction has the side effect of closing region, and
245 /// traversing past TopIdx or BottomIdx reopens it.
246 class RegPressureTracker {
247   const MachineFunction     *MF;
248   const TargetRegisterInfo  *TRI;
249   const RegisterClassInfo   *RCI;
250   const MachineRegisterInfo *MRI;
251   const LiveIntervals       *LIS;
252
253   /// We currently only allow pressure tracking within a block.
254   const MachineBasicBlock *MBB;
255
256   /// Track the max pressure within the region traversed so far.
257   RegisterPressure &P;
258
259   /// Run in two modes dependending on whether constructed with IntervalPressure
260   /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
261   bool RequireIntervals;
262
263   /// True if UntiedDefs will be populated.
264   bool TrackUntiedDefs;
265
266   /// Register pressure corresponds to liveness before this instruction
267   /// iterator. It may point to the end of the block or a DebugValue rather than
268   /// an instruction.
269   MachineBasicBlock::const_iterator CurrPos;
270
271   /// Pressure map indexed by pressure set ID, not class ID.
272   std::vector<unsigned> CurrSetPressure;
273
274   /// Set of live registers.
275   LiveRegSet LiveRegs;
276
277   /// Set of vreg defs that start a live range.
278   SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
279   /// Live-through pressure.
280   std::vector<unsigned> LiveThruPressure;
281
282 public:
283   RegPressureTracker(IntervalPressure &rp) :
284     MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(true),
285     TrackUntiedDefs(false) {}
286
287   RegPressureTracker(RegionPressure &rp) :
288     MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(false),
289     TrackUntiedDefs(false) {}
290
291   void init(const MachineFunction *mf, const RegisterClassInfo *rci,
292             const LiveIntervals *lis, const MachineBasicBlock *mbb,
293             MachineBasicBlock::const_iterator pos,
294             bool ShouldTrackUntiedDefs = false);
295
296   /// Force liveness of virtual registers or physical register
297   /// units. Particularly useful to initialize the livein/out state of the
298   /// tracker before the first call to advance/recede.
299   void addLiveRegs(ArrayRef<unsigned> Regs);
300
301   /// Get the MI position corresponding to this register pressure.
302   MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
303
304   // Reset the MI position corresponding to the register pressure. This allows
305   // schedulers to move instructions above the RegPressureTracker's
306   // CurrPos. Since the pressure is computed before CurrPos, the iterator
307   // position changes while pressure does not.
308   void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
309
310   /// \brief Get the SlotIndex for the first nondebug instruction including or
311   /// after the current position.
312   SlotIndex getCurrSlot() const;
313
314   /// Recede across the previous instruction.
315   bool recede(SmallVectorImpl<unsigned> *LiveUses = 0, PressureDiff *PDiff = 0);
316
317   /// Advance across the current instruction.
318   bool advance();
319
320   /// Finalize the region boundaries and recored live ins and live outs.
321   void closeRegion();
322
323   /// Initialize the LiveThru pressure set based on the untied defs found in
324   /// RPTracker.
325   void initLiveThru(const RegPressureTracker &RPTracker);
326
327   /// Copy an existing live thru pressure result.
328   void initLiveThru(ArrayRef<unsigned> PressureSet) {
329     LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
330   }
331
332   ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
333
334   /// Get the resulting register pressure over the traversed region.
335   /// This result is complete if either advance() or recede() has returned true,
336   /// or if closeRegion() was explicitly invoked.
337   RegisterPressure &getPressure() { return P; }
338   const RegisterPressure &getPressure() const { return P; }
339
340   /// Get the register set pressure at the current position, which may be less
341   /// than the pressure across the traversed region.
342   std::vector<unsigned> &getRegSetPressureAtPos() { return CurrSetPressure; }
343
344   void discoverLiveOut(unsigned Reg);
345   void discoverLiveIn(unsigned Reg);
346
347   bool isTopClosed() const;
348   bool isBottomClosed() const;
349
350   void closeTop();
351   void closeBottom();
352
353   /// Consider the pressure increase caused by traversing this instruction
354   /// bottom-up. Find the pressure set with the most change beyond its pressure
355   /// limit based on the tracker's current pressure, and record the number of
356   /// excess register units of that pressure set introduced by this instruction.
357   void getMaxUpwardPressureDelta(const MachineInstr *MI,
358                                  PressureDiff *PDiff,
359                                  RegPressureDelta &Delta,
360                                  ArrayRef<PressureChange> CriticalPSets,
361                                  ArrayRef<unsigned> MaxPressureLimit);
362
363   void getUpwardPressureDelta(const MachineInstr *MI,
364                               /*const*/ PressureDiff &PDiff,
365                               RegPressureDelta &Delta,
366                               ArrayRef<PressureChange> CriticalPSets,
367                               ArrayRef<unsigned> MaxPressureLimit) const;
368
369   /// Consider the pressure increase caused by traversing this instruction
370   /// top-down. Find the pressure set with the most change beyond its pressure
371   /// limit based on the tracker's current pressure, and record the number of
372   /// excess register units of that pressure set introduced by this instruction.
373   void getMaxDownwardPressureDelta(const MachineInstr *MI,
374                                    RegPressureDelta &Delta,
375                                    ArrayRef<PressureChange> CriticalPSets,
376                                    ArrayRef<unsigned> MaxPressureLimit);
377
378   /// Find the pressure set with the most change beyond its pressure limit after
379   /// traversing this instruction either upward or downward depending on the
380   /// closed end of the current region.
381   void getMaxPressureDelta(const MachineInstr *MI,
382                            RegPressureDelta &Delta,
383                            ArrayRef<PressureChange> CriticalPSets,
384                            ArrayRef<unsigned> MaxPressureLimit) {
385     if (isTopClosed())
386       return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
387                                          MaxPressureLimit);
388
389     assert(isBottomClosed() && "Uninitialized pressure tracker");
390     return getMaxUpwardPressureDelta(MI, 0, Delta, CriticalPSets,
391                                      MaxPressureLimit);
392   }
393
394   /// Get the pressure of each PSet after traversing this instruction bottom-up.
395   void getUpwardPressure(const MachineInstr *MI,
396                          std::vector<unsigned> &PressureResult,
397                          std::vector<unsigned> &MaxPressureResult);
398
399   /// Get the pressure of each PSet after traversing this instruction top-down.
400   void getDownwardPressure(const MachineInstr *MI,
401                            std::vector<unsigned> &PressureResult,
402                            std::vector<unsigned> &MaxPressureResult);
403
404   void getPressureAfterInst(const MachineInstr *MI,
405                             std::vector<unsigned> &PressureResult,
406                             std::vector<unsigned> &MaxPressureResult) {
407     if (isTopClosed())
408       return getUpwardPressure(MI, PressureResult, MaxPressureResult);
409
410     assert(isBottomClosed() && "Uninitialized pressure tracker");
411     return getDownwardPressure(MI, PressureResult, MaxPressureResult);
412   }
413
414   bool hasUntiedDef(unsigned VirtReg) const {
415     return UntiedDefs.count(VirtReg);
416   }
417
418   void dump() const;
419
420 protected:
421   const LiveInterval *getInterval(unsigned Reg) const;
422
423   void increaseRegPressure(ArrayRef<unsigned> Regs);
424   void decreaseRegPressure(ArrayRef<unsigned> Regs);
425
426   void bumpUpwardPressure(const MachineInstr *MI);
427   void bumpDownwardPressure(const MachineInstr *MI);
428 };
429
430 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
431 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
432                         const TargetRegisterInfo *TRI);
433 #endif
434 } // end namespace llvm
435
436 #endif