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"
22 #include "llvm/Target/TargetMachine.h"
26 /// Increase pressure for each pressure set provided by TargetRegisterInfo.
27 static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure,
29 unsigned Weight = PSetI.getWeight();
30 for (; PSetI.isValid(); ++PSetI)
31 CurrSetPressure[*PSetI] += Weight;
34 /// Decrease pressure for each pressure set provided by TargetRegisterInfo.
35 static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure,
37 unsigned Weight = PSetI.getWeight();
38 for (; PSetI.isValid(); ++PSetI) {
39 assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow");
40 CurrSetPressure[*PSetI] -= Weight;
44 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
45 void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
46 const TargetRegisterInfo *TRI) {
48 for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) {
49 if (SetPressure[i] != 0) {
50 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() << PrintReg(LiveInRegs[i], TRI) << " ";
65 dbgs() << "Live Out: ";
66 for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i)
67 dbgs() << PrintReg(LiveOutRegs[i], TRI) << " ";
71 void RegPressureTracker::dump() const {
72 if (!isTopClosed() || !isBottomClosed()) {
73 dbgs() << "Curr Pressure: ";
74 dumpRegSetPressure(CurrSetPressure, TRI);
80 /// Increase the current pressure as impacted by these registers and bump
81 /// the high water mark if needed.
82 void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) {
83 for (unsigned i = 0, e = RegUnits.size(); i != e; ++i) {
84 PSetIterator PSetI = MRI->getPressureSets(RegUnits[i]);
85 unsigned Weight = PSetI.getWeight();
86 for (; PSetI.isValid(); ++PSetI) {
87 CurrSetPressure[*PSetI] += Weight;
88 if (CurrSetPressure[*PSetI] > P.MaxSetPressure[*PSetI]) {
89 P.MaxSetPressure[*PSetI] = CurrSetPressure[*PSetI];
95 /// Simply decrease the current pressure as impacted by these registers.
96 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) {
97 for (unsigned I = 0, E = RegUnits.size(); I != E; ++I)
98 decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnits[I]));
101 /// Clear the result so it can be used for another round of pressure tracking.
102 void IntervalPressure::reset() {
103 TopIdx = BottomIdx = SlotIndex();
104 MaxSetPressure.clear();
109 /// Clear the result so it can be used for another round of pressure tracking.
110 void RegionPressure::reset() {
111 TopPos = BottomPos = MachineBasicBlock::const_iterator();
112 MaxSetPressure.clear();
117 /// If the current top is not less than or equal to the next index, open it.
118 /// We happen to need the SlotIndex for the next top for pressure update.
119 void IntervalPressure::openTop(SlotIndex NextTop) {
120 if (TopIdx <= NextTop)
122 TopIdx = SlotIndex();
126 /// If the current top is the previous instruction (before receding), open it.
127 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
128 if (TopPos != PrevTop)
130 TopPos = MachineBasicBlock::const_iterator();
134 /// If the current bottom is not greater than the previous index, open it.
135 void IntervalPressure::openBottom(SlotIndex PrevBottom) {
136 if (BottomIdx > PrevBottom)
138 BottomIdx = SlotIndex();
142 /// If the current bottom is the previous instr (before advancing), open it.
143 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
144 if (BottomPos != PrevBottom)
146 BottomPos = MachineBasicBlock::const_iterator();
150 const LiveRange *RegPressureTracker::getLiveRange(unsigned Reg) const {
151 if (TargetRegisterInfo::isVirtualRegister(Reg))
152 return &LIS->getInterval(Reg);
153 return LIS->getCachedRegUnit(Reg);
156 void RegPressureTracker::reset() {
160 CurrSetPressure.clear();
161 LiveThruPressure.clear();
162 P.MaxSetPressure.clear();
164 if (RequireIntervals)
165 static_cast<IntervalPressure&>(P).reset();
167 static_cast<RegionPressure&>(P).reset();
169 LiveRegs.PhysRegs.clear();
170 LiveRegs.VirtRegs.clear();
174 /// Setup the RegPressureTracker.
176 /// TODO: Add support for pressure without LiveIntervals.
177 void RegPressureTracker::init(const MachineFunction *mf,
178 const RegisterClassInfo *rci,
179 const LiveIntervals *lis,
180 const MachineBasicBlock *mbb,
181 MachineBasicBlock::const_iterator pos,
182 bool ShouldTrackUntiedDefs)
187 TRI = MF->getTarget().getRegisterInfo();
189 MRI = &MF->getRegInfo();
191 TrackUntiedDefs = ShouldTrackUntiedDefs;
193 if (RequireIntervals) {
194 assert(lis && "IntervalPressure requires LiveIntervals");
199 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
201 P.MaxSetPressure = CurrSetPressure;
203 LiveRegs.PhysRegs.setUniverse(TRI->getNumRegs());
204 LiveRegs.VirtRegs.setUniverse(MRI->getNumVirtRegs());
206 UntiedDefs.setUniverse(MRI->getNumVirtRegs());
209 /// Does this pressure result have a valid top position and live ins.
210 bool RegPressureTracker::isTopClosed() const {
211 if (RequireIntervals)
212 return static_cast<IntervalPressure&>(P).TopIdx.isValid();
213 return (static_cast<RegionPressure&>(P).TopPos ==
214 MachineBasicBlock::const_iterator());
217 /// Does this pressure result have a valid bottom position and live outs.
218 bool RegPressureTracker::isBottomClosed() const {
219 if (RequireIntervals)
220 return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
221 return (static_cast<RegionPressure&>(P).BottomPos ==
222 MachineBasicBlock::const_iterator());
226 SlotIndex RegPressureTracker::getCurrSlot() const {
227 MachineBasicBlock::const_iterator IdxPos = CurrPos;
228 while (IdxPos != MBB->end() && IdxPos->isDebugValue())
230 if (IdxPos == MBB->end())
231 return LIS->getMBBEndIdx(MBB);
232 return LIS->getInstructionIndex(IdxPos).getRegSlot();
235 /// Set the boundary for the top of the region and summarize live ins.
236 void RegPressureTracker::closeTop() {
237 if (RequireIntervals)
238 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
240 static_cast<RegionPressure&>(P).TopPos = CurrPos;
242 assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
243 P.LiveInRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
244 P.LiveInRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
245 for (SparseSet<unsigned>::const_iterator I =
246 LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
247 P.LiveInRegs.push_back(*I);
248 std::sort(P.LiveInRegs.begin(), P.LiveInRegs.end());
249 P.LiveInRegs.erase(std::unique(P.LiveInRegs.begin(), P.LiveInRegs.end()),
253 /// Set the boundary for the bottom of the region and summarize live outs.
254 void RegPressureTracker::closeBottom() {
255 if (RequireIntervals)
256 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
258 static_cast<RegionPressure&>(P).BottomPos = CurrPos;
260 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
261 P.LiveOutRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
262 P.LiveOutRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
263 for (SparseSet<unsigned>::const_iterator I =
264 LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
265 P.LiveOutRegs.push_back(*I);
266 std::sort(P.LiveOutRegs.begin(), P.LiveOutRegs.end());
267 P.LiveOutRegs.erase(std::unique(P.LiveOutRegs.begin(), P.LiveOutRegs.end()),
268 P.LiveOutRegs.end());
271 /// Finalize the region boundaries and record live ins and live outs.
272 void RegPressureTracker::closeRegion() {
273 if (!isTopClosed() && !isBottomClosed()) {
274 assert(LiveRegs.PhysRegs.empty() && LiveRegs.VirtRegs.empty() &&
275 "no region boundary");
278 if (!isBottomClosed())
280 else if (!isTopClosed())
282 // If both top and bottom are closed, do nothing.
285 /// The register tracker is unaware of global liveness so ignores normal
286 /// live-thru ranges. However, two-address or coalesced chains can also lead
287 /// to live ranges with no holes. Count these to inform heuristics that we
288 /// can never drop below this pressure.
289 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
290 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
291 assert(isBottomClosed() && "need bottom-up tracking to intialize.");
292 for (unsigned i = 0, e = P.LiveOutRegs.size(); i < e; ++i) {
293 unsigned Reg = P.LiveOutRegs[i];
294 if (TargetRegisterInfo::isVirtualRegister(Reg)
295 && !RPTracker.hasUntiedDef(Reg)) {
296 increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg));
301 /// \brief Convenient wrapper for checking membership in RegisterOperands.
302 /// (std::count() doesn't have an early exit).
303 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
304 return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
307 /// Collect this instruction's unique uses and defs into SmallVectors for
308 /// processing defs and uses in order.
310 /// FIXME: always ignore tied opers
311 class RegisterOperands {
312 const TargetRegisterInfo *TRI;
313 const MachineRegisterInfo *MRI;
317 SmallVector<unsigned, 8> Uses;
318 SmallVector<unsigned, 8> Defs;
319 SmallVector<unsigned, 8> DeadDefs;
321 RegisterOperands(const TargetRegisterInfo *tri,
322 const MachineRegisterInfo *mri, bool ID = false):
323 TRI(tri), MRI(mri), IgnoreDead(ID) {}
325 /// Push this operand's register onto the correct vector.
326 void collect(const MachineOperand &MO) {
327 if (!MO.isReg() || !MO.getReg())
330 pushRegUnits(MO.getReg(), Uses);
334 pushRegUnits(MO.getReg(), DeadDefs);
337 pushRegUnits(MO.getReg(), Defs);
342 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
343 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
344 if (containsReg(RegUnits, Reg))
346 RegUnits.push_back(Reg);
348 else if (MRI->isAllocatable(Reg)) {
349 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
350 if (containsReg(RegUnits, *Units))
352 RegUnits.push_back(*Units);
358 /// Collect physical and virtual register operands.
359 static void collectOperands(const MachineInstr *MI,
360 RegisterOperands &RegOpers) {
361 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
362 RegOpers.collect(*OperI);
364 // Remove redundant physreg dead defs.
365 SmallVectorImpl<unsigned>::iterator I =
366 std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
367 std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
368 RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
371 /// Initialize an array of N PressureDiffs.
372 void PressureDiffs::init(unsigned N) {
375 memset(PDiffArray, 0, N * sizeof(PressureDiff));
380 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
383 /// Add a change in pressure to the pressure diff of a given instruction.
384 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
385 const MachineRegisterInfo *MRI) {
386 PSetIterator PSetI = MRI->getPressureSets(RegUnit);
387 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
388 for (; PSetI.isValid(); ++PSetI) {
389 // Find an existing entry in the pressure diff for this PSet.
390 PressureDiff::iterator I = begin(), E = end();
391 for (; I != E && I->isValid(); ++I) {
392 if (I->getPSet() >= *PSetI)
395 // If all pressure sets are more constrained, skip the remaining PSets.
398 // Insert this PressureChange.
399 if (!I->isValid() || I->getPSet() != *PSetI) {
400 PressureChange PTmp = PressureChange(*PSetI);
401 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
404 // Update the units for this pressure set.
405 I->setUnitInc(I->getUnitInc() + Weight);
409 /// Record the pressure difference induced by the given operand list.
410 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
411 const MachineRegisterInfo *MRI) {
412 assert(!PDiff.begin()->isValid() && "stale PDiff");
414 for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
415 PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
417 for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
418 PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
421 /// Force liveness of registers.
422 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
423 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
424 if (LiveRegs.insert(Regs[i]))
425 increaseRegPressure(Regs[i]);
429 /// Add Reg to the live in set and increase max pressure.
430 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
431 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
432 if (containsReg(P.LiveInRegs, Reg))
435 // At live in discovery, unconditionally increase the high water mark.
436 P.LiveInRegs.push_back(Reg);
437 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
440 /// Add Reg to the live out set and increase max pressure.
441 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
442 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
443 if (containsReg(P.LiveOutRegs, Reg))
446 // At live out discovery, unconditionally increase the high water mark.
447 P.LiveOutRegs.push_back(Reg);
448 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
451 /// Recede across the previous instruction. If LiveUses is provided, record any
452 /// RegUnits that are made live by the current instruction's uses. This includes
453 /// registers that are both defined and used by the instruction. If a pressure
454 /// difference pointer is provided record the changes is pressure caused by this
455 /// instruction independent of liveness.
456 bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
457 PressureDiff *PDiff) {
458 // Check for the top of the analyzable region.
459 if (CurrPos == MBB->begin()) {
463 if (!isBottomClosed())
466 // Open the top of the region using block iterators.
467 if (!RequireIntervals && isTopClosed())
468 static_cast<RegionPressure&>(P).openTop(CurrPos);
470 // Find the previous instruction.
473 while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
475 if (CurrPos->isDebugValue()) {
480 if (RequireIntervals)
481 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
483 // Open the top of the region using slot indexes.
484 if (RequireIntervals && isTopClosed())
485 static_cast<IntervalPressure&>(P).openTop(SlotIdx);
487 RegisterOperands RegOpers(TRI, MRI);
488 collectOperands(CurrPos, RegOpers);
491 collectPDiff(*PDiff, RegOpers, MRI);
493 // Boost pressure for all dead defs together.
494 increaseRegPressure(RegOpers.DeadDefs);
495 decreaseRegPressure(RegOpers.DeadDefs);
497 // Kill liveness at live defs.
498 // TODO: consider earlyclobbers?
499 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
500 unsigned Reg = RegOpers.Defs[i];
501 bool DeadDef = false;
502 if (RequireIntervals) {
503 const LiveRange *LR = getLiveRange(Reg);
505 LiveQueryResult LRQ = LR->Query(SlotIdx);
506 DeadDef = LRQ.isDeadDef();
510 // LiveIntervals knows this is a dead even though it's MachineOperand is
511 // not flagged as such. Since this register will not be recorded as
512 // live-out, increase its PDiff value to avoid underflowing pressure.
514 PDiff->addPressureChange(Reg, false, MRI);
517 if (LiveRegs.erase(Reg))
518 decreaseRegPressure(Reg);
520 discoverLiveOut(Reg);
524 // Generate liveness for uses.
525 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
526 unsigned Reg = RegOpers.Uses[i];
527 if (!LiveRegs.contains(Reg)) {
528 // Adjust liveouts if LiveIntervals are available.
529 if (RequireIntervals) {
530 const LiveRange *LR = getLiveRange(Reg);
532 LiveQueryResult LRQ = LR->Query(SlotIdx);
533 if (!LRQ.isKill() && !LRQ.valueDefined())
534 discoverLiveOut(Reg);
537 increaseRegPressure(Reg);
538 LiveRegs.insert(Reg);
539 if (LiveUses && !containsReg(*LiveUses, Reg))
540 LiveUses->push_back(Reg);
543 if (TrackUntiedDefs) {
544 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
545 unsigned Reg = RegOpers.Defs[i];
546 if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
547 UntiedDefs.insert(Reg);
553 /// Advance across the current instruction.
554 bool RegPressureTracker::advance() {
555 assert(!TrackUntiedDefs && "unsupported mode");
557 // Check for the bottom of the analyzable region.
558 if (CurrPos == MBB->end()) {
566 if (RequireIntervals)
567 SlotIdx = getCurrSlot();
569 // Open the bottom of the region using slot indexes.
570 if (isBottomClosed()) {
571 if (RequireIntervals)
572 static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
574 static_cast<RegionPressure&>(P).openBottom(CurrPos);
577 RegisterOperands RegOpers(TRI, MRI);
578 collectOperands(CurrPos, RegOpers);
580 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
581 unsigned Reg = RegOpers.Uses[i];
582 // Discover live-ins.
583 bool isLive = LiveRegs.contains(Reg);
586 // Kill liveness at last uses.
587 bool lastUse = false;
588 if (RequireIntervals) {
589 const LiveRange *LR = getLiveRange(Reg);
590 lastUse = LR && LR->Query(SlotIdx).isKill();
593 // Allocatable physregs are always single-use before register rewriting.
594 lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
596 if (lastUse && isLive) {
598 decreaseRegPressure(Reg);
600 else if (!lastUse && !isLive)
601 increaseRegPressure(Reg);
604 // Generate liveness for defs.
605 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
606 unsigned Reg = RegOpers.Defs[i];
607 if (LiveRegs.insert(Reg))
608 increaseRegPressure(Reg);
611 // Boost pressure for all dead defs together.
612 increaseRegPressure(RegOpers.DeadDefs);
613 decreaseRegPressure(RegOpers.DeadDefs);
615 // Find the next instruction.
618 while (CurrPos != MBB->end() && CurrPos->isDebugValue());
622 /// Find the max change in excess pressure across all sets.
623 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
624 ArrayRef<unsigned> NewPressureVec,
625 RegPressureDelta &Delta,
626 const RegisterClassInfo *RCI,
627 ArrayRef<unsigned> LiveThruPressureVec) {
628 Delta.Excess = PressureChange();
629 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
630 unsigned POld = OldPressureVec[i];
631 unsigned PNew = NewPressureVec[i];
632 int PDiff = (int)PNew - (int)POld;
633 if (!PDiff) // No change in this set in the common case.
635 // Only consider change beyond the limit.
636 unsigned Limit = RCI->getRegPressureSetLimit(i);
637 if (!LiveThruPressureVec.empty())
638 Limit += LiveThruPressureVec[i];
642 PDiff = 0; // Under the limit
644 PDiff = PNew - Limit; // Just exceeded limit.
646 else if (Limit > PNew)
647 PDiff = Limit - POld; // Just obeyed limit.
650 Delta.Excess = PressureChange(i);
651 Delta.Excess.setUnitInc(PDiff);
657 /// Find the max change in max pressure that either surpasses a critical PSet
658 /// limit or exceeds the current MaxPressureLimit.
660 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
661 /// silly. It's done now to demonstrate the concept but will go away with a
662 /// RegPressureTracker API change to work with pressure differences.
663 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
664 ArrayRef<unsigned> NewMaxPressureVec,
665 ArrayRef<PressureChange> CriticalPSets,
666 ArrayRef<unsigned> MaxPressureLimit,
667 RegPressureDelta &Delta) {
668 Delta.CriticalMax = PressureChange();
669 Delta.CurrentMax = PressureChange();
671 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
672 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
673 unsigned POld = OldMaxPressureVec[i];
674 unsigned PNew = NewMaxPressureVec[i];
675 if (PNew == POld) // No change in this set in the common case.
678 if (!Delta.CriticalMax.isValid()) {
679 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
682 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
683 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
685 Delta.CriticalMax = PressureChange(i);
686 Delta.CriticalMax.setUnitInc(PDiff);
690 // Find the first increase above MaxPressureLimit.
691 // (Ignores negative MDiff).
692 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
693 Delta.CurrentMax = PressureChange(i);
694 Delta.CurrentMax.setUnitInc(PNew - POld);
695 if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
701 /// Record the upward impact of a single instruction on current register
702 /// pressure. Unlike the advance/recede pressure tracking interface, this does
703 /// not discover live in/outs.
705 /// This is intended for speculative queries. It leaves pressure inconsistent
706 /// with the current position, so must be restored by the caller.
707 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
708 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
710 // Account for register pressure similar to RegPressureTracker::recede().
711 RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
712 collectOperands(MI, RegOpers);
714 // Boost max pressure for all dead defs together.
715 // Since CurrSetPressure and MaxSetPressure
716 increaseRegPressure(RegOpers.DeadDefs);
717 decreaseRegPressure(RegOpers.DeadDefs);
719 // Kill liveness at live defs.
720 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
721 unsigned Reg = RegOpers.Defs[i];
722 bool DeadDef = false;
723 if (RequireIntervals) {
724 const LiveRange *LR = getLiveRange(Reg);
726 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
727 LiveQueryResult LRQ = LR->Query(SlotIdx);
728 DeadDef = LRQ.isDeadDef();
732 if (!containsReg(RegOpers.Uses, Reg))
733 decreaseRegPressure(Reg);
736 // Generate liveness for uses.
737 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
738 unsigned Reg = RegOpers.Uses[i];
739 if (!LiveRegs.contains(Reg))
740 increaseRegPressure(Reg);
744 /// Consider the pressure increase caused by traversing this instruction
745 /// bottom-up. Find the pressure set with the most change beyond its pressure
746 /// limit based on the tracker's current pressure, and return the change in
747 /// number of register units of that pressure set introduced by this
750 /// This assumes that the current LiveOut set is sufficient.
752 /// FIXME: This is expensive for an on-the-fly query. We need to cache the
753 /// result per-SUnit with enough information to adjust for the current
754 /// scheduling position. But this works as a proof of concept.
755 void RegPressureTracker::
756 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
757 RegPressureDelta &Delta,
758 ArrayRef<PressureChange> CriticalPSets,
759 ArrayRef<unsigned> MaxPressureLimit) {
760 // Snapshot Pressure.
761 // FIXME: The snapshot heap space should persist. But I'm planning to
762 // summarize the pressure effect so we don't need to snapshot at all.
763 std::vector<unsigned> SavedPressure = CurrSetPressure;
764 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
766 bumpUpwardPressure(MI);
768 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
770 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
771 MaxPressureLimit, Delta);
772 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
773 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
775 // Restore the tracker's state.
776 P.MaxSetPressure.swap(SavedMaxPressure);
777 CurrSetPressure.swap(SavedPressure);
783 // Check if the alternate algorithm yields the same result.
784 RegPressureDelta Delta2;
785 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
786 if (Delta != Delta2) {
787 dbgs() << "DELTA: " << *MI;
788 if (Delta.Excess.isValid())
789 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
790 << " " << Delta.Excess.getUnitInc() << "\n";
791 if (Delta.CriticalMax.isValid())
792 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
793 << " " << Delta.CriticalMax.getUnitInc() << "\n";
794 if (Delta.CurrentMax.isValid())
795 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
796 << " " << Delta.CurrentMax.getUnitInc() << "\n";
797 if (Delta2.Excess.isValid())
798 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
799 << " " << Delta2.Excess.getUnitInc() << "\n";
800 if (Delta2.CriticalMax.isValid())
801 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
802 << " " << Delta2.CriticalMax.getUnitInc() << "\n";
803 if (Delta2.CurrentMax.isValid())
804 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
805 << " " << Delta2.CurrentMax.getUnitInc() << "\n";
806 llvm_unreachable("RegP Delta Mismatch");
811 /// This is a prototype of the fast version of querying register pressure that
812 /// does not directly depend on current liveness. It's still slow because we
813 /// recompute pressure change on-the-fly. This implementation only exists to
814 /// prove correctness.
816 /// @param Delta captures information needed for heuristics.
818 /// @param CriticalPSets Are the pressure sets that are known to exceed some
819 /// limit within the region, not necessarily at the current position.
821 /// @param MaxPressureLimit Is the max pressure within the region, not
822 /// necessarily at the current position.
823 void RegPressureTracker::
824 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
825 RegPressureDelta &Delta,
826 ArrayRef<PressureChange> CriticalPSets,
827 ArrayRef<unsigned> MaxPressureLimit) const {
828 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
829 for (PressureDiff::const_iterator
830 PDiffI = PDiff.begin(), PDiffE = PDiff.end();
831 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
833 unsigned PSetID = PDiffI->getPSet();
834 unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
835 if (!LiveThruPressure.empty())
836 Limit += LiveThruPressure[PSetID];
838 unsigned POld = CurrSetPressure[PSetID];
839 unsigned MOld = P.MaxSetPressure[PSetID];
840 unsigned MNew = MOld;
841 // Ignore DeadDefs here because they aren't captured by PressureChange.
842 unsigned PNew = POld + PDiffI->getUnitInc();
843 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
846 // Check if current pressure has exceeded the limit.
847 if (!Delta.Excess.isValid()) {
848 unsigned ExcessInc = 0;
850 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
851 else if (POld > Limit)
852 ExcessInc = Limit - POld;
854 Delta.Excess = PressureChange(PSetID);
855 Delta.Excess.setUnitInc(ExcessInc);
858 // Check if max pressure has exceeded a critical pressure set max.
861 if (!Delta.CriticalMax.isValid()) {
862 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
865 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
866 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
867 if (CritInc > 0 && CritInc <= INT16_MAX) {
868 Delta.CriticalMax = PressureChange(PSetID);
869 Delta.CriticalMax.setUnitInc(CritInc);
873 // Check if max pressure has exceeded the current max.
874 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
875 Delta.CurrentMax = PressureChange(PSetID);
876 Delta.CurrentMax.setUnitInc(MNew - MOld);
881 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
882 static bool findUseBetween(unsigned Reg,
883 SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
884 const MachineRegisterInfo *MRI,
885 const LiveIntervals *LIS) {
886 for (MachineRegisterInfo::use_nodbg_iterator
887 UI = MRI->use_nodbg_begin(Reg), UE = MRI->use_nodbg_end();
888 UI != UE; UI.skipInstruction()) {
889 const MachineInstr* MI = &*UI;
890 if (MI->isDebugValue())
892 SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot();
893 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
899 /// Record the downward impact of a single instruction on current register
900 /// pressure. Unlike the advance/recede pressure tracking interface, this does
901 /// not discover live in/outs.
903 /// This is intended for speculative queries. It leaves pressure inconsistent
904 /// with the current position, so must be restored by the caller.
905 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
906 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
908 // Account for register pressure similar to RegPressureTracker::recede().
909 RegisterOperands RegOpers(TRI, MRI);
910 collectOperands(MI, RegOpers);
912 // Kill liveness at last uses. Assume allocatable physregs are single-use
913 // rather than checking LiveIntervals.
915 if (RequireIntervals)
916 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
918 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
919 unsigned Reg = RegOpers.Uses[i];
920 if (RequireIntervals) {
921 // FIXME: allow the caller to pass in the list of vreg uses that remain
922 // to be bottom-scheduled to avoid searching uses at each query.
923 SlotIndex CurrIdx = getCurrSlot();
924 const LiveRange *LR = getLiveRange(Reg);
926 LiveQueryResult LRQ = LR->Query(SlotIdx);
927 if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) {
928 decreaseRegPressure(Reg);
932 else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
933 // Allocatable physregs are always single-use before register rewriting.
934 decreaseRegPressure(Reg);
938 // Generate liveness for defs.
939 increaseRegPressure(RegOpers.Defs);
941 // Boost pressure for all dead defs together.
942 increaseRegPressure(RegOpers.DeadDefs);
943 decreaseRegPressure(RegOpers.DeadDefs);
946 /// Consider the pressure increase caused by traversing this instruction
947 /// top-down. Find the register class with the most change in its pressure limit
948 /// based on the tracker's current pressure, and return the number of excess
949 /// register units of that pressure set introduced by this instruction.
951 /// This assumes that the current LiveIn set is sufficient.
952 void RegPressureTracker::
953 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
954 ArrayRef<PressureChange> CriticalPSets,
955 ArrayRef<unsigned> MaxPressureLimit) {
956 // Snapshot Pressure.
957 std::vector<unsigned> SavedPressure = CurrSetPressure;
958 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
960 bumpDownwardPressure(MI);
962 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
964 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
965 MaxPressureLimit, Delta);
966 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
967 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
969 // Restore the tracker's state.
970 P.MaxSetPressure.swap(SavedMaxPressure);
971 CurrSetPressure.swap(SavedPressure);
974 /// Get the pressure of each PSet after traversing this instruction bottom-up.
975 void RegPressureTracker::
976 getUpwardPressure(const MachineInstr *MI,
977 std::vector<unsigned> &PressureResult,
978 std::vector<unsigned> &MaxPressureResult) {
979 // Snapshot pressure.
980 PressureResult = CurrSetPressure;
981 MaxPressureResult = P.MaxSetPressure;
983 bumpUpwardPressure(MI);
985 // Current pressure becomes the result. Restore current pressure.
986 P.MaxSetPressure.swap(MaxPressureResult);
987 CurrSetPressure.swap(PressureResult);
990 /// Get the pressure of each PSet after traversing this instruction top-down.
991 void RegPressureTracker::
992 getDownwardPressure(const MachineInstr *MI,
993 std::vector<unsigned> &PressureResult,
994 std::vector<unsigned> &MaxPressureResult) {
995 // Snapshot pressure.
996 PressureResult = CurrSetPressure;
997 MaxPressureResult = P.MaxSetPressure;
999 bumpDownwardPressure(MI);
1001 // Current pressure becomes the result. Restore current pressure.
1002 P.MaxSetPressure.swap(MaxPressureResult);
1003 CurrSetPressure.swap(PressureResult);