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 if (CurrSetPressure[*PSetI] > P.MaxSetPressure[*PSetI]) {
101 P.MaxSetPressure[*PSetI] = CurrSetPressure[*PSetI];
107 /// Simply decrease the current pressure as impacted by these registers.
108 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) {
109 for (unsigned RegUnit : RegUnits)
110 decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnit));
113 /// Clear the result so it can be used for another round of pressure tracking.
114 void IntervalPressure::reset() {
115 TopIdx = BottomIdx = SlotIndex();
116 MaxSetPressure.clear();
121 /// Clear the result so it can be used for another round of pressure tracking.
122 void RegionPressure::reset() {
123 TopPos = BottomPos = MachineBasicBlock::const_iterator();
124 MaxSetPressure.clear();
129 /// If the current top is not less than or equal to the next index, open it.
130 /// We happen to need the SlotIndex for the next top for pressure update.
131 void IntervalPressure::openTop(SlotIndex NextTop) {
132 if (TopIdx <= NextTop)
134 TopIdx = SlotIndex();
138 /// If the current top is the previous instruction (before receding), open it.
139 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
140 if (TopPos != PrevTop)
142 TopPos = MachineBasicBlock::const_iterator();
146 /// If the current bottom is not greater than the previous index, open it.
147 void IntervalPressure::openBottom(SlotIndex PrevBottom) {
148 if (BottomIdx > PrevBottom)
150 BottomIdx = SlotIndex();
154 /// If the current bottom is the previous instr (before advancing), open it.
155 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
156 if (BottomPos != PrevBottom)
158 BottomPos = MachineBasicBlock::const_iterator();
162 void LiveRegSet::init(const MachineRegisterInfo &MRI) {
163 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
164 unsigned NumRegUnits = TRI.getNumRegs();
165 unsigned NumVirtRegs = MRI.getNumVirtRegs();
166 Regs.setUniverse(NumRegUnits + NumVirtRegs);
167 this->NumRegUnits = NumRegUnits;
170 void LiveRegSet::clear() {
174 static const LiveRange *getLiveRange(const LiveIntervals &LIS, unsigned Reg) {
175 if (TargetRegisterInfo::isVirtualRegister(Reg))
176 return &LIS.getInterval(Reg);
177 return LIS.getCachedRegUnit(Reg);
180 void RegPressureTracker::reset() {
184 CurrSetPressure.clear();
185 LiveThruPressure.clear();
186 P.MaxSetPressure.clear();
188 if (RequireIntervals)
189 static_cast<IntervalPressure&>(P).reset();
191 static_cast<RegionPressure&>(P).reset();
197 /// Setup the RegPressureTracker.
199 /// TODO: Add support for pressure without LiveIntervals.
200 void RegPressureTracker::init(const MachineFunction *mf,
201 const RegisterClassInfo *rci,
202 const LiveIntervals *lis,
203 const MachineBasicBlock *mbb,
204 MachineBasicBlock::const_iterator pos,
205 bool ShouldTrackUntiedDefs)
210 TRI = MF->getSubtarget().getRegisterInfo();
212 MRI = &MF->getRegInfo();
214 TrackUntiedDefs = ShouldTrackUntiedDefs;
216 if (RequireIntervals) {
217 assert(lis && "IntervalPressure requires LiveIntervals");
222 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
224 P.MaxSetPressure = CurrSetPressure;
228 UntiedDefs.setUniverse(MRI->getNumVirtRegs());
231 /// Does this pressure result have a valid top position and live ins.
232 bool RegPressureTracker::isTopClosed() const {
233 if (RequireIntervals)
234 return static_cast<IntervalPressure&>(P).TopIdx.isValid();
235 return (static_cast<RegionPressure&>(P).TopPos ==
236 MachineBasicBlock::const_iterator());
239 /// Does this pressure result have a valid bottom position and live outs.
240 bool RegPressureTracker::isBottomClosed() const {
241 if (RequireIntervals)
242 return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
243 return (static_cast<RegionPressure&>(P).BottomPos ==
244 MachineBasicBlock::const_iterator());
248 SlotIndex RegPressureTracker::getCurrSlot() const {
249 MachineBasicBlock::const_iterator IdxPos = CurrPos;
250 while (IdxPos != MBB->end() && IdxPos->isDebugValue())
252 if (IdxPos == MBB->end())
253 return LIS->getMBBEndIdx(MBB);
254 return LIS->getInstructionIndex(IdxPos).getRegSlot();
257 /// Set the boundary for the top of the region and summarize live ins.
258 void RegPressureTracker::closeTop() {
259 if (RequireIntervals)
260 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
262 static_cast<RegionPressure&>(P).TopPos = CurrPos;
264 assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
265 P.LiveInRegs.reserve(LiveRegs.size());
266 LiveRegs.appendTo(P.LiveInRegs);
269 /// Set the boundary for the bottom of the region and summarize live outs.
270 void RegPressureTracker::closeBottom() {
271 if (RequireIntervals)
272 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
274 static_cast<RegionPressure&>(P).BottomPos = CurrPos;
276 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
277 P.LiveOutRegs.reserve(LiveRegs.size());
278 LiveRegs.appendTo(P.LiveOutRegs);
281 /// Finalize the region boundaries and record live ins and live outs.
282 void RegPressureTracker::closeRegion() {
283 if (!isTopClosed() && !isBottomClosed()) {
284 assert(LiveRegs.size() == 0 && "no region boundary");
287 if (!isBottomClosed())
289 else if (!isTopClosed())
291 // If both top and bottom are closed, do nothing.
294 /// The register tracker is unaware of global liveness so ignores normal
295 /// live-thru ranges. However, two-address or coalesced chains can also lead
296 /// to live ranges with no holes. Count these to inform heuristics that we
297 /// can never drop below this pressure.
298 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
299 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
300 assert(isBottomClosed() && "need bottom-up tracking to intialize.");
301 for (unsigned Reg : P.LiveOutRegs) {
302 if (TargetRegisterInfo::isVirtualRegister(Reg)
303 && !RPTracker.hasUntiedDef(Reg)) {
304 increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg));
309 /// \brief Convenient wrapper for checking membership in RegisterOperands.
310 /// (std::count() doesn't have an early exit).
311 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
312 return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
317 /// List of register defined and used by a machine instruction.
318 class RegisterOperands {
320 SmallVector<unsigned, 8> Uses;
321 SmallVector<unsigned, 8> Defs;
322 SmallVector<unsigned, 8> DeadDefs;
324 void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI,
325 const MachineRegisterInfo &MRI, bool IgnoreDead = false);
327 /// Use liveness information to find dead defs not marked with a dead flag
328 /// and move them to the DeadDefs vector.
329 void detectDeadDefs(const MachineInstr &MI, const LiveIntervals &LIS);
332 /// Collect this instruction's unique uses and defs into SmallVectors for
333 /// processing defs and uses in order.
335 /// FIXME: always ignore tied opers
336 class RegisterOperandsCollector {
337 RegisterOperands &RegOpers;
338 const TargetRegisterInfo &TRI;
339 const MachineRegisterInfo &MRI;
342 RegisterOperandsCollector(RegisterOperands &RegOpers,
343 const TargetRegisterInfo &TRI,
344 const MachineRegisterInfo &MRI,
346 : RegOpers(RegOpers), TRI(TRI), MRI(MRI), IgnoreDead(IgnoreDead) {}
348 void collectInstr(const MachineInstr &MI) const {
349 for (ConstMIBundleOperands OperI(&MI); OperI.isValid(); ++OperI)
350 collectOperand(*OperI);
352 // Remove redundant physreg dead defs.
353 SmallVectorImpl<unsigned>::iterator I =
354 std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
355 std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
356 RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
359 /// Push this operand's register onto the correct vectors.
360 void collectOperand(const MachineOperand &MO) const {
361 if (!MO.isReg() || !MO.getReg())
363 unsigned Reg = MO.getReg();
365 pushRegUnits(Reg, RegOpers.Uses);
369 pushRegUnits(Reg, RegOpers.DeadDefs);
371 pushRegUnits(Reg, RegOpers.Defs);
375 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) const {
376 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
377 if (containsReg(RegUnits, Reg))
379 RegUnits.push_back(Reg);
380 } else if (MRI.isAllocatable(Reg)) {
381 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) {
382 if (containsReg(RegUnits, *Units))
384 RegUnits.push_back(*Units);
389 friend class RegisterOperands;
392 void RegisterOperands::collect(const MachineInstr &MI,
393 const TargetRegisterInfo &TRI,
394 const MachineRegisterInfo &MRI,
396 RegisterOperandsCollector Collector(*this, TRI, MRI, IgnoreDead);
397 Collector.collectInstr(MI);
400 void RegisterOperands::detectDeadDefs(const MachineInstr &MI,
401 const LiveIntervals &LIS) {
402 SlotIndex SlotIdx = LIS.getInstructionIndex(&MI);
403 for (SmallVectorImpl<unsigned>::iterator RI = Defs.begin();
404 RI != Defs.end(); /*empty*/) {
406 const LiveRange *LR = getLiveRange(LIS, Reg);
408 LiveQueryResult LRQ = LR->Query(SlotIdx);
409 if (LRQ.isDeadDef()) {
410 // LiveIntervals knows this is a dead even though it's MachineOperand is
411 // not flagged as such.
412 DeadDefs.push_back(Reg);
423 /// Initialize an array of N PressureDiffs.
424 void PressureDiffs::init(unsigned N) {
427 memset(PDiffArray, 0, N * sizeof(PressureDiff));
432 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
435 /// Add a change in pressure to the pressure diff of a given instruction.
436 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
437 const MachineRegisterInfo *MRI) {
438 PSetIterator PSetI = MRI->getPressureSets(RegUnit);
439 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
440 for (; PSetI.isValid(); ++PSetI) {
441 // Find an existing entry in the pressure diff for this PSet.
442 PressureDiff::iterator I = nonconst_begin(), E = nonconst_end();
443 for (; I != E && I->isValid(); ++I) {
444 if (I->getPSet() >= *PSetI)
447 // If all pressure sets are more constrained, skip the remaining PSets.
450 // Insert this PressureChange.
451 if (!I->isValid() || I->getPSet() != *PSetI) {
452 PressureChange PTmp = PressureChange(*PSetI);
453 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
456 // Update the units for this pressure set.
457 unsigned NewUnitInc = I->getUnitInc() + Weight;
458 if (NewUnitInc != 0) {
459 I->setUnitInc(NewUnitInc);
462 PressureDiff::iterator J;
463 for (J = std::next(I); J != E && J->isValid(); ++J, ++I)
471 /// Record the pressure difference induced by the given operand list.
472 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
473 const MachineRegisterInfo *MRI) {
474 assert(!PDiff.begin()->isValid() && "stale PDiff");
476 for (unsigned Reg : RegOpers.Defs)
477 PDiff.addPressureChange(Reg, true, MRI);
479 for (unsigned Reg : RegOpers.Uses)
480 PDiff.addPressureChange(Reg, false, MRI);
483 /// Force liveness of registers.
484 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
485 for (unsigned Reg : Regs) {
486 if (LiveRegs.insert(Reg))
487 increaseRegPressure(Reg);
491 /// Add Reg to the live in set and increase max pressure.
492 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
493 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
494 if (containsReg(P.LiveInRegs, Reg))
497 // At live in discovery, unconditionally increase the high water mark.
498 P.LiveInRegs.push_back(Reg);
499 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
502 /// Add Reg to the live out set and increase max pressure.
503 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
504 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
505 if (containsReg(P.LiveOutRegs, Reg))
508 // At live out discovery, unconditionally increase the high water mark.
509 P.LiveOutRegs.push_back(Reg);
510 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
513 /// Recede across the previous instruction. If LiveUses is provided, record any
514 /// RegUnits that are made live by the current instruction's uses. This includes
515 /// registers that are both defined and used by the instruction. If a pressure
516 /// difference pointer is provided record the changes is pressure caused by this
517 /// instruction independent of liveness.
518 void RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
519 PressureDiff *PDiff) {
520 assert(CurrPos != MBB->begin());
521 if (!isBottomClosed())
524 // Open the top of the region using block iterators.
525 if (!RequireIntervals && isTopClosed())
526 static_cast<RegionPressure&>(P).openTop(CurrPos);
528 // Find the previous instruction.
531 while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
532 assert(!CurrPos->isDebugValue());
535 if (RequireIntervals)
536 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
538 // Open the top of the region using slot indexes.
539 if (RequireIntervals && isTopClosed())
540 static_cast<IntervalPressure&>(P).openTop(SlotIdx);
542 const MachineInstr &MI = *CurrPos;
543 RegisterOperands RegOpers;
544 RegOpers.collect(MI, *TRI, *MRI);
545 if (RequireIntervals)
546 RegOpers.detectDeadDefs(MI, *LIS);
549 collectPDiff(*PDiff, RegOpers, MRI);
551 // Boost pressure for all dead defs together.
552 increaseRegPressure(RegOpers.DeadDefs);
553 decreaseRegPressure(RegOpers.DeadDefs);
555 // Kill liveness at live defs.
556 // TODO: consider earlyclobbers?
557 for (unsigned Reg : RegOpers.Defs) {
558 if (LiveRegs.erase(Reg))
559 decreaseRegPressure(Reg);
561 discoverLiveOut(Reg);
564 // Generate liveness for uses.
565 for (unsigned Reg : RegOpers.Uses) {
566 if (!LiveRegs.contains(Reg)) {
567 // Adjust liveouts if LiveIntervals are available.
568 if (RequireIntervals) {
569 const LiveRange *LR = getLiveRange(*LIS, Reg);
571 LiveQueryResult LRQ = LR->Query(SlotIdx);
572 if (!LRQ.isKill() && !LRQ.valueDefined())
573 discoverLiveOut(Reg);
576 increaseRegPressure(Reg);
577 LiveRegs.insert(Reg);
578 if (LiveUses && !containsReg(*LiveUses, Reg))
579 LiveUses->push_back(Reg);
582 if (TrackUntiedDefs) {
583 for (unsigned Reg : RegOpers.Defs) {
584 if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
585 UntiedDefs.insert(Reg);
590 /// Advance across the current instruction.
591 void RegPressureTracker::advance() {
592 assert(!TrackUntiedDefs && "unsupported mode");
594 assert(CurrPos != MBB->end());
599 if (RequireIntervals)
600 SlotIdx = getCurrSlot();
602 // Open the bottom of the region using slot indexes.
603 if (isBottomClosed()) {
604 if (RequireIntervals)
605 static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
607 static_cast<RegionPressure&>(P).openBottom(CurrPos);
610 RegisterOperands RegOpers;
611 RegOpers.collect(*CurrPos, *TRI, *MRI);
613 for (unsigned Reg : RegOpers.Uses) {
614 // Discover live-ins.
615 bool isLive = LiveRegs.contains(Reg);
618 // Kill liveness at last uses.
619 bool lastUse = false;
620 if (RequireIntervals) {
621 const LiveRange *LR = getLiveRange(*LIS, Reg);
622 lastUse = LR && LR->Query(SlotIdx).isKill();
624 // Allocatable physregs are always single-use before register rewriting.
625 lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
627 if (lastUse && isLive) {
629 decreaseRegPressure(Reg);
630 } else if (!lastUse && !isLive)
631 increaseRegPressure(Reg);
634 // Generate liveness for defs.
635 for (unsigned Reg : RegOpers.Defs) {
636 if (LiveRegs.insert(Reg))
637 increaseRegPressure(Reg);
640 // Boost pressure for all dead defs together.
641 increaseRegPressure(RegOpers.DeadDefs);
642 decreaseRegPressure(RegOpers.DeadDefs);
644 // Find the next instruction.
647 while (CurrPos != MBB->end() && CurrPos->isDebugValue());
650 /// Find the max change in excess pressure across all sets.
651 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
652 ArrayRef<unsigned> NewPressureVec,
653 RegPressureDelta &Delta,
654 const RegisterClassInfo *RCI,
655 ArrayRef<unsigned> LiveThruPressureVec) {
656 Delta.Excess = PressureChange();
657 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
658 unsigned POld = OldPressureVec[i];
659 unsigned PNew = NewPressureVec[i];
660 int PDiff = (int)PNew - (int)POld;
661 if (!PDiff) // No change in this set in the common case.
663 // Only consider change beyond the limit.
664 unsigned Limit = RCI->getRegPressureSetLimit(i);
665 if (!LiveThruPressureVec.empty())
666 Limit += LiveThruPressureVec[i];
670 PDiff = 0; // Under the limit
672 PDiff = PNew - Limit; // Just exceeded limit.
673 } else if (Limit > PNew)
674 PDiff = Limit - POld; // Just obeyed limit.
677 Delta.Excess = PressureChange(i);
678 Delta.Excess.setUnitInc(PDiff);
684 /// Find the max change in max pressure that either surpasses a critical PSet
685 /// limit or exceeds the current MaxPressureLimit.
687 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
688 /// silly. It's done now to demonstrate the concept but will go away with a
689 /// RegPressureTracker API change to work with pressure differences.
690 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
691 ArrayRef<unsigned> NewMaxPressureVec,
692 ArrayRef<PressureChange> CriticalPSets,
693 ArrayRef<unsigned> MaxPressureLimit,
694 RegPressureDelta &Delta) {
695 Delta.CriticalMax = PressureChange();
696 Delta.CurrentMax = PressureChange();
698 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
699 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
700 unsigned POld = OldMaxPressureVec[i];
701 unsigned PNew = NewMaxPressureVec[i];
702 if (PNew == POld) // No change in this set in the common case.
705 if (!Delta.CriticalMax.isValid()) {
706 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
709 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
710 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
712 Delta.CriticalMax = PressureChange(i);
713 Delta.CriticalMax.setUnitInc(PDiff);
717 // Find the first increase above MaxPressureLimit.
718 // (Ignores negative MDiff).
719 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
720 Delta.CurrentMax = PressureChange(i);
721 Delta.CurrentMax.setUnitInc(PNew - POld);
722 if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
728 /// Record the upward impact of a single instruction on current register
729 /// pressure. Unlike the advance/recede pressure tracking interface, this does
730 /// not discover live in/outs.
732 /// This is intended for speculative queries. It leaves pressure inconsistent
733 /// with the current position, so must be restored by the caller.
734 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
735 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
737 // Account for register pressure similar to RegPressureTracker::recede().
738 RegisterOperands RegOpers;
739 RegOpers.collect(*MI, *TRI, *MRI, /*IgnoreDead=*/true);
740 assert(RegOpers.DeadDefs.size() == 0);
741 if (RequireIntervals)
742 RegOpers.detectDeadDefs(*MI, *LIS);
744 // Kill liveness at live defs.
745 for (unsigned Reg : RegOpers.Defs) {
746 if (!containsReg(RegOpers.Uses, Reg))
747 decreaseRegPressure(Reg);
749 // Generate liveness for uses.
750 for (unsigned Reg : RegOpers.Uses) {
751 if (!LiveRegs.contains(Reg))
752 increaseRegPressure(Reg);
756 /// Consider the pressure increase caused by traversing this instruction
757 /// bottom-up. Find the pressure set with the most change beyond its pressure
758 /// limit based on the tracker's current pressure, and return the change in
759 /// number of register units of that pressure set introduced by this
762 /// This assumes that the current LiveOut set is sufficient.
764 /// This is expensive for an on-the-fly query because it calls
765 /// bumpUpwardPressure to recompute the pressure sets based on current
766 /// liveness. This mainly exists to verify correctness, e.g. with
767 /// -verify-misched. getUpwardPressureDelta is the fast version of this query
768 /// that uses the per-SUnit cache of the PressureDiff.
769 void RegPressureTracker::
770 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
771 RegPressureDelta &Delta,
772 ArrayRef<PressureChange> CriticalPSets,
773 ArrayRef<unsigned> MaxPressureLimit) {
774 // Snapshot Pressure.
775 // FIXME: The snapshot heap space should persist. But I'm planning to
776 // summarize the pressure effect so we don't need to snapshot at all.
777 std::vector<unsigned> SavedPressure = CurrSetPressure;
778 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
780 bumpUpwardPressure(MI);
782 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
784 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
785 MaxPressureLimit, Delta);
786 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
787 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
789 // Restore the tracker's state.
790 P.MaxSetPressure.swap(SavedMaxPressure);
791 CurrSetPressure.swap(SavedPressure);
797 // Check if the alternate algorithm yields the same result.
798 RegPressureDelta Delta2;
799 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
800 if (Delta != Delta2) {
803 dbgs() << "DELTA: " << *MI;
804 if (Delta.Excess.isValid())
805 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
806 << " " << Delta.Excess.getUnitInc() << "\n";
807 if (Delta.CriticalMax.isValid())
808 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
809 << " " << Delta.CriticalMax.getUnitInc() << "\n";
810 if (Delta.CurrentMax.isValid())
811 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
812 << " " << Delta.CurrentMax.getUnitInc() << "\n";
813 if (Delta2.Excess.isValid())
814 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
815 << " " << Delta2.Excess.getUnitInc() << "\n";
816 if (Delta2.CriticalMax.isValid())
817 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
818 << " " << Delta2.CriticalMax.getUnitInc() << "\n";
819 if (Delta2.CurrentMax.isValid())
820 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
821 << " " << Delta2.CurrentMax.getUnitInc() << "\n";
822 llvm_unreachable("RegP Delta Mismatch");
827 /// This is the fast version of querying register pressure that does not
828 /// directly depend on current liveness.
830 /// @param Delta captures information needed for heuristics.
832 /// @param CriticalPSets Are the pressure sets that are known to exceed some
833 /// limit within the region, not necessarily at the current position.
835 /// @param MaxPressureLimit Is the max pressure within the region, not
836 /// necessarily at the current position.
837 void RegPressureTracker::
838 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
839 RegPressureDelta &Delta,
840 ArrayRef<PressureChange> CriticalPSets,
841 ArrayRef<unsigned> MaxPressureLimit) const {
842 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
843 for (PressureDiff::const_iterator
844 PDiffI = PDiff.begin(), PDiffE = PDiff.end();
845 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
847 unsigned PSetID = PDiffI->getPSet();
848 unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
849 if (!LiveThruPressure.empty())
850 Limit += LiveThruPressure[PSetID];
852 unsigned POld = CurrSetPressure[PSetID];
853 unsigned MOld = P.MaxSetPressure[PSetID];
854 unsigned MNew = MOld;
855 // Ignore DeadDefs here because they aren't captured by PressureChange.
856 unsigned PNew = POld + PDiffI->getUnitInc();
857 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld)
858 && "PSet overflow/underflow");
861 // Check if current pressure has exceeded the limit.
862 if (!Delta.Excess.isValid()) {
863 unsigned ExcessInc = 0;
865 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
866 else if (POld > Limit)
867 ExcessInc = Limit - POld;
869 Delta.Excess = PressureChange(PSetID);
870 Delta.Excess.setUnitInc(ExcessInc);
873 // Check if max pressure has exceeded a critical pressure set max.
876 if (!Delta.CriticalMax.isValid()) {
877 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
880 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
881 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
882 if (CritInc > 0 && CritInc <= INT16_MAX) {
883 Delta.CriticalMax = PressureChange(PSetID);
884 Delta.CriticalMax.setUnitInc(CritInc);
888 // Check if max pressure has exceeded the current max.
889 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
890 Delta.CurrentMax = PressureChange(PSetID);
891 Delta.CurrentMax.setUnitInc(MNew - MOld);
896 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
897 static bool findUseBetween(unsigned Reg, SlotIndex PriorUseIdx,
898 SlotIndex NextUseIdx, const MachineRegisterInfo &MRI,
899 const LiveIntervals *LIS) {
900 for (const MachineInstr &MI : MRI.use_nodbg_instructions(Reg)) {
901 SlotIndex InstSlot = LIS->getInstructionIndex(&MI).getRegSlot();
902 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
908 /// Record the downward impact of a single instruction on current register
909 /// pressure. Unlike the advance/recede pressure tracking interface, this does
910 /// not discover live in/outs.
912 /// This is intended for speculative queries. It leaves pressure inconsistent
913 /// with the current position, so must be restored by the caller.
914 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
915 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
917 // Account for register pressure similar to RegPressureTracker::recede().
918 RegisterOperands RegOpers;
919 RegOpers.collect(*MI, *TRI, *MRI);
921 // Kill liveness at last uses. Assume allocatable physregs are single-use
922 // rather than checking LiveIntervals.
924 if (RequireIntervals)
925 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
927 for (unsigned Reg : RegOpers.Uses) {
928 if (RequireIntervals) {
929 // FIXME: allow the caller to pass in the list of vreg uses that remain
930 // to be bottom-scheduled to avoid searching uses at each query.
931 SlotIndex CurrIdx = getCurrSlot();
932 const LiveRange *LR = getLiveRange(*LIS, Reg);
934 LiveQueryResult LRQ = LR->Query(SlotIdx);
935 if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, *MRI, LIS))
936 decreaseRegPressure(Reg);
938 } else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
939 // Allocatable physregs are always single-use before register rewriting.
940 decreaseRegPressure(Reg);
944 // Generate liveness for defs.
945 increaseRegPressure(RegOpers.Defs);
947 // Boost pressure for all dead defs together.
948 increaseRegPressure(RegOpers.DeadDefs);
949 decreaseRegPressure(RegOpers.DeadDefs);
952 /// Consider the pressure increase caused by traversing this instruction
953 /// top-down. Find the register class with the most change in its pressure limit
954 /// based on the tracker's current pressure, and return the number of excess
955 /// register units of that pressure set introduced by this instruction.
957 /// This assumes that the current LiveIn set is sufficient.
959 /// This is expensive for an on-the-fly query because it calls
960 /// bumpDownwardPressure to recompute the pressure sets based on current
961 /// liveness. We don't yet have a fast version of downward pressure tracking
962 /// analogous to getUpwardPressureDelta.
963 void RegPressureTracker::
964 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
965 ArrayRef<PressureChange> CriticalPSets,
966 ArrayRef<unsigned> MaxPressureLimit) {
967 // Snapshot Pressure.
968 std::vector<unsigned> SavedPressure = CurrSetPressure;
969 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
971 bumpDownwardPressure(MI);
973 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
975 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
976 MaxPressureLimit, Delta);
977 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
978 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
980 // Restore the tracker's state.
981 P.MaxSetPressure.swap(SavedMaxPressure);
982 CurrSetPressure.swap(SavedPressure);
985 /// Get the pressure of each PSet after traversing this instruction bottom-up.
986 void RegPressureTracker::
987 getUpwardPressure(const MachineInstr *MI,
988 std::vector<unsigned> &PressureResult,
989 std::vector<unsigned> &MaxPressureResult) {
990 // Snapshot pressure.
991 PressureResult = CurrSetPressure;
992 MaxPressureResult = P.MaxSetPressure;
994 bumpUpwardPressure(MI);
996 // Current pressure becomes the result. Restore current pressure.
997 P.MaxSetPressure.swap(MaxPressureResult);
998 CurrSetPressure.swap(PressureResult);
1001 /// Get the pressure of each PSet after traversing this instruction top-down.
1002 void RegPressureTracker::
1003 getDownwardPressure(const MachineInstr *MI,
1004 std::vector<unsigned> &PressureResult,
1005 std::vector<unsigned> &MaxPressureResult) {
1006 // Snapshot pressure.
1007 PressureResult = CurrSetPressure;
1008 MaxPressureResult = P.MaxSetPressure;
1010 bumpDownwardPressure(MI);
1012 // Current pressure becomes the result. Restore current pressure.
1013 P.MaxSetPressure.swap(MaxPressureResult);
1014 CurrSetPressure.swap(PressureResult);