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/CodeGen/RegisterScavenging.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetFrameInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Support/Compiler.h"
33 struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass {
34 const char *getPassName() const {
35 return "Prolog/Epilog Insertion & Frame Finalization";
38 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
39 /// frame indexes with appropriate references.
41 bool runOnMachineFunction(MachineFunction &Fn) {
42 const MRegisterInfo *MRI = Fn.getTarget().getRegisterInfo();
43 RS = MRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
45 // Get MachineModuleInfo so that we can track the construction of the
47 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
48 Fn.getFrameInfo()->setMachineModuleInfo(MMI);
51 // Allow the target machine to make some adjustments to the function
52 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
53 MRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
55 // Scan the function for modified callee saved registers and insert spill
56 // code for any callee saved registers that are modified. Also calculate
57 // the MaxCallFrameSize and HasCalls variables for the function's frame
58 // information and eliminates call frame pseudo instructions.
59 calculateCalleeSavedRegisters(Fn);
61 // Add the code to save and restore the callee saved registers
62 saveCalleeSavedRegisters(Fn);
64 // Allow the target machine to make final modifications to the function
65 // before the frame layout is finalized.
66 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
68 // Calculate actual frame offsets for all of the abstract stack objects...
69 calculateFrameObjectOffsets(Fn);
71 // Add prolog and epilog code to the function. This function is required
72 // to align the stack frame as necessary for any stack variables or
73 // called functions. Because of this, calculateCalleeSavedRegisters
74 // must be called before this function in order to set the HasCalls
75 // and MaxCallFrameSize variables.
76 insertPrologEpilogCode(Fn);
78 // Replace all MO_FrameIndex operands with physical register references
79 // and actual offsets.
81 replaceFrameIndices(Fn);
90 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
91 // stack frame indexes.
92 unsigned MinCSFrameIndex, MaxCSFrameIndex;
94 void calculateCalleeSavedRegisters(MachineFunction &Fn);
95 void saveCalleeSavedRegisters(MachineFunction &Fn);
96 void calculateFrameObjectOffsets(MachineFunction &Fn);
97 void replaceFrameIndices(MachineFunction &Fn);
98 void insertPrologEpilogCode(MachineFunction &Fn);
103 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
104 /// prolog and epilog code, and eliminates abstract frame references.
106 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
109 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
110 /// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
111 /// the function's frame information and eliminates call frame pseudo
114 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
115 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
116 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
118 // Get the callee saved register list...
119 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
121 // Get the function call frame set-up and tear-down instruction opcode
122 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
123 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
125 // These are used to keep track the callee-save area. Initialize them.
126 MinCSFrameIndex = INT_MAX;
129 // Early exit for targets which have no callee saved registers and no call
130 // frame setup/destroy pseudo instructions.
131 if ((CSRegs == 0 || CSRegs[0] == 0) &&
132 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
135 unsigned MaxCallFrameSize = 0;
136 bool HasCalls = false;
138 std::vector<MachineBasicBlock::iterator> FrameSDOps;
139 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
140 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
141 if (I->getOpcode() == FrameSetupOpcode ||
142 I->getOpcode() == FrameDestroyOpcode) {
143 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
144 " instructions should have a single immediate argument!");
145 unsigned Size = I->getOperand(0).getImmedValue();
146 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
148 FrameSDOps.push_back(I);
151 MachineFrameInfo *FFI = Fn.getFrameInfo();
152 FFI->setHasCalls(HasCalls);
153 FFI->setMaxCallFrameSize(MaxCallFrameSize);
154 for (unsigned i = 0, e = FrameSDOps.size(); i != e; ++i) {
155 MachineBasicBlock::iterator I = FrameSDOps[i];
156 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
159 // Now figure out which *callee saved* registers are modified by the current
160 // function, thus needing to be saved and restored in the prolog/epilog.
162 const TargetRegisterClass* const *CSRegClasses =
163 RegInfo->getCalleeSavedRegClasses();
164 std::vector<CalleeSavedInfo> CSI;
165 for (unsigned i = 0; CSRegs[i]; ++i) {
166 unsigned Reg = CSRegs[i];
167 if (Fn.isPhysRegUsed(Reg)) {
168 // If the reg is modified, save it!
169 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
171 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
172 *AliasSet; ++AliasSet) { // Check alias registers too.
173 if (Fn.isPhysRegUsed(*AliasSet)) {
174 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
182 return; // Early exit if no callee saved registers are modified!
184 unsigned NumFixedSpillSlots;
185 const std::pair<unsigned,int> *FixedSpillSlots =
186 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
188 // Now that we know which registers need to be saved and restored, allocate
189 // stack slots for them.
190 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
191 unsigned Reg = CSI[i].getReg();
192 const TargetRegisterClass *RC = CSI[i].getRegClass();
194 // Check to see if this physreg must be spilled to a particular stack slot
196 const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
197 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
198 FixedSlot->first != Reg)
202 if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
203 // Nope, just spill it anywhere convenient.
204 unsigned Align = RC->getAlignment();
205 unsigned StackAlign = TFI->getStackAlignment();
206 // We may not be able to sastify the desired alignment specification of
207 // the TargetRegisterClass if the stack alignment is smaller. Use the min.
208 Align = std::min(Align, StackAlign);
209 FrameIdx = FFI->CreateStackObject(RC->getSize(), Align);
210 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
211 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
213 // Spill it to the stack where we must.
214 FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
216 CSI[i].setFrameIdx(FrameIdx);
219 FFI->setCalleeSavedInfo(CSI);
222 /// saveCalleeSavedRegisters - Insert spill code for any callee saved registers
223 /// that are modified in the function.
225 void PEI::saveCalleeSavedRegisters(MachineFunction &Fn) {
226 // Get callee saved register information.
227 MachineFrameInfo *FFI = Fn.getFrameInfo();
228 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
230 // Early exit if no callee saved registers are modified!
234 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
236 // Now that we have a stack slot for each register to be saved, insert spill
237 // code into the entry block.
238 MachineBasicBlock *MBB = Fn.begin();
239 MachineBasicBlock::iterator I = MBB->begin();
240 if (!RegInfo->spillCalleeSavedRegisters(*MBB, I, CSI)) {
241 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
242 // Add the callee-saved register as live-in. It's killed at the spill.
243 MBB->addLiveIn(CSI[i].getReg());
245 // Insert the spill to the stack frame.
246 RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(),
247 CSI[i].getFrameIdx(), CSI[i].getRegClass());
251 // Add code to restore the callee-save registers in each exiting block.
252 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
253 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
254 // If last instruction is a return instruction, add an epilogue.
255 if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
259 // Skip over all terminator instructions, which are part of the return
261 MachineBasicBlock::iterator I2 = I;
262 while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
265 bool AtStart = I == MBB->begin();
266 MachineBasicBlock::iterator BeforeI = I;
270 // Restore all registers immediately before the return and any terminators
272 if (!RegInfo->restoreCalleeSavedRegisters(*MBB, I, CSI)) {
273 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
274 RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
275 CSI[i].getFrameIdx(),
276 CSI[i].getRegClass());
277 assert(I != MBB->begin() &&
278 "loadRegFromStackSlot didn't insert any code!");
279 // Insert in reverse order. loadRegFromStackSlot can insert multiple
293 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
294 /// abstract stack objects.
296 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
297 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
299 bool StackGrowsDown =
300 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
302 // Loop over all of the stack objects, assigning sequential addresses...
303 MachineFrameInfo *FFI = Fn.getFrameInfo();
305 unsigned MaxAlign = 0;
307 // Start at the beginning of the local area.
308 // The Offset is the distance from the stack top in the direction
309 // of stack growth -- so it's always positive.
310 int64_t Offset = TFI.getOffsetOfLocalArea();
314 && "Local area offset should be in direction of stack growth");
316 // If there are fixed sized objects that are preallocated in the local area,
317 // non-fixed objects can't be allocated right at the start of local area.
318 // We currently don't support filling in holes in between fixed sized objects,
319 // so we adjust 'Offset' to point to the end of last fixed sized
320 // preallocated object.
321 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
323 if (StackGrowsDown) {
324 // The maximum distance from the stack pointer is at lower address of
325 // the object -- which is given by offset. For down growing stack
326 // the offset is negative, so we negate the offset to get the distance.
327 FixedOff = -FFI->getObjectOffset(i);
329 // The maximum distance from the start pointer is at the upper
330 // address of the object.
331 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
333 if (FixedOff > Offset) Offset = FixedOff;
336 // First assign frame offsets to stack objects that are used to spill
337 // callee saved registers.
338 if (StackGrowsDown) {
339 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
340 // If stack grows down, we need to add size of find the lowest
341 // address of the object.
342 Offset += FFI->getObjectSize(i);
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;
351 FFI->setObjectOffset(i, -Offset); // Set the computed offset
354 for (unsigned i = MaxCSFrameIndex; i >= MinCSFrameIndex; --i) {
355 unsigned Align = FFI->getObjectAlignment(i);
356 // If the alignment of this object is greater than that of the stack, then
357 // increase the stack alignment to match.
358 MaxAlign = std::max(MaxAlign, Align);
359 // Adjust to alignment boundary
360 Offset = (Offset+Align-1)/Align*Align;
362 FFI->setObjectOffset(i, Offset);
363 Offset += FFI->getObjectSize(i);
367 // Make sure the special register scavenging spill slot is closest to the
368 // frame pointer if a frame pointer is required.
369 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
370 if (RS && RegInfo->hasFP(Fn)) {
371 int SFI = RS->getScavengingFrameIndex();
373 // If stack grows down, we need to add size of the lowest
374 // address of the object.
376 Offset += FFI->getObjectSize(SFI);
378 unsigned Align = FFI->getObjectAlignment(SFI);
379 // Adjust to alignment boundary
380 Offset = (Offset+Align-1)/Align*Align;
382 if (StackGrowsDown) {
383 FFI->setObjectOffset(SFI, -Offset); // Set the computed offset
385 FFI->setObjectOffset(SFI, Offset);
386 Offset += FFI->getObjectSize(SFI);
391 // Then assign frame offsets to stack objects that are not used to spill
392 // callee saved registers.
393 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
394 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
396 if (RS && (int)i == RS->getScavengingFrameIndex())
399 // If stack grows down, we need to add size of find the lowest
400 // address of the object.
402 Offset += FFI->getObjectSize(i);
404 unsigned Align = FFI->getObjectAlignment(i);
405 // If the alignment of this object is greater than that of the stack, then
406 // increase the stack alignment to match.
407 MaxAlign = std::max(MaxAlign, Align);
408 // Adjust to alignment boundary
409 Offset = (Offset+Align-1)/Align*Align;
411 if (StackGrowsDown) {
412 FFI->setObjectOffset(i, -Offset); // Set the computed offset
414 FFI->setObjectOffset(i, Offset);
415 Offset += FFI->getObjectSize(i);
419 // Make sure the special register scavenging spill slot is closest to the
422 int SFI = RS->getScavengingFrameIndex();
424 // If stack grows down, we need to add size of find the lowest
425 // address of the object.
427 Offset += FFI->getObjectSize(SFI);
429 unsigned Align = FFI->getObjectAlignment(SFI);
430 // Adjust to alignment boundary
431 Offset = (Offset+Align-1)/Align*Align;
433 if (StackGrowsDown) {
434 FFI->setObjectOffset(SFI, -Offset); // Set the computed offset
436 FFI->setObjectOffset(SFI, Offset);
437 Offset += FFI->getObjectSize(SFI);
442 // Round up the size to a multiple of the alignment, but only if there are
443 // calls or alloca's in the function. This ensures that any calls to
444 // subroutines have their stack frames suitable aligned.
445 if (!RegInfo->targetHandlesStackFrameRounding() &&
446 (FFI->hasCalls() || FFI->hasVarSizedObjects())) {
447 // If we have reserved argument space for call sites in the function
448 // immediately on entry to the current function, count it as part of the
449 // overall stack size.
450 if (RegInfo->hasReservedCallFrame(Fn))
451 Offset += FFI->getMaxCallFrameSize();
453 unsigned AlignMask = TFI.getStackAlignment() - 1;
454 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
457 // Update frame info to pretend that this is part of the stack...
458 FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
460 // Remember the required stack alignment in case targets need it to perform
461 // dynamic stack alignment.
462 assert(FFI->getMaxAlignment() == MaxAlign &&
463 "Stack alignment calculation broken!");
467 /// insertPrologEpilogCode - Scan the function for modified callee saved
468 /// registers, insert spill code for these callee saved registers, then add
469 /// prolog and epilog code to the function.
471 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
472 // Add prologue to the function...
473 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
475 // Add epilogue to restore the callee-save registers in each exiting block
476 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
477 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
478 // If last instruction is a return instruction, add an epilogue
479 if (!I->empty() && TII.isReturn(I->back().getOpcode()))
480 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
485 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
486 /// register references and actual offsets.
488 void PEI::replaceFrameIndices(MachineFunction &Fn) {
489 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
491 const TargetMachine &TM = Fn.getTarget();
492 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
493 const MRegisterInfo &MRI = *TM.getRegisterInfo();
495 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
496 if (RS) RS->enterBasicBlock(BB);
497 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
498 MachineInstr *MI = I++;
499 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
500 if (MI->getOperand(i).isFrameIndex()) {
501 // If this instruction has a FrameIndex operand, we need to use that
502 // target machine register info object to eliminate it.
503 MRI.eliminateFrameIndex(MI, RS);
505 // Revisit the instruction in full. Some instructions (e.g. inline
506 // asm instructions) can have multiple frame indices.
511 // Update register states.
512 if (RS && MI) RS->forward(MI);