RegAllocFast.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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/MapVector.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/SparseSet.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/CodeGen/MachineBasicBlock.h"
  23. #include "llvm/CodeGen/MachineFrameInfo.h"
  24. #include "llvm/CodeGen/MachineFunction.h"
  25. #include "llvm/CodeGen/MachineFunctionPass.h"
  26. #include "llvm/CodeGen/MachineInstr.h"
  27. #include "llvm/CodeGen/MachineInstrBuilder.h"
  28. #include "llvm/CodeGen/MachineOperand.h"
  29. #include "llvm/CodeGen/MachineRegisterInfo.h"
  30. #include "llvm/CodeGen/RegAllocCommon.h"
  31. #include "llvm/CodeGen/RegAllocRegistry.h"
  32. #include "llvm/CodeGen/RegisterClassInfo.h"
  33. #include "llvm/CodeGen/TargetInstrInfo.h"
  34. #include "llvm/CodeGen/TargetOpcodes.h"
  35. #include "llvm/CodeGen/TargetRegisterInfo.h"
  36. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  37. #include "llvm/InitializePasses.h"
  38. #include "llvm/MC/MCRegisterInfo.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include <cassert>
  44. #include <tuple>
  45. #include <vector>
  46. using namespace llvm;
  47. #define DEBUG_TYPE "regalloc"
  48. STATISTIC(NumStores, "Number of stores added");
  49. STATISTIC(NumLoads , "Number of loads added");
  50. STATISTIC(NumCoalesced, "Number of copies coalesced");
  51. // FIXME: Remove this switch when all testcases are fixed!
  52. static cl::opt<bool> IgnoreMissingDefs("rafast-ignore-missing-defs",
  53. cl::Hidden);
  54. static RegisterRegAlloc
  55. fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
  56. namespace {
  57. class RegAllocFast : public MachineFunctionPass {
  58. public:
  59. static char ID;
  60. RegAllocFast(const RegClassFilterFunc F = allocateAllRegClasses,
  61. bool ClearVirtRegs_ = true) :
  62. MachineFunctionPass(ID),
  63. ShouldAllocateClass(F),
  64. StackSlotForVirtReg(-1),
  65. ClearVirtRegs(ClearVirtRegs_) {
  66. }
  67. private:
  68. MachineFrameInfo *MFI;
  69. MachineRegisterInfo *MRI;
  70. const TargetRegisterInfo *TRI;
  71. const TargetInstrInfo *TII;
  72. RegisterClassInfo RegClassInfo;
  73. const RegClassFilterFunc ShouldAllocateClass;
  74. /// Basic block currently being allocated.
  75. MachineBasicBlock *MBB;
  76. /// Maps virtual regs to the frame index where these values are spilled.
  77. IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
  78. bool ClearVirtRegs;
  79. /// Everything we know about a live virtual register.
  80. struct LiveReg {
  81. MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
  82. Register VirtReg; ///< Virtual register number.
  83. MCPhysReg PhysReg = 0; ///< Currently held here.
  84. bool LiveOut = false; ///< Register is possibly live out.
  85. bool Reloaded = false; ///< Register was reloaded.
  86. bool Error = false; ///< Could not allocate.
  87. explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
  88. unsigned getSparseSetIndex() const {
  89. return Register::virtReg2Index(VirtReg);
  90. }
  91. };
  92. using LiveRegMap = SparseSet<LiveReg>;
  93. /// This map contains entries for each virtual register that is currently
  94. /// available in a physical register.
  95. LiveRegMap LiveVirtRegs;
  96. /// Stores assigned virtual registers present in the bundle MI.
  97. DenseMap<Register, MCPhysReg> BundleVirtRegsMap;
  98. DenseMap<unsigned, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
  99. /// List of DBG_VALUE that we encountered without the vreg being assigned
  100. /// because they were placed after the last use of the vreg.
  101. DenseMap<unsigned, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
  102. /// Has a bit set for every virtual register for which it was determined
  103. /// that it is alive across blocks.
  104. BitVector MayLiveAcrossBlocks;
  105. /// State of a register unit.
  106. enum RegUnitState {
  107. /// A free register is not currently in use and can be allocated
  108. /// immediately without checking aliases.
  109. regFree,
  110. /// A pre-assigned register has been assigned before register allocation
  111. /// (e.g., setting up a call parameter).
  112. regPreAssigned,
  113. /// Used temporarily in reloadAtBegin() to mark register units that are
  114. /// live-in to the basic block.
  115. regLiveIn,
  116. /// A register state may also be a virtual register number, indication
  117. /// that the physical register is currently allocated to a virtual
  118. /// register. In that case, LiveVirtRegs contains the inverse mapping.
  119. };
  120. /// Maps each physical register to a RegUnitState enum or virtual register.
  121. std::vector<unsigned> RegUnitStates;
  122. SmallVector<MachineInstr *, 32> Coalesced;
  123. using RegUnitSet = SparseSet<uint16_t, identity<uint16_t>>;
  124. /// Set of register units that are used in the current instruction, and so
  125. /// cannot be allocated.
  126. RegUnitSet UsedInInstr;
  127. RegUnitSet PhysRegUses;
  128. SmallVector<uint16_t, 8> DefOperandIndexes;
  129. // Register masks attached to the current instruction.
  130. SmallVector<const uint32_t *> RegMasks;
  131. void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
  132. bool isPhysRegFree(MCPhysReg PhysReg) const;
  133. /// Mark a physreg as used in this instruction.
  134. void markRegUsedInInstr(MCPhysReg PhysReg) {
  135. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
  136. UsedInInstr.insert(*Units);
  137. }
  138. // Check if physreg is clobbered by instruction's regmask(s).
  139. bool isClobberedByRegMasks(MCPhysReg PhysReg) const {
  140. return llvm::any_of(RegMasks, [PhysReg](const uint32_t *Mask) {
  141. return MachineOperand::clobbersPhysReg(Mask, PhysReg);
  142. });
  143. }
  144. /// Check if a physreg or any of its aliases are used in this instruction.
  145. bool isRegUsedInInstr(MCPhysReg PhysReg, bool LookAtPhysRegUses) const {
  146. if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
  147. return true;
  148. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  149. if (UsedInInstr.count(*Units))
  150. return true;
  151. if (LookAtPhysRegUses && PhysRegUses.count(*Units))
  152. return true;
  153. }
  154. return false;
  155. }
  156. /// Mark physical register as being used in a register use operand.
  157. /// This is only used by the special livethrough handling code.
  158. void markPhysRegUsedInInstr(MCPhysReg PhysReg) {
  159. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
  160. PhysRegUses.insert(*Units);
  161. }
  162. /// Remove mark of physical register being used in the instruction.
  163. void unmarkRegUsedInInstr(MCPhysReg PhysReg) {
  164. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
  165. UsedInInstr.erase(*Units);
  166. }
  167. enum : unsigned {
  168. spillClean = 50,
  169. spillDirty = 100,
  170. spillPrefBonus = 20,
  171. spillImpossible = ~0u
  172. };
  173. public:
  174. StringRef getPassName() const override { return "Fast Register Allocator"; }
  175. void getAnalysisUsage(AnalysisUsage &AU) const override {
  176. AU.setPreservesCFG();
  177. MachineFunctionPass::getAnalysisUsage(AU);
  178. }
  179. MachineFunctionProperties getRequiredProperties() const override {
  180. return MachineFunctionProperties().set(
  181. MachineFunctionProperties::Property::NoPHIs);
  182. }
  183. MachineFunctionProperties getSetProperties() const override {
  184. if (ClearVirtRegs) {
  185. return MachineFunctionProperties().set(
  186. MachineFunctionProperties::Property::NoVRegs);
  187. }
  188. return MachineFunctionProperties();
  189. }
  190. MachineFunctionProperties getClearedProperties() const override {
  191. return MachineFunctionProperties().set(
  192. MachineFunctionProperties::Property::IsSSA);
  193. }
  194. private:
  195. bool runOnMachineFunction(MachineFunction &MF) override;
  196. void allocateBasicBlock(MachineBasicBlock &MBB);
  197. void addRegClassDefCounts(std::vector<unsigned> &RegClassDefCounts,
  198. Register Reg) const;
  199. void allocateInstruction(MachineInstr &MI);
  200. void handleDebugValue(MachineInstr &MI);
  201. void handleBundle(MachineInstr &MI);
  202. bool usePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
  203. bool definePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
  204. bool displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
  205. void freePhysReg(MCPhysReg PhysReg);
  206. unsigned calcSpillCost(MCPhysReg PhysReg) const;
  207. LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
  208. return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
  209. }
  210. LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
  211. return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
  212. }
  213. void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCPhysReg PhysReg);
  214. void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
  215. bool LookAtPhysRegUses = false);
  216. void allocVirtRegUndef(MachineOperand &MO);
  217. void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
  218. MCPhysReg Reg);
  219. void defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
  220. Register VirtReg);
  221. void defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
  222. bool LookAtPhysRegUses = false);
  223. void useVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg);
  224. MachineBasicBlock::iterator
  225. getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
  226. SmallSet<Register, 2> &PrologLiveIns) const;
  227. void reloadAtBegin(MachineBasicBlock &MBB);
  228. void setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
  229. Register traceCopies(Register VirtReg) const;
  230. Register traceCopyChain(Register Reg) const;
  231. bool shouldAllocateRegister(const Register Reg) const;
  232. int getStackSpaceFor(Register VirtReg);
  233. void spill(MachineBasicBlock::iterator Before, Register VirtReg,
  234. MCPhysReg AssignedReg, bool Kill, bool LiveOut);
  235. void reload(MachineBasicBlock::iterator Before, Register VirtReg,
  236. MCPhysReg PhysReg);
  237. bool mayLiveOut(Register VirtReg);
  238. bool mayLiveIn(Register VirtReg);
  239. void dumpState() const;
  240. };
  241. } // end anonymous namespace
  242. char RegAllocFast::ID = 0;
  243. INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
  244. false)
  245. bool RegAllocFast::shouldAllocateRegister(const Register Reg) const {
  246. assert(Reg.isVirtual());
  247. const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
  248. return ShouldAllocateClass(*TRI, RC);
  249. }
  250. void RegAllocFast::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
  251. for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI)
  252. RegUnitStates[*UI] = NewState;
  253. }
  254. bool RegAllocFast::isPhysRegFree(MCPhysReg PhysReg) const {
  255. for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
  256. if (RegUnitStates[*UI] != regFree)
  257. return false;
  258. }
  259. return true;
  260. }
  261. /// This allocates space for the specified virtual register to be held on the
  262. /// stack.
  263. int RegAllocFast::getStackSpaceFor(Register VirtReg) {
  264. // Find the location Reg would belong...
  265. int SS = StackSlotForVirtReg[VirtReg];
  266. // Already has space allocated?
  267. if (SS != -1)
  268. return SS;
  269. // Allocate a new stack object for this spill location...
  270. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  271. unsigned Size = TRI->getSpillSize(RC);
  272. Align Alignment = TRI->getSpillAlign(RC);
  273. int FrameIdx = MFI->CreateSpillStackObject(Size, Alignment);
  274. // Assign the slot.
  275. StackSlotForVirtReg[VirtReg] = FrameIdx;
  276. return FrameIdx;
  277. }
  278. static bool dominates(MachineBasicBlock &MBB,
  279. MachineBasicBlock::const_iterator A,
  280. MachineBasicBlock::const_iterator B) {
  281. auto MBBEnd = MBB.end();
  282. if (B == MBBEnd)
  283. return true;
  284. MachineBasicBlock::const_iterator I = MBB.begin();
  285. for (; &*I != A && &*I != B; ++I)
  286. ;
  287. return &*I == A;
  288. }
  289. /// Returns false if \p VirtReg is known to not live out of the current block.
  290. bool RegAllocFast::mayLiveOut(Register VirtReg) {
  291. if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg))) {
  292. // Cannot be live-out if there are no successors.
  293. return !MBB->succ_empty();
  294. }
  295. const MachineInstr *SelfLoopDef = nullptr;
  296. // If this block loops back to itself, it is necessary to check whether the
  297. // use comes after the def.
  298. if (MBB->isSuccessor(MBB)) {
  299. // Find the first def in the self loop MBB.
  300. for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
  301. if (DefInst.getParent() != MBB) {
  302. MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
  303. return true;
  304. } else {
  305. if (!SelfLoopDef || dominates(*MBB, DefInst.getIterator(), SelfLoopDef))
  306. SelfLoopDef = &DefInst;
  307. }
  308. }
  309. if (!SelfLoopDef) {
  310. MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
  311. return true;
  312. }
  313. }
  314. // See if the first \p Limit uses of the register are all in the current
  315. // block.
  316. static const unsigned Limit = 8;
  317. unsigned C = 0;
  318. for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
  319. if (UseInst.getParent() != MBB || ++C >= Limit) {
  320. MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
  321. // Cannot be live-out if there are no successors.
  322. return !MBB->succ_empty();
  323. }
  324. if (SelfLoopDef) {
  325. // Try to handle some simple cases to avoid spilling and reloading every
  326. // value inside a self looping block.
  327. if (SelfLoopDef == &UseInst ||
  328. !dominates(*MBB, SelfLoopDef->getIterator(), UseInst.getIterator())) {
  329. MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
  330. return true;
  331. }
  332. }
  333. }
  334. return false;
  335. }
  336. /// Returns false if \p VirtReg is known to not be live into the current block.
  337. bool RegAllocFast::mayLiveIn(Register VirtReg) {
  338. if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg)))
  339. return !MBB->pred_empty();
  340. // See if the first \p Limit def of the register are all in the current block.
  341. static const unsigned Limit = 8;
  342. unsigned C = 0;
  343. for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
  344. if (DefInst.getParent() != MBB || ++C >= Limit) {
  345. MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
  346. return !MBB->pred_empty();
  347. }
  348. }
  349. return false;
  350. }
  351. /// Insert spill instruction for \p AssignedReg before \p Before. Update
  352. /// DBG_VALUEs with \p VirtReg operands with the stack slot.
  353. void RegAllocFast::spill(MachineBasicBlock::iterator Before, Register VirtReg,
  354. MCPhysReg AssignedReg, bool Kill, bool LiveOut) {
  355. LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI)
  356. << " in " << printReg(AssignedReg, TRI));
  357. int FI = getStackSpaceFor(VirtReg);
  358. LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
  359. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  360. TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI,
  361. VirtReg);
  362. ++NumStores;
  363. MachineBasicBlock::iterator FirstTerm = MBB->getFirstTerminator();
  364. // When we spill a virtual register, we will have spill instructions behind
  365. // every definition of it, meaning we can switch all the DBG_VALUEs over
  366. // to just reference the stack slot.
  367. SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
  368. SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
  369. SpilledOperandsMap;
  370. for (MachineOperand *MO : LRIDbgOperands)
  371. SpilledOperandsMap[MO->getParent()].push_back(MO);
  372. for (auto MISpilledOperands : SpilledOperandsMap) {
  373. MachineInstr &DBG = *MISpilledOperands.first;
  374. // We don't have enough support for tracking operands of DBG_VALUE_LISTs.
  375. if (DBG.isDebugValueList())
  376. continue;
  377. MachineInstr *NewDV = buildDbgValueForSpill(
  378. *MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
  379. assert(NewDV->getParent() == MBB && "dangling parent pointer");
  380. (void)NewDV;
  381. LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
  382. if (LiveOut) {
  383. // We need to insert a DBG_VALUE at the end of the block if the spill slot
  384. // is live out, but there is another use of the value after the
  385. // spill. This will allow LiveDebugValues to see the correct live out
  386. // value to propagate to the successors.
  387. MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
  388. MBB->insert(FirstTerm, ClonedDV);
  389. LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
  390. }
  391. // Rewrite unassigned dbg_values to use the stack slot.
  392. // TODO We can potentially do this for list debug values as well if we know
  393. // how the dbg_values are getting unassigned.
  394. if (DBG.isNonListDebugValue()) {
  395. MachineOperand &MO = DBG.getDebugOperand(0);
  396. if (MO.isReg() && MO.getReg() == 0) {
  397. updateDbgValueForSpill(DBG, FI, 0);
  398. }
  399. }
  400. }
  401. // Now this register is spilled there is should not be any DBG_VALUE
  402. // pointing to this register because they are all pointing to spilled value
  403. // now.
  404. LRIDbgOperands.clear();
  405. }
  406. /// Insert reload instruction for \p PhysReg before \p Before.
  407. void RegAllocFast::reload(MachineBasicBlock::iterator Before, Register VirtReg,
  408. MCPhysReg PhysReg) {
  409. LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
  410. << printReg(PhysReg, TRI) << '\n');
  411. int FI = getStackSpaceFor(VirtReg);
  412. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  413. TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI, VirtReg);
  414. ++NumLoads;
  415. }
  416. /// Get basic block begin insertion point.
  417. /// This is not just MBB.begin() because surprisingly we have EH_LABEL
  418. /// instructions marking the begin of a basic block. This means we must insert
  419. /// new instructions after such labels...
  420. MachineBasicBlock::iterator
  421. RegAllocFast::getMBBBeginInsertionPoint(
  422. MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
  423. MachineBasicBlock::iterator I = MBB.begin();
  424. while (I != MBB.end()) {
  425. if (I->isLabel()) {
  426. ++I;
  427. continue;
  428. }
  429. // Most reloads should be inserted after prolog instructions.
  430. if (!TII->isBasicBlockPrologue(*I))
  431. break;
  432. // However if a prolog instruction reads a register that needs to be
  433. // reloaded, the reload should be inserted before the prolog.
  434. for (MachineOperand &MO : I->operands()) {
  435. if (MO.isReg())
  436. PrologLiveIns.insert(MO.getReg());
  437. }
  438. ++I;
  439. }
  440. return I;
  441. }
  442. /// Reload all currently assigned virtual registers.
  443. void RegAllocFast::reloadAtBegin(MachineBasicBlock &MBB) {
  444. if (LiveVirtRegs.empty())
  445. return;
  446. for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
  447. MCPhysReg Reg = P.PhysReg;
  448. // Set state to live-in. This possibly overrides mappings to virtual
  449. // registers but we don't care anymore at this point.
  450. setPhysRegState(Reg, regLiveIn);
  451. }
  452. SmallSet<Register, 2> PrologLiveIns;
  453. // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
  454. // of spilling here is deterministic, if arbitrary.
  455. MachineBasicBlock::iterator InsertBefore
  456. = getMBBBeginInsertionPoint(MBB, PrologLiveIns);
  457. for (const LiveReg &LR : LiveVirtRegs) {
  458. MCPhysReg PhysReg = LR.PhysReg;
  459. if (PhysReg == 0)
  460. continue;
  461. MCRegister FirstUnit = *MCRegUnitIterator(PhysReg, TRI);
  462. if (RegUnitStates[FirstUnit] == regLiveIn)
  463. continue;
  464. assert((&MBB != &MBB.getParent()->front() || IgnoreMissingDefs) &&
  465. "no reload in start block. Missing vreg def?");
  466. if (PrologLiveIns.count(PhysReg)) {
  467. // FIXME: Theoretically this should use an insert point skipping labels
  468. // but I'm not sure how labels should interact with prolog instruction
  469. // that need reloads.
  470. reload(MBB.begin(), LR.VirtReg, PhysReg);
  471. } else
  472. reload(InsertBefore, LR.VirtReg, PhysReg);
  473. }
  474. LiveVirtRegs.clear();
  475. }
  476. /// Handle the direct use of a physical register. Check that the register is
  477. /// not used by a virtreg. Kill the physreg, marking it free. This may add
  478. /// implicit kills to MO->getParent() and invalidate MO.
  479. bool RegAllocFast::usePhysReg(MachineInstr &MI, MCPhysReg Reg) {
  480. assert(Register::isPhysicalRegister(Reg) && "expected physreg");
  481. bool displacedAny = displacePhysReg(MI, Reg);
  482. setPhysRegState(Reg, regPreAssigned);
  483. markRegUsedInInstr(Reg);
  484. return displacedAny;
  485. }
  486. bool RegAllocFast::definePhysReg(MachineInstr &MI, MCPhysReg Reg) {
  487. bool displacedAny = displacePhysReg(MI, Reg);
  488. setPhysRegState(Reg, regPreAssigned);
  489. return displacedAny;
  490. }
  491. /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
  492. /// similar to defineVirtReg except the physreg is reserved instead of
  493. /// allocated.
  494. bool RegAllocFast::displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg) {
  495. bool displacedAny = false;
  496. for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
  497. unsigned Unit = *UI;
  498. switch (unsigned VirtReg = RegUnitStates[Unit]) {
  499. default: {
  500. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  501. assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
  502. MachineBasicBlock::iterator ReloadBefore =
  503. std::next((MachineBasicBlock::iterator)MI.getIterator());
  504. reload(ReloadBefore, VirtReg, LRI->PhysReg);
  505. setPhysRegState(LRI->PhysReg, regFree);
  506. LRI->PhysReg = 0;
  507. LRI->Reloaded = true;
  508. displacedAny = true;
  509. break;
  510. }
  511. case regPreAssigned:
  512. RegUnitStates[Unit] = regFree;
  513. displacedAny = true;
  514. break;
  515. case regFree:
  516. break;
  517. }
  518. }
  519. return displacedAny;
  520. }
  521. void RegAllocFast::freePhysReg(MCPhysReg PhysReg) {
  522. LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
  523. MCRegister FirstUnit = *MCRegUnitIterator(PhysReg, TRI);
  524. switch (unsigned VirtReg = RegUnitStates[FirstUnit]) {
  525. case regFree:
  526. LLVM_DEBUG(dbgs() << '\n');
  527. return;
  528. case regPreAssigned:
  529. LLVM_DEBUG(dbgs() << '\n');
  530. setPhysRegState(PhysReg, regFree);
  531. return;
  532. default: {
  533. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  534. assert(LRI != LiveVirtRegs.end());
  535. LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
  536. setPhysRegState(LRI->PhysReg, regFree);
  537. LRI->PhysReg = 0;
  538. }
  539. return;
  540. }
  541. }
  542. /// Return the cost of spilling clearing out PhysReg and aliases so it is free
  543. /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
  544. /// disabled - it can be allocated directly.
  545. /// \returns spillImpossible when PhysReg or an alias can't be spilled.
  546. unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
  547. for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
  548. switch (unsigned VirtReg = RegUnitStates[*UI]) {
  549. case regFree:
  550. break;
  551. case regPreAssigned:
  552. LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
  553. << printReg(PhysReg, TRI) << '\n');
  554. return spillImpossible;
  555. default: {
  556. bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
  557. findLiveVirtReg(VirtReg)->LiveOut;
  558. return SureSpill ? spillClean : spillDirty;
  559. }
  560. }
  561. }
  562. return 0;
  563. }
  564. void RegAllocFast::assignDanglingDebugValues(MachineInstr &Definition,
  565. Register VirtReg, MCPhysReg Reg) {
  566. auto UDBGValIter = DanglingDbgValues.find(VirtReg);
  567. if (UDBGValIter == DanglingDbgValues.end())
  568. return;
  569. SmallVectorImpl<MachineInstr*> &Dangling = UDBGValIter->second;
  570. for (MachineInstr *DbgValue : Dangling) {
  571. assert(DbgValue->isDebugValue());
  572. if (!DbgValue->hasDebugOperandForReg(VirtReg))
  573. continue;
  574. // Test whether the physreg survives from the definition to the DBG_VALUE.
  575. MCPhysReg SetToReg = Reg;
  576. unsigned Limit = 20;
  577. for (MachineBasicBlock::iterator I = std::next(Definition.getIterator()),
  578. E = DbgValue->getIterator(); I != E; ++I) {
  579. if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
  580. LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
  581. << '\n');
  582. SetToReg = 0;
  583. break;
  584. }
  585. }
  586. for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
  587. MO.setReg(SetToReg);
  588. if (SetToReg != 0)
  589. MO.setIsRenamable();
  590. }
  591. }
  592. Dangling.clear();
  593. }
  594. /// This method updates local state so that we know that PhysReg is the
  595. /// proper container for VirtReg now. The physical register must not be used
  596. /// for anything else when this is called.
  597. void RegAllocFast::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
  598. MCPhysReg PhysReg) {
  599. Register VirtReg = LR.VirtReg;
  600. LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
  601. << printReg(PhysReg, TRI) << '\n');
  602. assert(LR.PhysReg == 0 && "Already assigned a physreg");
  603. assert(PhysReg != 0 && "Trying to assign no register");
  604. LR.PhysReg = PhysReg;
  605. setPhysRegState(PhysReg, VirtReg);
  606. assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
  607. }
  608. static bool isCoalescable(const MachineInstr &MI) {
  609. return MI.isFullCopy();
  610. }
  611. Register RegAllocFast::traceCopyChain(Register Reg) const {
  612. static const unsigned ChainLengthLimit = 3;
  613. unsigned C = 0;
  614. do {
  615. if (Reg.isPhysical())
  616. return Reg;
  617. assert(Reg.isVirtual());
  618. MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
  619. if (!VRegDef || !isCoalescable(*VRegDef))
  620. return 0;
  621. Reg = VRegDef->getOperand(1).getReg();
  622. } while (++C <= ChainLengthLimit);
  623. return 0;
  624. }
  625. /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
  626. /// chain of copies to check whether we reach a physical register we can
  627. /// coalesce with.
  628. Register RegAllocFast::traceCopies(Register VirtReg) const {
  629. static const unsigned DefLimit = 3;
  630. unsigned C = 0;
  631. for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
  632. if (isCoalescable(MI)) {
  633. Register Reg = MI.getOperand(1).getReg();
  634. Reg = traceCopyChain(Reg);
  635. if (Reg.isValid())
  636. return Reg;
  637. }
  638. if (++C >= DefLimit)
  639. break;
  640. }
  641. return Register();
  642. }
  643. /// Allocates a physical register for VirtReg.
  644. void RegAllocFast::allocVirtReg(MachineInstr &MI, LiveReg &LR,
  645. Register Hint0, bool LookAtPhysRegUses) {
  646. const Register VirtReg = LR.VirtReg;
  647. assert(LR.PhysReg == 0);
  648. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  649. LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
  650. << " in class " << TRI->getRegClassName(&RC)
  651. << " with hint " << printReg(Hint0, TRI) << '\n');
  652. // Take hint when possible.
  653. if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
  654. !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
  655. // Take hint if the register is currently free.
  656. if (isPhysRegFree(Hint0)) {
  657. LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
  658. << '\n');
  659. assignVirtToPhysReg(MI, LR, Hint0);
  660. return;
  661. } else {
  662. LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
  663. << " occupied\n");
  664. }
  665. } else {
  666. Hint0 = Register();
  667. }
  668. // Try other hint.
  669. Register Hint1 = traceCopies(VirtReg);
  670. if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
  671. !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
  672. // Take hint if the register is currently free.
  673. if (isPhysRegFree(Hint1)) {
  674. LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
  675. << '\n');
  676. assignVirtToPhysReg(MI, LR, Hint1);
  677. return;
  678. } else {
  679. LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
  680. << " occupied\n");
  681. }
  682. } else {
  683. Hint1 = Register();
  684. }
  685. MCPhysReg BestReg = 0;
  686. unsigned BestCost = spillImpossible;
  687. ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
  688. for (MCPhysReg PhysReg : AllocationOrder) {
  689. LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
  690. if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
  691. LLVM_DEBUG(dbgs() << "already used in instr.\n");
  692. continue;
  693. }
  694. unsigned Cost = calcSpillCost(PhysReg);
  695. LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
  696. // Immediate take a register with cost 0.
  697. if (Cost == 0) {
  698. assignVirtToPhysReg(MI, LR, PhysReg);
  699. return;
  700. }
  701. if (PhysReg == Hint0 || PhysReg == Hint1)
  702. Cost -= spillPrefBonus;
  703. if (Cost < BestCost) {
  704. BestReg = PhysReg;
  705. BestCost = Cost;
  706. }
  707. }
  708. if (!BestReg) {
  709. // Nothing we can do: Report an error and keep going with an invalid
  710. // allocation.
  711. if (MI.isInlineAsm())
  712. MI.emitError("inline assembly requires more registers than available");
  713. else
  714. MI.emitError("ran out of registers during register allocation");
  715. LR.Error = true;
  716. LR.PhysReg = 0;
  717. return;
  718. }
  719. displacePhysReg(MI, BestReg);
  720. assignVirtToPhysReg(MI, LR, BestReg);
  721. }
  722. void RegAllocFast::allocVirtRegUndef(MachineOperand &MO) {
  723. assert(MO.isUndef() && "expected undef use");
  724. Register VirtReg = MO.getReg();
  725. assert(VirtReg.isVirtual() && "Expected virtreg");
  726. if (!shouldAllocateRegister(VirtReg))
  727. return;
  728. LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
  729. MCPhysReg PhysReg;
  730. if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
  731. PhysReg = LRI->PhysReg;
  732. } else {
  733. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  734. ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
  735. assert(!AllocationOrder.empty() && "Allocation order must not be empty");
  736. PhysReg = AllocationOrder[0];
  737. }
  738. unsigned SubRegIdx = MO.getSubReg();
  739. if (SubRegIdx != 0) {
  740. PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
  741. MO.setSubReg(0);
  742. }
  743. MO.setReg(PhysReg);
  744. MO.setIsRenamable(true);
  745. }
  746. /// Variation of defineVirtReg() with special handling for livethrough regs
  747. /// (tied or earlyclobber) that may interfere with preassigned uses.
  748. void RegAllocFast::defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
  749. Register VirtReg) {
  750. if (!shouldAllocateRegister(VirtReg))
  751. return;
  752. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  753. if (LRI != LiveVirtRegs.end()) {
  754. MCPhysReg PrevReg = LRI->PhysReg;
  755. if (PrevReg != 0 && isRegUsedInInstr(PrevReg, true)) {
  756. LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
  757. << " (tied/earlyclobber resolution)\n");
  758. freePhysReg(PrevReg);
  759. LRI->PhysReg = 0;
  760. allocVirtReg(MI, *LRI, 0, true);
  761. MachineBasicBlock::iterator InsertBefore =
  762. std::next((MachineBasicBlock::iterator)MI.getIterator());
  763. LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
  764. << printReg(PrevReg, TRI) << '\n');
  765. BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
  766. TII->get(TargetOpcode::COPY), PrevReg)
  767. .addReg(LRI->PhysReg, llvm::RegState::Kill);
  768. }
  769. MachineOperand &MO = MI.getOperand(OpNum);
  770. if (MO.getSubReg() && !MO.isUndef()) {
  771. LRI->LastUse = &MI;
  772. }
  773. }
  774. return defineVirtReg(MI, OpNum, VirtReg, true);
  775. }
  776. /// Allocates a register for VirtReg definition. Typically the register is
  777. /// already assigned from a use of the virtreg, however we still need to
  778. /// perform an allocation if:
  779. /// - It is a dead definition without any uses.
  780. /// - The value is live out and all uses are in different basic blocks.
  781. void RegAllocFast::defineVirtReg(MachineInstr &MI, unsigned OpNum,
  782. Register VirtReg, bool LookAtPhysRegUses) {
  783. assert(VirtReg.isVirtual() && "Not a virtual register");
  784. if (!shouldAllocateRegister(VirtReg))
  785. return;
  786. MachineOperand &MO = MI.getOperand(OpNum);
  787. LiveRegMap::iterator LRI;
  788. bool New;
  789. std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
  790. if (New) {
  791. if (!MO.isDead()) {
  792. if (mayLiveOut(VirtReg)) {
  793. LRI->LiveOut = true;
  794. } else {
  795. // It is a dead def without the dead flag; add the flag now.
  796. MO.setIsDead(true);
  797. }
  798. }
  799. }
  800. if (LRI->PhysReg == 0)
  801. allocVirtReg(MI, *LRI, 0, LookAtPhysRegUses);
  802. else {
  803. assert(!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) &&
  804. "TODO: preassign mismatch");
  805. LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
  806. << " use existing assignment to "
  807. << printReg(LRI->PhysReg, TRI) << '\n');
  808. }
  809. MCPhysReg PhysReg = LRI->PhysReg;
  810. assert(PhysReg != 0 && "Register not assigned");
  811. if (LRI->Reloaded || LRI->LiveOut) {
  812. if (!MI.isImplicitDef()) {
  813. MachineBasicBlock::iterator SpillBefore =
  814. std::next((MachineBasicBlock::iterator)MI.getIterator());
  815. LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut << " RL: "
  816. << LRI->Reloaded << '\n');
  817. bool Kill = LRI->LastUse == nullptr;
  818. spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
  819. LRI->LastUse = nullptr;
  820. }
  821. LRI->LiveOut = false;
  822. LRI->Reloaded = false;
  823. }
  824. if (MI.getOpcode() == TargetOpcode::BUNDLE) {
  825. BundleVirtRegsMap[VirtReg] = PhysReg;
  826. }
  827. markRegUsedInInstr(PhysReg);
  828. setPhysReg(MI, MO, PhysReg);
  829. }
  830. /// Allocates a register for a VirtReg use.
  831. void RegAllocFast::useVirtReg(MachineInstr &MI, unsigned OpNum,
  832. Register VirtReg) {
  833. assert(VirtReg.isVirtual() && "Not a virtual register");
  834. if (!shouldAllocateRegister(VirtReg))
  835. return;
  836. MachineOperand &MO = MI.getOperand(OpNum);
  837. LiveRegMap::iterator LRI;
  838. bool New;
  839. std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
  840. if (New) {
  841. MachineOperand &MO = MI.getOperand(OpNum);
  842. if (!MO.isKill()) {
  843. if (mayLiveOut(VirtReg)) {
  844. LRI->LiveOut = true;
  845. } else {
  846. // It is a last (killing) use without the kill flag; add the flag now.
  847. MO.setIsKill(true);
  848. }
  849. }
  850. } else {
  851. assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
  852. }
  853. // If necessary allocate a register.
  854. if (LRI->PhysReg == 0) {
  855. assert(!MO.isTied() && "tied op should be allocated");
  856. Register Hint;
  857. if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
  858. Hint = MI.getOperand(0).getReg();
  859. if (Hint.isVirtual()) {
  860. assert(!shouldAllocateRegister(Hint));
  861. Hint = Register();
  862. } else {
  863. assert(Hint.isPhysical() &&
  864. "Copy destination should already be assigned");
  865. }
  866. }
  867. allocVirtReg(MI, *LRI, Hint, false);
  868. if (LRI->Error) {
  869. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
  870. ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
  871. setPhysReg(MI, MO, *AllocationOrder.begin());
  872. return;
  873. }
  874. }
  875. LRI->LastUse = &MI;
  876. if (MI.getOpcode() == TargetOpcode::BUNDLE) {
  877. BundleVirtRegsMap[VirtReg] = LRI->PhysReg;
  878. }
  879. markRegUsedInInstr(LRI->PhysReg);
  880. setPhysReg(MI, MO, LRI->PhysReg);
  881. }
  882. /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
  883. /// may invalidate any operand pointers. Return true if the operand kills its
  884. /// register.
  885. void RegAllocFast::setPhysReg(MachineInstr &MI, MachineOperand &MO,
  886. MCPhysReg PhysReg) {
  887. if (!MO.getSubReg()) {
  888. MO.setReg(PhysReg);
  889. MO.setIsRenamable(true);
  890. return;
  891. }
  892. // Handle subregister index.
  893. MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : MCRegister());
  894. MO.setIsRenamable(true);
  895. // Note: We leave the subreg number around a little longer in case of defs.
  896. // This is so that the register freeing logic in allocateInstruction can still
  897. // recognize this as subregister defs. The code there will clear the number.
  898. if (!MO.isDef())
  899. MO.setSubReg(0);
  900. // A kill flag implies killing the full register. Add corresponding super
  901. // register kill.
  902. if (MO.isKill()) {
  903. MI.addRegisterKilled(PhysReg, TRI, true);
  904. return;
  905. }
  906. // A <def,read-undef> of a sub-register requires an implicit def of the full
  907. // register.
  908. if (MO.isDef() && MO.isUndef()) {
  909. if (MO.isDead())
  910. MI.addRegisterDead(PhysReg, TRI, true);
  911. else
  912. MI.addRegisterDefined(PhysReg, TRI);
  913. }
  914. }
  915. #ifndef NDEBUG
  916. void RegAllocFast::dumpState() const {
  917. for (unsigned Unit = 1, UnitE = TRI->getNumRegUnits(); Unit != UnitE;
  918. ++Unit) {
  919. switch (unsigned VirtReg = RegUnitStates[Unit]) {
  920. case regFree:
  921. break;
  922. case regPreAssigned:
  923. dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
  924. break;
  925. case regLiveIn:
  926. llvm_unreachable("Should not have regLiveIn in map");
  927. default: {
  928. dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
  929. LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
  930. assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
  931. if (I->LiveOut || I->Reloaded) {
  932. dbgs() << '[';
  933. if (I->LiveOut) dbgs() << 'O';
  934. if (I->Reloaded) dbgs() << 'R';
  935. dbgs() << ']';
  936. }
  937. assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
  938. break;
  939. }
  940. }
  941. }
  942. dbgs() << '\n';
  943. // Check that LiveVirtRegs is the inverse.
  944. for (const LiveReg &LR : LiveVirtRegs) {
  945. Register VirtReg = LR.VirtReg;
  946. assert(VirtReg.isVirtual() && "Bad map key");
  947. MCPhysReg PhysReg = LR.PhysReg;
  948. if (PhysReg != 0) {
  949. assert(Register::isPhysicalRegister(PhysReg) &&
  950. "mapped to physreg");
  951. for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
  952. assert(RegUnitStates[*UI] == VirtReg && "inverse map valid");
  953. }
  954. }
  955. }
  956. }
  957. #endif
  958. /// Count number of defs consumed from each register class by \p Reg
  959. void RegAllocFast::addRegClassDefCounts(std::vector<unsigned> &RegClassDefCounts,
  960. Register Reg) const {
  961. assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
  962. if (Reg.isVirtual()) {
  963. if (!shouldAllocateRegister(Reg))
  964. return;
  965. const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
  966. for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
  967. RCIdx != RCIdxEnd; ++RCIdx) {
  968. const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
  969. // FIXME: Consider aliasing sub/super registers.
  970. if (OpRC->hasSubClassEq(IdxRC))
  971. ++RegClassDefCounts[RCIdx];
  972. }
  973. return;
  974. }
  975. for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
  976. RCIdx != RCIdxEnd; ++RCIdx) {
  977. const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
  978. for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
  979. if (IdxRC->contains(*Alias)) {
  980. ++RegClassDefCounts[RCIdx];
  981. break;
  982. }
  983. }
  984. }
  985. }
  986. void RegAllocFast::allocateInstruction(MachineInstr &MI) {
  987. // The basic algorithm here is:
  988. // 1. Mark registers of def operands as free
  989. // 2. Allocate registers to use operands and place reload instructions for
  990. // registers displaced by the allocation.
  991. //
  992. // However we need to handle some corner cases:
  993. // - pre-assigned defs and uses need to be handled before the other def/use
  994. // operands are processed to avoid the allocation heuristics clashing with
  995. // the pre-assignment.
  996. // - The "free def operands" step has to come last instead of first for tied
  997. // operands and early-clobbers.
  998. UsedInInstr.clear();
  999. RegMasks.clear();
  1000. BundleVirtRegsMap.clear();
  1001. auto TiedOpIsUndef = [&](const MachineOperand &MO, unsigned Idx) {
  1002. assert(MO.isTied());
  1003. unsigned TiedIdx = MI.findTiedOperandIdx(Idx);
  1004. const MachineOperand &TiedMO = MI.getOperand(TiedIdx);
  1005. return TiedMO.isUndef();
  1006. };
  1007. // Scan for special cases; Apply pre-assigned register defs to state.
  1008. bool HasPhysRegUse = false;
  1009. bool HasRegMask = false;
  1010. bool HasVRegDef = false;
  1011. bool HasDef = false;
  1012. bool HasEarlyClobber = false;
  1013. bool NeedToAssignLiveThroughs = false;
  1014. for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
  1015. MachineOperand &MO = MI.getOperand(I);
  1016. if (MO.isReg()) {
  1017. Register Reg = MO.getReg();
  1018. if (Reg.isVirtual()) {
  1019. if (!shouldAllocateRegister(Reg))
  1020. continue;
  1021. if (MO.isDef()) {
  1022. HasDef = true;
  1023. HasVRegDef = true;
  1024. if (MO.isEarlyClobber()) {
  1025. HasEarlyClobber = true;
  1026. NeedToAssignLiveThroughs = true;
  1027. }
  1028. if ((MO.isTied() && !TiedOpIsUndef(MO, I)) ||
  1029. (MO.getSubReg() != 0 && !MO.isUndef()))
  1030. NeedToAssignLiveThroughs = true;
  1031. }
  1032. } else if (Reg.isPhysical()) {
  1033. if (!MRI->isReserved(Reg)) {
  1034. if (MO.isDef()) {
  1035. HasDef = true;
  1036. bool displacedAny = definePhysReg(MI, Reg);
  1037. if (MO.isEarlyClobber())
  1038. HasEarlyClobber = true;
  1039. if (!displacedAny)
  1040. MO.setIsDead(true);
  1041. }
  1042. if (MO.readsReg())
  1043. HasPhysRegUse = true;
  1044. }
  1045. }
  1046. } else if (MO.isRegMask()) {
  1047. HasRegMask = true;
  1048. RegMasks.push_back(MO.getRegMask());
  1049. }
  1050. }
  1051. // Allocate virtreg defs.
  1052. if (HasDef) {
  1053. if (HasVRegDef) {
  1054. // Special handling for early clobbers, tied operands or subregister defs:
  1055. // Compared to "normal" defs these:
  1056. // - Must not use a register that is pre-assigned for a use operand.
  1057. // - In order to solve tricky inline assembly constraints we change the
  1058. // heuristic to figure out a good operand order before doing
  1059. // assignments.
  1060. if (NeedToAssignLiveThroughs) {
  1061. DefOperandIndexes.clear();
  1062. PhysRegUses.clear();
  1063. // Track number of defs which may consume a register from the class.
  1064. std::vector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
  1065. assert(RegClassDefCounts[0] == 0);
  1066. LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
  1067. for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
  1068. const MachineOperand &MO = MI.getOperand(I);
  1069. if (!MO.isReg())
  1070. continue;
  1071. Register Reg = MO.getReg();
  1072. if (MO.readsReg()) {
  1073. if (Reg.isPhysical()) {
  1074. LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI)
  1075. << '\n');
  1076. markPhysRegUsedInInstr(Reg);
  1077. }
  1078. }
  1079. if (MO.isDef()) {
  1080. if (Reg.isVirtual() && shouldAllocateRegister(Reg))
  1081. DefOperandIndexes.push_back(I);
  1082. addRegClassDefCounts(RegClassDefCounts, Reg);
  1083. }
  1084. }
  1085. llvm::sort(DefOperandIndexes, [&](uint16_t I0, uint16_t I1) {
  1086. const MachineOperand &MO0 = MI.getOperand(I0);
  1087. const MachineOperand &MO1 = MI.getOperand(I1);
  1088. Register Reg0 = MO0.getReg();
  1089. Register Reg1 = MO1.getReg();
  1090. const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
  1091. const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
  1092. // Identify regclass that are easy to use up completely just in this
  1093. // instruction.
  1094. unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
  1095. unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
  1096. bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
  1097. bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
  1098. if (SmallClass0 > SmallClass1)
  1099. return true;
  1100. if (SmallClass0 < SmallClass1)
  1101. return false;
  1102. // Allocate early clobbers and livethrough operands first.
  1103. bool Livethrough0 = MO0.isEarlyClobber() || MO0.isTied() ||
  1104. (MO0.getSubReg() == 0 && !MO0.isUndef());
  1105. bool Livethrough1 = MO1.isEarlyClobber() || MO1.isTied() ||
  1106. (MO1.getSubReg() == 0 && !MO1.isUndef());
  1107. if (Livethrough0 > Livethrough1)
  1108. return true;
  1109. if (Livethrough0 < Livethrough1)
  1110. return false;
  1111. // Tie-break rule: operand index.
  1112. return I0 < I1;
  1113. });
  1114. for (uint16_t OpIdx : DefOperandIndexes) {
  1115. MachineOperand &MO = MI.getOperand(OpIdx);
  1116. LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
  1117. unsigned Reg = MO.getReg();
  1118. if (MO.isEarlyClobber() ||
  1119. (MO.isTied() && !TiedOpIsUndef(MO, OpIdx)) ||
  1120. (MO.getSubReg() && !MO.isUndef())) {
  1121. defineLiveThroughVirtReg(MI, OpIdx, Reg);
  1122. } else {
  1123. defineVirtReg(MI, OpIdx, Reg);
  1124. }
  1125. }
  1126. } else {
  1127. // Assign virtual register defs.
  1128. for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
  1129. MachineOperand &MO = MI.getOperand(I);
  1130. if (!MO.isReg() || !MO.isDef())
  1131. continue;
  1132. Register Reg = MO.getReg();
  1133. if (Reg.isVirtual())
  1134. defineVirtReg(MI, I, Reg);
  1135. }
  1136. }
  1137. }
  1138. // Free registers occupied by defs.
  1139. // Iterate operands in reverse order, so we see the implicit super register
  1140. // defs first (we added them earlier in case of <def,read-undef>).
  1141. for (signed I = MI.getNumOperands() - 1; I >= 0; --I) {
  1142. MachineOperand &MO = MI.getOperand(I);
  1143. if (!MO.isReg() || !MO.isDef())
  1144. continue;
  1145. // subreg defs don't free the full register. We left the subreg number
  1146. // around as a marker in setPhysReg() to recognize this case here.
  1147. if (MO.getSubReg() != 0) {
  1148. MO.setSubReg(0);
  1149. continue;
  1150. }
  1151. assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
  1152. "tied def assigned to clobbered register");
  1153. // Do not free tied operands and early clobbers.
  1154. if ((MO.isTied() && !TiedOpIsUndef(MO, I)) || MO.isEarlyClobber())
  1155. continue;
  1156. Register Reg = MO.getReg();
  1157. if (!Reg)
  1158. continue;
  1159. if (Reg.isVirtual()) {
  1160. assert(!shouldAllocateRegister(Reg));
  1161. continue;
  1162. }
  1163. assert(Reg.isPhysical());
  1164. if (MRI->isReserved(Reg))
  1165. continue;
  1166. freePhysReg(Reg);
  1167. unmarkRegUsedInInstr(Reg);
  1168. }
  1169. }
  1170. // Displace clobbered registers.
  1171. if (HasRegMask) {
  1172. assert(!RegMasks.empty() && "expected RegMask");
  1173. // MRI bookkeeping.
  1174. for (const auto *RM : RegMasks)
  1175. MRI->addPhysRegsUsedFromRegMask(RM);
  1176. // Displace clobbered registers.
  1177. for (const LiveReg &LR : LiveVirtRegs) {
  1178. MCPhysReg PhysReg = LR.PhysReg;
  1179. if (PhysReg != 0 && isClobberedByRegMasks(PhysReg))
  1180. displacePhysReg(MI, PhysReg);
  1181. }
  1182. }
  1183. // Apply pre-assigned register uses to state.
  1184. if (HasPhysRegUse) {
  1185. for (MachineOperand &MO : MI.operands()) {
  1186. if (!MO.isReg() || !MO.readsReg())
  1187. continue;
  1188. Register Reg = MO.getReg();
  1189. if (!Reg.isPhysical())
  1190. continue;
  1191. if (MRI->isReserved(Reg))
  1192. continue;
  1193. bool displacedAny = usePhysReg(MI, Reg);
  1194. if (!displacedAny)
  1195. MO.setIsKill(true);
  1196. }
  1197. }
  1198. // Allocate virtreg uses and insert reloads as necessary.
  1199. bool HasUndefUse = false;
  1200. for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
  1201. MachineOperand &MO = MI.getOperand(I);
  1202. if (!MO.isReg() || !MO.isUse())
  1203. continue;
  1204. Register Reg = MO.getReg();
  1205. if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
  1206. continue;
  1207. if (MO.isUndef()) {
  1208. HasUndefUse = true;
  1209. continue;
  1210. }
  1211. // Populate MayLiveAcrossBlocks in case the use block is allocated before
  1212. // the def block (removing the vreg uses).
  1213. mayLiveIn(Reg);
  1214. assert(!MO.isInternalRead() && "Bundles not supported");
  1215. assert(MO.readsReg() && "reading use");
  1216. useVirtReg(MI, I, Reg);
  1217. }
  1218. // Allocate undef operands. This is a separate step because in a situation
  1219. // like ` = OP undef %X, %X` both operands need the same register assign
  1220. // so we should perform the normal assignment first.
  1221. if (HasUndefUse) {
  1222. for (MachineOperand &MO : MI.uses()) {
  1223. if (!MO.isReg() || !MO.isUse())
  1224. continue;
  1225. Register Reg = MO.getReg();
  1226. if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
  1227. continue;
  1228. assert(MO.isUndef() && "Should only have undef virtreg uses left");
  1229. allocVirtRegUndef(MO);
  1230. }
  1231. }
  1232. // Free early clobbers.
  1233. if (HasEarlyClobber) {
  1234. for (MachineOperand &MO : llvm::reverse(MI.operands())) {
  1235. if (!MO.isReg() || !MO.isDef() || !MO.isEarlyClobber())
  1236. continue;
  1237. assert(!MO.getSubReg() && "should be already handled in def processing");
  1238. Register Reg = MO.getReg();
  1239. if (!Reg)
  1240. continue;
  1241. if (Reg.isVirtual()) {
  1242. assert(!shouldAllocateRegister(Reg));
  1243. continue;
  1244. }
  1245. assert(Reg.isPhysical() && "should have register assigned");
  1246. // We sometimes get odd situations like:
  1247. // early-clobber %x0 = INSTRUCTION %x0
  1248. // which is semantically questionable as the early-clobber should
  1249. // apply before the use. But in practice we consider the use to
  1250. // happen before the early clobber now. Don't free the early clobber
  1251. // register in this case.
  1252. if (MI.readsRegister(Reg, TRI))
  1253. continue;
  1254. freePhysReg(Reg);
  1255. }
  1256. }
  1257. LLVM_DEBUG(dbgs() << "<< " << MI);
  1258. if (MI.isCopy() && MI.getOperand(0).getReg() == MI.getOperand(1).getReg() &&
  1259. MI.getNumOperands() == 2) {
  1260. LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
  1261. Coalesced.push_back(&MI);
  1262. }
  1263. }
  1264. void RegAllocFast::handleDebugValue(MachineInstr &MI) {
  1265. // Ignore DBG_VALUEs that aren't based on virtual registers. These are
  1266. // mostly constants and frame indices.
  1267. for (Register Reg : MI.getUsedDebugRegs()) {
  1268. if (!Reg.isVirtual())
  1269. continue;
  1270. if (!shouldAllocateRegister(Reg))
  1271. continue;
  1272. // Already spilled to a stackslot?
  1273. int SS = StackSlotForVirtReg[Reg];
  1274. if (SS != -1) {
  1275. // Modify DBG_VALUE now that the value is in a spill slot.
  1276. updateDbgValueForSpill(MI, SS, Reg);
  1277. LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
  1278. continue;
  1279. }
  1280. // See if this virtual register has already been allocated to a physical
  1281. // register or spilled to a stack slot.
  1282. LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
  1283. SmallVector<MachineOperand *> DbgOps;
  1284. for (MachineOperand &Op : MI.getDebugOperandsForReg(Reg))
  1285. DbgOps.push_back(&Op);
  1286. if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
  1287. // Update every use of Reg within MI.
  1288. for (auto &RegMO : DbgOps)
  1289. setPhysReg(MI, *RegMO, LRI->PhysReg);
  1290. } else {
  1291. DanglingDbgValues[Reg].push_back(&MI);
  1292. }
  1293. // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
  1294. // that future spills of Reg will have DBG_VALUEs.
  1295. LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
  1296. }
  1297. }
  1298. void RegAllocFast::handleBundle(MachineInstr &MI) {
  1299. MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
  1300. ++BundledMI;
  1301. while (BundledMI->isBundledWithPred()) {
  1302. for (MachineOperand &MO : BundledMI->operands()) {
  1303. if (!MO.isReg())
  1304. continue;
  1305. Register Reg = MO.getReg();
  1306. if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
  1307. continue;
  1308. DenseMap<Register, MCPhysReg>::iterator DI;
  1309. DI = BundleVirtRegsMap.find(Reg);
  1310. assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
  1311. setPhysReg(MI, MO, DI->second);
  1312. }
  1313. ++BundledMI;
  1314. }
  1315. }
  1316. void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
  1317. this->MBB = &MBB;
  1318. LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
  1319. RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
  1320. assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
  1321. for (const auto &LiveReg : MBB.liveouts())
  1322. setPhysRegState(LiveReg.PhysReg, regPreAssigned);
  1323. Coalesced.clear();
  1324. // Traverse block in reverse order allocating instructions one by one.
  1325. for (MachineInstr &MI : reverse(MBB)) {
  1326. LLVM_DEBUG(
  1327. dbgs() << "\n>> " << MI << "Regs:";
  1328. dumpState()
  1329. );
  1330. // Special handling for debug values. Note that they are not allowed to
  1331. // affect codegen of the other instructions in any way.
  1332. if (MI.isDebugValue()) {
  1333. handleDebugValue(MI);
  1334. continue;
  1335. }
  1336. allocateInstruction(MI);
  1337. // Once BUNDLE header is assigned registers, same assignments need to be
  1338. // done for bundled MIs.
  1339. if (MI.getOpcode() == TargetOpcode::BUNDLE) {
  1340. handleBundle(MI);
  1341. }
  1342. }
  1343. LLVM_DEBUG(
  1344. dbgs() << "Begin Regs:";
  1345. dumpState()
  1346. );
  1347. // Spill all physical registers holding virtual registers now.
  1348. LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
  1349. reloadAtBegin(MBB);
  1350. // Erase all the coalesced copies. We are delaying it until now because
  1351. // LiveVirtRegs might refer to the instrs.
  1352. for (MachineInstr *MI : Coalesced)
  1353. MBB.erase(MI);
  1354. NumCoalesced += Coalesced.size();
  1355. for (auto &UDBGPair : DanglingDbgValues) {
  1356. for (MachineInstr *DbgValue : UDBGPair.second) {
  1357. assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
  1358. // Nothing to do if the vreg was spilled in the meantime.
  1359. if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
  1360. continue;
  1361. LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
  1362. << '\n');
  1363. DbgValue->setDebugValueUndef();
  1364. }
  1365. }
  1366. DanglingDbgValues.clear();
  1367. LLVM_DEBUG(MBB.dump());
  1368. }
  1369. bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
  1370. LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
  1371. << "********** Function: " << MF.getName() << '\n');
  1372. MRI = &MF.getRegInfo();
  1373. const TargetSubtargetInfo &STI = MF.getSubtarget();
  1374. TRI = STI.getRegisterInfo();
  1375. TII = STI.getInstrInfo();
  1376. MFI = &MF.getFrameInfo();
  1377. MRI->freezeReservedRegs(MF);
  1378. RegClassInfo.runOnMachineFunction(MF);
  1379. unsigned NumRegUnits = TRI->getNumRegUnits();
  1380. UsedInInstr.clear();
  1381. UsedInInstr.setUniverse(NumRegUnits);
  1382. PhysRegUses.clear();
  1383. PhysRegUses.setUniverse(NumRegUnits);
  1384. // initialize the virtual->physical register map to have a 'null'
  1385. // mapping for all virtual registers
  1386. unsigned NumVirtRegs = MRI->getNumVirtRegs();
  1387. StackSlotForVirtReg.resize(NumVirtRegs);
  1388. LiveVirtRegs.setUniverse(NumVirtRegs);
  1389. MayLiveAcrossBlocks.clear();
  1390. MayLiveAcrossBlocks.resize(NumVirtRegs);
  1391. // Loop over all of the basic blocks, eliminating virtual register references
  1392. for (MachineBasicBlock &MBB : MF)
  1393. allocateBasicBlock(MBB);
  1394. if (ClearVirtRegs) {
  1395. // All machine operands and other references to virtual registers have been
  1396. // replaced. Remove the virtual registers.
  1397. MRI->clearVirtRegs();
  1398. }
  1399. StackSlotForVirtReg.clear();
  1400. LiveDbgValueMap.clear();
  1401. return true;
  1402. }
  1403. FunctionPass *llvm::createFastRegisterAllocator() {
  1404. return new RegAllocFast();
  1405. }
  1406. FunctionPass *llvm::createFastRegisterAllocator(RegClassFilterFunc Ftor,
  1407. bool ClearVirtRegs) {
  1408. return new RegAllocFast(Ftor, ClearVirtRegs);
  1409. }