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