LLVM API Documentation

RegisterPressure.cpp
Go to the documentation of this file.
00001 //===-- RegisterPressure.cpp - Dynamic Register Pressure ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the RegisterPressure class which can be used to track
00011 // MachineInstr level register pressure.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/RegisterPressure.h"
00016 #include "llvm/CodeGen/LiveInterval.h"
00017 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00018 #include "llvm/CodeGen/MachineRegisterInfo.h"
00019 #include "llvm/CodeGen/RegisterClassInfo.h"
00020 #include "llvm/Support/Debug.h"
00021 #include "llvm/Support/raw_ostream.h"
00022 #include "llvm/Target/TargetMachine.h"
00023 
00024 using namespace llvm;
00025 
00026 /// Increase pressure for each pressure set provided by TargetRegisterInfo.
00027 static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure,
00028                                 PSetIterator PSetI) {
00029   unsigned Weight = PSetI.getWeight();
00030   for (; PSetI.isValid(); ++PSetI)
00031     CurrSetPressure[*PSetI] += Weight;
00032 }
00033 
00034 /// Decrease pressure for each pressure set provided by TargetRegisterInfo.
00035 static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure,
00036                                 PSetIterator PSetI) {
00037   unsigned Weight = PSetI.getWeight();
00038   for (; PSetI.isValid(); ++PSetI) {
00039     assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow");
00040     CurrSetPressure[*PSetI] -= Weight;
00041   }
00042 }
00043 
00044 LLVM_DUMP_METHOD
00045 void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
00046                               const TargetRegisterInfo *TRI) {
00047   bool Empty = true;
00048   for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) {
00049     if (SetPressure[i] != 0) {
00050       dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << '\n';
00051       Empty = false;
00052     }
00053   }
00054   if (Empty)
00055     dbgs() << "\n";
00056 }
00057 
00058 LLVM_DUMP_METHOD
00059 void RegisterPressure::dump(const TargetRegisterInfo *TRI) const {
00060   dbgs() << "Max Pressure: ";
00061   dumpRegSetPressure(MaxSetPressure, TRI);
00062   dbgs() << "Live In: ";
00063   for (unsigned i = 0, e = LiveInRegs.size(); i < e; ++i)
00064     dbgs() << PrintReg(LiveInRegs[i], TRI) << " ";
00065   dbgs() << '\n';
00066   dbgs() << "Live Out: ";
00067   for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i)
00068     dbgs() << PrintReg(LiveOutRegs[i], TRI) << " ";
00069   dbgs() << '\n';
00070 }
00071 
00072 LLVM_DUMP_METHOD
00073 void RegPressureTracker::dump() const {
00074   if (!isTopClosed() || !isBottomClosed()) {
00075     dbgs() << "Curr Pressure: ";
00076     dumpRegSetPressure(CurrSetPressure, TRI);
00077   }
00078   P.dump(TRI);
00079 }
00080 
00081 /// Increase the current pressure as impacted by these registers and bump
00082 /// the high water mark if needed.
00083 void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) {
00084   for (unsigned i = 0, e = RegUnits.size(); i != e; ++i) {
00085     PSetIterator PSetI = MRI->getPressureSets(RegUnits[i]);
00086     unsigned Weight = PSetI.getWeight();
00087     for (; PSetI.isValid(); ++PSetI) {
00088       CurrSetPressure[*PSetI] += Weight;
00089       if (CurrSetPressure[*PSetI] > P.MaxSetPressure[*PSetI]) {
00090         P.MaxSetPressure[*PSetI] = CurrSetPressure[*PSetI];
00091       }
00092     }
00093   }
00094 }
00095 
00096 /// Simply decrease the current pressure as impacted by these registers.
00097 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) {
00098   for (unsigned I = 0, E = RegUnits.size(); I != E; ++I)
00099     decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnits[I]));
00100 }
00101 
00102 /// Clear the result so it can be used for another round of pressure tracking.
00103 void IntervalPressure::reset() {
00104   TopIdx = BottomIdx = SlotIndex();
00105   MaxSetPressure.clear();
00106   LiveInRegs.clear();
00107   LiveOutRegs.clear();
00108 }
00109 
00110 /// Clear the result so it can be used for another round of pressure tracking.
00111 void RegionPressure::reset() {
00112   TopPos = BottomPos = MachineBasicBlock::const_iterator();
00113   MaxSetPressure.clear();
00114   LiveInRegs.clear();
00115   LiveOutRegs.clear();
00116 }
00117 
00118 /// If the current top is not less than or equal to the next index, open it.
00119 /// We happen to need the SlotIndex for the next top for pressure update.
00120 void IntervalPressure::openTop(SlotIndex NextTop) {
00121   if (TopIdx <= NextTop)
00122     return;
00123   TopIdx = SlotIndex();
00124   LiveInRegs.clear();
00125 }
00126 
00127 /// If the current top is the previous instruction (before receding), open it.
00128 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
00129   if (TopPos != PrevTop)
00130     return;
00131   TopPos = MachineBasicBlock::const_iterator();
00132   LiveInRegs.clear();
00133 }
00134 
00135 /// If the current bottom is not greater than the previous index, open it.
00136 void IntervalPressure::openBottom(SlotIndex PrevBottom) {
00137   if (BottomIdx > PrevBottom)
00138     return;
00139   BottomIdx = SlotIndex();
00140   LiveInRegs.clear();
00141 }
00142 
00143 /// If the current bottom is the previous instr (before advancing), open it.
00144 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
00145   if (BottomPos != PrevBottom)
00146     return;
00147   BottomPos = MachineBasicBlock::const_iterator();
00148   LiveInRegs.clear();
00149 }
00150 
00151 const LiveRange *RegPressureTracker::getLiveRange(unsigned Reg) const {
00152   if (TargetRegisterInfo::isVirtualRegister(Reg))
00153     return &LIS->getInterval(Reg);
00154   return LIS->getCachedRegUnit(Reg);
00155 }
00156 
00157 void RegPressureTracker::reset() {
00158   MBB = nullptr;
00159   LIS = nullptr;
00160 
00161   CurrSetPressure.clear();
00162   LiveThruPressure.clear();
00163   P.MaxSetPressure.clear();
00164 
00165   if (RequireIntervals)
00166     static_cast<IntervalPressure&>(P).reset();
00167   else
00168     static_cast<RegionPressure&>(P).reset();
00169 
00170   LiveRegs.PhysRegs.clear();
00171   LiveRegs.VirtRegs.clear();
00172   UntiedDefs.clear();
00173 }
00174 
00175 /// Setup the RegPressureTracker.
00176 ///
00177 /// TODO: Add support for pressure without LiveIntervals.
00178 void RegPressureTracker::init(const MachineFunction *mf,
00179                               const RegisterClassInfo *rci,
00180                               const LiveIntervals *lis,
00181                               const MachineBasicBlock *mbb,
00182                               MachineBasicBlock::const_iterator pos,
00183                               bool ShouldTrackUntiedDefs)
00184 {
00185   reset();
00186 
00187   MF = mf;
00188   TRI = MF->getSubtarget().getRegisterInfo();
00189   RCI = rci;
00190   MRI = &MF->getRegInfo();
00191   MBB = mbb;
00192   TrackUntiedDefs = ShouldTrackUntiedDefs;
00193 
00194   if (RequireIntervals) {
00195     assert(lis && "IntervalPressure requires LiveIntervals");
00196     LIS = lis;
00197   }
00198 
00199   CurrPos = pos;
00200   CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
00201 
00202   P.MaxSetPressure = CurrSetPressure;
00203 
00204   LiveRegs.PhysRegs.setUniverse(TRI->getNumRegs());
00205   LiveRegs.VirtRegs.setUniverse(MRI->getNumVirtRegs());
00206   if (TrackUntiedDefs)
00207     UntiedDefs.setUniverse(MRI->getNumVirtRegs());
00208 }
00209 
00210 /// Does this pressure result have a valid top position and live ins.
00211 bool RegPressureTracker::isTopClosed() const {
00212   if (RequireIntervals)
00213     return static_cast<IntervalPressure&>(P).TopIdx.isValid();
00214   return (static_cast<RegionPressure&>(P).TopPos ==
00215           MachineBasicBlock::const_iterator());
00216 }
00217 
00218 /// Does this pressure result have a valid bottom position and live outs.
00219 bool RegPressureTracker::isBottomClosed() const {
00220   if (RequireIntervals)
00221     return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
00222   return (static_cast<RegionPressure&>(P).BottomPos ==
00223           MachineBasicBlock::const_iterator());
00224 }
00225 
00226 
00227 SlotIndex RegPressureTracker::getCurrSlot() const {
00228   MachineBasicBlock::const_iterator IdxPos = CurrPos;
00229   while (IdxPos != MBB->end() && IdxPos->isDebugValue())
00230     ++IdxPos;
00231   if (IdxPos == MBB->end())
00232     return LIS->getMBBEndIdx(MBB);
00233   return LIS->getInstructionIndex(IdxPos).getRegSlot();
00234 }
00235 
00236 /// Set the boundary for the top of the region and summarize live ins.
00237 void RegPressureTracker::closeTop() {
00238   if (RequireIntervals)
00239     static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
00240   else
00241     static_cast<RegionPressure&>(P).TopPos = CurrPos;
00242 
00243   assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
00244   P.LiveInRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
00245   P.LiveInRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
00246   for (SparseSet<unsigned>::const_iterator I =
00247          LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
00248     P.LiveInRegs.push_back(*I);
00249   std::sort(P.LiveInRegs.begin(), P.LiveInRegs.end());
00250   P.LiveInRegs.erase(std::unique(P.LiveInRegs.begin(), P.LiveInRegs.end()),
00251                      P.LiveInRegs.end());
00252 }
00253 
00254 /// Set the boundary for the bottom of the region and summarize live outs.
00255 void RegPressureTracker::closeBottom() {
00256   if (RequireIntervals)
00257     static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
00258   else
00259     static_cast<RegionPressure&>(P).BottomPos = CurrPos;
00260 
00261   assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
00262   P.LiveOutRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
00263   P.LiveOutRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
00264   for (SparseSet<unsigned>::const_iterator I =
00265          LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
00266     P.LiveOutRegs.push_back(*I);
00267   std::sort(P.LiveOutRegs.begin(), P.LiveOutRegs.end());
00268   P.LiveOutRegs.erase(std::unique(P.LiveOutRegs.begin(), P.LiveOutRegs.end()),
00269                       P.LiveOutRegs.end());
00270 }
00271 
00272 /// Finalize the region boundaries and record live ins and live outs.
00273 void RegPressureTracker::closeRegion() {
00274   if (!isTopClosed() && !isBottomClosed()) {
00275     assert(LiveRegs.PhysRegs.empty() && LiveRegs.VirtRegs.empty() &&
00276            "no region boundary");
00277     return;
00278   }
00279   if (!isBottomClosed())
00280     closeBottom();
00281   else if (!isTopClosed())
00282     closeTop();
00283   // If both top and bottom are closed, do nothing.
00284 }
00285 
00286 /// The register tracker is unaware of global liveness so ignores normal
00287 /// live-thru ranges. However, two-address or coalesced chains can also lead
00288 /// to live ranges with no holes. Count these to inform heuristics that we
00289 /// can never drop below this pressure.
00290 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
00291   LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
00292   assert(isBottomClosed() && "need bottom-up tracking to intialize.");
00293   for (unsigned i = 0, e = P.LiveOutRegs.size(); i < e; ++i) {
00294     unsigned Reg = P.LiveOutRegs[i];
00295     if (TargetRegisterInfo::isVirtualRegister(Reg)
00296         && !RPTracker.hasUntiedDef(Reg)) {
00297       increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg));
00298     }
00299   }
00300 }
00301 
00302 /// \brief Convenient wrapper for checking membership in RegisterOperands.
00303 /// (std::count() doesn't have an early exit).
00304 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
00305   return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
00306 }
00307 
00308 /// Collect this instruction's unique uses and defs into SmallVectors for
00309 /// processing defs and uses in order.
00310 ///
00311 /// FIXME: always ignore tied opers
00312 class RegisterOperands {
00313   const TargetRegisterInfo *TRI;
00314   const MachineRegisterInfo *MRI;
00315   bool IgnoreDead;
00316 
00317 public:
00318   SmallVector<unsigned, 8> Uses;
00319   SmallVector<unsigned, 8> Defs;
00320   SmallVector<unsigned, 8> DeadDefs;
00321 
00322   RegisterOperands(const TargetRegisterInfo *tri,
00323                    const MachineRegisterInfo *mri, bool ID = false):
00324     TRI(tri), MRI(mri), IgnoreDead(ID) {}
00325 
00326   /// Push this operand's register onto the correct vector.
00327   void collect(const MachineOperand &MO) {
00328     if (!MO.isReg() || !MO.getReg())
00329       return;
00330     if (MO.readsReg())
00331       pushRegUnits(MO.getReg(), Uses);
00332     if (MO.isDef()) {
00333       if (MO.isDead()) {
00334         if (!IgnoreDead)
00335           pushRegUnits(MO.getReg(), DeadDefs);
00336       }
00337       else
00338         pushRegUnits(MO.getReg(), Defs);
00339     }
00340   }
00341 
00342 protected:
00343   void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
00344     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00345       if (containsReg(RegUnits, Reg))
00346         return;
00347       RegUnits.push_back(Reg);
00348     }
00349     else if (MRI->isAllocatable(Reg)) {
00350       for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
00351         if (containsReg(RegUnits, *Units))
00352           continue;
00353         RegUnits.push_back(*Units);
00354       }
00355     }
00356   }
00357 };
00358 
00359 /// Collect physical and virtual register operands.
00360 static void collectOperands(const MachineInstr *MI,
00361                             RegisterOperands &RegOpers) {
00362   for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
00363     RegOpers.collect(*OperI);
00364 
00365   // Remove redundant physreg dead defs.
00366   SmallVectorImpl<unsigned>::iterator I =
00367     std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
00368                    std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
00369   RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
00370 }
00371 
00372 /// Initialize an array of N PressureDiffs.
00373 void PressureDiffs::init(unsigned N) {
00374   Size = N;
00375   if (N <= Max) {
00376     memset(PDiffArray, 0, N * sizeof(PressureDiff));
00377     return;
00378   }
00379   Max = Size;
00380   free(PDiffArray);
00381   PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
00382 }
00383 
00384 /// Add a change in pressure to the pressure diff of a given instruction.
00385 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
00386                                      const MachineRegisterInfo *MRI) {
00387   PSetIterator PSetI = MRI->getPressureSets(RegUnit);
00388   int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
00389   for (; PSetI.isValid(); ++PSetI) {
00390     // Find an existing entry in the pressure diff for this PSet.
00391     PressureDiff::iterator I = begin(), E = end();
00392     for (; I != E && I->isValid(); ++I) {
00393       if (I->getPSet() >= *PSetI)
00394         break;
00395     }
00396     // If all pressure sets are more constrained, skip the remaining PSets.
00397     if (I == E)
00398       break;
00399     // Insert this PressureChange.
00400     if (!I->isValid() || I->getPSet() != *PSetI) {
00401       PressureChange PTmp = PressureChange(*PSetI);
00402       for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
00403         std::swap(*J,PTmp);
00404     }
00405     // Update the units for this pressure set.
00406     I->setUnitInc(I->getUnitInc() + Weight);
00407   }
00408 }
00409 
00410 /// Record the pressure difference induced by the given operand list.
00411 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
00412                          const MachineRegisterInfo *MRI) {
00413   assert(!PDiff.begin()->isValid() && "stale PDiff");
00414 
00415   for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
00416     PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
00417 
00418   for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
00419     PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
00420 }
00421 
00422 /// Force liveness of registers.
00423 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
00424   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
00425     if (LiveRegs.insert(Regs[i]))
00426       increaseRegPressure(Regs[i]);
00427   }
00428 }
00429 
00430 /// Add Reg to the live in set and increase max pressure.
00431 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
00432   assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
00433   if (containsReg(P.LiveInRegs, Reg))
00434     return;
00435 
00436   // At live in discovery, unconditionally increase the high water mark.
00437   P.LiveInRegs.push_back(Reg);
00438   increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
00439 }
00440 
00441 /// Add Reg to the live out set and increase max pressure.
00442 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
00443   assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
00444   if (containsReg(P.LiveOutRegs, Reg))
00445     return;
00446 
00447   // At live out discovery, unconditionally increase the high water mark.
00448   P.LiveOutRegs.push_back(Reg);
00449   increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
00450 }
00451 
00452 /// Recede across the previous instruction. If LiveUses is provided, record any
00453 /// RegUnits that are made live by the current instruction's uses. This includes
00454 /// registers that are both defined and used by the instruction.  If a pressure
00455 /// difference pointer is provided record the changes is pressure caused by this
00456 /// instruction independent of liveness.
00457 bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
00458                                 PressureDiff *PDiff) {
00459   // Check for the top of the analyzable region.
00460   if (CurrPos == MBB->begin()) {
00461     closeRegion();
00462     return false;
00463   }
00464   if (!isBottomClosed())
00465     closeBottom();
00466 
00467   // Open the top of the region using block iterators.
00468   if (!RequireIntervals && isTopClosed())
00469     static_cast<RegionPressure&>(P).openTop(CurrPos);
00470 
00471   // Find the previous instruction.
00472   do
00473     --CurrPos;
00474   while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
00475 
00476   if (CurrPos->isDebugValue()) {
00477     closeRegion();
00478     return false;
00479   }
00480   SlotIndex SlotIdx;
00481   if (RequireIntervals)
00482     SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
00483 
00484   // Open the top of the region using slot indexes.
00485   if (RequireIntervals && isTopClosed())
00486     static_cast<IntervalPressure&>(P).openTop(SlotIdx);
00487 
00488   RegisterOperands RegOpers(TRI, MRI);
00489   collectOperands(CurrPos, RegOpers);
00490 
00491   if (PDiff)
00492     collectPDiff(*PDiff, RegOpers, MRI);
00493 
00494   // Boost pressure for all dead defs together.
00495   increaseRegPressure(RegOpers.DeadDefs);
00496   decreaseRegPressure(RegOpers.DeadDefs);
00497 
00498   // Kill liveness at live defs.
00499   // TODO: consider earlyclobbers?
00500   for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
00501     unsigned Reg = RegOpers.Defs[i];
00502     bool DeadDef = false;
00503     if (RequireIntervals) {
00504       const LiveRange *LR = getLiveRange(Reg);
00505       if (LR) {
00506         LiveQueryResult LRQ = LR->Query(SlotIdx);
00507         DeadDef = LRQ.isDeadDef();
00508       }
00509     }
00510     if (DeadDef) {
00511       // LiveIntervals knows this is a dead even though it's MachineOperand is
00512       // not flagged as such. Since this register will not be recorded as
00513       // live-out, increase its PDiff value to avoid underflowing pressure.
00514       if (PDiff)
00515         PDiff->addPressureChange(Reg, false, MRI);
00516     } else {
00517       if (LiveRegs.erase(Reg))
00518         decreaseRegPressure(Reg);
00519       else
00520         discoverLiveOut(Reg);
00521     }
00522   }
00523 
00524   // Generate liveness for uses.
00525   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
00526     unsigned Reg = RegOpers.Uses[i];
00527     if (!LiveRegs.contains(Reg)) {
00528       // Adjust liveouts if LiveIntervals are available.
00529       if (RequireIntervals) {
00530         const LiveRange *LR = getLiveRange(Reg);
00531         if (LR) {
00532           LiveQueryResult LRQ = LR->Query(SlotIdx);
00533           if (!LRQ.isKill() && !LRQ.valueDefined())
00534             discoverLiveOut(Reg);
00535         }
00536       }
00537       increaseRegPressure(Reg);
00538       LiveRegs.insert(Reg);
00539       if (LiveUses && !containsReg(*LiveUses, Reg))
00540         LiveUses->push_back(Reg);
00541     }
00542   }
00543   if (TrackUntiedDefs) {
00544     for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
00545       unsigned Reg = RegOpers.Defs[i];
00546       if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
00547         UntiedDefs.insert(Reg);
00548     }
00549   }
00550   return true;
00551 }
00552 
00553 /// Advance across the current instruction.
00554 bool RegPressureTracker::advance() {
00555   assert(!TrackUntiedDefs && "unsupported mode");
00556 
00557   // Check for the bottom of the analyzable region.
00558   if (CurrPos == MBB->end()) {
00559     closeRegion();
00560     return false;
00561   }
00562   if (!isTopClosed())
00563     closeTop();
00564 
00565   SlotIndex SlotIdx;
00566   if (RequireIntervals)
00567     SlotIdx = getCurrSlot();
00568 
00569   // Open the bottom of the region using slot indexes.
00570   if (isBottomClosed()) {
00571     if (RequireIntervals)
00572       static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
00573     else
00574       static_cast<RegionPressure&>(P).openBottom(CurrPos);
00575   }
00576 
00577   RegisterOperands RegOpers(TRI, MRI);
00578   collectOperands(CurrPos, RegOpers);
00579 
00580   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
00581     unsigned Reg = RegOpers.Uses[i];
00582     // Discover live-ins.
00583     bool isLive = LiveRegs.contains(Reg);
00584     if (!isLive)
00585       discoverLiveIn(Reg);
00586     // Kill liveness at last uses.
00587     bool lastUse = false;
00588     if (RequireIntervals) {
00589       const LiveRange *LR = getLiveRange(Reg);
00590       lastUse = LR && LR->Query(SlotIdx).isKill();
00591     }
00592     else {
00593       // Allocatable physregs are always single-use before register rewriting.
00594       lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
00595     }
00596     if (lastUse && isLive) {
00597       LiveRegs.erase(Reg);
00598       decreaseRegPressure(Reg);
00599     }
00600     else if (!lastUse && !isLive)
00601       increaseRegPressure(Reg);
00602   }
00603 
00604   // Generate liveness for defs.
00605   for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
00606     unsigned Reg = RegOpers.Defs[i];
00607     if (LiveRegs.insert(Reg))
00608       increaseRegPressure(Reg);
00609   }
00610 
00611   // Boost pressure for all dead defs together.
00612   increaseRegPressure(RegOpers.DeadDefs);
00613   decreaseRegPressure(RegOpers.DeadDefs);
00614 
00615   // Find the next instruction.
00616   do
00617     ++CurrPos;
00618   while (CurrPos != MBB->end() && CurrPos->isDebugValue());
00619   return true;
00620 }
00621 
00622 /// Find the max change in excess pressure across all sets.
00623 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
00624                                        ArrayRef<unsigned> NewPressureVec,
00625                                        RegPressureDelta &Delta,
00626                                        const RegisterClassInfo *RCI,
00627                                        ArrayRef<unsigned> LiveThruPressureVec) {
00628   Delta.Excess = PressureChange();
00629   for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
00630     unsigned POld = OldPressureVec[i];
00631     unsigned PNew = NewPressureVec[i];
00632     int PDiff = (int)PNew - (int)POld;
00633     if (!PDiff) // No change in this set in the common case.
00634       continue;
00635     // Only consider change beyond the limit.
00636     unsigned Limit = RCI->getRegPressureSetLimit(i);
00637     if (!LiveThruPressureVec.empty())
00638       Limit += LiveThruPressureVec[i];
00639 
00640     if (Limit > POld) {
00641       if (Limit > PNew)
00642         PDiff = 0;            // Under the limit
00643       else
00644         PDiff = PNew - Limit; // Just exceeded limit.
00645     }
00646     else if (Limit > PNew)
00647       PDiff = Limit - POld;   // Just obeyed limit.
00648 
00649     if (PDiff) {
00650       Delta.Excess = PressureChange(i);
00651       Delta.Excess.setUnitInc(PDiff);
00652       break;
00653     }
00654   }
00655 }
00656 
00657 /// Find the max change in max pressure that either surpasses a critical PSet
00658 /// limit or exceeds the current MaxPressureLimit.
00659 ///
00660 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
00661 /// silly. It's done now to demonstrate the concept but will go away with a
00662 /// RegPressureTracker API change to work with pressure differences.
00663 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
00664                                     ArrayRef<unsigned> NewMaxPressureVec,
00665                                     ArrayRef<PressureChange> CriticalPSets,
00666                                     ArrayRef<unsigned> MaxPressureLimit,
00667                                     RegPressureDelta &Delta) {
00668   Delta.CriticalMax = PressureChange();
00669   Delta.CurrentMax = PressureChange();
00670 
00671   unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
00672   for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
00673     unsigned POld = OldMaxPressureVec[i];
00674     unsigned PNew = NewMaxPressureVec[i];
00675     if (PNew == POld) // No change in this set in the common case.
00676       continue;
00677 
00678     if (!Delta.CriticalMax.isValid()) {
00679       while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
00680         ++CritIdx;
00681 
00682       if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
00683         int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
00684         if (PDiff > 0) {
00685           Delta.CriticalMax = PressureChange(i);
00686           Delta.CriticalMax.setUnitInc(PDiff);
00687         }
00688       }
00689     }
00690     // Find the first increase above MaxPressureLimit.
00691     // (Ignores negative MDiff).
00692     if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
00693       Delta.CurrentMax = PressureChange(i);
00694       Delta.CurrentMax.setUnitInc(PNew - POld);
00695       if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
00696         break;
00697     }
00698   }
00699 }
00700 
00701 /// Record the upward impact of a single instruction on current register
00702 /// pressure. Unlike the advance/recede pressure tracking interface, this does
00703 /// not discover live in/outs.
00704 ///
00705 /// This is intended for speculative queries. It leaves pressure inconsistent
00706 /// with the current position, so must be restored by the caller.
00707 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
00708   assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
00709 
00710   // Account for register pressure similar to RegPressureTracker::recede().
00711   RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
00712   collectOperands(MI, RegOpers);
00713 
00714   // Boost max pressure for all dead defs together.
00715   // Since CurrSetPressure and MaxSetPressure
00716   increaseRegPressure(RegOpers.DeadDefs);
00717   decreaseRegPressure(RegOpers.DeadDefs);
00718 
00719   // Kill liveness at live defs.
00720   for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
00721     unsigned Reg = RegOpers.Defs[i];
00722     bool DeadDef = false;
00723     if (RequireIntervals) {
00724       const LiveRange *LR = getLiveRange(Reg);
00725       if (LR) {
00726         SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
00727         LiveQueryResult LRQ = LR->Query(SlotIdx);
00728         DeadDef = LRQ.isDeadDef();
00729       }
00730     }
00731     if (!DeadDef) {
00732       if (!containsReg(RegOpers.Uses, Reg))
00733         decreaseRegPressure(Reg);
00734     }
00735   }
00736   // Generate liveness for uses.
00737   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
00738     unsigned Reg = RegOpers.Uses[i];
00739     if (!LiveRegs.contains(Reg))
00740       increaseRegPressure(Reg);
00741   }
00742 }
00743 
00744 /// Consider the pressure increase caused by traversing this instruction
00745 /// bottom-up. Find the pressure set with the most change beyond its pressure
00746 /// limit based on the tracker's current pressure, and return the change in
00747 /// number of register units of that pressure set introduced by this
00748 /// instruction.
00749 ///
00750 /// This assumes that the current LiveOut set is sufficient.
00751 ///
00752 /// FIXME: This is expensive for an on-the-fly query. We need to cache the
00753 /// result per-SUnit with enough information to adjust for the current
00754 /// scheduling position. But this works as a proof of concept.
00755 void RegPressureTracker::
00756 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
00757                           RegPressureDelta &Delta,
00758                           ArrayRef<PressureChange> CriticalPSets,
00759                           ArrayRef<unsigned> MaxPressureLimit) {
00760   // Snapshot Pressure.
00761   // FIXME: The snapshot heap space should persist. But I'm planning to
00762   // summarize the pressure effect so we don't need to snapshot at all.
00763   std::vector<unsigned> SavedPressure = CurrSetPressure;
00764   std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
00765 
00766   bumpUpwardPressure(MI);
00767 
00768   computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
00769                              LiveThruPressure);
00770   computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
00771                           MaxPressureLimit, Delta);
00772   assert(Delta.CriticalMax.getUnitInc() >= 0 &&
00773          Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
00774 
00775   // Restore the tracker's state.
00776   P.MaxSetPressure.swap(SavedMaxPressure);
00777   CurrSetPressure.swap(SavedPressure);
00778 
00779 #ifndef NDEBUG
00780   if (!PDiff)
00781     return;
00782 
00783   // Check if the alternate algorithm yields the same result.
00784   RegPressureDelta Delta2;
00785   getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
00786   if (Delta != Delta2) {
00787     dbgs() << "DELTA: " << *MI;
00788     if (Delta.Excess.isValid())
00789       dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
00790              << " " << Delta.Excess.getUnitInc() << "\n";
00791     if (Delta.CriticalMax.isValid())
00792       dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
00793              << " " << Delta.CriticalMax.getUnitInc() << "\n";
00794     if (Delta.CurrentMax.isValid())
00795       dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
00796              << " " << Delta.CurrentMax.getUnitInc() << "\n";
00797     if (Delta2.Excess.isValid())
00798       dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
00799              << " " << Delta2.Excess.getUnitInc() << "\n";
00800     if (Delta2.CriticalMax.isValid())
00801       dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
00802              << " " << Delta2.CriticalMax.getUnitInc() << "\n";
00803     if (Delta2.CurrentMax.isValid())
00804       dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
00805              << " " << Delta2.CurrentMax.getUnitInc() << "\n";
00806     llvm_unreachable("RegP Delta Mismatch");
00807   }
00808 #endif
00809 }
00810 
00811 /// This is a prototype of the fast version of querying register pressure that
00812 /// does not directly depend on current liveness. It's still slow because we
00813 /// recompute pressure change on-the-fly. This implementation only exists to
00814 /// prove correctness.
00815 ///
00816 /// @param Delta captures information needed for heuristics.
00817 ///
00818 /// @param CriticalPSets Are the pressure sets that are known to exceed some
00819 /// limit within the region, not necessarily at the current position.
00820 ///
00821 /// @param MaxPressureLimit Is the max pressure within the region, not
00822 /// necessarily at the current position.
00823 void RegPressureTracker::
00824 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
00825                        RegPressureDelta &Delta,
00826                        ArrayRef<PressureChange> CriticalPSets,
00827                        ArrayRef<unsigned> MaxPressureLimit) const {
00828   unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
00829   for (PressureDiff::const_iterator
00830          PDiffI = PDiff.begin(), PDiffE = PDiff.end();
00831        PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
00832 
00833     unsigned PSetID = PDiffI->getPSet();
00834     unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
00835     if (!LiveThruPressure.empty())
00836       Limit += LiveThruPressure[PSetID];
00837 
00838     unsigned POld = CurrSetPressure[PSetID];
00839     unsigned MOld = P.MaxSetPressure[PSetID];
00840     unsigned MNew = MOld;
00841     // Ignore DeadDefs here because they aren't captured by PressureChange.
00842     unsigned PNew = POld + PDiffI->getUnitInc();
00843     assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
00844     if (PNew > MOld)
00845       MNew = PNew;
00846     // Check if current pressure has exceeded the limit.
00847     if (!Delta.Excess.isValid()) {
00848       unsigned ExcessInc = 0;
00849       if (PNew > Limit)
00850         ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
00851       else if (POld > Limit)
00852         ExcessInc = Limit - POld;
00853       if (ExcessInc) {
00854         Delta.Excess = PressureChange(PSetID);
00855         Delta.Excess.setUnitInc(ExcessInc);
00856       }
00857     }
00858     // Check if max pressure has exceeded a critical pressure set max.
00859     if (MNew == MOld)
00860       continue;
00861     if (!Delta.CriticalMax.isValid()) {
00862       while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
00863         ++CritIdx;
00864 
00865       if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
00866         int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
00867         if (CritInc > 0 && CritInc <= INT16_MAX) {
00868           Delta.CriticalMax = PressureChange(PSetID);
00869           Delta.CriticalMax.setUnitInc(CritInc);
00870         }
00871       }
00872     }
00873     // Check if max pressure has exceeded the current max.
00874     if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
00875       Delta.CurrentMax = PressureChange(PSetID);
00876       Delta.CurrentMax.setUnitInc(MNew - MOld);
00877     }
00878   }
00879 }
00880 
00881 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
00882 static bool findUseBetween(unsigned Reg,
00883                            SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
00884                            const MachineRegisterInfo *MRI,
00885                            const LiveIntervals *LIS) {
00886   for (MachineRegisterInfo::use_instr_nodbg_iterator
00887        UI = MRI->use_instr_nodbg_begin(Reg),
00888        UE = MRI->use_instr_nodbg_end(); UI != UE; ++UI) {
00889       const MachineInstr* MI = &*UI;
00890       if (MI->isDebugValue())
00891         continue;
00892       SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot();
00893       if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
00894         return true;
00895   }
00896   return false;
00897 }
00898 
00899 /// Record the downward impact of a single instruction on current register
00900 /// pressure. Unlike the advance/recede pressure tracking interface, this does
00901 /// not discover live in/outs.
00902 ///
00903 /// This is intended for speculative queries. It leaves pressure inconsistent
00904 /// with the current position, so must be restored by the caller.
00905 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
00906   assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
00907 
00908   // Account for register pressure similar to RegPressureTracker::recede().
00909   RegisterOperands RegOpers(TRI, MRI);
00910   collectOperands(MI, RegOpers);
00911 
00912   // Kill liveness at last uses. Assume allocatable physregs are single-use
00913   // rather than checking LiveIntervals.
00914   SlotIndex SlotIdx;
00915   if (RequireIntervals)
00916     SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
00917 
00918   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
00919     unsigned Reg = RegOpers.Uses[i];
00920     if (RequireIntervals) {
00921       // FIXME: allow the caller to pass in the list of vreg uses that remain
00922       // to be bottom-scheduled to avoid searching uses at each query.
00923       SlotIndex CurrIdx = getCurrSlot();
00924       const LiveRange *LR = getLiveRange(Reg);
00925       if (LR) {
00926         LiveQueryResult LRQ = LR->Query(SlotIdx);
00927         if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) {
00928           decreaseRegPressure(Reg);
00929         }
00930       }
00931     }
00932     else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
00933       // Allocatable physregs are always single-use before register rewriting.
00934       decreaseRegPressure(Reg);
00935     }
00936   }
00937 
00938   // Generate liveness for defs.
00939   increaseRegPressure(RegOpers.Defs);
00940 
00941   // Boost pressure for all dead defs together.
00942   increaseRegPressure(RegOpers.DeadDefs);
00943   decreaseRegPressure(RegOpers.DeadDefs);
00944 }
00945 
00946 /// Consider the pressure increase caused by traversing this instruction
00947 /// top-down. Find the register class with the most change in its pressure limit
00948 /// based on the tracker's current pressure, and return the number of excess
00949 /// register units of that pressure set introduced by this instruction.
00950 ///
00951 /// This assumes that the current LiveIn set is sufficient.
00952 void RegPressureTracker::
00953 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
00954                             ArrayRef<PressureChange> CriticalPSets,
00955                             ArrayRef<unsigned> MaxPressureLimit) {
00956   // Snapshot Pressure.
00957   std::vector<unsigned> SavedPressure = CurrSetPressure;
00958   std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
00959 
00960   bumpDownwardPressure(MI);
00961 
00962   computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
00963                              LiveThruPressure);
00964   computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
00965                           MaxPressureLimit, Delta);
00966   assert(Delta.CriticalMax.getUnitInc() >= 0 &&
00967          Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
00968 
00969   // Restore the tracker's state.
00970   P.MaxSetPressure.swap(SavedMaxPressure);
00971   CurrSetPressure.swap(SavedPressure);
00972 }
00973 
00974 /// Get the pressure of each PSet after traversing this instruction bottom-up.
00975 void RegPressureTracker::
00976 getUpwardPressure(const MachineInstr *MI,
00977                   std::vector<unsigned> &PressureResult,
00978                   std::vector<unsigned> &MaxPressureResult) {
00979   // Snapshot pressure.
00980   PressureResult = CurrSetPressure;
00981   MaxPressureResult = P.MaxSetPressure;
00982 
00983   bumpUpwardPressure(MI);
00984 
00985   // Current pressure becomes the result. Restore current pressure.
00986   P.MaxSetPressure.swap(MaxPressureResult);
00987   CurrSetPressure.swap(PressureResult);
00988 }
00989 
00990 /// Get the pressure of each PSet after traversing this instruction top-down.
00991 void RegPressureTracker::
00992 getDownwardPressure(const MachineInstr *MI,
00993                     std::vector<unsigned> &PressureResult,
00994                     std::vector<unsigned> &MaxPressureResult) {
00995   // Snapshot pressure.
00996   PressureResult = CurrSetPressure;
00997   MaxPressureResult = P.MaxSetPressure;
00998 
00999   bumpDownwardPressure(MI);
01000 
01001   // Current pressure becomes the result. Restore current pressure.
01002   P.MaxSetPressure.swap(MaxPressureResult);
01003   CurrSetPressure.swap(PressureResult);
01004 }