WebAssemblyPEI.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. //===-- WebAssemblyPEI.cpp - Insert Prolog/Epilog code in function --===//
  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 pass is responsible for finalizing the functions frame layout, saving
  11. // callee saved registers, and for emitting prolog & epilog code for the
  12. // function.
  13. //
  14. // This pass must be run after register allocation. After this pass is
  15. // executed, it is illegal to construct MO_FrameIndex operands.
  16. //
  17. // This is a copy of lib/CodeGen/PrologEpilogInserter.cpp except that it does
  18. // not assert that all virtual registers are gone (because WebAssembly currently
  19. // uses virtual rather than physical registers), and only runs
  20. // MRI.clearVirtRegs() if scavenging happened (which it never does). It also
  21. // uses a different class name so it can be registered via INITIALIZE_PASS.
  22. // It is otherwise unmodified, so any changes to the target-independent PEI
  23. // can be easily applied.
  24. //===----------------------------------------------------------------------===//
  25. #include "llvm/ADT/IndexedMap.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/SetVector.h"
  28. #include "llvm/ADT/SmallSet.h"
  29. #include "llvm/ADT/Statistic.h"
  30. #include "llvm/CodeGen/MachineDominators.h"
  31. #include "llvm/CodeGen/MachineFrameInfo.h"
  32. #include "llvm/CodeGen/MachineInstr.h"
  33. #include "llvm/CodeGen/MachineLoopInfo.h"
  34. #include "llvm/CodeGen/MachineModuleInfo.h"
  35. #include "llvm/CodeGen/MachineRegisterInfo.h"
  36. #include "llvm/CodeGen/Passes.h"
  37. #include "llvm/CodeGen/RegisterScavenging.h"
  38. #include "llvm/CodeGen/StackProtector.h"
  39. #include "llvm/CodeGen/WinEHFuncInfo.h"
  40. #include "llvm/IR/DiagnosticInfo.h"
  41. #include "llvm/IR/InlineAsm.h"
  42. #include "llvm/IR/LLVMContext.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/Compiler.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include "llvm/Target/TargetFrameLowering.h"
  48. #include "llvm/Target/TargetInstrInfo.h"
  49. #include "llvm/Target/TargetMachine.h"
  50. #include "llvm/Target/TargetRegisterInfo.h"
  51. #include "llvm/Target/TargetSubtargetInfo.h"
  52. #include <climits>
  53. using namespace llvm;
  54. #define DEBUG_TYPE "pei"
  55. namespace llvm {
  56. void initializeWasmPEIPass(PassRegistry&);
  57. }
  58. namespace {
  59. class WasmPEI : public MachineFunctionPass {
  60. public:
  61. static char ID;
  62. WasmPEI() : MachineFunctionPass(ID) {
  63. initializeWasmPEIPass(*PassRegistry::getPassRegistry());
  64. }
  65. void getAnalysisUsage(AnalysisUsage &AU) const override;
  66. /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
  67. /// frame indexes with appropriate references.
  68. ///
  69. bool runOnMachineFunction(MachineFunction &Fn) override;
  70. private:
  71. RegScavenger *RS;
  72. // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
  73. // stack frame indexes.
  74. unsigned MinCSFrameIndex, MaxCSFrameIndex;
  75. // Save and Restore blocks of the current function. Typically there is a
  76. // single save block, unless Windows EH funclets are involved.
  77. SmallVector<MachineBasicBlock *, 1> SaveBlocks;
  78. SmallVector<MachineBasicBlock *, 4> RestoreBlocks;
  79. // Flag to control whether to use the register scavenger to resolve
  80. // frame index materialization registers. Set according to
  81. // TRI->requiresFrameIndexScavenging() for the current function.
  82. bool FrameIndexVirtualScavenging;
  83. void calculateSets(MachineFunction &Fn);
  84. void calculateCallsInformation(MachineFunction &Fn);
  85. void assignCalleeSavedSpillSlots(MachineFunction &Fn,
  86. const BitVector &SavedRegs);
  87. void insertCSRSpillsAndRestores(MachineFunction &Fn);
  88. void calculateFrameObjectOffsets(MachineFunction &Fn);
  89. void replaceFrameIndices(MachineFunction &Fn);
  90. void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
  91. int &SPAdj);
  92. void scavengeFrameVirtualRegs(MachineFunction &Fn);
  93. void insertPrologEpilogCode(MachineFunction &Fn);
  94. };
  95. } // namespace
  96. char WasmPEI::ID = 0;
  97. namespace llvm {
  98. FunctionPass *createWebAssemblyPEI() {
  99. return new WasmPEI();
  100. }
  101. }
  102. static cl::opt<unsigned>
  103. WarnStackSize("wasm-warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
  104. cl::desc("Warn for stack size bigger than the given"
  105. " number"));
  106. INITIALIZE_PASS_BEGIN(WasmPEI, "wasmprologepilog",
  107. "Wasm Prologue/Epilogue Insertion", false, false)
  108. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  109. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  110. INITIALIZE_PASS_DEPENDENCY(StackProtector)
  111. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  112. INITIALIZE_PASS_END(WasmPEI, "wasmprologepilog",
  113. "Wasm Prologue/Epilogue Insertion & Frame Finalization",
  114. false, false)
  115. STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
  116. STATISTIC(NumBytesStackSpace,
  117. "Number of bytes used for stack in all functions");
  118. void WasmPEI::getAnalysisUsage(AnalysisUsage &AU) const {
  119. AU.setPreservesCFG();
  120. AU.addPreserved<MachineLoopInfo>();
  121. AU.addPreserved<MachineDominatorTree>();
  122. AU.addRequired<StackProtector>();
  123. AU.addRequired<TargetPassConfig>();
  124. MachineFunctionPass::getAnalysisUsage(AU);
  125. }
  126. /// Compute the set of return blocks
  127. void WasmPEI::calculateSets(MachineFunction &Fn) {
  128. const MachineFrameInfo *MFI = Fn.getFrameInfo();
  129. // Even when we do not change any CSR, we still want to insert the
  130. // prologue and epilogue of the function.
  131. // So set the save points for those.
  132. // Use the points found by shrink-wrapping, if any.
  133. if (MFI->getSavePoint()) {
  134. SaveBlocks.push_back(MFI->getSavePoint());
  135. assert(MFI->getRestorePoint() && "Both restore and save must be set");
  136. MachineBasicBlock *RestoreBlock = MFI->getRestorePoint();
  137. // If RestoreBlock does not have any successor and is not a return block
  138. // then the end point is unreachable and we do not need to insert any
  139. // epilogue.
  140. if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
  141. RestoreBlocks.push_back(RestoreBlock);
  142. return;
  143. }
  144. // Save refs to entry and return blocks.
  145. SaveBlocks.push_back(&Fn.front());
  146. for (MachineBasicBlock &MBB : Fn) {
  147. if (MBB.isEHFuncletEntry())
  148. SaveBlocks.push_back(&MBB);
  149. if (MBB.isReturnBlock())
  150. RestoreBlocks.push_back(&MBB);
  151. }
  152. }
  153. /// StackObjSet - A set of stack object indexes
  154. typedef SmallSetVector<int, 8> StackObjSet;
  155. /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
  156. /// frame indexes with appropriate references.
  157. ///
  158. bool WasmPEI::runOnMachineFunction(MachineFunction &Fn) {
  159. const Function* F = Fn.getFunction();
  160. const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
  161. const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
  162. // LOCALMOD: assert removed from target-independent PEI
  163. //assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
  164. RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
  165. FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
  166. // Calculate the MaxCallFrameSize and AdjustsStack variables for the
  167. // function's frame information. Also eliminates call frame pseudo
  168. // instructions.
  169. calculateCallsInformation(Fn);
  170. // Determine which of the registers in the callee save list should be saved.
  171. BitVector SavedRegs;
  172. TFI->determineCalleeSaves(Fn, SavedRegs, RS);
  173. // Insert spill code for any callee saved registers that are modified.
  174. assignCalleeSavedSpillSlots(Fn, SavedRegs);
  175. // Determine placement of CSR spill/restore code:
  176. // place all spills in the entry block, all restores in return blocks.
  177. calculateSets(Fn);
  178. // Add the code to save and restore the callee saved registers.
  179. if (!F->hasFnAttribute(Attribute::Naked))
  180. insertCSRSpillsAndRestores(Fn);
  181. // Allow the target machine to make final modifications to the function
  182. // before the frame layout is finalized.
  183. TFI->processFunctionBeforeFrameFinalized(Fn, RS);
  184. // Calculate actual frame offsets for all abstract stack objects...
  185. calculateFrameObjectOffsets(Fn);
  186. // Add prolog and epilog code to the function. This function is required
  187. // to align the stack frame as necessary for any stack variables or
  188. // called functions. Because of this, calculateCalleeSavedRegisters()
  189. // must be called before this function in order to set the AdjustsStack
  190. // and MaxCallFrameSize variables.
  191. if (!F->hasFnAttribute(Attribute::Naked))
  192. insertPrologEpilogCode(Fn);
  193. // Replace all MO_FrameIndex operands with physical register references
  194. // and actual offsets.
  195. //
  196. replaceFrameIndices(Fn);
  197. // If register scavenging is needed, as we've enabled doing it as a
  198. // post-pass, scavenge the virtual registers that frame index elimination
  199. // inserted.
  200. if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) {
  201. scavengeFrameVirtualRegs(Fn);
  202. // Clear any vregs created by virtual scavenging.
  203. // LOCALMOD: made this call conditional with scavengeFrameVirtualregs()
  204. Fn.getRegInfo().clearVirtRegs();
  205. }
  206. // Warn on stack size when we exceeds the given limit.
  207. MachineFrameInfo *MFI = Fn.getFrameInfo();
  208. uint64_t StackSize = MFI->getStackSize();
  209. if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
  210. DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
  211. F->getContext().diagnose(DiagStackSize);
  212. }
  213. delete RS;
  214. SaveBlocks.clear();
  215. RestoreBlocks.clear();
  216. return true;
  217. }
  218. /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
  219. /// variables for the function's frame information and eliminate call frame
  220. /// pseudo instructions.
  221. void WasmPEI::calculateCallsInformation(MachineFunction &Fn) {
  222. const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
  223. const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
  224. MachineFrameInfo *MFI = Fn.getFrameInfo();
  225. unsigned MaxCallFrameSize = 0;
  226. bool AdjustsStack = MFI->adjustsStack();
  227. // Get the function call frame set-up and tear-down instruction opcode
  228. unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
  229. unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
  230. // Early exit for targets which have no call frame setup/destroy pseudo
  231. // instructions.
  232. if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
  233. return;
  234. std::vector<MachineBasicBlock::iterator> FrameSDOps;
  235. for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
  236. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
  237. if (I->getOpcode() == FrameSetupOpcode ||
  238. I->getOpcode() == FrameDestroyOpcode) {
  239. assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
  240. " instructions should have a single immediate argument!");
  241. unsigned Size = I->getOperand(0).getImm();
  242. if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
  243. AdjustsStack = true;
  244. FrameSDOps.push_back(I);
  245. } else if (I->isInlineAsm()) {
  246. // Some inline asm's need a stack frame, as indicated by operand 1.
  247. unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  248. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  249. AdjustsStack = true;
  250. }
  251. MFI->setAdjustsStack(AdjustsStack);
  252. MFI->setMaxCallFrameSize(MaxCallFrameSize);
  253. for (std::vector<MachineBasicBlock::iterator>::iterator
  254. i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
  255. MachineBasicBlock::iterator I = *i;
  256. // If call frames are not being included as part of the stack frame, and
  257. // the target doesn't indicate otherwise, remove the call frame pseudos
  258. // here. The sub/add sp instruction pairs are still inserted, but we don't
  259. // need to track the SP adjustment for frame index elimination.
  260. if (TFI->canSimplifyCallFramePseudos(Fn))
  261. TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
  262. }
  263. }
  264. void WasmPEI::assignCalleeSavedSpillSlots(MachineFunction &F,
  265. const BitVector &SavedRegs) {
  266. // These are used to keep track the callee-save area. Initialize them.
  267. MinCSFrameIndex = INT_MAX;
  268. MaxCSFrameIndex = 0;
  269. if (SavedRegs.empty())
  270. return;
  271. const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
  272. const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
  273. std::vector<CalleeSavedInfo> CSI;
  274. for (unsigned i = 0; CSRegs[i]; ++i) {
  275. unsigned Reg = CSRegs[i];
  276. if (SavedRegs.test(Reg))
  277. CSI.push_back(CalleeSavedInfo(Reg));
  278. }
  279. const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
  280. MachineFrameInfo *MFI = F.getFrameInfo();
  281. if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
  282. // If target doesn't implement this, use generic code.
  283. if (CSI.empty())
  284. return; // Early exit if no callee saved registers are modified!
  285. unsigned NumFixedSpillSlots;
  286. const TargetFrameLowering::SpillSlot *FixedSpillSlots =
  287. TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
  288. // Now that we know which registers need to be saved and restored, allocate
  289. // stack slots for them.
  290. for (std::vector<CalleeSavedInfo>::iterator I = CSI.begin(), E = CSI.end();
  291. I != E; ++I) {
  292. unsigned Reg = I->getReg();
  293. const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
  294. int FrameIdx;
  295. if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
  296. I->setFrameIdx(FrameIdx);
  297. continue;
  298. }
  299. // Check to see if this physreg must be spilled to a particular stack slot
  300. // on this target.
  301. const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
  302. while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
  303. FixedSlot->Reg != Reg)
  304. ++FixedSlot;
  305. if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
  306. // Nope, just spill it anywhere convenient.
  307. unsigned Align = RC->getAlignment();
  308. unsigned StackAlign = TFI->getStackAlignment();
  309. // We may not be able to satisfy the desired alignment specification of
  310. // the TargetRegisterClass if the stack alignment is smaller. Use the
  311. // min.
  312. Align = std::min(Align, StackAlign);
  313. FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
  314. if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
  315. if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
  316. } else {
  317. // Spill it to the stack where we must.
  318. FrameIdx =
  319. MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
  320. }
  321. I->setFrameIdx(FrameIdx);
  322. }
  323. }
  324. MFI->setCalleeSavedInfo(CSI);
  325. }
  326. /// Helper function to update the liveness information for the callee-saved
  327. /// registers.
  328. static void updateLiveness(MachineFunction &MF) {
  329. MachineFrameInfo *MFI = MF.getFrameInfo();
  330. // Visited will contain all the basic blocks that are in the region
  331. // where the callee saved registers are alive:
  332. // - Anything that is not Save or Restore -> LiveThrough.
  333. // - Save -> LiveIn.
  334. // - Restore -> LiveOut.
  335. // The live-out is not attached to the block, so no need to keep
  336. // Restore in this set.
  337. SmallPtrSet<MachineBasicBlock *, 8> Visited;
  338. SmallVector<MachineBasicBlock *, 8> WorkList;
  339. MachineBasicBlock *Entry = &MF.front();
  340. MachineBasicBlock *Save = MFI->getSavePoint();
  341. if (!Save)
  342. Save = Entry;
  343. if (Entry != Save) {
  344. WorkList.push_back(Entry);
  345. Visited.insert(Entry);
  346. }
  347. Visited.insert(Save);
  348. MachineBasicBlock *Restore = MFI->getRestorePoint();
  349. if (Restore)
  350. // By construction Restore cannot be visited, otherwise it
  351. // means there exists a path to Restore that does not go
  352. // through Save.
  353. WorkList.push_back(Restore);
  354. while (!WorkList.empty()) {
  355. const MachineBasicBlock *CurBB = WorkList.pop_back_val();
  356. // By construction, the region that is after the save point is
  357. // dominated by the Save and post-dominated by the Restore.
  358. if (CurBB == Save && Save != Restore)
  359. continue;
  360. // Enqueue all the successors not already visited.
  361. // Those are by construction either before Save or after Restore.
  362. for (MachineBasicBlock *SuccBB : CurBB->successors())
  363. if (Visited.insert(SuccBB).second)
  364. WorkList.push_back(SuccBB);
  365. }
  366. const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  367. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  368. for (MachineBasicBlock *MBB : Visited) {
  369. MCPhysReg Reg = CSI[i].getReg();
  370. // Add the callee-saved register as live-in.
  371. // It's killed at the spill.
  372. if (!MBB->isLiveIn(Reg))
  373. MBB->addLiveIn(Reg);
  374. }
  375. }
  376. }
  377. /// insertCSRSpillsAndRestores - Insert spill and restore code for
  378. /// callee saved registers used in the function.
  379. ///
  380. void WasmPEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
  381. // Get callee saved register information.
  382. MachineFrameInfo *MFI = Fn.getFrameInfo();
  383. const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  384. MFI->setCalleeSavedInfoValid(true);
  385. // Early exit if no callee saved registers are modified!
  386. if (CSI.empty())
  387. return;
  388. const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
  389. const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
  390. const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
  391. MachineBasicBlock::iterator I;
  392. // Spill using target interface.
  393. for (MachineBasicBlock *SaveBlock : SaveBlocks) {
  394. I = SaveBlock->begin();
  395. if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
  396. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  397. // Insert the spill to the stack frame.
  398. unsigned Reg = CSI[i].getReg();
  399. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  400. TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
  401. RC, TRI);
  402. }
  403. }
  404. // Update the live-in information of all the blocks up to the save point.
  405. updateLiveness(Fn);
  406. }
  407. // Restore using target interface.
  408. for (MachineBasicBlock *MBB : RestoreBlocks) {
  409. I = MBB->end();
  410. // Skip over all terminator instructions, which are part of the return
  411. // sequence.
  412. MachineBasicBlock::iterator I2 = I;
  413. while (I2 != MBB->begin() && (--I2)->isTerminator())
  414. I = I2;
  415. bool AtStart = I == MBB->begin();
  416. MachineBasicBlock::iterator BeforeI = I;
  417. if (!AtStart)
  418. --BeforeI;
  419. // Restore all registers immediately before the return and any
  420. // terminators that precede it.
  421. if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
  422. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  423. unsigned Reg = CSI[i].getReg();
  424. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  425. TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
  426. assert(I != MBB->begin() &&
  427. "loadRegFromStackSlot didn't insert any code!");
  428. // Insert in reverse order. loadRegFromStackSlot can insert
  429. // multiple instructions.
  430. if (AtStart)
  431. I = MBB->begin();
  432. else {
  433. I = BeforeI;
  434. ++I;
  435. }
  436. }
  437. }
  438. }
  439. }
  440. /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
  441. static inline void
  442. AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
  443. bool StackGrowsDown, int64_t &Offset,
  444. unsigned &MaxAlign, unsigned Skew) {
  445. // If the stack grows down, add the object size to find the lowest address.
  446. if (StackGrowsDown)
  447. Offset += MFI->getObjectSize(FrameIdx);
  448. unsigned Align = MFI->getObjectAlignment(FrameIdx);
  449. // If the alignment of this object is greater than that of the stack, then
  450. // increase the stack alignment to match.
  451. MaxAlign = std::max(MaxAlign, Align);
  452. // Adjust to alignment boundary.
  453. Offset = alignTo(Offset, Align, Skew);
  454. if (StackGrowsDown) {
  455. DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
  456. MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
  457. } else {
  458. DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
  459. MFI->setObjectOffset(FrameIdx, Offset);
  460. Offset += MFI->getObjectSize(FrameIdx);
  461. }
  462. }
  463. /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
  464. /// those required to be close to the Stack Protector) to stack offsets.
  465. static void
  466. AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
  467. SmallSet<int, 16> &ProtectedObjs,
  468. MachineFrameInfo *MFI, bool StackGrowsDown,
  469. int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
  470. for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
  471. E = UnassignedObjs.end(); I != E; ++I) {
  472. int i = *I;
  473. AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
  474. ProtectedObjs.insert(i);
  475. }
  476. }
  477. /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
  478. /// abstract stack objects.
  479. ///
  480. void WasmPEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
  481. const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
  482. StackProtector *SP = &getAnalysis<StackProtector>();
  483. bool StackGrowsDown =
  484. TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  485. // Loop over all of the stack objects, assigning sequential addresses...
  486. MachineFrameInfo *MFI = Fn.getFrameInfo();
  487. // Start at the beginning of the local area.
  488. // The Offset is the distance from the stack top in the direction
  489. // of stack growth -- so it's always nonnegative.
  490. int LocalAreaOffset = TFI.getOffsetOfLocalArea();
  491. if (StackGrowsDown)
  492. LocalAreaOffset = -LocalAreaOffset;
  493. assert(LocalAreaOffset >= 0
  494. && "Local area offset should be in direction of stack growth");
  495. int64_t Offset = LocalAreaOffset;
  496. // Skew to be applied to alignment.
  497. unsigned Skew = TFI.getStackAlignmentSkew(Fn);
  498. // If there are fixed sized objects that are preallocated in the local area,
  499. // non-fixed objects can't be allocated right at the start of local area.
  500. // We currently don't support filling in holes in between fixed sized
  501. // objects, so we adjust 'Offset' to point to the end of last fixed sized
  502. // preallocated object.
  503. for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
  504. int64_t FixedOff;
  505. if (StackGrowsDown) {
  506. // The maximum distance from the stack pointer is at lower address of
  507. // the object -- which is given by offset. For down growing stack
  508. // the offset is negative, so we negate the offset to get the distance.
  509. FixedOff = -MFI->getObjectOffset(i);
  510. } else {
  511. // The maximum distance from the start pointer is at the upper
  512. // address of the object.
  513. FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
  514. }
  515. if (FixedOff > Offset) Offset = FixedOff;
  516. }
  517. // First assign frame offsets to stack objects that are used to spill
  518. // callee saved registers.
  519. if (StackGrowsDown) {
  520. for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
  521. // If the stack grows down, we need to add the size to find the lowest
  522. // address of the object.
  523. Offset += MFI->getObjectSize(i);
  524. unsigned Align = MFI->getObjectAlignment(i);
  525. // Adjust to alignment boundary
  526. Offset = alignTo(Offset, Align, Skew);
  527. MFI->setObjectOffset(i, -Offset); // Set the computed offset
  528. }
  529. } else {
  530. int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
  531. for (int i = MaxCSFI; i >= MinCSFI ; --i) {
  532. unsigned Align = MFI->getObjectAlignment(i);
  533. // Adjust to alignment boundary
  534. Offset = alignTo(Offset, Align, Skew);
  535. MFI->setObjectOffset(i, Offset);
  536. Offset += MFI->getObjectSize(i);
  537. }
  538. }
  539. unsigned MaxAlign = MFI->getMaxAlignment();
  540. // Make sure the special register scavenging spill slot is closest to the
  541. // incoming stack pointer if a frame pointer is required and is closer
  542. // to the incoming rather than the final stack pointer.
  543. const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
  544. bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
  545. TFI.isFPCloseToIncomingSP() &&
  546. RegInfo->useFPForScavengingIndex(Fn) &&
  547. !RegInfo->needsStackRealignment(Fn));
  548. if (RS && EarlyScavengingSlots) {
  549. SmallVector<int, 2> SFIs;
  550. RS->getScavengingFrameIndices(SFIs);
  551. for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
  552. IE = SFIs.end(); I != IE; ++I)
  553. AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
  554. }
  555. // FIXME: Once this is working, then enable flag will change to a target
  556. // check for whether the frame is large enough to want to use virtual
  557. // frame index registers. Functions which don't want/need this optimization
  558. // will continue to use the existing code path.
  559. if (MFI->getUseLocalStackAllocationBlock()) {
  560. unsigned Align = MFI->getLocalFrameMaxAlign();
  561. // Adjust to alignment boundary.
  562. Offset = alignTo(Offset, Align, Skew);
  563. DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
  564. // Resolve offsets for objects in the local block.
  565. for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
  566. std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
  567. int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
  568. DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
  569. FIOffset << "]\n");
  570. MFI->setObjectOffset(Entry.first, FIOffset);
  571. }
  572. // Allocate the local block
  573. Offset += MFI->getLocalFrameSize();
  574. MaxAlign = std::max(Align, MaxAlign);
  575. }
  576. // Make sure that the stack protector comes before the local variables on the
  577. // stack.
  578. SmallSet<int, 16> ProtectedObjs;
  579. if (MFI->getStackProtectorIndex() >= 0) {
  580. StackObjSet LargeArrayObjs;
  581. StackObjSet SmallArrayObjs;
  582. StackObjSet AddrOfObjs;
  583. AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
  584. Offset, MaxAlign, Skew);
  585. // Assign large stack objects first.
  586. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  587. if (MFI->isObjectPreAllocated(i) &&
  588. MFI->getUseLocalStackAllocationBlock())
  589. continue;
  590. if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
  591. continue;
  592. if (RS && RS->isScavengingFrameIndex((int)i))
  593. continue;
  594. if (MFI->isDeadObjectIndex(i))
  595. continue;
  596. if (MFI->getStackProtectorIndex() == (int)i)
  597. continue;
  598. switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
  599. case StackProtector::SSPLK_None:
  600. continue;
  601. case StackProtector::SSPLK_SmallArray:
  602. SmallArrayObjs.insert(i);
  603. continue;
  604. case StackProtector::SSPLK_AddrOf:
  605. AddrOfObjs.insert(i);
  606. continue;
  607. case StackProtector::SSPLK_LargeArray:
  608. LargeArrayObjs.insert(i);
  609. continue;
  610. }
  611. llvm_unreachable("Unexpected SSPLayoutKind.");
  612. }
  613. AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
  614. Offset, MaxAlign, Skew);
  615. AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
  616. Offset, MaxAlign, Skew);
  617. AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
  618. Offset, MaxAlign, Skew);
  619. }
  620. // Then assign frame offsets to stack objects that are not used to spill
  621. // callee saved registers.
  622. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  623. if (MFI->isObjectPreAllocated(i) &&
  624. MFI->getUseLocalStackAllocationBlock())
  625. continue;
  626. if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
  627. continue;
  628. if (RS && RS->isScavengingFrameIndex((int)i))
  629. continue;
  630. if (MFI->isDeadObjectIndex(i))
  631. continue;
  632. if (MFI->getStackProtectorIndex() == (int)i)
  633. continue;
  634. if (ProtectedObjs.count(i))
  635. continue;
  636. AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
  637. }
  638. // Make sure the special register scavenging spill slot is closest to the
  639. // stack pointer.
  640. if (RS && !EarlyScavengingSlots) {
  641. SmallVector<int, 2> SFIs;
  642. RS->getScavengingFrameIndices(SFIs);
  643. for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
  644. IE = SFIs.end(); I != IE; ++I)
  645. AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
  646. }
  647. if (!TFI.targetHandlesStackFrameRounding()) {
  648. // If we have reserved argument space for call sites in the function
  649. // immediately on entry to the current function, count it as part of the
  650. // overall stack size.
  651. if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
  652. Offset += MFI->getMaxCallFrameSize();
  653. // Round up the size to a multiple of the alignment. If the function has
  654. // any calls or alloca's, align to the target's StackAlignment value to
  655. // ensure that the callee's frame or the alloca data is suitably aligned;
  656. // otherwise, for leaf functions, align to the TransientStackAlignment
  657. // value.
  658. unsigned StackAlign;
  659. if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
  660. (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
  661. StackAlign = TFI.getStackAlignment();
  662. else
  663. StackAlign = TFI.getTransientStackAlignment();
  664. // If the frame pointer is eliminated, all frame offsets will be relative to
  665. // SP not FP. Align to MaxAlign so this works.
  666. StackAlign = std::max(StackAlign, MaxAlign);
  667. Offset = alignTo(Offset, StackAlign, Skew);
  668. }
  669. // Update frame info to pretend that this is part of the stack...
  670. int64_t StackSize = Offset - LocalAreaOffset;
  671. MFI->setStackSize(StackSize);
  672. NumBytesStackSpace += StackSize;
  673. }
  674. /// insertPrologEpilogCode - Scan the function for modified callee saved
  675. /// registers, insert spill code for these callee saved registers, then add
  676. /// prolog and epilog code to the function.
  677. ///
  678. void WasmPEI::insertPrologEpilogCode(MachineFunction &Fn) {
  679. const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
  680. // Add prologue to the function...
  681. for (MachineBasicBlock *SaveBlock : SaveBlocks)
  682. TFI.emitPrologue(Fn, *SaveBlock);
  683. // Add epilogue to restore the callee-save registers in each exiting block.
  684. for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
  685. TFI.emitEpilogue(Fn, *RestoreBlock);
  686. for (MachineBasicBlock *SaveBlock : SaveBlocks)
  687. TFI.inlineStackProbe(Fn, *SaveBlock);
  688. // Emit additional code that is required to support segmented stacks, if
  689. // we've been asked for it. This, when linked with a runtime with support
  690. // for segmented stacks (libgcc is one), will result in allocating stack
  691. // space in small chunks instead of one large contiguous block.
  692. if (Fn.shouldSplitStack()) {
  693. for (MachineBasicBlock *SaveBlock : SaveBlocks)
  694. TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
  695. }
  696. // Emit additional code that is required to explicitly handle the stack in
  697. // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
  698. // approach is rather similar to that of Segmented Stacks, but it uses a
  699. // different conditional check and another BIF for allocating more stack
  700. // space.
  701. if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
  702. for (MachineBasicBlock *SaveBlock : SaveBlocks)
  703. TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
  704. }
  705. /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
  706. /// register references and actual offsets.
  707. ///
  708. void WasmPEI::replaceFrameIndices(MachineFunction &Fn) {
  709. const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
  710. if (!TFI.needsFrameIndexResolution(Fn)) return;
  711. // Store SPAdj at exit of a basic block.
  712. SmallVector<int, 8> SPState;
  713. SPState.resize(Fn.getNumBlockIDs());
  714. SmallPtrSet<MachineBasicBlock*, 8> Reachable;
  715. // Iterate over the reachable blocks in DFS order.
  716. for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
  717. DFI != DFE; ++DFI) {
  718. int SPAdj = 0;
  719. // Check the exit state of the DFS stack predecessor.
  720. if (DFI.getPathLength() >= 2) {
  721. MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
  722. assert(Reachable.count(StackPred) &&
  723. "DFS stack predecessor is already visited.\n");
  724. SPAdj = SPState[StackPred->getNumber()];
  725. }
  726. MachineBasicBlock *BB = *DFI;
  727. replaceFrameIndices(BB, Fn, SPAdj);
  728. SPState[BB->getNumber()] = SPAdj;
  729. }
  730. // Handle the unreachable blocks.
  731. for (auto &BB : Fn) {
  732. if (Reachable.count(&BB))
  733. // Already handled in DFS traversal.
  734. continue;
  735. int SPAdj = 0;
  736. replaceFrameIndices(&BB, Fn, SPAdj);
  737. }
  738. }
  739. void WasmPEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
  740. int &SPAdj) {
  741. assert(Fn.getSubtarget().getRegisterInfo() &&
  742. "getRegisterInfo() must be implemented!");
  743. const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
  744. const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
  745. const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
  746. unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
  747. unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
  748. if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
  749. bool InsideCallSequence = false;
  750. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
  751. if (I->getOpcode() == FrameSetupOpcode ||
  752. I->getOpcode() == FrameDestroyOpcode) {
  753. InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
  754. SPAdj += TII.getSPAdjust(I);
  755. MachineBasicBlock::iterator PrevI = BB->end();
  756. if (I != BB->begin()) PrevI = std::prev(I);
  757. TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
  758. // Visit the instructions created by eliminateCallFramePseudoInstr().
  759. if (PrevI == BB->end())
  760. I = BB->begin(); // The replaced instr was the first in the block.
  761. else
  762. I = std::next(PrevI);
  763. continue;
  764. }
  765. MachineInstr *MI = I;
  766. bool DoIncr = true;
  767. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  768. if (!MI->getOperand(i).isFI())
  769. continue;
  770. // Frame indices in debug values are encoded in a target independent
  771. // way with simply the frame index and offset rather than any
  772. // target-specific addressing mode.
  773. if (MI->isDebugValue()) {
  774. assert(i == 0 && "Frame indices can only appear as the first "
  775. "operand of a DBG_VALUE machine instruction");
  776. unsigned Reg;
  777. MachineOperand &Offset = MI->getOperand(1);
  778. Offset.setImm(Offset.getImm() +
  779. TFI->getFrameIndexReference(
  780. Fn, MI->getOperand(0).getIndex(), Reg));
  781. MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
  782. continue;
  783. }
  784. // TODO: This code should be commoned with the code for
  785. // PATCHPOINT. There's no good reason for the difference in
  786. // implementation other than historical accident. The only
  787. // remaining difference is the unconditional use of the stack
  788. // pointer as the base register.
  789. if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
  790. assert((!MI->isDebugValue() || i == 0) &&
  791. "Frame indicies can only appear as the first operand of a "
  792. "DBG_VALUE machine instruction");
  793. unsigned Reg;
  794. MachineOperand &Offset = MI->getOperand(i + 1);
  795. const unsigned refOffset =
  796. TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(),
  797. Reg);
  798. Offset.setImm(Offset.getImm() + refOffset);
  799. MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
  800. continue;
  801. }
  802. // Some instructions (e.g. inline asm instructions) can have
  803. // multiple frame indices and/or cause eliminateFrameIndex
  804. // to insert more than one instruction. We need the register
  805. // scavenger to go through all of these instructions so that
  806. // it can update its register information. We keep the
  807. // iterator at the point before insertion so that we can
  808. // revisit them in full.
  809. bool AtBeginning = (I == BB->begin());
  810. if (!AtBeginning) --I;
  811. // If this instruction has a FrameIndex operand, we need to
  812. // use that target machine register info object to eliminate
  813. // it.
  814. TRI.eliminateFrameIndex(MI, SPAdj, i,
  815. FrameIndexVirtualScavenging ? nullptr : RS);
  816. // Reset the iterator if we were at the beginning of the BB.
  817. if (AtBeginning) {
  818. I = BB->begin();
  819. DoIncr = false;
  820. }
  821. MI = nullptr;
  822. break;
  823. }
  824. // If we are looking at a call sequence, we need to keep track of
  825. // the SP adjustment made by each instruction in the sequence.
  826. // This includes both the frame setup/destroy pseudos (handled above),
  827. // as well as other instructions that have side effects w.r.t the SP.
  828. // Note that this must come after eliminateFrameIndex, because
  829. // if I itself referred to a frame index, we shouldn't count its own
  830. // adjustment.
  831. if (MI && InsideCallSequence)
  832. SPAdj += TII.getSPAdjust(MI);
  833. if (DoIncr && I != BB->end()) ++I;
  834. // Update register states.
  835. if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
  836. }
  837. }
  838. /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
  839. /// with physical registers. Use the register scavenger to find an
  840. /// appropriate register to use.
  841. ///
  842. /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
  843. /// iterate over the vreg use list, which at this point only contains machine
  844. /// operands for which eliminateFrameIndex need a new scratch reg.
  845. void
  846. WasmPEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
  847. // Run through the instructions and find any virtual registers.
  848. for (MachineFunction::iterator BB = Fn.begin(),
  849. E = Fn.end(); BB != E; ++BB) {
  850. RS->enterBasicBlock(&*BB);
  851. int SPAdj = 0;
  852. // The instruction stream may change in the loop, so check BB->end()
  853. // directly.
  854. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
  855. // We might end up here again with a NULL iterator if we scavenged a
  856. // register for which we inserted spill code for definition by what was
  857. // originally the first instruction in BB.
  858. if (I == MachineBasicBlock::iterator(nullptr))
  859. I = BB->begin();
  860. MachineInstr *MI = I;
  861. MachineBasicBlock::iterator J = std::next(I);
  862. MachineBasicBlock::iterator P =
  863. I == BB->begin() ? MachineBasicBlock::iterator(nullptr)
  864. : std::prev(I);
  865. // RS should process this instruction before we might scavenge at this
  866. // location. This is because we might be replacing a virtual register
  867. // defined by this instruction, and if so, registers killed by this
  868. // instruction are available, and defined registers are not.
  869. RS->forward(I);
  870. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  871. if (MI->getOperand(i).isReg()) {
  872. MachineOperand &MO = MI->getOperand(i);
  873. unsigned Reg = MO.getReg();
  874. if (Reg == 0)
  875. continue;
  876. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  877. continue;
  878. // When we first encounter a new virtual register, it
  879. // must be a definition.
  880. assert(MI->getOperand(i).isDef() &&
  881. "frame index virtual missing def!");
  882. // Scavenge a new scratch register
  883. const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
  884. unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
  885. ++NumScavengedRegs;
  886. // Replace this reference to the virtual register with the
  887. // scratch register.
  888. assert (ScratchReg && "Missing scratch register!");
  889. Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
  890. // Because this instruction was processed by the RS before this
  891. // register was allocated, make sure that the RS now records the
  892. // register as being used.
  893. RS->setRegUsed(ScratchReg);
  894. }
  895. }
  896. // If the scavenger needed to use one of its spill slots, the
  897. // spill code will have been inserted in between I and J. This is a
  898. // problem because we need the spill code before I: Move I to just
  899. // prior to J.
  900. if (I != std::prev(J)) {
  901. BB->splice(J, &*BB, I);
  902. // Before we move I, we need to prepare the RS to visit I again.
  903. // Specifically, RS will assert if it sees uses of registers that
  904. // it believes are undefined. Because we have already processed
  905. // register kills in I, when it visits I again, it will believe that
  906. // those registers are undefined. To avoid this situation, unprocess
  907. // the instruction I.
  908. assert(RS->getCurrentPosition() == I &&
  909. "The register scavenger has an unexpected position");
  910. I = P;
  911. RS->unprocess(P);
  912. } else
  913. ++I;
  914. }
  915. }
  916. }