Reapply r77654 with a fix: MachineFunctionPass's getAnalysisUsage
[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 is distributed under the University of Illinois Open Source
6 // 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 // This pass provides an optional shrink wrapping variant of prolog/epilog
18 // insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "PrologEpilogInserter.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/RegisterScavenging.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetFrameInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include <climits>
37
38 using namespace llvm;
39
40 char PEI::ID = 0;
41
42 static RegisterPass<PEI>
43 X("prologepilog", "Prologue/Epilogue Insertion");
44
45 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
46 /// prolog and epilog code, and eliminates abstract frame references.
47 ///
48 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
49
50 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
51 /// frame indexes with appropriate references.
52 ///
53 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
54   const Function* F = Fn.getFunction();
55   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
56   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
57
58   // Get MachineModuleInfo so that we can track the construction of the
59   // frame.
60   if (MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>())
61     Fn.getFrameInfo()->setMachineModuleInfo(MMI);
62
63   // Calculate the MaxCallFrameSize and HasCalls variables for the function's
64   // frame information. Also eliminates call frame pseudo instructions.
65   calculateCallsInformation(Fn);
66
67   // Allow the target machine to make some adjustments to the function
68   // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
69   TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
70
71   // Scan the function for modified callee saved registers and insert spill code
72   // for any callee saved registers that are modified.
73   calculateCalleeSavedRegisters(Fn);
74
75   // Determine placement of CSR spill/restore code:
76   //  - with shrink wrapping, place spills and restores to tightly
77   //    enclose regions in the Machine CFG of the function where
78   //    they are used. Without shrink wrapping
79   //  - default (no shrink wrapping), place all spills in the
80   //    entry block, all restores in return blocks.
81   placeCSRSpillsAndRestores(Fn);
82
83   // Add the code to save and restore the callee saved registers
84   if (!F->hasFnAttr(Attribute::Naked))
85     insertCSRSpillsAndRestores(Fn);
86
87   // Allow the target machine to make final modifications to the function
88   // before the frame layout is finalized.
89   TRI->processFunctionBeforeFrameFinalized(Fn);
90
91   // Calculate actual frame offsets for all abstract stack objects...
92   calculateFrameObjectOffsets(Fn);
93
94   // Add prolog and epilog code to the function.  This function is required
95   // to align the stack frame as necessary for any stack variables or
96   // called functions.  Because of this, calculateCalleeSavedRegisters
97   // must be called before this function in order to set the HasCalls
98   // and MaxCallFrameSize variables.
99   if (!F->hasFnAttr(Attribute::Naked))
100     insertPrologEpilogCode(Fn);
101
102   // Replace all MO_FrameIndex operands with physical register references
103   // and actual offsets.
104   //
105   replaceFrameIndices(Fn);
106
107   delete RS;
108   clearAllSets();
109   return true;
110 }
111
112 #if 0
113 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
114   if (ShrinkWrapping || ShrinkWrapFunc != "") {
115     AU.addRequired<MachineLoopInfo>();
116     AU.addRequired<MachineDominatorTree>();
117   }
118   AU.addPreserved<MachineLoopInfo>();
119   AU.addPreserved<MachineDominatorTree>();
120   MachineFunctionPass::getAnalysisUsage(AU);
121 }
122 #endif
123
124 /// calculateCallsInformation - Calculate the MaxCallFrameSize and HasCalls
125 /// variables for the function's frame information and eliminate call frame
126 /// pseudo instructions.
127 void PEI::calculateCallsInformation(MachineFunction &Fn) {
128   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
129
130   unsigned MaxCallFrameSize = 0;
131   bool HasCalls = false;
132
133   // Get the function call frame set-up and tear-down instruction opcode
134   int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
135   int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
136
137   // Early exit for targets which have no call frame setup/destroy pseudo
138   // instructions.
139   if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
140     return;
141
142   std::vector<MachineBasicBlock::iterator> FrameSDOps;
143   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
144     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
145       if (I->getOpcode() == FrameSetupOpcode ||
146           I->getOpcode() == FrameDestroyOpcode) {
147         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
148                " instructions should have a single immediate argument!");
149         unsigned Size = I->getOperand(0).getImm();
150         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
151         HasCalls = true;
152         FrameSDOps.push_back(I);
153       } else if (I->getOpcode() == TargetInstrInfo::INLINEASM) {
154         // An InlineAsm might be a call; assume it is to get the stack frame
155         // aligned correctly for calls.
156         HasCalls = true;
157       }
158
159   MachineFrameInfo *FFI = Fn.getFrameInfo();
160   FFI->setHasCalls(HasCalls);
161   FFI->setMaxCallFrameSize(MaxCallFrameSize);
162
163   for (std::vector<MachineBasicBlock::iterator>::iterator
164          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
165     MachineBasicBlock::iterator I = *i;
166
167     // If call frames are not being included as part of the stack frame, and
168     // there is no dynamic allocation (therefore referencing frame slots off
169     // sp), leave the pseudo ops alone. We'll eliminate them later.
170     if (RegInfo->hasReservedCallFrame(Fn) || RegInfo->hasFP(Fn))
171       RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
172   }
173 }
174
175
176 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
177 /// registers.
178 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
179   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
180   const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
181   MachineFrameInfo *FFI = Fn.getFrameInfo();
182
183   // Get the callee saved register list...
184   const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
185
186   // These are used to keep track the callee-save area. Initialize them.
187   MinCSFrameIndex = INT_MAX;
188   MaxCSFrameIndex = 0;
189
190   // Early exit for targets which have no callee saved registers.
191   if (CSRegs == 0 || CSRegs[0] == 0)
192     return;
193
194   // Figure out which *callee saved* registers are modified by the current
195   // function, thus needing to be saved and restored in the prolog/epilog.
196   const TargetRegisterClass * const *CSRegClasses =
197     RegInfo->getCalleeSavedRegClasses(&Fn);
198
199   std::vector<CalleeSavedInfo> CSI;
200   for (unsigned i = 0; CSRegs[i]; ++i) {
201     unsigned Reg = CSRegs[i];
202     if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
203       // If the reg is modified, save it!
204       CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
205     } else {
206       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
207            *AliasSet; ++AliasSet) {  // Check alias registers too.
208         if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
209           CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
210           break;
211         }
212       }
213     }
214   }
215
216   if (CSI.empty())
217     return;   // Early exit if no callee saved registers are modified!
218
219   unsigned NumFixedSpillSlots;
220   const std::pair<unsigned,int> *FixedSpillSlots =
221     TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
222
223   // Now that we know which registers need to be saved and restored, allocate
224   // stack slots for them.
225   for (std::vector<CalleeSavedInfo>::iterator
226          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
227     unsigned Reg = I->getReg();
228     const TargetRegisterClass *RC = I->getRegClass();
229
230     int FrameIdx;
231     if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
232       I->setFrameIdx(FrameIdx);
233       continue;
234     }
235
236     // Check to see if this physreg must be spilled to a particular stack slot
237     // on this target.
238     const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
239     while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
240            FixedSlot->first != Reg)
241       ++FixedSlot;
242
243     if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
244       // Nope, just spill it anywhere convenient.
245       unsigned Align = RC->getAlignment();
246       unsigned StackAlign = TFI->getStackAlignment();
247
248       // We may not be able to satisfy the desired alignment specification of
249       // the TargetRegisterClass if the stack alignment is smaller. Use the
250       // min.
251       Align = std::min(Align, StackAlign);
252       FrameIdx = FFI->CreateStackObject(RC->getSize(), Align);
253       if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
254       if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
255     } else {
256       // Spill it to the stack where we must.
257       FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
258     }
259
260     I->setFrameIdx(FrameIdx);
261   }
262
263   FFI->setCalleeSavedInfo(CSI);
264 }
265
266 /// insertCSRSpillsAndRestores - Insert spill and restore code for
267 /// callee saved registers used in the function, handling shrink wrapping.
268 ///
269 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
270   // Get callee saved register information.
271   MachineFrameInfo *FFI = Fn.getFrameInfo();
272   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
273
274   // Early exit if no callee saved registers are modified!
275   if (CSI.empty())
276     return;
277
278   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
279   MachineBasicBlock::iterator I;
280
281   if (! ShrinkWrapThisFunction) {
282     // Spill using target interface.
283     I = EntryBlock->begin();
284     if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI)) {
285       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
286         // Add the callee-saved register as live-in.
287         // It's killed at the spill.
288         EntryBlock->addLiveIn(CSI[i].getReg());
289
290         // Insert the spill to the stack frame.
291         TII.storeRegToStackSlot(*EntryBlock, I, CSI[i].getReg(), true,
292                                 CSI[i].getFrameIdx(), CSI[i].getRegClass());
293       }
294     }
295
296     // Restore using target interface.
297     for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
298       MachineBasicBlock* MBB = ReturnBlocks[ri];
299       I = MBB->end(); --I;
300
301       // Skip over all terminator instructions, which are part of the return
302       // sequence.
303       MachineBasicBlock::iterator I2 = I;
304       while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
305         I = I2;
306
307       bool AtStart = I == MBB->begin();
308       MachineBasicBlock::iterator BeforeI = I;
309       if (!AtStart)
310         --BeforeI;
311
312       // Restore all registers immediately before the return and any
313       // terminators that preceed it.
314       if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI)) {
315         for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
316           TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
317                                    CSI[i].getFrameIdx(),
318                                    CSI[i].getRegClass());
319           assert(I != MBB->begin() &&
320                  "loadRegFromStackSlot didn't insert any code!");
321           // Insert in reverse order.  loadRegFromStackSlot can insert
322           // multiple instructions.
323           if (AtStart)
324             I = MBB->begin();
325           else {
326             I = BeforeI;
327             ++I;
328           }
329         }
330       }
331     }
332     return;
333   }
334
335   // Insert spills.
336   std::vector<CalleeSavedInfo> blockCSI;
337   for (CSRegBlockMap::iterator BI = CSRSave.begin(),
338          BE = CSRSave.end(); BI != BE; ++BI) {
339     MachineBasicBlock* MBB = BI->first;
340     CSRegSet save = BI->second;
341
342     if (save.empty())
343       continue;
344
345     blockCSI.clear();
346     for (CSRegSet::iterator RI = save.begin(),
347            RE = save.end(); RI != RE; ++RI) {
348       blockCSI.push_back(CSI[*RI]);
349     }
350     assert(blockCSI.size() > 0 &&
351            "Could not collect callee saved register info");
352
353     I = MBB->begin();
354
355     // When shrink wrapping, use stack slot stores/loads.
356     for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
357       // Add the callee-saved register as live-in.
358       // It's killed at the spill.
359       MBB->addLiveIn(blockCSI[i].getReg());
360
361       // Insert the spill to the stack frame.
362       TII.storeRegToStackSlot(*MBB, I, blockCSI[i].getReg(),
363                               true,
364                               blockCSI[i].getFrameIdx(),
365                               blockCSI[i].getRegClass());
366     }
367   }
368
369   for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
370          BE = CSRRestore.end(); BI != BE; ++BI) {
371     MachineBasicBlock* MBB = BI->first;
372     CSRegSet restore = BI->second;
373
374     if (restore.empty())
375       continue;
376
377     blockCSI.clear();
378     for (CSRegSet::iterator RI = restore.begin(),
379            RE = restore.end(); RI != RE; ++RI) {
380       blockCSI.push_back(CSI[*RI]);
381     }
382     assert(blockCSI.size() > 0 &&
383            "Could not find callee saved register info");
384
385     // If MBB is empty and needs restores, insert at the _beginning_.
386     if (MBB->empty()) {
387       I = MBB->begin();
388     } else {
389       I = MBB->end();
390       --I;
391
392       // Skip over all terminator instructions, which are part of the
393       // return sequence.
394       if (! I->getDesc().isTerminator()) {
395         ++I;
396       } else {
397         MachineBasicBlock::iterator I2 = I;
398         while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
399           I = I2;
400       }
401     }
402
403     bool AtStart = I == MBB->begin();
404     MachineBasicBlock::iterator BeforeI = I;
405     if (!AtStart)
406       --BeforeI;
407
408     // Restore all registers immediately before the return and any
409     // terminators that preceed it.
410     for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
411       TII.loadRegFromStackSlot(*MBB, I, blockCSI[i].getReg(),
412                                blockCSI[i].getFrameIdx(),
413                                blockCSI[i].getRegClass());
414       assert(I != MBB->begin() &&
415              "loadRegFromStackSlot didn't insert any code!");
416       // Insert in reverse order.  loadRegFromStackSlot can insert
417       // multiple instructions.
418       if (AtStart)
419         I = MBB->begin();
420       else {
421         I = BeforeI;
422         ++I;
423       }
424     }
425   }
426 }
427
428 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
429 static inline void
430 AdjustStackOffset(MachineFrameInfo *FFI, int FrameIdx,
431                   bool StackGrowsDown, int64_t &Offset,
432                   unsigned &MaxAlign) {
433   // If stack grows down, we need to add size of find the lowest address of the
434   // object.
435   if (StackGrowsDown)
436     Offset += FFI->getObjectSize(FrameIdx);
437
438   unsigned Align = FFI->getObjectAlignment(FrameIdx);
439
440   // If the alignment of this object is greater than that of the stack, then
441   // increase the stack alignment to match.
442   MaxAlign = std::max(MaxAlign, Align);
443
444   // Adjust to alignment boundary.
445   Offset = (Offset + Align - 1) / Align * Align;
446
447   if (StackGrowsDown) {
448     FFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
449   } else {
450     FFI->setObjectOffset(FrameIdx, Offset);
451     Offset += FFI->getObjectSize(FrameIdx);
452   }
453 }
454
455 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
456 /// abstract stack objects.
457 ///
458 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
459   const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
460
461   bool StackGrowsDown =
462     TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
463
464   // Loop over all of the stack objects, assigning sequential addresses...
465   MachineFrameInfo *FFI = Fn.getFrameInfo();
466
467   unsigned MaxAlign = FFI->getMaxAlignment();
468
469   // Start at the beginning of the local area.
470   // The Offset is the distance from the stack top in the direction
471   // of stack growth -- so it's always nonnegative.
472   int64_t Offset = TFI.getOffsetOfLocalArea();
473   if (StackGrowsDown)
474     Offset = -Offset;
475   assert(Offset >= 0
476          && "Local area offset should be in direction of stack growth");
477
478   // If there are fixed sized objects that are preallocated in the local area,
479   // non-fixed objects can't be allocated right at the start of local area.
480   // We currently don't support filling in holes in between fixed sized
481   // objects, so we adjust 'Offset' to point to the end of last fixed sized
482   // preallocated object.
483   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
484     int64_t FixedOff;
485     if (StackGrowsDown) {
486       // The maximum distance from the stack pointer is at lower address of
487       // the object -- which is given by offset. For down growing stack
488       // the offset is negative, so we negate the offset to get the distance.
489       FixedOff = -FFI->getObjectOffset(i);
490     } else {
491       // The maximum distance from the start pointer is at the upper
492       // address of the object.
493       FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
494     }
495     if (FixedOff > Offset) Offset = FixedOff;
496   }
497
498   // First assign frame offsets to stack objects that are used to spill
499   // callee saved registers.
500   if (StackGrowsDown) {
501     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
502       // If stack grows down, we need to add size of find the lowest
503       // address of the object.
504       Offset += FFI->getObjectSize(i);
505
506       unsigned Align = FFI->getObjectAlignment(i);
507       // If the alignment of this object is greater than that of the stack,
508       // then increase the stack alignment to match.
509       MaxAlign = std::max(MaxAlign, Align);
510       // Adjust to alignment boundary
511       Offset = (Offset+Align-1)/Align*Align;
512
513       FFI->setObjectOffset(i, -Offset);        // Set the computed offset
514     }
515   } else {
516     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
517     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
518       unsigned Align = FFI->getObjectAlignment(i);
519       // If the alignment of this object is greater than that of the stack,
520       // then increase the stack alignment to match.
521       MaxAlign = std::max(MaxAlign, Align);
522       // Adjust to alignment boundary
523       Offset = (Offset+Align-1)/Align*Align;
524
525       FFI->setObjectOffset(i, Offset);
526       Offset += FFI->getObjectSize(i);
527     }
528   }
529
530   // Make sure the special register scavenging spill slot is closest to the
531   // frame pointer if a frame pointer is required.
532   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
533   if (RS && RegInfo->hasFP(Fn)) {
534     int SFI = RS->getScavengingFrameIndex();
535     if (SFI >= 0)
536       AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
537   }
538
539   // Make sure that the stack protector comes before the local variables on the
540   // stack.
541   if (FFI->getStackProtectorIndex() >= 0)
542     AdjustStackOffset(FFI, FFI->getStackProtectorIndex(), StackGrowsDown,
543                       Offset, MaxAlign);
544
545   // Then assign frame offsets to stack objects that are not used to spill
546   // callee saved registers.
547   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
548     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
549       continue;
550     if (RS && (int)i == RS->getScavengingFrameIndex())
551       continue;
552     if (FFI->isDeadObjectIndex(i))
553       continue;
554     if (FFI->getStackProtectorIndex() == (int)i)
555       continue;
556
557     AdjustStackOffset(FFI, i, StackGrowsDown, Offset, MaxAlign);
558   }
559
560   // Make sure the special register scavenging spill slot is closest to the
561   // stack pointer.
562   if (RS && !RegInfo->hasFP(Fn)) {
563     int SFI = RS->getScavengingFrameIndex();
564     if (SFI >= 0)
565       AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
566   }
567
568   // Round up the size to a multiple of the alignment, but only if there are
569   // calls or alloca's in the function.  This ensures that any calls to
570   // subroutines have their stack frames suitable aligned.
571   // Also do this if we need runtime alignment of the stack.  In this case
572   // offsets will be relative to SP not FP; round up the stack size so this
573   // works.
574   if (!RegInfo->targetHandlesStackFrameRounding() &&
575       (FFI->hasCalls() || FFI->hasVarSizedObjects() ||
576        (RegInfo->needsStackRealignment(Fn) &&
577         FFI->getObjectIndexEnd() != 0))) {
578     // If we have reserved argument space for call sites in the function
579     // immediately on entry to the current function, count it as part of the
580     // overall stack size.
581     if (RegInfo->hasReservedCallFrame(Fn))
582       Offset += FFI->getMaxCallFrameSize();
583
584     unsigned AlignMask = std::max(TFI.getStackAlignment(),MaxAlign) - 1;
585     Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
586   }
587
588   // Update frame info to pretend that this is part of the stack...
589   FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
590
591   // Remember the required stack alignment in case targets need it to perform
592   // dynamic stack alignment.
593   FFI->setMaxAlignment(MaxAlign);
594 }
595
596
597 /// insertPrologEpilogCode - Scan the function for modified callee saved
598 /// registers, insert spill code for these callee saved registers, then add
599 /// prolog and epilog code to the function.
600 ///
601 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
602   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
603
604   // Add prologue to the function...
605   TRI->emitPrologue(Fn);
606
607   // Add epilogue to restore the callee-save registers in each exiting block
608   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
609     // If last instruction is a return instruction, add an epilogue
610     if (!I->empty() && I->back().getDesc().isReturn())
611       TRI->emitEpilogue(Fn, *I);
612   }
613 }
614
615
616 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
617 /// register references and actual offsets.
618 ///
619 void PEI::replaceFrameIndices(MachineFunction &Fn) {
620   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
621
622   const TargetMachine &TM = Fn.getTarget();
623   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
624   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
625   const TargetFrameInfo *TFI = TM.getFrameInfo();
626   bool StackGrowsDown =
627     TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
628   int FrameSetupOpcode   = TRI.getCallFrameSetupOpcode();
629   int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
630
631   for (MachineFunction::iterator BB = Fn.begin(),
632          E = Fn.end(); BB != E; ++BB) {
633     int SPAdj = 0;  // SP offset due to call frame setup / destroy.
634     if (RS) RS->enterBasicBlock(BB);
635
636     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
637       if (I->getOpcode() == TargetInstrInfo::DECLARE) {
638         // Ignore it.
639         ++I;
640         continue;
641       }
642
643       if (I->getOpcode() == FrameSetupOpcode ||
644           I->getOpcode() == FrameDestroyOpcode) {
645         // Remember how much SP has been adjusted to create the call
646         // frame.
647         int Size = I->getOperand(0).getImm();
648
649         if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
650             (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
651           Size = -Size;
652
653         SPAdj += Size;
654
655         MachineBasicBlock::iterator PrevI = BB->end();
656         if (I != BB->begin()) PrevI = prior(I);
657         TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
658
659         // Visit the instructions created by eliminateCallFramePseudoInstr().
660         if (PrevI == BB->end())
661           I = BB->begin();     // The replaced instr was the first in the block.
662         else
663           I = next(PrevI);
664         continue;
665       }
666
667       MachineInstr *MI = I;
668       bool DoIncr = true;
669       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
670         if (MI->getOperand(i).isFI()) {
671           // Some instructions (e.g. inline asm instructions) can have
672           // multiple frame indices and/or cause eliminateFrameIndex
673           // to insert more than one instruction. We need the register
674           // scavenger to go through all of these instructions so that
675           // it can update its register information. We keep the
676           // iterator at the point before insertion so that we can
677           // revisit them in full.
678           bool AtBeginning = (I == BB->begin());
679           if (!AtBeginning) --I;
680
681           // If this instruction has a FrameIndex operand, we need to
682           // use that target machine register info object to eliminate
683           // it.
684
685           TRI.eliminateFrameIndex(MI, SPAdj, RS);
686
687           // Reset the iterator if we were at the beginning of the BB.
688           if (AtBeginning) {
689             I = BB->begin();
690             DoIncr = false;
691           }
692
693           MI = 0;
694           break;
695         }
696
697       if (DoIncr && I != BB->end()) ++I;
698
699       // Update register states.
700       if (RS && MI) RS->forward(MI);
701     }
702
703     assert(SPAdj == 0 && "Unbalanced call frame setup / destroy pairs?");
704   }
705 }
706