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 i = 0, e = LiveInRegs.size(); i < e; ++i)
63 dbgs() << PrintVRegOrUnit(LiveInRegs[i], TRI) << " ";
65 dbgs() << "Live Out: ";
66 for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i)
67 dbgs() << PrintVRegOrUnit(LiveOutRegs[i], 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 {
81 for (const PressureChange &Change : *this) {
82 if (!Change.isValid())
84 dbgs() << " " << TRI.getRegPressureSetName(Change.getPSet())
85 << " " << Change.getUnitInc();
90 /// Increase the current pressure as impacted by these registers and bump
91 /// the high water mark if needed.
92 void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) {
93 for (unsigned i = 0, e = RegUnits.size(); i != e; ++i) {
94 PSetIterator PSetI = MRI->getPressureSets(RegUnits[i]);
95 unsigned Weight = PSetI.getWeight();
96 for (; PSetI.isValid(); ++PSetI) {
97 CurrSetPressure[*PSetI] += Weight;
98 if (CurrSetPressure[*PSetI] > P.MaxSetPressure[*PSetI]) {
99 P.MaxSetPressure[*PSetI] = CurrSetPressure[*PSetI];
105 /// Simply decrease the current pressure as impacted by these registers.
106 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) {
107 for (unsigned I = 0, E = RegUnits.size(); I != E; ++I)
108 decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnits[I]));
111 /// Clear the result so it can be used for another round of pressure tracking.
112 void IntervalPressure::reset() {
113 TopIdx = BottomIdx = SlotIndex();
114 MaxSetPressure.clear();
119 /// Clear the result so it can be used for another round of pressure tracking.
120 void RegionPressure::reset() {
121 TopPos = BottomPos = MachineBasicBlock::const_iterator();
122 MaxSetPressure.clear();
127 /// If the current top is not less than or equal to the next index, open it.
128 /// We happen to need the SlotIndex for the next top for pressure update.
129 void IntervalPressure::openTop(SlotIndex NextTop) {
130 if (TopIdx <= NextTop)
132 TopIdx = SlotIndex();
136 /// If the current top is the previous instruction (before receding), open it.
137 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
138 if (TopPos != PrevTop)
140 TopPos = MachineBasicBlock::const_iterator();
144 /// If the current bottom is not greater than the previous index, open it.
145 void IntervalPressure::openBottom(SlotIndex PrevBottom) {
146 if (BottomIdx > PrevBottom)
148 BottomIdx = SlotIndex();
152 /// If the current bottom is the previous instr (before advancing), open it.
153 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
154 if (BottomPos != PrevBottom)
156 BottomPos = MachineBasicBlock::const_iterator();
160 void LiveRegSet::init(const MachineRegisterInfo &MRI) {
161 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
162 unsigned NumRegUnits = TRI.getNumRegs();
163 unsigned NumVirtRegs = MRI.getNumVirtRegs();
164 Regs.setUniverse(NumRegUnits + NumVirtRegs);
165 this->NumRegUnits = NumRegUnits;
168 void LiveRegSet::clear() {
172 const LiveRange *RegPressureTracker::getLiveRange(unsigned Reg) const {
173 if (TargetRegisterInfo::isVirtualRegister(Reg))
174 return &LIS->getInterval(Reg);
175 return LIS->getCachedRegUnit(Reg);
178 void RegPressureTracker::reset() {
182 CurrSetPressure.clear();
183 LiveThruPressure.clear();
184 P.MaxSetPressure.clear();
186 if (RequireIntervals)
187 static_cast<IntervalPressure&>(P).reset();
189 static_cast<RegionPressure&>(P).reset();
195 /// Setup the RegPressureTracker.
197 /// TODO: Add support for pressure without LiveIntervals.
198 void RegPressureTracker::init(const MachineFunction *mf,
199 const RegisterClassInfo *rci,
200 const LiveIntervals *lis,
201 const MachineBasicBlock *mbb,
202 MachineBasicBlock::const_iterator pos,
203 bool ShouldTrackUntiedDefs)
208 TRI = MF->getSubtarget().getRegisterInfo();
210 MRI = &MF->getRegInfo();
212 TrackUntiedDefs = ShouldTrackUntiedDefs;
214 if (RequireIntervals) {
215 assert(lis && "IntervalPressure requires LiveIntervals");
220 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
222 P.MaxSetPressure = CurrSetPressure;
226 UntiedDefs.setUniverse(MRI->getNumVirtRegs());
229 /// Does this pressure result have a valid top position and live ins.
230 bool RegPressureTracker::isTopClosed() const {
231 if (RequireIntervals)
232 return static_cast<IntervalPressure&>(P).TopIdx.isValid();
233 return (static_cast<RegionPressure&>(P).TopPos ==
234 MachineBasicBlock::const_iterator());
237 /// Does this pressure result have a valid bottom position and live outs.
238 bool RegPressureTracker::isBottomClosed() const {
239 if (RequireIntervals)
240 return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
241 return (static_cast<RegionPressure&>(P).BottomPos ==
242 MachineBasicBlock::const_iterator());
246 SlotIndex RegPressureTracker::getCurrSlot() const {
247 MachineBasicBlock::const_iterator IdxPos = CurrPos;
248 while (IdxPos != MBB->end() && IdxPos->isDebugValue())
250 if (IdxPos == MBB->end())
251 return LIS->getMBBEndIdx(MBB);
252 return LIS->getInstructionIndex(IdxPos).getRegSlot();
255 /// Set the boundary for the top of the region and summarize live ins.
256 void RegPressureTracker::closeTop() {
257 if (RequireIntervals)
258 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
260 static_cast<RegionPressure&>(P).TopPos = CurrPos;
262 assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
263 P.LiveInRegs.reserve(LiveRegs.size());
264 LiveRegs.appendTo(P.LiveInRegs);
267 /// Set the boundary for the bottom of the region and summarize live outs.
268 void RegPressureTracker::closeBottom() {
269 if (RequireIntervals)
270 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
272 static_cast<RegionPressure&>(P).BottomPos = CurrPos;
274 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
275 P.LiveOutRegs.reserve(LiveRegs.size());
276 LiveRegs.appendTo(P.LiveOutRegs);
279 /// Finalize the region boundaries and record live ins and live outs.
280 void RegPressureTracker::closeRegion() {
281 if (!isTopClosed() && !isBottomClosed()) {
282 assert(LiveRegs.size() == 0 && "no region boundary");
285 if (!isBottomClosed())
287 else if (!isTopClosed())
289 // If both top and bottom are closed, do nothing.
292 /// The register tracker is unaware of global liveness so ignores normal
293 /// live-thru ranges. However, two-address or coalesced chains can also lead
294 /// to live ranges with no holes. Count these to inform heuristics that we
295 /// can never drop below this pressure.
296 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
297 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
298 assert(isBottomClosed() && "need bottom-up tracking to intialize.");
299 for (unsigned i = 0, e = P.LiveOutRegs.size(); i < e; ++i) {
300 unsigned Reg = P.LiveOutRegs[i];
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();
315 /// Collect this instruction's unique uses and defs into SmallVectors for
316 /// processing defs and uses in order.
318 /// FIXME: always ignore tied opers
319 class RegisterOperands {
320 const TargetRegisterInfo *TRI;
321 const MachineRegisterInfo *MRI;
325 SmallVector<unsigned, 8> Uses;
326 SmallVector<unsigned, 8> Defs;
327 SmallVector<unsigned, 8> DeadDefs;
329 RegisterOperands(const TargetRegisterInfo *tri,
330 const MachineRegisterInfo *mri, bool ID = false):
331 TRI(tri), MRI(mri), IgnoreDead(ID) {}
333 /// Push this operand's register onto the correct vector.
334 void collect(const MachineOperand &MO) {
335 if (!MO.isReg() || !MO.getReg())
338 pushRegUnits(MO.getReg(), Uses);
342 pushRegUnits(MO.getReg(), DeadDefs);
345 pushRegUnits(MO.getReg(), Defs);
350 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
351 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
352 if (containsReg(RegUnits, Reg))
354 RegUnits.push_back(Reg);
356 else if (MRI->isAllocatable(Reg)) {
357 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
358 if (containsReg(RegUnits, *Units))
360 RegUnits.push_back(*Units);
367 /// Collect physical and virtual register operands.
368 static void collectOperands(const MachineInstr *MI,
369 RegisterOperands &RegOpers) {
370 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
371 RegOpers.collect(*OperI);
373 // Remove redundant physreg dead defs.
374 SmallVectorImpl<unsigned>::iterator I =
375 std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
376 std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
377 RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
380 /// Initialize an array of N PressureDiffs.
381 void PressureDiffs::init(unsigned N) {
384 memset(PDiffArray, 0, N * sizeof(PressureDiff));
389 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
392 /// Add a change in pressure to the pressure diff of a given instruction.
393 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
394 const MachineRegisterInfo *MRI) {
395 PSetIterator PSetI = MRI->getPressureSets(RegUnit);
396 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
397 for (; PSetI.isValid(); ++PSetI) {
398 // Find an existing entry in the pressure diff for this PSet.
399 PressureDiff::iterator I = nonconst_begin(), E = nonconst_end();
400 for (; I != E && I->isValid(); ++I) {
401 if (I->getPSet() >= *PSetI)
404 // If all pressure sets are more constrained, skip the remaining PSets.
407 // Insert this PressureChange.
408 if (!I->isValid() || I->getPSet() != *PSetI) {
409 PressureChange PTmp = PressureChange(*PSetI);
410 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
413 // Update the units for this pressure set.
414 unsigned NewUnitInc = I->getUnitInc() + Weight;
415 if (NewUnitInc != 0) {
416 I->setUnitInc(NewUnitInc);
419 PressureDiff::iterator J;
420 for (J = std::next(I); J != E && J->isValid(); ++J, ++I)
428 /// Record the pressure difference induced by the given operand list.
429 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
430 const MachineRegisterInfo *MRI) {
431 assert(!PDiff.begin()->isValid() && "stale PDiff");
433 for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
434 PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
436 for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
437 PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
440 /// Force liveness of registers.
441 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
442 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
443 if (LiveRegs.insert(Regs[i]))
444 increaseRegPressure(Regs[i]);
448 /// Add Reg to the live in set and increase max pressure.
449 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
450 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
451 if (containsReg(P.LiveInRegs, Reg))
454 // At live in discovery, unconditionally increase the high water mark.
455 P.LiveInRegs.push_back(Reg);
456 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
459 /// Add Reg to the live out set and increase max pressure.
460 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
461 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
462 if (containsReg(P.LiveOutRegs, Reg))
465 // At live out discovery, unconditionally increase the high water mark.
466 P.LiveOutRegs.push_back(Reg);
467 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
470 /// Recede across the previous instruction. If LiveUses is provided, record any
471 /// RegUnits that are made live by the current instruction's uses. This includes
472 /// registers that are both defined and used by the instruction. If a pressure
473 /// difference pointer is provided record the changes is pressure caused by this
474 /// instruction independent of liveness.
475 bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
476 PressureDiff *PDiff) {
477 // Check for the top of the analyzable region.
478 if (CurrPos == MBB->begin()) {
482 if (!isBottomClosed())
485 // Open the top of the region using block iterators.
486 if (!RequireIntervals && isTopClosed())
487 static_cast<RegionPressure&>(P).openTop(CurrPos);
489 // Find the previous instruction.
492 while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
494 if (CurrPos->isDebugValue()) {
499 if (RequireIntervals)
500 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
502 // Open the top of the region using slot indexes.
503 if (RequireIntervals && isTopClosed())
504 static_cast<IntervalPressure&>(P).openTop(SlotIdx);
506 RegisterOperands RegOpers(TRI, MRI);
507 collectOperands(CurrPos, RegOpers);
510 collectPDiff(*PDiff, RegOpers, MRI);
512 // Boost pressure for all dead defs together.
513 increaseRegPressure(RegOpers.DeadDefs);
514 decreaseRegPressure(RegOpers.DeadDefs);
516 // Kill liveness at live defs.
517 // TODO: consider earlyclobbers?
518 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
519 unsigned Reg = RegOpers.Defs[i];
520 bool DeadDef = false;
521 if (RequireIntervals) {
522 const LiveRange *LR = getLiveRange(Reg);
524 LiveQueryResult LRQ = LR->Query(SlotIdx);
525 DeadDef = LRQ.isDeadDef();
529 // LiveIntervals knows this is a dead even though it's MachineOperand is
530 // not flagged as such. Since this register will not be recorded as
531 // live-out, increase its PDiff value to avoid underflowing pressure.
533 PDiff->addPressureChange(Reg, false, MRI);
535 if (LiveRegs.erase(Reg))
536 decreaseRegPressure(Reg);
538 discoverLiveOut(Reg);
542 // Generate liveness for uses.
543 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
544 unsigned Reg = RegOpers.Uses[i];
545 if (!LiveRegs.contains(Reg)) {
546 // Adjust liveouts if LiveIntervals are available.
547 if (RequireIntervals) {
548 const LiveRange *LR = getLiveRange(Reg);
550 LiveQueryResult LRQ = LR->Query(SlotIdx);
551 if (!LRQ.isKill() && !LRQ.valueDefined())
552 discoverLiveOut(Reg);
555 increaseRegPressure(Reg);
556 LiveRegs.insert(Reg);
557 if (LiveUses && !containsReg(*LiveUses, Reg))
558 LiveUses->push_back(Reg);
561 if (TrackUntiedDefs) {
562 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
563 unsigned Reg = RegOpers.Defs[i];
564 if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
565 UntiedDefs.insert(Reg);
571 bool RegPressureTracker::isLastUse(unsigned VRegOrUnit, SlotIndex Pos) const {
572 // Allocatable physregs are always single-use before register rewriting.
573 if (!TargetRegisterInfo::isVirtualRegister(VRegOrUnit))
575 // Without liveness information we conservatively assume "no last use".
576 if (!RequireIntervals)
578 const LiveRange *LR = getLiveRange(VRegOrUnit);
579 return LR && LR->Query(Pos).isKill();
582 /// Advance across the current instruction.
583 bool RegPressureTracker::advance() {
584 assert(!TrackUntiedDefs && "unsupported mode");
586 // Check for the bottom of the analyzable region.
587 if (CurrPos == MBB->end()) {
595 if (RequireIntervals)
596 SlotIdx = getCurrSlot();
598 // Open the bottom of the region using slot indexes.
599 if (isBottomClosed()) {
600 if (RequireIntervals)
601 static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
603 static_cast<RegionPressure&>(P).openBottom(CurrPos);
606 RegisterOperands RegOpers(TRI, MRI);
607 collectOperands(CurrPos, RegOpers);
609 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
610 unsigned Reg = RegOpers.Uses[i];
611 // Discover live-ins.
612 bool isLive = LiveRegs.contains(Reg);
615 // Kill liveness at last uses.
616 if (isLastUse(Reg, SlotIdx)) {
619 decreaseRegPressure(Reg);
622 // We discovered a live which was not last used here, adjust pressure.
623 increaseRegPressure(Reg);
627 // Generate liveness for defs.
628 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
629 unsigned Reg = RegOpers.Defs[i];
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());
645 /// Find the max change in excess pressure across all sets.
646 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
647 ArrayRef<unsigned> NewPressureVec,
648 RegPressureDelta &Delta,
649 const RegisterClassInfo *RCI,
650 ArrayRef<unsigned> LiveThruPressureVec) {
651 Delta.Excess = PressureChange();
652 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
653 unsigned POld = OldPressureVec[i];
654 unsigned PNew = NewPressureVec[i];
655 int PDiff = (int)PNew - (int)POld;
656 if (!PDiff) // No change in this set in the common case.
658 // Only consider change beyond the limit.
659 unsigned Limit = RCI->getRegPressureSetLimit(i);
660 if (!LiveThruPressureVec.empty())
661 Limit += LiveThruPressureVec[i];
665 PDiff = 0; // Under the limit
667 PDiff = PNew - Limit; // Just exceeded limit.
669 else if (Limit > PNew)
670 PDiff = Limit - POld; // Just obeyed limit.
673 Delta.Excess = PressureChange(i);
674 Delta.Excess.setUnitInc(PDiff);
680 /// Find the max change in max pressure that either surpasses a critical PSet
681 /// limit or exceeds the current MaxPressureLimit.
683 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
684 /// silly. It's done now to demonstrate the concept but will go away with a
685 /// RegPressureTracker API change to work with pressure differences.
686 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
687 ArrayRef<unsigned> NewMaxPressureVec,
688 ArrayRef<PressureChange> CriticalPSets,
689 ArrayRef<unsigned> MaxPressureLimit,
690 RegPressureDelta &Delta) {
691 Delta.CriticalMax = PressureChange();
692 Delta.CurrentMax = PressureChange();
694 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
695 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
696 unsigned POld = OldMaxPressureVec[i];
697 unsigned PNew = NewMaxPressureVec[i];
698 if (PNew == POld) // No change in this set in the common case.
701 if (!Delta.CriticalMax.isValid()) {
702 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
705 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
706 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
708 Delta.CriticalMax = PressureChange(i);
709 Delta.CriticalMax.setUnitInc(PDiff);
713 // Find the first increase above MaxPressureLimit.
714 // (Ignores negative MDiff).
715 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
716 Delta.CurrentMax = PressureChange(i);
717 Delta.CurrentMax.setUnitInc(PNew - POld);
718 if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
724 /// Record the upward impact of a single instruction on current register
725 /// pressure. Unlike the advance/recede pressure tracking interface, this does
726 /// not discover live in/outs.
728 /// This is intended for speculative queries. It leaves pressure inconsistent
729 /// with the current position, so must be restored by the caller.
730 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
731 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
733 // Account for register pressure similar to RegPressureTracker::recede().
734 RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
735 collectOperands(MI, RegOpers);
737 // Boost max pressure for all dead defs together.
738 // Since CurrSetPressure and MaxSetPressure
739 increaseRegPressure(RegOpers.DeadDefs);
740 decreaseRegPressure(RegOpers.DeadDefs);
742 // Kill liveness at live defs.
743 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
744 unsigned Reg = RegOpers.Defs[i];
745 bool DeadDef = false;
746 if (RequireIntervals) {
747 const LiveRange *LR = getLiveRange(Reg);
749 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
750 LiveQueryResult LRQ = LR->Query(SlotIdx);
751 DeadDef = LRQ.isDeadDef();
755 if (!containsReg(RegOpers.Uses, Reg))
756 decreaseRegPressure(Reg);
759 // Generate liveness for uses.
760 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
761 unsigned Reg = RegOpers.Uses[i];
762 if (!LiveRegs.contains(Reg))
763 increaseRegPressure(Reg);
767 /// Consider the pressure increase caused by traversing this instruction
768 /// bottom-up. Find the pressure set with the most change beyond its pressure
769 /// limit based on the tracker's current pressure, and return the change in
770 /// number of register units of that pressure set introduced by this
773 /// This assumes that the current LiveOut set is sufficient.
775 /// This is expensive for an on-the-fly query because it calls
776 /// bumpUpwardPressure to recompute the pressure sets based on current
777 /// liveness. This mainly exists to verify correctness, e.g. with
778 /// -verify-misched. getUpwardPressureDelta is the fast version of this query
779 /// that uses the per-SUnit cache of the PressureDiff.
780 void RegPressureTracker::
781 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
782 RegPressureDelta &Delta,
783 ArrayRef<PressureChange> CriticalPSets,
784 ArrayRef<unsigned> MaxPressureLimit) {
785 // Snapshot Pressure.
786 // FIXME: The snapshot heap space should persist. But I'm planning to
787 // summarize the pressure effect so we don't need to snapshot at all.
788 std::vector<unsigned> SavedPressure = CurrSetPressure;
789 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
791 bumpUpwardPressure(MI);
793 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
795 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
796 MaxPressureLimit, Delta);
797 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
798 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
800 // Restore the tracker's state.
801 P.MaxSetPressure.swap(SavedMaxPressure);
802 CurrSetPressure.swap(SavedPressure);
808 // Check if the alternate algorithm yields the same result.
809 RegPressureDelta Delta2;
810 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
811 if (Delta != Delta2) {
814 dbgs() << "DELTA: " << *MI;
815 if (Delta.Excess.isValid())
816 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
817 << " " << Delta.Excess.getUnitInc() << "\n";
818 if (Delta.CriticalMax.isValid())
819 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
820 << " " << Delta.CriticalMax.getUnitInc() << "\n";
821 if (Delta.CurrentMax.isValid())
822 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
823 << " " << Delta.CurrentMax.getUnitInc() << "\n";
824 if (Delta2.Excess.isValid())
825 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
826 << " " << Delta2.Excess.getUnitInc() << "\n";
827 if (Delta2.CriticalMax.isValid())
828 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
829 << " " << Delta2.CriticalMax.getUnitInc() << "\n";
830 if (Delta2.CurrentMax.isValid())
831 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
832 << " " << Delta2.CurrentMax.getUnitInc() << "\n";
833 llvm_unreachable("RegP Delta Mismatch");
838 /// This is the fast version of querying register pressure that does not
839 /// directly depend on current liveness.
841 /// @param Delta captures information needed for heuristics.
843 /// @param CriticalPSets Are the pressure sets that are known to exceed some
844 /// limit within the region, not necessarily at the current position.
846 /// @param MaxPressureLimit Is the max pressure within the region, not
847 /// necessarily at the current position.
848 void RegPressureTracker::
849 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
850 RegPressureDelta &Delta,
851 ArrayRef<PressureChange> CriticalPSets,
852 ArrayRef<unsigned> MaxPressureLimit) const {
853 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
854 for (PressureDiff::const_iterator
855 PDiffI = PDiff.begin(), PDiffE = PDiff.end();
856 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
858 unsigned PSetID = PDiffI->getPSet();
859 unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
860 if (!LiveThruPressure.empty())
861 Limit += LiveThruPressure[PSetID];
863 unsigned POld = CurrSetPressure[PSetID];
864 unsigned MOld = P.MaxSetPressure[PSetID];
865 unsigned MNew = MOld;
866 // Ignore DeadDefs here because they aren't captured by PressureChange.
867 unsigned PNew = POld + PDiffI->getUnitInc();
868 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
871 // Check if current pressure has exceeded the limit.
872 if (!Delta.Excess.isValid()) {
873 unsigned ExcessInc = 0;
875 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
876 else if (POld > Limit)
877 ExcessInc = Limit - POld;
879 Delta.Excess = PressureChange(PSetID);
880 Delta.Excess.setUnitInc(ExcessInc);
883 // Check if max pressure has exceeded a critical pressure set max.
886 if (!Delta.CriticalMax.isValid()) {
887 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
890 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
891 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
892 if (CritInc > 0 && CritInc <= INT16_MAX) {
893 Delta.CriticalMax = PressureChange(PSetID);
894 Delta.CriticalMax.setUnitInc(CritInc);
898 // Check if max pressure has exceeded the current max.
899 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
900 Delta.CurrentMax = PressureChange(PSetID);
901 Delta.CurrentMax.setUnitInc(MNew - MOld);
906 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
907 static bool findUseBetween(unsigned Reg, SlotIndex PriorUseIdx,
908 SlotIndex NextUseIdx, const MachineRegisterInfo &MRI,
909 const LiveIntervals *LIS) {
910 for (const MachineInstr &MI : MRI.use_nodbg_instructions(Reg)) {
911 SlotIndex InstSlot = LIS->getInstructionIndex(&MI).getRegSlot();
912 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
918 /// Record the downward impact of a single instruction on current register
919 /// pressure. Unlike the advance/recede pressure tracking interface, this does
920 /// not discover live in/outs.
922 /// This is intended for speculative queries. It leaves pressure inconsistent
923 /// with the current position, so must be restored by the caller.
924 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
925 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
927 // Account for register pressure similar to RegPressureTracker::recede().
928 RegisterOperands RegOpers(TRI, MRI);
929 collectOperands(MI, RegOpers);
931 // Kill liveness at last uses. Assume allocatable physregs are single-use
932 // rather than checking LiveIntervals.
934 if (RequireIntervals)
935 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
937 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
938 unsigned Reg = RegOpers.Uses[i];
939 bool IsLastUse = isLastUse(Reg, SlotIdx);
940 // We had a last use at MIs position. To know the situation for the current
941 // position we have to check if there exist other uses in between.
942 if (IsLastUse && TargetRegisterInfo::isVirtualRegister(Reg)) {
943 SlotIndex CurrIdx = getCurrSlot();
944 // FIXME: allow the caller to pass in the list of vreg uses that remain
945 // to be bottom-scheduled to avoid searching uses at each query.
946 if (findUseBetween(Reg, CurrIdx, SlotIdx, *MRI, LIS))
950 decreaseRegPressure(Reg);
953 // Generate liveness for defs.
954 increaseRegPressure(RegOpers.Defs);
956 // Boost pressure for all dead defs together.
957 increaseRegPressure(RegOpers.DeadDefs);
958 decreaseRegPressure(RegOpers.DeadDefs);
961 /// Consider the pressure increase caused by traversing this instruction
962 /// top-down. Find the register class with the most change in its pressure limit
963 /// based on the tracker's current pressure, and return the number of excess
964 /// register units of that pressure set introduced by this instruction.
966 /// This assumes that the current LiveIn set is sufficient.
968 /// This is expensive for an on-the-fly query because it calls
969 /// bumpDownwardPressure to recompute the pressure sets based on current
970 /// liveness. We don't yet have a fast version of downward pressure tracking
971 /// analogous to getUpwardPressureDelta.
972 void RegPressureTracker::
973 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
974 ArrayRef<PressureChange> CriticalPSets,
975 ArrayRef<unsigned> MaxPressureLimit) {
976 // Snapshot Pressure.
977 std::vector<unsigned> SavedPressure = CurrSetPressure;
978 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
980 bumpDownwardPressure(MI);
982 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
984 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
985 MaxPressureLimit, Delta);
986 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
987 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
989 // Restore the tracker's state.
990 P.MaxSetPressure.swap(SavedMaxPressure);
991 CurrSetPressure.swap(SavedPressure);
994 /// Get the pressure of each PSet after traversing this instruction bottom-up.
995 void RegPressureTracker::
996 getUpwardPressure(const MachineInstr *MI,
997 std::vector<unsigned> &PressureResult,
998 std::vector<unsigned> &MaxPressureResult) {
999 // Snapshot pressure.
1000 PressureResult = CurrSetPressure;
1001 MaxPressureResult = P.MaxSetPressure;
1003 bumpUpwardPressure(MI);
1005 // Current pressure becomes the result. Restore current pressure.
1006 P.MaxSetPressure.swap(MaxPressureResult);
1007 CurrSetPressure.swap(PressureResult);
1010 /// Get the pressure of each PSet after traversing this instruction top-down.
1011 void RegPressureTracker::
1012 getDownwardPressure(const MachineInstr *MI,
1013 std::vector<unsigned> &PressureResult,
1014 std::vector<unsigned> &MaxPressureResult) {
1015 // Snapshot pressure.
1016 PressureResult = CurrSetPressure;
1017 MaxPressureResult = P.MaxSetPressure;
1019 bumpDownwardPressure(MI);
1021 // Current pressure becomes the result. Restore current pressure.
1022 P.MaxSetPressure.swap(MaxPressureResult);
1023 CurrSetPressure.swap(PressureResult);