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"
29 struct PEI : public MachineFunctionPass {
30 const char *getPassName() const {
31 return "Prolog/Epilog Insertion & Frame Finalization";
34 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
35 /// frame indexes with appropriate references.
37 bool runOnMachineFunction(MachineFunction &Fn) {
38 // Scan the function for modified caller saved registers and insert spill
39 // code for any caller saved registers that are modified. Also calculate
40 // the MaxCallFrameSize and HasCalls variables for the function's frame
41 // information and eliminates call frame pseudo instructions.
42 saveCallerSavedRegisters(Fn);
44 // Allow the target machine to make final modifications to the function
45 // before the frame layout is finalized.
46 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
48 // Calculate actual frame offsets for all of the abstract stack objects...
49 calculateFrameObjectOffsets(Fn);
51 // Add prolog and epilog code to the function.
52 insertPrologEpilogCode(Fn);
54 // Replace all MO_FrameIndex operands with physical register references
55 // and actual offsets.
57 replaceFrameIndices(Fn);
62 void saveCallerSavedRegisters(MachineFunction &Fn);
63 void calculateFrameObjectOffsets(MachineFunction &Fn);
64 void replaceFrameIndices(MachineFunction &Fn);
65 void insertPrologEpilogCode(MachineFunction &Fn);
69 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
70 /// prolog and epilog code, and eliminates abstract frame references.
72 FunctionPass *createPrologEpilogCodeInserter() { return new PEI(); }
75 /// saveCallerSavedRegisters - Scan the function for modified caller saved
76 /// registers and insert spill code for any caller saved registers that are
77 /// modified. Also calculate the MaxCallFrameSize and HasCalls variables for
78 /// the function's frame information and eliminates call frame pseudo
81 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
82 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
83 const TargetFrameInfo &FrameInfo = Fn.getTarget().getFrameInfo();
85 // Get the callee saved register list...
86 const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
88 // Get the function call frame set-up and tear-down instruction opcode
89 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
90 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
92 // Early exit for targets which have no callee saved registers and no call
93 // frame setup/destroy pseudo instructions.
94 if ((CSRegs == 0 || CSRegs[0] == 0) &&
95 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
98 // This bitset contains an entry for each physical register for the target...
99 std::vector<bool> ModifiedRegs(MRegisterInfo::FirstVirtualRegister);
100 unsigned MaxCallFrameSize = 0;
101 bool HasCalls = false;
103 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
104 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
105 if ((*I)->getOpcode() == FrameSetupOpcode ||
106 (*I)->getOpcode() == FrameDestroyOpcode) {
107 assert((*I)->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
108 " instructions should have a single immediate argument!");
109 unsigned Size = (*I)->getOperand(0).getImmedValue();
110 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
112 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I);
114 for (unsigned i = 0, e = (*I)->getNumOperands(); i != e; ++i) {
115 MachineOperand &MO = (*I)->getOperand(i);
116 assert(!MO.isVirtualRegister() &&
117 "Register allocation must be performed!");
118 if (MO.isPhysicalRegister() &&
119 (MO.opIsDefOnly() || MO.opIsDefAndUse()))
120 ModifiedRegs[MO.getReg()] = true; // Register is modified
125 MachineFrameInfo *FFI = Fn.getFrameInfo();
126 FFI->setHasCalls(HasCalls);
127 FFI->setMaxCallFrameSize(MaxCallFrameSize);
129 // Now figure out which *callee saved* registers are modified by the current
130 // function, thus needing to be saved and restored in the prolog/epilog.
132 std::vector<unsigned> RegsToSave;
133 for (unsigned i = 0; CSRegs[i]; ++i) {
134 unsigned Reg = CSRegs[i];
135 if (ModifiedRegs[Reg]) {
136 RegsToSave.push_back(Reg); // If modified register...
138 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
139 *AliasSet; ++AliasSet) { // Check alias registers too...
140 if (ModifiedRegs[*AliasSet]) {
141 RegsToSave.push_back(Reg);
148 if (RegsToSave.empty())
149 return; // Early exit if no caller saved registers are modified!
151 // Now that we know which registers need to be saved and restored, allocate
152 // stack slots for them.
153 std::vector<int> StackSlots;
154 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
155 int FrameIdx = FFI->CreateStackObject(RegInfo->getRegClass(RegsToSave[i]));
156 StackSlots.push_back(FrameIdx);
159 // Now that we have a stack slot for each register to be saved, insert spill
160 // code into the entry block...
161 MachineBasicBlock *MBB = Fn.begin();
162 MachineBasicBlock::iterator I = MBB->begin();
163 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
164 const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
166 // Insert the spill to the stack frame...
167 RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i], RC);
170 // Add code to restore the callee-save registers in each exiting block.
171 const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
172 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
173 // If last instruction is a return instruction, add an epilogue
174 if (!FI->empty() && TII.isReturn(FI->back()->getOpcode())) {
175 MBB = FI; I = MBB->end()-1;
177 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
178 const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
179 RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i], RC);
180 --I; // Insert in reverse order
187 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
188 /// abstract stack objects...
190 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
191 const TargetFrameInfo &TFI = Fn.getTarget().getFrameInfo();
193 bool StackGrowsDown =
194 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
195 assert(StackGrowsDown && "Only tested on stack down growing targets!");
197 // Loop over all of the stack objects, assigning sequential addresses...
198 MachineFrameInfo *FFI = Fn.getFrameInfo();
200 unsigned StackAlignment = TFI.getStackAlignment();
202 // Start at the beginning of the local area...
203 int Offset = TFI.getOffsetOfLocalArea();
204 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
205 Offset += FFI->getObjectSize(i); // Allocate Size bytes...
207 unsigned Align = FFI->getObjectAlignment(i);
208 assert(Align <= StackAlignment && "Cannot align stack object to higher "
209 "alignment boundary than the stack itself!");
210 Offset = (Offset+Align-1)/Align*Align; // Adjust to Alignment boundary...
212 FFI->setObjectOffset(i, -Offset); // Set the computed offset
215 // Align the final stack pointer offset...
216 Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
218 // Set the final value of the stack pointer...
219 FFI->setStackSize(Offset-TFI.getOffsetOfLocalArea());
223 /// insertPrologEpilogCode - Scan the function for modified caller saved
224 /// registers, insert spill code for these caller saved registers, then add
225 /// prolog and epilog code to the function.
227 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
228 // Add prologue to the function...
229 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
231 // Add epilogue to restore the callee-save registers in each exiting block
232 const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
233 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
234 // If last instruction is a return instruction, add an epilogue
235 if (!I->empty() && TII.isReturn(I->back()->getOpcode()))
236 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
241 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
242 /// register references and actual offsets.
244 void PEI::replaceFrameIndices(MachineFunction &Fn) {
245 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
247 const TargetMachine &TM = Fn.getTarget();
248 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
249 const MRegisterInfo &MRI = *TM.getRegisterInfo();
251 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
252 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
253 for (unsigned i = 0, e = (*I)->getNumOperands(); i != e; ++i)
254 if ((*I)->getOperand(i).isFrameIndex()) {
255 // If this instruction has a FrameIndex operand, we need to use that
256 // target machine register info object to eliminate it.
257 MRI.eliminateFrameIndex(Fn, I);