1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
30 struct PEI : public MachineFunctionPass {
31 const char *getPassName() const {
32 return "Prolog/Epilog Insertion & Frame Finalization";
35 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
36 /// frame indexes with appropriate references.
38 bool runOnMachineFunction(MachineFunction &Fn) {
39 // Scan the function for modified caller saved registers and insert spill
40 // code for any caller saved registers that are modified. Also calculate
41 // the MaxCallFrameSize and HasCalls variables for the function's frame
42 // information and eliminates call frame pseudo instructions.
43 calculateCallerSavedRegisters(Fn);
45 // Add the code to save and restore the caller saved registers
46 saveCallerSavedRegisters(Fn);
48 // Allow the target machine to make final modifications to the function
49 // before the frame layout is finalized.
50 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
52 // Calculate actual frame offsets for all of the abstract stack objects...
53 calculateFrameObjectOffsets(Fn);
55 // Add prolog and epilog code to the function. This function is required
56 // to align the stack frame as necessary for any stack variables or
57 // called functions. Because of this, calculateCallerSavedRegisters
58 // must be called before this function in order to set the HasCalls
59 // and MaxCallFrameSize variables.
60 insertPrologEpilogCode(Fn);
62 // Replace all MO_FrameIndex operands with physical register references
63 // and actual offsets.
65 replaceFrameIndices(Fn);
73 std::vector<unsigned> RegsToSave;
74 std::vector<int> StackSlots;
76 void calculateCallerSavedRegisters(MachineFunction &Fn);
77 void saveCallerSavedRegisters(MachineFunction &Fn);
78 void calculateFrameObjectOffsets(MachineFunction &Fn);
79 void replaceFrameIndices(MachineFunction &Fn);
80 void insertPrologEpilogCode(MachineFunction &Fn);
85 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
86 /// prolog and epilog code, and eliminates abstract frame references.
88 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
91 /// calculateCallerSavedRegisters - Scan the function for modified caller saved
92 /// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
93 /// the function's frame information and eliminates call frame pseudo
96 void PEI::calculateCallerSavedRegisters(MachineFunction &Fn) {
97 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
98 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
99 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
101 // Get the callee saved register list...
102 const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
104 // Get the function call frame set-up and tear-down instruction opcode
105 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
106 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
108 // Early exit for targets which have no callee saved registers and no call
109 // frame setup/destroy pseudo instructions.
110 if ((CSRegs == 0 || CSRegs[0] == 0) &&
111 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
114 unsigned MaxCallFrameSize = 0;
115 bool HasCalls = false;
117 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
118 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
119 if (I->getOpcode() == FrameSetupOpcode ||
120 I->getOpcode() == FrameDestroyOpcode) {
121 assert(I->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
122 " instructions should have a single immediate argument!");
123 unsigned Size = I->getOperand(0).getImmedValue();
124 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
126 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
131 MachineFrameInfo *FFI = Fn.getFrameInfo();
132 FFI->setHasCalls(HasCalls);
133 FFI->setMaxCallFrameSize(MaxCallFrameSize);
135 // Now figure out which *callee saved* registers are modified by the current
136 // function, thus needing to be saved and restored in the prolog/epilog.
138 const bool *PhysRegsUsed = Fn.getUsedPhysregs();
139 for (unsigned i = 0; CSRegs[i]; ++i) {
140 unsigned Reg = CSRegs[i];
141 if (PhysRegsUsed[Reg]) {
142 RegsToSave.push_back(Reg); // If the reg is modified, save it!
144 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
145 *AliasSet; ++AliasSet) { // Check alias registers too.
146 if (PhysRegsUsed[*AliasSet]) {
147 RegsToSave.push_back(Reg);
154 if (RegsToSave.empty())
155 return; // Early exit if no caller saved registers are modified!
157 unsigned NumFixedSpillSlots;
158 const std::pair<unsigned,int> *FixedSpillSlots =
159 TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
161 // Now that we know which registers need to be saved and restored, allocate
162 // stack slots for them.
163 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
164 unsigned Reg = RegsToSave[i];
166 // Check to see if this physreg must be spilled to a particular stack slot
168 const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
169 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
170 FixedSlot->first != Reg)
174 if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
175 // Nope, just spill it anywhere convenient.
176 FrameIdx = FFI->CreateStackObject(RegInfo->getSpillSize(Reg)/8,
177 RegInfo->getSpillAlignment(Reg)/8);
179 // Spill it to the stack where we must.
180 FrameIdx = FFI->CreateFixedObject(RegInfo->getSpillSize(Reg)/8,
183 StackSlots.push_back(FrameIdx);
187 /// saveCallerSavedRegisters - Insert spill code for any caller saved registers
188 /// that are modified in the function.
190 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
191 // Early exit if no caller saved registers are modified!
192 if (RegsToSave.empty())
195 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
197 // Now that we have a stack slot for each register to be saved, insert spill
198 // code into the entry block.
199 MachineBasicBlock *MBB = Fn.begin();
200 MachineBasicBlock::iterator I = MBB->begin();
201 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
202 // Insert the spill to the stack frame.
203 RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);
206 // Add code to restore the callee-save registers in each exiting block.
207 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
208 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
209 // If last instruction is a return instruction, add an epilogue.
210 if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
214 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
215 RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);
216 assert(I != MBB->begin() &&
217 "loadRegFromStackSlot didn't insert any code!");
218 --I; // Insert in reverse order
224 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
225 /// abstract stack objects.
227 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
228 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
230 bool StackGrowsDown =
231 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
233 // Loop over all of the stack objects, assigning sequential addresses...
234 MachineFrameInfo *FFI = Fn.getFrameInfo();
236 unsigned StackAlignment = TFI.getStackAlignment();
238 // Start at the beginning of the local area.
239 // The Offset is the distance from the stack top in the direction
240 // of stack growth -- so it's always positive.
241 int Offset = TFI.getOffsetOfLocalArea();
245 && "Local area offset should be in direction of stack growth");
247 // If there are fixed sized objects that are preallocated in the local area,
248 // non-fixed objects can't be allocated right at the start of local area.
249 // We currently don't support filling in holes in between fixed sized objects,
250 // so we adjust 'Offset' to point to the end of last fixed sized
251 // preallocated object.
252 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
254 if (StackGrowsDown) {
255 // The maximum distance from the stack pointer is at lower address of
256 // the object -- which is given by offset. For down growing stack
257 // the offset is negative, so we negate the offset to get the distance.
258 FixedOff = -FFI->getObjectOffset(i);
260 // The maximum distance from the start pointer is at the upper
261 // address of the object.
262 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
264 if (FixedOff > Offset) Offset = FixedOff;
267 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
268 // If stack grows down, we need to add size of find the lowest
269 // address of the object.
271 Offset += FFI->getObjectSize(i);
273 unsigned Align = FFI->getObjectAlignment(i);
274 assert(Align <= StackAlignment && "Cannot align stack object to higher "
275 "alignment boundary than the stack itself!");
276 Offset = (Offset+Align-1)/Align*Align; // Adjust to Alignment boundary...
278 if (StackGrowsDown) {
279 FFI->setObjectOffset(i, -Offset); // Set the computed offset
281 FFI->setObjectOffset(i, Offset);
282 Offset += FFI->getObjectSize(i);
286 // Align the final stack pointer offset, but only if there are calls in the
287 // function. This ensures that any calls to subroutines have their stack
288 // frames suitable aligned.
290 Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
292 // Set the final value of the stack pointer...
293 FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
297 /// insertPrologEpilogCode - Scan the function for modified caller saved
298 /// registers, insert spill code for these caller saved registers, then add
299 /// prolog and epilog code to the function.
301 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
302 // Add prologue to the function...
303 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
305 // Add epilogue to restore the callee-save registers in each exiting block
306 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
307 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
308 // If last instruction is a return instruction, add an epilogue
309 if (!I->empty() && TII.isReturn(I->back().getOpcode()))
310 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
315 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
316 /// register references and actual offsets.
318 void PEI::replaceFrameIndices(MachineFunction &Fn) {
319 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
321 const TargetMachine &TM = Fn.getTarget();
322 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
323 const MRegisterInfo &MRI = *TM.getRegisterInfo();
325 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
326 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
327 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
328 if (I->getOperand(i).isFrameIndex()) {
329 // If this instruction has a FrameIndex operand, we need to use that
330 // target machine register info object to eliminate it.
331 MRI.eliminateFrameIndex(I);