RegAllocFast.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This register allocator allocates registers to a basic block at a time,
  11. // attempting to keep values in registers and reusing registers as appropriate.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/Passes.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/IndexedMap.h"
  17. #include "llvm/ADT/STLExtras.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/MachineFrameInfo.h"
  23. #include "llvm/CodeGen/MachineFunctionPass.h"
  24. #include "llvm/CodeGen/MachineInstr.h"
  25. #include "llvm/CodeGen/MachineInstrBuilder.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/CodeGen/RegAllocRegistry.h"
  28. #include "llvm/CodeGen/RegisterClassInfo.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "llvm/Target/TargetInstrInfo.h"
  35. #include "llvm/Target/TargetSubtargetInfo.h"
  36. #include <algorithm>
  37. using namespace llvm;
  38. #define DEBUG_TYPE "regalloc"
  39. STATISTIC(NumStores, "Number of stores added");
  40. STATISTIC(NumLoads , "Number of loads added");
  41. STATISTIC(NumCopies, "Number of copies coalesced");
  42. static RegisterRegAlloc
  43. fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
  44. namespace {
  45. class RAFast : public MachineFunctionPass {
  46. public:
  47. static char ID;
  48. RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
  49. isBulkSpilling(false) {}
  50. private:
  51. MachineFunction *MF;
  52. MachineRegisterInfo *MRI;
  53. const TargetRegisterInfo *TRI;
  54. const TargetInstrInfo *TII;
  55. RegisterClassInfo RegClassInfo;
  56. // Basic block currently being allocated.
  57. MachineBasicBlock *MBB;
  58. // StackSlotForVirtReg - Maps virtual regs to the frame index where these
  59. // values are spilled.
  60. IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
  61. // Everything we know about a live virtual register.
  62. struct LiveReg {
  63. MachineInstr *LastUse; // Last instr to use reg.
  64. unsigned VirtReg; // Virtual register number.
  65. unsigned PhysReg; // Currently held here.
  66. unsigned short LastOpNum; // OpNum on LastUse.
  67. bool Dirty; // Register needs spill.
  68. explicit LiveReg(unsigned v)
  69. : LastUse(nullptr), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false){}
  70. unsigned getSparseSetIndex() const {
  71. return TargetRegisterInfo::virtReg2Index(VirtReg);
  72. }
  73. };
  74. typedef SparseSet<LiveReg> LiveRegMap;
  75. // LiveVirtRegs - This map contains entries for each virtual register
  76. // that is currently available in a physical register.
  77. LiveRegMap LiveVirtRegs;
  78. DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
  79. // RegState - Track the state of a physical register.
  80. enum RegState {
  81. // A disabled register is not available for allocation, but an alias may
  82. // be in use. A register can only be moved out of the disabled state if
  83. // all aliases are disabled.
  84. regDisabled,
  85. // A free register is not currently in use and can be allocated
  86. // immediately without checking aliases.
  87. regFree,
  88. // A reserved register has been assigned explicitly (e.g., setting up a
  89. // call parameter), and it remains reserved until it is used.
  90. regReserved
  91. // A register state may also be a virtual register number, indication that
  92. // the physical register is currently allocated to a virtual register. In
  93. // that case, LiveVirtRegs contains the inverse mapping.
  94. };
  95. // PhysRegState - One of the RegState enums, or a virtreg.
  96. std::vector<unsigned> PhysRegState;
  97. // Set of register units.
  98. typedef SparseSet<unsigned> UsedInInstrSet;
  99. // Set of register units that are used in the current instruction, and so
  100. // cannot be allocated.
  101. UsedInInstrSet UsedInInstr;
  102. // Mark a physreg as used in this instruction.
  103. void markRegUsedInInstr(unsigned PhysReg) {
  104. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
  105. UsedInInstr.insert(*Units);
  106. }
  107. // Check if a physreg or any of its aliases are used in this instruction.
  108. bool isRegUsedInInstr(unsigned PhysReg) const {
  109. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
  110. if (UsedInInstr.count(*Units))
  111. return true;
  112. return false;
  113. }
  114. // SkippedInstrs - Descriptors of instructions whose clobber list was
  115. // ignored because all registers were spilled. It is still necessary to
  116. // mark all the clobbered registers as used by the function.
  117. SmallPtrSet<const MCInstrDesc*, 4> SkippedInstrs;
  118. // isBulkSpilling - This flag is set when LiveRegMap will be cleared
  119. // completely after spilling all live registers. LiveRegMap entries should
  120. // not be erased.
  121. bool isBulkSpilling;
  122. enum : unsigned {
  123. spillClean = 1,
  124. spillDirty = 100,
  125. spillImpossible = ~0u
  126. };
  127. public:
  128. const char *getPassName() const override {
  129. return "Fast Register Allocator";
  130. }
  131. void getAnalysisUsage(AnalysisUsage &AU) const override {
  132. AU.setPreservesCFG();
  133. MachineFunctionPass::getAnalysisUsage(AU);
  134. }
  135. private:
  136. bool runOnMachineFunction(MachineFunction &Fn) override;
  137. void AllocateBasicBlock();
  138. void handleThroughOperands(MachineInstr *MI,
  139. SmallVectorImpl<unsigned> &VirtDead);
  140. int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
  141. bool isLastUseOfLocalReg(MachineOperand&);
  142. void addKillFlag(const LiveReg&);
  143. void killVirtReg(LiveRegMap::iterator);
  144. void killVirtReg(unsigned VirtReg);
  145. void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
  146. void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
  147. void usePhysReg(MachineOperand&);
  148. void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
  149. unsigned calcSpillCost(unsigned PhysReg) const;
  150. void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
  151. LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
  152. return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
  153. }
  154. LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
  155. return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
  156. }
  157. LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysReg);
  158. LiveRegMap::iterator allocVirtReg(MachineInstr *MI, LiveRegMap::iterator,
  159. unsigned Hint);
  160. LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
  161. unsigned VirtReg, unsigned Hint);
  162. LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
  163. unsigned VirtReg, unsigned Hint);
  164. void spillAll(MachineBasicBlock::iterator MI);
  165. bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
  166. };
  167. char RAFast::ID = 0;
  168. }
  169. /// getStackSpaceFor - This allocates space for the specified virtual register
  170. /// to be held on the stack.
  171. int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
  172. // Find the location Reg would belong...
  173. int SS = StackSlotForVirtReg[VirtReg];
  174. if (SS != -1)
  175. return SS; // Already has space allocated?
  176. // Allocate a new stack object for this spill location...
  177. int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
  178. RC->getAlignment());
  179. // Assign the slot.
  180. StackSlotForVirtReg[VirtReg] = FrameIdx;
  181. return FrameIdx;
  182. }
  183. /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
  184. /// its virtual register, and it is guaranteed to be a block-local register.
  185. ///
  186. bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
  187. // If the register has ever been spilled or reloaded, we conservatively assume
  188. // it is a global register used in multiple blocks.
  189. if (StackSlotForVirtReg[MO.getReg()] != -1)
  190. return false;
  191. // Check that the use/def chain has exactly one operand - MO.
  192. MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
  193. if (&*I != &MO)
  194. return false;
  195. return ++I == MRI->reg_nodbg_end();
  196. }
  197. /// addKillFlag - Set kill flags on last use of a virtual register.
  198. void RAFast::addKillFlag(const LiveReg &LR) {
  199. if (!LR.LastUse) return;
  200. MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
  201. if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
  202. if (MO.getReg() == LR.PhysReg)
  203. MO.setIsKill();
  204. else
  205. LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
  206. }
  207. }
  208. /// killVirtReg - Mark virtreg as no longer available.
  209. void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
  210. addKillFlag(*LRI);
  211. assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
  212. "Broken RegState mapping");
  213. PhysRegState[LRI->PhysReg] = regFree;
  214. // Erase from LiveVirtRegs unless we're spilling in bulk.
  215. if (!isBulkSpilling)
  216. LiveVirtRegs.erase(LRI);
  217. }
  218. /// killVirtReg - Mark virtreg as no longer available.
  219. void RAFast::killVirtReg(unsigned VirtReg) {
  220. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  221. "killVirtReg needs a virtual register");
  222. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  223. if (LRI != LiveVirtRegs.end())
  224. killVirtReg(LRI);
  225. }
  226. /// spillVirtReg - This method spills the value specified by VirtReg into the
  227. /// corresponding stack slot if needed.
  228. void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
  229. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  230. "Spilling a physical register is illegal!");
  231. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  232. assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
  233. spillVirtReg(MI, LRI);
  234. }
  235. /// spillVirtReg - Do the actual work of spilling.
  236. void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
  237. LiveRegMap::iterator LRI) {
  238. LiveReg &LR = *LRI;
  239. assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
  240. if (LR.Dirty) {
  241. // If this physreg is used by the instruction, we want to kill it on the
  242. // instruction, not on the spill.
  243. bool SpillKill = LR.LastUse != MI;
  244. LR.Dirty = false;
  245. DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
  246. << " in " << PrintReg(LR.PhysReg, TRI));
  247. const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
  248. int FI = getStackSpaceFor(LRI->VirtReg, RC);
  249. DEBUG(dbgs() << " to stack slot #" << FI << "\n");
  250. TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
  251. ++NumStores; // Update statistics
  252. // If this register is used by DBG_VALUE then insert new DBG_VALUE to
  253. // identify spilled location as the place to find corresponding variable's
  254. // value.
  255. SmallVectorImpl<MachineInstr *> &LRIDbgValues =
  256. LiveDbgValueMap[LRI->VirtReg];
  257. for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
  258. MachineInstr *DBG_instr = LRIDbgValues[li];
  259. const MDNode *Var = DBG_instr->getDebugVariable();
  260. const MDNode *Expr = DBG_instr->getDebugExpression();
  261. bool IsIndirect = DBG_instr->isIndirectDebugValue();
  262. uint64_t Offset = IsIndirect ? DBG_instr->getOperand(1).getImm() : 0;
  263. DebugLoc DL = DBG_instr->getDebugLoc();
  264. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  265. "Expected inlined-at fields to agree");
  266. MachineInstr *NewDV =
  267. BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::DBG_VALUE))
  268. .addFrameIndex(FI)
  269. .addImm(Offset)
  270. .addMetadata(Var)
  271. .addMetadata(Expr);
  272. assert(NewDV->getParent() == MBB && "dangling parent pointer");
  273. (void)NewDV;
  274. DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
  275. }
  276. // Now this register is spilled there is should not be any DBG_VALUE
  277. // pointing to this register because they are all pointing to spilled value
  278. // now.
  279. LRIDbgValues.clear();
  280. if (SpillKill)
  281. LR.LastUse = nullptr; // Don't kill register again
  282. }
  283. killVirtReg(LRI);
  284. }
  285. /// spillAll - Spill all dirty virtregs without killing them.
  286. void RAFast::spillAll(MachineBasicBlock::iterator MI) {
  287. if (LiveVirtRegs.empty()) return;
  288. isBulkSpilling = true;
  289. // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
  290. // of spilling here is deterministic, if arbitrary.
  291. for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
  292. i != e; ++i)
  293. spillVirtReg(MI, i);
  294. LiveVirtRegs.clear();
  295. isBulkSpilling = false;
  296. }
  297. /// usePhysReg - Handle the direct use of a physical register.
  298. /// Check that the register is not used by a virtreg.
  299. /// Kill the physreg, marking it free.
  300. /// This may add implicit kills to MO->getParent() and invalidate MO.
  301. void RAFast::usePhysReg(MachineOperand &MO) {
  302. unsigned PhysReg = MO.getReg();
  303. assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
  304. "Bad usePhysReg operand");
  305. markRegUsedInInstr(PhysReg);
  306. switch (PhysRegState[PhysReg]) {
  307. case regDisabled:
  308. break;
  309. case regReserved:
  310. PhysRegState[PhysReg] = regFree;
  311. // Fall through
  312. case regFree:
  313. MO.setIsKill();
  314. return;
  315. default:
  316. // The physreg was allocated to a virtual register. That means the value we
  317. // wanted has been clobbered.
  318. llvm_unreachable("Instruction uses an allocated register");
  319. }
  320. // Maybe a superregister is reserved?
  321. for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
  322. unsigned Alias = *AI;
  323. switch (PhysRegState[Alias]) {
  324. case regDisabled:
  325. break;
  326. case regReserved:
  327. // Either PhysReg is a subregister of Alias and we mark the
  328. // whole register as free, or PhysReg is the superregister of
  329. // Alias and we mark all the aliases as disabled before freeing
  330. // PhysReg.
  331. // In the latter case, since PhysReg was disabled, this means that
  332. // its value is defined only by physical sub-registers. This check
  333. // is performed by the assert of the default case in this loop.
  334. // Note: The value of the superregister may only be partial
  335. // defined, that is why regDisabled is a valid state for aliases.
  336. assert((TRI->isSuperRegister(PhysReg, Alias) ||
  337. TRI->isSuperRegister(Alias, PhysReg)) &&
  338. "Instruction is not using a subregister of a reserved register");
  339. // Fall through.
  340. case regFree:
  341. if (TRI->isSuperRegister(PhysReg, Alias)) {
  342. // Leave the superregister in the working set.
  343. PhysRegState[Alias] = regFree;
  344. MO.getParent()->addRegisterKilled(Alias, TRI, true);
  345. return;
  346. }
  347. // Some other alias was in the working set - clear it.
  348. PhysRegState[Alias] = regDisabled;
  349. break;
  350. default:
  351. llvm_unreachable("Instruction uses an alias of an allocated register");
  352. }
  353. }
  354. // All aliases are disabled, bring register into working set.
  355. PhysRegState[PhysReg] = regFree;
  356. MO.setIsKill();
  357. }
  358. /// definePhysReg - Mark PhysReg as reserved or free after spilling any
  359. /// virtregs. This is very similar to defineVirtReg except the physreg is
  360. /// reserved instead of allocated.
  361. void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
  362. RegState NewState) {
  363. markRegUsedInInstr(PhysReg);
  364. switch (unsigned VirtReg = PhysRegState[PhysReg]) {
  365. case regDisabled:
  366. break;
  367. default:
  368. spillVirtReg(MI, VirtReg);
  369. // Fall through.
  370. case regFree:
  371. case regReserved:
  372. PhysRegState[PhysReg] = NewState;
  373. return;
  374. }
  375. // This is a disabled register, disable all aliases.
  376. PhysRegState[PhysReg] = NewState;
  377. for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
  378. unsigned Alias = *AI;
  379. switch (unsigned VirtReg = PhysRegState[Alias]) {
  380. case regDisabled:
  381. break;
  382. default:
  383. spillVirtReg(MI, VirtReg);
  384. // Fall through.
  385. case regFree:
  386. case regReserved:
  387. PhysRegState[Alias] = regDisabled;
  388. if (TRI->isSuperRegister(PhysReg, Alias))
  389. return;
  390. break;
  391. }
  392. }
  393. }
  394. // calcSpillCost - Return the cost of spilling clearing out PhysReg and
  395. // aliases so it is free for allocation.
  396. // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
  397. // can be allocated directly.
  398. // Returns spillImpossible when PhysReg or an alias can't be spilled.
  399. unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
  400. if (isRegUsedInInstr(PhysReg)) {
  401. DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
  402. return spillImpossible;
  403. }
  404. switch (unsigned VirtReg = PhysRegState[PhysReg]) {
  405. case regDisabled:
  406. break;
  407. case regFree:
  408. return 0;
  409. case regReserved:
  410. DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
  411. << PrintReg(PhysReg, TRI) << " is reserved already.\n");
  412. return spillImpossible;
  413. default: {
  414. LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
  415. assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
  416. return I->Dirty ? spillDirty : spillClean;
  417. }
  418. }
  419. // This is a disabled register, add up cost of aliases.
  420. DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
  421. unsigned Cost = 0;
  422. for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
  423. unsigned Alias = *AI;
  424. switch (unsigned VirtReg = PhysRegState[Alias]) {
  425. case regDisabled:
  426. break;
  427. case regFree:
  428. ++Cost;
  429. break;
  430. case regReserved:
  431. return spillImpossible;
  432. default: {
  433. LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
  434. assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
  435. Cost += I->Dirty ? spillDirty : spillClean;
  436. break;
  437. }
  438. }
  439. }
  440. return Cost;
  441. }
  442. /// assignVirtToPhysReg - This method updates local state so that we know
  443. /// that PhysReg is the proper container for VirtReg now. The physical
  444. /// register must not be used for anything else when this is called.
  445. ///
  446. void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
  447. DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
  448. << PrintReg(PhysReg, TRI) << "\n");
  449. PhysRegState[PhysReg] = LR.VirtReg;
  450. assert(!LR.PhysReg && "Already assigned a physreg");
  451. LR.PhysReg = PhysReg;
  452. }
  453. RAFast::LiveRegMap::iterator
  454. RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
  455. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  456. assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
  457. assignVirtToPhysReg(*LRI, PhysReg);
  458. return LRI;
  459. }
  460. /// allocVirtReg - Allocate a physical register for VirtReg.
  461. RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr *MI,
  462. LiveRegMap::iterator LRI,
  463. unsigned Hint) {
  464. const unsigned VirtReg = LRI->VirtReg;
  465. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  466. "Can only allocate virtual registers");
  467. const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
  468. // Ignore invalid hints.
  469. if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
  470. !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
  471. Hint = 0;
  472. // Take hint when possible.
  473. if (Hint) {
  474. // Ignore the hint if we would have to spill a dirty register.
  475. unsigned Cost = calcSpillCost(Hint);
  476. if (Cost < spillDirty) {
  477. if (Cost)
  478. definePhysReg(MI, Hint, regFree);
  479. // definePhysReg may kill virtual registers and modify LiveVirtRegs.
  480. // That invalidates LRI, so run a new lookup for VirtReg.
  481. return assignVirtToPhysReg(VirtReg, Hint);
  482. }
  483. }
  484. ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(RC);
  485. // First try to find a completely free register.
  486. for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
  487. unsigned PhysReg = *I;
  488. if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
  489. assignVirtToPhysReg(*LRI, PhysReg);
  490. return LRI;
  491. }
  492. }
  493. DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
  494. << TRI->getRegClassName(RC) << "\n");
  495. unsigned BestReg = 0, BestCost = spillImpossible;
  496. for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
  497. unsigned Cost = calcSpillCost(*I);
  498. DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
  499. DEBUG(dbgs() << "\tCost: " << Cost << "\n");
  500. DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
  501. // Cost is 0 when all aliases are already disabled.
  502. if (Cost == 0) {
  503. assignVirtToPhysReg(*LRI, *I);
  504. return LRI;
  505. }
  506. if (Cost < BestCost)
  507. BestReg = *I, BestCost = Cost;
  508. }
  509. if (BestReg) {
  510. definePhysReg(MI, BestReg, regFree);
  511. // definePhysReg may kill virtual registers and modify LiveVirtRegs.
  512. // That invalidates LRI, so run a new lookup for VirtReg.
  513. return assignVirtToPhysReg(VirtReg, BestReg);
  514. }
  515. // Nothing we can do. Report an error and keep going with a bad allocation.
  516. if (MI->isInlineAsm())
  517. MI->emitError("inline assembly requires more registers than available");
  518. else
  519. MI->emitError("ran out of registers during register allocation");
  520. definePhysReg(MI, *AO.begin(), regFree);
  521. return assignVirtToPhysReg(VirtReg, *AO.begin());
  522. }
  523. /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
  524. RAFast::LiveRegMap::iterator
  525. RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
  526. unsigned VirtReg, unsigned Hint) {
  527. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  528. "Not a virtual register");
  529. LiveRegMap::iterator LRI;
  530. bool New;
  531. std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
  532. if (New) {
  533. // If there is no hint, peek at the only use of this register.
  534. if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
  535. MRI->hasOneNonDBGUse(VirtReg)) {
  536. const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
  537. // It's a copy, use the destination register as a hint.
  538. if (UseMI.isCopyLike())
  539. Hint = UseMI.getOperand(0).getReg();
  540. }
  541. LRI = allocVirtReg(MI, LRI, Hint);
  542. } else if (LRI->LastUse) {
  543. // Redefining a live register - kill at the last use, unless it is this
  544. // instruction defining VirtReg multiple times.
  545. if (LRI->LastUse != MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
  546. addKillFlag(*LRI);
  547. }
  548. assert(LRI->PhysReg && "Register not assigned");
  549. LRI->LastUse = MI;
  550. LRI->LastOpNum = OpNum;
  551. LRI->Dirty = true;
  552. markRegUsedInInstr(LRI->PhysReg);
  553. return LRI;
  554. }
  555. /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
  556. RAFast::LiveRegMap::iterator
  557. RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
  558. unsigned VirtReg, unsigned Hint) {
  559. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  560. "Not a virtual register");
  561. LiveRegMap::iterator LRI;
  562. bool New;
  563. std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
  564. MachineOperand &MO = MI->getOperand(OpNum);
  565. if (New) {
  566. LRI = allocVirtReg(MI, LRI, Hint);
  567. const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
  568. int FrameIndex = getStackSpaceFor(VirtReg, RC);
  569. DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
  570. << PrintReg(LRI->PhysReg, TRI) << "\n");
  571. TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
  572. ++NumLoads;
  573. } else if (LRI->Dirty) {
  574. if (isLastUseOfLocalReg(MO)) {
  575. DEBUG(dbgs() << "Killing last use: " << MO << "\n");
  576. if (MO.isUse())
  577. MO.setIsKill();
  578. else
  579. MO.setIsDead();
  580. } else if (MO.isKill()) {
  581. DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
  582. MO.setIsKill(false);
  583. } else if (MO.isDead()) {
  584. DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
  585. MO.setIsDead(false);
  586. }
  587. } else if (MO.isKill()) {
  588. // We must remove kill flags from uses of reloaded registers because the
  589. // register would be killed immediately, and there might be a second use:
  590. // %foo = OR %x<kill>, %x
  591. // This would cause a second reload of %x into a different register.
  592. DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
  593. MO.setIsKill(false);
  594. } else if (MO.isDead()) {
  595. DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
  596. MO.setIsDead(false);
  597. }
  598. assert(LRI->PhysReg && "Register not assigned");
  599. LRI->LastUse = MI;
  600. LRI->LastOpNum = OpNum;
  601. markRegUsedInInstr(LRI->PhysReg);
  602. return LRI;
  603. }
  604. // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
  605. // subregs. This may invalidate any operand pointers.
  606. // Return true if the operand kills its register.
  607. bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
  608. MachineOperand &MO = MI->getOperand(OpNum);
  609. bool Dead = MO.isDead();
  610. if (!MO.getSubReg()) {
  611. MO.setReg(PhysReg);
  612. return MO.isKill() || Dead;
  613. }
  614. // Handle subregister index.
  615. MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
  616. MO.setSubReg(0);
  617. // A kill flag implies killing the full register. Add corresponding super
  618. // register kill.
  619. if (MO.isKill()) {
  620. MI->addRegisterKilled(PhysReg, TRI, true);
  621. return true;
  622. }
  623. // A <def,read-undef> of a sub-register requires an implicit def of the full
  624. // register.
  625. if (MO.isDef() && MO.isUndef())
  626. MI->addRegisterDefined(PhysReg, TRI);
  627. return Dead;
  628. }
  629. // Handle special instruction operand like early clobbers and tied ops when
  630. // there are additional physreg defines.
  631. void RAFast::handleThroughOperands(MachineInstr *MI,
  632. SmallVectorImpl<unsigned> &VirtDead) {
  633. DEBUG(dbgs() << "Scanning for through registers:");
  634. SmallSet<unsigned, 8> ThroughRegs;
  635. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  636. MachineOperand &MO = MI->getOperand(i);
  637. if (!MO.isReg()) continue;
  638. unsigned Reg = MO.getReg();
  639. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  640. continue;
  641. if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
  642. (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
  643. if (ThroughRegs.insert(Reg).second)
  644. DEBUG(dbgs() << ' ' << PrintReg(Reg));
  645. }
  646. }
  647. // If any physreg defines collide with preallocated through registers,
  648. // we must spill and reallocate.
  649. DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
  650. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  651. MachineOperand &MO = MI->getOperand(i);
  652. if (!MO.isReg() || !MO.isDef()) continue;
  653. unsigned Reg = MO.getReg();
  654. if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  655. markRegUsedInInstr(Reg);
  656. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
  657. if (ThroughRegs.count(PhysRegState[*AI]))
  658. definePhysReg(MI, *AI, regFree);
  659. }
  660. }
  661. SmallVector<unsigned, 8> PartialDefs;
  662. DEBUG(dbgs() << "Allocating tied uses.\n");
  663. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  664. MachineOperand &MO = MI->getOperand(i);
  665. if (!MO.isReg()) continue;
  666. unsigned Reg = MO.getReg();
  667. if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
  668. if (MO.isUse()) {
  669. unsigned DefIdx = 0;
  670. if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
  671. DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
  672. << DefIdx << ".\n");
  673. LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
  674. unsigned PhysReg = LRI->PhysReg;
  675. setPhysReg(MI, i, PhysReg);
  676. // Note: we don't update the def operand yet. That would cause the normal
  677. // def-scan to attempt spilling.
  678. } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
  679. DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
  680. // Reload the register, but don't assign to the operand just yet.
  681. // That would confuse the later phys-def processing pass.
  682. LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
  683. PartialDefs.push_back(LRI->PhysReg);
  684. }
  685. }
  686. DEBUG(dbgs() << "Allocating early clobbers.\n");
  687. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  688. MachineOperand &MO = MI->getOperand(i);
  689. if (!MO.isReg()) continue;
  690. unsigned Reg = MO.getReg();
  691. if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
  692. if (!MO.isEarlyClobber())
  693. continue;
  694. // Note: defineVirtReg may invalidate MO.
  695. LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
  696. unsigned PhysReg = LRI->PhysReg;
  697. if (setPhysReg(MI, i, PhysReg))
  698. VirtDead.push_back(Reg);
  699. }
  700. // Restore UsedInInstr to a state usable for allocating normal virtual uses.
  701. UsedInInstr.clear();
  702. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  703. MachineOperand &MO = MI->getOperand(i);
  704. if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
  705. unsigned Reg = MO.getReg();
  706. if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  707. DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
  708. << " as used in instr\n");
  709. markRegUsedInInstr(Reg);
  710. }
  711. // Also mark PartialDefs as used to avoid reallocation.
  712. for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
  713. markRegUsedInInstr(PartialDefs[i]);
  714. }
  715. void RAFast::AllocateBasicBlock() {
  716. DEBUG(dbgs() << "\nAllocating " << *MBB);
  717. PhysRegState.assign(TRI->getNumRegs(), regDisabled);
  718. assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
  719. MachineBasicBlock::iterator MII = MBB->begin();
  720. // Add live-in registers as live.
  721. for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
  722. E = MBB->livein_end(); I != E; ++I)
  723. if (MRI->isAllocatable(*I))
  724. definePhysReg(MII, *I, regReserved);
  725. SmallVector<unsigned, 8> VirtDead;
  726. SmallVector<MachineInstr*, 32> Coalesced;
  727. // Otherwise, sequentially allocate each instruction in the MBB.
  728. while (MII != MBB->end()) {
  729. MachineInstr *MI = MII++;
  730. const MCInstrDesc &MCID = MI->getDesc();
  731. DEBUG({
  732. dbgs() << "\n>> " << *MI << "Regs:";
  733. for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
  734. if (PhysRegState[Reg] == regDisabled) continue;
  735. dbgs() << " " << TRI->getName(Reg);
  736. switch(PhysRegState[Reg]) {
  737. case regFree:
  738. break;
  739. case regReserved:
  740. dbgs() << "*";
  741. break;
  742. default: {
  743. dbgs() << '=' << PrintReg(PhysRegState[Reg]);
  744. LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
  745. assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
  746. if (I->Dirty)
  747. dbgs() << "*";
  748. assert(I->PhysReg == Reg && "Bad inverse map");
  749. break;
  750. }
  751. }
  752. }
  753. dbgs() << '\n';
  754. // Check that LiveVirtRegs is the inverse.
  755. for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
  756. e = LiveVirtRegs.end(); i != e; ++i) {
  757. assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
  758. "Bad map key");
  759. assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
  760. "Bad map value");
  761. assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
  762. }
  763. });
  764. // Debug values are not allowed to change codegen in any way.
  765. if (MI->isDebugValue()) {
  766. bool ScanDbgValue = true;
  767. while (ScanDbgValue) {
  768. ScanDbgValue = false;
  769. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  770. MachineOperand &MO = MI->getOperand(i);
  771. if (!MO.isReg()) continue;
  772. unsigned Reg = MO.getReg();
  773. if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
  774. LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
  775. if (LRI != LiveVirtRegs.end())
  776. setPhysReg(MI, i, LRI->PhysReg);
  777. else {
  778. int SS = StackSlotForVirtReg[Reg];
  779. if (SS == -1) {
  780. // We can't allocate a physreg for a DebugValue, sorry!
  781. DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
  782. MO.setReg(0);
  783. }
  784. else {
  785. // Modify DBG_VALUE now that the value is in a spill slot.
  786. bool IsIndirect = MI->isIndirectDebugValue();
  787. uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
  788. const MDNode *Var = MI->getDebugVariable();
  789. const MDNode *Expr = MI->getDebugExpression();
  790. DebugLoc DL = MI->getDebugLoc();
  791. MachineBasicBlock *MBB = MI->getParent();
  792. assert(
  793. cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  794. "Expected inlined-at fields to agree");
  795. MachineInstr *NewDV = BuildMI(*MBB, MBB->erase(MI), DL,
  796. TII->get(TargetOpcode::DBG_VALUE))
  797. .addFrameIndex(SS)
  798. .addImm(Offset)
  799. .addMetadata(Var)
  800. .addMetadata(Expr);
  801. DEBUG(dbgs() << "Modifying debug info due to spill:"
  802. << "\t" << *NewDV);
  803. // Scan NewDV operands from the beginning.
  804. MI = NewDV;
  805. ScanDbgValue = true;
  806. break;
  807. }
  808. }
  809. LiveDbgValueMap[Reg].push_back(MI);
  810. }
  811. }
  812. // Next instruction.
  813. continue;
  814. }
  815. // If this is a copy, we may be able to coalesce.
  816. unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
  817. if (MI->isCopy()) {
  818. CopyDst = MI->getOperand(0).getReg();
  819. CopySrc = MI->getOperand(1).getReg();
  820. CopyDstSub = MI->getOperand(0).getSubReg();
  821. CopySrcSub = MI->getOperand(1).getSubReg();
  822. }
  823. // Track registers used by instruction.
  824. UsedInInstr.clear();
  825. // First scan.
  826. // Mark physreg uses and early clobbers as used.
  827. // Find the end of the virtreg operands
  828. unsigned VirtOpEnd = 0;
  829. bool hasTiedOps = false;
  830. bool hasEarlyClobbers = false;
  831. bool hasPartialRedefs = false;
  832. bool hasPhysDefs = false;
  833. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  834. MachineOperand &MO = MI->getOperand(i);
  835. // Make sure MRI knows about registers clobbered by regmasks.
  836. if (MO.isRegMask()) {
  837. MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
  838. continue;
  839. }
  840. if (!MO.isReg()) continue;
  841. unsigned Reg = MO.getReg();
  842. if (!Reg) continue;
  843. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  844. VirtOpEnd = i+1;
  845. if (MO.isUse()) {
  846. hasTiedOps = hasTiedOps ||
  847. MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
  848. } else {
  849. if (MO.isEarlyClobber())
  850. hasEarlyClobbers = true;
  851. if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
  852. hasPartialRedefs = true;
  853. }
  854. continue;
  855. }
  856. if (!MRI->isAllocatable(Reg)) continue;
  857. if (MO.isUse()) {
  858. usePhysReg(MO);
  859. } else if (MO.isEarlyClobber()) {
  860. definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
  861. regFree : regReserved);
  862. hasEarlyClobbers = true;
  863. } else
  864. hasPhysDefs = true;
  865. }
  866. // The instruction may have virtual register operands that must be allocated
  867. // the same register at use-time and def-time: early clobbers and tied
  868. // operands. If there are also physical defs, these registers must avoid
  869. // both physical defs and uses, making them more constrained than normal
  870. // operands.
  871. // Similarly, if there are multiple defs and tied operands, we must make
  872. // sure the same register is allocated to uses and defs.
  873. // We didn't detect inline asm tied operands above, so just make this extra
  874. // pass for all inline asm.
  875. if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
  876. (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
  877. handleThroughOperands(MI, VirtDead);
  878. // Don't attempt coalescing when we have funny stuff going on.
  879. CopyDst = 0;
  880. // Pretend we have early clobbers so the use operands get marked below.
  881. // This is not necessary for the common case of a single tied use.
  882. hasEarlyClobbers = true;
  883. }
  884. // Second scan.
  885. // Allocate virtreg uses.
  886. for (unsigned i = 0; i != VirtOpEnd; ++i) {
  887. MachineOperand &MO = MI->getOperand(i);
  888. if (!MO.isReg()) continue;
  889. unsigned Reg = MO.getReg();
  890. if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
  891. if (MO.isUse()) {
  892. LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
  893. unsigned PhysReg = LRI->PhysReg;
  894. CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
  895. if (setPhysReg(MI, i, PhysReg))
  896. killVirtReg(LRI);
  897. }
  898. }
  899. for (UsedInInstrSet::iterator
  900. I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
  901. MRI->setRegUnitUsed(*I);
  902. // Track registers defined by instruction - early clobbers and tied uses at
  903. // this point.
  904. UsedInInstr.clear();
  905. if (hasEarlyClobbers) {
  906. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  907. MachineOperand &MO = MI->getOperand(i);
  908. if (!MO.isReg()) continue;
  909. unsigned Reg = MO.getReg();
  910. if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  911. // Look for physreg defs and tied uses.
  912. if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
  913. markRegUsedInInstr(Reg);
  914. }
  915. }
  916. unsigned DefOpEnd = MI->getNumOperands();
  917. if (MI->isCall()) {
  918. // Spill all virtregs before a call. This serves two purposes: 1. If an
  919. // exception is thrown, the landing pad is going to expect to find
  920. // registers in their spill slots, and 2. we don't have to wade through
  921. // all the <imp-def> operands on the call instruction.
  922. DefOpEnd = VirtOpEnd;
  923. DEBUG(dbgs() << " Spilling remaining registers before call.\n");
  924. spillAll(MI);
  925. // The imp-defs are skipped below, but we still need to mark those
  926. // registers as used by the function.
  927. SkippedInstrs.insert(&MCID);
  928. }
  929. // Third scan.
  930. // Allocate defs and collect dead defs.
  931. for (unsigned i = 0; i != DefOpEnd; ++i) {
  932. MachineOperand &MO = MI->getOperand(i);
  933. if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
  934. continue;
  935. unsigned Reg = MO.getReg();
  936. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  937. if (!MRI->isAllocatable(Reg)) continue;
  938. definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
  939. continue;
  940. }
  941. LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
  942. unsigned PhysReg = LRI->PhysReg;
  943. if (setPhysReg(MI, i, PhysReg)) {
  944. VirtDead.push_back(Reg);
  945. CopyDst = 0; // cancel coalescing;
  946. } else
  947. CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
  948. }
  949. // Kill dead defs after the scan to ensure that multiple defs of the same
  950. // register are allocated identically. We didn't need to do this for uses
  951. // because we are crerating our own kill flags, and they are always at the
  952. // last use.
  953. for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
  954. killVirtReg(VirtDead[i]);
  955. VirtDead.clear();
  956. for (UsedInInstrSet::iterator
  957. I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
  958. MRI->setRegUnitUsed(*I);
  959. if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
  960. DEBUG(dbgs() << "-- coalescing: " << *MI);
  961. Coalesced.push_back(MI);
  962. } else {
  963. DEBUG(dbgs() << "<< " << *MI);
  964. }
  965. }
  966. // Spill all physical registers holding virtual registers now.
  967. DEBUG(dbgs() << "Spilling live registers at end of block.\n");
  968. spillAll(MBB->getFirstTerminator());
  969. // Erase all the coalesced copies. We are delaying it until now because
  970. // LiveVirtRegs might refer to the instrs.
  971. for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
  972. MBB->erase(Coalesced[i]);
  973. NumCopies += Coalesced.size();
  974. DEBUG(MBB->dump());
  975. }
  976. /// runOnMachineFunction - Register allocate the whole function
  977. ///
  978. bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
  979. DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
  980. << "********** Function: " << Fn.getName() << '\n');
  981. MF = &Fn;
  982. MRI = &MF->getRegInfo();
  983. TRI = MF->getSubtarget().getRegisterInfo();
  984. TII = MF->getSubtarget().getInstrInfo();
  985. MRI->freezeReservedRegs(Fn);
  986. RegClassInfo.runOnMachineFunction(Fn);
  987. UsedInInstr.clear();
  988. UsedInInstr.setUniverse(TRI->getNumRegUnits());
  989. assert(!MRI->isSSA() && "regalloc requires leaving SSA");
  990. // initialize the virtual->physical register map to have a 'null'
  991. // mapping for all virtual registers
  992. StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
  993. LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
  994. // Loop over all of the basic blocks, eliminating virtual register references
  995. for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
  996. MBBi != MBBe; ++MBBi) {
  997. MBB = &*MBBi;
  998. AllocateBasicBlock();
  999. }
  1000. // Add the clobber lists for all the instructions we skipped earlier.
  1001. for (const MCInstrDesc *Desc : SkippedInstrs)
  1002. if (const uint16_t *Defs = Desc->getImplicitDefs())
  1003. while (*Defs)
  1004. MRI->setPhysRegUsed(*Defs++);
  1005. // All machine operands and other references to virtual registers have been
  1006. // replaced. Remove the virtual registers.
  1007. MRI->clearVirtRegs();
  1008. SkippedInstrs.clear();
  1009. StackSlotForVirtReg.clear();
  1010. LiveDbgValueMap.clear();
  1011. return true;
  1012. }
  1013. FunctionPass *llvm::createFastRegisterAllocator() {
  1014. return new RAFast();
  1015. }