RegAllocGreedy.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. //===-- RegAllocGreedy.cpp - greedy 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 RAGreedy function pass for register allocation in
  11. // optimized builds.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "regalloc"
  15. #include "AllocationOrder.h"
  16. #include "LiveIntervalUnion.h"
  17. #include "RegAllocBase.h"
  18. #include "Spiller.h"
  19. #include "VirtRegMap.h"
  20. #include "VirtRegRewriter.h"
  21. #include "llvm/Analysis/AliasAnalysis.h"
  22. #include "llvm/Function.h"
  23. #include "llvm/PassAnalysisSupport.h"
  24. #include "llvm/CodeGen/CalcSpillWeights.h"
  25. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  26. #include "llvm/CodeGen/LiveStackAnalysis.h"
  27. #include "llvm/CodeGen/MachineFunctionPass.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/TargetOptions.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. using namespace llvm;
  38. static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
  39. createGreedyRegisterAllocator);
  40. namespace {
  41. class RAGreedy : public MachineFunctionPass, public RegAllocBase {
  42. // context
  43. MachineFunction *MF;
  44. const TargetMachine *TM;
  45. MachineRegisterInfo *MRI;
  46. BitVector ReservedRegs;
  47. // analyses
  48. LiveStacks *LS;
  49. // state
  50. std::auto_ptr<Spiller> SpillerInstance;
  51. public:
  52. RAGreedy();
  53. /// Return the pass name.
  54. virtual const char* getPassName() const {
  55. return "Basic Register Allocator";
  56. }
  57. /// RAGreedy analysis usage.
  58. virtual void getAnalysisUsage(AnalysisUsage &AU) const;
  59. virtual void releaseMemory();
  60. virtual Spiller &spiller() { return *SpillerInstance; }
  61. virtual float getPriority(LiveInterval *LI);
  62. virtual unsigned selectOrSplit(LiveInterval &VirtReg,
  63. SmallVectorImpl<LiveInterval*> &SplitVRegs);
  64. /// Perform register allocation.
  65. virtual bool runOnMachineFunction(MachineFunction &mf);
  66. static char ID;
  67. private:
  68. bool checkUncachedInterference(LiveInterval &, unsigned);
  69. bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
  70. bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
  71. };
  72. } // end anonymous namespace
  73. char RAGreedy::ID = 0;
  74. FunctionPass* llvm::createGreedyRegisterAllocator() {
  75. return new RAGreedy();
  76. }
  77. RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
  78. initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
  79. initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
  80. initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
  81. initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
  82. initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
  83. initializeLiveStacksPass(*PassRegistry::getPassRegistry());
  84. initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
  85. initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
  86. initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
  87. }
  88. void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
  89. AU.setPreservesCFG();
  90. AU.addRequired<AliasAnalysis>();
  91. AU.addPreserved<AliasAnalysis>();
  92. AU.addRequired<LiveIntervals>();
  93. AU.addPreserved<SlotIndexes>();
  94. if (StrongPHIElim)
  95. AU.addRequiredID(StrongPHIEliminationID);
  96. AU.addRequiredTransitive<RegisterCoalescer>();
  97. AU.addRequired<CalculateSpillWeights>();
  98. AU.addRequired<LiveStacks>();
  99. AU.addPreserved<LiveStacks>();
  100. AU.addRequiredID(MachineDominatorsID);
  101. AU.addPreservedID(MachineDominatorsID);
  102. AU.addRequired<MachineLoopInfo>();
  103. AU.addPreserved<MachineLoopInfo>();
  104. AU.addRequired<VirtRegMap>();
  105. AU.addPreserved<VirtRegMap>();
  106. MachineFunctionPass::getAnalysisUsage(AU);
  107. }
  108. void RAGreedy::releaseMemory() {
  109. SpillerInstance.reset(0);
  110. RegAllocBase::releaseMemory();
  111. }
  112. float RAGreedy::getPriority(LiveInterval *LI) {
  113. float Priority = LI->weight;
  114. // Prioritize hinted registers so they are allocated first.
  115. std::pair<unsigned, unsigned> Hint;
  116. if (Hint.first || Hint.second) {
  117. // The hint can be target specific, a virtual register, or a physreg.
  118. Priority *= 2;
  119. // Prefer physreg hints above anything else.
  120. if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
  121. Priority *= 2;
  122. }
  123. return Priority;
  124. }
  125. // Check interference without using the cache.
  126. bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
  127. unsigned PhysReg) {
  128. LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[PhysReg]);
  129. if (subQ.checkInterference())
  130. return true;
  131. for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
  132. subQ.init(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
  133. if (subQ.checkInterference())
  134. return true;
  135. }
  136. return false;
  137. }
  138. // Attempt to reassign this virtual register to a different physical register.
  139. //
  140. // FIXME: we are not yet caching these "second-level" interferences discovered
  141. // in the sub-queries. These interferences can change with each call to
  142. // selectOrSplit. However, we could implement a "may-interfere" cache that
  143. // could be conservatively dirtied when we reassign or split.
  144. //
  145. // FIXME: This may result in a lot of alias queries. We could summarize alias
  146. // live intervals in their parent register's live union, but it's messy.
  147. bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
  148. unsigned OldPhysReg) {
  149. assert(OldPhysReg == VRM->getPhys(InterferingVReg.reg) &&
  150. "inconsistent phys reg assigment");
  151. AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
  152. while (unsigned PhysReg = Order.next()) {
  153. if (PhysReg == OldPhysReg)
  154. continue;
  155. if (checkUncachedInterference(InterferingVReg, PhysReg))
  156. continue;
  157. DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
  158. TRI->getName(OldPhysReg) << " to " << TRI->getName(PhysReg) << '\n');
  159. // Reassign the interfering virtual reg to this physical reg.
  160. PhysReg2LiveUnion[OldPhysReg].extract(InterferingVReg);
  161. VRM->clearVirt(InterferingVReg.reg);
  162. VRM->assignVirt2Phys(InterferingVReg.reg, PhysReg);
  163. PhysReg2LiveUnion[PhysReg].unify(InterferingVReg);
  164. return true;
  165. }
  166. return false;
  167. }
  168. // Collect all virtual regs currently assigned to PhysReg that interfere with
  169. // VirtReg.
  170. //
  171. // Currently, for simplicity, we only attempt to reassign a single interference
  172. // within the same register class.
  173. bool RAGreedy::reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg) {
  174. LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
  175. // Limit the interference search to one interference.
  176. Q.collectInterferingVRegs(1);
  177. assert(Q.interferingVRegs().size() == 1 &&
  178. "expected at least one interference");
  179. // Do not attempt reassignment unless we find only a single interference.
  180. if (!Q.seenAllInterferences())
  181. return false;
  182. // Don't allow any interferences on aliases.
  183. for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
  184. if (query(VirtReg, *AliasI).checkInterference())
  185. return false;
  186. }
  187. return reassignVReg(*Q.interferingVRegs()[0], PhysReg);
  188. }
  189. unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
  190. SmallVectorImpl<LiveInterval*> &SplitVRegs) {
  191. // Populate a list of physical register spill candidates.
  192. SmallVector<unsigned, 8> PhysRegSpillCands, ReassignCands;
  193. // Check for an available register in this class.
  194. const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
  195. DEBUG(dbgs() << "RegClass: " << TRC->getName() << ' ');
  196. AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
  197. while (unsigned PhysReg = Order.next()) {
  198. // Check interference and as a side effect, intialize queries for this
  199. // VirtReg and its aliases.
  200. unsigned InterfReg = checkPhysRegInterference(VirtReg, PhysReg);
  201. if (InterfReg == 0) {
  202. // Found an available register.
  203. return PhysReg;
  204. }
  205. assert(!VirtReg.empty() && "Empty VirtReg has interference");
  206. LiveInterval *InterferingVirtReg =
  207. Queries[InterfReg].firstInterference().liveUnionPos().value();
  208. // The current VirtReg must either be spillable, or one of its interferences
  209. // must have less spill weight.
  210. if (InterferingVirtReg->weight < VirtReg.weight ) {
  211. // For simplicity, only consider reassigning registers in the same class.
  212. if (InterfReg == PhysReg)
  213. ReassignCands.push_back(PhysReg);
  214. else
  215. PhysRegSpillCands.push_back(PhysReg);
  216. }
  217. }
  218. // Try to reassign interfering physical register. Priority among
  219. // PhysRegSpillCands does not matter yet, because the reassigned virtual
  220. // registers will still be assigned to physical registers.
  221. for (SmallVectorImpl<unsigned>::iterator PhysRegI = ReassignCands.begin(),
  222. PhysRegE = ReassignCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
  223. if (reassignInterferences(VirtReg, *PhysRegI))
  224. // Reassignment successfull. The caller may allocate now to this PhysReg.
  225. return *PhysRegI;
  226. }
  227. PhysRegSpillCands.insert(PhysRegSpillCands.end(), ReassignCands.begin(),
  228. ReassignCands.end());
  229. // Try to spill another interfering reg with less spill weight.
  230. //
  231. // FIXME: do this in two steps: (1) check for unspillable interferences while
  232. // accumulating spill weight; (2) spill the interferences with lowest
  233. // aggregate spill weight.
  234. for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
  235. PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
  236. if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
  237. assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
  238. "Interference after spill.");
  239. // Tell the caller to allocate to this newly freed physical register.
  240. return *PhysRegI;
  241. }
  242. // No other spill candidates were found, so spill the current VirtReg.
  243. DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
  244. SmallVector<LiveInterval*, 1> pendingSpills;
  245. spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
  246. // The live virtual register requesting allocation was spilled, so tell
  247. // the caller not to allocate anything during this round.
  248. return 0;
  249. }
  250. bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
  251. DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
  252. << "********** Function: "
  253. << ((Value*)mf.getFunction())->getName() << '\n');
  254. MF = &mf;
  255. TM = &mf.getTarget();
  256. MRI = &mf.getRegInfo();
  257. const TargetRegisterInfo *TRI = TM->getRegisterInfo();
  258. RegAllocBase::init(*TRI, getAnalysis<VirtRegMap>(),
  259. getAnalysis<LiveIntervals>());
  260. ReservedRegs = TRI->getReservedRegs(*MF);
  261. SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
  262. allocatePhysRegs();
  263. addMBBLiveIns(MF);
  264. // Run rewriter
  265. std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
  266. rewriter->runOnMachineFunction(*MF, *VRM, LIS);
  267. // The pass output is in VirtRegMap. Release all the transient data.
  268. releaseMemory();
  269. return true;
  270. }