PrologEpilogInserter.cpp revision 5709998993cade99e4aeda1c9d44a1bdf54aa720
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"
27using namespace llvm;
28
29namespace {
30  struct PEI : public MachineFunctionPass {
31    const char *getPassName() const {
32      return "Prolog/Epilog Insertion & Frame Finalization";
33    }
34
35    /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
36    /// frame indexes with appropriate references.
37    ///
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      calculateCallerSavedRegisters(Fn);
44
45      // Add the code to save and restore the caller saved registers
46      saveCallerSavedRegisters(Fn);
47
48      // Allow the target machine to make final modifications to the function
49      // before the frame layout is finalized.
50      Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
51
52      // Calculate actual frame offsets for all of the abstract stack objects...
53      calculateFrameObjectOffsets(Fn);
54
55      // Add prolog and epilog code to the function.  This function is required
56      // to align the stack frame as necessary for any stack variables or
57      // called functions.  Because of this, calculateCallerSavedRegisters
58      // must be called before this function in order to set the HasCalls
59      // and MaxCallFrameSize variables.
60      insertPrologEpilogCode(Fn);
61
62      // Replace all MO_FrameIndex operands with physical register references
63      // and actual offsets.
64      //
65      replaceFrameIndices(Fn);
66
67      RegsToSave.clear();
68      StackSlots.clear();
69      return true;
70    }
71
72  private:
73    std::vector<unsigned> RegsToSave;
74    std::vector<int> StackSlots;
75
76    void calculateCallerSavedRegisters(MachineFunction &Fn);
77    void saveCallerSavedRegisters(MachineFunction &Fn);
78    void calculateFrameObjectOffsets(MachineFunction &Fn);
79    void replaceFrameIndices(MachineFunction &Fn);
80    void insertPrologEpilogCode(MachineFunction &Fn);
81  };
82}
83
84
85/// createPrologEpilogCodeInserter - This function returns a pass that inserts
86/// prolog and epilog code, and eliminates abstract frame references.
87///
88FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
89
90
91/// calculateCallerSavedRegisters - Scan the function for modified caller saved
92/// registers.  Also calculate the MaxCallFrameSize and HasCalls variables for
93/// the function's frame information and eliminates call frame pseudo
94/// instructions.
95///
96void PEI::calculateCallerSavedRegisters(MachineFunction &Fn) {
97  const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
98  const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
99
100  // Get the callee saved register list...
101  const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
102
103  // Get the function call frame set-up and tear-down instruction opcode
104  int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
105  int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
106
107  // Early exit for targets which have no callee saved registers and no call
108  // frame setup/destroy pseudo instructions.
109  if ((CSRegs == 0 || CSRegs[0] == 0) &&
110      FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
111    return;
112
113  // This bitset contains an entry for each physical register for the target...
114  std::vector<bool> ModifiedRegs(RegInfo->getNumRegs());
115  unsigned MaxCallFrameSize = 0;
116  bool HasCalls = false;
117
118  for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
119    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
120      if (I->getOpcode() == FrameSetupOpcode ||
121          I->getOpcode() == FrameDestroyOpcode) {
122        assert(I->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
123               " instructions should have a single immediate argument!");
124        unsigned Size = I->getOperand(0).getImmedValue();
125        if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
126        HasCalls = true;
127        RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
128      } else {
129        for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
130          MachineOperand &MO = I->getOperand(i);
131          if (MO.isRegister() && MO.isDef()) {
132            assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
133                   "Register allocation must be performed!");
134            ModifiedRegs[MO.getReg()] = true;         // Register is modified
135          }
136        }
137        ++I;
138      }
139
140  MachineFrameInfo *FFI = Fn.getFrameInfo();
141  FFI->setHasCalls(HasCalls);
142  FFI->setMaxCallFrameSize(MaxCallFrameSize);
143
144  // Now figure out which *callee saved* registers are modified by the current
145  // function, thus needing to be saved and restored in the prolog/epilog.
146  //
147  for (unsigned i = 0; CSRegs[i]; ++i) {
148    unsigned Reg = CSRegs[i];
149    if (ModifiedRegs[Reg]) {
150      RegsToSave.push_back(Reg);  // If modified register...
151    } else {
152      for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
153           *AliasSet; ++AliasSet) {  // Check alias registers too...
154        if (ModifiedRegs[*AliasSet]) {
155          RegsToSave.push_back(Reg);
156          break;
157        }
158      }
159    }
160  }
161
162  if (RegsToSave.empty())
163    return;   // Early exit if no caller saved registers are modified!
164
165  unsigned NumFixedSpillSlots;
166  const std::pair<unsigned,int> *FixedSpillSlots =
167    TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
168
169  // Now that we know which registers need to be saved and restored, allocate
170  // stack slots for them.
171  for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
172    unsigned Reg = RegsToSave[i];
173
174    // Check to see if this physreg must be spilled to a particular stack slot
175    // on this target.
176    const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
177    while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
178           FixedSlot->first != Reg)
179      ++FixedSlot;
180
181    int FrameIdx;
182    if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
183      // Nope, just spill it anywhere convenient.
184      FrameIdx = FFI->CreateStackObject(RegInfo->getSpillSize(Reg)/8,
185                                        RegInfo->getSpillAlignment(Reg)/8);
186    } else {
187      // Spill it to the stack where we must.
188      FrameIdx = FFI->CreateFixedObject(RegInfo->getSpillSize(Reg)/8,
189                                        FixedSlot->second);
190    }
191    StackSlots.push_back(FrameIdx);
192  }
193}
194
195/// saveCallerSavedRegisters -  Insert spill code for any caller saved registers
196/// that are modified in the function.
197///
198void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
199  // Early exit if no caller saved registers are modified!
200  if (RegsToSave.empty())
201    return;
202
203  const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
204
205  // Now that we have a stack slot for each register to be saved, insert spill
206  // code into the entry block...
207  MachineBasicBlock *MBB = Fn.begin();
208  MachineBasicBlock::iterator I = MBB->begin();
209  for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
210    // Insert the spill to the stack frame.
211    RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);
212  }
213
214  // Add code to restore the callee-save registers in each exiting block.
215  const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
216  for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
217    // If last instruction is a return instruction, add an epilogue
218    if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
219      MBB = FI;
220      I = MBB->end(); --I;
221
222      for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
223        RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i]);
224        --I;  // Insert in reverse order
225      }
226    }
227  }
228}
229
230
231/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
232/// abstract stack objects...
233///
234void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
235  const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
236
237  bool StackGrowsDown =
238    TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
239
240  // Loop over all of the stack objects, assigning sequential addresses...
241  MachineFrameInfo *FFI = Fn.getFrameInfo();
242
243  unsigned StackAlignment = TFI.getStackAlignment();
244
245  // Start at the beginning of the local area.
246  // The Offset is the distance from the stack top in the direction
247  // of stack growth -- so it's always positive.
248  int Offset = TFI.getOffsetOfLocalArea();
249  if (StackGrowsDown)
250    Offset = -Offset;
251  assert(Offset >= 0
252         && "Local area offset should be in direction of stack growth");
253
254  // If there are fixed sized objects that are preallocated in the local area,
255  // non-fixed objects can't be allocated right at the start of local area.
256  // We currently don't support filling in holes in between fixed sized objects,
257  // so we adjust 'Offset' to point to the end of last fixed sized
258  // preallocated object.
259  for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
260    int FixedOff;
261    if (StackGrowsDown) {
262      // The maximum distance from the stack pointer is at lower address of
263      // the object -- which is given by offset. For down growing stack
264      // the offset is negative, so we negate the offset to get the distance.
265      FixedOff = -FFI->getObjectOffset(i);
266    } else {
267      // The maximum distance from the start pointer is at the upper
268      // address of the object.
269      FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
270    }
271    if (FixedOff > Offset) Offset = FixedOff;
272  }
273
274  for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
275    // If stack grows down, we need to add size of find the lowest
276    // address of the object.
277    if (StackGrowsDown)
278      Offset += FFI->getObjectSize(i);
279
280    unsigned Align = FFI->getObjectAlignment(i);
281    assert(Align <= StackAlignment && "Cannot align stack object to higher "
282           "alignment boundary than the stack itself!");
283    Offset = (Offset+Align-1)/Align*Align;   // Adjust to Alignment boundary...
284
285    if (StackGrowsDown) {
286      FFI->setObjectOffset(i, -Offset);        // Set the computed offset
287    } else {
288      FFI->setObjectOffset(i, Offset);
289      Offset += FFI->getObjectSize(i);
290    }
291  }
292
293  // Align the final stack pointer offset, but only if there are calls in the
294  // function.  This ensures that any calls to subroutines have their stack
295  // frames suitable aligned.
296  if (FFI->hasCalls())
297    Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
298
299  // Set the final value of the stack pointer...
300  FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
301}
302
303
304/// insertPrologEpilogCode - Scan the function for modified caller saved
305/// registers, insert spill code for these caller saved registers, then add
306/// prolog and epilog code to the function.
307///
308void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
309  // Add prologue to the function...
310  Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
311
312  // Add epilogue to restore the callee-save registers in each exiting block
313  const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
314  for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
315    // If last instruction is a return instruction, add an epilogue
316    if (!I->empty() && TII.isReturn(I->back().getOpcode()))
317      Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
318  }
319}
320
321
322/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
323/// register references and actual offsets.
324///
325void PEI::replaceFrameIndices(MachineFunction &Fn) {
326  if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
327
328  const TargetMachine &TM = Fn.getTarget();
329  assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
330  const MRegisterInfo &MRI = *TM.getRegisterInfo();
331
332  for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
333    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
334      for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
335        if (I->getOperand(i).isFrameIndex()) {
336          // If this instruction has a FrameIndex operand, we need to use that
337          // target machine register info object to eliminate it.
338          MRI.eliminateFrameIndex(I);
339          break;
340        }
341}
342