RegAllocFast.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  1. //===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. /// \file This register allocator allocates registers to a basic block at a
  10. /// time, attempting to keep values in registers and reusing registers as
  11. /// appropriate.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/IndexedMap.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/SparseSet.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/CodeGen/MachineBasicBlock.h"
  22. #include "llvm/CodeGen/MachineFrameInfo.h"
  23. #include "llvm/CodeGen/MachineFunction.h"
  24. #include "llvm/CodeGen/MachineFunctionPass.h"
  25. #include "llvm/CodeGen/MachineInstr.h"
  26. #include "llvm/CodeGen/MachineInstrBuilder.h"
  27. #include "llvm/CodeGen/MachineOperand.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/RegAllocRegistry.h"
  30. #include "llvm/CodeGen/RegisterClassInfo.h"
  31. #include "llvm/CodeGen/TargetInstrInfo.h"
  32. #include "llvm/CodeGen/TargetOpcodes.h"
  33. #include "llvm/CodeGen/TargetRegisterInfo.h"
  34. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  35. #include "llvm/IR/DebugLoc.h"
  36. #include "llvm/IR/Metadata.h"
  37. #include "llvm/MC/MCInstrDesc.h"
  38. #include "llvm/MC/MCRegisterInfo.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/Casting.h"
  41. #include "llvm/Support/Compiler.h"
  42. #include "llvm/Support/Debug.h"
  43. #include "llvm/Support/ErrorHandling.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include <cassert>
  46. #include <tuple>
  47. #include <vector>
  48. using namespace llvm;
  49. #define DEBUG_TYPE "regalloc"
  50. STATISTIC(NumStores, "Number of stores added");
  51. STATISTIC(NumLoads , "Number of loads added");
  52. STATISTIC(NumCoalesced, "Number of copies coalesced");
  53. static RegisterRegAlloc
  54. fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
  55. namespace {
  56. class RegAllocFast : public MachineFunctionPass {
  57. public:
  58. static char ID;
  59. RegAllocFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1) {}
  60. private:
  61. MachineFrameInfo *MFI;
  62. MachineRegisterInfo *MRI;
  63. const TargetRegisterInfo *TRI;
  64. const TargetInstrInfo *TII;
  65. RegisterClassInfo RegClassInfo;
  66. /// Basic block currently being allocated.
  67. MachineBasicBlock *MBB;
  68. /// Maps virtual regs to the frame index where these values are spilled.
  69. IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
  70. /// Everything we know about a live virtual register.
  71. struct LiveReg {
  72. MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
  73. unsigned VirtReg; ///< Virtual register number.
  74. MCPhysReg PhysReg = 0; ///< Currently held here.
  75. unsigned short LastOpNum = 0; ///< OpNum on LastUse.
  76. bool Dirty = false; ///< Register needs spill.
  77. explicit LiveReg(unsigned VirtReg) : VirtReg(VirtReg) {}
  78. unsigned getSparseSetIndex() const {
  79. return Register::virtReg2Index(VirtReg);
  80. }
  81. };
  82. using LiveRegMap = SparseSet<LiveReg>;
  83. /// This map contains entries for each virtual register that is currently
  84. /// available in a physical register.
  85. LiveRegMap LiveVirtRegs;
  86. DenseMap<unsigned, SmallVector<MachineInstr *, 2>> LiveDbgValueMap;
  87. /// Has a bit set for every virtual register for which it was determined
  88. /// that it is alive across blocks.
  89. BitVector MayLiveAcrossBlocks;
  90. /// State of a physical register.
  91. enum RegState {
  92. /// A disabled register is not available for allocation, but an alias may
  93. /// be in use. A register can only be moved out of the disabled state if
  94. /// all aliases are disabled.
  95. regDisabled,
  96. /// A free register is not currently in use and can be allocated
  97. /// immediately without checking aliases.
  98. regFree,
  99. /// A reserved register has been assigned explicitly (e.g., setting up a
  100. /// call parameter), and it remains reserved until it is used.
  101. regReserved
  102. /// A register state may also be a virtual register number, indication
  103. /// that the physical register is currently allocated to a virtual
  104. /// register. In that case, LiveVirtRegs contains the inverse mapping.
  105. };
  106. /// Maps each physical register to a RegState enum or a virtual register.
  107. std::vector<unsigned> PhysRegState;
  108. SmallVector<unsigned, 16> VirtDead;
  109. SmallVector<MachineInstr *, 32> Coalesced;
  110. using RegUnitSet = SparseSet<uint16_t, identity<uint16_t>>;
  111. /// Set of register units that are used in the current instruction, and so
  112. /// cannot be allocated.
  113. RegUnitSet UsedInInstr;
  114. void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
  115. /// Mark a physreg as used in this instruction.
  116. void markRegUsedInInstr(MCPhysReg PhysReg) {
  117. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
  118. UsedInInstr.insert(*Units);
  119. }
  120. /// Check if a physreg or any of its aliases are used in this instruction.
  121. bool isRegUsedInInstr(MCPhysReg PhysReg) const {
  122. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
  123. if (UsedInInstr.count(*Units))
  124. return true;
  125. return false;
  126. }
  127. enum : unsigned {
  128. spillClean = 50,
  129. spillDirty = 100,
  130. spillPrefBonus = 20,
  131. spillImpossible = ~0u
  132. };
  133. public:
  134. StringRef getPassName() const override { return "Fast Register Allocator"; }
  135. void getAnalysisUsage(AnalysisUsage &AU) const override {
  136. AU.setPreservesCFG();
  137. MachineFunctionPass::getAnalysisUsage(AU);
  138. }
  139. MachineFunctionProperties getRequiredProperties() const override {
  140. return MachineFunctionProperties().set(
  141. MachineFunctionProperties::Property::NoPHIs);
  142. }
  143. MachineFunctionProperties getSetProperties() const override {
  144. return MachineFunctionProperties().set(
  145. MachineFunctionProperties::Property::NoVRegs);
  146. }
  147. private:
  148. bool runOnMachineFunction(MachineFunction &MF) override;
  149. void allocateBasicBlock(MachineBasicBlock &MBB);
  150. void allocateInstruction(MachineInstr &MI);
  151. void handleDebugValue(MachineInstr &MI);
  152. void handleThroughOperands(MachineInstr &MI,
  153. SmallVectorImpl<unsigned> &VirtDead);
  154. bool isLastUseOfLocalReg(const MachineOperand &MO) const;
  155. void addKillFlag(const LiveReg &LRI);
  156. void killVirtReg(LiveReg &LR);
  157. void killVirtReg(unsigned VirtReg);
  158. void spillVirtReg(MachineBasicBlock::iterator MI, LiveReg &LR);
  159. void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
  160. void usePhysReg(MachineOperand &MO);
  161. void definePhysReg(MachineBasicBlock::iterator MI, MCPhysReg PhysReg,
  162. RegState NewState);
  163. unsigned calcSpillCost(MCPhysReg PhysReg) const;
  164. void assignVirtToPhysReg(LiveReg &, MCPhysReg PhysReg);
  165. LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
  166. return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
  167. }
  168. LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
  169. return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
  170. }
  171. void allocVirtReg(MachineInstr &MI, LiveReg &LR, unsigned Hint);
  172. void allocVirtRegUndef(MachineOperand &MO);
  173. MCPhysReg defineVirtReg(MachineInstr &MI, unsigned OpNum, unsigned VirtReg,
  174. unsigned Hint);
  175. LiveReg &reloadVirtReg(MachineInstr &MI, unsigned OpNum, unsigned VirtReg,
  176. unsigned Hint);
  177. void spillAll(MachineBasicBlock::iterator MI, bool OnlyLiveOut);
  178. bool setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
  179. unsigned traceCopies(unsigned VirtReg) const;
  180. unsigned traceCopyChain(unsigned Reg) const;
  181. int getStackSpaceFor(unsigned VirtReg);
  182. void spill(MachineBasicBlock::iterator Before, unsigned VirtReg,
  183. MCPhysReg AssignedReg, bool Kill);
  184. void reload(MachineBasicBlock::iterator Before, unsigned VirtReg,
  185. MCPhysReg PhysReg);
  186. bool mayLiveOut(unsigned VirtReg);
  187. bool mayLiveIn(unsigned VirtReg);
  188. void dumpState();
  189. };
  190. } // end anonymous namespace
  191. char RegAllocFast::ID = 0;
  192. INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
  193. false)
  194. void RegAllocFast::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
  195. PhysRegState[PhysReg] = NewState;
  196. }
  197. /// This allocates space for the specified virtual register to be held on the
  198. /// stack.
  199. int RegAllocFast::getStackSpaceFor(unsigned VirtReg) {
  200. // Find the location Reg would belong...
  201. int SS = StackSlotForVirtReg[VirtReg];
  202. // Already has space allocated?
  203. if (SS != -1)
  204. return SS;
  205. // Allocate a new stack object for this spill location...
  206. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  207. unsigned Size = TRI->getSpillSize(RC);
  208. unsigned Align = TRI->getSpillAlignment(RC);
  209. int FrameIdx = MFI->CreateSpillStackObject(Size, Align);
  210. // Assign the slot.
  211. StackSlotForVirtReg[VirtReg] = FrameIdx;
  212. return FrameIdx;
  213. }
  214. /// Returns false if \p VirtReg is known to not live out of the current block.
  215. bool RegAllocFast::mayLiveOut(unsigned VirtReg) {
  216. if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg))) {
  217. // Cannot be live-out if there are no successors.
  218. return !MBB->succ_empty();
  219. }
  220. // If this block loops back to itself, it would be necessary to check whether
  221. // the use comes after the def.
  222. if (MBB->isSuccessor(MBB)) {
  223. MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
  224. return true;
  225. }
  226. // See if the first \p Limit uses of the register are all in the current
  227. // block.
  228. static const unsigned Limit = 8;
  229. unsigned C = 0;
  230. for (const MachineInstr &UseInst : MRI->reg_nodbg_instructions(VirtReg)) {
  231. if (UseInst.getParent() != MBB || ++C >= Limit) {
  232. MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
  233. // Cannot be live-out if there are no successors.
  234. return !MBB->succ_empty();
  235. }
  236. }
  237. return false;
  238. }
  239. /// Returns false if \p VirtReg is known to not be live into the current block.
  240. bool RegAllocFast::mayLiveIn(unsigned VirtReg) {
  241. if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg)))
  242. return !MBB->pred_empty();
  243. // See if the first \p Limit def of the register are all in the current block.
  244. static const unsigned Limit = 8;
  245. unsigned C = 0;
  246. for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
  247. if (DefInst.getParent() != MBB || ++C >= Limit) {
  248. MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
  249. return !MBB->pred_empty();
  250. }
  251. }
  252. return false;
  253. }
  254. /// Insert spill instruction for \p AssignedReg before \p Before. Update
  255. /// DBG_VALUEs with \p VirtReg operands with the stack slot.
  256. void RegAllocFast::spill(MachineBasicBlock::iterator Before, unsigned VirtReg,
  257. MCPhysReg AssignedReg, bool Kill) {
  258. LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI)
  259. << " in " << printReg(AssignedReg, TRI));
  260. int FI = getStackSpaceFor(VirtReg);
  261. LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
  262. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  263. TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI);
  264. ++NumStores;
  265. // If this register is used by DBG_VALUE then insert new DBG_VALUE to
  266. // identify spilled location as the place to find corresponding variable's
  267. // value.
  268. SmallVectorImpl<MachineInstr *> &LRIDbgValues = LiveDbgValueMap[VirtReg];
  269. for (MachineInstr *DBG : LRIDbgValues) {
  270. MachineInstr *NewDV = buildDbgValueForSpill(*MBB, Before, *DBG, FI);
  271. assert(NewDV->getParent() == MBB && "dangling parent pointer");
  272. (void)NewDV;
  273. LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
  274. }
  275. // Now this register is spilled there is should not be any DBG_VALUE
  276. // pointing to this register because they are all pointing to spilled value
  277. // now.
  278. LRIDbgValues.clear();
  279. }
  280. /// Insert reload instruction for \p PhysReg before \p Before.
  281. void RegAllocFast::reload(MachineBasicBlock::iterator Before, unsigned VirtReg,
  282. MCPhysReg PhysReg) {
  283. LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
  284. << printReg(PhysReg, TRI) << '\n');
  285. int FI = getStackSpaceFor(VirtReg);
  286. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  287. TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI);
  288. ++NumLoads;
  289. }
  290. /// Return true if MO is the only remaining reference to its virtual register,
  291. /// and it is guaranteed to be a block-local register.
  292. bool RegAllocFast::isLastUseOfLocalReg(const MachineOperand &MO) const {
  293. // If the register has ever been spilled or reloaded, we conservatively assume
  294. // it is a global register used in multiple blocks.
  295. if (StackSlotForVirtReg[MO.getReg()] != -1)
  296. return false;
  297. // Check that the use/def chain has exactly one operand - MO.
  298. MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
  299. if (&*I != &MO)
  300. return false;
  301. return ++I == MRI->reg_nodbg_end();
  302. }
  303. /// Set kill flags on last use of a virtual register.
  304. void RegAllocFast::addKillFlag(const LiveReg &LR) {
  305. if (!LR.LastUse) return;
  306. MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
  307. if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
  308. if (MO.getReg() == LR.PhysReg)
  309. MO.setIsKill();
  310. // else, don't do anything we are problably redefining a
  311. // subreg of this register and given we don't track which
  312. // lanes are actually dead, we cannot insert a kill flag here.
  313. // Otherwise we may end up in a situation like this:
  314. // ... = (MO) physreg:sub1, implicit killed physreg
  315. // ... <== Here we would allow later pass to reuse physreg:sub1
  316. // which is potentially wrong.
  317. // LR:sub0 = ...
  318. // ... = LR.sub1 <== This is going to use physreg:sub1
  319. }
  320. }
  321. /// Mark virtreg as no longer available.
  322. void RegAllocFast::killVirtReg(LiveReg &LR) {
  323. addKillFlag(LR);
  324. assert(PhysRegState[LR.PhysReg] == LR.VirtReg &&
  325. "Broken RegState mapping");
  326. setPhysRegState(LR.PhysReg, regFree);
  327. LR.PhysReg = 0;
  328. }
  329. /// Mark virtreg as no longer available.
  330. void RegAllocFast::killVirtReg(unsigned VirtReg) {
  331. assert(Register::isVirtualRegister(VirtReg) &&
  332. "killVirtReg needs a virtual register");
  333. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  334. if (LRI != LiveVirtRegs.end() && LRI->PhysReg)
  335. killVirtReg(*LRI);
  336. }
  337. /// This method spills the value specified by VirtReg into the corresponding
  338. /// stack slot if needed.
  339. void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI,
  340. unsigned VirtReg) {
  341. assert(Register::isVirtualRegister(VirtReg) &&
  342. "Spilling a physical register is illegal!");
  343. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  344. assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
  345. "Spilling unmapped virtual register");
  346. spillVirtReg(MI, *LRI);
  347. }
  348. /// Do the actual work of spilling.
  349. void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI, LiveReg &LR) {
  350. assert(PhysRegState[LR.PhysReg] == LR.VirtReg && "Broken RegState mapping");
  351. if (LR.Dirty) {
  352. // If this physreg is used by the instruction, we want to kill it on the
  353. // instruction, not on the spill.
  354. bool SpillKill = MachineBasicBlock::iterator(LR.LastUse) != MI;
  355. LR.Dirty = false;
  356. spill(MI, LR.VirtReg, LR.PhysReg, SpillKill);
  357. if (SpillKill)
  358. LR.LastUse = nullptr; // Don't kill register again
  359. }
  360. killVirtReg(LR);
  361. }
  362. /// Spill all dirty virtregs without killing them.
  363. void RegAllocFast::spillAll(MachineBasicBlock::iterator MI, bool OnlyLiveOut) {
  364. if (LiveVirtRegs.empty())
  365. return;
  366. // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
  367. // of spilling here is deterministic, if arbitrary.
  368. for (LiveReg &LR : LiveVirtRegs) {
  369. if (!LR.PhysReg)
  370. continue;
  371. if (OnlyLiveOut && !mayLiveOut(LR.VirtReg))
  372. continue;
  373. spillVirtReg(MI, LR);
  374. }
  375. LiveVirtRegs.clear();
  376. }
  377. /// Handle the direct use of a physical register. Check that the register is
  378. /// not used by a virtreg. Kill the physreg, marking it free. This may add
  379. /// implicit kills to MO->getParent() and invalidate MO.
  380. void RegAllocFast::usePhysReg(MachineOperand &MO) {
  381. // Ignore undef uses.
  382. if (MO.isUndef())
  383. return;
  384. Register PhysReg = MO.getReg();
  385. assert(Register::isPhysicalRegister(PhysReg) && "Bad usePhysReg operand");
  386. markRegUsedInInstr(PhysReg);
  387. switch (PhysRegState[PhysReg]) {
  388. case regDisabled:
  389. break;
  390. case regReserved:
  391. PhysRegState[PhysReg] = regFree;
  392. LLVM_FALLTHROUGH;
  393. case regFree:
  394. MO.setIsKill();
  395. return;
  396. default:
  397. // The physreg was allocated to a virtual register. That means the value we
  398. // wanted has been clobbered.
  399. llvm_unreachable("Instruction uses an allocated register");
  400. }
  401. // Maybe a superregister is reserved?
  402. for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
  403. MCPhysReg Alias = *AI;
  404. switch (PhysRegState[Alias]) {
  405. case regDisabled:
  406. break;
  407. case regReserved:
  408. // Either PhysReg is a subregister of Alias and we mark the
  409. // whole register as free, or PhysReg is the superregister of
  410. // Alias and we mark all the aliases as disabled before freeing
  411. // PhysReg.
  412. // In the latter case, since PhysReg was disabled, this means that
  413. // its value is defined only by physical sub-registers. This check
  414. // is performed by the assert of the default case in this loop.
  415. // Note: The value of the superregister may only be partial
  416. // defined, that is why regDisabled is a valid state for aliases.
  417. assert((TRI->isSuperRegister(PhysReg, Alias) ||
  418. TRI->isSuperRegister(Alias, PhysReg)) &&
  419. "Instruction is not using a subregister of a reserved register");
  420. LLVM_FALLTHROUGH;
  421. case regFree:
  422. if (TRI->isSuperRegister(PhysReg, Alias)) {
  423. // Leave the superregister in the working set.
  424. setPhysRegState(Alias, regFree);
  425. MO.getParent()->addRegisterKilled(Alias, TRI, true);
  426. return;
  427. }
  428. // Some other alias was in the working set - clear it.
  429. setPhysRegState(Alias, regDisabled);
  430. break;
  431. default:
  432. llvm_unreachable("Instruction uses an alias of an allocated register");
  433. }
  434. }
  435. // All aliases are disabled, bring register into working set.
  436. setPhysRegState(PhysReg, regFree);
  437. MO.setIsKill();
  438. }
  439. /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
  440. /// similar to defineVirtReg except the physreg is reserved instead of
  441. /// allocated.
  442. void RegAllocFast::definePhysReg(MachineBasicBlock::iterator MI,
  443. MCPhysReg PhysReg, RegState NewState) {
  444. markRegUsedInInstr(PhysReg);
  445. switch (unsigned VirtReg = PhysRegState[PhysReg]) {
  446. case regDisabled:
  447. break;
  448. default:
  449. spillVirtReg(MI, VirtReg);
  450. LLVM_FALLTHROUGH;
  451. case regFree:
  452. case regReserved:
  453. setPhysRegState(PhysReg, NewState);
  454. return;
  455. }
  456. // This is a disabled register, disable all aliases.
  457. setPhysRegState(PhysReg, NewState);
  458. for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
  459. MCPhysReg Alias = *AI;
  460. switch (unsigned VirtReg = PhysRegState[Alias]) {
  461. case regDisabled:
  462. break;
  463. default:
  464. spillVirtReg(MI, VirtReg);
  465. LLVM_FALLTHROUGH;
  466. case regFree:
  467. case regReserved:
  468. setPhysRegState(Alias, regDisabled);
  469. if (TRI->isSuperRegister(PhysReg, Alias))
  470. return;
  471. break;
  472. }
  473. }
  474. }
  475. /// Return the cost of spilling clearing out PhysReg and aliases so it is free
  476. /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
  477. /// disabled - it can be allocated directly.
  478. /// \returns spillImpossible when PhysReg or an alias can't be spilled.
  479. unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
  480. if (isRegUsedInInstr(PhysReg)) {
  481. LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI)
  482. << " is already used in instr.\n");
  483. return spillImpossible;
  484. }
  485. switch (unsigned VirtReg = PhysRegState[PhysReg]) {
  486. case regDisabled:
  487. break;
  488. case regFree:
  489. return 0;
  490. case regReserved:
  491. LLVM_DEBUG(dbgs() << printReg(VirtReg, TRI) << " corresponding "
  492. << printReg(PhysReg, TRI) << " is reserved already.\n");
  493. return spillImpossible;
  494. default: {
  495. LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
  496. assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
  497. "Missing VirtReg entry");
  498. return LRI->Dirty ? spillDirty : spillClean;
  499. }
  500. }
  501. // This is a disabled register, add up cost of aliases.
  502. LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is disabled.\n");
  503. unsigned Cost = 0;
  504. for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
  505. MCPhysReg Alias = *AI;
  506. switch (unsigned VirtReg = PhysRegState[Alias]) {
  507. case regDisabled:
  508. break;
  509. case regFree:
  510. ++Cost;
  511. break;
  512. case regReserved:
  513. return spillImpossible;
  514. default: {
  515. LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
  516. assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
  517. "Missing VirtReg entry");
  518. Cost += LRI->Dirty ? spillDirty : spillClean;
  519. break;
  520. }
  521. }
  522. }
  523. return Cost;
  524. }
  525. /// This method updates local state so that we know that PhysReg is the
  526. /// proper container for VirtReg now. The physical register must not be used
  527. /// for anything else when this is called.
  528. void RegAllocFast::assignVirtToPhysReg(LiveReg &LR, MCPhysReg PhysReg) {
  529. unsigned VirtReg = LR.VirtReg;
  530. LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
  531. << printReg(PhysReg, TRI) << '\n');
  532. assert(LR.PhysReg == 0 && "Already assigned a physreg");
  533. assert(PhysReg != 0 && "Trying to assign no register");
  534. LR.PhysReg = PhysReg;
  535. setPhysRegState(PhysReg, VirtReg);
  536. }
  537. static bool isCoalescable(const MachineInstr &MI) {
  538. return MI.isFullCopy();
  539. }
  540. unsigned RegAllocFast::traceCopyChain(unsigned Reg) const {
  541. static const unsigned ChainLengthLimit = 3;
  542. unsigned C = 0;
  543. do {
  544. if (Register::isPhysicalRegister(Reg))
  545. return Reg;
  546. assert(Register::isVirtualRegister(Reg));
  547. MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
  548. if (!VRegDef || !isCoalescable(*VRegDef))
  549. return 0;
  550. Reg = VRegDef->getOperand(1).getReg();
  551. } while (++C <= ChainLengthLimit);
  552. return 0;
  553. }
  554. /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
  555. /// chain of copies to check whether we reach a physical register we can
  556. /// coalesce with.
  557. unsigned RegAllocFast::traceCopies(unsigned VirtReg) const {
  558. static const unsigned DefLimit = 3;
  559. unsigned C = 0;
  560. for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
  561. if (isCoalescable(MI)) {
  562. Register Reg = MI.getOperand(1).getReg();
  563. Reg = traceCopyChain(Reg);
  564. if (Reg != 0)
  565. return Reg;
  566. }
  567. if (++C >= DefLimit)
  568. break;
  569. }
  570. return 0;
  571. }
  572. /// Allocates a physical register for VirtReg.
  573. void RegAllocFast::allocVirtReg(MachineInstr &MI, LiveReg &LR, unsigned Hint0) {
  574. const unsigned VirtReg = LR.VirtReg;
  575. assert(Register::isVirtualRegister(VirtReg) &&
  576. "Can only allocate virtual registers");
  577. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  578. LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
  579. << " in class " << TRI->getRegClassName(&RC)
  580. << " with hint " << printReg(Hint0, TRI) << '\n');
  581. // Take hint when possible.
  582. if (Register::isPhysicalRegister(Hint0) && MRI->isAllocatable(Hint0) &&
  583. RC.contains(Hint0)) {
  584. // Ignore the hint if we would have to spill a dirty register.
  585. unsigned Cost = calcSpillCost(Hint0);
  586. if (Cost < spillDirty) {
  587. LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
  588. << '\n');
  589. if (Cost)
  590. definePhysReg(MI, Hint0, regFree);
  591. assignVirtToPhysReg(LR, Hint0);
  592. return;
  593. } else {
  594. LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
  595. << "occupied\n");
  596. }
  597. } else {
  598. Hint0 = 0;
  599. }
  600. // Try other hint.
  601. unsigned Hint1 = traceCopies(VirtReg);
  602. if (Register::isPhysicalRegister(Hint1) && MRI->isAllocatable(Hint1) &&
  603. RC.contains(Hint1) && !isRegUsedInInstr(Hint1)) {
  604. // Ignore the hint if we would have to spill a dirty register.
  605. unsigned Cost = calcSpillCost(Hint1);
  606. if (Cost < spillDirty) {
  607. LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
  608. << '\n');
  609. if (Cost)
  610. definePhysReg(MI, Hint1, regFree);
  611. assignVirtToPhysReg(LR, Hint1);
  612. return;
  613. } else {
  614. LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
  615. << "occupied\n");
  616. }
  617. } else {
  618. Hint1 = 0;
  619. }
  620. MCPhysReg BestReg = 0;
  621. unsigned BestCost = spillImpossible;
  622. ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
  623. for (MCPhysReg PhysReg : AllocationOrder) {
  624. LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
  625. unsigned Cost = calcSpillCost(PhysReg);
  626. LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
  627. // Immediate take a register with cost 0.
  628. if (Cost == 0) {
  629. assignVirtToPhysReg(LR, PhysReg);
  630. return;
  631. }
  632. if (PhysReg == Hint1 || PhysReg == Hint0)
  633. Cost -= spillPrefBonus;
  634. if (Cost < BestCost) {
  635. BestReg = PhysReg;
  636. BestCost = Cost;
  637. }
  638. }
  639. if (!BestReg) {
  640. // Nothing we can do: Report an error and keep going with an invalid
  641. // allocation.
  642. if (MI.isInlineAsm())
  643. MI.emitError("inline assembly requires more registers than available");
  644. else
  645. MI.emitError("ran out of registers during register allocation");
  646. definePhysReg(MI, *AllocationOrder.begin(), regFree);
  647. assignVirtToPhysReg(LR, *AllocationOrder.begin());
  648. return;
  649. }
  650. definePhysReg(MI, BestReg, regFree);
  651. assignVirtToPhysReg(LR, BestReg);
  652. }
  653. void RegAllocFast::allocVirtRegUndef(MachineOperand &MO) {
  654. assert(MO.isUndef() && "expected undef use");
  655. Register VirtReg = MO.getReg();
  656. assert(Register::isVirtualRegister(VirtReg) && "Expected virtreg");
  657. LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
  658. MCPhysReg PhysReg;
  659. if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
  660. PhysReg = LRI->PhysReg;
  661. } else {
  662. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  663. ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
  664. assert(!AllocationOrder.empty() && "Allocation order must not be empty");
  665. PhysReg = AllocationOrder[0];
  666. }
  667. unsigned SubRegIdx = MO.getSubReg();
  668. if (SubRegIdx != 0) {
  669. PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
  670. MO.setSubReg(0);
  671. }
  672. MO.setReg(PhysReg);
  673. MO.setIsRenamable(true);
  674. }
  675. /// Allocates a register for VirtReg and mark it as dirty.
  676. MCPhysReg RegAllocFast::defineVirtReg(MachineInstr &MI, unsigned OpNum,
  677. unsigned VirtReg, unsigned Hint) {
  678. assert(Register::isVirtualRegister(VirtReg) && "Not a virtual register");
  679. LiveRegMap::iterator LRI;
  680. bool New;
  681. std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
  682. if (!LRI->PhysReg) {
  683. // If there is no hint, peek at the only use of this register.
  684. if ((!Hint || !Register::isPhysicalRegister(Hint)) &&
  685. MRI->hasOneNonDBGUse(VirtReg)) {
  686. const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
  687. // It's a copy, use the destination register as a hint.
  688. if (UseMI.isCopyLike())
  689. Hint = UseMI.getOperand(0).getReg();
  690. }
  691. allocVirtReg(MI, *LRI, Hint);
  692. } else if (LRI->LastUse) {
  693. // Redefining a live register - kill at the last use, unless it is this
  694. // instruction defining VirtReg multiple times.
  695. if (LRI->LastUse != &MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
  696. addKillFlag(*LRI);
  697. }
  698. assert(LRI->PhysReg && "Register not assigned");
  699. LRI->LastUse = &MI;
  700. LRI->LastOpNum = OpNum;
  701. LRI->Dirty = true;
  702. markRegUsedInInstr(LRI->PhysReg);
  703. return LRI->PhysReg;
  704. }
  705. /// Make sure VirtReg is available in a physreg and return it.
  706. RegAllocFast::LiveReg &RegAllocFast::reloadVirtReg(MachineInstr &MI,
  707. unsigned OpNum,
  708. unsigned VirtReg,
  709. unsigned Hint) {
  710. assert(Register::isVirtualRegister(VirtReg) && "Not a virtual register");
  711. LiveRegMap::iterator LRI;
  712. bool New;
  713. std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
  714. MachineOperand &MO = MI.getOperand(OpNum);
  715. if (!LRI->PhysReg) {
  716. allocVirtReg(MI, *LRI, Hint);
  717. reload(MI, VirtReg, LRI->PhysReg);
  718. } else if (LRI->Dirty) {
  719. if (isLastUseOfLocalReg(MO)) {
  720. LLVM_DEBUG(dbgs() << "Killing last use: " << MO << '\n');
  721. if (MO.isUse())
  722. MO.setIsKill();
  723. else
  724. MO.setIsDead();
  725. } else if (MO.isKill()) {
  726. LLVM_DEBUG(dbgs() << "Clearing dubious kill: " << MO << '\n');
  727. MO.setIsKill(false);
  728. } else if (MO.isDead()) {
  729. LLVM_DEBUG(dbgs() << "Clearing dubious dead: " << MO << '\n');
  730. MO.setIsDead(false);
  731. }
  732. } else if (MO.isKill()) {
  733. // We must remove kill flags from uses of reloaded registers because the
  734. // register would be killed immediately, and there might be a second use:
  735. // %foo = OR killed %x, %x
  736. // This would cause a second reload of %x into a different register.
  737. LLVM_DEBUG(dbgs() << "Clearing clean kill: " << MO << '\n');
  738. MO.setIsKill(false);
  739. } else if (MO.isDead()) {
  740. LLVM_DEBUG(dbgs() << "Clearing clean dead: " << MO << '\n');
  741. MO.setIsDead(false);
  742. }
  743. assert(LRI->PhysReg && "Register not assigned");
  744. LRI->LastUse = &MI;
  745. LRI->LastOpNum = OpNum;
  746. markRegUsedInInstr(LRI->PhysReg);
  747. return *LRI;
  748. }
  749. /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
  750. /// may invalidate any operand pointers. Return true if the operand kills its
  751. /// register.
  752. bool RegAllocFast::setPhysReg(MachineInstr &MI, MachineOperand &MO,
  753. MCPhysReg PhysReg) {
  754. bool Dead = MO.isDead();
  755. if (!MO.getSubReg()) {
  756. MO.setReg(PhysReg);
  757. MO.setIsRenamable(true);
  758. return MO.isKill() || Dead;
  759. }
  760. // Handle subregister index.
  761. MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : Register());
  762. MO.setIsRenamable(true);
  763. MO.setSubReg(0);
  764. // A kill flag implies killing the full register. Add corresponding super
  765. // register kill.
  766. if (MO.isKill()) {
  767. MI.addRegisterKilled(PhysReg, TRI, true);
  768. return true;
  769. }
  770. // A <def,read-undef> of a sub-register requires an implicit def of the full
  771. // register.
  772. if (MO.isDef() && MO.isUndef())
  773. MI.addRegisterDefined(PhysReg, TRI);
  774. return Dead;
  775. }
  776. // Handles special instruction operand like early clobbers and tied ops when
  777. // there are additional physreg defines.
  778. void RegAllocFast::handleThroughOperands(MachineInstr &MI,
  779. SmallVectorImpl<unsigned> &VirtDead) {
  780. LLVM_DEBUG(dbgs() << "Scanning for through registers:");
  781. SmallSet<unsigned, 8> ThroughRegs;
  782. for (const MachineOperand &MO : MI.operands()) {
  783. if (!MO.isReg()) continue;
  784. Register Reg = MO.getReg();
  785. if (!Register::isVirtualRegister(Reg))
  786. continue;
  787. if (MO.isEarlyClobber() || (MO.isUse() && MO.isTied()) ||
  788. (MO.getSubReg() && MI.readsVirtualRegister(Reg))) {
  789. if (ThroughRegs.insert(Reg).second)
  790. LLVM_DEBUG(dbgs() << ' ' << printReg(Reg));
  791. }
  792. }
  793. // If any physreg defines collide with preallocated through registers,
  794. // we must spill and reallocate.
  795. LLVM_DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
  796. for (const MachineOperand &MO : MI.operands()) {
  797. if (!MO.isReg() || !MO.isDef()) continue;
  798. Register Reg = MO.getReg();
  799. if (!Reg || !Register::isPhysicalRegister(Reg))
  800. continue;
  801. markRegUsedInInstr(Reg);
  802. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
  803. if (ThroughRegs.count(PhysRegState[*AI]))
  804. definePhysReg(MI, *AI, regFree);
  805. }
  806. }
  807. SmallVector<unsigned, 8> PartialDefs;
  808. LLVM_DEBUG(dbgs() << "Allocating tied uses.\n");
  809. for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
  810. MachineOperand &MO = MI.getOperand(I);
  811. if (!MO.isReg()) continue;
  812. Register Reg = MO.getReg();
  813. if (!Register::isVirtualRegister(Reg))
  814. continue;
  815. if (MO.isUse()) {
  816. if (!MO.isTied()) continue;
  817. LLVM_DEBUG(dbgs() << "Operand " << I << "(" << MO
  818. << ") is tied to operand " << MI.findTiedOperandIdx(I)
  819. << ".\n");
  820. LiveReg &LR = reloadVirtReg(MI, I, Reg, 0);
  821. MCPhysReg PhysReg = LR.PhysReg;
  822. setPhysReg(MI, MO, PhysReg);
  823. // Note: we don't update the def operand yet. That would cause the normal
  824. // def-scan to attempt spilling.
  825. } else if (MO.getSubReg() && MI.readsVirtualRegister(Reg)) {
  826. LLVM_DEBUG(dbgs() << "Partial redefine: " << MO << '\n');
  827. // Reload the register, but don't assign to the operand just yet.
  828. // That would confuse the later phys-def processing pass.
  829. LiveReg &LR = reloadVirtReg(MI, I, Reg, 0);
  830. PartialDefs.push_back(LR.PhysReg);
  831. }
  832. }
  833. LLVM_DEBUG(dbgs() << "Allocating early clobbers.\n");
  834. for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
  835. const MachineOperand &MO = MI.getOperand(I);
  836. if (!MO.isReg()) continue;
  837. Register Reg = MO.getReg();
  838. if (!Register::isVirtualRegister(Reg))
  839. continue;
  840. if (!MO.isEarlyClobber())
  841. continue;
  842. // Note: defineVirtReg may invalidate MO.
  843. MCPhysReg PhysReg = defineVirtReg(MI, I, Reg, 0);
  844. if (setPhysReg(MI, MI.getOperand(I), PhysReg))
  845. VirtDead.push_back(Reg);
  846. }
  847. // Restore UsedInInstr to a state usable for allocating normal virtual uses.
  848. UsedInInstr.clear();
  849. for (const MachineOperand &MO : MI.operands()) {
  850. if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
  851. Register Reg = MO.getReg();
  852. if (!Reg || !Register::isPhysicalRegister(Reg))
  853. continue;
  854. LLVM_DEBUG(dbgs() << "\tSetting " << printReg(Reg, TRI)
  855. << " as used in instr\n");
  856. markRegUsedInInstr(Reg);
  857. }
  858. // Also mark PartialDefs as used to avoid reallocation.
  859. for (unsigned PartialDef : PartialDefs)
  860. markRegUsedInInstr(PartialDef);
  861. }
  862. #ifndef NDEBUG
  863. void RegAllocFast::dumpState() {
  864. for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
  865. if (PhysRegState[Reg] == regDisabled) continue;
  866. dbgs() << " " << printReg(Reg, TRI);
  867. switch(PhysRegState[Reg]) {
  868. case regFree:
  869. break;
  870. case regReserved:
  871. dbgs() << "*";
  872. break;
  873. default: {
  874. dbgs() << '=' << printReg(PhysRegState[Reg]);
  875. LiveRegMap::iterator LRI = findLiveVirtReg(PhysRegState[Reg]);
  876. assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
  877. "Missing VirtReg entry");
  878. if (LRI->Dirty)
  879. dbgs() << "*";
  880. assert(LRI->PhysReg == Reg && "Bad inverse map");
  881. break;
  882. }
  883. }
  884. }
  885. dbgs() << '\n';
  886. // Check that LiveVirtRegs is the inverse.
  887. for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
  888. e = LiveVirtRegs.end(); i != e; ++i) {
  889. if (!i->PhysReg)
  890. continue;
  891. assert(Register::isVirtualRegister(i->VirtReg) && "Bad map key");
  892. assert(Register::isPhysicalRegister(i->PhysReg) && "Bad map value");
  893. assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
  894. }
  895. }
  896. #endif
  897. void RegAllocFast::allocateInstruction(MachineInstr &MI) {
  898. const MCInstrDesc &MCID = MI.getDesc();
  899. // If this is a copy, we may be able to coalesce.
  900. unsigned CopySrcReg = 0;
  901. unsigned CopyDstReg = 0;
  902. unsigned CopySrcSub = 0;
  903. unsigned CopyDstSub = 0;
  904. if (MI.isCopy()) {
  905. CopyDstReg = MI.getOperand(0).getReg();
  906. CopySrcReg = MI.getOperand(1).getReg();
  907. CopyDstSub = MI.getOperand(0).getSubReg();
  908. CopySrcSub = MI.getOperand(1).getSubReg();
  909. }
  910. // Track registers used by instruction.
  911. UsedInInstr.clear();
  912. // First scan.
  913. // Mark physreg uses and early clobbers as used.
  914. // Find the end of the virtreg operands
  915. unsigned VirtOpEnd = 0;
  916. bool hasTiedOps = false;
  917. bool hasEarlyClobbers = false;
  918. bool hasPartialRedefs = false;
  919. bool hasPhysDefs = false;
  920. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  921. MachineOperand &MO = MI.getOperand(i);
  922. // Make sure MRI knows about registers clobbered by regmasks.
  923. if (MO.isRegMask()) {
  924. MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
  925. continue;
  926. }
  927. if (!MO.isReg()) continue;
  928. Register Reg = MO.getReg();
  929. if (!Reg) continue;
  930. if (Register::isVirtualRegister(Reg)) {
  931. VirtOpEnd = i+1;
  932. if (MO.isUse()) {
  933. hasTiedOps = hasTiedOps ||
  934. MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
  935. } else {
  936. if (MO.isEarlyClobber())
  937. hasEarlyClobbers = true;
  938. if (MO.getSubReg() && MI.readsVirtualRegister(Reg))
  939. hasPartialRedefs = true;
  940. }
  941. continue;
  942. }
  943. if (!MRI->isAllocatable(Reg)) continue;
  944. if (MO.isUse()) {
  945. usePhysReg(MO);
  946. } else if (MO.isEarlyClobber()) {
  947. definePhysReg(MI, Reg,
  948. (MO.isImplicit() || MO.isDead()) ? regFree : regReserved);
  949. hasEarlyClobbers = true;
  950. } else
  951. hasPhysDefs = true;
  952. }
  953. // The instruction may have virtual register operands that must be allocated
  954. // the same register at use-time and def-time: early clobbers and tied
  955. // operands. If there are also physical defs, these registers must avoid
  956. // both physical defs and uses, making them more constrained than normal
  957. // operands.
  958. // Similarly, if there are multiple defs and tied operands, we must make
  959. // sure the same register is allocated to uses and defs.
  960. // We didn't detect inline asm tied operands above, so just make this extra
  961. // pass for all inline asm.
  962. if (MI.isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
  963. (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
  964. handleThroughOperands(MI, VirtDead);
  965. // Don't attempt coalescing when we have funny stuff going on.
  966. CopyDstReg = 0;
  967. // Pretend we have early clobbers so the use operands get marked below.
  968. // This is not necessary for the common case of a single tied use.
  969. hasEarlyClobbers = true;
  970. }
  971. // Second scan.
  972. // Allocate virtreg uses.
  973. bool HasUndefUse = false;
  974. for (unsigned I = 0; I != VirtOpEnd; ++I) {
  975. MachineOperand &MO = MI.getOperand(I);
  976. if (!MO.isReg()) continue;
  977. Register Reg = MO.getReg();
  978. if (!Register::isVirtualRegister(Reg))
  979. continue;
  980. if (MO.isUse()) {
  981. if (MO.isUndef()) {
  982. HasUndefUse = true;
  983. // There is no need to allocate a register for an undef use.
  984. continue;
  985. }
  986. // Populate MayLiveAcrossBlocks in case the use block is allocated before
  987. // the def block (removing the vreg uses).
  988. mayLiveIn(Reg);
  989. LiveReg &LR = reloadVirtReg(MI, I, Reg, CopyDstReg);
  990. MCPhysReg PhysReg = LR.PhysReg;
  991. CopySrcReg = (CopySrcReg == Reg || CopySrcReg == PhysReg) ? PhysReg : 0;
  992. if (setPhysReg(MI, MO, PhysReg))
  993. killVirtReg(LR);
  994. }
  995. }
  996. // Allocate undef operands. This is a separate step because in a situation
  997. // like ` = OP undef %X, %X` both operands need the same register assign
  998. // so we should perform the normal assignment first.
  999. if (HasUndefUse) {
  1000. for (MachineOperand &MO : MI.uses()) {
  1001. if (!MO.isReg() || !MO.isUse())
  1002. continue;
  1003. Register Reg = MO.getReg();
  1004. if (!Register::isVirtualRegister(Reg))
  1005. continue;
  1006. assert(MO.isUndef() && "Should only have undef virtreg uses left");
  1007. allocVirtRegUndef(MO);
  1008. }
  1009. }
  1010. // Track registers defined by instruction - early clobbers and tied uses at
  1011. // this point.
  1012. UsedInInstr.clear();
  1013. if (hasEarlyClobbers) {
  1014. for (const MachineOperand &MO : MI.operands()) {
  1015. if (!MO.isReg()) continue;
  1016. Register Reg = MO.getReg();
  1017. if (!Reg || !Register::isPhysicalRegister(Reg))
  1018. continue;
  1019. // Look for physreg defs and tied uses.
  1020. if (!MO.isDef() && !MO.isTied()) continue;
  1021. markRegUsedInInstr(Reg);
  1022. }
  1023. }
  1024. unsigned DefOpEnd = MI.getNumOperands();
  1025. if (MI.isCall()) {
  1026. // Spill all virtregs before a call. This serves one purpose: If an
  1027. // exception is thrown, the landing pad is going to expect to find
  1028. // registers in their spill slots.
  1029. // Note: although this is appealing to just consider all definitions
  1030. // as call-clobbered, this is not correct because some of those
  1031. // definitions may be used later on and we do not want to reuse
  1032. // those for virtual registers in between.
  1033. LLVM_DEBUG(dbgs() << " Spilling remaining registers before call.\n");
  1034. spillAll(MI, /*OnlyLiveOut*/ false);
  1035. }
  1036. // Third scan.
  1037. // Mark all physreg defs as used before allocating virtreg defs.
  1038. for (unsigned I = 0; I != DefOpEnd; ++I) {
  1039. const MachineOperand &MO = MI.getOperand(I);
  1040. if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
  1041. continue;
  1042. Register Reg = MO.getReg();
  1043. if (!Reg || !Register::isPhysicalRegister(Reg) || !MRI->isAllocatable(Reg))
  1044. continue;
  1045. definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
  1046. }
  1047. // Fourth scan.
  1048. // Allocate defs and collect dead defs.
  1049. for (unsigned I = 0; I != DefOpEnd; ++I) {
  1050. const MachineOperand &MO = MI.getOperand(I);
  1051. if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
  1052. continue;
  1053. Register Reg = MO.getReg();
  1054. // We have already dealt with phys regs in the previous scan.
  1055. if (Register::isPhysicalRegister(Reg))
  1056. continue;
  1057. MCPhysReg PhysReg = defineVirtReg(MI, I, Reg, CopySrcReg);
  1058. if (setPhysReg(MI, MI.getOperand(I), PhysReg)) {
  1059. VirtDead.push_back(Reg);
  1060. CopyDstReg = 0; // cancel coalescing;
  1061. } else
  1062. CopyDstReg = (CopyDstReg == Reg || CopyDstReg == PhysReg) ? PhysReg : 0;
  1063. }
  1064. // Kill dead defs after the scan to ensure that multiple defs of the same
  1065. // register are allocated identically. We didn't need to do this for uses
  1066. // because we are crerating our own kill flags, and they are always at the
  1067. // last use.
  1068. for (unsigned VirtReg : VirtDead)
  1069. killVirtReg(VirtReg);
  1070. VirtDead.clear();
  1071. LLVM_DEBUG(dbgs() << "<< " << MI);
  1072. if (CopyDstReg && CopyDstReg == CopySrcReg && CopyDstSub == CopySrcSub) {
  1073. LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
  1074. Coalesced.push_back(&MI);
  1075. }
  1076. }
  1077. void RegAllocFast::handleDebugValue(MachineInstr &MI) {
  1078. MachineOperand &MO = MI.getOperand(0);
  1079. // Ignore DBG_VALUEs that aren't based on virtual registers. These are
  1080. // mostly constants and frame indices.
  1081. if (!MO.isReg())
  1082. return;
  1083. Register Reg = MO.getReg();
  1084. if (!Register::isVirtualRegister(Reg))
  1085. return;
  1086. // See if this virtual register has already been allocated to a physical
  1087. // register or spilled to a stack slot.
  1088. LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
  1089. if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
  1090. setPhysReg(MI, MO, LRI->PhysReg);
  1091. } else {
  1092. int SS = StackSlotForVirtReg[Reg];
  1093. if (SS != -1) {
  1094. // Modify DBG_VALUE now that the value is in a spill slot.
  1095. updateDbgValueForSpill(MI, SS);
  1096. LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << MI);
  1097. return;
  1098. }
  1099. // We can't allocate a physreg for a DebugValue, sorry!
  1100. LLVM_DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
  1101. MO.setReg(0);
  1102. }
  1103. // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
  1104. // that future spills of Reg will have DBG_VALUEs.
  1105. LiveDbgValueMap[Reg].push_back(&MI);
  1106. }
  1107. void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
  1108. this->MBB = &MBB;
  1109. LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
  1110. PhysRegState.assign(TRI->getNumRegs(), regDisabled);
  1111. assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
  1112. MachineBasicBlock::iterator MII = MBB.begin();
  1113. // Add live-in registers as live.
  1114. for (const MachineBasicBlock::RegisterMaskPair LI : MBB.liveins())
  1115. if (MRI->isAllocatable(LI.PhysReg))
  1116. definePhysReg(MII, LI.PhysReg, regReserved);
  1117. VirtDead.clear();
  1118. Coalesced.clear();
  1119. // Otherwise, sequentially allocate each instruction in the MBB.
  1120. for (MachineInstr &MI : MBB) {
  1121. LLVM_DEBUG(
  1122. dbgs() << "\n>> " << MI << "Regs:";
  1123. dumpState()
  1124. );
  1125. // Special handling for debug values. Note that they are not allowed to
  1126. // affect codegen of the other instructions in any way.
  1127. if (MI.isDebugValue()) {
  1128. handleDebugValue(MI);
  1129. continue;
  1130. }
  1131. allocateInstruction(MI);
  1132. }
  1133. // Spill all physical registers holding virtual registers now.
  1134. LLVM_DEBUG(dbgs() << "Spilling live registers at end of block.\n");
  1135. spillAll(MBB.getFirstTerminator(), /*OnlyLiveOut*/ true);
  1136. // Erase all the coalesced copies. We are delaying it until now because
  1137. // LiveVirtRegs might refer to the instrs.
  1138. for (MachineInstr *MI : Coalesced)
  1139. MBB.erase(MI);
  1140. NumCoalesced += Coalesced.size();
  1141. LLVM_DEBUG(MBB.dump());
  1142. }
  1143. bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
  1144. LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
  1145. << "********** Function: " << MF.getName() << '\n');
  1146. MRI = &MF.getRegInfo();
  1147. const TargetSubtargetInfo &STI = MF.getSubtarget();
  1148. TRI = STI.getRegisterInfo();
  1149. TII = STI.getInstrInfo();
  1150. MFI = &MF.getFrameInfo();
  1151. MRI->freezeReservedRegs(MF);
  1152. RegClassInfo.runOnMachineFunction(MF);
  1153. UsedInInstr.clear();
  1154. UsedInInstr.setUniverse(TRI->getNumRegUnits());
  1155. // initialize the virtual->physical register map to have a 'null'
  1156. // mapping for all virtual registers
  1157. unsigned NumVirtRegs = MRI->getNumVirtRegs();
  1158. StackSlotForVirtReg.resize(NumVirtRegs);
  1159. LiveVirtRegs.setUniverse(NumVirtRegs);
  1160. MayLiveAcrossBlocks.clear();
  1161. MayLiveAcrossBlocks.resize(NumVirtRegs);
  1162. // Loop over all of the basic blocks, eliminating virtual register references
  1163. for (MachineBasicBlock &MBB : MF)
  1164. allocateBasicBlock(MBB);
  1165. // All machine operands and other references to virtual registers have been
  1166. // replaced. Remove the virtual registers.
  1167. MRI->clearVirtRegs();
  1168. StackSlotForVirtReg.clear();
  1169. LiveDbgValueMap.clear();
  1170. return true;
  1171. }
  1172. FunctionPass *llvm::createFastRegisterAllocator() {
  1173. return new RegAllocFast();
  1174. }