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/ADT/IndexedMap.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/RegisterScavenging.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetFrameLowering.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
48 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
50 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
51 "Prologue/Epilogue Insertion", false, false)
52 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
53 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
54 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
55 INITIALIZE_PASS_END(PEI, "prologepilog",
56 "Prologue/Epilogue Insertion & Frame Finalization",
59 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
60 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
61 STATISTIC(NumBytesStackSpace,
62 "Number of bytes used for stack in all functions");
64 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
65 /// frame indexes with appropriate references.
67 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
68 const Function* F = Fn.getFunction();
69 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
70 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
72 assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
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->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
101 insertCSRSpillsAndRestores(Fn);
103 // Allow the target machine to make final modifications to the function
104 // before the frame layout is finalized.
105 TFI->processFunctionBeforeFrameFinalized(Fn);
107 // Calculate actual frame offsets for all abstract stack objects...
108 calculateFrameObjectOffsets(Fn);
110 // Add prolog and epilog code to the function. This function is required
111 // to align the stack frame as necessary for any stack variables or
112 // called functions. Because of this, calculateCalleeSavedRegisters()
113 // must be called before this function in order to set the AdjustsStack
114 // and MaxCallFrameSize variables.
115 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
117 insertPrologEpilogCode(Fn);
119 // Replace all MO_FrameIndex operands with physical register references
120 // and actual offsets.
122 replaceFrameIndices(Fn);
124 // If register scavenging is needed, as we've enabled doing it as a
125 // post-pass, scavenge the virtual registers that frame index elimiation
127 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
128 scavengeFrameVirtualRegs(Fn);
130 // Clear any vregs created by virtual scavenging.
131 Fn.getRegInfo().clearVirtRegs();
138 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
139 /// variables for the function's frame information and eliminate call frame
140 /// pseudo instructions.
141 void PEI::calculateCallsInformation(MachineFunction &Fn) {
142 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
143 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
144 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
145 MachineFrameInfo *MFI = Fn.getFrameInfo();
147 unsigned MaxCallFrameSize = 0;
148 bool AdjustsStack = MFI->adjustsStack();
150 // Get the function call frame set-up and tear-down instruction opcode
151 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
152 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
154 // Early exit for targets which have no call frame setup/destroy pseudo
156 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
159 std::vector<MachineBasicBlock::iterator> FrameSDOps;
160 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
161 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
162 if (I->getOpcode() == FrameSetupOpcode ||
163 I->getOpcode() == FrameDestroyOpcode) {
164 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
165 " instructions should have a single immediate argument!");
166 unsigned Size = I->getOperand(0).getImm();
167 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
169 FrameSDOps.push_back(I);
170 } else if (I->isInlineAsm()) {
171 // Some inline asm's need a stack frame, as indicated by operand 1.
172 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
173 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
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 &F) {
197 const TargetRegisterInfo *RegInfo = F.getTarget().getRegisterInfo();
198 const TargetFrameLowering *TFI = F.getTarget().getFrameLowering();
199 MachineFrameInfo *MFI = F.getFrameInfo();
201 // Get the callee saved register list...
202 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&F);
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 (F.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
217 std::vector<CalleeSavedInfo> CSI;
218 for (unsigned i = 0; CSRegs[i]; ++i) {
219 unsigned Reg = CSRegs[i];
220 if (F.getRegInfo().isPhysRegUsed(Reg)) {
221 // If the reg is modified, save it!
222 CSI.push_back(CalleeSavedInfo(Reg));
227 return; // Early exit if no callee saved registers are modified!
229 unsigned NumFixedSpillSlots;
230 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
231 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
233 // Now that we know which registers need to be saved and restored, allocate
234 // stack slots for them.
235 for (std::vector<CalleeSavedInfo>::iterator
236 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
237 unsigned Reg = I->getReg();
238 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
241 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
242 I->setFrameIdx(FrameIdx);
246 // Check to see if this physreg must be spilled to a particular stack slot
248 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
249 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
250 FixedSlot->Reg != Reg)
253 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
254 // Nope, just spill it anywhere convenient.
255 unsigned Align = RC->getAlignment();
256 unsigned StackAlign = TFI->getStackAlignment();
258 // We may not be able to satisfy the desired alignment specification of
259 // the TargetRegisterClass if the stack alignment is smaller. Use the
261 Align = std::min(Align, StackAlign);
262 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
263 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
264 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
266 // Spill it to the stack where we must.
267 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
270 I->setFrameIdx(FrameIdx);
273 MFI->setCalleeSavedInfo(CSI);
276 /// insertCSRSpillsAndRestores - Insert spill and restore code for
277 /// callee saved registers used in the function, handling shrink wrapping.
279 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
280 // Get callee saved register information.
281 MachineFrameInfo *MFI = Fn.getFrameInfo();
282 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
284 MFI->setCalleeSavedInfoValid(true);
286 // Early exit if no callee saved registers are modified!
290 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
291 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
292 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
293 MachineBasicBlock::iterator I;
295 if (!ShrinkWrapThisFunction) {
296 // Spill using target interface.
297 I = EntryBlock->begin();
298 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
299 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
300 // Add the callee-saved register as live-in.
301 // It's killed at the spill.
302 EntryBlock->addLiveIn(CSI[i].getReg());
304 // Insert the spill to the stack frame.
305 unsigned Reg = CSI[i].getReg();
306 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
307 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
308 CSI[i].getFrameIdx(), RC, TRI);
312 // Restore using target interface.
313 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
314 MachineBasicBlock* MBB = ReturnBlocks[ri];
317 // Skip over all terminator instructions, which are part of the return
319 MachineBasicBlock::iterator I2 = I;
320 while (I2 != MBB->begin() && (--I2)->isTerminator())
323 bool AtStart = I == MBB->begin();
324 MachineBasicBlock::iterator BeforeI = I;
328 // Restore all registers immediately before the return and any
329 // terminators that precede it.
330 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
331 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
332 unsigned Reg = CSI[i].getReg();
333 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
334 TII.loadRegFromStackSlot(*MBB, I, Reg,
335 CSI[i].getFrameIdx(),
337 assert(I != MBB->begin() &&
338 "loadRegFromStackSlot didn't insert any code!");
339 // Insert in reverse order. loadRegFromStackSlot can insert
340 // multiple instructions.
354 std::vector<CalleeSavedInfo> blockCSI;
355 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
356 BE = CSRSave.end(); BI != BE; ++BI) {
357 MachineBasicBlock* MBB = BI->first;
358 CSRegSet save = BI->second;
364 for (CSRegSet::iterator RI = save.begin(),
365 RE = save.end(); RI != RE; ++RI) {
366 blockCSI.push_back(CSI[*RI]);
368 assert(blockCSI.size() > 0 &&
369 "Could not collect callee saved register info");
373 // When shrink wrapping, use stack slot stores/loads.
374 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
375 // Add the callee-saved register as live-in.
376 // It's killed at the spill.
377 MBB->addLiveIn(blockCSI[i].getReg());
379 // Insert the spill to the stack frame.
380 unsigned Reg = blockCSI[i].getReg();
381 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
382 TII.storeRegToStackSlot(*MBB, I, Reg,
384 blockCSI[i].getFrameIdx(),
389 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
390 BE = CSRRestore.end(); BI != BE; ++BI) {
391 MachineBasicBlock* MBB = BI->first;
392 CSRegSet restore = BI->second;
398 for (CSRegSet::iterator RI = restore.begin(),
399 RE = restore.end(); RI != RE; ++RI) {
400 blockCSI.push_back(CSI[*RI]);
402 assert(blockCSI.size() > 0 &&
403 "Could not find callee saved register info");
405 // If MBB is empty and needs restores, insert at the _beginning_.
412 // Skip over all terminator instructions, which are part of the
414 if (! I->isTerminator()) {
417 MachineBasicBlock::iterator I2 = I;
418 while (I2 != MBB->begin() && (--I2)->isTerminator())
423 bool AtStart = I == MBB->begin();
424 MachineBasicBlock::iterator BeforeI = I;
428 // Restore all registers immediately before the return and any
429 // terminators that precede it.
430 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
431 unsigned Reg = blockCSI[i].getReg();
432 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
433 TII.loadRegFromStackSlot(*MBB, I, Reg,
434 blockCSI[i].getFrameIdx(),
436 assert(I != MBB->begin() &&
437 "loadRegFromStackSlot didn't insert any code!");
438 // Insert in reverse order. loadRegFromStackSlot can insert
439 // multiple instructions.
450 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
452 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
453 bool StackGrowsDown, int64_t &Offset,
454 unsigned &MaxAlign) {
455 // If the stack grows down, add the object size to find the lowest address.
457 Offset += MFI->getObjectSize(FrameIdx);
459 unsigned Align = MFI->getObjectAlignment(FrameIdx);
461 // If the alignment of this object is greater than that of the stack, then
462 // increase the stack alignment to match.
463 MaxAlign = std::max(MaxAlign, Align);
465 // Adjust to alignment boundary.
466 Offset = (Offset + Align - 1) / Align * Align;
468 if (StackGrowsDown) {
469 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
470 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
472 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
473 MFI->setObjectOffset(FrameIdx, Offset);
474 Offset += MFI->getObjectSize(FrameIdx);
478 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
479 /// abstract stack objects.
481 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
482 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
484 bool StackGrowsDown =
485 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
487 // Loop over all of the stack objects, assigning sequential addresses...
488 MachineFrameInfo *MFI = Fn.getFrameInfo();
490 // Start at the beginning of the local area.
491 // The Offset is the distance from the stack top in the direction
492 // of stack growth -- so it's always nonnegative.
493 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
495 LocalAreaOffset = -LocalAreaOffset;
496 assert(LocalAreaOffset >= 0
497 && "Local area offset should be in direction of stack growth");
498 int64_t Offset = LocalAreaOffset;
500 // If there are fixed sized objects that are preallocated in the local area,
501 // non-fixed objects can't be allocated right at the start of local area.
502 // We currently don't support filling in holes in between fixed sized
503 // objects, so we adjust 'Offset' to point to the end of last fixed sized
504 // preallocated object.
505 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
507 if (StackGrowsDown) {
508 // The maximum distance from the stack pointer is at lower address of
509 // the object -- which is given by offset. For down growing stack
510 // the offset is negative, so we negate the offset to get the distance.
511 FixedOff = -MFI->getObjectOffset(i);
513 // The maximum distance from the start pointer is at the upper
514 // address of the object.
515 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
517 if (FixedOff > Offset) Offset = FixedOff;
520 // First assign frame offsets to stack objects that are used to spill
521 // callee saved registers.
522 if (StackGrowsDown) {
523 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
524 // If the stack grows down, we need to add the size to find the lowest
525 // address of the object.
526 Offset += MFI->getObjectSize(i);
528 unsigned Align = MFI->getObjectAlignment(i);
529 // Adjust to alignment boundary
530 Offset = (Offset+Align-1)/Align*Align;
532 MFI->setObjectOffset(i, -Offset); // Set the computed offset
535 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
536 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
537 unsigned Align = MFI->getObjectAlignment(i);
538 // Adjust to alignment boundary
539 Offset = (Offset+Align-1)/Align*Align;
541 MFI->setObjectOffset(i, Offset);
542 Offset += MFI->getObjectSize(i);
546 unsigned MaxAlign = MFI->getMaxAlignment();
548 // Make sure the special register scavenging spill slot is closest to the
549 // frame pointer if a frame pointer is required.
550 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
551 if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
552 !RegInfo->needsStackRealignment(Fn)) {
553 int SFI = RS->getScavengingFrameIndex();
555 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
558 // FIXME: Once this is working, then enable flag will change to a target
559 // check for whether the frame is large enough to want to use virtual
560 // frame index registers. Functions which don't want/need this optimization
561 // will continue to use the existing code path.
562 if (MFI->getUseLocalStackAllocationBlock()) {
563 unsigned Align = MFI->getLocalFrameMaxAlign();
565 // Adjust to alignment boundary.
566 Offset = (Offset + Align - 1) / Align * Align;
568 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
570 // Resolve offsets for objects in the local block.
571 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
572 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
573 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
574 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
576 MFI->setObjectOffset(Entry.first, FIOffset);
578 // Allocate the local block
579 Offset += MFI->getLocalFrameSize();
581 MaxAlign = std::max(Align, MaxAlign);
584 // Make sure that the stack protector comes before the local variables on the
586 SmallSet<int, 16> LargeStackObjs;
587 if (MFI->getStackProtectorIndex() >= 0) {
588 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
591 // Assign large stack objects first.
592 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
593 if (MFI->isObjectPreAllocated(i) &&
594 MFI->getUseLocalStackAllocationBlock())
596 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
598 if (RS && (int)i == RS->getScavengingFrameIndex())
600 if (MFI->isDeadObjectIndex(i))
602 if (MFI->getStackProtectorIndex() == (int)i)
604 if (!MFI->MayNeedStackProtector(i))
607 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
608 LargeStackObjs.insert(i);
612 // Then assign frame offsets to stack objects that are not used to spill
613 // callee saved registers.
614 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
615 if (MFI->isObjectPreAllocated(i) &&
616 MFI->getUseLocalStackAllocationBlock())
618 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
620 if (RS && (int)i == RS->getScavengingFrameIndex())
622 if (MFI->isDeadObjectIndex(i))
624 if (MFI->getStackProtectorIndex() == (int)i)
626 if (LargeStackObjs.count(i))
629 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
632 // Make sure the special register scavenging spill slot is closest to the
634 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
635 !RegInfo->useFPForScavengingIndex(Fn))) {
636 int SFI = RS->getScavengingFrameIndex();
638 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
641 if (!TFI.targetHandlesStackFrameRounding()) {
642 // If we have reserved argument space for call sites in the function
643 // immediately on entry to the current function, count it as part of the
644 // overall stack size.
645 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
646 Offset += MFI->getMaxCallFrameSize();
648 // Round up the size to a multiple of the alignment. If the function has
649 // any calls or alloca's, align to the target's StackAlignment value to
650 // ensure that the callee's frame or the alloca data is suitably aligned;
651 // otherwise, for leaf functions, align to the TransientStackAlignment
654 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
655 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
656 StackAlign = TFI.getStackAlignment();
658 StackAlign = TFI.getTransientStackAlignment();
660 // If the frame pointer is eliminated, all frame offsets will be relative to
661 // SP not FP. Align to MaxAlign so this works.
662 StackAlign = std::max(StackAlign, MaxAlign);
663 unsigned AlignMask = StackAlign - 1;
664 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
667 // Update frame info to pretend that this is part of the stack...
668 int64_t StackSize = Offset - LocalAreaOffset;
669 MFI->setStackSize(StackSize);
670 NumBytesStackSpace += StackSize;
673 /// insertPrologEpilogCode - Scan the function for modified callee saved
674 /// registers, insert spill code for these callee saved registers, then add
675 /// prolog and epilog code to the function.
677 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
678 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
680 // Add prologue to the function...
681 TFI.emitPrologue(Fn);
683 // Add epilogue to restore the callee-save registers in each exiting block
684 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
685 // If last instruction is a return instruction, add an epilogue
686 if (!I->empty() && I->back().isReturn())
687 TFI.emitEpilogue(Fn, *I);
690 // Emit additional code that is required to support segmented stacks, if
691 // we've been asked for it. This, when linked with a runtime with support
692 // for segmented stacks (libgcc is one), will result in allocating stack
693 // space in small chunks instead of one large contiguous block.
694 if (Fn.getTarget().Options.EnableSegmentedStacks)
695 TFI.adjustForSegmentedStacks(Fn);
698 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
699 /// register references and actual offsets.
701 void PEI::replaceFrameIndices(MachineFunction &Fn) {
702 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
704 const TargetMachine &TM = Fn.getTarget();
705 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
706 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
707 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
708 const TargetFrameLowering *TFI = TM.getFrameLowering();
709 bool StackGrowsDown =
710 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
711 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
712 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
714 for (MachineFunction::iterator BB = Fn.begin(),
715 E = Fn.end(); BB != E; ++BB) {
717 int SPAdjCount = 0; // frame setup / destroy count.
719 int SPAdj = 0; // SP offset due to call frame setup / destroy.
720 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
722 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
724 if (I->getOpcode() == FrameSetupOpcode ||
725 I->getOpcode() == FrameDestroyOpcode) {
727 // Track whether we see even pairs of them
728 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
730 // Remember how much SP has been adjusted to create the call
732 int Size = I->getOperand(0).getImm();
734 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
735 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
740 MachineBasicBlock::iterator PrevI = BB->end();
741 if (I != BB->begin()) PrevI = prior(I);
742 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
744 // Visit the instructions created by eliminateCallFramePseudoInstr().
745 if (PrevI == BB->end())
746 I = BB->begin(); // The replaced instr was the first in the block.
748 I = llvm::next(PrevI);
752 MachineInstr *MI = I;
754 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
755 if (MI->getOperand(i).isFI()) {
756 // Some instructions (e.g. inline asm instructions) can have
757 // multiple frame indices and/or cause eliminateFrameIndex
758 // to insert more than one instruction. We need the register
759 // scavenger to go through all of these instructions so that
760 // it can update its register information. We keep the
761 // iterator at the point before insertion so that we can
762 // revisit them in full.
763 bool AtBeginning = (I == BB->begin());
764 if (!AtBeginning) --I;
766 // If this instruction has a FrameIndex operand, we need to
767 // use that target machine register info object to eliminate
769 TRI.eliminateFrameIndex(MI, SPAdj,
770 FrameIndexVirtualScavenging ? NULL : RS);
772 // Reset the iterator if we were at the beginning of the BB.
782 if (DoIncr && I != BB->end()) ++I;
784 // Update register states.
785 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
788 // If we have evenly matched pairs of frame setup / destroy instructions,
789 // make sure the adjustments come out to zero. If we don't have matched
790 // pairs, we can't be sure the missing bit isn't in another basic block
791 // due to a custom inserter playing tricks, so just asserting SPAdj==0
792 // isn't sufficient. See tMOVCC on Thumb1, for example.
793 assert((SPAdjCount || SPAdj == 0) &&
794 "Unbalanced call frame setup / destroy pairs?");
798 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
799 /// with physical registers. Use the register scavenger to find an
800 /// appropriate register to use.
802 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
803 /// iterate over the vreg use list, which at this point only contains machine
804 /// operands for which eliminateFrameIndex need a new scratch reg.
805 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
806 // Run through the instructions and find any virtual registers.
807 for (MachineFunction::iterator BB = Fn.begin(),
808 E = Fn.end(); BB != E; ++BB) {
809 RS->enterBasicBlock(BB);
811 unsigned VirtReg = 0;
812 unsigned ScratchReg = 0;
815 // The instruction stream may change in the loop, so check BB->end()
817 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
818 MachineInstr *MI = I;
819 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
820 if (MI->getOperand(i).isReg()) {
821 MachineOperand &MO = MI->getOperand(i);
822 unsigned Reg = MO.getReg();
825 if (!TargetRegisterInfo::isVirtualRegister(Reg))
828 ++NumVirtualFrameRegs;
830 // Have we already allocated a scratch register for this virtual?
831 if (Reg != VirtReg) {
832 // When we first encounter a new virtual register, it
833 // must be a definition.
834 assert(MI->getOperand(i).isDef() &&
835 "frame index virtual missing def!");
836 // Scavenge a new scratch register
838 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
839 ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
842 // Replace this reference to the virtual register with the
844 assert (ScratchReg && "Missing scratch register!");
845 MI->getOperand(i).setReg(ScratchReg);