5a18b920fc9b3ce29bbe119e3635c1f9847b1535
[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 #include "llvm/Support/Compiler.h"
28 #include <climits>
29 using namespace llvm;
30
31 namespace {
32   struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass {
33     const char *getPassName() const {
34       return "Prolog/Epilog Insertion & Frame Finalization";
35     }
36
37     /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
38     /// frame indexes with appropriate references.
39     ///
40     bool runOnMachineFunction(MachineFunction &Fn) {
41       // Get MachineDebugInfo so that we can track the construction of the
42       // frame.
43       if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) {
44         Fn.getFrameInfo()->setMachineDebugInfo(DI);
45       }
46
47       // Allow the target machine to make some adjustments to the function
48       // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
49       Fn.getTarget().getRegisterInfo()->processFunctionBeforeCalleeSaveScan(Fn);
50
51       // Scan the function for modified callee saved registers and insert spill
52       // code for any callee saved registers that are modified.  Also calculate
53       // the MaxCallFrameSize and HasCalls variables for the function's frame
54       // information and eliminates call frame pseudo instructions.
55       calculateCalleeSavedRegisters(Fn);
56
57       // Add the code to save and restore the callee saved registers
58       saveCalleeSavedRegisters(Fn);
59
60       // Allow the target machine to make final modifications to the function
61       // before the frame layout is finalized.
62       Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
63
64       // Calculate actual frame offsets for all of the abstract stack objects...
65       calculateFrameObjectOffsets(Fn);
66
67       // Add prolog and epilog code to the function.  This function is required
68       // to align the stack frame as necessary for any stack variables or
69       // called functions.  Because of this, calculateCalleeSavedRegisters
70       // must be called before this function in order to set the HasCalls
71       // and MaxCallFrameSize variables.
72       insertPrologEpilogCode(Fn);
73
74       // Replace all MO_FrameIndex operands with physical register references
75       // and actual offsets.
76       //
77       replaceFrameIndices(Fn);
78
79       return true;
80     }
81   
82   private:
83     // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee save
84     // stack frame indexes.
85     unsigned MinCSFrameIndex, MaxCSFrameIndex;
86
87     void calculateCalleeSavedRegisters(MachineFunction &Fn);
88     void saveCalleeSavedRegisters(MachineFunction &Fn);
89     void calculateFrameObjectOffsets(MachineFunction &Fn);
90     void replaceFrameIndices(MachineFunction &Fn);
91     void insertPrologEpilogCode(MachineFunction &Fn);
92   };
93 }
94
95
96 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
97 /// prolog and epilog code, and eliminates abstract frame references.
98 ///
99 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
100
101
102 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
103 /// registers.  Also calculate the MaxCallFrameSize and HasCalls variables for
104 /// the function's frame information and eliminates call frame pseudo
105 /// instructions.
106 ///
107 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
108   const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
109   const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
110
111   // Get the callee saved register list...
112   const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
113
114   // Get the function call frame set-up and tear-down instruction opcode
115   int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
116   int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
117
118   // Early exit for targets which have no callee saved registers and no call
119   // frame setup/destroy pseudo instructions.
120   if ((CSRegs == 0 || CSRegs[0] == 0) &&
121       FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
122     return;
123
124   unsigned MaxCallFrameSize = 0;
125   bool HasCalls = false;
126
127   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
128     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
129       if (I->getOpcode() == FrameSetupOpcode ||
130           I->getOpcode() == FrameDestroyOpcode) {
131         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
132                " instructions should have a single immediate argument!");
133         unsigned Size = I->getOperand(0).getImmedValue();
134         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
135         HasCalls = true;
136         RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
137       } else {
138         ++I;
139       }
140
141   MachineFrameInfo *FFI = Fn.getFrameInfo();
142   FFI->setHasCalls(HasCalls);
143   FFI->setMaxCallFrameSize(MaxCallFrameSize);
144
145   // Now figure out which *callee saved* registers are modified by the current
146   // function, thus needing to be saved and restored in the prolog/epilog.
147   //
148   const bool *PhysRegsUsed = Fn.getUsedPhysregs();
149   const TargetRegisterClass* const *CSRegClasses =
150     RegInfo->getCalleeSaveRegClasses();
151   std::vector<CalleeSavedInfo> CSI;
152   for (unsigned i = 0; CSRegs[i]; ++i) {
153     unsigned Reg = CSRegs[i];
154     if (PhysRegsUsed[Reg]) {
155         // If the reg is modified, save it!
156       CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
157     } else {
158       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
159            *AliasSet; ++AliasSet) {  // Check alias registers too.
160         if (PhysRegsUsed[*AliasSet]) {
161           CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
162           break;
163         }
164       }
165     }
166   }
167
168   if (CSI.empty())
169     return;   // Early exit if no callee saved registers are modified!
170
171   unsigned NumFixedSpillSlots;
172   const std::pair<unsigned,int> *FixedSpillSlots =
173     TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
174
175   // Now that we know which registers need to be saved and restored, allocate
176   // stack slots for them.
177   MinCSFrameIndex = INT_MAX;
178   MaxCSFrameIndex = 0;
179   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
180     unsigned Reg = CSI[i].getReg();
181     const TargetRegisterClass *RC = CSI[i].getRegClass();
182
183     // Check to see if this physreg must be spilled to a particular stack slot
184     // on this target.
185     const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
186     while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
187            FixedSlot->first != Reg)
188       ++FixedSlot;
189
190     int FrameIdx;
191     if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
192       // Nope, just spill it anywhere convenient.
193       unsigned Align = RC->getAlignment();
194       unsigned StackAlign = TFI->getStackAlignment();
195       // We may not be able to sastify the desired alignment specification of
196       // the TargetRegisterClass if the stack alignment is smaller. Use the min.
197       Align = std::min(Align, StackAlign);
198       FrameIdx = FFI->CreateStackObject(RC->getSize(), Align);
199       if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
200       if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
201     } else {
202       // Spill it to the stack where we must.
203       FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
204     }
205     CSI[i].setFrameIdx(FrameIdx);
206   }
207
208   FFI->setCalleeSavedInfo(CSI);
209 }
210
211 /// saveCalleeSavedRegisters -  Insert spill code for any callee saved registers
212 /// that are modified in the function.
213 ///
214 void PEI::saveCalleeSavedRegisters(MachineFunction &Fn) {
215   // Get callee saved register information.
216   MachineFrameInfo *FFI = Fn.getFrameInfo();
217   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
218   
219   // Early exit if no callee saved registers are modified!
220   if (CSI.empty())
221     return;
222
223   const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
224
225   // Now that we have a stack slot for each register to be saved, insert spill
226   // code into the entry block.
227   MachineBasicBlock *MBB = Fn.begin();
228   MachineBasicBlock::iterator I = MBB->begin();
229   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
230     // Insert the spill to the stack frame.
231     RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(), CSI[i].getFrameIdx(),
232                                  CSI[i].getRegClass());
233   }
234
235   // Add code to restore the callee-save registers in each exiting block.
236   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
237   for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
238     // If last instruction is a return instruction, add an epilogue.
239     if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
240       MBB = FI;
241       I = MBB->end(); --I;
242
243       // Skip over all terminator instructions, which are part of the return
244       // sequence.
245       MachineBasicBlock::iterator I2 = I;
246       while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
247         I = I2;
248
249       bool AtStart = I == MBB->begin();
250       MachineBasicBlock::iterator BeforeI = I;
251       if (!AtStart)
252         --BeforeI;
253       
254       // Restore all registers immediately before the return and any terminators
255       // that preceed it.
256       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
257         RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
258                                       CSI[i].getFrameIdx(),
259                                       CSI[i].getRegClass());
260         assert(I != MBB->begin() &&
261                "loadRegFromStackSlot didn't insert any code!");
262         // Insert in reverse order.  loadRegFromStackSlot can insert multiple
263         // instructions.
264         if (AtStart)
265           I = MBB->begin();
266         else {
267           I = BeforeI;
268           ++I;
269         }
270       }
271     }
272 }
273
274
275 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
276 /// abstract stack objects.
277 ///
278 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
279   const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
280
281   bool StackGrowsDown =
282     TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
283
284   // Loop over all of the stack objects, assigning sequential addresses...
285   MachineFrameInfo *FFI = Fn.getFrameInfo();
286
287   unsigned StackAlignment = TFI.getStackAlignment();
288   unsigned MaxAlign = 0;
289
290   // Start at the beginning of the local area.
291   // The Offset is the distance from the stack top in the direction
292   // of stack growth -- so it's always positive.
293   int Offset = TFI.getOffsetOfLocalArea();
294   if (StackGrowsDown)
295     Offset = -Offset;
296   assert(Offset >= 0
297          && "Local area offset should be in direction of stack growth");
298
299   // If there are fixed sized objects that are preallocated in the local area,
300   // non-fixed objects can't be allocated right at the start of local area.
301   // We currently don't support filling in holes in between fixed sized objects,
302   // so we adjust 'Offset' to point to the end of last fixed sized
303   // preallocated object.
304   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
305     int FixedOff;
306     if (StackGrowsDown) {
307       // The maximum distance from the stack pointer is at lower address of
308       // the object -- which is given by offset. For down growing stack
309       // the offset is negative, so we negate the offset to get the distance.
310       FixedOff = -FFI->getObjectOffset(i);
311     } else {
312       // The maximum distance from the start pointer is at the upper
313       // address of the object.
314       FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
315     }
316     if (FixedOff > Offset) Offset = FixedOff;
317   }
318
319   // First assign frame offsets to stack objects that are used to spill
320   // callee save registers.
321   if (StackGrowsDown) {
322     for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
323       if (i < MinCSFrameIndex || i > MaxCSFrameIndex)
324         continue;
325
326       // If stack grows down, we need to add size of find the lowest
327       // address of the object.
328       Offset += FFI->getObjectSize(i);
329
330       unsigned Align = FFI->getObjectAlignment(i);
331       // If the alignment of this object is greater than that of the stack, then
332       // increase the stack alignment to match.
333       MaxAlign = std::max(MaxAlign, Align);
334       // Adjust to alignment boundary
335       Offset = (Offset+Align-1)/Align*Align;
336
337       FFI->setObjectOffset(i, -Offset);        // Set the computed offset
338     }
339   } else {
340     for (int i = FFI->getObjectIndexEnd()-1; i >= 0; --i) {
341       if ((unsigned)i < MinCSFrameIndex || (unsigned)i > MaxCSFrameIndex)
342         continue;
343
344       unsigned Align = FFI->getObjectAlignment(i);
345       // If the alignment of this object is greater than that of the stack, then
346       // increase the stack alignment to match.
347       MaxAlign = std::max(MaxAlign, Align);
348       // Adjust to alignment boundary
349       Offset = (Offset+Align-1)/Align*Align;
350
351       FFI->setObjectOffset(i, Offset);
352       Offset += FFI->getObjectSize(i);
353     }
354   }
355
356   // Then assign frame offsets to stack objects that are not used to spill
357   // callee save registers.
358   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
359     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
360       continue;
361
362     // If stack grows down, we need to add size of find the lowest
363     // address of the object.
364     if (StackGrowsDown)
365       Offset += FFI->getObjectSize(i);
366
367     unsigned Align = FFI->getObjectAlignment(i);
368     // If the alignment of this object is greater than that of the stack, then
369     // increase the stack alignment to match.
370     MaxAlign = std::max(MaxAlign, Align);
371     // Adjust to alignment boundary
372     Offset = (Offset+Align-1)/Align*Align;
373
374     if (StackGrowsDown) {
375       FFI->setObjectOffset(i, -Offset);        // Set the computed offset
376     } else {
377       FFI->setObjectOffset(i, Offset);
378       Offset += FFI->getObjectSize(i);
379     }
380   }
381
382
383   // Align the final stack pointer offset, but only if there are calls in the
384   // function.  This ensures that any calls to subroutines have their stack
385   // frames suitable aligned.
386   if (FFI->hasCalls())
387     Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
388
389   // Set the final value of the stack pointer...
390   FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
391
392   // Remember the required stack alignment in case targets need it to perform
393   // dynamic stack alignment.
394   assert(FFI->getMaxAlignment() == MaxAlign &&
395          "Stack alignment calculation broken!");
396 }
397
398
399 /// insertPrologEpilogCode - Scan the function for modified callee saved
400 /// registers, insert spill code for these callee saved registers, then add
401 /// prolog and epilog code to the function.
402 ///
403 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
404   // Add prologue to the function...
405   Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
406
407   // Add epilogue to restore the callee-save registers in each exiting block
408   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
409   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
410     // If last instruction is a return instruction, add an epilogue
411     if (!I->empty() && TII.isReturn(I->back().getOpcode()))
412       Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
413   }
414 }
415
416
417 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
418 /// register references and actual offsets.
419 ///
420 void PEI::replaceFrameIndices(MachineFunction &Fn) {
421   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
422
423   const TargetMachine &TM = Fn.getTarget();
424   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
425   const MRegisterInfo &MRI = *TM.getRegisterInfo();
426
427   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
428     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
429       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
430         if (I->getOperand(i).isFrameIndex()) {
431           // If this instruction has a FrameIndex operand, we need to use that
432           // target machine register info object to eliminate it.
433           MRI.eliminateFrameIndex(I);
434           break;
435         }
436 }