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