RegAllocBasic.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the RABasic function pass, which provides a minimal
  10. // implementation of the basic register allocator.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "AllocationOrder.h"
  14. #include "LiveDebugVariables.h"
  15. #include "RegAllocBase.h"
  16. #include "llvm/Analysis/AliasAnalysis.h"
  17. #include "llvm/CodeGen/CalcSpillWeights.h"
  18. #include "llvm/CodeGen/LiveIntervals.h"
  19. #include "llvm/CodeGen/LiveRangeEdit.h"
  20. #include "llvm/CodeGen/LiveRegMatrix.h"
  21. #include "llvm/CodeGen/LiveStacks.h"
  22. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  23. #include "llvm/CodeGen/MachineFunctionPass.h"
  24. #include "llvm/CodeGen/MachineInstr.h"
  25. #include "llvm/CodeGen/MachineLoopInfo.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/CodeGen/Passes.h"
  28. #include "llvm/CodeGen/RegAllocRegistry.h"
  29. #include "llvm/CodeGen/Spiller.h"
  30. #include "llvm/CodeGen/TargetRegisterInfo.h"
  31. #include "llvm/CodeGen/VirtRegMap.h"
  32. #include "llvm/Pass.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <cstdlib>
  36. #include <queue>
  37. using namespace llvm;
  38. #define DEBUG_TYPE "regalloc"
  39. static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
  40. createBasicRegisterAllocator);
  41. namespace {
  42. struct CompSpillWeight {
  43. bool operator()(LiveInterval *A, LiveInterval *B) const {
  44. return A->weight() < B->weight();
  45. }
  46. };
  47. }
  48. namespace {
  49. /// RABasic provides a minimal implementation of the basic register allocation
  50. /// algorithm. It prioritizes live virtual registers by spill weight and spills
  51. /// whenever a register is unavailable. This is not practical in production but
  52. /// provides a useful baseline both for measuring other allocators and comparing
  53. /// the speed of the basic algorithm against other styles of allocators.
  54. class RABasic : public MachineFunctionPass,
  55. public RegAllocBase,
  56. private LiveRangeEdit::Delegate {
  57. // context
  58. MachineFunction *MF;
  59. // state
  60. std::unique_ptr<Spiller> SpillerInstance;
  61. std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
  62. CompSpillWeight> Queue;
  63. // Scratch space. Allocated here to avoid repeated malloc calls in
  64. // selectOrSplit().
  65. BitVector UsableRegs;
  66. bool LRE_CanEraseVirtReg(Register) override;
  67. void LRE_WillShrinkVirtReg(Register) override;
  68. public:
  69. RABasic(const RegClassFilterFunc F = allocateAllRegClasses);
  70. /// Return the pass name.
  71. StringRef getPassName() const override { return "Basic Register Allocator"; }
  72. /// RABasic analysis usage.
  73. void getAnalysisUsage(AnalysisUsage &AU) const override;
  74. void releaseMemory() override;
  75. Spiller &spiller() override { return *SpillerInstance; }
  76. void enqueueImpl(LiveInterval *LI) override {
  77. Queue.push(LI);
  78. }
  79. LiveInterval *dequeue() override {
  80. if (Queue.empty())
  81. return nullptr;
  82. LiveInterval *LI = Queue.top();
  83. Queue.pop();
  84. return LI;
  85. }
  86. MCRegister selectOrSplit(LiveInterval &VirtReg,
  87. SmallVectorImpl<Register> &SplitVRegs) override;
  88. /// Perform register allocation.
  89. bool runOnMachineFunction(MachineFunction &mf) override;
  90. MachineFunctionProperties getRequiredProperties() const override {
  91. return MachineFunctionProperties().set(
  92. MachineFunctionProperties::Property::NoPHIs);
  93. }
  94. MachineFunctionProperties getClearedProperties() const override {
  95. return MachineFunctionProperties().set(
  96. MachineFunctionProperties::Property::IsSSA);
  97. }
  98. // Helper for spilling all live virtual registers currently unified under preg
  99. // that interfere with the most recently queried lvr. Return true if spilling
  100. // was successful, and append any new spilled/split intervals to splitLVRs.
  101. bool spillInterferences(LiveInterval &VirtReg, MCRegister PhysReg,
  102. SmallVectorImpl<Register> &SplitVRegs);
  103. static char ID;
  104. };
  105. char RABasic::ID = 0;
  106. } // end anonymous namespace
  107. char &llvm::RABasicID = RABasic::ID;
  108. INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
  109. false, false)
  110. INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
  111. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  112. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  113. INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
  114. INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
  115. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  116. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  117. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  118. INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
  119. INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
  120. INITIALIZE_PASS_END(RABasic, "regallocbasic", "Basic Register Allocator", false,
  121. false)
  122. bool RABasic::LRE_CanEraseVirtReg(Register VirtReg) {
  123. LiveInterval &LI = LIS->getInterval(VirtReg);
  124. if (VRM->hasPhys(VirtReg)) {
  125. Matrix->unassign(LI);
  126. aboutToRemoveInterval(LI);
  127. return true;
  128. }
  129. // Unassigned virtreg is probably in the priority queue.
  130. // RegAllocBase will erase it after dequeueing.
  131. // Nonetheless, clear the live-range so that the debug
  132. // dump will show the right state for that VirtReg.
  133. LI.clear();
  134. return false;
  135. }
  136. void RABasic::LRE_WillShrinkVirtReg(Register VirtReg) {
  137. if (!VRM->hasPhys(VirtReg))
  138. return;
  139. // Register is assigned, put it back on the queue for reassignment.
  140. LiveInterval &LI = LIS->getInterval(VirtReg);
  141. Matrix->unassign(LI);
  142. enqueue(&LI);
  143. }
  144. RABasic::RABasic(RegClassFilterFunc F):
  145. MachineFunctionPass(ID),
  146. RegAllocBase(F) {
  147. }
  148. void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
  149. AU.setPreservesCFG();
  150. AU.addRequired<AAResultsWrapperPass>();
  151. AU.addPreserved<AAResultsWrapperPass>();
  152. AU.addRequired<LiveIntervals>();
  153. AU.addPreserved<LiveIntervals>();
  154. AU.addPreserved<SlotIndexes>();
  155. AU.addRequired<LiveDebugVariables>();
  156. AU.addPreserved<LiveDebugVariables>();
  157. AU.addRequired<LiveStacks>();
  158. AU.addPreserved<LiveStacks>();
  159. AU.addRequired<MachineBlockFrequencyInfo>();
  160. AU.addPreserved<MachineBlockFrequencyInfo>();
  161. AU.addRequiredID(MachineDominatorsID);
  162. AU.addPreservedID(MachineDominatorsID);
  163. AU.addRequired<MachineLoopInfo>();
  164. AU.addPreserved<MachineLoopInfo>();
  165. AU.addRequired<VirtRegMap>();
  166. AU.addPreserved<VirtRegMap>();
  167. AU.addRequired<LiveRegMatrix>();
  168. AU.addPreserved<LiveRegMatrix>();
  169. MachineFunctionPass::getAnalysisUsage(AU);
  170. }
  171. void RABasic::releaseMemory() {
  172. SpillerInstance.reset();
  173. }
  174. // Spill or split all live virtual registers currently unified under PhysReg
  175. // that interfere with VirtReg. The newly spilled or split live intervals are
  176. // returned by appending them to SplitVRegs.
  177. bool RABasic::spillInterferences(LiveInterval &VirtReg, MCRegister PhysReg,
  178. SmallVectorImpl<Register> &SplitVRegs) {
  179. // Record each interference and determine if all are spillable before mutating
  180. // either the union or live intervals.
  181. SmallVector<LiveInterval*, 8> Intfs;
  182. // Collect interferences assigned to any alias of the physical register.
  183. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  184. LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
  185. for (auto *Intf : reverse(Q.interferingVRegs())) {
  186. if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
  187. return false;
  188. Intfs.push_back(Intf);
  189. }
  190. }
  191. LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
  192. << " interferences with " << VirtReg << "\n");
  193. assert(!Intfs.empty() && "expected interference");
  194. // Spill each interfering vreg allocated to PhysReg or an alias.
  195. for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
  196. LiveInterval &Spill = *Intfs[i];
  197. // Skip duplicates.
  198. if (!VRM->hasPhys(Spill.reg()))
  199. continue;
  200. // Deallocate the interfering vreg by removing it from the union.
  201. // A LiveInterval instance may not be in a union during modification!
  202. Matrix->unassign(Spill);
  203. // Spill the extracted interval.
  204. LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
  205. spiller().spill(LRE);
  206. }
  207. return true;
  208. }
  209. // Driver for the register assignment and splitting heuristics.
  210. // Manages iteration over the LiveIntervalUnions.
  211. //
  212. // This is a minimal implementation of register assignment and splitting that
  213. // spills whenever we run out of registers.
  214. //
  215. // selectOrSplit can only be called once per live virtual register. We then do a
  216. // single interference test for each register the correct class until we find an
  217. // available register. So, the number of interference tests in the worst case is
  218. // |vregs| * |machineregs|. And since the number of interference tests is
  219. // minimal, there is no value in caching them outside the scope of
  220. // selectOrSplit().
  221. MCRegister RABasic::selectOrSplit(LiveInterval &VirtReg,
  222. SmallVectorImpl<Register> &SplitVRegs) {
  223. // Populate a list of physical register spill candidates.
  224. SmallVector<MCRegister, 8> PhysRegSpillCands;
  225. // Check for an available register in this class.
  226. auto Order =
  227. AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
  228. for (MCRegister PhysReg : Order) {
  229. assert(PhysReg.isValid());
  230. // Check for interference in PhysReg
  231. switch (Matrix->checkInterference(VirtReg, PhysReg)) {
  232. case LiveRegMatrix::IK_Free:
  233. // PhysReg is available, allocate it.
  234. return PhysReg;
  235. case LiveRegMatrix::IK_VirtReg:
  236. // Only virtual registers in the way, we may be able to spill them.
  237. PhysRegSpillCands.push_back(PhysReg);
  238. continue;
  239. default:
  240. // RegMask or RegUnit interference.
  241. continue;
  242. }
  243. }
  244. // Try to spill another interfering reg with less spill weight.
  245. for (MCRegister &PhysReg : PhysRegSpillCands) {
  246. if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
  247. continue;
  248. assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
  249. "Interference after spill.");
  250. // Tell the caller to allocate to this newly freed physical register.
  251. return PhysReg;
  252. }
  253. // No other spill candidates were found, so spill the current VirtReg.
  254. LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
  255. if (!VirtReg.isSpillable())
  256. return ~0u;
  257. LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
  258. spiller().spill(LRE);
  259. // The live virtual register requesting allocation was spilled, so tell
  260. // the caller not to allocate anything during this round.
  261. return 0;
  262. }
  263. bool RABasic::runOnMachineFunction(MachineFunction &mf) {
  264. LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
  265. << "********** Function: " << mf.getName() << '\n');
  266. MF = &mf;
  267. RegAllocBase::init(getAnalysis<VirtRegMap>(),
  268. getAnalysis<LiveIntervals>(),
  269. getAnalysis<LiveRegMatrix>());
  270. VirtRegAuxInfo VRAI(*MF, *LIS, *VRM, getAnalysis<MachineLoopInfo>(),
  271. getAnalysis<MachineBlockFrequencyInfo>());
  272. VRAI.calculateSpillWeightsAndHints();
  273. SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, VRAI));
  274. allocatePhysRegs();
  275. postOptimization();
  276. // Diagnostic output before rewriting
  277. LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
  278. releaseMemory();
  279. return true;
  280. }
  281. FunctionPass* llvm::createBasicRegisterAllocator() {
  282. return new RABasic();
  283. }
  284. FunctionPass* llvm::createBasicRegisterAllocator(RegClassFilterFunc F) {
  285. return new RABasic(F);
  286. }