1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
14 // This pass must be run after register allocation. After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
17 // This pass provides an optional shrink wrapping variant of prolog/epilog
18 // insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "pei"
23 #include "PrologEpilogInserter.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegisterScavenging.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetFrameLowering.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/ADT/IndexedMap.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/STLExtras.h"
48 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
49 "Prologue/Epilogue Insertion", false, false)
50 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
51 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
52 INITIALIZE_PASS_END(PEI, "prologepilog",
53 "Prologue/Epilogue Insertion", false, false)
55 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
56 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
58 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
59 /// prolog and epilog code, and eliminates abstract frame references.
61 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
63 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
64 /// frame indexes with appropriate references.
66 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
67 const Function* F = Fn.getFunction();
68 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
69 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
71 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
72 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
74 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
75 // function's frame information. Also eliminates call frame pseudo
77 calculateCallsInformation(Fn);
79 // Allow the target machine to make some adjustments to the function
80 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
81 TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
83 // Scan the function for modified callee saved registers and insert spill code
84 // for any callee saved registers that are modified.
85 calculateCalleeSavedRegisters(Fn);
87 // Determine placement of CSR spill/restore code:
88 // - With shrink wrapping, place spills and restores to tightly
89 // enclose regions in the Machine CFG of the function where
91 // - Without shink wrapping (default), place all spills in the
92 // entry block, all restores in return blocks.
93 placeCSRSpillsAndRestores(Fn);
95 // Add the code to save and restore the callee saved registers
96 if (!F->hasFnAttr(Attribute::Naked))
97 insertCSRSpillsAndRestores(Fn);
99 // Allow the target machine to make final modifications to the function
100 // before the frame layout is finalized.
101 TFI->processFunctionBeforeFrameFinalized(Fn);
103 // Calculate actual frame offsets for all abstract stack objects...
104 calculateFrameObjectOffsets(Fn);
106 // Add prolog and epilog code to the function. This function is required
107 // to align the stack frame as necessary for any stack variables or
108 // called functions. Because of this, calculateCalleeSavedRegisters()
109 // must be called before this function in order to set the AdjustsStack
110 // and MaxCallFrameSize variables.
111 if (!F->hasFnAttr(Attribute::Naked))
112 insertPrologEpilogCode(Fn);
114 // Replace all MO_FrameIndex operands with physical register references
115 // and actual offsets.
117 replaceFrameIndices(Fn);
119 // If register scavenging is needed, as we've enabled doing it as a
120 // post-pass, scavenge the virtual registers that frame index elimiation
122 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
123 scavengeFrameVirtualRegs(Fn);
131 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
132 AU.setPreservesCFG();
133 if (ShrinkWrapping || ShrinkWrapFunc != "") {
134 AU.addRequired<MachineLoopInfo>();
135 AU.addRequired<MachineDominatorTree>();
137 AU.addPreserved<MachineLoopInfo>();
138 AU.addPreserved<MachineDominatorTree>();
139 MachineFunctionPass::getAnalysisUsage(AU);
143 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
144 /// variables for the function's frame information and eliminate call frame
145 /// pseudo instructions.
146 void PEI::calculateCallsInformation(MachineFunction &Fn) {
147 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
148 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
149 MachineFrameInfo *MFI = Fn.getFrameInfo();
151 unsigned MaxCallFrameSize = 0;
152 bool AdjustsStack = MFI->adjustsStack();
154 // Get the function call frame set-up and tear-down instruction opcode
155 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
156 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
158 // Early exit for targets which have no call frame setup/destroy pseudo
160 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
163 std::vector<MachineBasicBlock::iterator> FrameSDOps;
164 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
165 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
166 if (I->getOpcode() == FrameSetupOpcode ||
167 I->getOpcode() == FrameDestroyOpcode) {
168 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
169 " instructions should have a single immediate argument!");
170 unsigned Size = I->getOperand(0).getImm();
171 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
173 FrameSDOps.push_back(I);
174 } else if (I->isInlineAsm()) {
175 // Some inline asm's need a stack frame, as indicated by operand 1.
176 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
177 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
181 MFI->setAdjustsStack(AdjustsStack);
182 MFI->setMaxCallFrameSize(MaxCallFrameSize);
184 for (std::vector<MachineBasicBlock::iterator>::iterator
185 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
186 MachineBasicBlock::iterator I = *i;
188 // If call frames are not being included as part of the stack frame, and
189 // the target doesn't indicate otherwise, remove the call frame pseudos
190 // here. The sub/add sp instruction pairs are still inserted, but we don't
191 // need to track the SP adjustment for frame index elimination.
192 if (TFI->canSimplifyCallFramePseudos(Fn))
193 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
198 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
200 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
201 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
202 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
203 MachineFrameInfo *MFI = Fn.getFrameInfo();
205 // Get the callee saved register list...
206 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
208 // These are used to keep track the callee-save area. Initialize them.
209 MinCSFrameIndex = INT_MAX;
212 // Early exit for targets which have no callee saved registers.
213 if (CSRegs == 0 || CSRegs[0] == 0)
216 // In Naked functions we aren't going to save any registers.
217 if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
220 std::vector<CalleeSavedInfo> CSI;
221 for (unsigned i = 0; CSRegs[i]; ++i) {
222 unsigned Reg = CSRegs[i];
223 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
224 // If the reg is modified, save it!
225 CSI.push_back(CalleeSavedInfo(Reg));
227 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
228 *AliasSet; ++AliasSet) { // Check alias registers too.
229 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
230 CSI.push_back(CalleeSavedInfo(Reg));
238 return; // Early exit if no callee saved registers are modified!
240 unsigned NumFixedSpillSlots;
241 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
242 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
244 // Now that we know which registers need to be saved and restored, allocate
245 // stack slots for them.
246 for (std::vector<CalleeSavedInfo>::iterator
247 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
248 unsigned Reg = I->getReg();
249 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
252 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
253 I->setFrameIdx(FrameIdx);
257 // Check to see if this physreg must be spilled to a particular stack slot
259 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
260 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
261 FixedSlot->Reg != Reg)
264 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
265 // Nope, just spill it anywhere convenient.
266 unsigned Align = RC->getAlignment();
267 unsigned StackAlign = TFI->getStackAlignment();
269 // We may not be able to satisfy the desired alignment specification of
270 // the TargetRegisterClass if the stack alignment is smaller. Use the
272 Align = std::min(Align, StackAlign);
273 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
274 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
275 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
277 // Spill it to the stack where we must.
278 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
281 I->setFrameIdx(FrameIdx);
284 MFI->setCalleeSavedInfo(CSI);
287 /// insertCSRSpillsAndRestores - Insert spill and restore code for
288 /// callee saved registers used in the function, handling shrink wrapping.
290 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
291 // Get callee saved register information.
292 MachineFrameInfo *MFI = Fn.getFrameInfo();
293 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
295 MFI->setCalleeSavedInfoValid(true);
297 // Early exit if no callee saved registers are modified!
301 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
302 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
303 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
304 MachineBasicBlock::iterator I;
306 if (! ShrinkWrapThisFunction) {
307 // Spill using target interface.
308 I = EntryBlock->begin();
309 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
310 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
311 // Add the callee-saved register as live-in.
312 // It's killed at the spill.
313 EntryBlock->addLiveIn(CSI[i].getReg());
315 // Insert the spill to the stack frame.
316 unsigned Reg = CSI[i].getReg();
317 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
318 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
319 CSI[i].getFrameIdx(), RC, TRI);
323 // Restore using target interface.
324 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
325 MachineBasicBlock* MBB = ReturnBlocks[ri];
328 // Skip over all terminator instructions, which are part of the return
330 MachineBasicBlock::iterator I2 = I;
331 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
334 bool AtStart = I == MBB->begin();
335 MachineBasicBlock::iterator BeforeI = I;
339 // Restore all registers immediately before the return and any
340 // terminators that preceed it.
341 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
342 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
343 unsigned Reg = CSI[i].getReg();
344 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
345 TII.loadRegFromStackSlot(*MBB, I, Reg,
346 CSI[i].getFrameIdx(),
348 assert(I != MBB->begin() &&
349 "loadRegFromStackSlot didn't insert any code!");
350 // Insert in reverse order. loadRegFromStackSlot can insert
351 // multiple instructions.
365 std::vector<CalleeSavedInfo> blockCSI;
366 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
367 BE = CSRSave.end(); BI != BE; ++BI) {
368 MachineBasicBlock* MBB = BI->first;
369 CSRegSet save = BI->second;
375 for (CSRegSet::iterator RI = save.begin(),
376 RE = save.end(); RI != RE; ++RI) {
377 blockCSI.push_back(CSI[*RI]);
379 assert(blockCSI.size() > 0 &&
380 "Could not collect callee saved register info");
384 // When shrink wrapping, use stack slot stores/loads.
385 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
386 // Add the callee-saved register as live-in.
387 // It's killed at the spill.
388 MBB->addLiveIn(blockCSI[i].getReg());
390 // Insert the spill to the stack frame.
391 unsigned Reg = blockCSI[i].getReg();
392 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
393 TII.storeRegToStackSlot(*MBB, I, Reg,
395 blockCSI[i].getFrameIdx(),
400 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
401 BE = CSRRestore.end(); BI != BE; ++BI) {
402 MachineBasicBlock* MBB = BI->first;
403 CSRegSet restore = BI->second;
409 for (CSRegSet::iterator RI = restore.begin(),
410 RE = restore.end(); RI != RE; ++RI) {
411 blockCSI.push_back(CSI[*RI]);
413 assert(blockCSI.size() > 0 &&
414 "Could not find callee saved register info");
416 // If MBB is empty and needs restores, insert at the _beginning_.
423 // Skip over all terminator instructions, which are part of the
425 if (! I->getDesc().isTerminator()) {
428 MachineBasicBlock::iterator I2 = I;
429 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
434 bool AtStart = I == MBB->begin();
435 MachineBasicBlock::iterator BeforeI = I;
439 // Restore all registers immediately before the return and any
440 // terminators that preceed it.
441 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
442 unsigned Reg = blockCSI[i].getReg();
443 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
444 TII.loadRegFromStackSlot(*MBB, I, Reg,
445 blockCSI[i].getFrameIdx(),
447 assert(I != MBB->begin() &&
448 "loadRegFromStackSlot didn't insert any code!");
449 // Insert in reverse order. loadRegFromStackSlot can insert
450 // multiple instructions.
461 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
463 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
464 bool StackGrowsDown, int64_t &Offset,
465 unsigned &MaxAlign) {
466 // If the stack grows down, add the object size to find the lowest address.
468 Offset += MFI->getObjectSize(FrameIdx);
470 unsigned Align = MFI->getObjectAlignment(FrameIdx);
472 // If the alignment of this object is greater than that of the stack, then
473 // increase the stack alignment to match.
474 MaxAlign = std::max(MaxAlign, Align);
476 // Adjust to alignment boundary.
477 Offset = (Offset + Align - 1) / Align * Align;
479 if (StackGrowsDown) {
480 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
481 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
483 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
484 MFI->setObjectOffset(FrameIdx, Offset);
485 Offset += MFI->getObjectSize(FrameIdx);
489 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
490 /// abstract stack objects.
492 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
493 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
495 bool StackGrowsDown =
496 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
498 // Loop over all of the stack objects, assigning sequential addresses...
499 MachineFrameInfo *MFI = Fn.getFrameInfo();
501 // Start at the beginning of the local area.
502 // The Offset is the distance from the stack top in the direction
503 // of stack growth -- so it's always nonnegative.
504 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
506 LocalAreaOffset = -LocalAreaOffset;
507 assert(LocalAreaOffset >= 0
508 && "Local area offset should be in direction of stack growth");
509 int64_t Offset = LocalAreaOffset;
511 // If there are fixed sized objects that are preallocated in the local area,
512 // non-fixed objects can't be allocated right at the start of local area.
513 // We currently don't support filling in holes in between fixed sized
514 // objects, so we adjust 'Offset' to point to the end of last fixed sized
515 // preallocated object.
516 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
518 if (StackGrowsDown) {
519 // The maximum distance from the stack pointer is at lower address of
520 // the object -- which is given by offset. For down growing stack
521 // the offset is negative, so we negate the offset to get the distance.
522 FixedOff = -MFI->getObjectOffset(i);
524 // The maximum distance from the start pointer is at the upper
525 // address of the object.
526 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
528 if (FixedOff > Offset) Offset = FixedOff;
531 // First assign frame offsets to stack objects that are used to spill
532 // callee saved registers.
533 if (StackGrowsDown) {
534 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
535 // If the stack grows down, we need to add the size to find the lowest
536 // address of the object.
537 Offset += MFI->getObjectSize(i);
539 unsigned Align = MFI->getObjectAlignment(i);
540 // Adjust to alignment boundary
541 Offset = (Offset+Align-1)/Align*Align;
543 MFI->setObjectOffset(i, -Offset); // Set the computed offset
546 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
547 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
548 unsigned Align = MFI->getObjectAlignment(i);
549 // Adjust to alignment boundary
550 Offset = (Offset+Align-1)/Align*Align;
552 MFI->setObjectOffset(i, Offset);
553 Offset += MFI->getObjectSize(i);
557 unsigned MaxAlign = MFI->getMaxAlignment();
559 // Make sure the special register scavenging spill slot is closest to the
560 // frame pointer if a frame pointer is required.
561 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
562 if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
563 !RegInfo->needsStackRealignment(Fn)) {
564 int SFI = RS->getScavengingFrameIndex();
566 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
569 // FIXME: Once this is working, then enable flag will change to a target
570 // check for whether the frame is large enough to want to use virtual
571 // frame index registers. Functions which don't want/need this optimization
572 // will continue to use the existing code path.
573 if (MFI->getUseLocalStackAllocationBlock()) {
574 unsigned Align = MFI->getLocalFrameMaxAlign();
576 // Adjust to alignment boundary.
577 Offset = (Offset + Align - 1) / Align * Align;
579 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
581 // Resolve offsets for objects in the local block.
582 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
583 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
584 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
585 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
587 MFI->setObjectOffset(Entry.first, FIOffset);
589 // Allocate the local block
590 Offset += MFI->getLocalFrameSize();
592 MaxAlign = std::max(Align, MaxAlign);
595 // Make sure that the stack protector comes before the local variables on the
597 SmallSet<int, 16> LargeStackObjs;
598 if (MFI->getStackProtectorIndex() >= 0) {
599 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
602 // Assign large stack objects first.
603 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
604 if (MFI->isObjectPreAllocated(i) &&
605 MFI->getUseLocalStackAllocationBlock())
607 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
609 if (RS && (int)i == RS->getScavengingFrameIndex())
611 if (MFI->isDeadObjectIndex(i))
613 if (MFI->getStackProtectorIndex() == (int)i)
615 if (!MFI->MayNeedStackProtector(i))
618 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
619 LargeStackObjs.insert(i);
623 // Then assign frame offsets to stack objects that are not used to spill
624 // callee saved registers.
625 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
626 if (MFI->isObjectPreAllocated(i) &&
627 MFI->getUseLocalStackAllocationBlock())
629 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
631 if (RS && (int)i == RS->getScavengingFrameIndex())
633 if (MFI->isDeadObjectIndex(i))
635 if (MFI->getStackProtectorIndex() == (int)i)
637 if (LargeStackObjs.count(i))
640 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
643 // Make sure the special register scavenging spill slot is closest to the
645 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
646 !RegInfo->useFPForScavengingIndex(Fn))) {
647 int SFI = RS->getScavengingFrameIndex();
649 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
652 if (!TFI.targetHandlesStackFrameRounding()) {
653 // If we have reserved argument space for call sites in the function
654 // immediately on entry to the current function, count it as part of the
655 // overall stack size.
656 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
657 Offset += MFI->getMaxCallFrameSize();
659 // Round up the size to a multiple of the alignment. If the function has
660 // any calls or alloca's, align to the target's StackAlignment value to
661 // ensure that the callee's frame or the alloca data is suitably aligned;
662 // otherwise, for leaf functions, align to the TransientStackAlignment
665 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
666 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
667 StackAlign = TFI.getStackAlignment();
669 StackAlign = TFI.getTransientStackAlignment();
671 // If the frame pointer is eliminated, all frame offsets will be relative to
672 // SP not FP. Align to MaxAlign so this works.
673 StackAlign = std::max(StackAlign, MaxAlign);
674 unsigned AlignMask = StackAlign - 1;
675 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
678 // Update frame info to pretend that this is part of the stack...
679 MFI->setStackSize(Offset - LocalAreaOffset);
682 /// insertPrologEpilogCode - Scan the function for modified callee saved
683 /// registers, insert spill code for these callee saved registers, then add
684 /// prolog and epilog code to the function.
686 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
687 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
689 // Add prologue to the function...
690 TFI.emitPrologue(Fn);
692 // Add epilogue to restore the callee-save registers in each exiting block
693 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
694 // If last instruction is a return instruction, add an epilogue
695 if (!I->empty() && I->back().getDesc().isReturn())
696 TFI.emitEpilogue(Fn, *I);
700 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
701 /// register references and actual offsets.
703 void PEI::replaceFrameIndices(MachineFunction &Fn) {
704 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
706 const TargetMachine &TM = Fn.getTarget();
707 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
708 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
709 const TargetFrameLowering *TFI = TM.getFrameLowering();
710 bool StackGrowsDown =
711 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
712 int FrameSetupOpcode = TRI.getCallFrameSetupOpcode();
713 int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
715 for (MachineFunction::iterator BB = Fn.begin(),
716 E = Fn.end(); BB != E; ++BB) {
718 int SPAdjCount = 0; // frame setup / destroy count.
720 int SPAdj = 0; // SP offset due to call frame setup / destroy.
721 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
723 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
725 if (I->getOpcode() == FrameSetupOpcode ||
726 I->getOpcode() == FrameDestroyOpcode) {
728 // Track whether we see even pairs of them
729 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
731 // Remember how much SP has been adjusted to create the call
733 int Size = I->getOperand(0).getImm();
735 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
736 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
741 MachineBasicBlock::iterator PrevI = BB->end();
742 if (I != BB->begin()) PrevI = prior(I);
743 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
745 // Visit the instructions created by eliminateCallFramePseudoInstr().
746 if (PrevI == BB->end())
747 I = BB->begin(); // The replaced instr was the first in the block.
749 I = llvm::next(PrevI);
753 MachineInstr *MI = I;
755 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
756 if (MI->getOperand(i).isFI()) {
757 // Some instructions (e.g. inline asm instructions) can have
758 // multiple frame indices and/or cause eliminateFrameIndex
759 // to insert more than one instruction. We need the register
760 // scavenger to go through all of these instructions so that
761 // it can update its register information. We keep the
762 // iterator at the point before insertion so that we can
763 // revisit them in full.
764 bool AtBeginning = (I == BB->begin());
765 if (!AtBeginning) --I;
767 // If this instruction has a FrameIndex operand, we need to
768 // use that target machine register info object to eliminate
770 TRI.eliminateFrameIndex(MI, SPAdj,
771 FrameIndexVirtualScavenging ? NULL : RS);
773 // Reset the iterator if we were at the beginning of the BB.
783 if (DoIncr && I != BB->end()) ++I;
785 // Update register states.
786 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
789 // If we have evenly matched pairs of frame setup / destroy instructions,
790 // make sure the adjustments come out to zero. If we don't have matched
791 // pairs, we can't be sure the missing bit isn't in another basic block
792 // due to a custom inserter playing tricks, so just asserting SPAdj==0
793 // isn't sufficient. See tMOVCC on Thumb1, for example.
794 assert((SPAdjCount || SPAdj == 0) &&
795 "Unbalanced call frame setup / destroy pairs?");
799 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
800 /// with physical registers. Use the register scavenger to find an
801 /// appropriate register to use.
802 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
803 // Run through the instructions and find any virtual registers.
804 for (MachineFunction::iterator BB = Fn.begin(),
805 E = Fn.end(); BB != E; ++BB) {
806 RS->enterBasicBlock(BB);
808 unsigned VirtReg = 0;
809 unsigned ScratchReg = 0;
812 // The instruction stream may change in the loop, so check BB->end()
814 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
815 MachineInstr *MI = I;
816 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
817 if (MI->getOperand(i).isReg()) {
818 MachineOperand &MO = MI->getOperand(i);
819 unsigned Reg = MO.getReg();
822 if (!TargetRegisterInfo::isVirtualRegister(Reg))
825 ++NumVirtualFrameRegs;
827 // Have we already allocated a scratch register for this virtual?
828 if (Reg != VirtReg) {
829 // When we first encounter a new virtual register, it
830 // must be a definition.
831 assert(MI->getOperand(i).isDef() &&
832 "frame index virtual missing def!");
833 // Scavenge a new scratch register
835 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
836 ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
839 // Replace this reference to the virtual register with the
841 assert (ScratchReg && "Missing scratch register!");
842 MI->getOperand(i).setReg(ScratchReg);