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 saveCallerSavedRegisters(Fn);
45 // Allow the target machine to make final modifications to the function
46 // before the frame layout is finalized.
47 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
49 // Calculate actual frame offsets for all of the abstract stack objects...
50 calculateFrameObjectOffsets(Fn);
52 // Add prolog and epilog code to the function.
53 insertPrologEpilogCode(Fn);
55 // Replace all MO_FrameIndex operands with physical register references
56 // and actual offsets.
58 replaceFrameIndices(Fn);
63 void saveCallerSavedRegisters(MachineFunction &Fn);
64 void calculateFrameObjectOffsets(MachineFunction &Fn);
65 void replaceFrameIndices(MachineFunction &Fn);
66 void insertPrologEpilogCode(MachineFunction &Fn);
71 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
72 /// prolog and epilog code, and eliminates abstract frame references.
74 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
77 /// saveCallerSavedRegisters - Scan the function for modified caller saved
78 /// registers and insert spill code for any caller saved registers that are
79 /// modified. Also calculate the MaxCallFrameSize and HasCalls variables for
80 /// the function's frame information and eliminates call frame pseudo
83 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
84 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
85 const TargetFrameInfo &FrameInfo = *Fn.getTarget().getFrameInfo();
87 // Get the callee saved register list...
88 const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
90 // Get the function call frame set-up and tear-down instruction opcode
91 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
92 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
94 // Early exit for targets which have no callee saved registers and no call
95 // frame setup/destroy pseudo instructions.
96 if ((CSRegs == 0 || CSRegs[0] == 0) &&
97 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
100 // This bitset contains an entry for each physical register for the target...
101 std::vector<bool> ModifiedRegs(RegInfo->getNumRegs());
102 unsigned MaxCallFrameSize = 0;
103 bool HasCalls = false;
105 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
106 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
107 if (I->getOpcode() == FrameSetupOpcode ||
108 I->getOpcode() == FrameDestroyOpcode) {
109 assert(I->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
110 " instructions should have a single immediate argument!");
111 unsigned Size = I->getOperand(0).getImmedValue();
112 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
114 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
116 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
117 MachineOperand &MO = I->getOperand(i);
118 if (MO.isRegister() && MO.isDef()) {
119 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
120 "Register allocation must be performed!");
121 ModifiedRegs[MO.getReg()] = true; // Register is modified
127 MachineFrameInfo *FFI = Fn.getFrameInfo();
128 FFI->setHasCalls(HasCalls);
129 FFI->setMaxCallFrameSize(MaxCallFrameSize);
131 // Now figure out which *callee saved* registers are modified by the current
132 // function, thus needing to be saved and restored in the prolog/epilog.
134 std::vector<unsigned> RegsToSave;
135 for (unsigned i = 0; CSRegs[i]; ++i) {
136 unsigned Reg = CSRegs[i];
137 if (ModifiedRegs[Reg]) {
138 RegsToSave.push_back(Reg); // If modified register...
140 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
141 *AliasSet; ++AliasSet) { // Check alias registers too...
142 if (ModifiedRegs[*AliasSet]) {
143 RegsToSave.push_back(Reg);
150 if (RegsToSave.empty())
151 return; // Early exit if no caller saved registers are modified!
153 // Now that we know which registers need to be saved and restored, allocate
154 // stack slots for them.
155 std::vector<int> StackSlots;
156 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
157 int FrameIdx = FFI->CreateStackObject(RegInfo->getRegClass(RegsToSave[i]));
158 StackSlots.push_back(FrameIdx);
161 // Now that we have a stack slot for each register to be saved, insert spill
162 // code into the entry block...
163 MachineBasicBlock *MBB = Fn.begin();
164 MachineBasicBlock::iterator I = MBB->begin();
165 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
166 const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
168 // Insert the spill to the stack frame...
169 RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i], RC);
172 // Add code to restore the callee-save registers in each exiting block.
173 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
174 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
175 // If last instruction is a return instruction, add an epilogue
176 if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
180 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
181 const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
182 RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i], RC);
183 --I; // Insert in reverse order
190 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
191 /// abstract stack objects...
193 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
194 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
196 bool StackGrowsDown =
197 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
199 // Loop over all of the stack objects, assigning sequential addresses...
200 MachineFrameInfo *FFI = Fn.getFrameInfo();
202 unsigned StackAlignment = TFI.getStackAlignment();
204 // Start at the beginning of the local area.
205 // The Offset is the distance from the stack top in the direction
206 // of stack growth -- so it's always positive.
207 int Offset = TFI.getOffsetOfLocalArea();
211 && "Local area offset should be in direction of stack growth");
213 // If there are fixed sized objects that are preallocated in the local area,
214 // non-fixed objects can't be allocated right at the start of local area.
215 // We currently don't support filling in holes in between fixed sized objects,
216 // so we adjust 'Offset' to point to the end of last fixed sized
217 // preallocated object.
218 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
220 if (StackGrowsDown) {
221 // The maximum distance from the stack pointer is at lower address of
222 // the object -- which is given by offset. For down growing stack
223 // the offset is negative, so we negate the offset to get the distance.
224 FixedOff = -FFI->getObjectOffset(i);
226 // The maximum distance from the start pointer is at the upper
227 // address of the object.
228 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
230 if (FixedOff > Offset) Offset = FixedOff;
233 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
234 // If stack grows down, we need to add size of find the lowest
235 // address of the object.
237 Offset += FFI->getObjectSize(i);
239 unsigned Align = FFI->getObjectAlignment(i);
240 assert(Align <= StackAlignment && "Cannot align stack object to higher "
241 "alignment boundary than the stack itself!");
242 Offset = (Offset+Align-1)/Align*Align; // Adjust to Alignment boundary...
244 if (StackGrowsDown) {
245 FFI->setObjectOffset(i, -Offset); // Set the computed offset
247 FFI->setObjectOffset(i, Offset);
248 Offset += FFI->getObjectSize(i);
252 // Align the final stack pointer offset, but only if there are calls in the
253 // function. This ensures that any calls to subroutines have their stack
254 // frames suitable aligned.
256 Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
258 // Set the final value of the stack pointer...
259 FFI->setStackSize(Offset-TFI.getOffsetOfLocalArea());
263 /// insertPrologEpilogCode - Scan the function for modified caller saved
264 /// registers, insert spill code for these caller saved registers, then add
265 /// prolog and epilog code to the function.
267 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
268 // Add prologue to the function...
269 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
271 // Add epilogue to restore the callee-save registers in each exiting block
272 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
273 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
274 // If last instruction is a return instruction, add an epilogue
275 if (!I->empty() && TII.isReturn(I->back().getOpcode()))
276 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
281 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
282 /// register references and actual offsets.
284 void PEI::replaceFrameIndices(MachineFunction &Fn) {
285 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
287 const TargetMachine &TM = Fn.getTarget();
288 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
289 const MRegisterInfo &MRI = *TM.getRegisterInfo();
291 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
292 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
293 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
294 if (I->getOperand(i).isFrameIndex()) {
295 // If this instruction has a FrameIndex operand, we need to use that
296 // target machine register info object to eliminate it.
297 MRI.eliminateFrameIndex(Fn, I);