RegAllocLocal.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. //===-- RegAllocLocal.cpp - A BasicBlock generic 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 register allocator allocates registers to a basic block at a time,
  11. // attempting to keep values in registers and reusing registers as appropriate.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "regalloc"
  15. #include "llvm/BasicBlock.h"
  16. #include "llvm/CodeGen/MachineFunctionPass.h"
  17. #include "llvm/CodeGen/MachineInstr.h"
  18. #include "llvm/CodeGen/MachineFrameInfo.h"
  19. #include "llvm/CodeGen/MachineRegisterInfo.h"
  20. #include "llvm/CodeGen/Passes.h"
  21. #include "llvm/CodeGen/RegAllocRegistry.h"
  22. #include "llvm/Target/TargetInstrInfo.h"
  23. #include "llvm/Target/TargetMachine.h"
  24. #include "llvm/Support/CommandLine.h"
  25. #include "llvm/Support/Debug.h"
  26. #include "llvm/Support/Compiler.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/IndexedMap.h"
  29. #include "llvm/ADT/SmallVector.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include "llvm/ADT/STLExtras.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. STATISTIC(NumStores, "Number of stores added");
  35. STATISTIC(NumLoads , "Number of loads added");
  36. static RegisterRegAlloc
  37. localRegAlloc("local", " local register allocator",
  38. createLocalRegisterAllocator);
  39. namespace {
  40. class VISIBILITY_HIDDEN RALocal : public MachineFunctionPass {
  41. public:
  42. static char ID;
  43. RALocal() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1) {}
  44. private:
  45. const TargetMachine *TM;
  46. MachineFunction *MF;
  47. const TargetRegisterInfo *TRI;
  48. const TargetInstrInfo *TII;
  49. // StackSlotForVirtReg - Maps virtual regs to the frame index where these
  50. // values are spilled.
  51. IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
  52. // Virt2PhysRegMap - This map contains entries for each virtual register
  53. // that is currently available in a physical register.
  54. IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
  55. unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
  56. return Virt2PhysRegMap[VirtReg];
  57. }
  58. // PhysRegsUsed - This array is effectively a map, containing entries for
  59. // each physical register that currently has a value (ie, it is in
  60. // Virt2PhysRegMap). The value mapped to is the virtual register
  61. // corresponding to the physical register (the inverse of the
  62. // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
  63. // because it is used by a future instruction, and to -2 if it is not
  64. // allocatable. If the entry for a physical register is -1, then the
  65. // physical register is "not in the map".
  66. //
  67. std::vector<int> PhysRegsUsed;
  68. // PhysRegsUseOrder - This contains a list of the physical registers that
  69. // currently have a virtual register value in them. This list provides an
  70. // ordering of registers, imposing a reallocation order. This list is only
  71. // used if all registers are allocated and we have to spill one, in which
  72. // case we spill the least recently used register. Entries at the front of
  73. // the list are the least recently used registers, entries at the back are
  74. // the most recently used.
  75. //
  76. std::vector<unsigned> PhysRegsUseOrder;
  77. // Virt2LastUseMap - This maps each virtual register to its last use
  78. // (MachineInstr*, operand index pair).
  79. IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
  80. Virt2LastUseMap;
  81. std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
  82. assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
  83. return Virt2LastUseMap[Reg];
  84. }
  85. // VirtRegModified - This bitset contains information about which virtual
  86. // registers need to be spilled back to memory when their registers are
  87. // scavenged. If a virtual register has simply been rematerialized, there
  88. // is no reason to spill it to memory when we need the register back.
  89. //
  90. BitVector VirtRegModified;
  91. // UsedInMultipleBlocks - Tracks whether a particular register is used in
  92. // more than one block.
  93. BitVector UsedInMultipleBlocks;
  94. void markVirtRegModified(unsigned Reg, bool Val = true) {
  95. assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
  96. Reg -= TargetRegisterInfo::FirstVirtualRegister;
  97. if (Val)
  98. VirtRegModified.set(Reg);
  99. else
  100. VirtRegModified.reset(Reg);
  101. }
  102. bool isVirtRegModified(unsigned Reg) const {
  103. assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
  104. assert(Reg - TargetRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
  105. && "Illegal virtual register!");
  106. return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
  107. }
  108. void AddToPhysRegsUseOrder(unsigned Reg) {
  109. std::vector<unsigned>::iterator It =
  110. std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
  111. if (It != PhysRegsUseOrder.end())
  112. PhysRegsUseOrder.erase(It);
  113. PhysRegsUseOrder.push_back(Reg);
  114. }
  115. void MarkPhysRegRecentlyUsed(unsigned Reg) {
  116. if (PhysRegsUseOrder.empty() ||
  117. PhysRegsUseOrder.back() == Reg) return; // Already most recently used
  118. for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
  119. if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
  120. unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
  121. PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
  122. // Add it to the end of the list
  123. PhysRegsUseOrder.push_back(RegMatch);
  124. if (RegMatch == Reg)
  125. return; // Found an exact match, exit early
  126. }
  127. }
  128. public:
  129. virtual const char *getPassName() const {
  130. return "Local Register Allocator";
  131. }
  132. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  133. AU.addRequiredID(PHIEliminationID);
  134. AU.addRequiredID(TwoAddressInstructionPassID);
  135. MachineFunctionPass::getAnalysisUsage(AU);
  136. }
  137. private:
  138. /// runOnMachineFunction - Register allocate the whole function
  139. bool runOnMachineFunction(MachineFunction &Fn);
  140. /// AllocateBasicBlock - Register allocate the specified basic block.
  141. void AllocateBasicBlock(MachineBasicBlock &MBB);
  142. /// areRegsEqual - This method returns true if the specified registers are
  143. /// related to each other. To do this, it checks to see if they are equal
  144. /// or if the first register is in the alias set of the second register.
  145. ///
  146. bool areRegsEqual(unsigned R1, unsigned R2) const {
  147. if (R1 == R2) return true;
  148. for (const unsigned *AliasSet = TRI->getAliasSet(R2);
  149. *AliasSet; ++AliasSet) {
  150. if (*AliasSet == R1) return true;
  151. }
  152. return false;
  153. }
  154. /// getStackSpaceFor - This returns the frame index of the specified virtual
  155. /// register on the stack, allocating space if necessary.
  156. int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
  157. /// removePhysReg - This method marks the specified physical register as no
  158. /// longer being in use.
  159. ///
  160. void removePhysReg(unsigned PhysReg);
  161. /// spillVirtReg - This method spills the value specified by PhysReg into
  162. /// the virtual register slot specified by VirtReg. It then updates the RA
  163. /// data structures to indicate the fact that PhysReg is now available.
  164. ///
  165. void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  166. unsigned VirtReg, unsigned PhysReg);
  167. /// spillPhysReg - This method spills the specified physical register into
  168. /// the virtual register slot associated with it. If OnlyVirtRegs is set to
  169. /// true, then the request is ignored if the physical register does not
  170. /// contain a virtual register.
  171. ///
  172. void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
  173. unsigned PhysReg, bool OnlyVirtRegs = false);
  174. /// assignVirtToPhysReg - This method updates local state so that we know
  175. /// that PhysReg is the proper container for VirtReg now. The physical
  176. /// register must not be used for anything else when this is called.
  177. ///
  178. void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
  179. /// isPhysRegAvailable - Return true if the specified physical register is
  180. /// free and available for use. This also includes checking to see if
  181. /// aliased registers are all free...
  182. ///
  183. bool isPhysRegAvailable(unsigned PhysReg) const;
  184. /// getFreeReg - Look to see if there is a free register available in the
  185. /// specified register class. If not, return 0.
  186. ///
  187. unsigned getFreeReg(const TargetRegisterClass *RC);
  188. /// getReg - Find a physical register to hold the specified virtual
  189. /// register. If all compatible physical registers are used, this method
  190. /// spills the last used virtual register to the stack, and uses that
  191. /// register.
  192. ///
  193. unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
  194. unsigned VirtReg);
  195. /// reloadVirtReg - This method transforms the specified specified virtual
  196. /// register use to refer to a physical register. This method may do this
  197. /// in one of several ways: if the register is available in a physical
  198. /// register already, it uses that physical register. If the value is not
  199. /// in a physical register, and if there are physical registers available,
  200. /// it loads it into a register. If register pressure is high, and it is
  201. /// possible, it tries to fold the load of the virtual register into the
  202. /// instruction itself. It avoids doing this if register pressure is low to
  203. /// improve the chance that subsequent instructions can use the reloaded
  204. /// value. This method returns the modified instruction.
  205. ///
  206. MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
  207. unsigned OpNum);
  208. /// ComputeLocalLiveness - Computes liveness of registers within a basic
  209. /// block, setting the killed/dead flags as appropriate.
  210. void ComputeLocalLiveness(MachineBasicBlock& MBB);
  211. void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
  212. unsigned PhysReg);
  213. };
  214. char RALocal::ID = 0;
  215. }
  216. /// getStackSpaceFor - This allocates space for the specified virtual register
  217. /// to be held on the stack.
  218. int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
  219. // Find the location Reg would belong...
  220. int SS = StackSlotForVirtReg[VirtReg];
  221. if (SS != -1)
  222. return SS; // Already has space allocated?
  223. // Allocate a new stack object for this spill location...
  224. int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
  225. RC->getAlignment());
  226. // Assign the slot...
  227. StackSlotForVirtReg[VirtReg] = FrameIdx;
  228. return FrameIdx;
  229. }
  230. /// removePhysReg - This method marks the specified physical register as no
  231. /// longer being in use.
  232. ///
  233. void RALocal::removePhysReg(unsigned PhysReg) {
  234. PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
  235. std::vector<unsigned>::iterator It =
  236. std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
  237. if (It != PhysRegsUseOrder.end())
  238. PhysRegsUseOrder.erase(It);
  239. }
  240. /// spillVirtReg - This method spills the value specified by PhysReg into the
  241. /// virtual register slot specified by VirtReg. It then updates the RA data
  242. /// structures to indicate the fact that PhysReg is now available.
  243. ///
  244. void RALocal::spillVirtReg(MachineBasicBlock &MBB,
  245. MachineBasicBlock::iterator I,
  246. unsigned VirtReg, unsigned PhysReg) {
  247. assert(VirtReg && "Spilling a physical register is illegal!"
  248. " Must not have appropriate kill for the register or use exists beyond"
  249. " the intended one.");
  250. DOUT << " Spilling register " << TRI->getName(PhysReg)
  251. << " containing %reg" << VirtReg;
  252. if (!isVirtRegModified(VirtReg)) {
  253. DOUT << " which has not been modified, so no store necessary!";
  254. std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
  255. if (LastUse.first)
  256. LastUse.first->getOperand(LastUse.second).setIsKill();
  257. } else {
  258. // Otherwise, there is a virtual register corresponding to this physical
  259. // register. We only need to spill it into its stack slot if it has been
  260. // modified.
  261. const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
  262. int FrameIndex = getStackSpaceFor(VirtReg, RC);
  263. DOUT << " to stack slot #" << FrameIndex;
  264. // If the instruction reads the register that's spilled, (e.g. this can
  265. // happen if it is a move to a physical register), then the spill
  266. // instruction is not a kill.
  267. bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
  268. TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC);
  269. ++NumStores; // Update statistics
  270. }
  271. getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
  272. DOUT << "\n";
  273. removePhysReg(PhysReg);
  274. }
  275. /// spillPhysReg - This method spills the specified physical register into the
  276. /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
  277. /// then the request is ignored if the physical register does not contain a
  278. /// virtual register.
  279. ///
  280. void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
  281. unsigned PhysReg, bool OnlyVirtRegs) {
  282. if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
  283. assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
  284. if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
  285. spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
  286. } else {
  287. // If the selected register aliases any other registers, we must make
  288. // sure that one of the aliases isn't alive.
  289. for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
  290. *AliasSet; ++AliasSet)
  291. if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
  292. PhysRegsUsed[*AliasSet] != -2) // If allocatable.
  293. if (PhysRegsUsed[*AliasSet])
  294. spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
  295. }
  296. }
  297. /// assignVirtToPhysReg - This method updates local state so that we know
  298. /// that PhysReg is the proper container for VirtReg now. The physical
  299. /// register must not be used for anything else when this is called.
  300. ///
  301. void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
  302. assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
  303. // Update information to note the fact that this register was just used, and
  304. // it holds VirtReg.
  305. PhysRegsUsed[PhysReg] = VirtReg;
  306. getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
  307. AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
  308. }
  309. /// isPhysRegAvailable - Return true if the specified physical register is free
  310. /// and available for use. This also includes checking to see if aliased
  311. /// registers are all free...
  312. ///
  313. bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
  314. if (PhysRegsUsed[PhysReg] != -1) return false;
  315. // If the selected register aliases any other allocated registers, it is
  316. // not free!
  317. for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
  318. *AliasSet; ++AliasSet)
  319. if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
  320. return false; // Can't use this reg then.
  321. return true;
  322. }
  323. /// getFreeReg - Look to see if there is a free register available in the
  324. /// specified register class. If not, return 0.
  325. ///
  326. unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
  327. // Get iterators defining the range of registers that are valid to allocate in
  328. // this class, which also specifies the preferred allocation order.
  329. TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
  330. TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
  331. for (; RI != RE; ++RI)
  332. if (isPhysRegAvailable(*RI)) { // Is reg unused?
  333. assert(*RI != 0 && "Cannot use register!");
  334. return *RI; // Found an unused register!
  335. }
  336. return 0;
  337. }
  338. /// getReg - Find a physical register to hold the specified virtual
  339. /// register. If all compatible physical registers are used, this method spills
  340. /// the last used virtual register to the stack, and uses that register.
  341. ///
  342. unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
  343. unsigned VirtReg) {
  344. const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
  345. // First check to see if we have a free register of the requested type...
  346. unsigned PhysReg = getFreeReg(RC);
  347. // If we didn't find an unused register, scavenge one now!
  348. if (PhysReg == 0) {
  349. assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
  350. // Loop over all of the preallocated registers from the least recently used
  351. // to the most recently used. When we find one that is capable of holding
  352. // our register, use it.
  353. for (unsigned i = 0; PhysReg == 0; ++i) {
  354. assert(i != PhysRegsUseOrder.size() &&
  355. "Couldn't find a register of the appropriate class!");
  356. unsigned R = PhysRegsUseOrder[i];
  357. // We can only use this register if it holds a virtual register (ie, it
  358. // can be spilled). Do not use it if it is an explicitly allocated
  359. // physical register!
  360. assert(PhysRegsUsed[R] != -1 &&
  361. "PhysReg in PhysRegsUseOrder, but is not allocated?");
  362. if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
  363. // If the current register is compatible, use it.
  364. if (RC->contains(R)) {
  365. PhysReg = R;
  366. break;
  367. } else {
  368. // If one of the registers aliased to the current register is
  369. // compatible, use it.
  370. for (const unsigned *AliasIt = TRI->getAliasSet(R);
  371. *AliasIt; ++AliasIt) {
  372. if (RC->contains(*AliasIt) &&
  373. // If this is pinned down for some reason, don't use it. For
  374. // example, if CL is pinned, and we run across CH, don't use
  375. // CH as justification for using scavenging ECX (which will
  376. // fail).
  377. PhysRegsUsed[*AliasIt] != 0 &&
  378. // Make sure the register is allocatable. Don't allocate SIL on
  379. // x86-32.
  380. PhysRegsUsed[*AliasIt] != -2) {
  381. PhysReg = *AliasIt; // Take an aliased register
  382. break;
  383. }
  384. }
  385. }
  386. }
  387. }
  388. assert(PhysReg && "Physical register not assigned!?!?");
  389. // At this point PhysRegsUseOrder[i] is the least recently used register of
  390. // compatible register class. Spill it to memory and reap its remains.
  391. spillPhysReg(MBB, I, PhysReg);
  392. }
  393. // Now that we know which register we need to assign this to, do it now!
  394. assignVirtToPhysReg(VirtReg, PhysReg);
  395. return PhysReg;
  396. }
  397. /// reloadVirtReg - This method transforms the specified specified virtual
  398. /// register use to refer to a physical register. This method may do this in
  399. /// one of several ways: if the register is available in a physical register
  400. /// already, it uses that physical register. If the value is not in a physical
  401. /// register, and if there are physical registers available, it loads it into a
  402. /// register. If register pressure is high, and it is possible, it tries to
  403. /// fold the load of the virtual register into the instruction itself. It
  404. /// avoids doing this if register pressure is low to improve the chance that
  405. /// subsequent instructions can use the reloaded value. This method returns the
  406. /// modified instruction.
  407. ///
  408. MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
  409. unsigned OpNum) {
  410. unsigned VirtReg = MI->getOperand(OpNum).getReg();
  411. // If the virtual register is already available, just update the instruction
  412. // and return.
  413. if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
  414. MarkPhysRegRecentlyUsed(PR); // Already have this value available!
  415. MI->getOperand(OpNum).setReg(PR); // Assign the input register
  416. getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
  417. return MI;
  418. }
  419. // Otherwise, we need to fold it into the current instruction, or reload it.
  420. // If we have registers available to hold the value, use them.
  421. const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
  422. unsigned PhysReg = getFreeReg(RC);
  423. int FrameIndex = getStackSpaceFor(VirtReg, RC);
  424. if (PhysReg) { // Register is available, allocate it!
  425. assignVirtToPhysReg(VirtReg, PhysReg);
  426. } else { // No registers available.
  427. // Force some poor hapless value out of the register file to
  428. // make room for the new register, and reload it.
  429. PhysReg = getReg(MBB, MI, VirtReg);
  430. }
  431. markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
  432. DOUT << " Reloading %reg" << VirtReg << " into "
  433. << TRI->getName(PhysReg) << "\n";
  434. // Add move instruction(s)
  435. TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
  436. ++NumLoads; // Update statistics
  437. MF->getRegInfo().setPhysRegUsed(PhysReg);
  438. MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
  439. getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
  440. return MI;
  441. }
  442. /// isReadModWriteImplicitKill - True if this is an implicit kill for a
  443. /// read/mod/write register, i.e. update partial register.
  444. static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
  445. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  446. MachineOperand& MO = MI->getOperand(i);
  447. if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
  448. MO.isDef() && !MO.isDead())
  449. return true;
  450. }
  451. return false;
  452. }
  453. /// isReadModWriteImplicitDef - True if this is an implicit def for a
  454. /// read/mod/write register, i.e. update partial register.
  455. static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
  456. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  457. MachineOperand& MO = MI->getOperand(i);
  458. if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
  459. !MO.isDef() && MO.isKill())
  460. return true;
  461. }
  462. return false;
  463. }
  464. // precedes - Helper function to determine with MachineInstr A
  465. // precedes MachineInstr B within the same MBB.
  466. static bool precedes(MachineBasicBlock::iterator A,
  467. MachineBasicBlock::iterator B) {
  468. if (A == B)
  469. return false;
  470. MachineBasicBlock::iterator I = A->getParent()->begin();
  471. while (I != A->getParent()->end()) {
  472. if (I == A)
  473. return true;
  474. else if (I == B)
  475. return false;
  476. ++I;
  477. }
  478. return false;
  479. }
  480. /// ComputeLocalLiveness - Computes liveness of registers within a basic
  481. /// block, setting the killed/dead flags as appropriate.
  482. void RALocal::ComputeLocalLiveness(MachineBasicBlock& MBB) {
  483. MachineRegisterInfo& MRI = MBB.getParent()->getRegInfo();
  484. // Keep track of the most recently seen previous use or def of each reg,
  485. // so that we can update them with dead/kill markers.
  486. DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > LastUseDef;
  487. for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
  488. I != E; ++I) {
  489. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  490. MachineOperand& MO = I->getOperand(i);
  491. // Uses don't trigger any flags, but we need to save
  492. // them for later. Also, we have to process these
  493. // _before_ processing the defs, since an instr
  494. // uses regs before it defs them.
  495. if (MO.isReg() && MO.getReg() && MO.isUse())
  496. LastUseDef[MO.getReg()] = std::make_pair(I, i);
  497. }
  498. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  499. MachineOperand& MO = I->getOperand(i);
  500. // Defs others than 2-addr redefs _do_ trigger flag changes:
  501. // - A def followed by a def is dead
  502. // - A use followed by a def is a kill
  503. if (MO.isReg() && MO.getReg() && MO.isDef()) {
  504. DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
  505. last = LastUseDef.find(MO.getReg());
  506. if (last != LastUseDef.end()) {
  507. // Check if this is a two address instruction. If so, then
  508. // the def does not kill the use.
  509. if (last->second.first == I &&
  510. I->isRegReDefinedByTwoAddr(MO.getReg(), i))
  511. continue;
  512. MachineOperand& lastUD =
  513. last->second.first->getOperand(last->second.second);
  514. if (lastUD.isDef())
  515. lastUD.setIsDead(true);
  516. else
  517. lastUD.setIsKill(true);
  518. }
  519. LastUseDef[MO.getReg()] = std::make_pair(I, i);
  520. }
  521. }
  522. }
  523. // Live-out (of the function) registers contain return values of the function,
  524. // so we need to make sure they are alive at return time.
  525. if (!MBB.empty() && MBB.back().getDesc().isReturn()) {
  526. MachineInstr* Ret = &MBB.back();
  527. for (MachineRegisterInfo::liveout_iterator
  528. I = MF->getRegInfo().liveout_begin(),
  529. E = MF->getRegInfo().liveout_end(); I != E; ++I)
  530. if (!Ret->readsRegister(*I)) {
  531. Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
  532. LastUseDef[*I] = std::make_pair(Ret, Ret->getNumOperands()-1);
  533. }
  534. }
  535. // Finally, loop over the final use/def of each reg
  536. // in the block and determine if it is dead.
  537. for (DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
  538. I = LastUseDef.begin(), E = LastUseDef.end(); I != E; ++I) {
  539. MachineInstr* MI = I->second.first;
  540. unsigned idx = I->second.second;
  541. MachineOperand& MO = MI->getOperand(idx);
  542. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(MO.getReg());
  543. // A crude approximation of "live-out" calculation
  544. bool usedOutsideBlock = isPhysReg ? false :
  545. UsedInMultipleBlocks.test(MO.getReg() -
  546. TargetRegisterInfo::FirstVirtualRegister);
  547. if (!isPhysReg && !usedOutsideBlock)
  548. for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
  549. UE = MRI.reg_end(); UI != UE; ++UI)
  550. // Two cases:
  551. // - used in another block
  552. // - used in the same block before it is defined (loop)
  553. if (UI->getParent() != &MBB ||
  554. (MO.isDef() && UI.getOperand().isUse() && precedes(&*UI, MI))) {
  555. UsedInMultipleBlocks.set(MO.getReg() -
  556. TargetRegisterInfo::FirstVirtualRegister);
  557. usedOutsideBlock = true;
  558. break;
  559. }
  560. // Physical registers and those that are not live-out of the block
  561. // are killed/dead at their last use/def within this block.
  562. if (isPhysReg || !usedOutsideBlock) {
  563. if (MO.isUse())
  564. MO.setIsKill(true);
  565. else
  566. MO.setIsDead(true);
  567. }
  568. }
  569. }
  570. void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
  571. // loop over each instruction
  572. MachineBasicBlock::iterator MII = MBB.begin();
  573. DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
  574. if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
  575. // If this is the first basic block in the machine function, add live-in
  576. // registers as active.
  577. if (&MBB == &*MF->begin() || MBB.isLandingPad()) {
  578. for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
  579. E = MBB.livein_end(); I != E; ++I) {
  580. unsigned Reg = *I;
  581. MF->getRegInfo().setPhysRegUsed(Reg);
  582. PhysRegsUsed[Reg] = 0; // It is free and reserved now
  583. AddToPhysRegsUseOrder(Reg);
  584. for (const unsigned *AliasSet = TRI->getSubRegisters(Reg);
  585. *AliasSet; ++AliasSet) {
  586. if (PhysRegsUsed[*AliasSet] != -2) {
  587. AddToPhysRegsUseOrder(*AliasSet);
  588. PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
  589. MF->getRegInfo().setPhysRegUsed(*AliasSet);
  590. }
  591. }
  592. }
  593. }
  594. ComputeLocalLiveness(MBB);
  595. // Otherwise, sequentially allocate each instruction in the MBB.
  596. while (MII != MBB.end()) {
  597. MachineInstr *MI = MII++;
  598. const TargetInstrDesc &TID = MI->getDesc();
  599. DEBUG(DOUT << "\nStarting RegAlloc of: " << *MI;
  600. DOUT << " Regs have values: ";
  601. for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
  602. if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
  603. DOUT << "[" << TRI->getName(i)
  604. << ",%reg" << PhysRegsUsed[i] << "] ";
  605. DOUT << "\n");
  606. // Loop over the implicit uses, making sure that they are at the head of the
  607. // use order list, so they don't get reallocated.
  608. if (TID.ImplicitUses) {
  609. for (const unsigned *ImplicitUses = TID.ImplicitUses;
  610. *ImplicitUses; ++ImplicitUses)
  611. MarkPhysRegRecentlyUsed(*ImplicitUses);
  612. }
  613. SmallVector<unsigned, 8> Kills;
  614. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  615. MachineOperand& MO = MI->getOperand(i);
  616. if (MO.isRegister() && MO.isKill()) {
  617. if (!MO.isImplicit())
  618. Kills.push_back(MO.getReg());
  619. else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
  620. // These are extra physical register kills when a sub-register
  621. // is defined (def of a sub-register is a read/mod/write of the
  622. // larger registers). Ignore.
  623. Kills.push_back(MO.getReg());
  624. }
  625. }
  626. // Get the used operands into registers. This has the potential to spill
  627. // incoming values if we are out of registers. Note that we completely
  628. // ignore physical register uses here. We assume that if an explicit
  629. // physical register is referenced by the instruction, that it is guaranteed
  630. // to be live-in, or the input is badly hosed.
  631. //
  632. for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
  633. MachineOperand& MO = MI->getOperand(i);
  634. // here we are looking for only used operands (never def&use)
  635. if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
  636. TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  637. MI = reloadVirtReg(MBB, MI, i);
  638. }
  639. // If this instruction is the last user of this register, kill the
  640. // value, freeing the register being used, so it doesn't need to be
  641. // spilled to memory.
  642. //
  643. for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
  644. unsigned VirtReg = Kills[i];
  645. unsigned PhysReg = VirtReg;
  646. if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
  647. // If the virtual register was never materialized into a register, it
  648. // might not be in the map, but it won't hurt to zero it out anyway.
  649. unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
  650. PhysReg = PhysRegSlot;
  651. PhysRegSlot = 0;
  652. } else if (PhysRegsUsed[PhysReg] == -2) {
  653. // Unallocatable register dead, ignore.
  654. continue;
  655. } else {
  656. assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
  657. "Silently clearing a virtual register?");
  658. }
  659. if (PhysReg) {
  660. DOUT << " Last use of " << TRI->getName(PhysReg)
  661. << "[%reg" << VirtReg <<"], removing it from live set\n";
  662. removePhysReg(PhysReg);
  663. for (const unsigned *AliasSet = TRI->getSubRegisters(PhysReg);
  664. *AliasSet; ++AliasSet) {
  665. if (PhysRegsUsed[*AliasSet] != -2) {
  666. DOUT << " Last use of "
  667. << TRI->getName(*AliasSet)
  668. << "[%reg" << VirtReg <<"], removing it from live set\n";
  669. removePhysReg(*AliasSet);
  670. }
  671. }
  672. }
  673. }
  674. // Loop over all of the operands of the instruction, spilling registers that
  675. // are defined, and marking explicit destinations in the PhysRegsUsed map.
  676. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  677. MachineOperand& MO = MI->getOperand(i);
  678. if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
  679. TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
  680. unsigned Reg = MO.getReg();
  681. if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
  682. // These are extra physical register defs when a sub-register
  683. // is defined (def of a sub-register is a read/mod/write of the
  684. // larger registers). Ignore.
  685. if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
  686. MF->getRegInfo().setPhysRegUsed(Reg);
  687. spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
  688. PhysRegsUsed[Reg] = 0; // It is free and reserved now
  689. AddToPhysRegsUseOrder(Reg);
  690. for (const unsigned *AliasSet = TRI->getSubRegisters(Reg);
  691. *AliasSet; ++AliasSet) {
  692. if (PhysRegsUsed[*AliasSet] != -2) {
  693. MF->getRegInfo().setPhysRegUsed(*AliasSet);
  694. PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
  695. AddToPhysRegsUseOrder(*AliasSet);
  696. }
  697. }
  698. }
  699. }
  700. // Loop over the implicit defs, spilling them as well.
  701. if (TID.ImplicitDefs) {
  702. for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
  703. *ImplicitDefs; ++ImplicitDefs) {
  704. unsigned Reg = *ImplicitDefs;
  705. if (PhysRegsUsed[Reg] != -2) {
  706. spillPhysReg(MBB, MI, Reg, true);
  707. AddToPhysRegsUseOrder(Reg);
  708. PhysRegsUsed[Reg] = 0; // It is free and reserved now
  709. }
  710. MF->getRegInfo().setPhysRegUsed(Reg);
  711. for (const unsigned *AliasSet = TRI->getSubRegisters(Reg);
  712. *AliasSet; ++AliasSet) {
  713. if (PhysRegsUsed[*AliasSet] != -2) {
  714. AddToPhysRegsUseOrder(*AliasSet);
  715. PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
  716. MF->getRegInfo().setPhysRegUsed(*AliasSet);
  717. }
  718. }
  719. }
  720. }
  721. SmallVector<unsigned, 8> DeadDefs;
  722. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  723. MachineOperand& MO = MI->getOperand(i);
  724. if (MO.isRegister() && MO.isDead())
  725. DeadDefs.push_back(MO.getReg());
  726. }
  727. // Okay, we have allocated all of the source operands and spilled any values
  728. // that would be destroyed by defs of this instruction. Loop over the
  729. // explicit defs and assign them to a register, spilling incoming values if
  730. // we need to scavenge a register.
  731. //
  732. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  733. MachineOperand& MO = MI->getOperand(i);
  734. if (MO.isRegister() && MO.isDef() && MO.getReg() &&
  735. TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
  736. unsigned DestVirtReg = MO.getReg();
  737. unsigned DestPhysReg;
  738. // If DestVirtReg already has a value, use it.
  739. if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
  740. DestPhysReg = getReg(MBB, MI, DestVirtReg);
  741. MF->getRegInfo().setPhysRegUsed(DestPhysReg);
  742. markVirtRegModified(DestVirtReg);
  743. getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
  744. DOUT << " Assigning " << TRI->getName(DestPhysReg)
  745. << " to %reg" << DestVirtReg << "\n";
  746. MO.setReg(DestPhysReg); // Assign the output register
  747. }
  748. }
  749. // If this instruction defines any registers that are immediately dead,
  750. // kill them now.
  751. //
  752. for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
  753. unsigned VirtReg = DeadDefs[i];
  754. unsigned PhysReg = VirtReg;
  755. if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
  756. unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
  757. PhysReg = PhysRegSlot;
  758. assert(PhysReg != 0);
  759. PhysRegSlot = 0;
  760. } else if (PhysRegsUsed[PhysReg] == -2) {
  761. // Unallocatable register dead, ignore.
  762. continue;
  763. }
  764. if (PhysReg) {
  765. DOUT << " Register " << TRI->getName(PhysReg)
  766. << " [%reg" << VirtReg
  767. << "] is never used, removing it frame live list\n";
  768. removePhysReg(PhysReg);
  769. for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
  770. *AliasSet; ++AliasSet) {
  771. if (PhysRegsUsed[*AliasSet] != -2) {
  772. DOUT << " Register " << TRI->getName(*AliasSet)
  773. << " [%reg" << *AliasSet
  774. << "] is never used, removing it frame live list\n";
  775. removePhysReg(*AliasSet);
  776. }
  777. }
  778. }
  779. }
  780. // Finally, if this is a noop copy instruction, zap it.
  781. unsigned SrcReg, DstReg;
  782. if (TII->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg)
  783. MBB.erase(MI);
  784. }
  785. MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
  786. // Spill all physical registers holding virtual registers now.
  787. for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
  788. if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
  789. if (unsigned VirtReg = PhysRegsUsed[i])
  790. spillVirtReg(MBB, MI, VirtReg, i);
  791. else
  792. removePhysReg(i);
  793. }
  794. #if 0
  795. // This checking code is very expensive.
  796. bool AllOk = true;
  797. for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
  798. e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
  799. if (unsigned PR = Virt2PhysRegMap[i]) {
  800. cerr << "Register still mapped: " << i << " -> " << PR << "\n";
  801. AllOk = false;
  802. }
  803. assert(AllOk && "Virtual registers still in phys regs?");
  804. #endif
  805. // Clear any physical register which appear live at the end of the basic
  806. // block, but which do not hold any virtual registers. e.g., the stack
  807. // pointer.
  808. PhysRegsUseOrder.clear();
  809. }
  810. /// runOnMachineFunction - Register allocate the whole function
  811. ///
  812. bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
  813. DOUT << "Machine Function " << "\n";
  814. MF = &Fn;
  815. TM = &Fn.getTarget();
  816. TRI = TM->getRegisterInfo();
  817. TII = TM->getInstrInfo();
  818. PhysRegsUsed.assign(TRI->getNumRegs(), -1);
  819. // At various places we want to efficiently check to see whether a register
  820. // is allocatable. To handle this, we mark all unallocatable registers as
  821. // being pinned down, permanently.
  822. {
  823. BitVector Allocable = TRI->getAllocatableSet(Fn);
  824. for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
  825. if (!Allocable[i])
  826. PhysRegsUsed[i] = -2; // Mark the reg unallocable.
  827. }
  828. // initialize the virtual->physical register map to have a 'null'
  829. // mapping for all virtual registers
  830. unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
  831. StackSlotForVirtReg.grow(LastVirtReg);
  832. Virt2PhysRegMap.grow(LastVirtReg);
  833. Virt2LastUseMap.grow(LastVirtReg);
  834. VirtRegModified.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
  835. UsedInMultipleBlocks.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
  836. // Loop over all of the basic blocks, eliminating virtual register references
  837. for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
  838. MBB != MBBe; ++MBB)
  839. AllocateBasicBlock(*MBB);
  840. StackSlotForVirtReg.clear();
  841. PhysRegsUsed.clear();
  842. VirtRegModified.clear();
  843. UsedInMultipleBlocks.clear();
  844. Virt2PhysRegMap.clear();
  845. Virt2LastUseMap.clear();
  846. return true;
  847. }
  848. FunctionPass *llvm::createLocalRegisterAllocator() {
  849. return new RALocal();
  850. }