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(PEI, "prologepilog",
48 "Prologue/Epilogue Insertion", false, false);
50 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
51 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
53 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
54 /// prolog and epilog code, and eliminates abstract frame references.
56 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
58 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
59 /// frame indexes with appropriate references.
61 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
62 const Function* F = Fn.getFunction();
63 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
64 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
65 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
66 FrameConstantRegMap.clear();
68 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
69 // function's frame information. Also eliminates call frame pseudo
71 calculateCallsInformation(Fn);
73 // Allow the target machine to make some adjustments to the function
74 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
75 TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
77 // Scan the function for modified callee saved registers and insert spill code
78 // for any callee saved registers that are modified.
79 calculateCalleeSavedRegisters(Fn);
81 // Determine placement of CSR spill/restore code:
82 // - With shrink wrapping, place spills and restores to tightly
83 // enclose regions in the Machine CFG of the function where
85 // - Without shink wrapping (default), place all spills in the
86 // entry block, all restores in return blocks.
87 placeCSRSpillsAndRestores(Fn);
89 // Add the code to save and restore the callee saved registers
90 if (!F->hasFnAttr(Attribute::Naked))
91 insertCSRSpillsAndRestores(Fn);
93 // Allow the target machine to make final modifications to the function
94 // before the frame layout is finalized.
95 TRI->processFunctionBeforeFrameFinalized(Fn);
97 // Calculate actual frame offsets for all abstract stack objects...
98 calculateFrameObjectOffsets(Fn);
100 // Add prolog and epilog code to the function. This function is required
101 // to align the stack frame as necessary for any stack variables or
102 // called functions. Because of this, calculateCalleeSavedRegisters()
103 // must be called before this function in order to set the AdjustsStack
104 // and MaxCallFrameSize variables.
105 if (!F->hasFnAttr(Attribute::Naked))
106 insertPrologEpilogCode(Fn);
108 // Replace all MO_FrameIndex operands with physical register references
109 // and actual offsets.
111 replaceFrameIndices(Fn);
113 // If register scavenging is needed, as we've enabled doing it as a
114 // post-pass, scavenge the virtual registers that frame index elimiation
116 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
117 scavengeFrameVirtualRegs(Fn);
125 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
126 AU.setPreservesCFG();
127 if (ShrinkWrapping || ShrinkWrapFunc != "") {
128 AU.addRequired<MachineLoopInfo>();
129 AU.addRequired<MachineDominatorTree>();
131 AU.addPreserved<MachineLoopInfo>();
132 AU.addPreserved<MachineDominatorTree>();
133 MachineFunctionPass::getAnalysisUsage(AU);
137 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
138 /// variables for the function's frame information and eliminate call frame
139 /// pseudo instructions.
140 void PEI::calculateCallsInformation(MachineFunction &Fn) {
141 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
142 MachineFrameInfo *MFI = Fn.getFrameInfo();
144 unsigned MaxCallFrameSize = 0;
145 bool AdjustsStack = MFI->adjustsStack();
147 // Get the function call frame set-up and tear-down instruction opcode
148 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
149 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
151 // Early exit for targets which have no call frame setup/destroy pseudo
153 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
156 std::vector<MachineBasicBlock::iterator> FrameSDOps;
157 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
158 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
159 if (I->getOpcode() == FrameSetupOpcode ||
160 I->getOpcode() == FrameDestroyOpcode) {
161 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
162 " instructions should have a single immediate argument!");
163 unsigned Size = I->getOperand(0).getImm();
164 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
166 FrameSDOps.push_back(I);
167 } else if (I->isInlineAsm()) {
168 // Some inline asm's need a stack frame, as indicated by operand 1.
169 if (I->getOperand(1).getImm())
173 MFI->setAdjustsStack(AdjustsStack);
174 MFI->setMaxCallFrameSize(MaxCallFrameSize);
176 for (std::vector<MachineBasicBlock::iterator>::iterator
177 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
178 MachineBasicBlock::iterator I = *i;
180 // If call frames are not being included as part of the stack frame, and
181 // the target doesn't indicate otherwise, remove the call frame pseudos
182 // here. The sub/add sp instruction pairs are still inserted, but we don't
183 // need to track the SP adjustment for frame index elimination.
184 if (RegInfo->canSimplifyCallFramePseudos(Fn))
185 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
190 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
192 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
193 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
194 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
195 MachineFrameInfo *MFI = Fn.getFrameInfo();
197 // Get the callee saved register list...
198 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
200 // These are used to keep track the callee-save area. Initialize them.
201 MinCSFrameIndex = INT_MAX;
204 // Early exit for targets which have no callee saved registers.
205 if (CSRegs == 0 || CSRegs[0] == 0)
208 // In Naked functions we aren't going to save any registers.
209 if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
212 std::vector<CalleeSavedInfo> CSI;
213 for (unsigned i = 0; CSRegs[i]; ++i) {
214 unsigned Reg = CSRegs[i];
215 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
216 // If the reg is modified, save it!
217 CSI.push_back(CalleeSavedInfo(Reg));
219 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
220 *AliasSet; ++AliasSet) { // Check alias registers too.
221 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
222 CSI.push_back(CalleeSavedInfo(Reg));
230 return; // Early exit if no callee saved registers are modified!
232 unsigned NumFixedSpillSlots;
233 const TargetFrameInfo::SpillSlot *FixedSpillSlots =
234 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
236 // Now that we know which registers need to be saved and restored, allocate
237 // stack slots for them.
238 for (std::vector<CalleeSavedInfo>::iterator
239 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
240 unsigned Reg = I->getReg();
241 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
244 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
245 I->setFrameIdx(FrameIdx);
249 // Check to see if this physreg must be spilled to a particular stack slot
251 const TargetFrameInfo::SpillSlot *FixedSlot = FixedSpillSlots;
252 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
253 FixedSlot->Reg != Reg)
256 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
257 // Nope, just spill it anywhere convenient.
258 unsigned Align = RC->getAlignment();
259 unsigned StackAlign = TFI->getStackAlignment();
261 // We may not be able to satisfy the desired alignment specification of
262 // the TargetRegisterClass if the stack alignment is smaller. Use the
264 Align = std::min(Align, StackAlign);
265 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
266 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
267 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
269 // Spill it to the stack where we must.
270 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
273 I->setFrameIdx(FrameIdx);
276 MFI->setCalleeSavedInfo(CSI);
279 /// insertCSRSpillsAndRestores - Insert spill and restore code for
280 /// callee saved registers used in the function, handling shrink wrapping.
282 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
283 // Get callee saved register information.
284 MachineFrameInfo *MFI = Fn.getFrameInfo();
285 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
287 MFI->setCalleeSavedInfoValid(true);
289 // Early exit if no callee saved registers are modified!
293 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
294 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
295 MachineBasicBlock::iterator I;
297 if (! ShrinkWrapThisFunction) {
298 // Spill using target interface.
299 I = EntryBlock->begin();
300 if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
301 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
302 // Add the callee-saved register as live-in.
303 // It's killed at the spill.
304 EntryBlock->addLiveIn(CSI[i].getReg());
306 // Insert the spill to the stack frame.
307 unsigned Reg = CSI[i].getReg();
308 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
309 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
310 CSI[i].getFrameIdx(), RC, TRI);
314 // Restore using target interface.
315 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
316 MachineBasicBlock* MBB = ReturnBlocks[ri];
319 // Skip over all terminator instructions, which are part of the return
321 MachineBasicBlock::iterator I2 = I;
322 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
325 bool AtStart = I == MBB->begin();
326 MachineBasicBlock::iterator BeforeI = I;
330 // Restore all registers immediately before the return and any
331 // terminators that preceed it.
332 if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
333 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
334 unsigned Reg = CSI[i].getReg();
335 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
336 TII.loadRegFromStackSlot(*MBB, I, Reg,
337 CSI[i].getFrameIdx(),
339 assert(I != MBB->begin() &&
340 "loadRegFromStackSlot didn't insert any code!");
341 // Insert in reverse order. loadRegFromStackSlot can insert
342 // multiple instructions.
356 std::vector<CalleeSavedInfo> blockCSI;
357 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
358 BE = CSRSave.end(); BI != BE; ++BI) {
359 MachineBasicBlock* MBB = BI->first;
360 CSRegSet save = BI->second;
366 for (CSRegSet::iterator RI = save.begin(),
367 RE = save.end(); RI != RE; ++RI) {
368 blockCSI.push_back(CSI[*RI]);
370 assert(blockCSI.size() > 0 &&
371 "Could not collect callee saved register info");
375 // When shrink wrapping, use stack slot stores/loads.
376 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
377 // Add the callee-saved register as live-in.
378 // It's killed at the spill.
379 MBB->addLiveIn(blockCSI[i].getReg());
381 // Insert the spill to the stack frame.
382 unsigned Reg = blockCSI[i].getReg();
383 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
384 TII.storeRegToStackSlot(*MBB, I, Reg,
386 blockCSI[i].getFrameIdx(),
391 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
392 BE = CSRRestore.end(); BI != BE; ++BI) {
393 MachineBasicBlock* MBB = BI->first;
394 CSRegSet restore = BI->second;
400 for (CSRegSet::iterator RI = restore.begin(),
401 RE = restore.end(); RI != RE; ++RI) {
402 blockCSI.push_back(CSI[*RI]);
404 assert(blockCSI.size() > 0 &&
405 "Could not find callee saved register info");
407 // If MBB is empty and needs restores, insert at the _beginning_.
414 // Skip over all terminator instructions, which are part of the
416 if (! I->getDesc().isTerminator()) {
419 MachineBasicBlock::iterator I2 = I;
420 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
425 bool AtStart = I == MBB->begin();
426 MachineBasicBlock::iterator BeforeI = I;
430 // Restore all registers immediately before the return and any
431 // terminators that preceed it.
432 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
433 unsigned Reg = blockCSI[i].getReg();
434 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
435 TII.loadRegFromStackSlot(*MBB, I, Reg,
436 blockCSI[i].getFrameIdx(),
438 assert(I != MBB->begin() &&
439 "loadRegFromStackSlot didn't insert any code!");
440 // Insert in reverse order. loadRegFromStackSlot can insert
441 // multiple instructions.
452 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
454 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
455 bool StackGrowsDown, int64_t &Offset,
456 unsigned &MaxAlign) {
457 // If the stack grows down, add the object size to find the lowest address.
459 Offset += MFI->getObjectSize(FrameIdx);
461 unsigned Align = MFI->getObjectAlignment(FrameIdx);
463 // If the alignment of this object is greater than that of the stack, then
464 // increase the stack alignment to match.
465 MaxAlign = std::max(MaxAlign, Align);
467 // Adjust to alignment boundary.
468 Offset = (Offset + Align - 1) / Align * Align;
470 if (StackGrowsDown) {
471 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
472 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
474 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
475 MFI->setObjectOffset(FrameIdx, Offset);
476 Offset += MFI->getObjectSize(FrameIdx);
480 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
481 /// abstract stack objects.
483 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
484 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
486 bool StackGrowsDown =
487 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
489 // Loop over all of the stack objects, assigning sequential addresses...
490 MachineFrameInfo *MFI = Fn.getFrameInfo();
492 // Start at the beginning of the local area.
493 // The Offset is the distance from the stack top in the direction
494 // of stack growth -- so it's always nonnegative.
495 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
497 LocalAreaOffset = -LocalAreaOffset;
498 assert(LocalAreaOffset >= 0
499 && "Local area offset should be in direction of stack growth");
500 int64_t Offset = LocalAreaOffset;
502 // If there are fixed sized objects that are preallocated in the local area,
503 // non-fixed objects can't be allocated right at the start of local area.
504 // We currently don't support filling in holes in between fixed sized
505 // objects, so we adjust 'Offset' to point to the end of last fixed sized
506 // preallocated object.
507 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
509 if (StackGrowsDown) {
510 // The maximum distance from the stack pointer is at lower address of
511 // the object -- which is given by offset. For down growing stack
512 // the offset is negative, so we negate the offset to get the distance.
513 FixedOff = -MFI->getObjectOffset(i);
515 // The maximum distance from the start pointer is at the upper
516 // address of the object.
517 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
519 if (FixedOff > Offset) Offset = FixedOff;
522 // First assign frame offsets to stack objects that are used to spill
523 // callee saved registers.
524 if (StackGrowsDown) {
525 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
526 // If the stack grows down, we need to add the size to find the lowest
527 // address of the object.
528 Offset += MFI->getObjectSize(i);
530 unsigned Align = MFI->getObjectAlignment(i);
531 // Adjust to alignment boundary
532 Offset = (Offset+Align-1)/Align*Align;
534 MFI->setObjectOffset(i, -Offset); // Set the computed offset
537 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
538 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
539 unsigned Align = MFI->getObjectAlignment(i);
540 // Adjust to alignment boundary
541 Offset = (Offset+Align-1)/Align*Align;
543 MFI->setObjectOffset(i, Offset);
544 Offset += MFI->getObjectSize(i);
548 unsigned MaxAlign = MFI->getMaxAlignment();
550 // Make sure the special register scavenging spill slot is closest to the
551 // frame pointer if a frame pointer is required.
552 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
553 if (RS && RegInfo->hasFP(Fn) && !RegInfo->needsStackRealignment(Fn)) {
554 int SFI = RS->getScavengingFrameIndex();
556 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
559 // FIXME: Once this is working, then enable flag will change to a target
560 // check for whether the frame is large enough to want to use virtual
561 // frame index registers. Functions which don't want/need this optimization
562 // will continue to use the existing code path.
563 if (MFI->getUseLocalStackAllocationBlock()) {
564 unsigned Align = MFI->getLocalFrameMaxAlign();
566 // Adjust to alignment boundary.
567 Offset = (Offset + Align - 1) / Align * Align;
569 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
571 // Resolve offsets for objects in the local block.
572 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
573 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
574 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
575 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
577 MFI->setObjectOffset(Entry.first, FIOffset);
579 // Allocate the local block
580 Offset += MFI->getLocalFrameSize();
582 MaxAlign = std::max(Align, MaxAlign);
585 // Make sure that the stack protector comes before the local variables on the
587 SmallSet<int, 16> LargeStackObjs;
588 if (MFI->getStackProtectorIndex() >= 0) {
589 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
592 // Assign large stack objects first.
593 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
594 if (MFI->isObjectPreAllocated(i) &&
595 MFI->getUseLocalStackAllocationBlock())
597 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
599 if (RS && (int)i == RS->getScavengingFrameIndex())
601 if (MFI->isDeadObjectIndex(i))
603 if (MFI->getStackProtectorIndex() == (int)i)
605 if (!MFI->MayNeedStackProtector(i))
608 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
609 LargeStackObjs.insert(i);
613 // Then assign frame offsets to stack objects that are not used to spill
614 // callee saved registers.
615 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
616 if (MFI->isObjectPreAllocated(i) &&
617 MFI->getUseLocalStackAllocationBlock())
619 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
621 if (RS && (int)i == RS->getScavengingFrameIndex())
623 if (MFI->isDeadObjectIndex(i))
625 if (MFI->getStackProtectorIndex() == (int)i)
627 if (LargeStackObjs.count(i))
630 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
633 // Make sure the special register scavenging spill slot is closest to the
635 if (RS && (!RegInfo->hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) {
636 int SFI = RS->getScavengingFrameIndex();
638 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
641 if (!RegInfo->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() && RegInfo->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 MFI->setStackSize(Offset - LocalAreaOffset);
671 /// insertPrologEpilogCode - Scan the function for modified callee saved
672 /// registers, insert spill code for these callee saved registers, then add
673 /// prolog and epilog code to the function.
675 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
676 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
678 // Add prologue to the function...
679 TRI->emitPrologue(Fn);
681 // Add epilogue to restore the callee-save registers in each exiting block
682 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
683 // If last instruction is a return instruction, add an epilogue
684 if (!I->empty() && I->back().getDesc().isReturn())
685 TRI->emitEpilogue(Fn, *I);
689 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
690 /// register references and actual offsets.
692 void PEI::replaceFrameIndices(MachineFunction &Fn) {
693 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
695 const TargetMachine &TM = Fn.getTarget();
696 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
697 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
698 const TargetFrameInfo *TFI = TM.getFrameInfo();
699 bool StackGrowsDown =
700 TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
701 int FrameSetupOpcode = TRI.getCallFrameSetupOpcode();
702 int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
704 for (MachineFunction::iterator BB = Fn.begin(),
705 E = Fn.end(); BB != E; ++BB) {
707 int SPAdjCount = 0; // frame setup / destroy count.
709 int SPAdj = 0; // SP offset due to call frame setup / destroy.
710 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
712 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
714 if (I->getOpcode() == FrameSetupOpcode ||
715 I->getOpcode() == FrameDestroyOpcode) {
717 // Track whether we see even pairs of them
718 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
720 // Remember how much SP has been adjusted to create the call
722 int Size = I->getOperand(0).getImm();
724 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
725 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
730 MachineBasicBlock::iterator PrevI = BB->end();
731 if (I != BB->begin()) PrevI = prior(I);
732 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
734 // Visit the instructions created by eliminateCallFramePseudoInstr().
735 if (PrevI == BB->end())
736 I = BB->begin(); // The replaced instr was the first in the block.
738 I = llvm::next(PrevI);
742 MachineInstr *MI = I;
744 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
745 if (MI->getOperand(i).isFI()) {
746 // Some instructions (e.g. inline asm instructions) can have
747 // multiple frame indices and/or cause eliminateFrameIndex
748 // to insert more than one instruction. We need the register
749 // scavenger to go through all of these instructions so that
750 // it can update its register information. We keep the
751 // iterator at the point before insertion so that we can
752 // revisit them in full.
753 bool AtBeginning = (I == BB->begin());
754 if (!AtBeginning) --I;
756 // If this instruction has a FrameIndex operand, we need to
757 // use that target machine register info object to eliminate
759 TargetRegisterInfo::FrameIndexValue Value;
761 TRI.eliminateFrameIndex(MI, SPAdj, &Value,
762 FrameIndexVirtualScavenging ? NULL : RS);
764 assert (FrameIndexVirtualScavenging &&
765 "Not scavenging, but virtual returned from "
766 "eliminateFrameIndex()!");
767 FrameConstantRegMap[VReg] = FrameConstantEntry(Value, SPAdj);
770 // Reset the iterator if we were at the beginning of the BB.
780 if (DoIncr && I != BB->end()) ++I;
782 // Update register states.
783 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
786 // If we have evenly matched pairs of frame setup / destroy instructions,
787 // make sure the adjustments come out to zero. If we don't have matched
788 // pairs, we can't be sure the missing bit isn't in another basic block
789 // due to a custom inserter playing tricks, so just asserting SPAdj==0
790 // isn't sufficient. See tMOVCC on Thumb1, for example.
791 assert((SPAdjCount || SPAdj == 0) &&
792 "Unbalanced call frame setup / destroy pairs?");
796 /// findLastUseReg - find the killing use of the specified register within
797 /// the instruciton range. Return the operand number of the kill in Operand.
798 static MachineBasicBlock::iterator
799 findLastUseReg(MachineBasicBlock::iterator I, MachineBasicBlock::iterator ME,
801 // Scan forward to find the last use of this virtual register
802 for (++I; I != ME; ++I) {
803 MachineInstr *MI = I;
804 bool isDefInsn = false;
805 bool isKillInsn = false;
806 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
807 if (MI->getOperand(i).isReg()) {
808 unsigned OpReg = MI->getOperand(i).getReg();
809 if (OpReg == 0 || !TargetRegisterInfo::isVirtualRegister(OpReg))
812 && "overlapping use of scavenged index register!");
813 // If this is the killing use, we have a candidate.
814 if (MI->getOperand(i).isKill())
816 else if (MI->getOperand(i).isDef())
819 if (isKillInsn && !isDefInsn)
822 // If we hit the end of the basic block, there was no kill of
823 // the virtual register, which is wrong.
824 assert (0 && "scavenged index register never killed!");
828 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
829 /// with physical registers. Use the register scavenger to find an
830 /// appropriate register to use.
831 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
832 // Run through the instructions and find any virtual registers.
833 for (MachineFunction::iterator BB = Fn.begin(),
834 E = Fn.end(); BB != E; ++BB) {
835 RS->enterBasicBlock(BB);
837 // FIXME: The logic flow in this function is still too convoluted.
838 // It needs a cleanup refactoring. Do that in preparation for tracking
839 // more than one scratch register value and using ranges to find
840 // available scratch registers.
841 unsigned CurrentVirtReg = 0;
842 unsigned CurrentScratchReg = 0;
843 bool havePrevValue = false;
844 TargetRegisterInfo::FrameIndexValue PrevValue(0,0);
845 TargetRegisterInfo::FrameIndexValue Value(0,0);
846 MachineInstr *PrevLastUseMI = NULL;
847 unsigned PrevLastUseOp = 0;
848 bool trackingCurrentValue = false;
851 // The instruction stream may change in the loop, so check BB->end()
853 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
854 MachineInstr *MI = I;
855 bool isDefInsn = false;
856 bool isKillInsn = false;
857 bool clobbersScratchReg = false;
859 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
860 if (MI->getOperand(i).isReg()) {
861 MachineOperand &MO = MI->getOperand(i);
862 unsigned Reg = MO.getReg();
865 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
866 // If we have a previous scratch reg, check and see if anything
867 // here kills whatever value is in there.
868 if (Reg == CurrentScratchReg) {
870 // Two-address operands implicitly kill
871 if (MO.isKill() || MI->isRegTiedToDefOperand(i))
872 clobbersScratchReg = true;
875 clobbersScratchReg = true;
880 ++NumVirtualFrameRegs;
882 // If this is a def, remember that this insn defines the value.
883 // This lets us properly consider insns which re-use the scratch
884 // register, such as r2 = sub r2, #imm, in the middle of the
889 // Have we already allocated a scratch register for this virtual?
890 if (Reg != CurrentVirtReg) {
891 // When we first encounter a new virtual register, it
892 // must be a definition.
893 assert(MI->getOperand(i).isDef() &&
894 "frame index virtual missing def!");
895 // We can't have nested virtual register live ranges because
896 // there's only a guarantee of one scavenged register at a time.
897 assert (CurrentVirtReg == 0 &&
898 "overlapping frame index virtual registers!");
900 // If the target gave us information about what's in the register,
901 // we can use that to re-use scratch regs.
902 DenseMap<unsigned, FrameConstantEntry>::iterator Entry =
903 FrameConstantRegMap.find(Reg);
904 trackingCurrentValue = Entry != FrameConstantRegMap.end();
905 if (trackingCurrentValue) {
906 SPAdj = (*Entry).second.second;
907 Value = (*Entry).second.first;
914 // If the scratch register from the last allocation is still
915 // available, see if the value matches. If it does, just re-use it.
916 if (trackingCurrentValue && havePrevValue && PrevValue == Value) {
917 // FIXME: This assumes that the instructions in the live range
918 // for the virtual register are exclusively for the purpose
919 // of populating the value in the register. That's reasonable
920 // for these frame index registers, but it's still a very, very
921 // strong assumption. rdar://7322732. Better would be to
922 // explicitly check each instruction in the range for references
923 // to the virtual register. Only delete those insns that
924 // touch the virtual register.
926 // Find the last use of the new virtual register. Remove all
927 // instruction between here and there, and update the current
928 // instruction to reference the last use insn instead.
929 MachineBasicBlock::iterator LastUseMI =
930 findLastUseReg(I, BB->end(), Reg);
932 // Remove all instructions up 'til the last use, since they're
933 // just calculating the value we already have.
934 BB->erase(I, LastUseMI);
937 // Extend the live range of the scratch register
938 PrevLastUseMI->getOperand(PrevLastUseOp).setIsKill(false);
939 RS->setUsed(CurrentScratchReg);
940 CurrentVirtReg = Reg;
942 // We deleted the instruction we were scanning the operands of.
943 // Jump back to the instruction iterator loop. Don't increment
944 // past this instruction since we updated the iterator already.
949 // Scavenge a new scratch register
950 CurrentVirtReg = Reg;
951 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
952 CurrentScratchReg = RS->scavengeRegister(RC, I, SPAdj);
956 // replace this reference to the virtual register with the
958 assert (CurrentScratchReg && "Missing scratch register!");
959 MI->getOperand(i).setReg(CurrentScratchReg);
961 if (MI->getOperand(i).isKill()) {
968 // If this is the last use of the scratch, stop tracking it. The
969 // last use will be a kill operand in an instruction that does
970 // not also define the scratch register.
971 if (isKillInsn && !isDefInsn) {
973 havePrevValue = trackingCurrentValue;
975 // Similarly, notice if instruction clobbered the value in the
976 // register we're tracking for possible later reuse. This is noted
977 // above, but enforced here since the value is still live while we
978 // process the rest of the operands of the instruction.
979 if (clobbersScratchReg) {
980 havePrevValue = false;
981 CurrentScratchReg = 0;