RegisterPressure.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. //===-- RegisterPressure.cpp - Dynamic Register Pressure ------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the RegisterPressure class which can be used to track
  11. // MachineInstr level register pressure.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/RegisterPressure.h"
  15. #include "llvm/CodeGen/LiveInterval.h"
  16. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  17. #include "llvm/CodeGen/MachineRegisterInfo.h"
  18. #include "llvm/CodeGen/RegisterClassInfo.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. using namespace llvm;
  22. /// Increase pressure for each pressure set provided by TargetRegisterInfo.
  23. static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure,
  24. PSetIterator PSetI) {
  25. unsigned Weight = PSetI.getWeight();
  26. for (; PSetI.isValid(); ++PSetI)
  27. CurrSetPressure[*PSetI] += Weight;
  28. }
  29. /// Decrease pressure for each pressure set provided by TargetRegisterInfo.
  30. static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure,
  31. PSetIterator PSetI) {
  32. unsigned Weight = PSetI.getWeight();
  33. for (; PSetI.isValid(); ++PSetI) {
  34. assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow");
  35. CurrSetPressure[*PSetI] -= Weight;
  36. }
  37. }
  38. LLVM_DUMP_METHOD
  39. void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
  40. const TargetRegisterInfo *TRI) {
  41. bool Empty = true;
  42. for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) {
  43. if (SetPressure[i] != 0) {
  44. dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << '\n';
  45. Empty = false;
  46. }
  47. }
  48. if (Empty)
  49. dbgs() << "\n";
  50. }
  51. LLVM_DUMP_METHOD
  52. void RegisterPressure::dump(const TargetRegisterInfo *TRI) const {
  53. dbgs() << "Max Pressure: ";
  54. dumpRegSetPressure(MaxSetPressure, TRI);
  55. dbgs() << "Live In: ";
  56. for (unsigned i = 0, e = LiveInRegs.size(); i < e; ++i)
  57. dbgs() << PrintVRegOrUnit(LiveInRegs[i], TRI) << " ";
  58. dbgs() << '\n';
  59. dbgs() << "Live Out: ";
  60. for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i)
  61. dbgs() << PrintVRegOrUnit(LiveOutRegs[i], TRI) << " ";
  62. dbgs() << '\n';
  63. }
  64. LLVM_DUMP_METHOD
  65. void RegPressureTracker::dump() const {
  66. if (!isTopClosed() || !isBottomClosed()) {
  67. dbgs() << "Curr Pressure: ";
  68. dumpRegSetPressure(CurrSetPressure, TRI);
  69. }
  70. P.dump(TRI);
  71. }
  72. void PressureDiff::dump(const TargetRegisterInfo &TRI) const {
  73. for (const PressureChange &Change : *this) {
  74. if (!Change.isValid() || Change.getUnitInc() == 0)
  75. continue;
  76. dbgs() << " " << TRI.getRegPressureSetName(Change.getPSet())
  77. << " " << Change.getUnitInc();
  78. }
  79. dbgs() << '\n';
  80. }
  81. /// Increase the current pressure as impacted by these registers and bump
  82. /// the high water mark if needed.
  83. void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) {
  84. for (unsigned i = 0, e = RegUnits.size(); i != e; ++i) {
  85. PSetIterator PSetI = MRI->getPressureSets(RegUnits[i]);
  86. unsigned Weight = PSetI.getWeight();
  87. for (; PSetI.isValid(); ++PSetI) {
  88. CurrSetPressure[*PSetI] += Weight;
  89. if (CurrSetPressure[*PSetI] > P.MaxSetPressure[*PSetI]) {
  90. P.MaxSetPressure[*PSetI] = CurrSetPressure[*PSetI];
  91. }
  92. }
  93. }
  94. }
  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]));
  99. }
  100. /// Clear the result so it can be used for another round of pressure tracking.
  101. void IntervalPressure::reset() {
  102. TopIdx = BottomIdx = SlotIndex();
  103. MaxSetPressure.clear();
  104. LiveInRegs.clear();
  105. LiveOutRegs.clear();
  106. }
  107. /// Clear the result so it can be used for another round of pressure tracking.
  108. void RegionPressure::reset() {
  109. TopPos = BottomPos = MachineBasicBlock::const_iterator();
  110. MaxSetPressure.clear();
  111. LiveInRegs.clear();
  112. LiveOutRegs.clear();
  113. }
  114. /// If the current top is not less than or equal to the next index, open it.
  115. /// We happen to need the SlotIndex for the next top for pressure update.
  116. void IntervalPressure::openTop(SlotIndex NextTop) {
  117. if (TopIdx <= NextTop)
  118. return;
  119. TopIdx = SlotIndex();
  120. LiveInRegs.clear();
  121. }
  122. /// If the current top is the previous instruction (before receding), open it.
  123. void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
  124. if (TopPos != PrevTop)
  125. return;
  126. TopPos = MachineBasicBlock::const_iterator();
  127. LiveInRegs.clear();
  128. }
  129. /// If the current bottom is not greater than the previous index, open it.
  130. void IntervalPressure::openBottom(SlotIndex PrevBottom) {
  131. if (BottomIdx > PrevBottom)
  132. return;
  133. BottomIdx = SlotIndex();
  134. LiveInRegs.clear();
  135. }
  136. /// If the current bottom is the previous instr (before advancing), open it.
  137. void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
  138. if (BottomPos != PrevBottom)
  139. return;
  140. BottomPos = MachineBasicBlock::const_iterator();
  141. LiveInRegs.clear();
  142. }
  143. const LiveRange *RegPressureTracker::getLiveRange(unsigned Reg) const {
  144. if (TargetRegisterInfo::isVirtualRegister(Reg))
  145. return &LIS->getInterval(Reg);
  146. return LIS->getCachedRegUnit(Reg);
  147. }
  148. void RegPressureTracker::reset() {
  149. MBB = nullptr;
  150. LIS = nullptr;
  151. CurrSetPressure.clear();
  152. LiveThruPressure.clear();
  153. P.MaxSetPressure.clear();
  154. if (RequireIntervals)
  155. static_cast<IntervalPressure&>(P).reset();
  156. else
  157. static_cast<RegionPressure&>(P).reset();
  158. LiveRegs.PhysRegs.clear();
  159. LiveRegs.VirtRegs.clear();
  160. UntiedDefs.clear();
  161. }
  162. /// Setup the RegPressureTracker.
  163. ///
  164. /// TODO: Add support for pressure without LiveIntervals.
  165. void RegPressureTracker::init(const MachineFunction *mf,
  166. const RegisterClassInfo *rci,
  167. const LiveIntervals *lis,
  168. const MachineBasicBlock *mbb,
  169. MachineBasicBlock::const_iterator pos,
  170. bool ShouldTrackUntiedDefs)
  171. {
  172. reset();
  173. MF = mf;
  174. TRI = MF->getSubtarget().getRegisterInfo();
  175. RCI = rci;
  176. MRI = &MF->getRegInfo();
  177. MBB = mbb;
  178. TrackUntiedDefs = ShouldTrackUntiedDefs;
  179. if (RequireIntervals) {
  180. assert(lis && "IntervalPressure requires LiveIntervals");
  181. LIS = lis;
  182. }
  183. CurrPos = pos;
  184. CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
  185. P.MaxSetPressure = CurrSetPressure;
  186. LiveRegs.PhysRegs.setUniverse(TRI->getNumRegs());
  187. LiveRegs.VirtRegs.setUniverse(MRI->getNumVirtRegs());
  188. if (TrackUntiedDefs)
  189. UntiedDefs.setUniverse(MRI->getNumVirtRegs());
  190. }
  191. /// Does this pressure result have a valid top position and live ins.
  192. bool RegPressureTracker::isTopClosed() const {
  193. if (RequireIntervals)
  194. return static_cast<IntervalPressure&>(P).TopIdx.isValid();
  195. return (static_cast<RegionPressure&>(P).TopPos ==
  196. MachineBasicBlock::const_iterator());
  197. }
  198. /// Does this pressure result have a valid bottom position and live outs.
  199. bool RegPressureTracker::isBottomClosed() const {
  200. if (RequireIntervals)
  201. return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
  202. return (static_cast<RegionPressure&>(P).BottomPos ==
  203. MachineBasicBlock::const_iterator());
  204. }
  205. SlotIndex RegPressureTracker::getCurrSlot() const {
  206. MachineBasicBlock::const_iterator IdxPos = CurrPos;
  207. while (IdxPos != MBB->end() && IdxPos->isDebugValue())
  208. ++IdxPos;
  209. if (IdxPos == MBB->end())
  210. return LIS->getMBBEndIdx(MBB);
  211. return LIS->getInstructionIndex(IdxPos).getRegSlot();
  212. }
  213. /// Set the boundary for the top of the region and summarize live ins.
  214. void RegPressureTracker::closeTop() {
  215. if (RequireIntervals)
  216. static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
  217. else
  218. static_cast<RegionPressure&>(P).TopPos = CurrPos;
  219. assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
  220. P.LiveInRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
  221. P.LiveInRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
  222. for (SparseSet<unsigned>::const_iterator I =
  223. LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
  224. P.LiveInRegs.push_back(*I);
  225. std::sort(P.LiveInRegs.begin(), P.LiveInRegs.end());
  226. P.LiveInRegs.erase(std::unique(P.LiveInRegs.begin(), P.LiveInRegs.end()),
  227. P.LiveInRegs.end());
  228. }
  229. /// Set the boundary for the bottom of the region and summarize live outs.
  230. void RegPressureTracker::closeBottom() {
  231. if (RequireIntervals)
  232. static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
  233. else
  234. static_cast<RegionPressure&>(P).BottomPos = CurrPos;
  235. assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
  236. P.LiveOutRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
  237. P.LiveOutRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
  238. for (SparseSet<unsigned>::const_iterator I =
  239. LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
  240. P.LiveOutRegs.push_back(*I);
  241. std::sort(P.LiveOutRegs.begin(), P.LiveOutRegs.end());
  242. P.LiveOutRegs.erase(std::unique(P.LiveOutRegs.begin(), P.LiveOutRegs.end()),
  243. P.LiveOutRegs.end());
  244. }
  245. /// Finalize the region boundaries and record live ins and live outs.
  246. void RegPressureTracker::closeRegion() {
  247. if (!isTopClosed() && !isBottomClosed()) {
  248. assert(LiveRegs.PhysRegs.empty() && LiveRegs.VirtRegs.empty() &&
  249. "no region boundary");
  250. return;
  251. }
  252. if (!isBottomClosed())
  253. closeBottom();
  254. else if (!isTopClosed())
  255. closeTop();
  256. // If both top and bottom are closed, do nothing.
  257. }
  258. /// The register tracker is unaware of global liveness so ignores normal
  259. /// live-thru ranges. However, two-address or coalesced chains can also lead
  260. /// to live ranges with no holes. Count these to inform heuristics that we
  261. /// can never drop below this pressure.
  262. void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
  263. LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
  264. assert(isBottomClosed() && "need bottom-up tracking to intialize.");
  265. for (unsigned i = 0, e = P.LiveOutRegs.size(); i < e; ++i) {
  266. unsigned Reg = P.LiveOutRegs[i];
  267. if (TargetRegisterInfo::isVirtualRegister(Reg)
  268. && !RPTracker.hasUntiedDef(Reg)) {
  269. increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg));
  270. }
  271. }
  272. }
  273. /// \brief Convenient wrapper for checking membership in RegisterOperands.
  274. /// (std::count() doesn't have an early exit).
  275. static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
  276. return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
  277. }
  278. namespace {
  279. /// Collect this instruction's unique uses and defs into SmallVectors for
  280. /// processing defs and uses in order.
  281. ///
  282. /// FIXME: always ignore tied opers
  283. class RegisterOperands {
  284. const TargetRegisterInfo *TRI;
  285. const MachineRegisterInfo *MRI;
  286. bool IgnoreDead;
  287. public:
  288. SmallVector<unsigned, 8> Uses;
  289. SmallVector<unsigned, 8> Defs;
  290. SmallVector<unsigned, 8> DeadDefs;
  291. RegisterOperands(const TargetRegisterInfo *tri,
  292. const MachineRegisterInfo *mri, bool ID = false):
  293. TRI(tri), MRI(mri), IgnoreDead(ID) {}
  294. /// Push this operand's register onto the correct vector.
  295. void collect(const MachineOperand &MO) {
  296. if (!MO.isReg() || !MO.getReg())
  297. return;
  298. if (MO.readsReg())
  299. pushRegUnits(MO.getReg(), Uses);
  300. if (MO.isDef()) {
  301. if (MO.isDead()) {
  302. if (!IgnoreDead)
  303. pushRegUnits(MO.getReg(), DeadDefs);
  304. }
  305. else
  306. pushRegUnits(MO.getReg(), Defs);
  307. }
  308. }
  309. protected:
  310. void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
  311. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  312. if (containsReg(RegUnits, Reg))
  313. return;
  314. RegUnits.push_back(Reg);
  315. }
  316. else if (MRI->isAllocatable(Reg)) {
  317. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
  318. if (containsReg(RegUnits, *Units))
  319. continue;
  320. RegUnits.push_back(*Units);
  321. }
  322. }
  323. }
  324. };
  325. } // namespace
  326. /// Collect physical and virtual register operands.
  327. static void collectOperands(const MachineInstr *MI,
  328. RegisterOperands &RegOpers) {
  329. for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
  330. RegOpers.collect(*OperI);
  331. // Remove redundant physreg dead defs.
  332. SmallVectorImpl<unsigned>::iterator I =
  333. std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
  334. std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
  335. RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
  336. }
  337. /// Initialize an array of N PressureDiffs.
  338. void PressureDiffs::init(unsigned N) {
  339. Size = N;
  340. if (N <= Max) {
  341. memset(PDiffArray, 0, N * sizeof(PressureDiff));
  342. return;
  343. }
  344. Max = Size;
  345. // HLSL Change Begin: Use overridable operator new/delete
  346. delete[] PDiffArray;
  347. PDiffArray = new PressureDiff[N];
  348. std::memset(PDiffArray, 0, N * sizeof(PressureDiff));
  349. // HLSL Change End
  350. }
  351. /// Add a change in pressure to the pressure diff of a given instruction.
  352. void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
  353. const MachineRegisterInfo *MRI) {
  354. PSetIterator PSetI = MRI->getPressureSets(RegUnit);
  355. int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
  356. for (; PSetI.isValid(); ++PSetI) {
  357. // Find an existing entry in the pressure diff for this PSet.
  358. PressureDiff::iterator I = begin(), E = end();
  359. for (; I != E && I->isValid(); ++I) {
  360. if (I->getPSet() >= *PSetI)
  361. break;
  362. }
  363. // If all pressure sets are more constrained, skip the remaining PSets.
  364. if (I == E)
  365. break;
  366. // Insert this PressureChange.
  367. if (!I->isValid() || I->getPSet() != *PSetI) {
  368. PressureChange PTmp = PressureChange(*PSetI);
  369. for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
  370. std::swap(*J,PTmp);
  371. }
  372. // Update the units for this pressure set.
  373. I->setUnitInc(I->getUnitInc() + Weight);
  374. }
  375. }
  376. /// Record the pressure difference induced by the given operand list.
  377. static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
  378. const MachineRegisterInfo *MRI) {
  379. assert(!PDiff.begin()->isValid() && "stale PDiff");
  380. for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
  381. PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
  382. for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
  383. PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
  384. }
  385. /// Force liveness of registers.
  386. void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
  387. for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
  388. if (LiveRegs.insert(Regs[i]))
  389. increaseRegPressure(Regs[i]);
  390. }
  391. }
  392. /// Add Reg to the live in set and increase max pressure.
  393. void RegPressureTracker::discoverLiveIn(unsigned Reg) {
  394. assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
  395. if (containsReg(P.LiveInRegs, Reg))
  396. return;
  397. // At live in discovery, unconditionally increase the high water mark.
  398. P.LiveInRegs.push_back(Reg);
  399. increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
  400. }
  401. /// Add Reg to the live out set and increase max pressure.
  402. void RegPressureTracker::discoverLiveOut(unsigned Reg) {
  403. assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
  404. if (containsReg(P.LiveOutRegs, Reg))
  405. return;
  406. // At live out discovery, unconditionally increase the high water mark.
  407. P.LiveOutRegs.push_back(Reg);
  408. increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
  409. }
  410. /// Recede across the previous instruction. If LiveUses is provided, record any
  411. /// RegUnits that are made live by the current instruction's uses. This includes
  412. /// registers that are both defined and used by the instruction. If a pressure
  413. /// difference pointer is provided record the changes is pressure caused by this
  414. /// instruction independent of liveness.
  415. bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
  416. PressureDiff *PDiff) {
  417. // Check for the top of the analyzable region.
  418. if (CurrPos == MBB->begin()) {
  419. closeRegion();
  420. return false;
  421. }
  422. if (!isBottomClosed())
  423. closeBottom();
  424. // Open the top of the region using block iterators.
  425. if (!RequireIntervals && isTopClosed())
  426. static_cast<RegionPressure&>(P).openTop(CurrPos);
  427. // Find the previous instruction.
  428. do
  429. --CurrPos;
  430. while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
  431. if (CurrPos->isDebugValue()) {
  432. closeRegion();
  433. return false;
  434. }
  435. SlotIndex SlotIdx;
  436. if (RequireIntervals)
  437. SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
  438. // Open the top of the region using slot indexes.
  439. if (RequireIntervals && isTopClosed())
  440. static_cast<IntervalPressure&>(P).openTop(SlotIdx);
  441. RegisterOperands RegOpers(TRI, MRI);
  442. collectOperands(CurrPos, RegOpers);
  443. if (PDiff)
  444. collectPDiff(*PDiff, RegOpers, MRI);
  445. // Boost pressure for all dead defs together.
  446. increaseRegPressure(RegOpers.DeadDefs);
  447. decreaseRegPressure(RegOpers.DeadDefs);
  448. // Kill liveness at live defs.
  449. // TODO: consider earlyclobbers?
  450. for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
  451. unsigned Reg = RegOpers.Defs[i];
  452. bool DeadDef = false;
  453. if (RequireIntervals) {
  454. const LiveRange *LR = getLiveRange(Reg);
  455. if (LR) {
  456. LiveQueryResult LRQ = LR->Query(SlotIdx);
  457. DeadDef = LRQ.isDeadDef();
  458. }
  459. }
  460. if (DeadDef) {
  461. // LiveIntervals knows this is a dead even though it's MachineOperand is
  462. // not flagged as such. Since this register will not be recorded as
  463. // live-out, increase its PDiff value to avoid underflowing pressure.
  464. if (PDiff)
  465. PDiff->addPressureChange(Reg, false, MRI);
  466. } else {
  467. if (LiveRegs.erase(Reg))
  468. decreaseRegPressure(Reg);
  469. else
  470. discoverLiveOut(Reg);
  471. }
  472. }
  473. // Generate liveness for uses.
  474. for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
  475. unsigned Reg = RegOpers.Uses[i];
  476. if (!LiveRegs.contains(Reg)) {
  477. // Adjust liveouts if LiveIntervals are available.
  478. if (RequireIntervals) {
  479. const LiveRange *LR = getLiveRange(Reg);
  480. if (LR) {
  481. LiveQueryResult LRQ = LR->Query(SlotIdx);
  482. if (!LRQ.isKill() && !LRQ.valueDefined())
  483. discoverLiveOut(Reg);
  484. }
  485. }
  486. increaseRegPressure(Reg);
  487. LiveRegs.insert(Reg);
  488. if (LiveUses && !containsReg(*LiveUses, Reg))
  489. LiveUses->push_back(Reg);
  490. }
  491. }
  492. if (TrackUntiedDefs) {
  493. for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
  494. unsigned Reg = RegOpers.Defs[i];
  495. if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
  496. UntiedDefs.insert(Reg);
  497. }
  498. }
  499. return true;
  500. }
  501. /// Advance across the current instruction.
  502. bool RegPressureTracker::advance() {
  503. assert(!TrackUntiedDefs && "unsupported mode");
  504. // Check for the bottom of the analyzable region.
  505. if (CurrPos == MBB->end()) {
  506. closeRegion();
  507. return false;
  508. }
  509. if (!isTopClosed())
  510. closeTop();
  511. SlotIndex SlotIdx;
  512. if (RequireIntervals)
  513. SlotIdx = getCurrSlot();
  514. // Open the bottom of the region using slot indexes.
  515. if (isBottomClosed()) {
  516. if (RequireIntervals)
  517. static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
  518. else
  519. static_cast<RegionPressure&>(P).openBottom(CurrPos);
  520. }
  521. RegisterOperands RegOpers(TRI, MRI);
  522. collectOperands(CurrPos, RegOpers);
  523. for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
  524. unsigned Reg = RegOpers.Uses[i];
  525. // Discover live-ins.
  526. bool isLive = LiveRegs.contains(Reg);
  527. if (!isLive)
  528. discoverLiveIn(Reg);
  529. // Kill liveness at last uses.
  530. bool lastUse = false;
  531. if (RequireIntervals) {
  532. const LiveRange *LR = getLiveRange(Reg);
  533. lastUse = LR && LR->Query(SlotIdx).isKill();
  534. }
  535. else {
  536. // Allocatable physregs are always single-use before register rewriting.
  537. lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
  538. }
  539. if (lastUse && isLive) {
  540. LiveRegs.erase(Reg);
  541. decreaseRegPressure(Reg);
  542. }
  543. else if (!lastUse && !isLive)
  544. increaseRegPressure(Reg);
  545. }
  546. // Generate liveness for defs.
  547. for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
  548. unsigned Reg = RegOpers.Defs[i];
  549. if (LiveRegs.insert(Reg))
  550. increaseRegPressure(Reg);
  551. }
  552. // Boost pressure for all dead defs together.
  553. increaseRegPressure(RegOpers.DeadDefs);
  554. decreaseRegPressure(RegOpers.DeadDefs);
  555. // Find the next instruction.
  556. do
  557. ++CurrPos;
  558. while (CurrPos != MBB->end() && CurrPos->isDebugValue());
  559. return true;
  560. }
  561. /// Find the max change in excess pressure across all sets.
  562. static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
  563. ArrayRef<unsigned> NewPressureVec,
  564. RegPressureDelta &Delta,
  565. const RegisterClassInfo *RCI,
  566. ArrayRef<unsigned> LiveThruPressureVec) {
  567. Delta.Excess = PressureChange();
  568. for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
  569. unsigned POld = OldPressureVec[i];
  570. unsigned PNew = NewPressureVec[i];
  571. int PDiff = (int)PNew - (int)POld;
  572. if (!PDiff) // No change in this set in the common case.
  573. continue;
  574. // Only consider change beyond the limit.
  575. unsigned Limit = RCI->getRegPressureSetLimit(i);
  576. if (!LiveThruPressureVec.empty())
  577. Limit += LiveThruPressureVec[i];
  578. if (Limit > POld) {
  579. if (Limit > PNew)
  580. PDiff = 0; // Under the limit
  581. else
  582. PDiff = PNew - Limit; // Just exceeded limit.
  583. }
  584. else if (Limit > PNew)
  585. PDiff = Limit - POld; // Just obeyed limit.
  586. if (PDiff) {
  587. Delta.Excess = PressureChange(i);
  588. Delta.Excess.setUnitInc(PDiff);
  589. break;
  590. }
  591. }
  592. }
  593. /// Find the max change in max pressure that either surpasses a critical PSet
  594. /// limit or exceeds the current MaxPressureLimit.
  595. ///
  596. /// FIXME: comparing each element of the old and new MaxPressure vectors here is
  597. /// silly. It's done now to demonstrate the concept but will go away with a
  598. /// RegPressureTracker API change to work with pressure differences.
  599. static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
  600. ArrayRef<unsigned> NewMaxPressureVec,
  601. ArrayRef<PressureChange> CriticalPSets,
  602. ArrayRef<unsigned> MaxPressureLimit,
  603. RegPressureDelta &Delta) {
  604. Delta.CriticalMax = PressureChange();
  605. Delta.CurrentMax = PressureChange();
  606. unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
  607. for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
  608. unsigned POld = OldMaxPressureVec[i];
  609. unsigned PNew = NewMaxPressureVec[i];
  610. if (PNew == POld) // No change in this set in the common case.
  611. continue;
  612. if (!Delta.CriticalMax.isValid()) {
  613. while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
  614. ++CritIdx;
  615. if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
  616. int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
  617. if (PDiff > 0) {
  618. Delta.CriticalMax = PressureChange(i);
  619. Delta.CriticalMax.setUnitInc(PDiff);
  620. }
  621. }
  622. }
  623. // Find the first increase above MaxPressureLimit.
  624. // (Ignores negative MDiff).
  625. if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
  626. Delta.CurrentMax = PressureChange(i);
  627. Delta.CurrentMax.setUnitInc(PNew - POld);
  628. if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
  629. break;
  630. }
  631. }
  632. }
  633. /// Record the upward impact of a single instruction on current register
  634. /// pressure. Unlike the advance/recede pressure tracking interface, this does
  635. /// not discover live in/outs.
  636. ///
  637. /// This is intended for speculative queries. It leaves pressure inconsistent
  638. /// with the current position, so must be restored by the caller.
  639. void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
  640. assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
  641. // Account for register pressure similar to RegPressureTracker::recede().
  642. RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
  643. collectOperands(MI, RegOpers);
  644. // Boost max pressure for all dead defs together.
  645. // Since CurrSetPressure and MaxSetPressure
  646. increaseRegPressure(RegOpers.DeadDefs);
  647. decreaseRegPressure(RegOpers.DeadDefs);
  648. // Kill liveness at live defs.
  649. for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
  650. unsigned Reg = RegOpers.Defs[i];
  651. bool DeadDef = false;
  652. if (RequireIntervals) {
  653. const LiveRange *LR = getLiveRange(Reg);
  654. if (LR) {
  655. SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
  656. LiveQueryResult LRQ = LR->Query(SlotIdx);
  657. DeadDef = LRQ.isDeadDef();
  658. }
  659. }
  660. if (!DeadDef) {
  661. if (!containsReg(RegOpers.Uses, Reg))
  662. decreaseRegPressure(Reg);
  663. }
  664. }
  665. // Generate liveness for uses.
  666. for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
  667. unsigned Reg = RegOpers.Uses[i];
  668. if (!LiveRegs.contains(Reg))
  669. increaseRegPressure(Reg);
  670. }
  671. }
  672. /// Consider the pressure increase caused by traversing this instruction
  673. /// bottom-up. Find the pressure set with the most change beyond its pressure
  674. /// limit based on the tracker's current pressure, and return the change in
  675. /// number of register units of that pressure set introduced by this
  676. /// instruction.
  677. ///
  678. /// This assumes that the current LiveOut set is sufficient.
  679. ///
  680. /// This is expensive for an on-the-fly query because it calls
  681. /// bumpUpwardPressure to recompute the pressure sets based on current
  682. /// liveness. This mainly exists to verify correctness, e.g. with
  683. /// -verify-misched. getUpwardPressureDelta is the fast version of this query
  684. /// that uses the per-SUnit cache of the PressureDiff.
  685. void RegPressureTracker::
  686. getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
  687. RegPressureDelta &Delta,
  688. ArrayRef<PressureChange> CriticalPSets,
  689. ArrayRef<unsigned> MaxPressureLimit) {
  690. // Snapshot Pressure.
  691. // FIXME: The snapshot heap space should persist. But I'm planning to
  692. // summarize the pressure effect so we don't need to snapshot at all.
  693. std::vector<unsigned> SavedPressure = CurrSetPressure;
  694. std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
  695. bumpUpwardPressure(MI);
  696. computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
  697. LiveThruPressure);
  698. computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
  699. MaxPressureLimit, Delta);
  700. assert(Delta.CriticalMax.getUnitInc() >= 0 &&
  701. Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
  702. // Restore the tracker's state.
  703. P.MaxSetPressure.swap(SavedMaxPressure);
  704. CurrSetPressure.swap(SavedPressure);
  705. #ifndef NDEBUG
  706. if (!PDiff)
  707. return;
  708. // Check if the alternate algorithm yields the same result.
  709. RegPressureDelta Delta2;
  710. getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
  711. if (Delta != Delta2) {
  712. dbgs() << "PDiff: ";
  713. PDiff->dump(*TRI);
  714. dbgs() << "DELTA: " << *MI;
  715. if (Delta.Excess.isValid())
  716. dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
  717. << " " << Delta.Excess.getUnitInc() << "\n";
  718. if (Delta.CriticalMax.isValid())
  719. dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
  720. << " " << Delta.CriticalMax.getUnitInc() << "\n";
  721. if (Delta.CurrentMax.isValid())
  722. dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
  723. << " " << Delta.CurrentMax.getUnitInc() << "\n";
  724. if (Delta2.Excess.isValid())
  725. dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
  726. << " " << Delta2.Excess.getUnitInc() << "\n";
  727. if (Delta2.CriticalMax.isValid())
  728. dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
  729. << " " << Delta2.CriticalMax.getUnitInc() << "\n";
  730. if (Delta2.CurrentMax.isValid())
  731. dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
  732. << " " << Delta2.CurrentMax.getUnitInc() << "\n";
  733. llvm_unreachable("RegP Delta Mismatch");
  734. }
  735. #endif
  736. }
  737. /// This is the fast version of querying register pressure that does not
  738. /// directly depend on current liveness.
  739. ///
  740. /// @param Delta captures information needed for heuristics.
  741. ///
  742. /// @param CriticalPSets Are the pressure sets that are known to exceed some
  743. /// limit within the region, not necessarily at the current position.
  744. ///
  745. /// @param MaxPressureLimit Is the max pressure within the region, not
  746. /// necessarily at the current position.
  747. void RegPressureTracker::
  748. getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
  749. RegPressureDelta &Delta,
  750. ArrayRef<PressureChange> CriticalPSets,
  751. ArrayRef<unsigned> MaxPressureLimit) const {
  752. unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
  753. for (PressureDiff::const_iterator
  754. PDiffI = PDiff.begin(), PDiffE = PDiff.end();
  755. PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
  756. unsigned PSetID = PDiffI->getPSet();
  757. unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
  758. if (!LiveThruPressure.empty())
  759. Limit += LiveThruPressure[PSetID];
  760. unsigned POld = CurrSetPressure[PSetID];
  761. unsigned MOld = P.MaxSetPressure[PSetID];
  762. unsigned MNew = MOld;
  763. // Ignore DeadDefs here because they aren't captured by PressureChange.
  764. unsigned PNew = POld + PDiffI->getUnitInc();
  765. assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
  766. if (PNew > MOld)
  767. MNew = PNew;
  768. // Check if current pressure has exceeded the limit.
  769. if (!Delta.Excess.isValid()) {
  770. unsigned ExcessInc = 0;
  771. if (PNew > Limit)
  772. ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
  773. else if (POld > Limit)
  774. ExcessInc = Limit - POld;
  775. if (ExcessInc) {
  776. Delta.Excess = PressureChange(PSetID);
  777. Delta.Excess.setUnitInc(ExcessInc);
  778. }
  779. }
  780. // Check if max pressure has exceeded a critical pressure set max.
  781. if (MNew == MOld)
  782. continue;
  783. if (!Delta.CriticalMax.isValid()) {
  784. while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
  785. ++CritIdx;
  786. if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
  787. int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
  788. if (CritInc > 0 && CritInc <= INT16_MAX) {
  789. Delta.CriticalMax = PressureChange(PSetID);
  790. Delta.CriticalMax.setUnitInc(CritInc);
  791. }
  792. }
  793. }
  794. // Check if max pressure has exceeded the current max.
  795. if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
  796. Delta.CurrentMax = PressureChange(PSetID);
  797. Delta.CurrentMax.setUnitInc(MNew - MOld);
  798. }
  799. }
  800. }
  801. /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
  802. static bool findUseBetween(unsigned Reg,
  803. SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
  804. const MachineRegisterInfo *MRI,
  805. const LiveIntervals *LIS) {
  806. for (MachineRegisterInfo::use_instr_nodbg_iterator
  807. UI = MRI->use_instr_nodbg_begin(Reg),
  808. UE = MRI->use_instr_nodbg_end(); UI != UE; ++UI) {
  809. const MachineInstr* MI = &*UI;
  810. if (MI->isDebugValue())
  811. continue;
  812. SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot();
  813. if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
  814. return true;
  815. }
  816. return false;
  817. }
  818. /// Record the downward impact of a single instruction on current register
  819. /// pressure. Unlike the advance/recede pressure tracking interface, this does
  820. /// not discover live in/outs.
  821. ///
  822. /// This is intended for speculative queries. It leaves pressure inconsistent
  823. /// with the current position, so must be restored by the caller.
  824. void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
  825. assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
  826. // Account for register pressure similar to RegPressureTracker::recede().
  827. RegisterOperands RegOpers(TRI, MRI);
  828. collectOperands(MI, RegOpers);
  829. // Kill liveness at last uses. Assume allocatable physregs are single-use
  830. // rather than checking LiveIntervals.
  831. SlotIndex SlotIdx;
  832. if (RequireIntervals)
  833. SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
  834. for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
  835. unsigned Reg = RegOpers.Uses[i];
  836. if (RequireIntervals) {
  837. // FIXME: allow the caller to pass in the list of vreg uses that remain
  838. // to be bottom-scheduled to avoid searching uses at each query.
  839. SlotIndex CurrIdx = getCurrSlot();
  840. const LiveRange *LR = getLiveRange(Reg);
  841. if (LR) {
  842. LiveQueryResult LRQ = LR->Query(SlotIdx);
  843. if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) {
  844. decreaseRegPressure(Reg);
  845. }
  846. }
  847. }
  848. else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
  849. // Allocatable physregs are always single-use before register rewriting.
  850. decreaseRegPressure(Reg);
  851. }
  852. }
  853. // Generate liveness for defs.
  854. increaseRegPressure(RegOpers.Defs);
  855. // Boost pressure for all dead defs together.
  856. increaseRegPressure(RegOpers.DeadDefs);
  857. decreaseRegPressure(RegOpers.DeadDefs);
  858. }
  859. /// Consider the pressure increase caused by traversing this instruction
  860. /// top-down. Find the register class with the most change in its pressure limit
  861. /// based on the tracker's current pressure, and return the number of excess
  862. /// register units of that pressure set introduced by this instruction.
  863. ///
  864. /// This assumes that the current LiveIn set is sufficient.
  865. ///
  866. /// This is expensive for an on-the-fly query because it calls
  867. /// bumpDownwardPressure to recompute the pressure sets based on current
  868. /// liveness. We don't yet have a fast version of downward pressure tracking
  869. /// analagous to getUpwardPressureDelta.
  870. void RegPressureTracker::
  871. getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
  872. ArrayRef<PressureChange> CriticalPSets,
  873. ArrayRef<unsigned> MaxPressureLimit) {
  874. // Snapshot Pressure.
  875. std::vector<unsigned> SavedPressure = CurrSetPressure;
  876. std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
  877. bumpDownwardPressure(MI);
  878. computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
  879. LiveThruPressure);
  880. computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
  881. MaxPressureLimit, Delta);
  882. assert(Delta.CriticalMax.getUnitInc() >= 0 &&
  883. Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
  884. // Restore the tracker's state.
  885. P.MaxSetPressure.swap(SavedMaxPressure);
  886. CurrSetPressure.swap(SavedPressure);
  887. }
  888. /// Get the pressure of each PSet after traversing this instruction bottom-up.
  889. void RegPressureTracker::
  890. getUpwardPressure(const MachineInstr *MI,
  891. std::vector<unsigned> &PressureResult,
  892. std::vector<unsigned> &MaxPressureResult) {
  893. // Snapshot pressure.
  894. PressureResult = CurrSetPressure;
  895. MaxPressureResult = P.MaxSetPressure;
  896. bumpUpwardPressure(MI);
  897. // Current pressure becomes the result. Restore current pressure.
  898. P.MaxSetPressure.swap(MaxPressureResult);
  899. CurrSetPressure.swap(PressureResult);
  900. }
  901. /// Get the pressure of each PSet after traversing this instruction top-down.
  902. void RegPressureTracker::
  903. getDownwardPressure(const MachineInstr *MI,
  904. std::vector<unsigned> &PressureResult,
  905. std::vector<unsigned> &MaxPressureResult) {
  906. // Snapshot pressure.
  907. PressureResult = CurrSetPressure;
  908. MaxPressureResult = P.MaxSetPressure;
  909. bumpDownwardPressure(MI);
  910. // Current pressure becomes the result. Restore current pressure.
  911. P.MaxSetPressure.swap(MaxPressureResult);
  912. CurrSetPressure.swap(PressureResult);
  913. }