RegisterPressure.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. free(PDiffArray);
  346. PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
  347. if (PDiffArray == nullptr) throw std::bad_alloc(); // HLSL Change
  348. }
  349. /// Add a change in pressure to the pressure diff of a given instruction.
  350. void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
  351. const MachineRegisterInfo *MRI) {
  352. PSetIterator PSetI = MRI->getPressureSets(RegUnit);
  353. int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
  354. for (; PSetI.isValid(); ++PSetI) {
  355. // Find an existing entry in the pressure diff for this PSet.
  356. PressureDiff::iterator I = begin(), E = end();
  357. for (; I != E && I->isValid(); ++I) {
  358. if (I->getPSet() >= *PSetI)
  359. break;
  360. }
  361. // If all pressure sets are more constrained, skip the remaining PSets.
  362. if (I == E)
  363. break;
  364. // Insert this PressureChange.
  365. if (!I->isValid() || I->getPSet() != *PSetI) {
  366. PressureChange PTmp = PressureChange(*PSetI);
  367. for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
  368. std::swap(*J,PTmp);
  369. }
  370. // Update the units for this pressure set.
  371. I->setUnitInc(I->getUnitInc() + Weight);
  372. }
  373. }
  374. /// Record the pressure difference induced by the given operand list.
  375. static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
  376. const MachineRegisterInfo *MRI) {
  377. assert(!PDiff.begin()->isValid() && "stale PDiff");
  378. for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
  379. PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
  380. for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
  381. PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
  382. }
  383. /// Force liveness of registers.
  384. void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
  385. for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
  386. if (LiveRegs.insert(Regs[i]))
  387. increaseRegPressure(Regs[i]);
  388. }
  389. }
  390. /// Add Reg to the live in set and increase max pressure.
  391. void RegPressureTracker::discoverLiveIn(unsigned Reg) {
  392. assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
  393. if (containsReg(P.LiveInRegs, Reg))
  394. return;
  395. // At live in discovery, unconditionally increase the high water mark.
  396. P.LiveInRegs.push_back(Reg);
  397. increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
  398. }
  399. /// Add Reg to the live out set and increase max pressure.
  400. void RegPressureTracker::discoverLiveOut(unsigned Reg) {
  401. assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
  402. if (containsReg(P.LiveOutRegs, Reg))
  403. return;
  404. // At live out discovery, unconditionally increase the high water mark.
  405. P.LiveOutRegs.push_back(Reg);
  406. increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
  407. }
  408. /// Recede across the previous instruction. If LiveUses is provided, record any
  409. /// RegUnits that are made live by the current instruction's uses. This includes
  410. /// registers that are both defined and used by the instruction. If a pressure
  411. /// difference pointer is provided record the changes is pressure caused by this
  412. /// instruction independent of liveness.
  413. bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
  414. PressureDiff *PDiff) {
  415. // Check for the top of the analyzable region.
  416. if (CurrPos == MBB->begin()) {
  417. closeRegion();
  418. return false;
  419. }
  420. if (!isBottomClosed())
  421. closeBottom();
  422. // Open the top of the region using block iterators.
  423. if (!RequireIntervals && isTopClosed())
  424. static_cast<RegionPressure&>(P).openTop(CurrPos);
  425. // Find the previous instruction.
  426. do
  427. --CurrPos;
  428. while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
  429. if (CurrPos->isDebugValue()) {
  430. closeRegion();
  431. return false;
  432. }
  433. SlotIndex SlotIdx;
  434. if (RequireIntervals)
  435. SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
  436. // Open the top of the region using slot indexes.
  437. if (RequireIntervals && isTopClosed())
  438. static_cast<IntervalPressure&>(P).openTop(SlotIdx);
  439. RegisterOperands RegOpers(TRI, MRI);
  440. collectOperands(CurrPos, RegOpers);
  441. if (PDiff)
  442. collectPDiff(*PDiff, RegOpers, MRI);
  443. // Boost pressure for all dead defs together.
  444. increaseRegPressure(RegOpers.DeadDefs);
  445. decreaseRegPressure(RegOpers.DeadDefs);
  446. // Kill liveness at live defs.
  447. // TODO: consider earlyclobbers?
  448. for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
  449. unsigned Reg = RegOpers.Defs[i];
  450. bool DeadDef = false;
  451. if (RequireIntervals) {
  452. const LiveRange *LR = getLiveRange(Reg);
  453. if (LR) {
  454. LiveQueryResult LRQ = LR->Query(SlotIdx);
  455. DeadDef = LRQ.isDeadDef();
  456. }
  457. }
  458. if (DeadDef) {
  459. // LiveIntervals knows this is a dead even though it's MachineOperand is
  460. // not flagged as such. Since this register will not be recorded as
  461. // live-out, increase its PDiff value to avoid underflowing pressure.
  462. if (PDiff)
  463. PDiff->addPressureChange(Reg, false, MRI);
  464. } else {
  465. if (LiveRegs.erase(Reg))
  466. decreaseRegPressure(Reg);
  467. else
  468. discoverLiveOut(Reg);
  469. }
  470. }
  471. // Generate liveness for uses.
  472. for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
  473. unsigned Reg = RegOpers.Uses[i];
  474. if (!LiveRegs.contains(Reg)) {
  475. // Adjust liveouts if LiveIntervals are available.
  476. if (RequireIntervals) {
  477. const LiveRange *LR = getLiveRange(Reg);
  478. if (LR) {
  479. LiveQueryResult LRQ = LR->Query(SlotIdx);
  480. if (!LRQ.isKill() && !LRQ.valueDefined())
  481. discoverLiveOut(Reg);
  482. }
  483. }
  484. increaseRegPressure(Reg);
  485. LiveRegs.insert(Reg);
  486. if (LiveUses && !containsReg(*LiveUses, Reg))
  487. LiveUses->push_back(Reg);
  488. }
  489. }
  490. if (TrackUntiedDefs) {
  491. for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
  492. unsigned Reg = RegOpers.Defs[i];
  493. if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
  494. UntiedDefs.insert(Reg);
  495. }
  496. }
  497. return true;
  498. }
  499. /// Advance across the current instruction.
  500. bool RegPressureTracker::advance() {
  501. assert(!TrackUntiedDefs && "unsupported mode");
  502. // Check for the bottom of the analyzable region.
  503. if (CurrPos == MBB->end()) {
  504. closeRegion();
  505. return false;
  506. }
  507. if (!isTopClosed())
  508. closeTop();
  509. SlotIndex SlotIdx;
  510. if (RequireIntervals)
  511. SlotIdx = getCurrSlot();
  512. // Open the bottom of the region using slot indexes.
  513. if (isBottomClosed()) {
  514. if (RequireIntervals)
  515. static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
  516. else
  517. static_cast<RegionPressure&>(P).openBottom(CurrPos);
  518. }
  519. RegisterOperands RegOpers(TRI, MRI);
  520. collectOperands(CurrPos, RegOpers);
  521. for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
  522. unsigned Reg = RegOpers.Uses[i];
  523. // Discover live-ins.
  524. bool isLive = LiveRegs.contains(Reg);
  525. if (!isLive)
  526. discoverLiveIn(Reg);
  527. // Kill liveness at last uses.
  528. bool lastUse = false;
  529. if (RequireIntervals) {
  530. const LiveRange *LR = getLiveRange(Reg);
  531. lastUse = LR && LR->Query(SlotIdx).isKill();
  532. }
  533. else {
  534. // Allocatable physregs are always single-use before register rewriting.
  535. lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
  536. }
  537. if (lastUse && isLive) {
  538. LiveRegs.erase(Reg);
  539. decreaseRegPressure(Reg);
  540. }
  541. else if (!lastUse && !isLive)
  542. increaseRegPressure(Reg);
  543. }
  544. // Generate liveness for defs.
  545. for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
  546. unsigned Reg = RegOpers.Defs[i];
  547. if (LiveRegs.insert(Reg))
  548. increaseRegPressure(Reg);
  549. }
  550. // Boost pressure for all dead defs together.
  551. increaseRegPressure(RegOpers.DeadDefs);
  552. decreaseRegPressure(RegOpers.DeadDefs);
  553. // Find the next instruction.
  554. do
  555. ++CurrPos;
  556. while (CurrPos != MBB->end() && CurrPos->isDebugValue());
  557. return true;
  558. }
  559. /// Find the max change in excess pressure across all sets.
  560. static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
  561. ArrayRef<unsigned> NewPressureVec,
  562. RegPressureDelta &Delta,
  563. const RegisterClassInfo *RCI,
  564. ArrayRef<unsigned> LiveThruPressureVec) {
  565. Delta.Excess = PressureChange();
  566. for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
  567. unsigned POld = OldPressureVec[i];
  568. unsigned PNew = NewPressureVec[i];
  569. int PDiff = (int)PNew - (int)POld;
  570. if (!PDiff) // No change in this set in the common case.
  571. continue;
  572. // Only consider change beyond the limit.
  573. unsigned Limit = RCI->getRegPressureSetLimit(i);
  574. if (!LiveThruPressureVec.empty())
  575. Limit += LiveThruPressureVec[i];
  576. if (Limit > POld) {
  577. if (Limit > PNew)
  578. PDiff = 0; // Under the limit
  579. else
  580. PDiff = PNew - Limit; // Just exceeded limit.
  581. }
  582. else if (Limit > PNew)
  583. PDiff = Limit - POld; // Just obeyed limit.
  584. if (PDiff) {
  585. Delta.Excess = PressureChange(i);
  586. Delta.Excess.setUnitInc(PDiff);
  587. break;
  588. }
  589. }
  590. }
  591. /// Find the max change in max pressure that either surpasses a critical PSet
  592. /// limit or exceeds the current MaxPressureLimit.
  593. ///
  594. /// FIXME: comparing each element of the old and new MaxPressure vectors here is
  595. /// silly. It's done now to demonstrate the concept but will go away with a
  596. /// RegPressureTracker API change to work with pressure differences.
  597. static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
  598. ArrayRef<unsigned> NewMaxPressureVec,
  599. ArrayRef<PressureChange> CriticalPSets,
  600. ArrayRef<unsigned> MaxPressureLimit,
  601. RegPressureDelta &Delta) {
  602. Delta.CriticalMax = PressureChange();
  603. Delta.CurrentMax = PressureChange();
  604. unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
  605. for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
  606. unsigned POld = OldMaxPressureVec[i];
  607. unsigned PNew = NewMaxPressureVec[i];
  608. if (PNew == POld) // No change in this set in the common case.
  609. continue;
  610. if (!Delta.CriticalMax.isValid()) {
  611. while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
  612. ++CritIdx;
  613. if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
  614. int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
  615. if (PDiff > 0) {
  616. Delta.CriticalMax = PressureChange(i);
  617. Delta.CriticalMax.setUnitInc(PDiff);
  618. }
  619. }
  620. }
  621. // Find the first increase above MaxPressureLimit.
  622. // (Ignores negative MDiff).
  623. if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
  624. Delta.CurrentMax = PressureChange(i);
  625. Delta.CurrentMax.setUnitInc(PNew - POld);
  626. if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
  627. break;
  628. }
  629. }
  630. }
  631. /// Record the upward impact of a single instruction on current register
  632. /// pressure. Unlike the advance/recede pressure tracking interface, this does
  633. /// not discover live in/outs.
  634. ///
  635. /// This is intended for speculative queries. It leaves pressure inconsistent
  636. /// with the current position, so must be restored by the caller.
  637. void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
  638. assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
  639. // Account for register pressure similar to RegPressureTracker::recede().
  640. RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
  641. collectOperands(MI, RegOpers);
  642. // Boost max pressure for all dead defs together.
  643. // Since CurrSetPressure and MaxSetPressure
  644. increaseRegPressure(RegOpers.DeadDefs);
  645. decreaseRegPressure(RegOpers.DeadDefs);
  646. // Kill liveness at live defs.
  647. for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
  648. unsigned Reg = RegOpers.Defs[i];
  649. bool DeadDef = false;
  650. if (RequireIntervals) {
  651. const LiveRange *LR = getLiveRange(Reg);
  652. if (LR) {
  653. SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
  654. LiveQueryResult LRQ = LR->Query(SlotIdx);
  655. DeadDef = LRQ.isDeadDef();
  656. }
  657. }
  658. if (!DeadDef) {
  659. if (!containsReg(RegOpers.Uses, Reg))
  660. decreaseRegPressure(Reg);
  661. }
  662. }
  663. // Generate liveness for uses.
  664. for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
  665. unsigned Reg = RegOpers.Uses[i];
  666. if (!LiveRegs.contains(Reg))
  667. increaseRegPressure(Reg);
  668. }
  669. }
  670. /// Consider the pressure increase caused by traversing this instruction
  671. /// bottom-up. Find the pressure set with the most change beyond its pressure
  672. /// limit based on the tracker's current pressure, and return the change in
  673. /// number of register units of that pressure set introduced by this
  674. /// instruction.
  675. ///
  676. /// This assumes that the current LiveOut set is sufficient.
  677. ///
  678. /// This is expensive for an on-the-fly query because it calls
  679. /// bumpUpwardPressure to recompute the pressure sets based on current
  680. /// liveness. This mainly exists to verify correctness, e.g. with
  681. /// -verify-misched. getUpwardPressureDelta is the fast version of this query
  682. /// that uses the per-SUnit cache of the PressureDiff.
  683. void RegPressureTracker::
  684. getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
  685. RegPressureDelta &Delta,
  686. ArrayRef<PressureChange> CriticalPSets,
  687. ArrayRef<unsigned> MaxPressureLimit) {
  688. // Snapshot Pressure.
  689. // FIXME: The snapshot heap space should persist. But I'm planning to
  690. // summarize the pressure effect so we don't need to snapshot at all.
  691. std::vector<unsigned> SavedPressure = CurrSetPressure;
  692. std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
  693. bumpUpwardPressure(MI);
  694. computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
  695. LiveThruPressure);
  696. computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
  697. MaxPressureLimit, Delta);
  698. assert(Delta.CriticalMax.getUnitInc() >= 0 &&
  699. Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
  700. // Restore the tracker's state.
  701. P.MaxSetPressure.swap(SavedMaxPressure);
  702. CurrSetPressure.swap(SavedPressure);
  703. #ifndef NDEBUG
  704. if (!PDiff)
  705. return;
  706. // Check if the alternate algorithm yields the same result.
  707. RegPressureDelta Delta2;
  708. getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
  709. if (Delta != Delta2) {
  710. dbgs() << "PDiff: ";
  711. PDiff->dump(*TRI);
  712. dbgs() << "DELTA: " << *MI;
  713. if (Delta.Excess.isValid())
  714. dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
  715. << " " << Delta.Excess.getUnitInc() << "\n";
  716. if (Delta.CriticalMax.isValid())
  717. dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
  718. << " " << Delta.CriticalMax.getUnitInc() << "\n";
  719. if (Delta.CurrentMax.isValid())
  720. dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
  721. << " " << Delta.CurrentMax.getUnitInc() << "\n";
  722. if (Delta2.Excess.isValid())
  723. dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
  724. << " " << Delta2.Excess.getUnitInc() << "\n";
  725. if (Delta2.CriticalMax.isValid())
  726. dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
  727. << " " << Delta2.CriticalMax.getUnitInc() << "\n";
  728. if (Delta2.CurrentMax.isValid())
  729. dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
  730. << " " << Delta2.CurrentMax.getUnitInc() << "\n";
  731. llvm_unreachable("RegP Delta Mismatch");
  732. }
  733. #endif
  734. }
  735. /// This is the fast version of querying register pressure that does not
  736. /// directly depend on current liveness.
  737. ///
  738. /// @param Delta captures information needed for heuristics.
  739. ///
  740. /// @param CriticalPSets Are the pressure sets that are known to exceed some
  741. /// limit within the region, not necessarily at the current position.
  742. ///
  743. /// @param MaxPressureLimit Is the max pressure within the region, not
  744. /// necessarily at the current position.
  745. void RegPressureTracker::
  746. getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
  747. RegPressureDelta &Delta,
  748. ArrayRef<PressureChange> CriticalPSets,
  749. ArrayRef<unsigned> MaxPressureLimit) const {
  750. unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
  751. for (PressureDiff::const_iterator
  752. PDiffI = PDiff.begin(), PDiffE = PDiff.end();
  753. PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
  754. unsigned PSetID = PDiffI->getPSet();
  755. unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
  756. if (!LiveThruPressure.empty())
  757. Limit += LiveThruPressure[PSetID];
  758. unsigned POld = CurrSetPressure[PSetID];
  759. unsigned MOld = P.MaxSetPressure[PSetID];
  760. unsigned MNew = MOld;
  761. // Ignore DeadDefs here because they aren't captured by PressureChange.
  762. unsigned PNew = POld + PDiffI->getUnitInc();
  763. assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
  764. if (PNew > MOld)
  765. MNew = PNew;
  766. // Check if current pressure has exceeded the limit.
  767. if (!Delta.Excess.isValid()) {
  768. unsigned ExcessInc = 0;
  769. if (PNew > Limit)
  770. ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
  771. else if (POld > Limit)
  772. ExcessInc = Limit - POld;
  773. if (ExcessInc) {
  774. Delta.Excess = PressureChange(PSetID);
  775. Delta.Excess.setUnitInc(ExcessInc);
  776. }
  777. }
  778. // Check if max pressure has exceeded a critical pressure set max.
  779. if (MNew == MOld)
  780. continue;
  781. if (!Delta.CriticalMax.isValid()) {
  782. while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
  783. ++CritIdx;
  784. if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
  785. int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
  786. if (CritInc > 0 && CritInc <= INT16_MAX) {
  787. Delta.CriticalMax = PressureChange(PSetID);
  788. Delta.CriticalMax.setUnitInc(CritInc);
  789. }
  790. }
  791. }
  792. // Check if max pressure has exceeded the current max.
  793. if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
  794. Delta.CurrentMax = PressureChange(PSetID);
  795. Delta.CurrentMax.setUnitInc(MNew - MOld);
  796. }
  797. }
  798. }
  799. /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
  800. static bool findUseBetween(unsigned Reg,
  801. SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
  802. const MachineRegisterInfo *MRI,
  803. const LiveIntervals *LIS) {
  804. for (MachineRegisterInfo::use_instr_nodbg_iterator
  805. UI = MRI->use_instr_nodbg_begin(Reg),
  806. UE = MRI->use_instr_nodbg_end(); UI != UE; ++UI) {
  807. const MachineInstr* MI = &*UI;
  808. if (MI->isDebugValue())
  809. continue;
  810. SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot();
  811. if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
  812. return true;
  813. }
  814. return false;
  815. }
  816. /// Record the downward impact of a single instruction on current register
  817. /// pressure. Unlike the advance/recede pressure tracking interface, this does
  818. /// not discover live in/outs.
  819. ///
  820. /// This is intended for speculative queries. It leaves pressure inconsistent
  821. /// with the current position, so must be restored by the caller.
  822. void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
  823. assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
  824. // Account for register pressure similar to RegPressureTracker::recede().
  825. RegisterOperands RegOpers(TRI, MRI);
  826. collectOperands(MI, RegOpers);
  827. // Kill liveness at last uses. Assume allocatable physregs are single-use
  828. // rather than checking LiveIntervals.
  829. SlotIndex SlotIdx;
  830. if (RequireIntervals)
  831. SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
  832. for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
  833. unsigned Reg = RegOpers.Uses[i];
  834. if (RequireIntervals) {
  835. // FIXME: allow the caller to pass in the list of vreg uses that remain
  836. // to be bottom-scheduled to avoid searching uses at each query.
  837. SlotIndex CurrIdx = getCurrSlot();
  838. const LiveRange *LR = getLiveRange(Reg);
  839. if (LR) {
  840. LiveQueryResult LRQ = LR->Query(SlotIdx);
  841. if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) {
  842. decreaseRegPressure(Reg);
  843. }
  844. }
  845. }
  846. else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
  847. // Allocatable physregs are always single-use before register rewriting.
  848. decreaseRegPressure(Reg);
  849. }
  850. }
  851. // Generate liveness for defs.
  852. increaseRegPressure(RegOpers.Defs);
  853. // Boost pressure for all dead defs together.
  854. increaseRegPressure(RegOpers.DeadDefs);
  855. decreaseRegPressure(RegOpers.DeadDefs);
  856. }
  857. /// Consider the pressure increase caused by traversing this instruction
  858. /// top-down. Find the register class with the most change in its pressure limit
  859. /// based on the tracker's current pressure, and return the number of excess
  860. /// register units of that pressure set introduced by this instruction.
  861. ///
  862. /// This assumes that the current LiveIn set is sufficient.
  863. ///
  864. /// This is expensive for an on-the-fly query because it calls
  865. /// bumpDownwardPressure to recompute the pressure sets based on current
  866. /// liveness. We don't yet have a fast version of downward pressure tracking
  867. /// analagous to getUpwardPressureDelta.
  868. void RegPressureTracker::
  869. getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
  870. ArrayRef<PressureChange> CriticalPSets,
  871. ArrayRef<unsigned> MaxPressureLimit) {
  872. // Snapshot Pressure.
  873. std::vector<unsigned> SavedPressure = CurrSetPressure;
  874. std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
  875. bumpDownwardPressure(MI);
  876. computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
  877. LiveThruPressure);
  878. computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
  879. MaxPressureLimit, Delta);
  880. assert(Delta.CriticalMax.getUnitInc() >= 0 &&
  881. Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
  882. // Restore the tracker's state.
  883. P.MaxSetPressure.swap(SavedMaxPressure);
  884. CurrSetPressure.swap(SavedPressure);
  885. }
  886. /// Get the pressure of each PSet after traversing this instruction bottom-up.
  887. void RegPressureTracker::
  888. getUpwardPressure(const MachineInstr *MI,
  889. std::vector<unsigned> &PressureResult,
  890. std::vector<unsigned> &MaxPressureResult) {
  891. // Snapshot pressure.
  892. PressureResult = CurrSetPressure;
  893. MaxPressureResult = P.MaxSetPressure;
  894. bumpUpwardPressure(MI);
  895. // Current pressure becomes the result. Restore current pressure.
  896. P.MaxSetPressure.swap(MaxPressureResult);
  897. CurrSetPressure.swap(PressureResult);
  898. }
  899. /// Get the pressure of each PSet after traversing this instruction top-down.
  900. void RegPressureTracker::
  901. getDownwardPressure(const MachineInstr *MI,
  902. std::vector<unsigned> &PressureResult,
  903. std::vector<unsigned> &MaxPressureResult) {
  904. // Snapshot pressure.
  905. PressureResult = CurrSetPressure;
  906. MaxPressureResult = P.MaxSetPressure;
  907. bumpDownwardPressure(MI);
  908. // Current pressure becomes the result. Restore current pressure.
  909. P.MaxSetPressure.swap(MaxPressureResult);
  910. CurrSetPressure.swap(PressureResult);
  911. }