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);
64 void RegPressureTracker::dump() const {
65 if (!isTopClosed() || !isBottomClosed()) {
66 dbgs() << "Curr Pressure: ";
67 dumpRegSetPressure(CurrSetPressure, TRI);
70 dbgs() << "Live In: ";
71 for (unsigned i = 0, e = LiveInRegs.size(); i < e; ++i)
72 dbgs() << PrintVRegOrUnit(LiveInRegs[i], TRI) << " ";
74 dbgs() << "Live Out: ";
75 for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i)
76 dbgs() << PrintVRegOrUnit(LiveOutRegs[i], TRI) << " ";
80 void PressureDiff::dump(const TargetRegisterInfo &TRI) const {
81 for (const PressureChange &Change : *this) {
82 if (!Change.isValid() || Change.getUnitInc() == 0)
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();
117 /// Clear the result so it can be used for another round of pressure tracking.
118 void RegionPressure::reset() {
119 TopPos = BottomPos = MachineBasicBlock::const_iterator();
120 MaxSetPressure.clear();
123 /// If the current top is not less than or equal to the next index, open it.
124 /// We happen to need the SlotIndex for the next top for pressure update.
125 void IntervalPressure::openTop(SlotIndex NextTop) {
126 if (TopIdx <= NextTop)
128 TopIdx = SlotIndex();
131 /// If the current top is the previous instruction (before receding), open it.
132 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
133 if (TopPos != PrevTop)
135 TopPos = MachineBasicBlock::const_iterator();
138 /// If the current bottom is not greater than the previous index, open it.
139 void IntervalPressure::openBottom(SlotIndex PrevBottom) {
140 if (BottomIdx > PrevBottom)
142 BottomIdx = SlotIndex();
145 /// If the current bottom is the previous instr (before advancing), open it.
146 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
147 if (BottomPos != PrevBottom)
149 BottomPos = MachineBasicBlock::const_iterator();
152 const LiveRange *RegPressureTracker::getLiveRange(unsigned Reg) const {
153 if (TargetRegisterInfo::isVirtualRegister(Reg))
154 return &LIS->getInterval(Reg);
155 return LIS->getCachedRegUnit(Reg);
158 void RegPressureTracker::reset() {
162 CurrSetPressure.clear();
163 LiveThruPressure.clear();
164 P.MaxSetPressure.clear();
166 if (RequireIntervals)
167 static_cast<IntervalPressure&>(P).reset();
169 static_cast<RegionPressure&>(P).reset();
173 LiveRegs.PhysRegs.clear();
174 LiveRegs.VirtRegs.clear();
178 /// Setup the RegPressureTracker.
180 /// TODO: Add support for pressure without LiveIntervals.
181 void RegPressureTracker::init(const MachineFunction *mf,
182 const RegisterClassInfo *rci,
183 const LiveIntervals *lis,
184 const MachineBasicBlock *mbb,
185 MachineBasicBlock::const_iterator pos,
186 bool ShouldTrackUntiedDefs)
191 TRI = MF->getSubtarget().getRegisterInfo();
193 MRI = &MF->getRegInfo();
195 TrackUntiedDefs = ShouldTrackUntiedDefs;
197 if (RequireIntervals) {
198 assert(lis && "IntervalPressure requires LiveIntervals");
203 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
205 P.MaxSetPressure = CurrSetPressure;
207 LiveRegs.PhysRegs.setUniverse(TRI->getNumRegs());
208 LiveRegs.VirtRegs.setUniverse(MRI->getNumVirtRegs());
210 UntiedDefs.setUniverse(MRI->getNumVirtRegs());
213 /// Does this pressure result have a valid top position and live ins.
214 bool RegPressureTracker::isTopClosed() const {
215 if (RequireIntervals)
216 return static_cast<IntervalPressure&>(P).TopIdx.isValid();
217 return (static_cast<RegionPressure&>(P).TopPos ==
218 MachineBasicBlock::const_iterator());
221 /// Does this pressure result have a valid bottom position and live outs.
222 bool RegPressureTracker::isBottomClosed() const {
223 if (RequireIntervals)
224 return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
225 return (static_cast<RegionPressure&>(P).BottomPos ==
226 MachineBasicBlock::const_iterator());
230 SlotIndex RegPressureTracker::getCurrSlot() const {
231 MachineBasicBlock::const_iterator IdxPos = CurrPos;
232 while (IdxPos != MBB->end() && IdxPos->isDebugValue())
234 if (IdxPos == MBB->end())
235 return LIS->getMBBEndIdx(MBB);
236 return LIS->getInstructionIndex(IdxPos).getRegSlot();
239 /// Set the boundary for the top of the region and summarize live ins.
240 void RegPressureTracker::closeTop() {
241 if (RequireIntervals)
242 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
244 static_cast<RegionPressure&>(P).TopPos = CurrPos;
246 assert(LiveInRegs.empty() && "inconsistent max pressure result");
247 LiveInRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
248 LiveInRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
249 LiveInRegs.append(LiveRegs.VirtRegs.begin(), LiveRegs.VirtRegs.end());
252 /// Set the boundary for the bottom of the region and summarize live outs.
253 void RegPressureTracker::closeBottom() {
254 if (RequireIntervals)
255 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
257 static_cast<RegionPressure&>(P).BottomPos = CurrPos;
259 assert(LiveOutRegs.empty() && "inconsistent max pressure result");
260 LiveOutRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
261 LiveOutRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
262 LiveOutRegs.append(LiveRegs.VirtRegs.begin(), LiveRegs.VirtRegs.end());
265 /// Finalize the region boundaries and record live ins and live outs.
266 void RegPressureTracker::closeRegion() {
267 if (!isTopClosed() && !isBottomClosed()) {
268 assert(LiveRegs.PhysRegs.empty() && LiveRegs.VirtRegs.empty() &&
269 "no region boundary");
272 if (!isBottomClosed())
274 else if (!isTopClosed())
276 // If both top and bottom are closed, do nothing.
279 /// The register tracker is unaware of global liveness so ignores normal
280 /// live-thru ranges. However, two-address or coalesced chains can also lead
281 /// to live ranges with no holes. Count these to inform heuristics that we
282 /// can never drop below this pressure.
283 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
284 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
285 assert(isBottomClosed() && "need bottom-up tracking to intialize.");
286 for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i) {
287 unsigned Reg = LiveOutRegs[i];
288 if (TargetRegisterInfo::isVirtualRegister(Reg)
289 && !RPTracker.hasUntiedDef(Reg)) {
290 increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg));
295 /// \brief Convenient wrapper for checking membership in RegisterOperands.
296 /// (std::count() doesn't have an early exit).
297 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
298 return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
302 /// Collect this instruction's unique uses and defs into SmallVectors for
303 /// processing defs and uses in order.
305 /// FIXME: always ignore tied opers
306 class RegisterOperands {
307 const TargetRegisterInfo *TRI;
308 const MachineRegisterInfo *MRI;
312 SmallVector<unsigned, 8> Uses;
313 SmallVector<unsigned, 8> Defs;
314 SmallVector<unsigned, 8> DeadDefs;
316 RegisterOperands(const TargetRegisterInfo *tri,
317 const MachineRegisterInfo *mri, bool ID = false):
318 TRI(tri), MRI(mri), IgnoreDead(ID) {}
320 /// Push this operand's register onto the correct vector.
321 void collect(const MachineOperand &MO) {
322 if (!MO.isReg() || !MO.getReg())
325 pushRegUnits(MO.getReg(), Uses);
329 pushRegUnits(MO.getReg(), DeadDefs);
332 pushRegUnits(MO.getReg(), Defs);
337 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
338 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
339 if (containsReg(RegUnits, Reg))
341 RegUnits.push_back(Reg);
343 else if (MRI->isAllocatable(Reg)) {
344 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
345 if (containsReg(RegUnits, *Units))
347 RegUnits.push_back(*Units);
354 /// Collect physical and virtual register operands.
355 static void collectOperands(const MachineInstr *MI,
356 RegisterOperands &RegOpers) {
357 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
358 RegOpers.collect(*OperI);
360 // Remove redundant physreg dead defs.
361 SmallVectorImpl<unsigned>::iterator I =
362 std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
363 std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
364 RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
367 /// Initialize an array of N PressureDiffs.
368 void PressureDiffs::init(unsigned N) {
371 memset(PDiffArray, 0, N * sizeof(PressureDiff));
376 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
379 /// Add a change in pressure to the pressure diff of a given instruction.
380 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
381 const MachineRegisterInfo *MRI) {
382 PSetIterator PSetI = MRI->getPressureSets(RegUnit);
383 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
384 for (; PSetI.isValid(); ++PSetI) {
385 // Find an existing entry in the pressure diff for this PSet.
386 PressureDiff::iterator I = begin(), E = end();
387 for (; I != E && I->isValid(); ++I) {
388 if (I->getPSet() >= *PSetI)
391 // If all pressure sets are more constrained, skip the remaining PSets.
394 // Insert this PressureChange.
395 if (!I->isValid() || I->getPSet() != *PSetI) {
396 PressureChange PTmp = PressureChange(*PSetI);
397 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
400 // Update the units for this pressure set.
401 I->setUnitInc(I->getUnitInc() + Weight);
405 /// Record the pressure difference induced by the given operand list.
406 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
407 const MachineRegisterInfo *MRI) {
408 assert(!PDiff.begin()->isValid() && "stale PDiff");
410 for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
411 PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
413 for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
414 PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
417 /// Force liveness of registers.
418 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
419 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
420 if (LiveRegs.insert(Regs[i]))
421 increaseRegPressure(Regs[i]);
425 /// Add Reg to the live in set and increase max pressure.
426 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
427 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
428 if (containsReg(LiveInRegs, Reg))
431 // At live in discovery, unconditionally increase the high water mark.
432 LiveInRegs.push_back(Reg);
433 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
436 /// Add Reg to the live out set and increase max pressure.
437 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
438 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
439 if (containsReg(LiveOutRegs, Reg))
442 // At live out discovery, unconditionally increase the high water mark.
443 LiveOutRegs.push_back(Reg);
444 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
447 /// Recede across the previous instruction. If LiveUses is provided, record any
448 /// RegUnits that are made live by the current instruction's uses. This includes
449 /// registers that are both defined and used by the instruction. If a pressure
450 /// difference pointer is provided record the changes is pressure caused by this
451 /// instruction independent of liveness.
452 bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
453 PressureDiff *PDiff) {
454 // Check for the top of the analyzable region.
455 if (CurrPos == MBB->begin()) {
459 if (!isBottomClosed())
462 // Open the top of the region using block iterators.
463 if (!RequireIntervals && isTopClosed())
464 static_cast<RegionPressure&>(P).openTop(CurrPos);
466 // Find the previous instruction.
469 while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
471 if (CurrPos->isDebugValue()) {
476 if (RequireIntervals)
477 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
479 // Open the top of the region using slot indexes.
481 if (RequireIntervals)
482 static_cast<IntervalPressure&>(P).openTop(SlotIdx);
486 RegisterOperands RegOpers(TRI, MRI);
487 collectOperands(CurrPos, RegOpers);
490 collectPDiff(*PDiff, RegOpers, MRI);
492 // Boost pressure for all dead defs together.
493 increaseRegPressure(RegOpers.DeadDefs);
494 decreaseRegPressure(RegOpers.DeadDefs);
496 // Kill liveness at live defs.
497 // TODO: consider earlyclobbers?
498 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
499 unsigned Reg = RegOpers.Defs[i];
500 bool DeadDef = false;
501 if (RequireIntervals) {
502 const LiveRange *LR = getLiveRange(Reg);
504 LiveQueryResult LRQ = LR->Query(SlotIdx);
505 DeadDef = LRQ.isDeadDef();
509 // LiveIntervals knows this is a dead even though it's MachineOperand is
510 // not flagged as such. Since this register will not be recorded as
511 // live-out, increase its PDiff value to avoid underflowing pressure.
513 PDiff->addPressureChange(Reg, false, MRI);
515 if (LiveRegs.erase(Reg))
516 decreaseRegPressure(Reg);
518 discoverLiveOut(Reg);
522 // Generate liveness for uses.
523 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
524 unsigned Reg = RegOpers.Uses[i];
525 if (!LiveRegs.contains(Reg)) {
526 // Adjust liveouts if LiveIntervals are available.
527 if (RequireIntervals) {
528 const LiveRange *LR = getLiveRange(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 i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
543 unsigned Reg = RegOpers.Defs[i];
544 if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
545 UntiedDefs.insert(Reg);
551 /// Advance across the current instruction.
552 bool RegPressureTracker::advance() {
553 assert(!TrackUntiedDefs && "unsupported mode");
555 // Check for the bottom of the analyzable region.
556 if (CurrPos == MBB->end()) {
564 if (RequireIntervals)
565 SlotIdx = getCurrSlot();
567 // Open the bottom of the region using slot indexes.
568 if (isBottomClosed()) {
569 if (RequireIntervals)
570 static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
572 static_cast<RegionPressure&>(P).openBottom(CurrPos);
576 RegisterOperands RegOpers(TRI, MRI);
577 collectOperands(CurrPos, RegOpers);
579 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
580 unsigned Reg = RegOpers.Uses[i];
581 // Discover live-ins.
582 bool isLive = LiveRegs.contains(Reg);
585 // Kill liveness at last uses.
586 bool lastUse = false;
587 if (RequireIntervals) {
588 const LiveRange *LR = getLiveRange(Reg);
589 lastUse = LR && LR->Query(SlotIdx).isKill();
592 // Allocatable physregs are always single-use before register rewriting.
593 lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
595 if (lastUse && isLive) {
597 decreaseRegPressure(Reg);
599 else if (!lastUse && !isLive)
600 increaseRegPressure(Reg);
603 // Generate liveness for defs.
604 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
605 unsigned Reg = RegOpers.Defs[i];
606 if (LiveRegs.insert(Reg))
607 increaseRegPressure(Reg);
610 // Boost pressure for all dead defs together.
611 increaseRegPressure(RegOpers.DeadDefs);
612 decreaseRegPressure(RegOpers.DeadDefs);
614 // Find the next instruction.
617 while (CurrPos != MBB->end() && CurrPos->isDebugValue());
621 /// Find the max change in excess pressure across all sets.
622 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
623 ArrayRef<unsigned> NewPressureVec,
624 RegPressureDelta &Delta,
625 const RegisterClassInfo *RCI,
626 ArrayRef<unsigned> LiveThruPressureVec) {
627 Delta.Excess = PressureChange();
628 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
629 unsigned POld = OldPressureVec[i];
630 unsigned PNew = NewPressureVec[i];
631 int PDiff = (int)PNew - (int)POld;
632 if (!PDiff) // No change in this set in the common case.
634 // Only consider change beyond the limit.
635 unsigned Limit = RCI->getRegPressureSetLimit(i);
636 if (!LiveThruPressureVec.empty())
637 Limit += LiveThruPressureVec[i];
641 PDiff = 0; // Under the limit
643 PDiff = PNew - Limit; // Just exceeded limit.
645 else if (Limit > PNew)
646 PDiff = Limit - POld; // Just obeyed limit.
649 Delta.Excess = PressureChange(i);
650 Delta.Excess.setUnitInc(PDiff);
656 /// Find the max change in max pressure that either surpasses a critical PSet
657 /// limit or exceeds the current MaxPressureLimit.
659 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
660 /// silly. It's done now to demonstrate the concept but will go away with a
661 /// RegPressureTracker API change to work with pressure differences.
662 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
663 ArrayRef<unsigned> NewMaxPressureVec,
664 ArrayRef<PressureChange> CriticalPSets,
665 ArrayRef<unsigned> MaxPressureLimit,
666 RegPressureDelta &Delta) {
667 Delta.CriticalMax = PressureChange();
668 Delta.CurrentMax = PressureChange();
670 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
671 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
672 unsigned POld = OldMaxPressureVec[i];
673 unsigned PNew = NewMaxPressureVec[i];
674 if (PNew == POld) // No change in this set in the common case.
677 if (!Delta.CriticalMax.isValid()) {
678 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
681 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
682 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
684 Delta.CriticalMax = PressureChange(i);
685 Delta.CriticalMax.setUnitInc(PDiff);
689 // Find the first increase above MaxPressureLimit.
690 // (Ignores negative MDiff).
691 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
692 Delta.CurrentMax = PressureChange(i);
693 Delta.CurrentMax.setUnitInc(PNew - POld);
694 if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
700 /// Record the upward impact of a single instruction on current register
701 /// pressure. Unlike the advance/recede pressure tracking interface, this does
702 /// not discover live in/outs.
704 /// This is intended for speculative queries. It leaves pressure inconsistent
705 /// with the current position, so must be restored by the caller.
706 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
707 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
709 // Account for register pressure similar to RegPressureTracker::recede().
710 RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
711 collectOperands(MI, RegOpers);
713 // Boost max pressure for all dead defs together.
714 // Since CurrSetPressure and MaxSetPressure
715 increaseRegPressure(RegOpers.DeadDefs);
716 decreaseRegPressure(RegOpers.DeadDefs);
718 // Kill liveness at live defs.
719 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
720 unsigned Reg = RegOpers.Defs[i];
721 bool DeadDef = false;
722 if (RequireIntervals) {
723 const LiveRange *LR = getLiveRange(Reg);
725 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
726 LiveQueryResult LRQ = LR->Query(SlotIdx);
727 DeadDef = LRQ.isDeadDef();
731 if (!containsReg(RegOpers.Uses, Reg))
732 decreaseRegPressure(Reg);
735 // Generate liveness for uses.
736 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
737 unsigned Reg = RegOpers.Uses[i];
738 if (!LiveRegs.contains(Reg))
739 increaseRegPressure(Reg);
743 /// Consider the pressure increase caused by traversing this instruction
744 /// bottom-up. Find the pressure set with the most change beyond its pressure
745 /// limit based on the tracker's current pressure, and return the change in
746 /// number of register units of that pressure set introduced by this
749 /// This assumes that the current LiveOut set is sufficient.
751 /// This is expensive for an on-the-fly query because it calls
752 /// bumpUpwardPressure to recompute the pressure sets based on current
753 /// liveness. This mainly exists to verify correctness, e.g. with
754 /// -verify-misched. getUpwardPressureDelta is the fast version of this query
755 /// that uses the per-SUnit cache of the PressureDiff.
756 void RegPressureTracker::
757 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
758 RegPressureDelta &Delta,
759 ArrayRef<PressureChange> CriticalPSets,
760 ArrayRef<unsigned> MaxPressureLimit) {
761 // Snapshot Pressure.
762 // FIXME: The snapshot heap space should persist. But I'm planning to
763 // summarize the pressure effect so we don't need to snapshot at all.
764 std::vector<unsigned> SavedPressure = CurrSetPressure;
765 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
767 bumpUpwardPressure(MI);
769 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
771 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
772 MaxPressureLimit, Delta);
773 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
774 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
776 // Restore the tracker's state.
777 P.MaxSetPressure.swap(SavedMaxPressure);
778 CurrSetPressure.swap(SavedPressure);
784 // Check if the alternate algorithm yields the same result.
785 RegPressureDelta Delta2;
786 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
787 if (Delta != Delta2) {
790 dbgs() << "DELTA: " << *MI;
791 if (Delta.Excess.isValid())
792 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
793 << " " << Delta.Excess.getUnitInc() << "\n";
794 if (Delta.CriticalMax.isValid())
795 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
796 << " " << Delta.CriticalMax.getUnitInc() << "\n";
797 if (Delta.CurrentMax.isValid())
798 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
799 << " " << Delta.CurrentMax.getUnitInc() << "\n";
800 if (Delta2.Excess.isValid())
801 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
802 << " " << Delta2.Excess.getUnitInc() << "\n";
803 if (Delta2.CriticalMax.isValid())
804 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
805 << " " << Delta2.CriticalMax.getUnitInc() << "\n";
806 if (Delta2.CurrentMax.isValid())
807 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
808 << " " << Delta2.CurrentMax.getUnitInc() << "\n";
809 llvm_unreachable("RegP Delta Mismatch");
814 /// This is the fast version of querying register pressure that does not
815 /// directly depend on current liveness.
817 /// @param Delta captures information needed for heuristics.
819 /// @param CriticalPSets Are the pressure sets that are known to exceed some
820 /// limit within the region, not necessarily at the current position.
822 /// @param MaxPressureLimit Is the max pressure within the region, not
823 /// necessarily at the current position.
824 void RegPressureTracker::
825 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
826 RegPressureDelta &Delta,
827 ArrayRef<PressureChange> CriticalPSets,
828 ArrayRef<unsigned> MaxPressureLimit) const {
829 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
830 for (PressureDiff::const_iterator
831 PDiffI = PDiff.begin(), PDiffE = PDiff.end();
832 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
834 unsigned PSetID = PDiffI->getPSet();
835 unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
836 if (!LiveThruPressure.empty())
837 Limit += LiveThruPressure[PSetID];
839 unsigned POld = CurrSetPressure[PSetID];
840 unsigned MOld = P.MaxSetPressure[PSetID];
841 unsigned MNew = MOld;
842 // Ignore DeadDefs here because they aren't captured by PressureChange.
843 unsigned PNew = POld + PDiffI->getUnitInc();
844 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
847 // Check if current pressure has exceeded the limit.
848 if (!Delta.Excess.isValid()) {
849 unsigned ExcessInc = 0;
851 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
852 else if (POld > Limit)
853 ExcessInc = Limit - POld;
855 Delta.Excess = PressureChange(PSetID);
856 Delta.Excess.setUnitInc(ExcessInc);
859 // Check if max pressure has exceeded a critical pressure set max.
862 if (!Delta.CriticalMax.isValid()) {
863 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
866 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
867 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
868 if (CritInc > 0 && CritInc <= INT16_MAX) {
869 Delta.CriticalMax = PressureChange(PSetID);
870 Delta.CriticalMax.setUnitInc(CritInc);
874 // Check if max pressure has exceeded the current max.
875 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
876 Delta.CurrentMax = PressureChange(PSetID);
877 Delta.CurrentMax.setUnitInc(MNew - MOld);
882 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
883 static bool findUseBetween(unsigned Reg,
884 SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
885 const MachineRegisterInfo *MRI,
886 const LiveIntervals *LIS) {
887 for (MachineRegisterInfo::use_instr_nodbg_iterator
888 UI = MRI->use_instr_nodbg_begin(Reg),
889 UE = MRI->use_instr_nodbg_end(); UI != UE; ++UI) {
890 const MachineInstr* MI = &*UI;
891 if (MI->isDebugValue())
893 SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot();
894 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
900 /// Record the downward impact of a single instruction on current register
901 /// pressure. Unlike the advance/recede pressure tracking interface, this does
902 /// not discover live in/outs.
904 /// This is intended for speculative queries. It leaves pressure inconsistent
905 /// with the current position, so must be restored by the caller.
906 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
907 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
909 // Account for register pressure similar to RegPressureTracker::recede().
910 RegisterOperands RegOpers(TRI, MRI);
911 collectOperands(MI, RegOpers);
913 // Kill liveness at last uses. Assume allocatable physregs are single-use
914 // rather than checking LiveIntervals.
916 if (RequireIntervals)
917 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
919 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
920 unsigned Reg = RegOpers.Uses[i];
921 if (RequireIntervals) {
922 // FIXME: allow the caller to pass in the list of vreg uses that remain
923 // to be bottom-scheduled to avoid searching uses at each query.
924 SlotIndex CurrIdx = getCurrSlot();
925 const LiveRange *LR = getLiveRange(Reg);
927 LiveQueryResult LRQ = LR->Query(SlotIdx);
928 if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) {
929 decreaseRegPressure(Reg);
933 else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
934 // Allocatable physregs are always single-use before register rewriting.
935 decreaseRegPressure(Reg);
939 // Generate liveness for defs.
940 increaseRegPressure(RegOpers.Defs);
942 // Boost pressure for all dead defs together.
943 increaseRegPressure(RegOpers.DeadDefs);
944 decreaseRegPressure(RegOpers.DeadDefs);
947 /// Consider the pressure increase caused by traversing this instruction
948 /// top-down. Find the register class with the most change in its pressure limit
949 /// based on the tracker's current pressure, and return the number of excess
950 /// register units of that pressure set introduced by this instruction.
952 /// This assumes that the current LiveIn set is sufficient.
954 /// This is expensive for an on-the-fly query because it calls
955 /// bumpDownwardPressure to recompute the pressure sets based on current
956 /// liveness. We don't yet have a fast version of downward pressure tracking
957 /// analogous to getUpwardPressureDelta.
958 void RegPressureTracker::
959 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
960 ArrayRef<PressureChange> CriticalPSets,
961 ArrayRef<unsigned> MaxPressureLimit) {
962 // Snapshot Pressure.
963 std::vector<unsigned> SavedPressure = CurrSetPressure;
964 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
966 bumpDownwardPressure(MI);
968 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
970 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
971 MaxPressureLimit, Delta);
972 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
973 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
975 // Restore the tracker's state.
976 P.MaxSetPressure.swap(SavedMaxPressure);
977 CurrSetPressure.swap(SavedPressure);
980 /// Get the pressure of each PSet after traversing this instruction bottom-up.
981 void RegPressureTracker::
982 getUpwardPressure(const MachineInstr *MI,
983 std::vector<unsigned> &PressureResult,
984 std::vector<unsigned> &MaxPressureResult) {
985 // Snapshot pressure.
986 PressureResult = CurrSetPressure;
987 MaxPressureResult = P.MaxSetPressure;
989 bumpUpwardPressure(MI);
991 // Current pressure becomes the result. Restore current pressure.
992 P.MaxSetPressure.swap(MaxPressureResult);
993 CurrSetPressure.swap(PressureResult);
996 /// Get the pressure of each PSet after traversing this instruction top-down.
997 void RegPressureTracker::
998 getDownwardPressure(const MachineInstr *MI,
999 std::vector<unsigned> &PressureResult,
1000 std::vector<unsigned> &MaxPressureResult) {
1001 // Snapshot pressure.
1002 PressureResult = CurrSetPressure;
1003 MaxPressureResult = P.MaxSetPressure;
1005 bumpDownwardPressure(MI);
1007 // Current pressure becomes the result. Restore current pressure.
1008 P.MaxSetPressure.swap(MaxPressureResult);
1009 CurrSetPressure.swap(PressureResult);