1 //===-- RegisterPressure.h - Dynamic Register Pressure -*- C++ -*-------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the RegisterPressure class which can be used to track
11 // MachineInstr level register pressure.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_REGISTERPRESSURE_H
16 #define LLVM_CODEGEN_REGISTERPRESSURE_H
18 #include "llvm/ADT/SparseSet.h"
19 #include "llvm/CodeGen/SlotIndexes.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
26 class RegisterClassInfo;
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;
34 /// List of live in virtual registers or physical register units.
35 SmallVector<unsigned,8> LiveInRegs;
36 SmallVector<unsigned,8> LiveOutRegs;
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).
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);
46 /// Decrease register pressure for each pressure set impacted by this register
47 /// class. This is only useful to account for spilling or rematerialization.
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);
53 void dump(const TargetRegisterInfo *TRI) const;
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.
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.
72 void openTop(SlotIndex NextTop);
74 void openBottom(SlotIndex PrevBottom);
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;
87 void openTop(MachineBasicBlock::const_iterator PrevTop);
89 void openBottom(MachineBasicBlock::const_iterator PrevBottom);
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.
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.
104 PressureChange(): PSetID(0), UnitInc(0) {}
105 PressureChange(unsigned id): PSetID(id+1), UnitInc(0) {
106 assert(id < UINT16_MAX && "PSetID overflow.");
109 bool isValid() const { return PSetID > 0; }
111 unsigned getPSet() const {
112 assert(isValid() && "invalid PressureChange");
115 // If PSetID is invalid, return UINT16_MAX to give it lowest priority.
116 unsigned getPSetOrMax() const { return (PSetID - 1) & UINT16_MAX; }
118 int getUnitInc() const { return UnitInc; }
120 void setUnitInc(int Inc) { UnitInc = Inc; }
122 bool operator==(const PressureChange &RHS) const {
123 return PSetID == RHS.PSetID && UnitInc == RHS.UnitInc;
127 template <> struct isPodLike<PressureChange> {
128 static const bool value = true;
131 /// List of PressureChanges in order of increasing, unique PSetID.
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.
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 };
142 PressureChange PressureChanges[MaxPSets];
144 typedef PressureChange* iterator;
145 typedef const PressureChange* const_iterator;
146 iterator begin() { return &PressureChanges[0]; }
147 iterator end() { return &PressureChanges[MaxPSets]; }
149 void addPressureChange(unsigned RegUnit, bool IsDec,
150 const MachineRegisterInfo *MRI);
153 /// Array of PressureDiffs.
154 class PressureDiffs {
155 PressureDiff *PDiffArray;
159 PressureDiffs(): PDiffArray(0), Size(0), Max(0) {}
160 ~PressureDiffs() { free(PDiffArray); }
162 void init(unsigned N);
164 PressureDiff &operator[](unsigned Idx) {
165 assert(Idx < Size && "PressureDiff index out of bounds");
166 return PDiffArray[Idx];
168 const PressureDiff &operator[](unsigned Idx) const {
169 return const_cast<PressureDiffs*>(this)->operator[](Idx);
173 /// Store the effects of a change in pressure on things that MI scheduler cares
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
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.
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;
192 RegPressureDelta() {}
194 bool operator==(const RegPressureDelta &RHS) const {
195 return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
196 && CurrentMax == RHS.CurrentMax;
198 bool operator!=(const RegPressureDelta &RHS) const {
199 return !operator==(RHS);
203 /// \brief A set of live virtual registers and physical register units.
205 /// Virtual and physical register numbers require separate sparse sets, but most
206 /// of the RegisterPressureTracker handles them uniformly.
208 SparseSet<unsigned> PhysRegs;
209 SparseSet<unsigned, VirtReg2IndexFunctor> VirtRegs;
211 bool contains(unsigned Reg) const {
212 if (TargetRegisterInfo::isVirtualRegister(Reg))
213 return VirtRegs.count(Reg);
214 return PhysRegs.count(Reg);
217 bool insert(unsigned Reg) {
218 if (TargetRegisterInfo::isVirtualRegister(Reg))
219 return VirtRegs.insert(Reg).second;
220 return PhysRegs.insert(Reg).second;
223 bool erase(unsigned Reg) {
224 if (TargetRegisterInfo::isVirtualRegister(Reg))
225 return VirtRegs.erase(Reg);
226 return PhysRegs.erase(Reg);
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.
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.
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;
253 /// We currently only allow pressure tracking within a block.
254 const MachineBasicBlock *MBB;
256 /// Track the max pressure within the region traversed so far.
259 /// Run in two modes dependending on whether constructed with IntervalPressure
260 /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
261 bool RequireIntervals;
263 /// True if UntiedDefs will be populated.
264 bool TrackUntiedDefs;
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
269 MachineBasicBlock::const_iterator CurrPos;
271 /// Pressure map indexed by pressure set ID, not class ID.
272 std::vector<unsigned> CurrSetPressure;
274 /// Set of live registers.
277 /// Set of vreg defs that start a live range.
278 SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
279 /// Live-through pressure.
280 std::vector<unsigned> LiveThruPressure;
283 RegPressureTracker(IntervalPressure &rp) :
284 MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(true),
285 TrackUntiedDefs(false) {}
287 RegPressureTracker(RegionPressure &rp) :
288 MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(false),
289 TrackUntiedDefs(false) {}
293 void init(const MachineFunction *mf, const RegisterClassInfo *rci,
294 const LiveIntervals *lis, const MachineBasicBlock *mbb,
295 MachineBasicBlock::const_iterator pos,
296 bool ShouldTrackUntiedDefs = false);
298 /// Force liveness of virtual registers or physical register
299 /// units. Particularly useful to initialize the livein/out state of the
300 /// tracker before the first call to advance/recede.
301 void addLiveRegs(ArrayRef<unsigned> Regs);
303 /// Get the MI position corresponding to this register pressure.
304 MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
306 // Reset the MI position corresponding to the register pressure. This allows
307 // schedulers to move instructions above the RegPressureTracker's
308 // CurrPos. Since the pressure is computed before CurrPos, the iterator
309 // position changes while pressure does not.
310 void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
312 /// \brief Get the SlotIndex for the first nondebug instruction including or
313 /// after the current position.
314 SlotIndex getCurrSlot() const;
316 /// Recede across the previous instruction.
317 bool recede(SmallVectorImpl<unsigned> *LiveUses = 0, PressureDiff *PDiff = 0);
319 /// Advance across the current instruction.
322 /// Finalize the region boundaries and recored live ins and live outs.
325 /// Initialize the LiveThru pressure set based on the untied defs found in
327 void initLiveThru(const RegPressureTracker &RPTracker);
329 /// Copy an existing live thru pressure result.
330 void initLiveThru(ArrayRef<unsigned> PressureSet) {
331 LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
334 ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
336 /// Get the resulting register pressure over the traversed region.
337 /// This result is complete if either advance() or recede() has returned true,
338 /// or if closeRegion() was explicitly invoked.
339 RegisterPressure &getPressure() { return P; }
340 const RegisterPressure &getPressure() const { return P; }
342 /// Get the register set pressure at the current position, which may be less
343 /// than the pressure across the traversed region.
344 std::vector<unsigned> &getRegSetPressureAtPos() { return CurrSetPressure; }
346 void discoverLiveOut(unsigned Reg);
347 void discoverLiveIn(unsigned Reg);
349 bool isTopClosed() const;
350 bool isBottomClosed() const;
355 /// Consider the pressure increase caused by traversing this instruction
356 /// bottom-up. Find the pressure set with the most change beyond its pressure
357 /// limit based on the tracker's current pressure, and record the number of
358 /// excess register units of that pressure set introduced by this instruction.
359 void getMaxUpwardPressureDelta(const MachineInstr *MI,
361 RegPressureDelta &Delta,
362 ArrayRef<PressureChange> CriticalPSets,
363 ArrayRef<unsigned> MaxPressureLimit);
365 void getUpwardPressureDelta(const MachineInstr *MI,
366 /*const*/ PressureDiff &PDiff,
367 RegPressureDelta &Delta,
368 ArrayRef<PressureChange> CriticalPSets,
369 ArrayRef<unsigned> MaxPressureLimit) const;
371 /// Consider the pressure increase caused by traversing this instruction
372 /// top-down. Find the pressure set with the most change beyond its pressure
373 /// limit based on the tracker's current pressure, and record the number of
374 /// excess register units of that pressure set introduced by this instruction.
375 void getMaxDownwardPressureDelta(const MachineInstr *MI,
376 RegPressureDelta &Delta,
377 ArrayRef<PressureChange> CriticalPSets,
378 ArrayRef<unsigned> MaxPressureLimit);
380 /// Find the pressure set with the most change beyond its pressure limit after
381 /// traversing this instruction either upward or downward depending on the
382 /// closed end of the current region.
383 void getMaxPressureDelta(const MachineInstr *MI,
384 RegPressureDelta &Delta,
385 ArrayRef<PressureChange> CriticalPSets,
386 ArrayRef<unsigned> MaxPressureLimit) {
388 return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
391 assert(isBottomClosed() && "Uninitialized pressure tracker");
392 return getMaxUpwardPressureDelta(MI, 0, Delta, CriticalPSets,
396 /// Get the pressure of each PSet after traversing this instruction bottom-up.
397 void getUpwardPressure(const MachineInstr *MI,
398 std::vector<unsigned> &PressureResult,
399 std::vector<unsigned> &MaxPressureResult);
401 /// Get the pressure of each PSet after traversing this instruction top-down.
402 void getDownwardPressure(const MachineInstr *MI,
403 std::vector<unsigned> &PressureResult,
404 std::vector<unsigned> &MaxPressureResult);
406 void getPressureAfterInst(const MachineInstr *MI,
407 std::vector<unsigned> &PressureResult,
408 std::vector<unsigned> &MaxPressureResult) {
410 return getUpwardPressure(MI, PressureResult, MaxPressureResult);
412 assert(isBottomClosed() && "Uninitialized pressure tracker");
413 return getDownwardPressure(MI, PressureResult, MaxPressureResult);
416 bool hasUntiedDef(unsigned VirtReg) const {
417 return UntiedDefs.count(VirtReg);
423 const LiveInterval *getInterval(unsigned Reg) const;
425 void increaseRegPressure(ArrayRef<unsigned> Regs);
426 void decreaseRegPressure(ArrayRef<unsigned> Regs);
428 void bumpUpwardPressure(const MachineInstr *MI);
429 void bumpDownwardPressure(const MachineInstr *MI);
432 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
433 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
434 const TargetRegisterInfo *TRI);
436 } // end namespace llvm