Merging r260164:
[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 /// List of registers defined and used by a machine instruction.
145 class RegisterOperands {
146 public:
147   /// List of virtual regiserts and register units read by the instruction.
148   SmallVector<unsigned, 8> Uses;
149   /// \brief List of virtual registers and register units defined by the
150   /// instruction which are not dead.
151   SmallVector<unsigned, 8> Defs;
152   /// \brief List of virtual registers and register units defined by the
153   /// instruction but dead.
154   SmallVector<unsigned, 8> DeadDefs;
155
156   /// Analyze the given instruction \p MI and fill in the Uses, Defs and
157   /// DeadDefs list based on the MachineOperand flags.
158   void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI,
159                const MachineRegisterInfo &MRI, bool IgnoreDead = false);
160
161   /// Use liveness information to find dead defs not marked with a dead flag
162   /// and move them to the DeadDefs vector.
163   void detectDeadDefs(const MachineInstr &MI, const LiveIntervals &LIS);
164 };
165
166 /// Array of PressureDiffs.
167 class PressureDiffs {
168   PressureDiff *PDiffArray;
169   unsigned Size;
170   unsigned Max;
171 public:
172   PressureDiffs(): PDiffArray(nullptr), Size(0), Max(0) {}
173   ~PressureDiffs() { free(PDiffArray); }
174
175   void clear() { Size = 0; }
176
177   void init(unsigned N);
178
179   PressureDiff &operator[](unsigned Idx) {
180     assert(Idx < Size && "PressureDiff index out of bounds");
181     return PDiffArray[Idx];
182   }
183   const PressureDiff &operator[](unsigned Idx) const {
184     return const_cast<PressureDiffs*>(this)->operator[](Idx);
185   }
186   /// \brief Record pressure difference induced by the given operand list to
187   /// node with index \p Idx.
188   void addInstruction(unsigned Idx, const RegisterOperands &RegOpers,
189                       const MachineRegisterInfo &MRI);
190 };
191
192 /// Store the effects of a change in pressure on things that MI scheduler cares
193 /// about.
194 ///
195 /// Excess records the value of the largest difference in register units beyond
196 /// the target's pressure limits across the affected pressure sets, where
197 /// largest is defined as the absolute value of the difference. Negative
198 /// ExcessUnits indicates a reduction in pressure that had already exceeded the
199 /// target's limits.
200 ///
201 /// CriticalMax records the largest increase in the tracker's max pressure that
202 /// exceeds the critical limit for some pressure set determined by the client.
203 ///
204 /// CurrentMax records the largest increase in the tracker's max pressure that
205 /// exceeds the current limit for some pressure set determined by the client.
206 struct RegPressureDelta {
207   PressureChange Excess;
208   PressureChange CriticalMax;
209   PressureChange CurrentMax;
210
211   RegPressureDelta() {}
212
213   bool operator==(const RegPressureDelta &RHS) const {
214     return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
215       && CurrentMax == RHS.CurrentMax;
216   }
217   bool operator!=(const RegPressureDelta &RHS) const {
218     return !operator==(RHS);
219   }
220 };
221
222 /// A set of live virtual registers and physical register units.
223 ///
224 /// This is a wrapper around a SparseSet which deals with mapping register unit
225 /// and virtual register indexes to an index usable by the sparse set.
226 class LiveRegSet {
227 private:
228   SparseSet<unsigned> Regs;
229   unsigned NumRegUnits;
230
231   unsigned getSparseIndexFromReg(unsigned Reg) const {
232     if (TargetRegisterInfo::isVirtualRegister(Reg))
233       return TargetRegisterInfo::virtReg2Index(Reg) + NumRegUnits;
234     assert(Reg < NumRegUnits);
235     return Reg;
236   }
237   unsigned getRegFromSparseIndex(unsigned SparseIndex) const {
238     if (SparseIndex >= NumRegUnits)
239       return TargetRegisterInfo::index2VirtReg(SparseIndex-NumRegUnits);
240     return SparseIndex;
241   }
242
243 public:
244   void clear();
245   void init(const MachineRegisterInfo &MRI);
246
247   bool contains(unsigned Reg) const {
248     unsigned SparseIndex = getSparseIndexFromReg(Reg);
249     return Regs.count(SparseIndex);
250   }
251
252   bool insert(unsigned Reg) {
253     unsigned SparseIndex = getSparseIndexFromReg(Reg);
254     return Regs.insert(SparseIndex).second;
255   }
256
257   bool erase(unsigned Reg) {
258     unsigned SparseIndex = getSparseIndexFromReg(Reg);
259     return Regs.erase(SparseIndex);
260   }
261
262   size_t size() const {
263     return Regs.size();
264   }
265
266   template<typename ContainerT>
267   void appendTo(ContainerT &To) const {
268     for (unsigned I : Regs) {
269       unsigned Reg = getRegFromSparseIndex(I);
270       To.push_back(Reg);
271     }
272   }
273 };
274
275 /// Track the current register pressure at some position in the instruction
276 /// stream, and remember the high water mark within the region traversed. This
277 /// does not automatically consider live-through ranges. The client may
278 /// independently adjust for global liveness.
279 ///
280 /// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
281 /// be tracked across a larger region by storing a RegisterPressure result at
282 /// each block boundary and explicitly adjusting pressure to account for block
283 /// live-in and live-out register sets.
284 ///
285 /// RegPressureTracker holds a reference to a RegisterPressure result that it
286 /// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
287 /// is invalid until it reaches the end of the block or closeRegion() is
288 /// explicitly called. Similarly, P.TopIdx is invalid during upward
289 /// tracking. Changing direction has the side effect of closing region, and
290 /// traversing past TopIdx or BottomIdx reopens it.
291 class RegPressureTracker {
292   const MachineFunction     *MF;
293   const TargetRegisterInfo  *TRI;
294   const RegisterClassInfo   *RCI;
295   const MachineRegisterInfo *MRI;
296   const LiveIntervals       *LIS;
297
298   /// We currently only allow pressure tracking within a block.
299   const MachineBasicBlock *MBB;
300
301   /// Track the max pressure within the region traversed so far.
302   RegisterPressure &P;
303
304   /// Run in two modes dependending on whether constructed with IntervalPressure
305   /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
306   bool RequireIntervals;
307
308   /// True if UntiedDefs will be populated.
309   bool TrackUntiedDefs;
310
311   /// Register pressure corresponds to liveness before this instruction
312   /// iterator. It may point to the end of the block or a DebugValue rather than
313   /// an instruction.
314   MachineBasicBlock::const_iterator CurrPos;
315
316   /// Pressure map indexed by pressure set ID, not class ID.
317   std::vector<unsigned> CurrSetPressure;
318
319   /// Set of live registers.
320   LiveRegSet LiveRegs;
321
322   /// Set of vreg defs that start a live range.
323   SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
324   /// Live-through pressure.
325   std::vector<unsigned> LiveThruPressure;
326
327 public:
328   RegPressureTracker(IntervalPressure &rp) :
329     MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
330     RequireIntervals(true), TrackUntiedDefs(false) {}
331
332   RegPressureTracker(RegionPressure &rp) :
333     MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
334     RequireIntervals(false), TrackUntiedDefs(false) {}
335
336   void reset();
337
338   void init(const MachineFunction *mf, const RegisterClassInfo *rci,
339             const LiveIntervals *lis, const MachineBasicBlock *mbb,
340             MachineBasicBlock::const_iterator pos,
341             bool ShouldTrackUntiedDefs = false);
342
343   /// Force liveness of virtual registers or physical register
344   /// units. Particularly useful to initialize the livein/out state of the
345   /// tracker before the first call to advance/recede.
346   void addLiveRegs(ArrayRef<unsigned> Regs);
347
348   /// Get the MI position corresponding to this register pressure.
349   MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
350
351   // Reset the MI position corresponding to the register pressure. This allows
352   // schedulers to move instructions above the RegPressureTracker's
353   // CurrPos. Since the pressure is computed before CurrPos, the iterator
354   // position changes while pressure does not.
355   void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
356
357   /// Recede across the previous instruction.
358   void recede(SmallVectorImpl<unsigned> *LiveUses = nullptr);
359
360   /// Recede across the previous instruction.
361   /// This "low-level" variant assumes that recedeSkipDebugValues() was
362   /// called previously and takes precomputed RegisterOperands for the
363   /// instruction.
364   void recede(const RegisterOperands &RegOpers,
365               SmallVectorImpl<unsigned> *LiveUses = nullptr);
366
367   /// Recede until we find an instruction which is not a DebugValue.
368   void recedeSkipDebugValues();
369
370   /// Advance across the current instruction.
371   void advance();
372
373   /// Finalize the region boundaries and recored live ins and live outs.
374   void closeRegion();
375
376   /// Initialize the LiveThru pressure set based on the untied defs found in
377   /// RPTracker.
378   void initLiveThru(const RegPressureTracker &RPTracker);
379
380   /// Copy an existing live thru pressure result.
381   void initLiveThru(ArrayRef<unsigned> PressureSet) {
382     LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
383   }
384
385   ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
386
387   /// Get the resulting register pressure over the traversed region.
388   /// This result is complete if closeRegion() was explicitly invoked.
389   RegisterPressure &getPressure() { return P; }
390   const RegisterPressure &getPressure() const { return P; }
391
392   /// Get the register set pressure at the current position, which may be less
393   /// than the pressure across the traversed region.
394   const std::vector<unsigned> &getRegSetPressureAtPos() const {
395     return CurrSetPressure;
396   }
397
398   bool isTopClosed() const;
399   bool isBottomClosed() const;
400
401   void closeTop();
402   void closeBottom();
403
404   /// Consider the pressure increase caused by traversing this instruction
405   /// bottom-up. Find the pressure set with the most change beyond its pressure
406   /// limit based on the tracker's current pressure, and record the number of
407   /// excess register units of that pressure set introduced by this instruction.
408   void getMaxUpwardPressureDelta(const MachineInstr *MI,
409                                  PressureDiff *PDiff,
410                                  RegPressureDelta &Delta,
411                                  ArrayRef<PressureChange> CriticalPSets,
412                                  ArrayRef<unsigned> MaxPressureLimit);
413
414   void getUpwardPressureDelta(const MachineInstr *MI,
415                               /*const*/ PressureDiff &PDiff,
416                               RegPressureDelta &Delta,
417                               ArrayRef<PressureChange> CriticalPSets,
418                               ArrayRef<unsigned> MaxPressureLimit) const;
419
420   /// Consider the pressure increase caused by traversing this instruction
421   /// top-down. Find the pressure set with the most change beyond its pressure
422   /// limit based on the tracker's current pressure, and record the number of
423   /// excess register units of that pressure set introduced by this instruction.
424   void getMaxDownwardPressureDelta(const MachineInstr *MI,
425                                    RegPressureDelta &Delta,
426                                    ArrayRef<PressureChange> CriticalPSets,
427                                    ArrayRef<unsigned> MaxPressureLimit);
428
429   /// Find the pressure set with the most change beyond its pressure limit after
430   /// traversing this instruction either upward or downward depending on the
431   /// closed end of the current region.
432   void getMaxPressureDelta(const MachineInstr *MI,
433                            RegPressureDelta &Delta,
434                            ArrayRef<PressureChange> CriticalPSets,
435                            ArrayRef<unsigned> MaxPressureLimit) {
436     if (isTopClosed())
437       return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
438                                          MaxPressureLimit);
439
440     assert(isBottomClosed() && "Uninitialized pressure tracker");
441     return getMaxUpwardPressureDelta(MI, nullptr, Delta, CriticalPSets,
442                                      MaxPressureLimit);
443   }
444
445   /// Get the pressure of each PSet after traversing this instruction bottom-up.
446   void getUpwardPressure(const MachineInstr *MI,
447                          std::vector<unsigned> &PressureResult,
448                          std::vector<unsigned> &MaxPressureResult);
449
450   /// Get the pressure of each PSet after traversing this instruction top-down.
451   void getDownwardPressure(const MachineInstr *MI,
452                            std::vector<unsigned> &PressureResult,
453                            std::vector<unsigned> &MaxPressureResult);
454
455   void getPressureAfterInst(const MachineInstr *MI,
456                             std::vector<unsigned> &PressureResult,
457                             std::vector<unsigned> &MaxPressureResult) {
458     if (isTopClosed())
459       return getUpwardPressure(MI, PressureResult, MaxPressureResult);
460
461     assert(isBottomClosed() && "Uninitialized pressure tracker");
462     return getDownwardPressure(MI, PressureResult, MaxPressureResult);
463   }
464
465   bool hasUntiedDef(unsigned VirtReg) const {
466     return UntiedDefs.count(VirtReg);
467   }
468
469   void dump() const;
470
471 protected:
472   void discoverLiveOut(unsigned Reg);
473   void discoverLiveIn(unsigned Reg);
474
475   /// \brief Get the SlotIndex for the first nondebug instruction including or
476   /// after the current position.
477   SlotIndex getCurrSlot() const;
478
479   void increaseRegPressure(ArrayRef<unsigned> Regs);
480   void decreaseRegPressure(ArrayRef<unsigned> Regs);
481
482   void bumpUpwardPressure(const MachineInstr *MI);
483   void bumpDownwardPressure(const MachineInstr *MI);
484 };
485
486 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
487                         const TargetRegisterInfo *TRI);
488 } // end namespace llvm
489
490 #endif