There is no reason to align the stack pointer if there are no callees of this function!
[oota-llvm.git] / lib / CodeGen / PrologEpilogInserter.cpp
1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
12 // function.
13 //
14 // This pass must be run after register allocation.  After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
16 //
17 //===----------------------------------------------------------------------===//
18
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
28 namespace llvm {
29
30 namespace {
31   struct PEI : public MachineFunctionPass {
32     const char *getPassName() const {
33       return "Prolog/Epilog Insertion & Frame Finalization";
34     }
35
36     /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
37     /// frame indexes with appropriate references.
38     ///
39     bool runOnMachineFunction(MachineFunction &Fn) {
40       // Scan the function for modified caller saved registers and insert spill
41       // code for any caller saved registers that are modified.  Also calculate
42       // the MaxCallFrameSize and HasCalls variables for the function's frame
43       // information and eliminates call frame pseudo instructions.
44       saveCallerSavedRegisters(Fn);
45
46       // Allow the target machine to make final modifications to the function
47       // before the frame layout is finalized.
48       Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
49
50       // Calculate actual frame offsets for all of the abstract stack objects...
51       calculateFrameObjectOffsets(Fn);
52
53       // Add prolog and epilog code to the function.
54       insertPrologEpilogCode(Fn);
55
56       // Replace all MO_FrameIndex operands with physical register references
57       // and actual offsets.
58       //
59       replaceFrameIndices(Fn);
60       return true;
61     }
62
63   private:
64     void saveCallerSavedRegisters(MachineFunction &Fn);
65     void calculateFrameObjectOffsets(MachineFunction &Fn);
66     void replaceFrameIndices(MachineFunction &Fn);
67     void insertPrologEpilogCode(MachineFunction &Fn);
68   };
69 }
70
71
72 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
73 /// prolog and epilog code, and eliminates abstract frame references.
74 ///
75 FunctionPass *createPrologEpilogCodeInserter() { return new PEI(); }
76
77
78 /// saveCallerSavedRegisters - Scan the function for modified caller saved
79 /// registers and insert spill code for any caller saved registers that are
80 /// modified.  Also calculate the MaxCallFrameSize and HasCalls variables for
81 /// the function's frame information and eliminates call frame pseudo
82 /// instructions.
83 ///
84 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
85   const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
86   const TargetFrameInfo &FrameInfo = Fn.getTarget().getFrameInfo();
87
88   // Get the callee saved register list...
89   const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
90
91   // Get the function call frame set-up and tear-down instruction opcode
92   int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
93   int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
94
95   // Early exit for targets which have no callee saved registers and no call
96   // frame setup/destroy pseudo instructions.
97   if ((CSRegs == 0 || CSRegs[0] == 0) &&
98       FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
99     return;
100
101   // This bitset contains an entry for each physical register for the target...
102   std::vector<bool> ModifiedRegs(MRegisterInfo::FirstVirtualRegister);
103   unsigned MaxCallFrameSize = 0;
104   bool HasCalls = false;
105
106   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
107     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
108       if (I->getOpcode() == FrameSetupOpcode ||
109           I->getOpcode() == FrameDestroyOpcode) {
110         assert(I->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
111                " instructions should have a single immediate argument!");
112         unsigned Size = I->getOperand(0).getImmedValue();
113         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
114         HasCalls = true;
115         RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
116       } else {
117         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
118           MachineOperand &MO = I->getOperand(i);
119           if (MO.isRegister() && MO.isDef()) {
120             assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
121                    "Register allocation must be performed!");
122             ModifiedRegs[MO.getReg()] = true;         // Register is modified
123           }
124         }
125         ++I;
126       }
127
128   MachineFrameInfo *FFI = Fn.getFrameInfo();
129   FFI->setHasCalls(HasCalls);
130   FFI->setMaxCallFrameSize(MaxCallFrameSize);
131
132   // Now figure out which *callee saved* registers are modified by the current
133   // function, thus needing to be saved and restored in the prolog/epilog.
134   //
135   std::vector<unsigned> RegsToSave;
136   for (unsigned i = 0; CSRegs[i]; ++i) {
137     unsigned Reg = CSRegs[i];
138     if (ModifiedRegs[Reg]) {
139       RegsToSave.push_back(Reg);  // If modified register...
140     } else {
141       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
142            *AliasSet; ++AliasSet) {  // Check alias registers too...
143         if (ModifiedRegs[*AliasSet]) {
144           RegsToSave.push_back(Reg);
145           break;
146         }
147       }
148     }
149   }
150
151   if (RegsToSave.empty())
152     return;   // Early exit if no caller saved registers are modified!
153
154   // Now that we know which registers need to be saved and restored, allocate
155   // stack slots for them.
156   std::vector<int> StackSlots;
157   for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
158     int FrameIdx = FFI->CreateStackObject(RegInfo->getRegClass(RegsToSave[i]));
159     StackSlots.push_back(FrameIdx);
160   }
161
162   // Now that we have a stack slot for each register to be saved, insert spill
163   // code into the entry block...
164   MachineBasicBlock *MBB = Fn.begin();
165   MachineBasicBlock::iterator I = MBB->begin();
166   for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
167     const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
168
169     // Insert the spill to the stack frame...
170     RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i], RC);
171   }
172
173   // Add code to restore the callee-save registers in each exiting block.
174   const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
175   for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
176     // If last instruction is a return instruction, add an epilogue
177     if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
178       MBB = FI;
179       I = MBB->end(); --I;
180
181       for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
182         const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
183         RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i], RC);
184         --I;  // Insert in reverse order
185       }
186     }
187   }
188 }
189
190
191 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
192 /// abstract stack objects...
193 ///
194 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
195   const TargetFrameInfo &TFI = Fn.getTarget().getFrameInfo();
196   
197   bool StackGrowsDown =
198     TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
199   assert(StackGrowsDown && "Only tested on stack down growing targets!");
200  
201   // Loop over all of the stack objects, assigning sequential addresses...
202   MachineFrameInfo *FFI = Fn.getFrameInfo();
203
204   unsigned StackAlignment = TFI.getStackAlignment();
205
206   // Start at the beginning of the local area...
207   int Offset = TFI.getOffsetOfLocalArea();
208   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
209     Offset += FFI->getObjectSize(i);         // Allocate Size bytes...
210
211     unsigned Align = FFI->getObjectAlignment(i);
212     assert(Align <= StackAlignment && "Cannot align stack object to higher "
213            "alignment boundary than the stack itself!");
214     Offset = (Offset+Align-1)/Align*Align;   // Adjust to Alignment boundary...
215     
216     FFI->setObjectOffset(i, -Offset);        // Set the computed offset
217   }
218
219   // Align the final stack pointer offset, but only if there are calls in the
220   // function.  This ensures that any calls to subroutines have their stack
221   // frames suitable aligned.
222   if (FFI->hasCalls())
223     Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
224
225   // Set the final value of the stack pointer...
226   FFI->setStackSize(Offset-TFI.getOffsetOfLocalArea());
227 }
228
229
230 /// insertPrologEpilogCode - Scan the function for modified caller saved
231 /// registers, insert spill code for these caller saved registers, then add
232 /// prolog and epilog code to the function.
233 ///
234 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
235   // Add prologue to the function...
236   Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
237
238   // Add epilogue to restore the callee-save registers in each exiting block
239   const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
240   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
241     // If last instruction is a return instruction, add an epilogue
242     if (!I->empty() && TII.isReturn(I->back().getOpcode()))
243       Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
244   }
245 }
246
247
248 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
249 /// register references and actual offsets.
250 ///
251 void PEI::replaceFrameIndices(MachineFunction &Fn) {
252   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
253
254   const TargetMachine &TM = Fn.getTarget();
255   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
256   const MRegisterInfo &MRI = *TM.getRegisterInfo();
257
258   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
259     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
260       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
261         if (I->getOperand(i).isFrameIndex()) {
262           // If this instruction has a FrameIndex operand, we need to use that
263           // target machine register info object to eliminate it.
264           MRI.eliminateFrameIndex(Fn, I);
265           break;
266         }
267 }
268
269 } // End llvm namespace