RegAllocBasic.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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 "LiveIntervalUnion.h"
  16. #include "RegAllocBase.h"
  17. #include "RenderMachineFunction.h"
  18. #include "Spiller.h"
  19. #include "VirtRegMap.h"
  20. #include "VirtRegRewriter.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/LiveStackAnalysis.h"
  26. #include "llvm/CodeGen/MachineFunctionPass.h"
  27. #include "llvm/CodeGen/MachineInstr.h"
  28. #include "llvm/CodeGen/MachineLoopInfo.h"
  29. #include "llvm/CodeGen/MachineRegisterInfo.h"
  30. #include "llvm/CodeGen/Passes.h"
  31. #include "llvm/CodeGen/RegAllocRegistry.h"
  32. #include "llvm/CodeGen/RegisterCoalescer.h"
  33. #include "llvm/Target/TargetMachine.h"
  34. #include "llvm/Target/TargetOptions.h"
  35. #include "llvm/Target/TargetRegisterInfo.h"
  36. #ifndef NDEBUG
  37. #include "llvm/ADT/SparseBitVector.h"
  38. #endif
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include <vector>
  43. #include <queue>
  44. using namespace llvm;
  45. static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
  46. createBasicRegisterAllocator);
  47. // Temporary verification option until we can put verification inside
  48. // MachineVerifier.
  49. static cl::opt<bool>
  50. VerifyRegAlloc("verify-regalloc",
  51. cl::desc("Verify live intervals before renaming"));
  52. class PhysicalRegisterDescription : public AbstractRegisterDescription {
  53. const TargetRegisterInfo *tri_;
  54. public:
  55. PhysicalRegisterDescription(const TargetRegisterInfo *tri): tri_(tri) {}
  56. virtual const char *getName(unsigned reg) const { return tri_->getName(reg); }
  57. };
  58. namespace {
  59. /// RABasic provides a minimal implementation of the basic register allocation
  60. /// algorithm. It prioritizes live virtual registers by spill weight and spills
  61. /// whenever a register is unavailable. This is not practical in production but
  62. /// provides a useful baseline both for measuring other allocators and comparing
  63. /// the speed of the basic algorithm against other styles of allocators.
  64. class RABasic : public MachineFunctionPass, public RegAllocBase
  65. {
  66. // context
  67. MachineFunction *mf_;
  68. const TargetMachine *tm_;
  69. MachineRegisterInfo *mri_;
  70. // analyses
  71. LiveStacks *ls_;
  72. RenderMachineFunction *rmf_;
  73. // state
  74. std::auto_ptr<Spiller> spiller_;
  75. public:
  76. RABasic();
  77. /// Return the pass name.
  78. virtual const char* getPassName() const {
  79. return "Basic Register Allocator";
  80. }
  81. /// RABasic analysis usage.
  82. virtual void getAnalysisUsage(AnalysisUsage &au) const;
  83. virtual void releaseMemory();
  84. virtual Spiller &spiller() { return *spiller_; }
  85. virtual unsigned selectOrSplit(LiveInterval &lvr,
  86. SmallVectorImpl<LiveInterval*> &splitLVRs);
  87. /// Perform register allocation.
  88. virtual bool runOnMachineFunction(MachineFunction &mf);
  89. static char ID;
  90. };
  91. char RABasic::ID = 0;
  92. } // end anonymous namespace
  93. // We should not need to publish the initializer as long as no other passes
  94. // require RABasic.
  95. #if 0 // disable INITIALIZE_PASS
  96. INITIALIZE_PASS_BEGIN(RABasic, "basic-regalloc",
  97. "Basic Register Allocator", false, false)
  98. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  99. INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
  100. INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
  101. INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
  102. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  103. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  104. INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
  105. #ifndef NDEBUG
  106. INITIALIZE_PASS_DEPENDENCY(RenderMachineFunction)
  107. #endif
  108. INITIALIZE_PASS_END(RABasic, "basic-regalloc",
  109. "Basic Register Allocator", false, false)
  110. #endif // disable INITIALIZE_PASS
  111. RABasic::RABasic(): MachineFunctionPass(ID) {
  112. initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
  113. initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
  114. initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
  115. initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
  116. initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
  117. initializeLiveStacksPass(*PassRegistry::getPassRegistry());
  118. initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
  119. initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
  120. initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
  121. initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
  122. }
  123. void RABasic::getAnalysisUsage(AnalysisUsage &au) const {
  124. au.setPreservesCFG();
  125. au.addRequired<LiveIntervals>();
  126. au.addPreserved<SlotIndexes>();
  127. if (StrongPHIElim)
  128. au.addRequiredID(StrongPHIEliminationID);
  129. au.addRequiredTransitive<RegisterCoalescer>();
  130. au.addRequired<CalculateSpillWeights>();
  131. au.addRequired<LiveStacks>();
  132. au.addPreserved<LiveStacks>();
  133. au.addRequiredID(MachineDominatorsID);
  134. au.addPreservedID(MachineDominatorsID);
  135. au.addRequired<MachineLoopInfo>();
  136. au.addPreserved<MachineLoopInfo>();
  137. au.addRequired<VirtRegMap>();
  138. au.addPreserved<VirtRegMap>();
  139. DEBUG(au.addRequired<RenderMachineFunction>());
  140. MachineFunctionPass::getAnalysisUsage(au);
  141. }
  142. void RABasic::releaseMemory() {
  143. spiller_.reset(0);
  144. RegAllocBase::releaseMemory();
  145. }
  146. #ifndef NDEBUG
  147. // Verify each LiveIntervalUnion.
  148. void RegAllocBase::verify() {
  149. LvrBitSet visitedVRegs;
  150. OwningArrayPtr<LvrBitSet> unionVRegs(new LvrBitSet[physReg2liu_.numRegs()]);
  151. // Verify disjoint unions.
  152. for (unsigned preg = 0; preg < physReg2liu_.numRegs(); ++preg) {
  153. DEBUG(PhysicalRegisterDescription prd(tri_); physReg2liu_[preg].dump(&prd));
  154. LvrBitSet &vregs = unionVRegs[preg];
  155. physReg2liu_[preg].verify(vregs);
  156. // Union + intersection test could be done efficiently in one pass, but
  157. // don't add a method to SparseBitVector unless we really need it.
  158. assert(!visitedVRegs.intersects(vregs) && "vreg in multiple unions");
  159. visitedVRegs |= vregs;
  160. }
  161. // Verify vreg coverage.
  162. for (LiveIntervals::iterator liItr = lis_->begin(), liEnd = lis_->end();
  163. liItr != liEnd; ++liItr) {
  164. unsigned reg = liItr->first;
  165. LiveInterval &li = *liItr->second;
  166. if (li.empty() ) continue;
  167. if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
  168. if (!vrm_->hasPhys(reg)) continue; // spilled?
  169. unsigned preg = vrm_->getPhys(reg);
  170. if (!unionVRegs[preg].test(reg)) {
  171. dbgs() << "LiveVirtReg " << reg << " not in union " <<
  172. tri_->getName(preg) << "\n";
  173. llvm_unreachable("unallocated live vreg");
  174. }
  175. }
  176. // FIXME: I'm not sure how to verify spilled intervals.
  177. }
  178. #endif //!NDEBUG
  179. //===----------------------------------------------------------------------===//
  180. // RegAllocBase Implementation
  181. //===----------------------------------------------------------------------===//
  182. // Instantiate a LiveIntervalUnion for each physical register.
  183. void RegAllocBase::LIUArray::init(unsigned nRegs) {
  184. array_.reset(new LiveIntervalUnion[nRegs]);
  185. nRegs_ = nRegs;
  186. for (unsigned pr = 0; pr < nRegs; ++pr) {
  187. array_[pr].init(pr);
  188. }
  189. }
  190. void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
  191. LiveIntervals &lis) {
  192. tri_ = &tri;
  193. vrm_ = &vrm;
  194. lis_ = &lis;
  195. physReg2liu_.init(tri_->getNumRegs());
  196. // Cache an interferece query for each physical reg
  197. queries_.reset(new LiveIntervalUnion::Query[physReg2liu_.numRegs()]);
  198. }
  199. void RegAllocBase::LIUArray::clear() {
  200. nRegs_ = 0;
  201. array_.reset(0);
  202. }
  203. void RegAllocBase::releaseMemory() {
  204. physReg2liu_.clear();
  205. }
  206. namespace llvm {
  207. /// This class defines a queue of live virtual registers prioritized by spill
  208. /// weight. The heaviest vreg is popped first.
  209. ///
  210. /// Currently, this is trivial wrapper that gives us an opaque type in the
  211. /// header, but we may later give it a virtual interface for register allocators
  212. /// to override the priority queue comparator.
  213. class LiveVirtRegQueue {
  214. typedef std::priority_queue
  215. <LiveInterval*, std::vector<LiveInterval*>, LessSpillWeightPriority> PQ;
  216. PQ pq_;
  217. public:
  218. // Is the queue empty?
  219. bool empty() { return pq_.empty(); }
  220. // Get the highest priority lvr (top + pop)
  221. LiveInterval *get() {
  222. LiveInterval *lvr = pq_.top();
  223. pq_.pop();
  224. return lvr;
  225. }
  226. // Add this lvr to the queue
  227. void push(LiveInterval *lvr) {
  228. pq_.push(lvr);
  229. }
  230. };
  231. } // end namespace llvm
  232. // Visit all the live virtual registers. If they are already assigned to a
  233. // physical register, unify them with the corresponding LiveIntervalUnion,
  234. // otherwise push them on the priority queue for later assignment.
  235. void RegAllocBase::seedLiveVirtRegs(LiveVirtRegQueue &lvrQ) {
  236. for (LiveIntervals::iterator liItr = lis_->begin(), liEnd = lis_->end();
  237. liItr != liEnd; ++liItr) {
  238. unsigned reg = liItr->first;
  239. LiveInterval &li = *liItr->second;
  240. if (li.empty()) continue;
  241. if (TargetRegisterInfo::isPhysicalRegister(reg)) {
  242. physReg2liu_[reg].unify(li);
  243. }
  244. else {
  245. lvrQ.push(&li);
  246. }
  247. }
  248. }
  249. // Top-level driver to manage the queue of unassigned LiveVirtRegs and call the
  250. // selectOrSplit implementation.
  251. void RegAllocBase::allocatePhysRegs() {
  252. LiveVirtRegQueue lvrQ;
  253. seedLiveVirtRegs(lvrQ);
  254. while (!lvrQ.empty()) {
  255. LiveInterval *lvr = lvrQ.get();
  256. typedef SmallVector<LiveInterval*, 4> LVRVec;
  257. LVRVec splitLVRs;
  258. unsigned availablePhysReg = selectOrSplit(*lvr, splitLVRs);
  259. if (availablePhysReg) {
  260. DEBUG(dbgs() << "allocating: " << tri_->getName(availablePhysReg) <<
  261. " " << *lvr << '\n');
  262. assert(!vrm_->hasPhys(lvr->reg) && "duplicate vreg in interval unions");
  263. vrm_->assignVirt2Phys(lvr->reg, availablePhysReg);
  264. physReg2liu_[availablePhysReg].unify(*lvr);
  265. }
  266. for (LVRVec::iterator lvrI = splitLVRs.begin(), lvrEnd = splitLVRs.end();
  267. lvrI != lvrEnd; ++lvrI) {
  268. if ((*lvrI)->empty()) continue;
  269. DEBUG(dbgs() << "queuing new interval: " << **lvrI << "\n");
  270. assert(TargetRegisterInfo::isVirtualRegister((*lvrI)->reg) &&
  271. "expect split value in virtual register");
  272. lvrQ.push(*lvrI);
  273. }
  274. }
  275. }
  276. // Check if this live virtual reg interferes with a physical register. If not,
  277. // then check for interference on each register that aliases with the physical
  278. // register. Return the interfering register.
  279. unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &lvr,
  280. unsigned preg) {
  281. queries_[preg].init(&lvr, &physReg2liu_[preg]);
  282. if (queries_[preg].checkInterference())
  283. return preg;
  284. for (const unsigned *asI = tri_->getAliasSet(preg); *asI; ++asI) {
  285. queries_[*asI].init(&lvr, &physReg2liu_[*asI]);
  286. if (queries_[*asI].checkInterference())
  287. return *asI;
  288. }
  289. return 0;
  290. }
  291. // Sort live virtual registers by their register number.
  292. struct LessLiveVirtualReg
  293. : public std::binary_function<LiveInterval, LiveInterval, bool> {
  294. bool operator()(const LiveInterval *left, const LiveInterval *right) const {
  295. return left->reg < right->reg;
  296. }
  297. };
  298. // Spill all interferences currently assigned to this physical register.
  299. void RegAllocBase::spillReg(unsigned reg,
  300. SmallVectorImpl<LiveInterval*> &splitLVRs) {
  301. LiveIntervalUnion::Query &query = queries_[reg];
  302. const SmallVectorImpl<LiveInterval*> &pendingSpills =
  303. query.interferingVRegs();
  304. for (SmallVectorImpl<LiveInterval*>::const_iterator I = pendingSpills.begin(),
  305. E = pendingSpills.end(); I != E; ++I) {
  306. LiveInterval &lvr = **I;
  307. DEBUG(dbgs() <<
  308. "extracting from " << tri_->getName(reg) << " " << lvr << '\n');
  309. // Deallocate the interfering vreg by removing it from the union.
  310. // A LiveInterval instance may not be in a union during modification!
  311. physReg2liu_[reg].extract(lvr);
  312. // After extracting segments, the query's results are invalid.
  313. query.clear();
  314. // Clear the vreg assignment.
  315. vrm_->clearVirt(lvr.reg);
  316. // Spill the extracted interval.
  317. spiller().spill(&lvr, splitLVRs, pendingSpills);
  318. }
  319. }
  320. // Spill or split all live virtual registers currently unified under preg that
  321. // interfere with lvr. The newly spilled or split live intervals are returned by
  322. // appending them to splitLVRs.
  323. bool
  324. RegAllocBase::spillInterferences(unsigned preg,
  325. SmallVectorImpl<LiveInterval*> &splitLVRs) {
  326. // Record each interference and determine if all are spillable before mutating
  327. // either the union or live intervals.
  328. std::vector<LiveInterval*> spilledLVRs;
  329. unsigned numInterferences = queries_[preg].collectInterferingVRegs();
  330. if (queries_[preg].seenUnspillableVReg()) {
  331. return false;
  332. }
  333. for (const unsigned *asI = tri_->getAliasSet(preg); *asI; ++asI) {
  334. numInterferences += queries_[*asI].collectInterferingVRegs();
  335. if (queries_[*asI].seenUnspillableVReg()) {
  336. return false;
  337. }
  338. }
  339. DEBUG(dbgs() << "spilling " << tri_->getName(preg) <<
  340. " interferences with " << queries_[preg].lvr() << "\n");
  341. assert(numInterferences > 0 && "expect interference");
  342. // Spill each interfering vreg allocated to preg or an alias.
  343. spillReg(preg, splitLVRs);
  344. for (const unsigned *asI = tri_->getAliasSet(preg); *asI; ++asI)
  345. spillReg(*asI, splitLVRs);
  346. return true;
  347. }
  348. //===----------------------------------------------------------------------===//
  349. // RABasic Implementation
  350. //===----------------------------------------------------------------------===//
  351. // Driver for the register assignment and splitting heuristics.
  352. // Manages iteration over the LiveIntervalUnions.
  353. //
  354. // Minimal implementation of register assignment and splitting--spills whenever
  355. // we run out of registers.
  356. //
  357. // selectOrSplit can only be called once per live virtual register. We then do a
  358. // single interference test for each register the correct class until we find an
  359. // available register. So, the number of interference tests in the worst case is
  360. // |vregs| * |machineregs|. And since the number of interference tests is
  361. // minimal, there is no value in caching them.
  362. unsigned RABasic::selectOrSplit(LiveInterval &lvr,
  363. SmallVectorImpl<LiveInterval*> &splitLVRs) {
  364. // Populate a list of physical register spill candidates.
  365. std::vector<unsigned> pregSpillCands;
  366. // Check for an available register in this class.
  367. const TargetRegisterClass *trc = mri_->getRegClass(lvr.reg);
  368. for (TargetRegisterClass::iterator trcI = trc->allocation_order_begin(*mf_),
  369. trcEnd = trc->allocation_order_end(*mf_);
  370. trcI != trcEnd; ++trcI) {
  371. unsigned preg = *trcI;
  372. // Check interference and intialize queries for this lvr as a side effect.
  373. unsigned interfReg = checkPhysRegInterference(lvr, preg);
  374. if (interfReg == 0) {
  375. // Found an available register.
  376. return preg;
  377. }
  378. LiveInterval *interferingVirtReg =
  379. queries_[interfReg].firstInterference().liuSegPos()->liveVirtReg;
  380. // The current lvr must either spillable, or one of its interferences must
  381. // have less spill weight.
  382. if (interferingVirtReg->weight < lvr.weight ) {
  383. pregSpillCands.push_back(preg);
  384. }
  385. }
  386. // Try to spill another interfering reg with less spill weight.
  387. //
  388. // FIXME: RAGreedy will sort this list by spill weight.
  389. for (std::vector<unsigned>::iterator pregI = pregSpillCands.begin(),
  390. pregE = pregSpillCands.end(); pregI != pregE; ++pregI) {
  391. if (!spillInterferences(*pregI, splitLVRs)) continue;
  392. unsigned interfReg = checkPhysRegInterference(lvr, *pregI);
  393. if (interfReg != 0) {
  394. const LiveSegment &seg =
  395. *queries_[interfReg].firstInterference().liuSegPos();
  396. dbgs() << "spilling cannot free " << tri_->getName(*pregI) <<
  397. " for " << lvr.reg << " with interference " << seg.liveVirtReg << "\n";
  398. llvm_unreachable("Interference after spill.");
  399. }
  400. // Tell the caller to allocate to this newly freed physical register.
  401. return *pregI;
  402. }
  403. // No other spill candidates were found, so spill the current lvr.
  404. DEBUG(dbgs() << "spilling: " << lvr << '\n');
  405. SmallVector<LiveInterval*, 1> pendingSpills;
  406. spiller().spill(&lvr, splitLVRs, pendingSpills);
  407. // The live virtual register requesting allocation was spilled, so tell
  408. // the caller not to allocate anything during this round.
  409. return 0;
  410. }
  411. namespace llvm {
  412. Spiller *createInlineSpiller(MachineFunctionPass &pass,
  413. MachineFunction &mf,
  414. VirtRegMap &vrm);
  415. }
  416. bool RABasic::runOnMachineFunction(MachineFunction &mf) {
  417. DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
  418. << "********** Function: "
  419. << ((Value*)mf.getFunction())->getName() << '\n');
  420. mf_ = &mf;
  421. tm_ = &mf.getTarget();
  422. mri_ = &mf.getRegInfo();
  423. DEBUG(rmf_ = &getAnalysis<RenderMachineFunction>());
  424. RegAllocBase::init(*tm_->getRegisterInfo(), getAnalysis<VirtRegMap>(),
  425. getAnalysis<LiveIntervals>());
  426. // We may want to force InlineSpiller for this register allocator. For
  427. // now we're also experimenting with the standard spiller.
  428. //
  429. //spiller_.reset(createInlineSpiller(*this, *mf_, *vrm_));
  430. spiller_.reset(createSpiller(*this, *mf_, *vrm_));
  431. allocatePhysRegs();
  432. // Diagnostic output before rewriting
  433. DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm_ << "\n");
  434. // optional HTML output
  435. DEBUG(rmf_->renderMachineFunction("After basic register allocation.", vrm_));
  436. // FIXME: Verification currently must run before VirtRegRewriter. We should
  437. // make the rewriter a separate pass and override verifyAnalysis instead. When
  438. // that happens, verification naturally falls under VerifyMachineCode.
  439. #ifndef NDEBUG
  440. if (VerifyRegAlloc) {
  441. // Verify accuracy of LiveIntervals. The standard machine code verifier
  442. // ensures that each LiveIntervals covers all uses of the virtual reg.
  443. // FIXME: MachineVerifier is currently broken when using the standard
  444. // spiller. Enable it for InlineSpiller only.
  445. // mf_->verify(this);
  446. // Verify that LiveIntervals are partitioned into unions and disjoint within
  447. // the unions.
  448. verify();
  449. }
  450. #endif // !NDEBUG
  451. // Run rewriter
  452. std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
  453. rewriter->runOnMachineFunction(*mf_, *vrm_, lis_);
  454. // The pass output is in VirtRegMap. Release all the transient data.
  455. releaseMemory();
  456. return true;
  457. }
  458. FunctionPass* llvm::createBasicRegisterAllocator()
  459. {
  460. return new RABasic();
  461. }