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,
59 "Number of bytes used for stack in all functions");
61 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
62 /// prolog and epilog code, and eliminates abstract frame references.
64 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
66 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
67 /// frame indexes with appropriate references.
69 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
70 const Function* F = Fn.getFunction();
71 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
72 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
74 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
75 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
77 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
78 // function's frame information. Also eliminates call frame pseudo
80 calculateCallsInformation(Fn);
82 // Allow the target machine to make some adjustments to the function
83 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
84 TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
86 // Scan the function for modified callee saved registers and insert spill code
87 // for any callee saved registers that are modified.
88 calculateCalleeSavedRegisters(Fn);
90 // Determine placement of CSR spill/restore code:
91 // - With shrink wrapping, place spills and restores to tightly
92 // enclose regions in the Machine CFG of the function where
94 // - Without shink wrapping (default), place all spills in the
95 // entry block, all restores in return blocks.
96 placeCSRSpillsAndRestores(Fn);
98 // Add the code to save and restore the callee saved registers
99 if (!F->hasFnAttr(Attribute::Naked))
100 insertCSRSpillsAndRestores(Fn);
102 // Allow the target machine to make final modifications to the function
103 // before the frame layout is finalized.
104 TFI->processFunctionBeforeFrameFinalized(Fn);
106 // Calculate actual frame offsets for all abstract stack objects...
107 calculateFrameObjectOffsets(Fn);
109 // Add prolog and epilog code to the function. This function is required
110 // to align the stack frame as necessary for any stack variables or
111 // called functions. Because of this, calculateCalleeSavedRegisters()
112 // must be called before this function in order to set the AdjustsStack
113 // and MaxCallFrameSize variables.
114 if (!F->hasFnAttr(Attribute::Naked))
115 insertPrologEpilogCode(Fn);
117 // Replace all MO_FrameIndex operands with physical register references
118 // and actual offsets.
120 replaceFrameIndices(Fn);
122 // If register scavenging is needed, as we've enabled doing it as a
123 // post-pass, scavenge the virtual registers that frame index elimiation
125 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
126 scavengeFrameVirtualRegs(Fn);
134 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
135 AU.setPreservesCFG();
136 if (ShrinkWrapping || ShrinkWrapFunc != "") {
137 AU.addRequired<MachineLoopInfo>();
138 AU.addRequired<MachineDominatorTree>();
140 AU.addPreserved<MachineLoopInfo>();
141 AU.addPreserved<MachineDominatorTree>();
142 MachineFunctionPass::getAnalysisUsage(AU);
146 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
147 /// variables for the function's frame information and eliminate call frame
148 /// pseudo instructions.
149 void PEI::calculateCallsInformation(MachineFunction &Fn) {
150 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
151 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
152 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
153 MachineFrameInfo *MFI = Fn.getFrameInfo();
155 unsigned MaxCallFrameSize = 0;
156 bool AdjustsStack = MFI->adjustsStack();
158 // Get the function call frame set-up and tear-down instruction opcode
159 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
160 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
162 // Early exit for targets which have no call frame setup/destroy pseudo
164 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
167 std::vector<MachineBasicBlock::iterator> FrameSDOps;
168 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
169 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
170 if (I->getOpcode() == FrameSetupOpcode ||
171 I->getOpcode() == FrameDestroyOpcode) {
172 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
173 " instructions should have a single immediate argument!");
174 unsigned Size = I->getOperand(0).getImm();
175 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
177 FrameSDOps.push_back(I);
178 } else if (I->isInlineAsm()) {
179 // Some inline asm's need a stack frame, as indicated by operand 1.
180 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
181 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
185 MFI->setAdjustsStack(AdjustsStack);
186 MFI->setMaxCallFrameSize(MaxCallFrameSize);
188 for (std::vector<MachineBasicBlock::iterator>::iterator
189 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
190 MachineBasicBlock::iterator I = *i;
192 // If call frames are not being included as part of the stack frame, and
193 // the target doesn't indicate otherwise, remove the call frame pseudos
194 // here. The sub/add sp instruction pairs are still inserted, but we don't
195 // need to track the SP adjustment for frame index elimination.
196 if (TFI->canSimplifyCallFramePseudos(Fn))
197 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
202 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
204 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
205 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
206 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
207 MachineFrameInfo *MFI = Fn.getFrameInfo();
209 // Get the callee saved register list...
210 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
212 // These are used to keep track the callee-save area. Initialize them.
213 MinCSFrameIndex = INT_MAX;
216 // Early exit for targets which have no callee saved registers.
217 if (CSRegs == 0 || CSRegs[0] == 0)
220 // In Naked functions we aren't going to save any registers.
221 if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
224 std::vector<CalleeSavedInfo> CSI;
225 for (unsigned i = 0; CSRegs[i]; ++i) {
226 unsigned Reg = CSRegs[i];
227 if (Fn.getRegInfo().isPhysRegOrOverlapUsed(Reg)) {
228 // If the reg is modified, save it!
229 CSI.push_back(CalleeSavedInfo(Reg));
234 return; // Early exit if no callee saved registers are modified!
236 unsigned NumFixedSpillSlots;
237 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
238 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
240 // Now that we know which registers need to be saved and restored, allocate
241 // stack slots for them.
242 for (std::vector<CalleeSavedInfo>::iterator
243 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
244 unsigned Reg = I->getReg();
245 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
248 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
249 I->setFrameIdx(FrameIdx);
253 // Check to see if this physreg must be spilled to a particular stack slot
255 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
256 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
257 FixedSlot->Reg != Reg)
260 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
261 // Nope, just spill it anywhere convenient.
262 unsigned Align = RC->getAlignment();
263 unsigned StackAlign = TFI->getStackAlignment();
265 // We may not be able to satisfy the desired alignment specification of
266 // the TargetRegisterClass if the stack alignment is smaller. Use the
268 Align = std::min(Align, StackAlign);
269 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
270 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
271 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
273 // Spill it to the stack where we must.
274 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
277 I->setFrameIdx(FrameIdx);
280 MFI->setCalleeSavedInfo(CSI);
283 /// insertCSRSpillsAndRestores - Insert spill and restore code for
284 /// callee saved registers used in the function, handling shrink wrapping.
286 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
287 // Get callee saved register information.
288 MachineFrameInfo *MFI = Fn.getFrameInfo();
289 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
291 MFI->setCalleeSavedInfoValid(true);
293 // Early exit if no callee saved registers are modified!
297 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
298 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
299 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
300 MachineBasicBlock::iterator I;
302 if (! ShrinkWrapThisFunction) {
303 // Spill using target interface.
304 I = EntryBlock->begin();
305 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
306 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
307 // Add the callee-saved register as live-in.
308 // It's killed at the spill.
309 EntryBlock->addLiveIn(CSI[i].getReg());
311 // Insert the spill to the stack frame.
312 unsigned Reg = CSI[i].getReg();
313 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
314 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
315 CSI[i].getFrameIdx(), RC, TRI);
319 // Restore using target interface.
320 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
321 MachineBasicBlock* MBB = ReturnBlocks[ri];
324 // Skip over all terminator instructions, which are part of the return
326 MachineBasicBlock::iterator I2 = I;
327 while (I2 != MBB->begin() && (--I2)->isTerminator())
330 bool AtStart = I == MBB->begin();
331 MachineBasicBlock::iterator BeforeI = I;
335 // Restore all registers immediately before the return and any
336 // terminators that precede it.
337 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
338 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
339 unsigned Reg = CSI[i].getReg();
340 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
341 TII.loadRegFromStackSlot(*MBB, I, Reg,
342 CSI[i].getFrameIdx(),
344 assert(I != MBB->begin() &&
345 "loadRegFromStackSlot didn't insert any code!");
346 // Insert in reverse order. loadRegFromStackSlot can insert
347 // multiple instructions.
361 std::vector<CalleeSavedInfo> blockCSI;
362 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
363 BE = CSRSave.end(); BI != BE; ++BI) {
364 MachineBasicBlock* MBB = BI->first;
365 CSRegSet save = BI->second;
371 for (CSRegSet::iterator RI = save.begin(),
372 RE = save.end(); RI != RE; ++RI) {
373 blockCSI.push_back(CSI[*RI]);
375 assert(blockCSI.size() > 0 &&
376 "Could not collect callee saved register info");
380 // When shrink wrapping, use stack slot stores/loads.
381 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
382 // Add the callee-saved register as live-in.
383 // It's killed at the spill.
384 MBB->addLiveIn(blockCSI[i].getReg());
386 // Insert the spill to the stack frame.
387 unsigned Reg = blockCSI[i].getReg();
388 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
389 TII.storeRegToStackSlot(*MBB, I, Reg,
391 blockCSI[i].getFrameIdx(),
396 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
397 BE = CSRRestore.end(); BI != BE; ++BI) {
398 MachineBasicBlock* MBB = BI->first;
399 CSRegSet restore = BI->second;
405 for (CSRegSet::iterator RI = restore.begin(),
406 RE = restore.end(); RI != RE; ++RI) {
407 blockCSI.push_back(CSI[*RI]);
409 assert(blockCSI.size() > 0 &&
410 "Could not find callee saved register info");
412 // If MBB is empty and needs restores, insert at the _beginning_.
419 // Skip over all terminator instructions, which are part of the
421 if (! I->isTerminator()) {
424 MachineBasicBlock::iterator I2 = I;
425 while (I2 != MBB->begin() && (--I2)->isTerminator())
430 bool AtStart = I == MBB->begin();
431 MachineBasicBlock::iterator BeforeI = I;
435 // Restore all registers immediately before the return and any
436 // terminators that precede it.
437 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
438 unsigned Reg = blockCSI[i].getReg();
439 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
440 TII.loadRegFromStackSlot(*MBB, I, Reg,
441 blockCSI[i].getFrameIdx(),
443 assert(I != MBB->begin() &&
444 "loadRegFromStackSlot didn't insert any code!");
445 // Insert in reverse order. loadRegFromStackSlot can insert
446 // multiple instructions.
457 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
459 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
460 bool StackGrowsDown, int64_t &Offset,
461 unsigned &MaxAlign) {
462 // If the stack grows down, add the object size to find the lowest address.
464 Offset += MFI->getObjectSize(FrameIdx);
466 unsigned Align = MFI->getObjectAlignment(FrameIdx);
468 // If the alignment of this object is greater than that of the stack, then
469 // increase the stack alignment to match.
470 MaxAlign = std::max(MaxAlign, Align);
472 // Adjust to alignment boundary.
473 Offset = (Offset + Align - 1) / Align * Align;
475 if (StackGrowsDown) {
476 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
477 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
479 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
480 MFI->setObjectOffset(FrameIdx, Offset);
481 Offset += MFI->getObjectSize(FrameIdx);
485 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
486 /// abstract stack objects.
488 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
489 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
491 bool StackGrowsDown =
492 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
494 // Loop over all of the stack objects, assigning sequential addresses...
495 MachineFrameInfo *MFI = Fn.getFrameInfo();
497 // Start at the beginning of the local area.
498 // The Offset is the distance from the stack top in the direction
499 // of stack growth -- so it's always nonnegative.
500 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
502 LocalAreaOffset = -LocalAreaOffset;
503 assert(LocalAreaOffset >= 0
504 && "Local area offset should be in direction of stack growth");
505 int64_t Offset = LocalAreaOffset;
507 // If there are fixed sized objects that are preallocated in the local area,
508 // non-fixed objects can't be allocated right at the start of local area.
509 // We currently don't support filling in holes in between fixed sized
510 // objects, so we adjust 'Offset' to point to the end of last fixed sized
511 // preallocated object.
512 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
514 if (StackGrowsDown) {
515 // The maximum distance from the stack pointer is at lower address of
516 // the object -- which is given by offset. For down growing stack
517 // the offset is negative, so we negate the offset to get the distance.
518 FixedOff = -MFI->getObjectOffset(i);
520 // The maximum distance from the start pointer is at the upper
521 // address of the object.
522 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
524 if (FixedOff > Offset) Offset = FixedOff;
527 // First assign frame offsets to stack objects that are used to spill
528 // callee saved registers.
529 if (StackGrowsDown) {
530 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
531 // If the stack grows down, we need to add the size to find the lowest
532 // address of the object.
533 Offset += MFI->getObjectSize(i);
535 unsigned Align = MFI->getObjectAlignment(i);
536 // Adjust to alignment boundary
537 Offset = (Offset+Align-1)/Align*Align;
539 MFI->setObjectOffset(i, -Offset); // Set the computed offset
542 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
543 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
544 unsigned Align = MFI->getObjectAlignment(i);
545 // Adjust to alignment boundary
546 Offset = (Offset+Align-1)/Align*Align;
548 MFI->setObjectOffset(i, Offset);
549 Offset += MFI->getObjectSize(i);
553 unsigned MaxAlign = MFI->getMaxAlignment();
555 // Make sure the special register scavenging spill slot is closest to the
556 // frame pointer if a frame pointer is required.
557 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
558 if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
559 !RegInfo->needsStackRealignment(Fn)) {
560 int SFI = RS->getScavengingFrameIndex();
562 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
565 // FIXME: Once this is working, then enable flag will change to a target
566 // check for whether the frame is large enough to want to use virtual
567 // frame index registers. Functions which don't want/need this optimization
568 // will continue to use the existing code path.
569 if (MFI->getUseLocalStackAllocationBlock()) {
570 unsigned Align = MFI->getLocalFrameMaxAlign();
572 // Adjust to alignment boundary.
573 Offset = (Offset + Align - 1) / Align * Align;
575 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
577 // Resolve offsets for objects in the local block.
578 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
579 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
580 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
581 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
583 MFI->setObjectOffset(Entry.first, FIOffset);
585 // Allocate the local block
586 Offset += MFI->getLocalFrameSize();
588 MaxAlign = std::max(Align, MaxAlign);
591 // Make sure that the stack protector comes before the local variables on the
593 SmallSet<int, 16> LargeStackObjs;
594 if (MFI->getStackProtectorIndex() >= 0) {
595 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
598 // Assign large stack objects first.
599 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
600 if (MFI->isObjectPreAllocated(i) &&
601 MFI->getUseLocalStackAllocationBlock())
603 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
605 if (RS && (int)i == RS->getScavengingFrameIndex())
607 if (MFI->isDeadObjectIndex(i))
609 if (MFI->getStackProtectorIndex() == (int)i)
611 if (!MFI->MayNeedStackProtector(i))
614 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
615 LargeStackObjs.insert(i);
619 // Then assign frame offsets to stack objects that are not used to spill
620 // callee saved registers.
621 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
622 if (MFI->isObjectPreAllocated(i) &&
623 MFI->getUseLocalStackAllocationBlock())
625 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
627 if (RS && (int)i == RS->getScavengingFrameIndex())
629 if (MFI->isDeadObjectIndex(i))
631 if (MFI->getStackProtectorIndex() == (int)i)
633 if (LargeStackObjs.count(i))
636 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
639 // Make sure the special register scavenging spill slot is closest to the
641 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
642 !RegInfo->useFPForScavengingIndex(Fn))) {
643 int SFI = RS->getScavengingFrameIndex();
645 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
648 if (!TFI.targetHandlesStackFrameRounding()) {
649 // If we have reserved argument space for call sites in the function
650 // immediately on entry to the current function, count it as part of the
651 // overall stack size.
652 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
653 Offset += MFI->getMaxCallFrameSize();
655 // Round up the size to a multiple of the alignment. If the function has
656 // any calls or alloca's, align to the target's StackAlignment value to
657 // ensure that the callee's frame or the alloca data is suitably aligned;
658 // otherwise, for leaf functions, align to the TransientStackAlignment
661 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
662 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
663 StackAlign = TFI.getStackAlignment();
665 StackAlign = TFI.getTransientStackAlignment();
667 // If the frame pointer is eliminated, all frame offsets will be relative to
668 // SP not FP. Align to MaxAlign so this works.
669 StackAlign = std::max(StackAlign, MaxAlign);
670 unsigned AlignMask = StackAlign - 1;
671 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
674 // Update frame info to pretend that this is part of the stack...
675 int64_t StackSize = Offset - LocalAreaOffset;
676 MFI->setStackSize(StackSize);
677 NumBytesStackSpace += StackSize;
680 /// insertPrologEpilogCode - Scan the function for modified callee saved
681 /// registers, insert spill code for these callee saved registers, then add
682 /// prolog and epilog code to the function.
684 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
685 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
687 // Add prologue to the function...
688 TFI.emitPrologue(Fn);
690 // Add epilogue to restore the callee-save registers in each exiting block
691 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
692 // If last instruction is a return instruction, add an epilogue
693 if (!I->empty() && I->back().isReturn())
694 TFI.emitEpilogue(Fn, *I);
697 // Emit additional code that is required to support segmented stacks, if
698 // we've been asked for it. This, when linked with a runtime with support
699 // for segmented stacks (libgcc is one), will result in allocating stack
700 // space in small chunks instead of one large contiguous block.
701 if (Fn.getTarget().Options.EnableSegmentedStacks)
702 TFI.adjustForSegmentedStacks(Fn);
705 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
706 /// register references and actual offsets.
708 void PEI::replaceFrameIndices(MachineFunction &Fn) {
709 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
711 const TargetMachine &TM = Fn.getTarget();
712 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
713 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
714 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
715 const TargetFrameLowering *TFI = TM.getFrameLowering();
716 bool StackGrowsDown =
717 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
718 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
719 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
721 for (MachineFunction::iterator BB = Fn.begin(),
722 E = Fn.end(); BB != E; ++BB) {
724 int SPAdjCount = 0; // frame setup / destroy count.
726 int SPAdj = 0; // SP offset due to call frame setup / destroy.
727 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
729 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
731 if (I->getOpcode() == FrameSetupOpcode ||
732 I->getOpcode() == FrameDestroyOpcode) {
734 // Track whether we see even pairs of them
735 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
737 // Remember how much SP has been adjusted to create the call
739 int Size = I->getOperand(0).getImm();
741 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
742 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
747 MachineBasicBlock::iterator PrevI = BB->end();
748 if (I != BB->begin()) PrevI = prior(I);
749 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
751 // Visit the instructions created by eliminateCallFramePseudoInstr().
752 if (PrevI == BB->end())
753 I = BB->begin(); // The replaced instr was the first in the block.
755 I = llvm::next(PrevI);
759 MachineInstr *MI = I;
761 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
762 if (MI->getOperand(i).isFI()) {
763 // Some instructions (e.g. inline asm instructions) can have
764 // multiple frame indices and/or cause eliminateFrameIndex
765 // to insert more than one instruction. We need the register
766 // scavenger to go through all of these instructions so that
767 // it can update its register information. We keep the
768 // iterator at the point before insertion so that we can
769 // revisit them in full.
770 bool AtBeginning = (I == BB->begin());
771 if (!AtBeginning) --I;
773 // If this instruction has a FrameIndex operand, we need to
774 // use that target machine register info object to eliminate
776 TRI.eliminateFrameIndex(MI, SPAdj,
777 FrameIndexVirtualScavenging ? NULL : RS);
779 // Reset the iterator if we were at the beginning of the BB.
789 if (DoIncr && I != BB->end()) ++I;
791 // Update register states.
792 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
795 // If we have evenly matched pairs of frame setup / destroy instructions,
796 // make sure the adjustments come out to zero. If we don't have matched
797 // pairs, we can't be sure the missing bit isn't in another basic block
798 // due to a custom inserter playing tricks, so just asserting SPAdj==0
799 // isn't sufficient. See tMOVCC on Thumb1, for example.
800 assert((SPAdjCount || SPAdj == 0) &&
801 "Unbalanced call frame setup / destroy pairs?");
805 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
806 /// with physical registers. Use the register scavenger to find an
807 /// appropriate register to use.
808 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
809 // Run through the instructions and find any virtual registers.
810 for (MachineFunction::iterator BB = Fn.begin(),
811 E = Fn.end(); BB != E; ++BB) {
812 RS->enterBasicBlock(BB);
814 unsigned VirtReg = 0;
815 unsigned ScratchReg = 0;
818 // The instruction stream may change in the loop, so check BB->end()
820 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
821 MachineInstr *MI = I;
822 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
823 if (MI->getOperand(i).isReg()) {
824 MachineOperand &MO = MI->getOperand(i);
825 unsigned Reg = MO.getReg();
828 if (!TargetRegisterInfo::isVirtualRegister(Reg))
831 ++NumVirtualFrameRegs;
833 // Have we already allocated a scratch register for this virtual?
834 if (Reg != VirtReg) {
835 // When we first encounter a new virtual register, it
836 // must be a definition.
837 assert(MI->getOperand(i).isDef() &&
838 "frame index virtual missing def!");
839 // Scavenge a new scratch register
841 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
842 ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
845 // Replace this reference to the virtual register with the
847 assert (ScratchReg && "Missing scratch register!");
848 MI->getOperand(i).setReg(ScratchReg);