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"
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->getFnAttributes().hasAttribute(Attributes::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->getFnAttributes().hasAttribute(Attributes::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);
128 // Clear any vregs created by virtual scavenging.
129 Fn.getRegInfo().clearVirtRegs();
136 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
137 /// variables for the function's frame information and eliminate call frame
138 /// pseudo instructions.
139 void PEI::calculateCallsInformation(MachineFunction &Fn) {
140 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
141 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
142 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
143 MachineFrameInfo *MFI = Fn.getFrameInfo();
145 unsigned MaxCallFrameSize = 0;
146 bool AdjustsStack = MFI->adjustsStack();
148 // Get the function call frame set-up and tear-down instruction opcode
149 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
150 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
152 // Early exit for targets which have no call frame setup/destroy pseudo
154 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
157 std::vector<MachineBasicBlock::iterator> FrameSDOps;
158 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
159 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
160 if (I->getOpcode() == FrameSetupOpcode ||
161 I->getOpcode() == FrameDestroyOpcode) {
162 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
163 " instructions should have a single immediate argument!");
164 unsigned Size = I->getOperand(0).getImm();
165 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
167 FrameSDOps.push_back(I);
168 } else if (I->isInlineAsm()) {
169 // Some inline asm's need a stack frame, as indicated by operand 1.
170 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
171 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
175 MFI->setAdjustsStack(AdjustsStack);
176 MFI->setMaxCallFrameSize(MaxCallFrameSize);
178 for (std::vector<MachineBasicBlock::iterator>::iterator
179 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
180 MachineBasicBlock::iterator I = *i;
182 // If call frames are not being included as part of the stack frame, and
183 // the target doesn't indicate otherwise, remove the call frame pseudos
184 // here. The sub/add sp instruction pairs are still inserted, but we don't
185 // need to track the SP adjustment for frame index elimination.
186 if (TFI->canSimplifyCallFramePseudos(Fn))
187 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
192 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
194 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
195 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
196 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
197 MachineFrameInfo *MFI = Fn.getFrameInfo();
199 // Get the callee saved register list...
200 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
202 // These are used to keep track the callee-save area. Initialize them.
203 MinCSFrameIndex = INT_MAX;
206 // Early exit for targets which have no callee saved registers.
207 if (CSRegs == 0 || CSRegs[0] == 0)
210 // In Naked functions we aren't going to save any registers.
211 if (Fn.getFunction()->getFnAttributes().hasAttribute(Attributes::Naked))
214 std::vector<CalleeSavedInfo> CSI;
215 for (unsigned i = 0; CSRegs[i]; ++i) {
216 unsigned Reg = CSRegs[i];
217 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
218 // If the reg is modified, save it!
219 CSI.push_back(CalleeSavedInfo(Reg));
224 return; // Early exit if no callee saved registers are modified!
226 unsigned NumFixedSpillSlots;
227 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
228 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
230 // Now that we know which registers need to be saved and restored, allocate
231 // stack slots for them.
232 for (std::vector<CalleeSavedInfo>::iterator
233 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
234 unsigned Reg = I->getReg();
235 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
238 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
239 I->setFrameIdx(FrameIdx);
243 // Check to see if this physreg must be spilled to a particular stack slot
245 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
246 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
247 FixedSlot->Reg != Reg)
250 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
251 // Nope, just spill it anywhere convenient.
252 unsigned Align = RC->getAlignment();
253 unsigned StackAlign = TFI->getStackAlignment();
255 // We may not be able to satisfy the desired alignment specification of
256 // the TargetRegisterClass if the stack alignment is smaller. Use the
258 Align = std::min(Align, StackAlign);
259 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
260 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
261 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
263 // Spill it to the stack where we must.
264 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
267 I->setFrameIdx(FrameIdx);
270 MFI->setCalleeSavedInfo(CSI);
273 /// insertCSRSpillsAndRestores - Insert spill and restore code for
274 /// callee saved registers used in the function, handling shrink wrapping.
276 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
277 // Get callee saved register information.
278 MachineFrameInfo *MFI = Fn.getFrameInfo();
279 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
281 MFI->setCalleeSavedInfoValid(true);
283 // Early exit if no callee saved registers are modified!
287 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
288 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
289 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
290 MachineBasicBlock::iterator I;
292 if (!ShrinkWrapThisFunction) {
293 // Spill using target interface.
294 I = EntryBlock->begin();
295 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
296 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
297 // Add the callee-saved register as live-in.
298 // It's killed at the spill.
299 EntryBlock->addLiveIn(CSI[i].getReg());
301 // Insert the spill to the stack frame.
302 unsigned Reg = CSI[i].getReg();
303 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
304 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
305 CSI[i].getFrameIdx(), RC, TRI);
309 // Restore using target interface.
310 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
311 MachineBasicBlock* MBB = ReturnBlocks[ri];
314 // Skip over all terminator instructions, which are part of the return
316 MachineBasicBlock::iterator I2 = I;
317 while (I2 != MBB->begin() && (--I2)->isTerminator())
320 bool AtStart = I == MBB->begin();
321 MachineBasicBlock::iterator BeforeI = I;
325 // Restore all registers immediately before the return and any
326 // terminators that precede it.
327 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
328 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
329 unsigned Reg = CSI[i].getReg();
330 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
331 TII.loadRegFromStackSlot(*MBB, I, Reg,
332 CSI[i].getFrameIdx(),
334 assert(I != MBB->begin() &&
335 "loadRegFromStackSlot didn't insert any code!");
336 // Insert in reverse order. loadRegFromStackSlot can insert
337 // multiple instructions.
351 std::vector<CalleeSavedInfo> blockCSI;
352 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
353 BE = CSRSave.end(); BI != BE; ++BI) {
354 MachineBasicBlock* MBB = BI->first;
355 CSRegSet save = BI->second;
361 for (CSRegSet::iterator RI = save.begin(),
362 RE = save.end(); RI != RE; ++RI) {
363 blockCSI.push_back(CSI[*RI]);
365 assert(blockCSI.size() > 0 &&
366 "Could not collect callee saved register info");
370 // When shrink wrapping, use stack slot stores/loads.
371 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
372 // Add the callee-saved register as live-in.
373 // It's killed at the spill.
374 MBB->addLiveIn(blockCSI[i].getReg());
376 // Insert the spill to the stack frame.
377 unsigned Reg = blockCSI[i].getReg();
378 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
379 TII.storeRegToStackSlot(*MBB, I, Reg,
381 blockCSI[i].getFrameIdx(),
386 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
387 BE = CSRRestore.end(); BI != BE; ++BI) {
388 MachineBasicBlock* MBB = BI->first;
389 CSRegSet restore = BI->second;
395 for (CSRegSet::iterator RI = restore.begin(),
396 RE = restore.end(); RI != RE; ++RI) {
397 blockCSI.push_back(CSI[*RI]);
399 assert(blockCSI.size() > 0 &&
400 "Could not find callee saved register info");
402 // If MBB is empty and needs restores, insert at the _beginning_.
409 // Skip over all terminator instructions, which are part of the
411 if (! I->isTerminator()) {
414 MachineBasicBlock::iterator I2 = I;
415 while (I2 != MBB->begin() && (--I2)->isTerminator())
420 bool AtStart = I == MBB->begin();
421 MachineBasicBlock::iterator BeforeI = I;
425 // Restore all registers immediately before the return and any
426 // terminators that precede it.
427 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
428 unsigned Reg = blockCSI[i].getReg();
429 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
430 TII.loadRegFromStackSlot(*MBB, I, Reg,
431 blockCSI[i].getFrameIdx(),
433 assert(I != MBB->begin() &&
434 "loadRegFromStackSlot didn't insert any code!");
435 // Insert in reverse order. loadRegFromStackSlot can insert
436 // multiple instructions.
447 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
449 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
450 bool StackGrowsDown, int64_t &Offset,
451 unsigned &MaxAlign) {
452 // If the stack grows down, add the object size to find the lowest address.
454 Offset += MFI->getObjectSize(FrameIdx);
456 unsigned Align = MFI->getObjectAlignment(FrameIdx);
458 // If the alignment of this object is greater than that of the stack, then
459 // increase the stack alignment to match.
460 MaxAlign = std::max(MaxAlign, Align);
462 // Adjust to alignment boundary.
463 Offset = (Offset + Align - 1) / Align * Align;
465 if (StackGrowsDown) {
466 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
467 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
469 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
470 MFI->setObjectOffset(FrameIdx, Offset);
471 Offset += MFI->getObjectSize(FrameIdx);
475 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
476 /// abstract stack objects.
478 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
479 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
481 bool StackGrowsDown =
482 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
484 // Loop over all of the stack objects, assigning sequential addresses...
485 MachineFrameInfo *MFI = Fn.getFrameInfo();
487 // Start at the beginning of the local area.
488 // The Offset is the distance from the stack top in the direction
489 // of stack growth -- so it's always nonnegative.
490 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
492 LocalAreaOffset = -LocalAreaOffset;
493 assert(LocalAreaOffset >= 0
494 && "Local area offset should be in direction of stack growth");
495 int64_t Offset = LocalAreaOffset;
497 // If there are fixed sized objects that are preallocated in the local area,
498 // non-fixed objects can't be allocated right at the start of local area.
499 // We currently don't support filling in holes in between fixed sized
500 // objects, so we adjust 'Offset' to point to the end of last fixed sized
501 // preallocated object.
502 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
504 if (StackGrowsDown) {
505 // The maximum distance from the stack pointer is at lower address of
506 // the object -- which is given by offset. For down growing stack
507 // the offset is negative, so we negate the offset to get the distance.
508 FixedOff = -MFI->getObjectOffset(i);
510 // The maximum distance from the start pointer is at the upper
511 // address of the object.
512 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
514 if (FixedOff > Offset) Offset = FixedOff;
517 // First assign frame offsets to stack objects that are used to spill
518 // callee saved registers.
519 if (StackGrowsDown) {
520 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
521 // If the stack grows down, we need to add the size to find the lowest
522 // address of the object.
523 Offset += MFI->getObjectSize(i);
525 unsigned Align = MFI->getObjectAlignment(i);
526 // Adjust to alignment boundary
527 Offset = (Offset+Align-1)/Align*Align;
529 MFI->setObjectOffset(i, -Offset); // Set the computed offset
532 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
533 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
534 unsigned Align = MFI->getObjectAlignment(i);
535 // Adjust to alignment boundary
536 Offset = (Offset+Align-1)/Align*Align;
538 MFI->setObjectOffset(i, Offset);
539 Offset += MFI->getObjectSize(i);
543 unsigned MaxAlign = MFI->getMaxAlignment();
545 // Make sure the special register scavenging spill slot is closest to the
546 // frame pointer if a frame pointer is required.
547 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
548 if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
549 !RegInfo->needsStackRealignment(Fn)) {
550 int SFI = RS->getScavengingFrameIndex();
552 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
555 // FIXME: Once this is working, then enable flag will change to a target
556 // check for whether the frame is large enough to want to use virtual
557 // frame index registers. Functions which don't want/need this optimization
558 // will continue to use the existing code path.
559 if (MFI->getUseLocalStackAllocationBlock()) {
560 unsigned Align = MFI->getLocalFrameMaxAlign();
562 // Adjust to alignment boundary.
563 Offset = (Offset + Align - 1) / Align * Align;
565 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
567 // Resolve offsets for objects in the local block.
568 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
569 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
570 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
571 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
573 MFI->setObjectOffset(Entry.first, FIOffset);
575 // Allocate the local block
576 Offset += MFI->getLocalFrameSize();
578 MaxAlign = std::max(Align, MaxAlign);
581 // Make sure that the stack protector comes before the local variables on the
583 SmallSet<int, 16> LargeStackObjs;
584 if (MFI->getStackProtectorIndex() >= 0) {
585 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
588 // Assign large stack objects first.
589 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
590 if (MFI->isObjectPreAllocated(i) &&
591 MFI->getUseLocalStackAllocationBlock())
593 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
595 if (RS && (int)i == RS->getScavengingFrameIndex())
597 if (MFI->isDeadObjectIndex(i))
599 if (MFI->getStackProtectorIndex() == (int)i)
601 if (!MFI->MayNeedStackProtector(i))
604 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
605 LargeStackObjs.insert(i);
609 // Then assign frame offsets to stack objects that are not used to spill
610 // callee saved registers.
611 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
612 if (MFI->isObjectPreAllocated(i) &&
613 MFI->getUseLocalStackAllocationBlock())
615 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
617 if (RS && (int)i == RS->getScavengingFrameIndex())
619 if (MFI->isDeadObjectIndex(i))
621 if (MFI->getStackProtectorIndex() == (int)i)
623 if (LargeStackObjs.count(i))
626 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
629 // Make sure the special register scavenging spill slot is closest to the
631 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
632 !RegInfo->useFPForScavengingIndex(Fn))) {
633 int SFI = RS->getScavengingFrameIndex();
635 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
638 if (!TFI.targetHandlesStackFrameRounding()) {
639 // If we have reserved argument space for call sites in the function
640 // immediately on entry to the current function, count it as part of the
641 // overall stack size.
642 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
643 Offset += MFI->getMaxCallFrameSize();
645 // Round up the size to a multiple of the alignment. If the function has
646 // any calls or alloca's, align to the target's StackAlignment value to
647 // ensure that the callee's frame or the alloca data is suitably aligned;
648 // otherwise, for leaf functions, align to the TransientStackAlignment
651 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
652 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
653 StackAlign = TFI.getStackAlignment();
655 StackAlign = TFI.getTransientStackAlignment();
657 // If the frame pointer is eliminated, all frame offsets will be relative to
658 // SP not FP. Align to MaxAlign so this works.
659 StackAlign = std::max(StackAlign, MaxAlign);
660 unsigned AlignMask = StackAlign - 1;
661 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
664 // Update frame info to pretend that this is part of the stack...
665 int64_t StackSize = Offset - LocalAreaOffset;
666 MFI->setStackSize(StackSize);
667 NumBytesStackSpace += StackSize;
670 /// insertPrologEpilogCode - Scan the function for modified callee saved
671 /// registers, insert spill code for these callee saved registers, then add
672 /// prolog and epilog code to the function.
674 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
675 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
677 // Add prologue to the function...
678 TFI.emitPrologue(Fn);
680 // Add epilogue to restore the callee-save registers in each exiting block
681 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
682 // If last instruction is a return instruction, add an epilogue
683 if (!I->empty() && I->back().isReturn())
684 TFI.emitEpilogue(Fn, *I);
687 // Emit additional code that is required to support segmented stacks, if
688 // we've been asked for it. This, when linked with a runtime with support
689 // for segmented stacks (libgcc is one), will result in allocating stack
690 // space in small chunks instead of one large contiguous block.
691 if (Fn.getTarget().Options.EnableSegmentedStacks)
692 TFI.adjustForSegmentedStacks(Fn);
695 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
696 /// register references and actual offsets.
698 void PEI::replaceFrameIndices(MachineFunction &Fn) {
699 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
701 const TargetMachine &TM = Fn.getTarget();
702 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
703 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
704 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
705 const TargetFrameLowering *TFI = TM.getFrameLowering();
706 bool StackGrowsDown =
707 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
708 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
709 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
711 for (MachineFunction::iterator BB = Fn.begin(),
712 E = Fn.end(); BB != E; ++BB) {
714 int SPAdjCount = 0; // frame setup / destroy count.
716 int SPAdj = 0; // SP offset due to call frame setup / destroy.
717 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
719 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
721 if (I->getOpcode() == FrameSetupOpcode ||
722 I->getOpcode() == FrameDestroyOpcode) {
724 // Track whether we see even pairs of them
725 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
727 // Remember how much SP has been adjusted to create the call
729 int Size = I->getOperand(0).getImm();
731 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
732 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
737 MachineBasicBlock::iterator PrevI = BB->end();
738 if (I != BB->begin()) PrevI = prior(I);
739 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
741 // Visit the instructions created by eliminateCallFramePseudoInstr().
742 if (PrevI == BB->end())
743 I = BB->begin(); // The replaced instr was the first in the block.
745 I = llvm::next(PrevI);
749 MachineInstr *MI = I;
751 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
752 if (MI->getOperand(i).isFI()) {
753 // Some instructions (e.g. inline asm instructions) can have
754 // multiple frame indices and/or cause eliminateFrameIndex
755 // to insert more than one instruction. We need the register
756 // scavenger to go through all of these instructions so that
757 // it can update its register information. We keep the
758 // iterator at the point before insertion so that we can
759 // revisit them in full.
760 bool AtBeginning = (I == BB->begin());
761 if (!AtBeginning) --I;
763 // If this instruction has a FrameIndex operand, we need to
764 // use that target machine register info object to eliminate
766 TRI.eliminateFrameIndex(MI, SPAdj,
767 FrameIndexVirtualScavenging ? NULL : RS);
769 // Reset the iterator if we were at the beginning of the BB.
779 if (DoIncr && I != BB->end()) ++I;
781 // Update register states.
782 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
785 // If we have evenly matched pairs of frame setup / destroy instructions,
786 // make sure the adjustments come out to zero. If we don't have matched
787 // pairs, we can't be sure the missing bit isn't in another basic block
788 // due to a custom inserter playing tricks, so just asserting SPAdj==0
789 // isn't sufficient. See tMOVCC on Thumb1, for example.
790 assert((SPAdjCount || SPAdj == 0) &&
791 "Unbalanced call frame setup / destroy pairs?");
795 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
796 /// with physical registers. Use the register scavenger to find an
797 /// appropriate register to use.
799 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
800 /// iterate over the vreg use list, which at this point only contains machine
801 /// operands for which eliminateFrameIndex need a new scratch reg.
802 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
803 // Run through the instructions and find any virtual registers.
804 for (MachineFunction::iterator BB = Fn.begin(),
805 E = Fn.end(); BB != E; ++BB) {
806 RS->enterBasicBlock(BB);
808 unsigned VirtReg = 0;
809 unsigned ScratchReg = 0;
812 // The instruction stream may change in the loop, so check BB->end()
814 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
815 MachineInstr *MI = I;
816 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
817 if (MI->getOperand(i).isReg()) {
818 MachineOperand &MO = MI->getOperand(i);
819 unsigned Reg = MO.getReg();
822 if (!TargetRegisterInfo::isVirtualRegister(Reg))
825 ++NumVirtualFrameRegs;
827 // Have we already allocated a scratch register for this virtual?
828 if (Reg != VirtReg) {
829 // When we first encounter a new virtual register, it
830 // must be a definition.
831 assert(MI->getOperand(i).isDef() &&
832 "frame index virtual missing def!");
833 // Scavenge a new scratch register
835 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
836 ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
839 // Replace this reference to the virtual register with the
841 assert (ScratchReg && "Missing scratch register!");
842 MI->getOperand(i).setReg(ScratchReg);