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_DEPENDENCY(TargetPassConfig)
54 INITIALIZE_PASS_END(PEI, "prologepilog",
55 "Prologue/Epilogue Insertion", false, false)
57 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
58 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
59 STATISTIC(NumBytesStackSpace,
60 "Number of bytes used for stack in all functions");
62 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
63 /// prolog and epilog code, and eliminates abstract frame references.
65 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
67 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
68 /// frame indexes with appropriate references.
70 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
71 const Function* F = Fn.getFunction();
72 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
73 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
75 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
76 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
78 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
79 // function's frame information. Also eliminates call frame pseudo
81 calculateCallsInformation(Fn);
83 // Allow the target machine to make some adjustments to the function
84 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
85 TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
87 // Scan the function for modified callee saved registers and insert spill code
88 // for any callee saved registers that are modified.
89 calculateCalleeSavedRegisters(Fn);
91 // Determine placement of CSR spill/restore code:
92 // - With shrink wrapping, place spills and restores to tightly
93 // enclose regions in the Machine CFG of the function where
95 // - Without shink wrapping (default), place all spills in the
96 // entry block, all restores in return blocks.
97 placeCSRSpillsAndRestores(Fn);
99 // Add the code to save and restore the callee saved registers
100 if (!F->hasFnAttr(Attribute::Naked))
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->hasFnAttr(Attribute::Naked))
116 insertPrologEpilogCode(Fn);
118 // Replace all MO_FrameIndex operands with physical register references
119 // and actual offsets.
121 replaceFrameIndices(Fn);
123 // If register scavenging is needed, as we've enabled doing it as a
124 // post-pass, scavenge the virtual registers that frame index elimiation
126 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
127 scavengeFrameVirtualRegs(Fn);
135 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
136 AU.setPreservesCFG();
137 if (ShrinkWrapping || ShrinkWrapFunc != "") {
138 AU.addRequired<MachineLoopInfo>();
139 AU.addRequired<MachineDominatorTree>();
141 AU.addPreserved<MachineLoopInfo>();
142 AU.addPreserved<MachineDominatorTree>();
143 MachineFunctionPass::getAnalysisUsage(AU);
147 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
148 /// variables for the function's frame information and eliminate call frame
149 /// pseudo instructions.
150 void PEI::calculateCallsInformation(MachineFunction &Fn) {
151 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
152 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
153 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
154 MachineFrameInfo *MFI = Fn.getFrameInfo();
156 unsigned MaxCallFrameSize = 0;
157 bool AdjustsStack = MFI->adjustsStack();
159 // Get the function call frame set-up and tear-down instruction opcode
160 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
161 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
163 // Early exit for targets which have no call frame setup/destroy pseudo
165 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
168 std::vector<MachineBasicBlock::iterator> FrameSDOps;
169 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
170 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
171 if (I->getOpcode() == FrameSetupOpcode ||
172 I->getOpcode() == FrameDestroyOpcode) {
173 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
174 " instructions should have a single immediate argument!");
175 unsigned Size = I->getOperand(0).getImm();
176 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
178 FrameSDOps.push_back(I);
179 } else if (I->isInlineAsm()) {
180 // Some inline asm's need a stack frame, as indicated by operand 1.
181 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
182 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
186 MFI->setAdjustsStack(AdjustsStack);
187 MFI->setMaxCallFrameSize(MaxCallFrameSize);
189 for (std::vector<MachineBasicBlock::iterator>::iterator
190 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
191 MachineBasicBlock::iterator I = *i;
193 // If call frames are not being included as part of the stack frame, and
194 // the target doesn't indicate otherwise, remove the call frame pseudos
195 // here. The sub/add sp instruction pairs are still inserted, but we don't
196 // need to track the SP adjustment for frame index elimination.
197 if (TFI->canSimplifyCallFramePseudos(Fn))
198 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
203 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
205 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
206 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
207 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
208 MachineFrameInfo *MFI = Fn.getFrameInfo();
210 // Get the callee saved register list...
211 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
213 // These are used to keep track the callee-save area. Initialize them.
214 MinCSFrameIndex = INT_MAX;
217 // Early exit for targets which have no callee saved registers.
218 if (CSRegs == 0 || CSRegs[0] == 0)
221 // In Naked functions we aren't going to save any registers.
222 if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
225 std::vector<CalleeSavedInfo> CSI;
226 for (unsigned i = 0; CSRegs[i]; ++i) {
227 unsigned Reg = CSRegs[i];
228 if (Fn.getRegInfo().isPhysRegOrOverlapUsed(Reg)) {
229 // If the reg is modified, save it!
230 CSI.push_back(CalleeSavedInfo(Reg));
235 return; // Early exit if no callee saved registers are modified!
237 unsigned NumFixedSpillSlots;
238 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
239 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
241 // Now that we know which registers need to be saved and restored, allocate
242 // stack slots for them.
243 for (std::vector<CalleeSavedInfo>::iterator
244 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
245 unsigned Reg = I->getReg();
246 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
249 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
250 I->setFrameIdx(FrameIdx);
254 // Check to see if this physreg must be spilled to a particular stack slot
256 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
257 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
258 FixedSlot->Reg != Reg)
261 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
262 // Nope, just spill it anywhere convenient.
263 unsigned Align = RC->getAlignment();
264 unsigned StackAlign = TFI->getStackAlignment();
266 // We may not be able to satisfy the desired alignment specification of
267 // the TargetRegisterClass if the stack alignment is smaller. Use the
269 Align = std::min(Align, StackAlign);
270 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
271 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
272 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
274 // Spill it to the stack where we must.
275 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
278 I->setFrameIdx(FrameIdx);
281 MFI->setCalleeSavedInfo(CSI);
284 /// insertCSRSpillsAndRestores - Insert spill and restore code for
285 /// callee saved registers used in the function, handling shrink wrapping.
287 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
288 // Get callee saved register information.
289 MachineFrameInfo *MFI = Fn.getFrameInfo();
290 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
292 MFI->setCalleeSavedInfoValid(true);
294 // Early exit if no callee saved registers are modified!
298 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
299 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
300 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
301 MachineBasicBlock::iterator I;
303 if (! ShrinkWrapThisFunction) {
304 // Spill using target interface.
305 I = EntryBlock->begin();
306 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
307 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
308 // Add the callee-saved register as live-in.
309 // It's killed at the spill.
310 EntryBlock->addLiveIn(CSI[i].getReg());
312 // Insert the spill to the stack frame.
313 unsigned Reg = CSI[i].getReg();
314 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
315 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
316 CSI[i].getFrameIdx(), RC, TRI);
320 // Restore using target interface.
321 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
322 MachineBasicBlock* MBB = ReturnBlocks[ri];
325 // Skip over all terminator instructions, which are part of the return
327 MachineBasicBlock::iterator I2 = I;
328 while (I2 != MBB->begin() && (--I2)->isTerminator())
331 bool AtStart = I == MBB->begin();
332 MachineBasicBlock::iterator BeforeI = I;
336 // Restore all registers immediately before the return and any
337 // terminators that precede it.
338 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
339 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
340 unsigned Reg = CSI[i].getReg();
341 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
342 TII.loadRegFromStackSlot(*MBB, I, Reg,
343 CSI[i].getFrameIdx(),
345 assert(I != MBB->begin() &&
346 "loadRegFromStackSlot didn't insert any code!");
347 // Insert in reverse order. loadRegFromStackSlot can insert
348 // multiple instructions.
362 std::vector<CalleeSavedInfo> blockCSI;
363 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
364 BE = CSRSave.end(); BI != BE; ++BI) {
365 MachineBasicBlock* MBB = BI->first;
366 CSRegSet save = BI->second;
372 for (CSRegSet::iterator RI = save.begin(),
373 RE = save.end(); RI != RE; ++RI) {
374 blockCSI.push_back(CSI[*RI]);
376 assert(blockCSI.size() > 0 &&
377 "Could not collect callee saved register info");
381 // When shrink wrapping, use stack slot stores/loads.
382 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
383 // Add the callee-saved register as live-in.
384 // It's killed at the spill.
385 MBB->addLiveIn(blockCSI[i].getReg());
387 // Insert the spill to the stack frame.
388 unsigned Reg = blockCSI[i].getReg();
389 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
390 TII.storeRegToStackSlot(*MBB, I, Reg,
392 blockCSI[i].getFrameIdx(),
397 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
398 BE = CSRRestore.end(); BI != BE; ++BI) {
399 MachineBasicBlock* MBB = BI->first;
400 CSRegSet restore = BI->second;
406 for (CSRegSet::iterator RI = restore.begin(),
407 RE = restore.end(); RI != RE; ++RI) {
408 blockCSI.push_back(CSI[*RI]);
410 assert(blockCSI.size() > 0 &&
411 "Could not find callee saved register info");
413 // If MBB is empty and needs restores, insert at the _beginning_.
420 // Skip over all terminator instructions, which are part of the
422 if (! I->isTerminator()) {
425 MachineBasicBlock::iterator I2 = I;
426 while (I2 != MBB->begin() && (--I2)->isTerminator())
431 bool AtStart = I == MBB->begin();
432 MachineBasicBlock::iterator BeforeI = I;
436 // Restore all registers immediately before the return and any
437 // terminators that precede it.
438 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
439 unsigned Reg = blockCSI[i].getReg();
440 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
441 TII.loadRegFromStackSlot(*MBB, I, Reg,
442 blockCSI[i].getFrameIdx(),
444 assert(I != MBB->begin() &&
445 "loadRegFromStackSlot didn't insert any code!");
446 // Insert in reverse order. loadRegFromStackSlot can insert
447 // multiple instructions.
458 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
460 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
461 bool StackGrowsDown, int64_t &Offset,
462 unsigned &MaxAlign) {
463 // If the stack grows down, add the object size to find the lowest address.
465 Offset += MFI->getObjectSize(FrameIdx);
467 unsigned Align = MFI->getObjectAlignment(FrameIdx);
469 // If the alignment of this object is greater than that of the stack, then
470 // increase the stack alignment to match.
471 MaxAlign = std::max(MaxAlign, Align);
473 // Adjust to alignment boundary.
474 Offset = (Offset + Align - 1) / Align * Align;
476 if (StackGrowsDown) {
477 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
478 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
480 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
481 MFI->setObjectOffset(FrameIdx, Offset);
482 Offset += MFI->getObjectSize(FrameIdx);
486 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
487 /// abstract stack objects.
489 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
490 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
492 bool StackGrowsDown =
493 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
495 // Loop over all of the stack objects, assigning sequential addresses...
496 MachineFrameInfo *MFI = Fn.getFrameInfo();
498 // Start at the beginning of the local area.
499 // The Offset is the distance from the stack top in the direction
500 // of stack growth -- so it's always nonnegative.
501 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
503 LocalAreaOffset = -LocalAreaOffset;
504 assert(LocalAreaOffset >= 0
505 && "Local area offset should be in direction of stack growth");
506 int64_t Offset = LocalAreaOffset;
508 // If there are fixed sized objects that are preallocated in the local area,
509 // non-fixed objects can't be allocated right at the start of local area.
510 // We currently don't support filling in holes in between fixed sized
511 // objects, so we adjust 'Offset' to point to the end of last fixed sized
512 // preallocated object.
513 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
515 if (StackGrowsDown) {
516 // The maximum distance from the stack pointer is at lower address of
517 // the object -- which is given by offset. For down growing stack
518 // the offset is negative, so we negate the offset to get the distance.
519 FixedOff = -MFI->getObjectOffset(i);
521 // The maximum distance from the start pointer is at the upper
522 // address of the object.
523 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
525 if (FixedOff > Offset) Offset = FixedOff;
528 // First assign frame offsets to stack objects that are used to spill
529 // callee saved registers.
530 if (StackGrowsDown) {
531 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
532 // If the stack grows down, we need to add the size to find the lowest
533 // address of the object.
534 Offset += MFI->getObjectSize(i);
536 unsigned Align = MFI->getObjectAlignment(i);
537 // Adjust to alignment boundary
538 Offset = (Offset+Align-1)/Align*Align;
540 MFI->setObjectOffset(i, -Offset); // Set the computed offset
543 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
544 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
545 unsigned Align = MFI->getObjectAlignment(i);
546 // Adjust to alignment boundary
547 Offset = (Offset+Align-1)/Align*Align;
549 MFI->setObjectOffset(i, Offset);
550 Offset += MFI->getObjectSize(i);
554 unsigned MaxAlign = MFI->getMaxAlignment();
556 // Make sure the special register scavenging spill slot is closest to the
557 // frame pointer if a frame pointer is required.
558 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
559 if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
560 !RegInfo->needsStackRealignment(Fn)) {
561 int SFI = RS->getScavengingFrameIndex();
563 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
566 // FIXME: Once this is working, then enable flag will change to a target
567 // check for whether the frame is large enough to want to use virtual
568 // frame index registers. Functions which don't want/need this optimization
569 // will continue to use the existing code path.
570 if (MFI->getUseLocalStackAllocationBlock()) {
571 unsigned Align = MFI->getLocalFrameMaxAlign();
573 // Adjust to alignment boundary.
574 Offset = (Offset + Align - 1) / Align * Align;
576 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
578 // Resolve offsets for objects in the local block.
579 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
580 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
581 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
582 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
584 MFI->setObjectOffset(Entry.first, FIOffset);
586 // Allocate the local block
587 Offset += MFI->getLocalFrameSize();
589 MaxAlign = std::max(Align, MaxAlign);
592 // Make sure that the stack protector comes before the local variables on the
594 SmallSet<int, 16> LargeStackObjs;
595 if (MFI->getStackProtectorIndex() >= 0) {
596 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
599 // Assign large stack objects first.
600 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
601 if (MFI->isObjectPreAllocated(i) &&
602 MFI->getUseLocalStackAllocationBlock())
604 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
606 if (RS && (int)i == RS->getScavengingFrameIndex())
608 if (MFI->isDeadObjectIndex(i))
610 if (MFI->getStackProtectorIndex() == (int)i)
612 if (!MFI->MayNeedStackProtector(i))
615 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
616 LargeStackObjs.insert(i);
620 // Then assign frame offsets to stack objects that are not used to spill
621 // callee saved registers.
622 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
623 if (MFI->isObjectPreAllocated(i) &&
624 MFI->getUseLocalStackAllocationBlock())
626 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
628 if (RS && (int)i == RS->getScavengingFrameIndex())
630 if (MFI->isDeadObjectIndex(i))
632 if (MFI->getStackProtectorIndex() == (int)i)
634 if (LargeStackObjs.count(i))
637 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
640 // Make sure the special register scavenging spill slot is closest to the
642 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
643 !RegInfo->useFPForScavengingIndex(Fn))) {
644 int SFI = RS->getScavengingFrameIndex();
646 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
649 if (!TFI.targetHandlesStackFrameRounding()) {
650 // If we have reserved argument space for call sites in the function
651 // immediately on entry to the current function, count it as part of the
652 // overall stack size.
653 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
654 Offset += MFI->getMaxCallFrameSize();
656 // Round up the size to a multiple of the alignment. If the function has
657 // any calls or alloca's, align to the target's StackAlignment value to
658 // ensure that the callee's frame or the alloca data is suitably aligned;
659 // otherwise, for leaf functions, align to the TransientStackAlignment
662 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
663 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
664 StackAlign = TFI.getStackAlignment();
666 StackAlign = TFI.getTransientStackAlignment();
668 // If the frame pointer is eliminated, all frame offsets will be relative to
669 // SP not FP. Align to MaxAlign so this works.
670 StackAlign = std::max(StackAlign, MaxAlign);
671 unsigned AlignMask = StackAlign - 1;
672 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
675 // Update frame info to pretend that this is part of the stack...
676 int64_t StackSize = Offset - LocalAreaOffset;
677 MFI->setStackSize(StackSize);
678 NumBytesStackSpace += StackSize;
681 /// insertPrologEpilogCode - Scan the function for modified callee saved
682 /// registers, insert spill code for these callee saved registers, then add
683 /// prolog and epilog code to the function.
685 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
686 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
688 // Add prologue to the function...
689 TFI.emitPrologue(Fn);
691 // Add epilogue to restore the callee-save registers in each exiting block
692 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
693 // If last instruction is a return instruction, add an epilogue
694 if (!I->empty() && I->back().isReturn())
695 TFI.emitEpilogue(Fn, *I);
698 // Emit additional code that is required to support segmented stacks, if
699 // we've been asked for it. This, when linked with a runtime with support
700 // for segmented stacks (libgcc is one), will result in allocating stack
701 // space in small chunks instead of one large contiguous block.
702 if (Fn.getTarget().Options.EnableSegmentedStacks)
703 TFI.adjustForSegmentedStacks(Fn);
706 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
707 /// register references and actual offsets.
709 void PEI::replaceFrameIndices(MachineFunction &Fn) {
710 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
712 const TargetMachine &TM = Fn.getTarget();
713 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
714 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
715 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
716 const TargetFrameLowering *TFI = TM.getFrameLowering();
717 bool StackGrowsDown =
718 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
719 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
720 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
722 for (MachineFunction::iterator BB = Fn.begin(),
723 E = Fn.end(); BB != E; ++BB) {
725 int SPAdjCount = 0; // frame setup / destroy count.
727 int SPAdj = 0; // SP offset due to call frame setup / destroy.
728 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
730 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
732 if (I->getOpcode() == FrameSetupOpcode ||
733 I->getOpcode() == FrameDestroyOpcode) {
735 // Track whether we see even pairs of them
736 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
738 // Remember how much SP has been adjusted to create the call
740 int Size = I->getOperand(0).getImm();
742 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
743 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
748 MachineBasicBlock::iterator PrevI = BB->end();
749 if (I != BB->begin()) PrevI = prior(I);
750 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
752 // Visit the instructions created by eliminateCallFramePseudoInstr().
753 if (PrevI == BB->end())
754 I = BB->begin(); // The replaced instr was the first in the block.
756 I = llvm::next(PrevI);
760 MachineInstr *MI = I;
762 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
763 if (MI->getOperand(i).isFI()) {
764 // Some instructions (e.g. inline asm instructions) can have
765 // multiple frame indices and/or cause eliminateFrameIndex
766 // to insert more than one instruction. We need the register
767 // scavenger to go through all of these instructions so that
768 // it can update its register information. We keep the
769 // iterator at the point before insertion so that we can
770 // revisit them in full.
771 bool AtBeginning = (I == BB->begin());
772 if (!AtBeginning) --I;
774 // If this instruction has a FrameIndex operand, we need to
775 // use that target machine register info object to eliminate
777 TRI.eliminateFrameIndex(MI, SPAdj,
778 FrameIndexVirtualScavenging ? NULL : RS);
780 // Reset the iterator if we were at the beginning of the BB.
790 if (DoIncr && I != BB->end()) ++I;
792 // Update register states.
793 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
796 // If we have evenly matched pairs of frame setup / destroy instructions,
797 // make sure the adjustments come out to zero. If we don't have matched
798 // pairs, we can't be sure the missing bit isn't in another basic block
799 // due to a custom inserter playing tricks, so just asserting SPAdj==0
800 // isn't sufficient. See tMOVCC on Thumb1, for example.
801 assert((SPAdjCount || SPAdj == 0) &&
802 "Unbalanced call frame setup / destroy pairs?");
806 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
807 /// with physical registers. Use the register scavenger to find an
808 /// appropriate register to use.
809 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
810 // Run through the instructions and find any virtual registers.
811 for (MachineFunction::iterator BB = Fn.begin(),
812 E = Fn.end(); BB != E; ++BB) {
813 RS->enterBasicBlock(BB);
815 unsigned VirtReg = 0;
816 unsigned ScratchReg = 0;
819 // The instruction stream may change in the loop, so check BB->end()
821 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
822 MachineInstr *MI = I;
823 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
824 if (MI->getOperand(i).isReg()) {
825 MachineOperand &MO = MI->getOperand(i);
826 unsigned Reg = MO.getReg();
829 if (!TargetRegisterInfo::isVirtualRegister(Reg))
832 ++NumVirtualFrameRegs;
834 // Have we already allocated a scratch register for this virtual?
835 if (Reg != VirtReg) {
836 // When we first encounter a new virtual register, it
837 // must be a definition.
838 assert(MI->getOperand(i).isDef() &&
839 "frame index virtual missing def!");
840 // Scavenge a new scratch register
842 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
843 ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
846 // Replace this reference to the virtual register with the
848 assert (ScratchReg && "Missing scratch register!");
849 MI->getOperand(i).setReg(ScratchReg);