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/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/RegisterScavenging.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetFrameInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/ADT/IndexedMap.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/STLExtras.h"
47 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
48 "Prologue/Epilogue Insertion", false, false)
49 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
50 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
51 INITIALIZE_PASS_END(PEI, "prologepilog",
52 "Prologue/Epilogue Insertion", false, false)
54 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
55 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
57 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
58 /// prolog and epilog code, and eliminates abstract frame references.
60 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
62 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
63 /// frame indexes with appropriate references.
65 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
66 const Function* F = Fn.getFunction();
67 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
68 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
69 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
71 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
72 // function's frame information. Also eliminates call frame pseudo
74 calculateCallsInformation(Fn);
76 // Allow the target machine to make some adjustments to the function
77 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
78 TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
80 // Scan the function for modified callee saved registers and insert spill code
81 // for any callee saved registers that are modified.
82 calculateCalleeSavedRegisters(Fn);
84 // Determine placement of CSR spill/restore code:
85 // - With shrink wrapping, place spills and restores to tightly
86 // enclose regions in the Machine CFG of the function where
88 // - Without shink wrapping (default), place all spills in the
89 // entry block, all restores in return blocks.
90 placeCSRSpillsAndRestores(Fn);
92 // Add the code to save and restore the callee saved registers
93 if (!F->hasFnAttr(Attribute::Naked))
94 insertCSRSpillsAndRestores(Fn);
96 // Allow the target machine to make final modifications to the function
97 // before the frame layout is finalized.
98 TRI->processFunctionBeforeFrameFinalized(Fn);
100 // Calculate actual frame offsets for all abstract stack objects...
101 calculateFrameObjectOffsets(Fn);
103 // Add prolog and epilog code to the function. This function is required
104 // to align the stack frame as necessary for any stack variables or
105 // called functions. Because of this, calculateCalleeSavedRegisters()
106 // must be called before this function in order to set the AdjustsStack
107 // and MaxCallFrameSize variables.
108 if (!F->hasFnAttr(Attribute::Naked))
109 insertPrologEpilogCode(Fn);
111 // Replace all MO_FrameIndex operands with physical register references
112 // and actual offsets.
114 replaceFrameIndices(Fn);
116 // If register scavenging is needed, as we've enabled doing it as a
117 // post-pass, scavenge the virtual registers that frame index elimiation
119 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
120 scavengeFrameVirtualRegs(Fn);
128 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
129 AU.setPreservesCFG();
130 if (ShrinkWrapping || ShrinkWrapFunc != "") {
131 AU.addRequired<MachineLoopInfo>();
132 AU.addRequired<MachineDominatorTree>();
134 AU.addPreserved<MachineLoopInfo>();
135 AU.addPreserved<MachineDominatorTree>();
136 MachineFunctionPass::getAnalysisUsage(AU);
140 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
141 /// variables for the function's frame information and eliminate call frame
142 /// pseudo instructions.
143 void PEI::calculateCallsInformation(MachineFunction &Fn) {
144 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
145 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
146 MachineFrameInfo *MFI = Fn.getFrameInfo();
148 unsigned MaxCallFrameSize = 0;
149 bool AdjustsStack = MFI->adjustsStack();
151 // Get the function call frame set-up and tear-down instruction opcode
152 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
153 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
155 // Early exit for targets which have no call frame setup/destroy pseudo
157 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
160 std::vector<MachineBasicBlock::iterator> FrameSDOps;
161 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
162 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
163 if (I->getOpcode() == FrameSetupOpcode ||
164 I->getOpcode() == FrameDestroyOpcode) {
165 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
166 " instructions should have a single immediate argument!");
167 unsigned Size = I->getOperand(0).getImm();
168 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
170 FrameSDOps.push_back(I);
171 } else if (I->isInlineAsm()) {
172 // Some inline asm's need a stack frame, as indicated by operand 1.
173 if (I->getOperand(1).getImm())
177 MFI->setAdjustsStack(AdjustsStack);
178 MFI->setMaxCallFrameSize(MaxCallFrameSize);
180 for (std::vector<MachineBasicBlock::iterator>::iterator
181 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
182 MachineBasicBlock::iterator I = *i;
184 // If call frames are not being included as part of the stack frame, and
185 // the target doesn't indicate otherwise, remove the call frame pseudos
186 // here. The sub/add sp instruction pairs are still inserted, but we don't
187 // need to track the SP adjustment for frame index elimination.
188 if (TFI->canSimplifyCallFramePseudos(Fn))
189 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
194 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
196 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
197 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
198 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
199 MachineFrameInfo *MFI = Fn.getFrameInfo();
201 // Get the callee saved register list...
202 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
204 // These are used to keep track the callee-save area. Initialize them.
205 MinCSFrameIndex = INT_MAX;
208 // Early exit for targets which have no callee saved registers.
209 if (CSRegs == 0 || CSRegs[0] == 0)
212 // In Naked functions we aren't going to save any registers.
213 if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
216 std::vector<CalleeSavedInfo> CSI;
217 for (unsigned i = 0; CSRegs[i]; ++i) {
218 unsigned Reg = CSRegs[i];
219 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
220 // If the reg is modified, save it!
221 CSI.push_back(CalleeSavedInfo(Reg));
223 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
224 *AliasSet; ++AliasSet) { // Check alias registers too.
225 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
226 CSI.push_back(CalleeSavedInfo(Reg));
234 return; // Early exit if no callee saved registers are modified!
236 unsigned NumFixedSpillSlots;
237 const TargetFrameInfo::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 TargetFrameInfo::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 TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
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)->getDesc().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 preceed 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->getDesc().isTerminator()) {
424 MachineBasicBlock::iterator I2 = I;
425 while (I2 != MBB->begin() && (--I2)->getDesc().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 preceed 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 TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
491 bool StackGrowsDown =
492 TFI.getStackGrowthDirection() == TargetFrameInfo::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->needsStackRealignment(Fn)) {
559 int SFI = RS->getScavengingFrameIndex();
561 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
564 // FIXME: Once this is working, then enable flag will change to a target
565 // check for whether the frame is large enough to want to use virtual
566 // frame index registers. Functions which don't want/need this optimization
567 // will continue to use the existing code path.
568 if (MFI->getUseLocalStackAllocationBlock()) {
569 unsigned Align = MFI->getLocalFrameMaxAlign();
571 // Adjust to alignment boundary.
572 Offset = (Offset + Align - 1) / Align * Align;
574 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
576 // Resolve offsets for objects in the local block.
577 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
578 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
579 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
580 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
582 MFI->setObjectOffset(Entry.first, FIOffset);
584 // Allocate the local block
585 Offset += MFI->getLocalFrameSize();
587 MaxAlign = std::max(Align, MaxAlign);
590 // Make sure that the stack protector comes before the local variables on the
592 SmallSet<int, 16> LargeStackObjs;
593 if (MFI->getStackProtectorIndex() >= 0) {
594 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
597 // Assign large stack objects first.
598 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
599 if (MFI->isObjectPreAllocated(i) &&
600 MFI->getUseLocalStackAllocationBlock())
602 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
604 if (RS && (int)i == RS->getScavengingFrameIndex())
606 if (MFI->isDeadObjectIndex(i))
608 if (MFI->getStackProtectorIndex() == (int)i)
610 if (!MFI->MayNeedStackProtector(i))
613 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
614 LargeStackObjs.insert(i);
618 // Then assign frame offsets to stack objects that are not used to spill
619 // callee saved registers.
620 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
621 if (MFI->isObjectPreAllocated(i) &&
622 MFI->getUseLocalStackAllocationBlock())
624 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
626 if (RS && (int)i == RS->getScavengingFrameIndex())
628 if (MFI->isDeadObjectIndex(i))
630 if (MFI->getStackProtectorIndex() == (int)i)
632 if (LargeStackObjs.count(i))
635 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
638 // Make sure the special register scavenging spill slot is closest to the
640 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) {
641 int SFI = RS->getScavengingFrameIndex();
643 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
646 if (!TFI.targetHandlesStackFrameRounding()) {
647 // If we have reserved argument space for call sites in the function
648 // immediately on entry to the current function, count it as part of the
649 // overall stack size.
650 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
651 Offset += MFI->getMaxCallFrameSize();
653 // Round up the size to a multiple of the alignment. If the function has
654 // any calls or alloca's, align to the target's StackAlignment value to
655 // ensure that the callee's frame or the alloca data is suitably aligned;
656 // otherwise, for leaf functions, align to the TransientStackAlignment
659 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
660 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
661 StackAlign = TFI.getStackAlignment();
663 StackAlign = TFI.getTransientStackAlignment();
665 // If the frame pointer is eliminated, all frame offsets will be relative to
666 // SP not FP. Align to MaxAlign so this works.
667 StackAlign = std::max(StackAlign, MaxAlign);
668 unsigned AlignMask = StackAlign - 1;
669 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
672 // Update frame info to pretend that this is part of the stack...
673 MFI->setStackSize(Offset - LocalAreaOffset);
676 /// insertPrologEpilogCode - Scan the function for modified callee saved
677 /// registers, insert spill code for these callee saved registers, then add
678 /// prolog and epilog code to the function.
680 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
681 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
683 // Add prologue to the function...
684 TFI.emitPrologue(Fn);
686 // Add epilogue to restore the callee-save registers in each exiting block
687 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
688 // If last instruction is a return instruction, add an epilogue
689 if (!I->empty() && I->back().getDesc().isReturn())
690 TFI.emitEpilogue(Fn, *I);
694 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
695 /// register references and actual offsets.
697 void PEI::replaceFrameIndices(MachineFunction &Fn) {
698 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
700 const TargetMachine &TM = Fn.getTarget();
701 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
702 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
703 const TargetFrameInfo *TFI = TM.getFrameInfo();
704 bool StackGrowsDown =
705 TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
706 int FrameSetupOpcode = TRI.getCallFrameSetupOpcode();
707 int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
709 for (MachineFunction::iterator BB = Fn.begin(),
710 E = Fn.end(); BB != E; ++BB) {
712 int SPAdjCount = 0; // frame setup / destroy count.
714 int SPAdj = 0; // SP offset due to call frame setup / destroy.
715 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
717 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
719 if (I->getOpcode() == FrameSetupOpcode ||
720 I->getOpcode() == FrameDestroyOpcode) {
722 // Track whether we see even pairs of them
723 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
725 // Remember how much SP has been adjusted to create the call
727 int Size = I->getOperand(0).getImm();
729 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
730 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
735 MachineBasicBlock::iterator PrevI = BB->end();
736 if (I != BB->begin()) PrevI = prior(I);
737 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
739 // Visit the instructions created by eliminateCallFramePseudoInstr().
740 if (PrevI == BB->end())
741 I = BB->begin(); // The replaced instr was the first in the block.
743 I = llvm::next(PrevI);
747 MachineInstr *MI = I;
749 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
750 if (MI->getOperand(i).isFI()) {
751 // Some instructions (e.g. inline asm instructions) can have
752 // multiple frame indices and/or cause eliminateFrameIndex
753 // to insert more than one instruction. We need the register
754 // scavenger to go through all of these instructions so that
755 // it can update its register information. We keep the
756 // iterator at the point before insertion so that we can
757 // revisit them in full.
758 bool AtBeginning = (I == BB->begin());
759 if (!AtBeginning) --I;
761 // If this instruction has a FrameIndex operand, we need to
762 // use that target machine register info object to eliminate
764 TRI.eliminateFrameIndex(MI, SPAdj,
765 FrameIndexVirtualScavenging ? NULL : RS);
767 // Reset the iterator if we were at the beginning of the BB.
777 if (DoIncr && I != BB->end()) ++I;
779 // Update register states.
780 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
783 // If we have evenly matched pairs of frame setup / destroy instructions,
784 // make sure the adjustments come out to zero. If we don't have matched
785 // pairs, we can't be sure the missing bit isn't in another basic block
786 // due to a custom inserter playing tricks, so just asserting SPAdj==0
787 // isn't sufficient. See tMOVCC on Thumb1, for example.
788 assert((SPAdjCount || SPAdj == 0) &&
789 "Unbalanced call frame setup / destroy pairs?");
793 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
794 /// with physical registers. Use the register scavenger to find an
795 /// appropriate register to use.
796 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
797 // Run through the instructions and find any virtual registers.
798 for (MachineFunction::iterator BB = Fn.begin(),
799 E = Fn.end(); BB != E; ++BB) {
800 RS->enterBasicBlock(BB);
802 unsigned VirtReg = 0;
803 unsigned ScratchReg = 0;
806 // The instruction stream may change in the loop, so check BB->end()
808 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
809 MachineInstr *MI = I;
811 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
812 if (MI->getOperand(i).isReg()) {
813 MachineOperand &MO = MI->getOperand(i);
814 unsigned Reg = MO.getReg();
817 if (!TargetRegisterInfo::isVirtualRegister(Reg))
820 ++NumVirtualFrameRegs;
822 // Have we already allocated a scratch register for this virtual?
823 if (Reg != VirtReg) {
824 // When we first encounter a new virtual register, it
825 // must be a definition.
826 assert(MI->getOperand(i).isDef() &&
827 "frame index virtual missing def!");
828 // Scavenge a new scratch register
830 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
831 ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
834 // Replace this reference to the virtual register with the
836 assert (ScratchReg && "Missing scratch register!");
837 MI->getOperand(i).setReg(ScratchReg);