PrologEpilogInserter.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. //===-- PrologEpilogInserter.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 pass provides an optional shrink wrapping variant of prolog/epilog
  18. // insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #define DEBUG_TYPE "pei"
  22. #include "PrologEpilogInserter.h"
  23. #include "llvm/ADT/IndexedMap.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SmallSet.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/CodeGen/MachineDominators.h"
  28. #include "llvm/CodeGen/MachineFrameInfo.h"
  29. #include "llvm/CodeGen/MachineInstr.h"
  30. #include "llvm/CodeGen/MachineLoopInfo.h"
  31. #include "llvm/CodeGen/MachineRegisterInfo.h"
  32. #include "llvm/CodeGen/RegisterScavenging.h"
  33. #include "llvm/IR/InlineAsm.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Support/Compiler.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Target/TargetFrameLowering.h"
  38. #include "llvm/Target/TargetInstrInfo.h"
  39. #include "llvm/Target/TargetMachine.h"
  40. #include "llvm/Target/TargetRegisterInfo.h"
  41. #include <climits>
  42. using namespace llvm;
  43. char PEI::ID = 0;
  44. char &llvm::PrologEpilogCodeInserterID = PEI::ID;
  45. INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
  46. "Prologue/Epilogue Insertion", false, false)
  47. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  48. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  49. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  50. INITIALIZE_PASS_END(PEI, "prologepilog",
  51. "Prologue/Epilogue Insertion & Frame Finalization",
  52. false, false)
  53. STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
  54. STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
  55. STATISTIC(NumBytesStackSpace,
  56. "Number of bytes used for stack in all functions");
  57. /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
  58. /// frame indexes with appropriate references.
  59. ///
  60. bool PEI::runOnMachineFunction(MachineFunction &Fn) {
  61. const Function* F = Fn.getFunction();
  62. const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
  63. const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
  64. assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
  65. RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
  66. FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
  67. // Calculate the MaxCallFrameSize and AdjustsStack variables for the
  68. // function's frame information. Also eliminates call frame pseudo
  69. // instructions.
  70. calculateCallsInformation(Fn);
  71. // Allow the target machine to make some adjustments to the function
  72. // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
  73. TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
  74. // Scan the function for modified callee saved registers and insert spill code
  75. // for any callee saved registers that are modified.
  76. calculateCalleeSavedRegisters(Fn);
  77. // Determine placement of CSR spill/restore code:
  78. // - With shrink wrapping, place spills and restores to tightly
  79. // enclose regions in the Machine CFG of the function where
  80. // they are used.
  81. // - Without shink wrapping (default), place all spills in the
  82. // entry block, all restores in return blocks.
  83. placeCSRSpillsAndRestores(Fn);
  84. // Add the code to save and restore the callee saved registers
  85. if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  86. Attribute::Naked))
  87. insertCSRSpillsAndRestores(Fn);
  88. // Allow the target machine to make final modifications to the function
  89. // before the frame layout is finalized.
  90. TFI->processFunctionBeforeFrameFinalized(Fn);
  91. // Calculate actual frame offsets for all abstract stack objects...
  92. calculateFrameObjectOffsets(Fn);
  93. // Add prolog and epilog code to the function. This function is required
  94. // to align the stack frame as necessary for any stack variables or
  95. // called functions. Because of this, calculateCalleeSavedRegisters()
  96. // must be called before this function in order to set the AdjustsStack
  97. // and MaxCallFrameSize variables.
  98. if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  99. Attribute::Naked))
  100. insertPrologEpilogCode(Fn);
  101. // Replace all MO_FrameIndex operands with physical register references
  102. // and actual offsets.
  103. //
  104. replaceFrameIndices(Fn);
  105. // If register scavenging is needed, as we've enabled doing it as a
  106. // post-pass, scavenge the virtual registers that frame index elimiation
  107. // inserted.
  108. if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
  109. scavengeFrameVirtualRegs(Fn);
  110. // Clear any vregs created by virtual scavenging.
  111. Fn.getRegInfo().clearVirtRegs();
  112. delete RS;
  113. clearAllSets();
  114. return true;
  115. }
  116. /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
  117. /// variables for the function's frame information and eliminate call frame
  118. /// pseudo instructions.
  119. void PEI::calculateCallsInformation(MachineFunction &Fn) {
  120. const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
  121. const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
  122. MachineFrameInfo *MFI = Fn.getFrameInfo();
  123. unsigned MaxCallFrameSize = 0;
  124. bool AdjustsStack = MFI->adjustsStack();
  125. // Get the function call frame set-up and tear-down instruction opcode
  126. int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
  127. int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
  128. // Early exit for targets which have no call frame setup/destroy pseudo
  129. // instructions.
  130. if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
  131. return;
  132. std::vector<MachineBasicBlock::iterator> FrameSDOps;
  133. for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
  134. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
  135. if (I->getOpcode() == FrameSetupOpcode ||
  136. I->getOpcode() == FrameDestroyOpcode) {
  137. assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
  138. " instructions should have a single immediate argument!");
  139. unsigned Size = I->getOperand(0).getImm();
  140. if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
  141. AdjustsStack = true;
  142. FrameSDOps.push_back(I);
  143. } else if (I->isInlineAsm()) {
  144. // Some inline asm's need a stack frame, as indicated by operand 1.
  145. unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  146. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  147. AdjustsStack = true;
  148. }
  149. MFI->setAdjustsStack(AdjustsStack);
  150. MFI->setMaxCallFrameSize(MaxCallFrameSize);
  151. for (std::vector<MachineBasicBlock::iterator>::iterator
  152. i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
  153. MachineBasicBlock::iterator I = *i;
  154. // If call frames are not being included as part of the stack frame, and
  155. // the target doesn't indicate otherwise, remove the call frame pseudos
  156. // here. The sub/add sp instruction pairs are still inserted, but we don't
  157. // need to track the SP adjustment for frame index elimination.
  158. if (TFI->canSimplifyCallFramePseudos(Fn))
  159. TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
  160. }
  161. }
  162. /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
  163. /// registers.
  164. void PEI::calculateCalleeSavedRegisters(MachineFunction &F) {
  165. const TargetRegisterInfo *RegInfo = F.getTarget().getRegisterInfo();
  166. const TargetFrameLowering *TFI = F.getTarget().getFrameLowering();
  167. MachineFrameInfo *MFI = F.getFrameInfo();
  168. // Get the callee saved register list...
  169. const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&F);
  170. // These are used to keep track the callee-save area. Initialize them.
  171. MinCSFrameIndex = INT_MAX;
  172. MaxCSFrameIndex = 0;
  173. // Early exit for targets which have no callee saved registers.
  174. if (CSRegs == 0 || CSRegs[0] == 0)
  175. return;
  176. // In Naked functions we aren't going to save any registers.
  177. if (F.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  178. Attribute::Naked))
  179. return;
  180. std::vector<CalleeSavedInfo> CSI;
  181. for (unsigned i = 0; CSRegs[i]; ++i) {
  182. unsigned Reg = CSRegs[i];
  183. if (F.getRegInfo().isPhysRegUsed(Reg)) {
  184. // If the reg is modified, save it!
  185. CSI.push_back(CalleeSavedInfo(Reg));
  186. }
  187. }
  188. if (CSI.empty())
  189. return; // Early exit if no callee saved registers are modified!
  190. unsigned NumFixedSpillSlots;
  191. const TargetFrameLowering::SpillSlot *FixedSpillSlots =
  192. TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
  193. // Now that we know which registers need to be saved and restored, allocate
  194. // stack slots for them.
  195. for (std::vector<CalleeSavedInfo>::iterator
  196. I = CSI.begin(), E = CSI.end(); I != E; ++I) {
  197. unsigned Reg = I->getReg();
  198. const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
  199. int FrameIdx;
  200. if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
  201. I->setFrameIdx(FrameIdx);
  202. continue;
  203. }
  204. // Check to see if this physreg must be spilled to a particular stack slot
  205. // on this target.
  206. const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
  207. while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
  208. FixedSlot->Reg != Reg)
  209. ++FixedSlot;
  210. if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
  211. // Nope, just spill it anywhere convenient.
  212. unsigned Align = RC->getAlignment();
  213. unsigned StackAlign = TFI->getStackAlignment();
  214. // We may not be able to satisfy the desired alignment specification of
  215. // the TargetRegisterClass if the stack alignment is smaller. Use the
  216. // min.
  217. Align = std::min(Align, StackAlign);
  218. FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
  219. if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
  220. if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
  221. } else {
  222. // Spill it to the stack where we must.
  223. FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
  224. }
  225. I->setFrameIdx(FrameIdx);
  226. }
  227. MFI->setCalleeSavedInfo(CSI);
  228. }
  229. /// insertCSRSpillsAndRestores - Insert spill and restore code for
  230. /// callee saved registers used in the function, handling shrink wrapping.
  231. ///
  232. void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
  233. // Get callee saved register information.
  234. MachineFrameInfo *MFI = Fn.getFrameInfo();
  235. const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  236. MFI->setCalleeSavedInfoValid(true);
  237. // Early exit if no callee saved registers are modified!
  238. if (CSI.empty())
  239. return;
  240. const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
  241. const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
  242. const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
  243. MachineBasicBlock::iterator I;
  244. if (!ShrinkWrapThisFunction) {
  245. // Spill using target interface.
  246. I = EntryBlock->begin();
  247. if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
  248. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  249. // Add the callee-saved register as live-in.
  250. // It's killed at the spill.
  251. EntryBlock->addLiveIn(CSI[i].getReg());
  252. // Insert the spill to the stack frame.
  253. unsigned Reg = CSI[i].getReg();
  254. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  255. TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
  256. CSI[i].getFrameIdx(), RC, TRI);
  257. }
  258. }
  259. // Restore using target interface.
  260. for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
  261. MachineBasicBlock* MBB = ReturnBlocks[ri];
  262. I = MBB->end(); --I;
  263. // Skip over all terminator instructions, which are part of the return
  264. // sequence.
  265. MachineBasicBlock::iterator I2 = I;
  266. while (I2 != MBB->begin() && (--I2)->isTerminator())
  267. I = I2;
  268. bool AtStart = I == MBB->begin();
  269. MachineBasicBlock::iterator BeforeI = I;
  270. if (!AtStart)
  271. --BeforeI;
  272. // Restore all registers immediately before the return and any
  273. // terminators that precede it.
  274. if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
  275. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  276. unsigned Reg = CSI[i].getReg();
  277. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  278. TII.loadRegFromStackSlot(*MBB, I, Reg,
  279. CSI[i].getFrameIdx(),
  280. RC, TRI);
  281. assert(I != MBB->begin() &&
  282. "loadRegFromStackSlot didn't insert any code!");
  283. // Insert in reverse order. loadRegFromStackSlot can insert
  284. // multiple instructions.
  285. if (AtStart)
  286. I = MBB->begin();
  287. else {
  288. I = BeforeI;
  289. ++I;
  290. }
  291. }
  292. }
  293. }
  294. return;
  295. }
  296. // Insert spills.
  297. std::vector<CalleeSavedInfo> blockCSI;
  298. for (CSRegBlockMap::iterator BI = CSRSave.begin(),
  299. BE = CSRSave.end(); BI != BE; ++BI) {
  300. MachineBasicBlock* MBB = BI->first;
  301. CSRegSet save = BI->second;
  302. if (save.empty())
  303. continue;
  304. blockCSI.clear();
  305. for (CSRegSet::iterator RI = save.begin(),
  306. RE = save.end(); RI != RE; ++RI) {
  307. blockCSI.push_back(CSI[*RI]);
  308. }
  309. assert(blockCSI.size() > 0 &&
  310. "Could not collect callee saved register info");
  311. I = MBB->begin();
  312. // When shrink wrapping, use stack slot stores/loads.
  313. for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
  314. // Add the callee-saved register as live-in.
  315. // It's killed at the spill.
  316. MBB->addLiveIn(blockCSI[i].getReg());
  317. // Insert the spill to the stack frame.
  318. unsigned Reg = blockCSI[i].getReg();
  319. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  320. TII.storeRegToStackSlot(*MBB, I, Reg,
  321. true,
  322. blockCSI[i].getFrameIdx(),
  323. RC, TRI);
  324. }
  325. }
  326. for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
  327. BE = CSRRestore.end(); BI != BE; ++BI) {
  328. MachineBasicBlock* MBB = BI->first;
  329. CSRegSet restore = BI->second;
  330. if (restore.empty())
  331. continue;
  332. blockCSI.clear();
  333. for (CSRegSet::iterator RI = restore.begin(),
  334. RE = restore.end(); RI != RE; ++RI) {
  335. blockCSI.push_back(CSI[*RI]);
  336. }
  337. assert(blockCSI.size() > 0 &&
  338. "Could not find callee saved register info");
  339. // If MBB is empty and needs restores, insert at the _beginning_.
  340. if (MBB->empty()) {
  341. I = MBB->begin();
  342. } else {
  343. I = MBB->end();
  344. --I;
  345. // Skip over all terminator instructions, which are part of the
  346. // return sequence.
  347. if (! I->isTerminator()) {
  348. ++I;
  349. } else {
  350. MachineBasicBlock::iterator I2 = I;
  351. while (I2 != MBB->begin() && (--I2)->isTerminator())
  352. I = I2;
  353. }
  354. }
  355. bool AtStart = I == MBB->begin();
  356. MachineBasicBlock::iterator BeforeI = I;
  357. if (!AtStart)
  358. --BeforeI;
  359. // Restore all registers immediately before the return and any
  360. // terminators that precede it.
  361. for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
  362. unsigned Reg = blockCSI[i].getReg();
  363. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  364. TII.loadRegFromStackSlot(*MBB, I, Reg,
  365. blockCSI[i].getFrameIdx(),
  366. RC, TRI);
  367. assert(I != MBB->begin() &&
  368. "loadRegFromStackSlot didn't insert any code!");
  369. // Insert in reverse order. loadRegFromStackSlot can insert
  370. // multiple instructions.
  371. if (AtStart)
  372. I = MBB->begin();
  373. else {
  374. I = BeforeI;
  375. ++I;
  376. }
  377. }
  378. }
  379. }
  380. /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
  381. static inline void
  382. AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
  383. bool StackGrowsDown, int64_t &Offset,
  384. unsigned &MaxAlign) {
  385. // If the stack grows down, add the object size to find the lowest address.
  386. if (StackGrowsDown)
  387. Offset += MFI->getObjectSize(FrameIdx);
  388. unsigned Align = MFI->getObjectAlignment(FrameIdx);
  389. // If the alignment of this object is greater than that of the stack, then
  390. // increase the stack alignment to match.
  391. MaxAlign = std::max(MaxAlign, Align);
  392. // Adjust to alignment boundary.
  393. Offset = (Offset + Align - 1) / Align * Align;
  394. if (StackGrowsDown) {
  395. DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
  396. MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
  397. } else {
  398. DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
  399. MFI->setObjectOffset(FrameIdx, Offset);
  400. Offset += MFI->getObjectSize(FrameIdx);
  401. }
  402. }
  403. /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
  404. /// abstract stack objects.
  405. ///
  406. void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
  407. const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
  408. bool StackGrowsDown =
  409. TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  410. // Loop over all of the stack objects, assigning sequential addresses...
  411. MachineFrameInfo *MFI = Fn.getFrameInfo();
  412. // Start at the beginning of the local area.
  413. // The Offset is the distance from the stack top in the direction
  414. // of stack growth -- so it's always nonnegative.
  415. int LocalAreaOffset = TFI.getOffsetOfLocalArea();
  416. if (StackGrowsDown)
  417. LocalAreaOffset = -LocalAreaOffset;
  418. assert(LocalAreaOffset >= 0
  419. && "Local area offset should be in direction of stack growth");
  420. int64_t Offset = LocalAreaOffset;
  421. // If there are fixed sized objects that are preallocated in the local area,
  422. // non-fixed objects can't be allocated right at the start of local area.
  423. // We currently don't support filling in holes in between fixed sized
  424. // objects, so we adjust 'Offset' to point to the end of last fixed sized
  425. // preallocated object.
  426. for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
  427. int64_t FixedOff;
  428. if (StackGrowsDown) {
  429. // The maximum distance from the stack pointer is at lower address of
  430. // the object -- which is given by offset. For down growing stack
  431. // the offset is negative, so we negate the offset to get the distance.
  432. FixedOff = -MFI->getObjectOffset(i);
  433. } else {
  434. // The maximum distance from the start pointer is at the upper
  435. // address of the object.
  436. FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
  437. }
  438. if (FixedOff > Offset) Offset = FixedOff;
  439. }
  440. // First assign frame offsets to stack objects that are used to spill
  441. // callee saved registers.
  442. if (StackGrowsDown) {
  443. for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
  444. // If the stack grows down, we need to add the size to find the lowest
  445. // address of the object.
  446. Offset += MFI->getObjectSize(i);
  447. unsigned Align = MFI->getObjectAlignment(i);
  448. // Adjust to alignment boundary
  449. Offset = (Offset+Align-1)/Align*Align;
  450. MFI->setObjectOffset(i, -Offset); // Set the computed offset
  451. }
  452. } else {
  453. int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
  454. for (int i = MaxCSFI; i >= MinCSFI ; --i) {
  455. unsigned Align = MFI->getObjectAlignment(i);
  456. // Adjust to alignment boundary
  457. Offset = (Offset+Align-1)/Align*Align;
  458. MFI->setObjectOffset(i, Offset);
  459. Offset += MFI->getObjectSize(i);
  460. }
  461. }
  462. unsigned MaxAlign = MFI->getMaxAlignment();
  463. // Make sure the special register scavenging spill slot is closest to the
  464. // frame pointer if a frame pointer is required.
  465. const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
  466. if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
  467. !RegInfo->needsStackRealignment(Fn)) {
  468. int SFI = RS->getScavengingFrameIndex();
  469. if (SFI >= 0)
  470. AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
  471. }
  472. // FIXME: Once this is working, then enable flag will change to a target
  473. // check for whether the frame is large enough to want to use virtual
  474. // frame index registers. Functions which don't want/need this optimization
  475. // will continue to use the existing code path.
  476. if (MFI->getUseLocalStackAllocationBlock()) {
  477. unsigned Align = MFI->getLocalFrameMaxAlign();
  478. // Adjust to alignment boundary.
  479. Offset = (Offset + Align - 1) / Align * Align;
  480. DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
  481. // Resolve offsets for objects in the local block.
  482. for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
  483. std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
  484. int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
  485. DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
  486. FIOffset << "]\n");
  487. MFI->setObjectOffset(Entry.first, FIOffset);
  488. }
  489. // Allocate the local block
  490. Offset += MFI->getLocalFrameSize();
  491. MaxAlign = std::max(Align, MaxAlign);
  492. }
  493. // Make sure that the stack protector comes before the local variables on the
  494. // stack.
  495. SmallSet<int, 16> LargeStackObjs;
  496. if (MFI->getStackProtectorIndex() >= 0) {
  497. AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
  498. Offset, MaxAlign);
  499. // Assign large stack objects first.
  500. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  501. if (MFI->isObjectPreAllocated(i) &&
  502. MFI->getUseLocalStackAllocationBlock())
  503. continue;
  504. if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
  505. continue;
  506. if (RS && (int)i == RS->getScavengingFrameIndex())
  507. continue;
  508. if (MFI->isDeadObjectIndex(i))
  509. continue;
  510. if (MFI->getStackProtectorIndex() == (int)i)
  511. continue;
  512. if (!MFI->MayNeedStackProtector(i))
  513. continue;
  514. AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
  515. LargeStackObjs.insert(i);
  516. }
  517. }
  518. // Then assign frame offsets to stack objects that are not used to spill
  519. // callee saved registers.
  520. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  521. if (MFI->isObjectPreAllocated(i) &&
  522. MFI->getUseLocalStackAllocationBlock())
  523. continue;
  524. if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
  525. continue;
  526. if (RS && (int)i == RS->getScavengingFrameIndex())
  527. continue;
  528. if (MFI->isDeadObjectIndex(i))
  529. continue;
  530. if (MFI->getStackProtectorIndex() == (int)i)
  531. continue;
  532. if (LargeStackObjs.count(i))
  533. continue;
  534. AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
  535. }
  536. // Make sure the special register scavenging spill slot is closest to the
  537. // stack pointer.
  538. if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
  539. !RegInfo->useFPForScavengingIndex(Fn))) {
  540. int SFI = RS->getScavengingFrameIndex();
  541. if (SFI >= 0)
  542. AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
  543. }
  544. if (!TFI.targetHandlesStackFrameRounding()) {
  545. // If we have reserved argument space for call sites in the function
  546. // immediately on entry to the current function, count it as part of the
  547. // overall stack size.
  548. if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
  549. Offset += MFI->getMaxCallFrameSize();
  550. // Round up the size to a multiple of the alignment. If the function has
  551. // any calls or alloca's, align to the target's StackAlignment value to
  552. // ensure that the callee's frame or the alloca data is suitably aligned;
  553. // otherwise, for leaf functions, align to the TransientStackAlignment
  554. // value.
  555. unsigned StackAlign;
  556. if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
  557. (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
  558. StackAlign = TFI.getStackAlignment();
  559. else
  560. StackAlign = TFI.getTransientStackAlignment();
  561. // If the frame pointer is eliminated, all frame offsets will be relative to
  562. // SP not FP. Align to MaxAlign so this works.
  563. StackAlign = std::max(StackAlign, MaxAlign);
  564. unsigned AlignMask = StackAlign - 1;
  565. Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
  566. }
  567. // Update frame info to pretend that this is part of the stack...
  568. int64_t StackSize = Offset - LocalAreaOffset;
  569. MFI->setStackSize(StackSize);
  570. NumBytesStackSpace += StackSize;
  571. }
  572. /// insertPrologEpilogCode - Scan the function for modified callee saved
  573. /// registers, insert spill code for these callee saved registers, then add
  574. /// prolog and epilog code to the function.
  575. ///
  576. void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
  577. const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
  578. // Add prologue to the function...
  579. TFI.emitPrologue(Fn);
  580. // Add epilogue to restore the callee-save registers in each exiting block
  581. for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
  582. // If last instruction is a return instruction, add an epilogue
  583. if (!I->empty() && I->back().isReturn())
  584. TFI.emitEpilogue(Fn, *I);
  585. }
  586. // Emit additional code that is required to support segmented stacks, if
  587. // we've been asked for it. This, when linked with a runtime with support
  588. // for segmented stacks (libgcc is one), will result in allocating stack
  589. // space in small chunks instead of one large contiguous block.
  590. if (Fn.getTarget().Options.EnableSegmentedStacks)
  591. TFI.adjustForSegmentedStacks(Fn);
  592. // Emit additional code that is required to explicitly handle the stack in
  593. // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
  594. // approach is rather similar to that of Segmented Stacks, but it uses a
  595. // different conditional check and another BIF for allocating more stack
  596. // space.
  597. if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
  598. TFI.adjustForHiPEPrologue(Fn);
  599. }
  600. /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
  601. /// register references and actual offsets.
  602. ///
  603. void PEI::replaceFrameIndices(MachineFunction &Fn) {
  604. if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
  605. const TargetMachine &TM = Fn.getTarget();
  606. assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
  607. const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
  608. const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
  609. const TargetFrameLowering *TFI = TM.getFrameLowering();
  610. bool StackGrowsDown =
  611. TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  612. int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
  613. int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
  614. for (MachineFunction::iterator BB = Fn.begin(),
  615. E = Fn.end(); BB != E; ++BB) {
  616. #ifndef NDEBUG
  617. int SPAdjCount = 0; // frame setup / destroy count.
  618. #endif
  619. int SPAdj = 0; // SP offset due to call frame setup / destroy.
  620. if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
  621. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
  622. if (I->getOpcode() == FrameSetupOpcode ||
  623. I->getOpcode() == FrameDestroyOpcode) {
  624. #ifndef NDEBUG
  625. // Track whether we see even pairs of them
  626. SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
  627. #endif
  628. // Remember how much SP has been adjusted to create the call
  629. // frame.
  630. int Size = I->getOperand(0).getImm();
  631. if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
  632. (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
  633. Size = -Size;
  634. SPAdj += Size;
  635. MachineBasicBlock::iterator PrevI = BB->end();
  636. if (I != BB->begin()) PrevI = prior(I);
  637. TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
  638. // Visit the instructions created by eliminateCallFramePseudoInstr().
  639. if (PrevI == BB->end())
  640. I = BB->begin(); // The replaced instr was the first in the block.
  641. else
  642. I = llvm::next(PrevI);
  643. continue;
  644. }
  645. MachineInstr *MI = I;
  646. bool DoIncr = true;
  647. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  648. if (!MI->getOperand(i).isFI())
  649. continue;
  650. // Some instructions (e.g. inline asm instructions) can have
  651. // multiple frame indices and/or cause eliminateFrameIndex
  652. // to insert more than one instruction. We need the register
  653. // scavenger to go through all of these instructions so that
  654. // it can update its register information. We keep the
  655. // iterator at the point before insertion so that we can
  656. // revisit them in full.
  657. bool AtBeginning = (I == BB->begin());
  658. if (!AtBeginning) --I;
  659. // If this instruction has a FrameIndex operand, we need to
  660. // use that target machine register info object to eliminate
  661. // it.
  662. TRI.eliminateFrameIndex(MI, SPAdj, i,
  663. FrameIndexVirtualScavenging ? NULL : RS);
  664. // Reset the iterator if we were at the beginning of the BB.
  665. if (AtBeginning) {
  666. I = BB->begin();
  667. DoIncr = false;
  668. }
  669. MI = 0;
  670. break;
  671. }
  672. if (DoIncr && I != BB->end()) ++I;
  673. // Update register states.
  674. if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
  675. }
  676. // If we have evenly matched pairs of frame setup / destroy instructions,
  677. // make sure the adjustments come out to zero. If we don't have matched
  678. // pairs, we can't be sure the missing bit isn't in another basic block
  679. // due to a custom inserter playing tricks, so just asserting SPAdj==0
  680. // isn't sufficient. See tMOVCC on Thumb1, for example.
  681. assert((SPAdjCount || SPAdj == 0) &&
  682. "Unbalanced call frame setup / destroy pairs?");
  683. }
  684. }
  685. /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
  686. /// with physical registers. Use the register scavenger to find an
  687. /// appropriate register to use.
  688. ///
  689. /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
  690. /// iterate over the vreg use list, which at this point only contains machine
  691. /// operands for which eliminateFrameIndex need a new scratch reg.
  692. void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
  693. // Run through the instructions and find any virtual registers.
  694. for (MachineFunction::iterator BB = Fn.begin(),
  695. E = Fn.end(); BB != E; ++BB) {
  696. RS->enterBasicBlock(BB);
  697. unsigned VirtReg = 0;
  698. unsigned ScratchReg = 0;
  699. int SPAdj = 0;
  700. // The instruction stream may change in the loop, so check BB->end()
  701. // directly.
  702. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
  703. MachineInstr *MI = I;
  704. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  705. if (MI->getOperand(i).isReg()) {
  706. MachineOperand &MO = MI->getOperand(i);
  707. unsigned Reg = MO.getReg();
  708. if (Reg == 0)
  709. continue;
  710. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  711. continue;
  712. ++NumVirtualFrameRegs;
  713. // Have we already allocated a scratch register for this virtual?
  714. if (Reg != VirtReg) {
  715. // When we first encounter a new virtual register, it
  716. // must be a definition.
  717. assert(MI->getOperand(i).isDef() &&
  718. "frame index virtual missing def!");
  719. // Scavenge a new scratch register
  720. VirtReg = Reg;
  721. const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
  722. ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
  723. ++NumScavengedRegs;
  724. }
  725. // Replace this reference to the virtual register with the
  726. // scratch register.
  727. assert (ScratchReg && "Missing scratch register!");
  728. MI->getOperand(i).setReg(ScratchReg);
  729. }
  730. }
  731. RS->forward(I);
  732. ++I;
  733. }
  734. }
  735. }