RegAllocBasic.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
  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 defines the RABasic function pass, which provides a minimal
  11. // implementation of the basic register allocator.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "regalloc"
  15. #include "RegAllocBase.h"
  16. #include "LiveDebugVariables.h"
  17. #include "RenderMachineFunction.h"
  18. #include "Spiller.h"
  19. #include "VirtRegMap.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Function.h"
  22. #include "llvm/PassAnalysisSupport.h"
  23. #include "llvm/CodeGen/CalcSpillWeights.h"
  24. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  25. #include "llvm/CodeGen/LiveRangeEdit.h"
  26. #include "llvm/CodeGen/LiveStackAnalysis.h"
  27. #include "llvm/CodeGen/MachineFunctionPass.h"
  28. #include "llvm/CodeGen/MachineInstr.h"
  29. #include "llvm/CodeGen/MachineLoopInfo.h"
  30. #include "llvm/CodeGen/MachineRegisterInfo.h"
  31. #include "llvm/CodeGen/Passes.h"
  32. #include "llvm/CodeGen/RegAllocRegistry.h"
  33. #include "llvm/Target/TargetMachine.h"
  34. #include "llvm/Target/TargetOptions.h"
  35. #include "llvm/Target/TargetRegisterInfo.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <cstdlib>
  39. #include <queue>
  40. using namespace llvm;
  41. static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
  42. createBasicRegisterAllocator);
  43. namespace {
  44. struct CompSpillWeight {
  45. bool operator()(LiveInterval *A, LiveInterval *B) const {
  46. return A->weight < B->weight;
  47. }
  48. };
  49. }
  50. namespace {
  51. /// RABasic provides a minimal implementation of the basic register allocation
  52. /// algorithm. It prioritizes live virtual registers by spill weight and spills
  53. /// whenever a register is unavailable. This is not practical in production but
  54. /// provides a useful baseline both for measuring other allocators and comparing
  55. /// the speed of the basic algorithm against other styles of allocators.
  56. class RABasic : public MachineFunctionPass, public RegAllocBase
  57. {
  58. // context
  59. MachineFunction *MF;
  60. // analyses
  61. LiveStacks *LS;
  62. RenderMachineFunction *RMF;
  63. // state
  64. std::auto_ptr<Spiller> SpillerInstance;
  65. std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
  66. CompSpillWeight> Queue;
  67. // Scratch space. Allocated here to avoid repeated malloc calls in
  68. // selectOrSplit().
  69. BitVector UsableRegs;
  70. public:
  71. RABasic();
  72. /// Return the pass name.
  73. virtual const char* getPassName() const {
  74. return "Basic Register Allocator";
  75. }
  76. /// RABasic analysis usage.
  77. virtual void getAnalysisUsage(AnalysisUsage &AU) const;
  78. virtual void releaseMemory();
  79. virtual Spiller &spiller() { return *SpillerInstance; }
  80. virtual float getPriority(LiveInterval *LI) { return LI->weight; }
  81. virtual void enqueue(LiveInterval *LI) {
  82. Queue.push(LI);
  83. }
  84. virtual LiveInterval *dequeue() {
  85. if (Queue.empty())
  86. return 0;
  87. LiveInterval *LI = Queue.top();
  88. Queue.pop();
  89. return LI;
  90. }
  91. virtual unsigned selectOrSplit(LiveInterval &VirtReg,
  92. SmallVectorImpl<LiveInterval*> &SplitVRegs);
  93. /// Perform register allocation.
  94. virtual bool runOnMachineFunction(MachineFunction &mf);
  95. // Helper for spilling all live virtual registers currently unified under preg
  96. // that interfere with the most recently queried lvr. Return true if spilling
  97. // was successful, and append any new spilled/split intervals to splitLVRs.
  98. bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
  99. SmallVectorImpl<LiveInterval*> &SplitVRegs);
  100. void spillReg(LiveInterval &VirtReg, unsigned PhysReg,
  101. SmallVectorImpl<LiveInterval*> &SplitVRegs);
  102. static char ID;
  103. };
  104. char RABasic::ID = 0;
  105. } // end anonymous namespace
  106. RABasic::RABasic(): MachineFunctionPass(ID) {
  107. initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
  108. initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
  109. initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
  110. initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
  111. initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
  112. initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
  113. initializeLiveStacksPass(*PassRegistry::getPassRegistry());
  114. initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
  115. initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
  116. initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
  117. initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
  118. }
  119. void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
  120. AU.setPreservesCFG();
  121. AU.addRequired<AliasAnalysis>();
  122. AU.addPreserved<AliasAnalysis>();
  123. AU.addRequired<LiveIntervals>();
  124. AU.addPreserved<SlotIndexes>();
  125. AU.addRequired<LiveDebugVariables>();
  126. AU.addPreserved<LiveDebugVariables>();
  127. AU.addRequired<CalculateSpillWeights>();
  128. AU.addRequired<LiveStacks>();
  129. AU.addPreserved<LiveStacks>();
  130. AU.addRequiredID(MachineDominatorsID);
  131. AU.addPreservedID(MachineDominatorsID);
  132. AU.addRequired<MachineLoopInfo>();
  133. AU.addPreserved<MachineLoopInfo>();
  134. AU.addRequired<VirtRegMap>();
  135. AU.addPreserved<VirtRegMap>();
  136. DEBUG(AU.addRequired<RenderMachineFunction>());
  137. MachineFunctionPass::getAnalysisUsage(AU);
  138. }
  139. void RABasic::releaseMemory() {
  140. SpillerInstance.reset(0);
  141. RegAllocBase::releaseMemory();
  142. }
  143. // Helper for spillInterferences() that spills all interfering vregs currently
  144. // assigned to this physical register.
  145. void RABasic::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
  146. SmallVectorImpl<LiveInterval*> &SplitVRegs) {
  147. LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
  148. assert(Q.seenAllInterferences() && "need collectInterferences()");
  149. const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
  150. for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
  151. E = PendingSpills.end(); I != E; ++I) {
  152. LiveInterval &SpilledVReg = **I;
  153. DEBUG(dbgs() << "extracting from " <<
  154. TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
  155. // Deallocate the interfering vreg by removing it from the union.
  156. // A LiveInterval instance may not be in a union during modification!
  157. unassign(SpilledVReg, PhysReg);
  158. // Spill the extracted interval.
  159. LiveRangeEdit LRE(&SpilledVReg, SplitVRegs, *MF, *LIS, VRM);
  160. spiller().spill(LRE);
  161. }
  162. // After extracting segments, the query's results are invalid. But keep the
  163. // contents valid until we're done accessing pendingSpills.
  164. Q.clear();
  165. }
  166. // Spill or split all live virtual registers currently unified under PhysReg
  167. // that interfere with VirtReg. The newly spilled or split live intervals are
  168. // returned by appending them to SplitVRegs.
  169. bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
  170. SmallVectorImpl<LiveInterval*> &SplitVRegs) {
  171. // Record each interference and determine if all are spillable before mutating
  172. // either the union or live intervals.
  173. unsigned NumInterferences = 0;
  174. // Collect interferences assigned to any alias of the physical register.
  175. for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
  176. LiveIntervalUnion::Query &QAlias = query(VirtReg, *AI);
  177. NumInterferences += QAlias.collectInterferingVRegs();
  178. if (QAlias.seenUnspillableVReg()) {
  179. return false;
  180. }
  181. }
  182. DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
  183. " interferences with " << VirtReg << "\n");
  184. assert(NumInterferences > 0 && "expect interference");
  185. // Spill each interfering vreg allocated to PhysReg or an alias.
  186. for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI)
  187. spillReg(VirtReg, *AI, SplitVRegs);
  188. return true;
  189. }
  190. // Driver for the register assignment and splitting heuristics.
  191. // Manages iteration over the LiveIntervalUnions.
  192. //
  193. // This is a minimal implementation of register assignment and splitting that
  194. // spills whenever we run out of registers.
  195. //
  196. // selectOrSplit can only be called once per live virtual register. We then do a
  197. // single interference test for each register the correct class until we find an
  198. // available register. So, the number of interference tests in the worst case is
  199. // |vregs| * |machineregs|. And since the number of interference tests is
  200. // minimal, there is no value in caching them outside the scope of
  201. // selectOrSplit().
  202. unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
  203. SmallVectorImpl<LiveInterval*> &SplitVRegs) {
  204. // Check for register mask interference. When live ranges cross calls, the
  205. // set of usable registers is reduced to the callee-saved ones.
  206. bool CrossRegMasks = LIS->checkRegMaskInterference(VirtReg, UsableRegs);
  207. // Populate a list of physical register spill candidates.
  208. SmallVector<unsigned, 8> PhysRegSpillCands;
  209. // Check for an available register in this class.
  210. ArrayRef<unsigned> Order =
  211. RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg));
  212. for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E;
  213. ++I) {
  214. unsigned PhysReg = *I;
  215. // If PhysReg is clobbered by a register mask, it isn't useful for
  216. // allocation or spilling.
  217. if (CrossRegMasks && !UsableRegs.test(PhysReg))
  218. continue;
  219. // Check interference and as a side effect, intialize queries for this
  220. // VirtReg and its aliases.
  221. unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
  222. if (interfReg == 0) {
  223. // Found an available register.
  224. return PhysReg;
  225. }
  226. LiveIntervalUnion::Query &IntfQ = query(VirtReg, interfReg);
  227. IntfQ.collectInterferingVRegs(1);
  228. LiveInterval *interferingVirtReg = IntfQ.interferingVRegs().front();
  229. // The current VirtReg must either be spillable, or one of its interferences
  230. // must have less spill weight.
  231. if (interferingVirtReg->weight < VirtReg.weight ) {
  232. PhysRegSpillCands.push_back(PhysReg);
  233. }
  234. }
  235. // Try to spill another interfering reg with less spill weight.
  236. for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
  237. PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
  238. if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
  239. assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
  240. "Interference after spill.");
  241. // Tell the caller to allocate to this newly freed physical register.
  242. return *PhysRegI;
  243. }
  244. // No other spill candidates were found, so spill the current VirtReg.
  245. DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
  246. if (!VirtReg.isSpillable())
  247. return ~0u;
  248. LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
  249. spiller().spill(LRE);
  250. // The live virtual register requesting allocation was spilled, so tell
  251. // the caller not to allocate anything during this round.
  252. return 0;
  253. }
  254. bool RABasic::runOnMachineFunction(MachineFunction &mf) {
  255. DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
  256. << "********** Function: "
  257. << ((Value*)mf.getFunction())->getName() << '\n');
  258. MF = &mf;
  259. DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
  260. RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
  261. SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
  262. allocatePhysRegs();
  263. addMBBLiveIns(MF);
  264. // Diagnostic output before rewriting
  265. DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
  266. // optional HTML output
  267. DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
  268. // FIXME: Verification currently must run before VirtRegRewriter. We should
  269. // make the rewriter a separate pass and override verifyAnalysis instead. When
  270. // that happens, verification naturally falls under VerifyMachineCode.
  271. #ifndef NDEBUG
  272. if (VerifyEnabled) {
  273. // Verify accuracy of LiveIntervals. The standard machine code verifier
  274. // ensures that each LiveIntervals covers all uses of the virtual reg.
  275. // FIXME: MachineVerifier is badly broken when using the standard
  276. // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
  277. // inline spiller, some tests fail to verify because the coalescer does not
  278. // always generate verifiable code.
  279. MF->verify(this, "In RABasic::verify");
  280. // Verify that LiveIntervals are partitioned into unions and disjoint within
  281. // the unions.
  282. verify();
  283. }
  284. #endif // !NDEBUG
  285. // Run rewriter
  286. VRM->rewrite(LIS->getSlotIndexes());
  287. // Write out new DBG_VALUE instructions.
  288. getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
  289. // All machine operands and other references to virtual registers have been
  290. // replaced. Remove the virtual registers and release all the transient data.
  291. VRM->clearAllVirt();
  292. MRI->clearVirtRegs();
  293. releaseMemory();
  294. return true;
  295. }
  296. FunctionPass* llvm::createBasicRegisterAllocator()
  297. {
  298. return new RABasic();
  299. }