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/TargetOptions.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetFrameLowering.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/ADT/IndexedMap.h"
40 #include "llvm/ADT/SmallSet.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/STLExtras.h"
49 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
50 "Prologue/Epilogue Insertion", false, false)
51 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
52 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
53 INITIALIZE_PASS_END(PEI, "prologepilog",
54 "Prologue/Epilogue Insertion", false, false)
56 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
57 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
58 STATISTIC(NumBytesStackSpace, "Number of bytes used for stack in all functions");
60 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
61 /// prolog and epilog code, and eliminates abstract frame references.
63 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
65 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
66 /// frame indexes with appropriate references.
68 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
69 const Function* F = Fn.getFunction();
70 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
71 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
73 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
74 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
76 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
77 // function's frame information. Also eliminates call frame pseudo
79 calculateCallsInformation(Fn);
81 // Allow the target machine to make some adjustments to the function
82 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
83 TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
85 // Scan the function for modified callee saved registers and insert spill code
86 // for any callee saved registers that are modified.
87 calculateCalleeSavedRegisters(Fn);
89 // Determine placement of CSR spill/restore code:
90 // - With shrink wrapping, place spills and restores to tightly
91 // enclose regions in the Machine CFG of the function where
93 // - Without shink wrapping (default), place all spills in the
94 // entry block, all restores in return blocks.
95 placeCSRSpillsAndRestores(Fn);
97 // Add the code to save and restore the callee saved registers
98 if (!F->hasFnAttr(Attribute::Naked))
99 insertCSRSpillsAndRestores(Fn);
101 // Allow the target machine to make final modifications to the function
102 // before the frame layout is finalized.
103 TFI->processFunctionBeforeFrameFinalized(Fn);
105 // Calculate actual frame offsets for all abstract stack objects...
106 calculateFrameObjectOffsets(Fn);
108 // Add prolog and epilog code to the function. This function is required
109 // to align the stack frame as necessary for any stack variables or
110 // called functions. Because of this, calculateCalleeSavedRegisters()
111 // must be called before this function in order to set the AdjustsStack
112 // and MaxCallFrameSize variables.
113 if (!F->hasFnAttr(Attribute::Naked))
114 insertPrologEpilogCode(Fn);
116 // Replace all MO_FrameIndex operands with physical register references
117 // and actual offsets.
119 replaceFrameIndices(Fn);
121 // If register scavenging is needed, as we've enabled doing it as a
122 // post-pass, scavenge the virtual registers that frame index elimiation
124 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
125 scavengeFrameVirtualRegs(Fn);
133 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
134 AU.setPreservesCFG();
135 if (ShrinkWrapping || ShrinkWrapFunc != "") {
136 AU.addRequired<MachineLoopInfo>();
137 AU.addRequired<MachineDominatorTree>();
139 AU.addPreserved<MachineLoopInfo>();
140 AU.addPreserved<MachineDominatorTree>();
141 MachineFunctionPass::getAnalysisUsage(AU);
145 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
146 /// variables for the function's frame information and eliminate call frame
147 /// pseudo instructions.
148 void PEI::calculateCallsInformation(MachineFunction &Fn) {
149 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
150 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
151 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
152 MachineFrameInfo *MFI = Fn.getFrameInfo();
154 unsigned MaxCallFrameSize = 0;
155 bool AdjustsStack = MFI->adjustsStack();
157 // Get the function call frame set-up and tear-down instruction opcode
158 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
159 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
161 // Early exit for targets which have no call frame setup/destroy pseudo
163 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
166 std::vector<MachineBasicBlock::iterator> FrameSDOps;
167 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
168 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
169 if (I->getOpcode() == FrameSetupOpcode ||
170 I->getOpcode() == FrameDestroyOpcode) {
171 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
172 " instructions should have a single immediate argument!");
173 unsigned Size = I->getOperand(0).getImm();
174 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
176 FrameSDOps.push_back(I);
177 } else if (I->isInlineAsm()) {
178 // Some inline asm's need a stack frame, as indicated by operand 1.
179 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
180 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
184 MFI->setAdjustsStack(AdjustsStack);
185 MFI->setMaxCallFrameSize(MaxCallFrameSize);
187 for (std::vector<MachineBasicBlock::iterator>::iterator
188 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
189 MachineBasicBlock::iterator I = *i;
191 // If call frames are not being included as part of the stack frame, and
192 // the target doesn't indicate otherwise, remove the call frame pseudos
193 // here. The sub/add sp instruction pairs are still inserted, but we don't
194 // need to track the SP adjustment for frame index elimination.
195 if (TFI->canSimplifyCallFramePseudos(Fn))
196 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
201 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
203 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
204 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
205 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
206 MachineFrameInfo *MFI = Fn.getFrameInfo();
208 // Get the callee saved register list...
209 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
211 // These are used to keep track the callee-save area. Initialize them.
212 MinCSFrameIndex = INT_MAX;
215 // Early exit for targets which have no callee saved registers.
216 if (CSRegs == 0 || CSRegs[0] == 0)
219 // In Naked functions we aren't going to save any registers.
220 if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
223 std::vector<CalleeSavedInfo> CSI;
224 for (unsigned i = 0; CSRegs[i]; ++i) {
225 unsigned Reg = CSRegs[i];
226 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
227 // If the reg is modified, save it!
228 CSI.push_back(CalleeSavedInfo(Reg));
230 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
231 *AliasSet; ++AliasSet) { // Check alias registers too.
232 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
233 CSI.push_back(CalleeSavedInfo(Reg));
241 return; // Early exit if no callee saved registers are modified!
243 unsigned NumFixedSpillSlots;
244 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
245 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
247 // Now that we know which registers need to be saved and restored, allocate
248 // stack slots for them.
249 for (std::vector<CalleeSavedInfo>::iterator
250 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
251 unsigned Reg = I->getReg();
252 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
255 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
256 I->setFrameIdx(FrameIdx);
260 // Check to see if this physreg must be spilled to a particular stack slot
262 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
263 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
264 FixedSlot->Reg != Reg)
267 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
268 // Nope, just spill it anywhere convenient.
269 unsigned Align = RC->getAlignment();
270 unsigned StackAlign = TFI->getStackAlignment();
272 // We may not be able to satisfy the desired alignment specification of
273 // the TargetRegisterClass if the stack alignment is smaller. Use the
275 Align = std::min(Align, StackAlign);
276 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
277 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
278 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
280 // Spill it to the stack where we must.
281 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
284 I->setFrameIdx(FrameIdx);
287 MFI->setCalleeSavedInfo(CSI);
290 /// insertCSRSpillsAndRestores - Insert spill and restore code for
291 /// callee saved registers used in the function, handling shrink wrapping.
293 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
294 // Get callee saved register information.
295 MachineFrameInfo *MFI = Fn.getFrameInfo();
296 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
298 MFI->setCalleeSavedInfoValid(true);
300 // Early exit if no callee saved registers are modified!
304 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
305 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
306 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
307 MachineBasicBlock::iterator I;
309 if (! ShrinkWrapThisFunction) {
310 // Spill using target interface.
311 I = EntryBlock->begin();
312 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
313 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
314 // Add the callee-saved register as live-in.
315 // It's killed at the spill.
316 EntryBlock->addLiveIn(CSI[i].getReg());
318 // Insert the spill to the stack frame.
319 unsigned Reg = CSI[i].getReg();
320 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
321 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
322 CSI[i].getFrameIdx(), RC, TRI);
326 // Restore using target interface.
327 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
328 MachineBasicBlock* MBB = ReturnBlocks[ri];
331 // Skip over all terminator instructions, which are part of the return
333 MachineBasicBlock::iterator I2 = I;
334 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
337 bool AtStart = I == MBB->begin();
338 MachineBasicBlock::iterator BeforeI = I;
342 // Restore all registers immediately before the return and any
343 // terminators that precede it.
344 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
345 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
346 unsigned Reg = CSI[i].getReg();
347 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
348 TII.loadRegFromStackSlot(*MBB, I, Reg,
349 CSI[i].getFrameIdx(),
351 assert(I != MBB->begin() &&
352 "loadRegFromStackSlot didn't insert any code!");
353 // Insert in reverse order. loadRegFromStackSlot can insert
354 // multiple instructions.
368 std::vector<CalleeSavedInfo> blockCSI;
369 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
370 BE = CSRSave.end(); BI != BE; ++BI) {
371 MachineBasicBlock* MBB = BI->first;
372 CSRegSet save = BI->second;
378 for (CSRegSet::iterator RI = save.begin(),
379 RE = save.end(); RI != RE; ++RI) {
380 blockCSI.push_back(CSI[*RI]);
382 assert(blockCSI.size() > 0 &&
383 "Could not collect callee saved register info");
387 // When shrink wrapping, use stack slot stores/loads.
388 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
389 // Add the callee-saved register as live-in.
390 // It's killed at the spill.
391 MBB->addLiveIn(blockCSI[i].getReg());
393 // Insert the spill to the stack frame.
394 unsigned Reg = blockCSI[i].getReg();
395 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
396 TII.storeRegToStackSlot(*MBB, I, Reg,
398 blockCSI[i].getFrameIdx(),
403 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
404 BE = CSRRestore.end(); BI != BE; ++BI) {
405 MachineBasicBlock* MBB = BI->first;
406 CSRegSet restore = BI->second;
412 for (CSRegSet::iterator RI = restore.begin(),
413 RE = restore.end(); RI != RE; ++RI) {
414 blockCSI.push_back(CSI[*RI]);
416 assert(blockCSI.size() > 0 &&
417 "Could not find callee saved register info");
419 // If MBB is empty and needs restores, insert at the _beginning_.
426 // Skip over all terminator instructions, which are part of the
428 if (! I->getDesc().isTerminator()) {
431 MachineBasicBlock::iterator I2 = I;
432 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
437 bool AtStart = I == MBB->begin();
438 MachineBasicBlock::iterator BeforeI = I;
442 // Restore all registers immediately before the return and any
443 // terminators that precede it.
444 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
445 unsigned Reg = blockCSI[i].getReg();
446 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
447 TII.loadRegFromStackSlot(*MBB, I, Reg,
448 blockCSI[i].getFrameIdx(),
450 assert(I != MBB->begin() &&
451 "loadRegFromStackSlot didn't insert any code!");
452 // Insert in reverse order. loadRegFromStackSlot can insert
453 // multiple instructions.
464 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
466 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
467 bool StackGrowsDown, int64_t &Offset,
468 unsigned &MaxAlign) {
469 // If the stack grows down, add the object size to find the lowest address.
471 Offset += MFI->getObjectSize(FrameIdx);
473 unsigned Align = MFI->getObjectAlignment(FrameIdx);
475 // If the alignment of this object is greater than that of the stack, then
476 // increase the stack alignment to match.
477 MaxAlign = std::max(MaxAlign, Align);
479 // Adjust to alignment boundary.
480 Offset = (Offset + Align - 1) / Align * Align;
482 if (StackGrowsDown) {
483 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
484 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
486 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
487 MFI->setObjectOffset(FrameIdx, Offset);
488 Offset += MFI->getObjectSize(FrameIdx);
492 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
493 /// abstract stack objects.
495 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
496 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
498 bool StackGrowsDown =
499 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
501 // Loop over all of the stack objects, assigning sequential addresses...
502 MachineFrameInfo *MFI = Fn.getFrameInfo();
504 // Start at the beginning of the local area.
505 // The Offset is the distance from the stack top in the direction
506 // of stack growth -- so it's always nonnegative.
507 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
509 LocalAreaOffset = -LocalAreaOffset;
510 assert(LocalAreaOffset >= 0
511 && "Local area offset should be in direction of stack growth");
512 int64_t Offset = LocalAreaOffset;
514 // If there are fixed sized objects that are preallocated in the local area,
515 // non-fixed objects can't be allocated right at the start of local area.
516 // We currently don't support filling in holes in between fixed sized
517 // objects, so we adjust 'Offset' to point to the end of last fixed sized
518 // preallocated object.
519 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
521 if (StackGrowsDown) {
522 // The maximum distance from the stack pointer is at lower address of
523 // the object -- which is given by offset. For down growing stack
524 // the offset is negative, so we negate the offset to get the distance.
525 FixedOff = -MFI->getObjectOffset(i);
527 // The maximum distance from the start pointer is at the upper
528 // address of the object.
529 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
531 if (FixedOff > Offset) Offset = FixedOff;
534 // First assign frame offsets to stack objects that are used to spill
535 // callee saved registers.
536 if (StackGrowsDown) {
537 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
538 // If the stack grows down, we need to add the size to find the lowest
539 // address of the object.
540 Offset += MFI->getObjectSize(i);
542 unsigned Align = MFI->getObjectAlignment(i);
543 // Adjust to alignment boundary
544 Offset = (Offset+Align-1)/Align*Align;
546 MFI->setObjectOffset(i, -Offset); // Set the computed offset
549 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
550 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
551 unsigned Align = MFI->getObjectAlignment(i);
552 // Adjust to alignment boundary
553 Offset = (Offset+Align-1)/Align*Align;
555 MFI->setObjectOffset(i, Offset);
556 Offset += MFI->getObjectSize(i);
560 unsigned MaxAlign = MFI->getMaxAlignment();
562 // Make sure the special register scavenging spill slot is closest to the
563 // frame pointer if a frame pointer is required.
564 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
565 if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
566 !RegInfo->needsStackRealignment(Fn)) {
567 int SFI = RS->getScavengingFrameIndex();
569 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
572 // FIXME: Once this is working, then enable flag will change to a target
573 // check for whether the frame is large enough to want to use virtual
574 // frame index registers. Functions which don't want/need this optimization
575 // will continue to use the existing code path.
576 if (MFI->getUseLocalStackAllocationBlock()) {
577 unsigned Align = MFI->getLocalFrameMaxAlign();
579 // Adjust to alignment boundary.
580 Offset = (Offset + Align - 1) / Align * Align;
582 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
584 // Resolve offsets for objects in the local block.
585 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
586 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
587 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
588 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
590 MFI->setObjectOffset(Entry.first, FIOffset);
592 // Allocate the local block
593 Offset += MFI->getLocalFrameSize();
595 MaxAlign = std::max(Align, MaxAlign);
598 // Make sure that the stack protector comes before the local variables on the
600 SmallSet<int, 16> LargeStackObjs;
601 if (MFI->getStackProtectorIndex() >= 0) {
602 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
605 // Assign large stack objects first.
606 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
607 if (MFI->isObjectPreAllocated(i) &&
608 MFI->getUseLocalStackAllocationBlock())
610 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
612 if (RS && (int)i == RS->getScavengingFrameIndex())
614 if (MFI->isDeadObjectIndex(i))
616 if (MFI->getStackProtectorIndex() == (int)i)
618 if (!MFI->MayNeedStackProtector(i))
621 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
622 LargeStackObjs.insert(i);
626 // Then assign frame offsets to stack objects that are not used to spill
627 // callee saved registers.
628 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
629 if (MFI->isObjectPreAllocated(i) &&
630 MFI->getUseLocalStackAllocationBlock())
632 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
634 if (RS && (int)i == RS->getScavengingFrameIndex())
636 if (MFI->isDeadObjectIndex(i))
638 if (MFI->getStackProtectorIndex() == (int)i)
640 if (LargeStackObjs.count(i))
643 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
646 // Make sure the special register scavenging spill slot is closest to the
648 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
649 !RegInfo->useFPForScavengingIndex(Fn))) {
650 int SFI = RS->getScavengingFrameIndex();
652 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
655 if (!TFI.targetHandlesStackFrameRounding()) {
656 // If we have reserved argument space for call sites in the function
657 // immediately on entry to the current function, count it as part of the
658 // overall stack size.
659 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
660 Offset += MFI->getMaxCallFrameSize();
662 // Round up the size to a multiple of the alignment. If the function has
663 // any calls or alloca's, align to the target's StackAlignment value to
664 // ensure that the callee's frame or the alloca data is suitably aligned;
665 // otherwise, for leaf functions, align to the TransientStackAlignment
668 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
669 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
670 StackAlign = TFI.getStackAlignment();
672 StackAlign = TFI.getTransientStackAlignment();
674 // If the frame pointer is eliminated, all frame offsets will be relative to
675 // SP not FP. Align to MaxAlign so this works.
676 StackAlign = std::max(StackAlign, MaxAlign);
677 unsigned AlignMask = StackAlign - 1;
678 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
681 // Update frame info to pretend that this is part of the stack...
682 int64_t StackSize = Offset - LocalAreaOffset;
683 MFI->setStackSize(StackSize);
684 NumBytesStackSpace += StackSize;
687 /// insertPrologEpilogCode - Scan the function for modified callee saved
688 /// registers, insert spill code for these callee saved registers, then add
689 /// prolog and epilog code to the function.
691 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
692 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
694 // Add prologue to the function...
695 TFI.emitPrologue(Fn);
697 // Add epilogue to restore the callee-save registers in each exiting block
698 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
699 // If last instruction is a return instruction, add an epilogue
700 if (!I->empty() && I->back().getDesc().isReturn())
701 TFI.emitEpilogue(Fn, *I);
704 // Emit additional code that is required to support segmented stacks, if
705 // we've been asked for it. This, when linked with a runtime with support
706 // for segmented stacks (libgcc is one), will result in allocating stack
707 // space in small chunks instead of one large contiguous block.
708 if (EnableSegmentedStacks)
709 TFI.adjustForSegmentedStacks(Fn);
712 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
713 /// register references and actual offsets.
715 void PEI::replaceFrameIndices(MachineFunction &Fn) {
716 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
718 const TargetMachine &TM = Fn.getTarget();
719 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
720 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
721 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
722 const TargetFrameLowering *TFI = TM.getFrameLowering();
723 bool StackGrowsDown =
724 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
725 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
726 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
728 for (MachineFunction::iterator BB = Fn.begin(),
729 E = Fn.end(); BB != E; ++BB) {
731 int SPAdjCount = 0; // frame setup / destroy count.
733 int SPAdj = 0; // SP offset due to call frame setup / destroy.
734 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
736 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
738 if (I->getOpcode() == FrameSetupOpcode ||
739 I->getOpcode() == FrameDestroyOpcode) {
741 // Track whether we see even pairs of them
742 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
744 // Remember how much SP has been adjusted to create the call
746 int Size = I->getOperand(0).getImm();
748 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
749 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
754 MachineBasicBlock::iterator PrevI = BB->end();
755 if (I != BB->begin()) PrevI = prior(I);
756 TRI.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.
762 I = llvm::next(PrevI);
766 MachineInstr *MI = I;
768 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
769 if (MI->getOperand(i).isFI()) {
770 // Some instructions (e.g. inline asm instructions) can have
771 // multiple frame indices and/or cause eliminateFrameIndex
772 // to insert more than one instruction. We need the register
773 // scavenger to go through all of these instructions so that
774 // it can update its register information. We keep the
775 // iterator at the point before insertion so that we can
776 // revisit them in full.
777 bool AtBeginning = (I == BB->begin());
778 if (!AtBeginning) --I;
780 // If this instruction has a FrameIndex operand, we need to
781 // use that target machine register info object to eliminate
783 TRI.eliminateFrameIndex(MI, SPAdj,
784 FrameIndexVirtualScavenging ? NULL : RS);
786 // Reset the iterator if we were at the beginning of the BB.
796 if (DoIncr && I != BB->end()) ++I;
798 // Update register states.
799 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
802 // If we have evenly matched pairs of frame setup / destroy instructions,
803 // make sure the adjustments come out to zero. If we don't have matched
804 // pairs, we can't be sure the missing bit isn't in another basic block
805 // due to a custom inserter playing tricks, so just asserting SPAdj==0
806 // isn't sufficient. See tMOVCC on Thumb1, for example.
807 assert((SPAdjCount || SPAdj == 0) &&
808 "Unbalanced call frame setup / destroy pairs?");
812 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
813 /// with physical registers. Use the register scavenger to find an
814 /// appropriate register to use.
815 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
816 // Run through the instructions and find any virtual registers.
817 for (MachineFunction::iterator BB = Fn.begin(),
818 E = Fn.end(); BB != E; ++BB) {
819 RS->enterBasicBlock(BB);
821 unsigned VirtReg = 0;
822 unsigned ScratchReg = 0;
825 // The instruction stream may change in the loop, so check BB->end()
827 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
828 MachineInstr *MI = I;
829 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
830 if (MI->getOperand(i).isReg()) {
831 MachineOperand &MO = MI->getOperand(i);
832 unsigned Reg = MO.getReg();
835 if (!TargetRegisterInfo::isVirtualRegister(Reg))
838 ++NumVirtualFrameRegs;
840 // Have we already allocated a scratch register for this virtual?
841 if (Reg != VirtReg) {
842 // When we first encounter a new virtual register, it
843 // must be a definition.
844 assert(MI->getOperand(i).isDef() &&
845 "frame index virtual missing def!");
846 // Scavenge a new scratch register
848 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
849 ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
852 // Replace this reference to the virtual register with the
854 assert (ScratchReg && "Missing scratch register!");
855 MI->getOperand(i).setReg(ScratchReg);