RegisterScavenging.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. //===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
  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 machine register scavenger. It can provide
  11. // information, such as unused registers, at any point in a machine basic block.
  12. // It also provides a mechanism to make registers available by evicting them to
  13. // spill slots.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/CodeGen/RegisterScavenging.h"
  17. #include "llvm/CodeGen/MachineBasicBlock.h"
  18. #include "llvm/CodeGen/MachineFrameInfo.h"
  19. #include "llvm/CodeGen/MachineFunction.h"
  20. #include "llvm/CodeGen/MachineInstr.h"
  21. #include "llvm/CodeGen/MachineRegisterInfo.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "llvm/Target/TargetInstrInfo.h"
  26. #include "llvm/Target/TargetRegisterInfo.h"
  27. #include "llvm/Target/TargetSubtargetInfo.h"
  28. using namespace llvm;
  29. #define DEBUG_TYPE "reg-scavenging"
  30. /// setUsed - Set the register units of this register as used.
  31. void RegScavenger::setRegUsed(unsigned Reg) {
  32. for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
  33. RegUnitsAvailable.reset(*RUI);
  34. }
  35. void RegScavenger::initRegState() {
  36. for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
  37. IE = Scavenged.end(); I != IE; ++I) {
  38. I->Reg = 0;
  39. I->Restore = nullptr;
  40. }
  41. // All register units start out unused.
  42. RegUnitsAvailable.set();
  43. if (!MBB)
  44. return;
  45. // Live-in registers are in use.
  46. for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
  47. E = MBB->livein_end(); I != E; ++I)
  48. setRegUsed(*I);
  49. // Pristine CSRs are also unavailable.
  50. const MachineFunction &MF = *MBB->getParent();
  51. BitVector PR = MF.getFrameInfo()->getPristineRegs(MF);
  52. for (int I = PR.find_first(); I>0; I = PR.find_next(I))
  53. setRegUsed(I);
  54. }
  55. void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
  56. MachineFunction &MF = *mbb->getParent();
  57. TII = MF.getSubtarget().getInstrInfo();
  58. TRI = MF.getSubtarget().getRegisterInfo();
  59. MRI = &MF.getRegInfo();
  60. assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) &&
  61. "Target changed?");
  62. // It is not possible to use the register scavenger after late optimization
  63. // passes that don't preserve accurate liveness information.
  64. assert(MRI->tracksLiveness() &&
  65. "Cannot use register scavenger with inaccurate liveness");
  66. // Self-initialize.
  67. if (!MBB) {
  68. NumRegUnits = TRI->getNumRegUnits();
  69. RegUnitsAvailable.resize(NumRegUnits);
  70. KillRegUnits.resize(NumRegUnits);
  71. DefRegUnits.resize(NumRegUnits);
  72. TmpRegUnits.resize(NumRegUnits);
  73. }
  74. MBB = mbb;
  75. initRegState();
  76. Tracking = false;
  77. }
  78. void RegScavenger::addRegUnits(BitVector &BV, unsigned Reg) {
  79. for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
  80. BV.set(*RUI);
  81. }
  82. void RegScavenger::determineKillsAndDefs() {
  83. assert(Tracking && "Must be tracking to determine kills and defs");
  84. MachineInstr *MI = MBBI;
  85. assert(!MI->isDebugValue() && "Debug values have no kills or defs");
  86. // Find out which registers are early clobbered, killed, defined, and marked
  87. // def-dead in this instruction.
  88. KillRegUnits.reset();
  89. DefRegUnits.reset();
  90. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  91. const MachineOperand &MO = MI->getOperand(i);
  92. if (MO.isRegMask()) {
  93. TmpRegUnits.clear();
  94. for (unsigned RU = 0, RUEnd = TRI->getNumRegUnits(); RU != RUEnd; ++RU) {
  95. for (MCRegUnitRootIterator RURI(RU, TRI); RURI.isValid(); ++RURI) {
  96. if (MO.clobbersPhysReg(*RURI)) {
  97. TmpRegUnits.set(RU);
  98. break;
  99. }
  100. }
  101. }
  102. // Apply the mask.
  103. KillRegUnits |= TmpRegUnits;
  104. }
  105. if (!MO.isReg())
  106. continue;
  107. unsigned Reg = MO.getReg();
  108. if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
  109. continue;
  110. if (MO.isUse()) {
  111. // Ignore undef uses.
  112. if (MO.isUndef())
  113. continue;
  114. if (MO.isKill())
  115. addRegUnits(KillRegUnits, Reg);
  116. } else {
  117. assert(MO.isDef());
  118. if (MO.isDead())
  119. addRegUnits(KillRegUnits, Reg);
  120. else
  121. addRegUnits(DefRegUnits, Reg);
  122. }
  123. }
  124. }
  125. void RegScavenger::unprocess() {
  126. assert(Tracking && "Cannot unprocess because we're not tracking");
  127. MachineInstr *MI = MBBI;
  128. if (!MI->isDebugValue()) {
  129. determineKillsAndDefs();
  130. // Commit the changes.
  131. setUsed(KillRegUnits);
  132. setUnused(DefRegUnits);
  133. }
  134. if (MBBI == MBB->begin()) {
  135. MBBI = MachineBasicBlock::iterator(nullptr);
  136. Tracking = false;
  137. } else
  138. --MBBI;
  139. }
  140. void RegScavenger::forward() {
  141. // Move ptr forward.
  142. if (!Tracking) {
  143. MBBI = MBB->begin();
  144. Tracking = true;
  145. } else {
  146. assert(MBBI != MBB->end() && "Already past the end of the basic block!");
  147. MBBI = std::next(MBBI);
  148. }
  149. assert(MBBI != MBB->end() && "Already at the end of the basic block!");
  150. MachineInstr *MI = MBBI;
  151. for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
  152. IE = Scavenged.end(); I != IE; ++I) {
  153. if (I->Restore != MI)
  154. continue;
  155. I->Reg = 0;
  156. I->Restore = nullptr;
  157. }
  158. if (MI->isDebugValue())
  159. return;
  160. determineKillsAndDefs();
  161. // Verify uses and defs.
  162. #ifndef NDEBUG
  163. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  164. const MachineOperand &MO = MI->getOperand(i);
  165. if (!MO.isReg())
  166. continue;
  167. unsigned Reg = MO.getReg();
  168. if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
  169. continue;
  170. if (MO.isUse()) {
  171. if (MO.isUndef())
  172. continue;
  173. if (!isRegUsed(Reg)) {
  174. // Check if it's partial live: e.g.
  175. // D0 = insert_subreg D0<undef>, S0
  176. // ... D0
  177. // The problem is the insert_subreg could be eliminated. The use of
  178. // D0 is using a partially undef value. This is not *incorrect* since
  179. // S1 is can be freely clobbered.
  180. // Ideally we would like a way to model this, but leaving the
  181. // insert_subreg around causes both correctness and performance issues.
  182. bool SubUsed = false;
  183. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  184. if (isRegUsed(*SubRegs)) {
  185. SubUsed = true;
  186. break;
  187. }
  188. bool SuperUsed = false;
  189. for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
  190. if (isRegUsed(*SR)) {
  191. SuperUsed = true;
  192. break;
  193. }
  194. }
  195. if (!SubUsed && !SuperUsed) {
  196. MBB->getParent()->verify(nullptr, "In Register Scavenger");
  197. llvm_unreachable("Using an undefined register!");
  198. }
  199. (void)SubUsed;
  200. (void)SuperUsed;
  201. }
  202. } else {
  203. assert(MO.isDef());
  204. #if 0
  205. // FIXME: Enable this once we've figured out how to correctly transfer
  206. // implicit kills during codegen passes like the coalescer.
  207. assert((KillRegs.test(Reg) || isUnused(Reg) ||
  208. isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
  209. "Re-defining a live register!");
  210. #endif
  211. }
  212. }
  213. #endif // NDEBUG
  214. // Commit the changes.
  215. setUnused(KillRegUnits);
  216. setUsed(DefRegUnits);
  217. }
  218. bool RegScavenger::isRegUsed(unsigned Reg, bool includeReserved) const {
  219. if (includeReserved && isReserved(Reg))
  220. return true;
  221. for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
  222. if (!RegUnitsAvailable.test(*RUI))
  223. return true;
  224. return false;
  225. }
  226. unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
  227. for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
  228. I != E; ++I)
  229. if (!isRegUsed(*I)) {
  230. DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
  231. "\n");
  232. return *I;
  233. }
  234. return 0;
  235. }
  236. /// getRegsAvailable - Return all available registers in the register class
  237. /// in Mask.
  238. BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
  239. BitVector Mask(TRI->getNumRegs());
  240. for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
  241. I != E; ++I)
  242. if (!isRegUsed(*I))
  243. Mask.set(*I);
  244. return Mask;
  245. }
  246. /// findSurvivorReg - Return the candidate register that is unused for the
  247. /// longest after StartMII. UseMI is set to the instruction where the search
  248. /// stopped.
  249. ///
  250. /// No more than InstrLimit instructions are inspected.
  251. ///
  252. unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
  253. BitVector &Candidates,
  254. unsigned InstrLimit,
  255. MachineBasicBlock::iterator &UseMI) {
  256. int Survivor = Candidates.find_first();
  257. assert(Survivor > 0 && "No candidates for scavenging");
  258. MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
  259. assert(StartMI != ME && "MI already at terminator");
  260. MachineBasicBlock::iterator RestorePointMI = StartMI;
  261. MachineBasicBlock::iterator MI = StartMI;
  262. bool inVirtLiveRange = false;
  263. for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
  264. if (MI->isDebugValue()) {
  265. ++InstrLimit; // Don't count debug instructions
  266. continue;
  267. }
  268. bool isVirtKillInsn = false;
  269. bool isVirtDefInsn = false;
  270. // Remove any candidates touched by instruction.
  271. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  272. const MachineOperand &MO = MI->getOperand(i);
  273. if (MO.isRegMask())
  274. Candidates.clearBitsNotInMask(MO.getRegMask());
  275. if (!MO.isReg() || MO.isUndef() || !MO.getReg())
  276. continue;
  277. if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
  278. if (MO.isDef())
  279. isVirtDefInsn = true;
  280. else if (MO.isKill())
  281. isVirtKillInsn = true;
  282. continue;
  283. }
  284. for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
  285. Candidates.reset(*AI);
  286. }
  287. // If we're not in a virtual reg's live range, this is a valid
  288. // restore point.
  289. if (!inVirtLiveRange) RestorePointMI = MI;
  290. // Update whether we're in the live range of a virtual register
  291. if (isVirtKillInsn) inVirtLiveRange = false;
  292. if (isVirtDefInsn) inVirtLiveRange = true;
  293. // Was our survivor untouched by this instruction?
  294. if (Candidates.test(Survivor))
  295. continue;
  296. // All candidates gone?
  297. if (Candidates.none())
  298. break;
  299. Survivor = Candidates.find_first();
  300. }
  301. // If we ran off the end, that's where we want to restore.
  302. if (MI == ME) RestorePointMI = ME;
  303. assert (RestorePointMI != StartMI &&
  304. "No available scavenger restore location!");
  305. // We ran out of candidates, so stop the search.
  306. UseMI = RestorePointMI;
  307. return Survivor;
  308. }
  309. static unsigned getFrameIndexOperandNum(MachineInstr *MI) {
  310. unsigned i = 0;
  311. while (!MI->getOperand(i).isFI()) {
  312. ++i;
  313. assert(i < MI->getNumOperands() &&
  314. "Instr doesn't have FrameIndex operand!");
  315. }
  316. return i;
  317. }
  318. unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
  319. MachineBasicBlock::iterator I,
  320. int SPAdj) {
  321. // Consider all allocatable registers in the register class initially
  322. BitVector Candidates =
  323. TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
  324. // Exclude all the registers being used by the instruction.
  325. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  326. MachineOperand &MO = I->getOperand(i);
  327. if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
  328. !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  329. Candidates.reset(MO.getReg());
  330. }
  331. // Try to find a register that's unused if there is one, as then we won't
  332. // have to spill.
  333. BitVector Available = getRegsAvailable(RC);
  334. Available &= Candidates;
  335. if (Available.any())
  336. Candidates = Available;
  337. // Find the register whose use is furthest away.
  338. MachineBasicBlock::iterator UseMI;
  339. unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
  340. // If we found an unused register there is no reason to spill it.
  341. if (!isRegUsed(SReg)) {
  342. DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
  343. return SReg;
  344. }
  345. // Find an available scavenging slot.
  346. unsigned SI;
  347. for (SI = 0; SI < Scavenged.size(); ++SI)
  348. if (Scavenged[SI].Reg == 0)
  349. break;
  350. if (SI == Scavenged.size()) {
  351. // We need to scavenge a register but have no spill slot, the target
  352. // must know how to do it (if not, we'll assert below).
  353. Scavenged.push_back(ScavengedInfo());
  354. }
  355. // Avoid infinite regress
  356. Scavenged[SI].Reg = SReg;
  357. // If the target knows how to save/restore the register, let it do so;
  358. // otherwise, use the emergency stack spill slot.
  359. if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
  360. // Spill the scavenged register before I.
  361. assert(Scavenged[SI].FrameIndex >= 0 &&
  362. "Cannot scavenge register without an emergency spill slot!");
  363. TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
  364. RC, TRI);
  365. MachineBasicBlock::iterator II = std::prev(I);
  366. unsigned FIOperandNum = getFrameIndexOperandNum(II);
  367. TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
  368. // Restore the scavenged register before its use (or first terminator).
  369. TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
  370. RC, TRI);
  371. II = std::prev(UseMI);
  372. FIOperandNum = getFrameIndexOperandNum(II);
  373. TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
  374. }
  375. Scavenged[SI].Restore = std::prev(UseMI);
  376. // Doing this here leads to infinite regress.
  377. // Scavenged[SI].Reg = SReg;
  378. DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<
  379. "\n");
  380. return SReg;
  381. }