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"
27 #include "llvm/Support/Compiler.h"
32 struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass {
33 const char *getPassName() const {
34 return "Prolog/Epilog Insertion & Frame Finalization";
37 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
38 /// frame indexes with appropriate references.
40 bool runOnMachineFunction(MachineFunction &Fn) {
41 // Get MachineDebugInfo so that we can track the construction of the
43 if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) {
44 Fn.getFrameInfo()->setMachineDebugInfo(DI);
47 // Allow the target machine to make some adjustments to the function
48 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
49 Fn.getTarget().getRegisterInfo()
50 ->processFunctionBeforeCalleeSavedScan(Fn);
52 // Scan the function for modified callee saved registers and insert spill
53 // code for any callee saved registers that are modified. Also calculate
54 // the MaxCallFrameSize and HasCalls variables for the function's frame
55 // information and eliminates call frame pseudo instructions.
56 calculateCalleeSavedRegisters(Fn);
58 // Add the code to save and restore the callee saved registers
59 saveCalleeSavedRegisters(Fn);
61 // Allow the target machine to make final modifications to the function
62 // before the frame layout is finalized.
63 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
65 // Calculate actual frame offsets for all of the abstract stack objects...
66 calculateFrameObjectOffsets(Fn);
68 // Add prolog and epilog code to the function. This function is required
69 // to align the stack frame as necessary for any stack variables or
70 // called functions. Because of this, calculateCalleeSavedRegisters
71 // must be called before this function in order to set the HasCalls
72 // and MaxCallFrameSize variables.
73 insertPrologEpilogCode(Fn);
75 // Replace all MO_FrameIndex operands with physical register references
76 // and actual offsets.
78 replaceFrameIndices(Fn);
84 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
85 // stack frame indexes.
86 unsigned MinCSFrameIndex, MaxCSFrameIndex;
88 void calculateCalleeSavedRegisters(MachineFunction &Fn);
89 void saveCalleeSavedRegisters(MachineFunction &Fn);
90 void calculateFrameObjectOffsets(MachineFunction &Fn);
91 void replaceFrameIndices(MachineFunction &Fn);
92 void insertPrologEpilogCode(MachineFunction &Fn);
97 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
98 /// prolog and epilog code, and eliminates abstract frame references.
100 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
103 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
104 /// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
105 /// the function's frame information and eliminates call frame pseudo
108 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
109 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
110 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
112 // Get the callee saved register list...
113 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
115 // Get the function call frame set-up and tear-down instruction opcode
116 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
117 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
119 // These are used to keep track the callee-save area. Initialize them.
120 MinCSFrameIndex = INT_MAX;
123 // Early exit for targets which have no callee saved registers and no call
124 // frame setup/destroy pseudo instructions.
125 if ((CSRegs == 0 || CSRegs[0] == 0) &&
126 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
129 unsigned MaxCallFrameSize = 0;
130 bool HasCalls = false;
132 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
133 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
134 if (I->getOpcode() == FrameSetupOpcode ||
135 I->getOpcode() == FrameDestroyOpcode) {
136 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
137 " instructions should have a single immediate argument!");
138 unsigned Size = I->getOperand(0).getImmedValue();
139 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
141 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
146 MachineFrameInfo *FFI = Fn.getFrameInfo();
147 FFI->setHasCalls(HasCalls);
148 FFI->setMaxCallFrameSize(MaxCallFrameSize);
150 // Now figure out which *callee saved* registers are modified by the current
151 // function, thus needing to be saved and restored in the prolog/epilog.
153 const bool *PhysRegsUsed = Fn.getUsedPhysregs();
154 const TargetRegisterClass* const *CSRegClasses =
155 RegInfo->getCalleeSavedRegClasses();
156 std::vector<CalleeSavedInfo> CSI;
157 for (unsigned i = 0; CSRegs[i]; ++i) {
158 unsigned Reg = CSRegs[i];
159 if (PhysRegsUsed[Reg]) {
160 // If the reg is modified, save it!
161 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
163 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
164 *AliasSet; ++AliasSet) { // Check alias registers too.
165 if (PhysRegsUsed[*AliasSet]) {
166 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
174 return; // Early exit if no callee saved registers are modified!
176 unsigned NumFixedSpillSlots;
177 const std::pair<unsigned,int> *FixedSpillSlots =
178 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
180 // Now that we know which registers need to be saved and restored, allocate
181 // stack slots for them.
182 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
183 unsigned Reg = CSI[i].getReg();
184 const TargetRegisterClass *RC = CSI[i].getRegClass();
186 // Check to see if this physreg must be spilled to a particular stack slot
188 const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
189 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
190 FixedSlot->first != Reg)
194 if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
195 // Nope, just spill it anywhere convenient.
196 unsigned Align = RC->getAlignment();
197 unsigned StackAlign = TFI->getStackAlignment();
198 // We may not be able to sastify the desired alignment specification of
199 // the TargetRegisterClass if the stack alignment is smaller. Use the min.
200 Align = std::min(Align, StackAlign);
201 FrameIdx = FFI->CreateStackObject(RC->getSize(), Align);
202 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
203 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
205 // Spill it to the stack where we must.
206 FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
208 CSI[i].setFrameIdx(FrameIdx);
211 FFI->setCalleeSavedInfo(CSI);
214 /// saveCalleeSavedRegisters - Insert spill code for any callee saved registers
215 /// that are modified in the function.
217 void PEI::saveCalleeSavedRegisters(MachineFunction &Fn) {
218 // Get callee saved register information.
219 MachineFrameInfo *FFI = Fn.getFrameInfo();
220 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
222 // Early exit if no callee saved registers are modified!
226 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
228 // Now that we have a stack slot for each register to be saved, insert spill
229 // code into the entry block.
230 MachineBasicBlock *MBB = Fn.begin();
231 MachineBasicBlock::iterator I = MBB->begin();
232 if (!RegInfo->spillCalleeSavedRegisters(*MBB, I, CSI)) {
233 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
234 // Insert the spill to the stack frame.
235 RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(),
236 CSI[i].getFrameIdx(),
237 CSI[i].getRegClass());
241 // Add code to restore the callee-save registers in each exiting block.
242 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
243 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
244 // If last instruction is a return instruction, add an epilogue.
245 if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
249 // Skip over all terminator instructions, which are part of the return
251 MachineBasicBlock::iterator I2 = I;
252 while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
255 bool AtStart = I == MBB->begin();
256 MachineBasicBlock::iterator BeforeI = I;
260 // Restore all registers immediately before the return and any terminators
262 if (!RegInfo->restoreCalleeSavedRegisters(*MBB, I, CSI)) {
263 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
264 RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
265 CSI[i].getFrameIdx(),
266 CSI[i].getRegClass());
267 assert(I != MBB->begin() &&
268 "loadRegFromStackSlot didn't insert any code!");
269 // Insert in reverse order. loadRegFromStackSlot can insert multiple
283 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
284 /// abstract stack objects.
286 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
287 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
289 bool StackGrowsDown =
290 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
292 // Loop over all of the stack objects, assigning sequential addresses...
293 MachineFrameInfo *FFI = Fn.getFrameInfo();
295 unsigned StackAlignment = TFI.getStackAlignment();
296 unsigned MaxAlign = 0;
298 // Start at the beginning of the local area.
299 // The Offset is the distance from the stack top in the direction
300 // of stack growth -- so it's always positive.
301 int Offset = TFI.getOffsetOfLocalArea();
305 && "Local area offset should be in direction of stack growth");
307 // If there are fixed sized objects that are preallocated in the local area,
308 // non-fixed objects can't be allocated right at the start of local area.
309 // We currently don't support filling in holes in between fixed sized objects,
310 // so we adjust 'Offset' to point to the end of last fixed sized
311 // preallocated object.
312 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
314 if (StackGrowsDown) {
315 // The maximum distance from the stack pointer is at lower address of
316 // the object -- which is given by offset. For down growing stack
317 // the offset is negative, so we negate the offset to get the distance.
318 FixedOff = -FFI->getObjectOffset(i);
320 // The maximum distance from the start pointer is at the upper
321 // address of the object.
322 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
324 if (FixedOff > Offset) Offset = FixedOff;
327 // First assign frame offsets to stack objects that are used to spill
328 // callee saved registers.
329 if (StackGrowsDown) {
330 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
331 if (i < MinCSFrameIndex || i > MaxCSFrameIndex)
334 // If stack grows down, we need to add size of find the lowest
335 // address of the object.
336 Offset += FFI->getObjectSize(i);
338 unsigned Align = FFI->getObjectAlignment(i);
339 // If the alignment of this object is greater than that of the stack, then
340 // increase the stack alignment to match.
341 MaxAlign = std::max(MaxAlign, Align);
342 // Adjust to alignment boundary
343 Offset = (Offset+Align-1)/Align*Align;
345 FFI->setObjectOffset(i, -Offset); // Set the computed offset
348 for (int i = FFI->getObjectIndexEnd()-1; i >= 0; --i) {
349 if ((unsigned)i < MinCSFrameIndex || (unsigned)i > MaxCSFrameIndex)
352 unsigned Align = FFI->getObjectAlignment(i);
353 // If the alignment of this object is greater than that of the stack, then
354 // increase the stack alignment to match.
355 MaxAlign = std::max(MaxAlign, Align);
356 // Adjust to alignment boundary
357 Offset = (Offset+Align-1)/Align*Align;
359 FFI->setObjectOffset(i, Offset);
360 Offset += FFI->getObjectSize(i);
364 // Then assign frame offsets to stack objects that are not used to spill
365 // callee saved registers.
366 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
367 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
370 // If stack grows down, we need to add size of find the lowest
371 // address of the object.
373 Offset += FFI->getObjectSize(i);
375 unsigned Align = FFI->getObjectAlignment(i);
376 // If the alignment of this object is greater than that of the stack, then
377 // increase the stack alignment to match.
378 MaxAlign = std::max(MaxAlign, Align);
379 // Adjust to alignment boundary
380 Offset = (Offset+Align-1)/Align*Align;
382 if (StackGrowsDown) {
383 FFI->setObjectOffset(i, -Offset); // Set the computed offset
385 FFI->setObjectOffset(i, Offset);
386 Offset += FFI->getObjectSize(i);
391 // Align the final stack pointer offset, but only if there are calls in the
392 // function. This ensures that any calls to subroutines have their stack
393 // frames suitable aligned.
395 Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
397 // Set the final value of the stack pointer...
398 FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
400 // Remember the required stack alignment in case targets need it to perform
401 // dynamic stack alignment.
402 assert(FFI->getMaxAlignment() == MaxAlign &&
403 "Stack alignment calculation broken!");
407 /// insertPrologEpilogCode - Scan the function for modified callee saved
408 /// registers, insert spill code for these callee saved registers, then add
409 /// prolog and epilog code to the function.
411 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
412 // Add prologue to the function...
413 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
415 // Add epilogue to restore the callee-save registers in each exiting block
416 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
417 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
418 // If last instruction is a return instruction, add an epilogue
419 if (!I->empty() && TII.isReturn(I->back().getOpcode()))
420 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
425 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
426 /// register references and actual offsets.
428 void PEI::replaceFrameIndices(MachineFunction &Fn) {
429 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
431 const TargetMachine &TM = Fn.getTarget();
432 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
433 const MRegisterInfo &MRI = *TM.getRegisterInfo();
435 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
436 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
437 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
438 if (I->getOperand(i).isFrameIndex()) {
439 // If this instruction has a FrameIndex operand, we need to use that
440 // target machine register info object to eliminate it.
441 MRI.eliminateFrameIndex(I);