1 //===-- RegisterPressure.cpp - Dynamic Register Pressure ------------------===//
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 implements the RegisterPressure class which can be used to track
11 // MachineInstr level register pressure.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/RegisterPressure.h"
16 #include "llvm/CodeGen/LiveInterval.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/RegisterClassInfo.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
25 /// Increase pressure for each pressure set provided by TargetRegisterInfo.
26 static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure,
28 unsigned Weight = PSetI.getWeight();
29 for (; PSetI.isValid(); ++PSetI)
30 CurrSetPressure[*PSetI] += Weight;
33 /// Decrease pressure for each pressure set provided by TargetRegisterInfo.
34 static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure,
36 unsigned Weight = PSetI.getWeight();
37 for (; PSetI.isValid(); ++PSetI) {
38 assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow");
39 CurrSetPressure[*PSetI] -= Weight;
44 void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
45 const TargetRegisterInfo *TRI) {
47 for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) {
48 if (SetPressure[i] != 0) {
49 dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << '\n';
58 void RegisterPressure::dump(const TargetRegisterInfo *TRI) const {
59 dbgs() << "Max Pressure: ";
60 dumpRegSetPressure(MaxSetPressure, TRI);
61 dbgs() << "Live In: ";
62 for (unsigned Reg : LiveInRegs)
63 dbgs() << PrintVRegOrUnit(Reg, TRI) << " ";
65 dbgs() << "Live Out: ";
66 for (unsigned Reg : LiveOutRegs)
67 dbgs() << PrintVRegOrUnit(Reg, TRI) << " ";
72 void RegPressureTracker::dump() const {
73 if (!isTopClosed() || !isBottomClosed()) {
74 dbgs() << "Curr Pressure: ";
75 dumpRegSetPressure(CurrSetPressure, TRI);
80 void PressureDiff::dump(const TargetRegisterInfo &TRI) const {
82 for (const PressureChange &Change : *this) {
83 if (!Change.isValid())
85 dbgs() << sep << TRI.getRegPressureSetName(Change.getPSet())
86 << " " << Change.getUnitInc();
92 /// Increase the current pressure as impacted by these registers and bump
93 /// the high water mark if needed.
94 void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) {
95 for (unsigned RegUnit : RegUnits) {
96 PSetIterator PSetI = MRI->getPressureSets(RegUnit);
97 unsigned Weight = PSetI.getWeight();
98 for (; PSetI.isValid(); ++PSetI) {
99 CurrSetPressure[*PSetI] += Weight;
100 P.MaxSetPressure[*PSetI] =
101 std::max(P.MaxSetPressure[*PSetI], CurrSetPressure[*PSetI]);
106 /// Simply decrease the current pressure as impacted by these registers.
107 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) {
108 for (unsigned RegUnit : RegUnits)
109 decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnit));
112 /// Clear the result so it can be used for another round of pressure tracking.
113 void IntervalPressure::reset() {
114 TopIdx = BottomIdx = SlotIndex();
115 MaxSetPressure.clear();
120 /// Clear the result so it can be used for another round of pressure tracking.
121 void RegionPressure::reset() {
122 TopPos = BottomPos = MachineBasicBlock::const_iterator();
123 MaxSetPressure.clear();
128 /// If the current top is not less than or equal to the next index, open it.
129 /// We happen to need the SlotIndex for the next top for pressure update.
130 void IntervalPressure::openTop(SlotIndex NextTop) {
131 if (TopIdx <= NextTop)
133 TopIdx = SlotIndex();
137 /// If the current top is the previous instruction (before receding), open it.
138 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
139 if (TopPos != PrevTop)
141 TopPos = MachineBasicBlock::const_iterator();
145 /// If the current bottom is not greater than the previous index, open it.
146 void IntervalPressure::openBottom(SlotIndex PrevBottom) {
147 if (BottomIdx > PrevBottom)
149 BottomIdx = SlotIndex();
153 /// If the current bottom is the previous instr (before advancing), open it.
154 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
155 if (BottomPos != PrevBottom)
157 BottomPos = MachineBasicBlock::const_iterator();
161 void LiveRegSet::init(const MachineRegisterInfo &MRI) {
162 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
163 unsigned NumRegUnits = TRI.getNumRegs();
164 unsigned NumVirtRegs = MRI.getNumVirtRegs();
165 Regs.setUniverse(NumRegUnits + NumVirtRegs);
166 this->NumRegUnits = NumRegUnits;
169 void LiveRegSet::clear() {
173 static const LiveRange *getLiveRange(const LiveIntervals &LIS, unsigned Reg) {
174 if (TargetRegisterInfo::isVirtualRegister(Reg))
175 return &LIS.getInterval(Reg);
176 return LIS.getCachedRegUnit(Reg);
179 void RegPressureTracker::reset() {
183 CurrSetPressure.clear();
184 LiveThruPressure.clear();
185 P.MaxSetPressure.clear();
187 if (RequireIntervals)
188 static_cast<IntervalPressure&>(P).reset();
190 static_cast<RegionPressure&>(P).reset();
196 /// Setup the RegPressureTracker.
198 /// TODO: Add support for pressure without LiveIntervals.
199 void RegPressureTracker::init(const MachineFunction *mf,
200 const RegisterClassInfo *rci,
201 const LiveIntervals *lis,
202 const MachineBasicBlock *mbb,
203 MachineBasicBlock::const_iterator pos,
204 bool ShouldTrackUntiedDefs)
209 TRI = MF->getSubtarget().getRegisterInfo();
211 MRI = &MF->getRegInfo();
213 TrackUntiedDefs = ShouldTrackUntiedDefs;
215 if (RequireIntervals) {
216 assert(lis && "IntervalPressure requires LiveIntervals");
221 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
223 P.MaxSetPressure = CurrSetPressure;
227 UntiedDefs.setUniverse(MRI->getNumVirtRegs());
230 /// Does this pressure result have a valid top position and live ins.
231 bool RegPressureTracker::isTopClosed() const {
232 if (RequireIntervals)
233 return static_cast<IntervalPressure&>(P).TopIdx.isValid();
234 return (static_cast<RegionPressure&>(P).TopPos ==
235 MachineBasicBlock::const_iterator());
238 /// Does this pressure result have a valid bottom position and live outs.
239 bool RegPressureTracker::isBottomClosed() const {
240 if (RequireIntervals)
241 return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
242 return (static_cast<RegionPressure&>(P).BottomPos ==
243 MachineBasicBlock::const_iterator());
247 SlotIndex RegPressureTracker::getCurrSlot() const {
248 MachineBasicBlock::const_iterator IdxPos = CurrPos;
249 while (IdxPos != MBB->end() && IdxPos->isDebugValue())
251 if (IdxPos == MBB->end())
252 return LIS->getMBBEndIdx(MBB);
253 return LIS->getInstructionIndex(IdxPos).getRegSlot();
256 /// Set the boundary for the top of the region and summarize live ins.
257 void RegPressureTracker::closeTop() {
258 if (RequireIntervals)
259 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
261 static_cast<RegionPressure&>(P).TopPos = CurrPos;
263 assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
264 P.LiveInRegs.reserve(LiveRegs.size());
265 LiveRegs.appendTo(P.LiveInRegs);
268 /// Set the boundary for the bottom of the region and summarize live outs.
269 void RegPressureTracker::closeBottom() {
270 if (RequireIntervals)
271 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
273 static_cast<RegionPressure&>(P).BottomPos = CurrPos;
275 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
276 P.LiveOutRegs.reserve(LiveRegs.size());
277 LiveRegs.appendTo(P.LiveOutRegs);
280 /// Finalize the region boundaries and record live ins and live outs.
281 void RegPressureTracker::closeRegion() {
282 if (!isTopClosed() && !isBottomClosed()) {
283 assert(LiveRegs.size() == 0 && "no region boundary");
286 if (!isBottomClosed())
288 else if (!isTopClosed())
290 // If both top and bottom are closed, do nothing.
293 /// The register tracker is unaware of global liveness so ignores normal
294 /// live-thru ranges. However, two-address or coalesced chains can also lead
295 /// to live ranges with no holes. Count these to inform heuristics that we
296 /// can never drop below this pressure.
297 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
298 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
299 assert(isBottomClosed() && "need bottom-up tracking to intialize.");
300 for (unsigned Reg : P.LiveOutRegs) {
301 if (TargetRegisterInfo::isVirtualRegister(Reg)
302 && !RPTracker.hasUntiedDef(Reg)) {
303 increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg));
308 /// \brief Convenient wrapper for checking membership in RegisterOperands.
309 /// (std::count() doesn't have an early exit).
310 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
311 return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
316 /// Collect this instruction's unique uses and defs into SmallVectors for
317 /// processing defs and uses in order.
319 /// FIXME: always ignore tied opers
320 class RegisterOperandsCollector {
321 RegisterOperands &RegOpers;
322 const TargetRegisterInfo &TRI;
323 const MachineRegisterInfo &MRI;
326 RegisterOperandsCollector(RegisterOperands &RegOpers,
327 const TargetRegisterInfo &TRI,
328 const MachineRegisterInfo &MRI,
330 : RegOpers(RegOpers), TRI(TRI), MRI(MRI), IgnoreDead(IgnoreDead) {}
332 void collectInstr(const MachineInstr &MI) const {
333 for (ConstMIBundleOperands OperI(&MI); OperI.isValid(); ++OperI)
334 collectOperand(*OperI);
336 // Remove redundant physreg dead defs.
337 SmallVectorImpl<unsigned>::iterator I =
338 std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
339 std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
340 RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
343 /// Push this operand's register onto the correct vectors.
344 void collectOperand(const MachineOperand &MO) const {
345 if (!MO.isReg() || !MO.getReg())
347 unsigned Reg = MO.getReg();
349 pushRegUnits(Reg, RegOpers.Uses);
353 pushRegUnits(Reg, RegOpers.DeadDefs);
355 pushRegUnits(Reg, RegOpers.Defs);
359 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) const {
360 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
361 if (containsReg(RegUnits, Reg))
363 RegUnits.push_back(Reg);
364 } else if (MRI.isAllocatable(Reg)) {
365 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) {
366 if (containsReg(RegUnits, *Units))
368 RegUnits.push_back(*Units);
373 friend class llvm::RegisterOperands;
378 void RegisterOperands::collect(const MachineInstr &MI,
379 const TargetRegisterInfo &TRI,
380 const MachineRegisterInfo &MRI,
382 RegisterOperandsCollector Collector(*this, TRI, MRI, IgnoreDead);
383 Collector.collectInstr(MI);
386 void RegisterOperands::detectDeadDefs(const MachineInstr &MI,
387 const LiveIntervals &LIS) {
388 SlotIndex SlotIdx = LIS.getInstructionIndex(&MI);
389 for (SmallVectorImpl<unsigned>::iterator RI = Defs.begin();
390 RI != Defs.end(); /*empty*/) {
392 const LiveRange *LR = getLiveRange(LIS, Reg);
394 LiveQueryResult LRQ = LR->Query(SlotIdx);
395 if (LRQ.isDeadDef()) {
396 // LiveIntervals knows this is a dead even though it's MachineOperand is
397 // not flagged as such.
398 DeadDefs.push_back(Reg);
407 /// Initialize an array of N PressureDiffs.
408 void PressureDiffs::init(unsigned N) {
411 memset(PDiffArray, 0, N * sizeof(PressureDiff));
416 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
419 void PressureDiffs::addInstruction(unsigned Idx,
420 const RegisterOperands &RegOpers,
421 const MachineRegisterInfo &MRI) {
422 PressureDiff &PDiff = (*this)[Idx];
423 assert(!PDiff.begin()->isValid() && "stale PDiff");
424 for (unsigned Reg : RegOpers.Defs)
425 PDiff.addPressureChange(Reg, true, &MRI);
427 for (unsigned Reg : RegOpers.Uses)
428 PDiff.addPressureChange(Reg, false, &MRI);
431 /// Add a change in pressure to the pressure diff of a given instruction.
432 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
433 const MachineRegisterInfo *MRI) {
434 PSetIterator PSetI = MRI->getPressureSets(RegUnit);
435 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
436 for (; PSetI.isValid(); ++PSetI) {
437 // Find an existing entry in the pressure diff for this PSet.
438 PressureDiff::iterator I = nonconst_begin(), E = nonconst_end();
439 for (; I != E && I->isValid(); ++I) {
440 if (I->getPSet() >= *PSetI)
443 // If all pressure sets are more constrained, skip the remaining PSets.
446 // Insert this PressureChange.
447 if (!I->isValid() || I->getPSet() != *PSetI) {
448 PressureChange PTmp = PressureChange(*PSetI);
449 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
452 // Update the units for this pressure set.
453 unsigned NewUnitInc = I->getUnitInc() + Weight;
454 if (NewUnitInc != 0) {
455 I->setUnitInc(NewUnitInc);
458 PressureDiff::iterator J;
459 for (J = std::next(I); J != E && J->isValid(); ++J, ++I)
467 /// Force liveness of registers.
468 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
469 for (unsigned Reg : Regs) {
470 if (LiveRegs.insert(Reg))
471 increaseRegPressure(Reg);
475 /// Add Reg to the live in set and increase max pressure.
476 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
477 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
478 if (containsReg(P.LiveInRegs, Reg))
481 // At live in discovery, unconditionally increase the high water mark.
482 P.LiveInRegs.push_back(Reg);
483 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
486 /// Add Reg to the live out set and increase max pressure.
487 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
488 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
489 if (containsReg(P.LiveOutRegs, Reg))
492 // At live out discovery, unconditionally increase the high water mark.
493 P.LiveOutRegs.push_back(Reg);
494 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
497 /// Recede across the previous instruction. If LiveUses is provided, record any
498 /// RegUnits that are made live by the current instruction's uses. This includes
499 /// registers that are both defined and used by the instruction. If a pressure
500 /// difference pointer is provided record the changes is pressure caused by this
501 /// instruction independent of liveness.
502 void RegPressureTracker::recede(const RegisterOperands &RegOpers,
503 SmallVectorImpl<unsigned> *LiveUses) {
504 assert(!CurrPos->isDebugValue());
506 // Boost pressure for all dead defs together.
507 increaseRegPressure(RegOpers.DeadDefs);
508 decreaseRegPressure(RegOpers.DeadDefs);
510 // Kill liveness at live defs.
511 // TODO: consider earlyclobbers?
512 for (unsigned Reg : RegOpers.Defs) {
513 if (LiveRegs.erase(Reg))
514 decreaseRegPressure(Reg);
516 discoverLiveOut(Reg);
520 if (RequireIntervals)
521 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
523 // Generate liveness for uses.
524 for (unsigned Reg : RegOpers.Uses) {
525 if (!LiveRegs.contains(Reg)) {
526 // Adjust liveouts if LiveIntervals are available.
527 if (RequireIntervals) {
528 const LiveRange *LR = getLiveRange(*LIS, Reg);
530 LiveQueryResult LRQ = LR->Query(SlotIdx);
531 if (!LRQ.isKill() && !LRQ.valueDefined())
532 discoverLiveOut(Reg);
535 increaseRegPressure(Reg);
536 LiveRegs.insert(Reg);
537 if (LiveUses && !containsReg(*LiveUses, Reg))
538 LiveUses->push_back(Reg);
541 if (TrackUntiedDefs) {
542 for (unsigned Reg : RegOpers.Defs) {
543 if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
544 UntiedDefs.insert(Reg);
549 void RegPressureTracker::recedeSkipDebugValues() {
550 assert(CurrPos != MBB->begin());
551 if (!isBottomClosed())
554 // Open the top of the region using block iterators.
555 if (!RequireIntervals && isTopClosed())
556 static_cast<RegionPressure&>(P).openTop(CurrPos);
558 // Find the previous instruction.
561 while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
564 if (RequireIntervals)
565 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
567 // Open the top of the region using slot indexes.
568 if (RequireIntervals && isTopClosed())
569 static_cast<IntervalPressure&>(P).openTop(SlotIdx);
572 void RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses) {
573 recedeSkipDebugValues();
575 const MachineInstr &MI = *CurrPos;
576 RegisterOperands RegOpers;
577 RegOpers.collect(MI, *TRI, *MRI);
578 if (RequireIntervals)
579 RegOpers.detectDeadDefs(MI, *LIS);
581 recede(RegOpers, LiveUses);
584 /// Advance across the current instruction.
585 void RegPressureTracker::advance() {
586 assert(!TrackUntiedDefs && "unsupported mode");
588 assert(CurrPos != MBB->end());
593 if (RequireIntervals)
594 SlotIdx = getCurrSlot();
596 // Open the bottom of the region using slot indexes.
597 if (isBottomClosed()) {
598 if (RequireIntervals)
599 static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
601 static_cast<RegionPressure&>(P).openBottom(CurrPos);
604 RegisterOperands RegOpers;
605 RegOpers.collect(*CurrPos, *TRI, *MRI);
607 for (unsigned Reg : RegOpers.Uses) {
608 // Discover live-ins.
609 bool isLive = LiveRegs.contains(Reg);
612 // Kill liveness at last uses.
613 bool lastUse = false;
614 if (RequireIntervals) {
615 const LiveRange *LR = getLiveRange(*LIS, Reg);
616 lastUse = LR && LR->Query(SlotIdx).isKill();
618 // Allocatable physregs are always single-use before register rewriting.
619 lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
621 if (lastUse && isLive) {
623 decreaseRegPressure(Reg);
624 } else if (!lastUse && !isLive)
625 increaseRegPressure(Reg);
628 // Generate liveness for defs.
629 for (unsigned Reg : RegOpers.Defs) {
630 if (LiveRegs.insert(Reg))
631 increaseRegPressure(Reg);
634 // Boost pressure for all dead defs together.
635 increaseRegPressure(RegOpers.DeadDefs);
636 decreaseRegPressure(RegOpers.DeadDefs);
638 // Find the next instruction.
641 while (CurrPos != MBB->end() && CurrPos->isDebugValue());
644 /// Find the max change in excess pressure across all sets.
645 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
646 ArrayRef<unsigned> NewPressureVec,
647 RegPressureDelta &Delta,
648 const RegisterClassInfo *RCI,
649 ArrayRef<unsigned> LiveThruPressureVec) {
650 Delta.Excess = PressureChange();
651 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
652 unsigned POld = OldPressureVec[i];
653 unsigned PNew = NewPressureVec[i];
654 int PDiff = (int)PNew - (int)POld;
655 if (!PDiff) // No change in this set in the common case.
657 // Only consider change beyond the limit.
658 unsigned Limit = RCI->getRegPressureSetLimit(i);
659 if (!LiveThruPressureVec.empty())
660 Limit += LiveThruPressureVec[i];
664 PDiff = 0; // Under the limit
666 PDiff = PNew - Limit; // Just exceeded limit.
667 } else if (Limit > PNew)
668 PDiff = Limit - POld; // Just obeyed limit.
671 Delta.Excess = PressureChange(i);
672 Delta.Excess.setUnitInc(PDiff);
678 /// Find the max change in max pressure that either surpasses a critical PSet
679 /// limit or exceeds the current MaxPressureLimit.
681 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
682 /// silly. It's done now to demonstrate the concept but will go away with a
683 /// RegPressureTracker API change to work with pressure differences.
684 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
685 ArrayRef<unsigned> NewMaxPressureVec,
686 ArrayRef<PressureChange> CriticalPSets,
687 ArrayRef<unsigned> MaxPressureLimit,
688 RegPressureDelta &Delta) {
689 Delta.CriticalMax = PressureChange();
690 Delta.CurrentMax = PressureChange();
692 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
693 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
694 unsigned POld = OldMaxPressureVec[i];
695 unsigned PNew = NewMaxPressureVec[i];
696 if (PNew == POld) // No change in this set in the common case.
699 if (!Delta.CriticalMax.isValid()) {
700 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
703 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
704 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
706 Delta.CriticalMax = PressureChange(i);
707 Delta.CriticalMax.setUnitInc(PDiff);
711 // Find the first increase above MaxPressureLimit.
712 // (Ignores negative MDiff).
713 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
714 Delta.CurrentMax = PressureChange(i);
715 Delta.CurrentMax.setUnitInc(PNew - POld);
716 if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
722 /// Record the upward impact of a single instruction on current register
723 /// pressure. Unlike the advance/recede pressure tracking interface, this does
724 /// not discover live in/outs.
726 /// This is intended for speculative queries. It leaves pressure inconsistent
727 /// with the current position, so must be restored by the caller.
728 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
729 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
731 // Account for register pressure similar to RegPressureTracker::recede().
732 RegisterOperands RegOpers;
733 RegOpers.collect(*MI, *TRI, *MRI, /*IgnoreDead=*/true);
734 assert(RegOpers.DeadDefs.size() == 0);
735 if (RequireIntervals)
736 RegOpers.detectDeadDefs(*MI, *LIS);
738 // Kill liveness at live defs.
739 for (unsigned Reg : RegOpers.Defs) {
740 if (!containsReg(RegOpers.Uses, Reg))
741 decreaseRegPressure(Reg);
743 // Generate liveness for uses.
744 for (unsigned Reg : RegOpers.Uses) {
745 if (!LiveRegs.contains(Reg))
746 increaseRegPressure(Reg);
750 /// Consider the pressure increase caused by traversing this instruction
751 /// bottom-up. Find the pressure set with the most change beyond its pressure
752 /// limit based on the tracker's current pressure, and return the change in
753 /// number of register units of that pressure set introduced by this
756 /// This assumes that the current LiveOut set is sufficient.
758 /// This is expensive for an on-the-fly query because it calls
759 /// bumpUpwardPressure to recompute the pressure sets based on current
760 /// liveness. This mainly exists to verify correctness, e.g. with
761 /// -verify-misched. getUpwardPressureDelta is the fast version of this query
762 /// that uses the per-SUnit cache of the PressureDiff.
763 void RegPressureTracker::
764 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
765 RegPressureDelta &Delta,
766 ArrayRef<PressureChange> CriticalPSets,
767 ArrayRef<unsigned> MaxPressureLimit) {
768 // Snapshot Pressure.
769 // FIXME: The snapshot heap space should persist. But I'm planning to
770 // summarize the pressure effect so we don't need to snapshot at all.
771 std::vector<unsigned> SavedPressure = CurrSetPressure;
772 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
774 bumpUpwardPressure(MI);
776 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
778 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
779 MaxPressureLimit, Delta);
780 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
781 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
783 // Restore the tracker's state.
784 P.MaxSetPressure.swap(SavedMaxPressure);
785 CurrSetPressure.swap(SavedPressure);
791 // Check if the alternate algorithm yields the same result.
792 RegPressureDelta Delta2;
793 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
794 if (Delta != Delta2) {
797 dbgs() << "DELTA: " << *MI;
798 if (Delta.Excess.isValid())
799 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
800 << " " << Delta.Excess.getUnitInc() << "\n";
801 if (Delta.CriticalMax.isValid())
802 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
803 << " " << Delta.CriticalMax.getUnitInc() << "\n";
804 if (Delta.CurrentMax.isValid())
805 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
806 << " " << Delta.CurrentMax.getUnitInc() << "\n";
807 if (Delta2.Excess.isValid())
808 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
809 << " " << Delta2.Excess.getUnitInc() << "\n";
810 if (Delta2.CriticalMax.isValid())
811 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
812 << " " << Delta2.CriticalMax.getUnitInc() << "\n";
813 if (Delta2.CurrentMax.isValid())
814 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
815 << " " << Delta2.CurrentMax.getUnitInc() << "\n";
816 llvm_unreachable("RegP Delta Mismatch");
821 /// This is the fast version of querying register pressure that does not
822 /// directly depend on current liveness.
824 /// @param Delta captures information needed for heuristics.
826 /// @param CriticalPSets Are the pressure sets that are known to exceed some
827 /// limit within the region, not necessarily at the current position.
829 /// @param MaxPressureLimit Is the max pressure within the region, not
830 /// necessarily at the current position.
831 void RegPressureTracker::
832 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
833 RegPressureDelta &Delta,
834 ArrayRef<PressureChange> CriticalPSets,
835 ArrayRef<unsigned> MaxPressureLimit) const {
836 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
837 for (PressureDiff::const_iterator
838 PDiffI = PDiff.begin(), PDiffE = PDiff.end();
839 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
841 unsigned PSetID = PDiffI->getPSet();
842 unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
843 if (!LiveThruPressure.empty())
844 Limit += LiveThruPressure[PSetID];
846 unsigned POld = CurrSetPressure[PSetID];
847 unsigned MOld = P.MaxSetPressure[PSetID];
848 unsigned MNew = MOld;
849 // Ignore DeadDefs here because they aren't captured by PressureChange.
850 unsigned PNew = POld + PDiffI->getUnitInc();
851 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld)
852 && "PSet overflow/underflow");
855 // Check if current pressure has exceeded the limit.
856 if (!Delta.Excess.isValid()) {
857 unsigned ExcessInc = 0;
859 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
860 else if (POld > Limit)
861 ExcessInc = Limit - POld;
863 Delta.Excess = PressureChange(PSetID);
864 Delta.Excess.setUnitInc(ExcessInc);
867 // Check if max pressure has exceeded a critical pressure set max.
870 if (!Delta.CriticalMax.isValid()) {
871 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
874 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
875 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
876 if (CritInc > 0 && CritInc <= INT16_MAX) {
877 Delta.CriticalMax = PressureChange(PSetID);
878 Delta.CriticalMax.setUnitInc(CritInc);
882 // Check if max pressure has exceeded the current max.
883 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
884 Delta.CurrentMax = PressureChange(PSetID);
885 Delta.CurrentMax.setUnitInc(MNew - MOld);
890 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
891 static bool findUseBetween(unsigned Reg, SlotIndex PriorUseIdx,
892 SlotIndex NextUseIdx, const MachineRegisterInfo &MRI,
893 const LiveIntervals *LIS) {
894 for (const MachineInstr &MI : MRI.use_nodbg_instructions(Reg)) {
895 SlotIndex InstSlot = LIS->getInstructionIndex(&MI).getRegSlot();
896 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
902 /// Record the downward impact of a single instruction on current register
903 /// pressure. Unlike the advance/recede pressure tracking interface, this does
904 /// not discover live in/outs.
906 /// This is intended for speculative queries. It leaves pressure inconsistent
907 /// with the current position, so must be restored by the caller.
908 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
909 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
911 // Account for register pressure similar to RegPressureTracker::recede().
912 RegisterOperands RegOpers;
913 RegOpers.collect(*MI, *TRI, *MRI);
915 // Kill liveness at last uses. Assume allocatable physregs are single-use
916 // rather than checking LiveIntervals.
918 if (RequireIntervals)
919 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
921 for (unsigned Reg : RegOpers.Uses) {
922 if (RequireIntervals) {
923 // FIXME: allow the caller to pass in the list of vreg uses that remain
924 // to be bottom-scheduled to avoid searching uses at each query.
925 SlotIndex CurrIdx = getCurrSlot();
926 const LiveRange *LR = getLiveRange(*LIS, Reg);
928 LiveQueryResult LRQ = LR->Query(SlotIdx);
929 if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, *MRI, LIS))
930 decreaseRegPressure(Reg);
932 } else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
933 // Allocatable physregs are always single-use before register rewriting.
934 decreaseRegPressure(Reg);
938 // Generate liveness for defs.
939 increaseRegPressure(RegOpers.Defs);
941 // Boost pressure for all dead defs together.
942 increaseRegPressure(RegOpers.DeadDefs);
943 decreaseRegPressure(RegOpers.DeadDefs);
946 /// Consider the pressure increase caused by traversing this instruction
947 /// top-down. Find the register class with the most change in its pressure limit
948 /// based on the tracker's current pressure, and return the number of excess
949 /// register units of that pressure set introduced by this instruction.
951 /// This assumes that the current LiveIn set is sufficient.
953 /// This is expensive for an on-the-fly query because it calls
954 /// bumpDownwardPressure to recompute the pressure sets based on current
955 /// liveness. We don't yet have a fast version of downward pressure tracking
956 /// analogous to getUpwardPressureDelta.
957 void RegPressureTracker::
958 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
959 ArrayRef<PressureChange> CriticalPSets,
960 ArrayRef<unsigned> MaxPressureLimit) {
961 // Snapshot Pressure.
962 std::vector<unsigned> SavedPressure = CurrSetPressure;
963 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
965 bumpDownwardPressure(MI);
967 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
969 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
970 MaxPressureLimit, Delta);
971 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
972 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
974 // Restore the tracker's state.
975 P.MaxSetPressure.swap(SavedMaxPressure);
976 CurrSetPressure.swap(SavedPressure);
979 /// Get the pressure of each PSet after traversing this instruction bottom-up.
980 void RegPressureTracker::
981 getUpwardPressure(const MachineInstr *MI,
982 std::vector<unsigned> &PressureResult,
983 std::vector<unsigned> &MaxPressureResult) {
984 // Snapshot pressure.
985 PressureResult = CurrSetPressure;
986 MaxPressureResult = P.MaxSetPressure;
988 bumpUpwardPressure(MI);
990 // Current pressure becomes the result. Restore current pressure.
991 P.MaxSetPressure.swap(MaxPressureResult);
992 CurrSetPressure.swap(PressureResult);
995 /// Get the pressure of each PSet after traversing this instruction top-down.
996 void RegPressureTracker::
997 getDownwardPressure(const MachineInstr *MI,
998 std::vector<unsigned> &PressureResult,
999 std::vector<unsigned> &MaxPressureResult) {
1000 // Snapshot pressure.
1001 PressureResult = CurrSetPressure;
1002 MaxPressureResult = P.MaxSetPressure;
1004 bumpDownwardPressure(MI);
1006 // Current pressure becomes the result. Restore current pressure.
1007 P.MaxSetPressure.swap(MaxPressureResult);
1008 CurrSetPressure.swap(PressureResult);