b18d52d124d4bee9b151c06ecd4b5c187a03e256
[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 #define DEBUG_TYPE "pei"
23 #include "PrologEpilogInserter.h"
24 #include "llvm/ADT/IndexedMap.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/RegisterScavenging.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetFrameLowering.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include <climits>
44
45 using namespace llvm;
46
47 char PEI::ID = 0;
48 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
49
50 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
51                 "Prologue/Epilogue Insertion", false, false)
52 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
53 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
54 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
55 INITIALIZE_PASS_END(PEI, "prologepilog",
56                     "Prologue/Epilogue Insertion & Frame Finalization",
57                     false, false)
58
59 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
60 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
61 STATISTIC(NumBytesStackSpace,
62           "Number of bytes used for stack in all functions");
63
64 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
65 /// frame indexes with appropriate references.
66 ///
67 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
68   const Function* F = Fn.getFunction();
69   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
70   const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
71
72   assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
73
74   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
75   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
76
77   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
78   // function's frame information. Also eliminates call frame pseudo
79   // instructions.
80   calculateCallsInformation(Fn);
81
82   // Allow the target machine to make some adjustments to the function
83   // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
84   TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
85
86   // Scan the function for modified callee saved registers and insert spill code
87   // for any callee saved registers that are modified.
88   calculateCalleeSavedRegisters(Fn);
89
90   // Determine placement of CSR spill/restore code:
91   //  - With shrink wrapping, place spills and restores to tightly
92   //    enclose regions in the Machine CFG of the function where
93   //    they are used.
94   //  - Without shink wrapping (default), place all spills in the
95   //    entry block, all restores in return blocks.
96   placeCSRSpillsAndRestores(Fn);
97
98   // Add the code to save and restore the callee saved registers
99   if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
100                                        Attribute::Naked))
101     insertCSRSpillsAndRestores(Fn);
102
103   // Allow the target machine to make final modifications to the function
104   // before the frame layout is finalized.
105   TFI->processFunctionBeforeFrameFinalized(Fn);
106
107   // Calculate actual frame offsets for all abstract stack objects...
108   calculateFrameObjectOffsets(Fn);
109
110   // Add prolog and epilog code to the function.  This function is required
111   // to align the stack frame as necessary for any stack variables or
112   // called functions.  Because of this, calculateCalleeSavedRegisters()
113   // must be called before this function in order to set the AdjustsStack
114   // and MaxCallFrameSize variables.
115   if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
116                                        Attribute::Naked))
117     insertPrologEpilogCode(Fn);
118
119   // Replace all MO_FrameIndex operands with physical register references
120   // and actual offsets.
121   //
122   replaceFrameIndices(Fn);
123
124   // If register scavenging is needed, as we've enabled doing it as a
125   // post-pass, scavenge the virtual registers that frame index elimiation
126   // inserted.
127   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
128     scavengeFrameVirtualRegs(Fn);
129
130   // Clear any vregs created by virtual scavenging.
131   Fn.getRegInfo().clearVirtRegs();
132
133   delete RS;
134   clearAllSets();
135   return true;
136 }
137
138 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
139 /// variables for the function's frame information and eliminate call frame
140 /// pseudo instructions.
141 void PEI::calculateCallsInformation(MachineFunction &Fn) {
142   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
143   const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
144   MachineFrameInfo *MFI = Fn.getFrameInfo();
145
146   unsigned MaxCallFrameSize = 0;
147   bool AdjustsStack = MFI->adjustsStack();
148
149   // Get the function call frame set-up and tear-down instruction opcode
150   int FrameSetupOpcode   = TII.getCallFrameSetupOpcode();
151   int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
152
153   // Early exit for targets which have no call frame setup/destroy pseudo
154   // instructions.
155   if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
156     return;
157
158   std::vector<MachineBasicBlock::iterator> FrameSDOps;
159   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
160     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
161       if (I->getOpcode() == FrameSetupOpcode ||
162           I->getOpcode() == FrameDestroyOpcode) {
163         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
164                " instructions should have a single immediate argument!");
165         unsigned Size = I->getOperand(0).getImm();
166         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
167         AdjustsStack = true;
168         FrameSDOps.push_back(I);
169       } else if (I->isInlineAsm()) {
170         // Some inline asm's need a stack frame, as indicated by operand 1.
171         unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
172         if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
173           AdjustsStack = true;
174       }
175
176   MFI->setAdjustsStack(AdjustsStack);
177   MFI->setMaxCallFrameSize(MaxCallFrameSize);
178
179   for (std::vector<MachineBasicBlock::iterator>::iterator
180          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
181     MachineBasicBlock::iterator I = *i;
182
183     // If call frames are not being included as part of the stack frame, and
184     // the target doesn't indicate otherwise, remove the call frame pseudos
185     // here. The sub/add sp instruction pairs are still inserted, but we don't
186     // need to track the SP adjustment for frame index elimination.
187     if (TFI->canSimplifyCallFramePseudos(Fn))
188       TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
189   }
190 }
191
192
193 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
194 /// registers.
195 void PEI::calculateCalleeSavedRegisters(MachineFunction &F) {
196   const TargetRegisterInfo *RegInfo = F.getTarget().getRegisterInfo();
197   const TargetFrameLowering *TFI = F.getTarget().getFrameLowering();
198   MachineFrameInfo *MFI = F.getFrameInfo();
199
200   // Get the callee saved register list...
201   const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&F);
202
203   // These are used to keep track the callee-save area. Initialize them.
204   MinCSFrameIndex = INT_MAX;
205   MaxCSFrameIndex = 0;
206
207   // Early exit for targets which have no callee saved registers.
208   if (CSRegs == 0 || CSRegs[0] == 0)
209     return;
210
211   // In Naked functions we aren't going to save any registers.
212   if (F.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
213                                                     Attribute::Naked))
214     return;
215
216   std::vector<CalleeSavedInfo> CSI;
217   for (unsigned i = 0; CSRegs[i]; ++i) {
218     unsigned Reg = CSRegs[i];
219     if (F.getRegInfo().isPhysRegUsed(Reg)) {
220       // If the reg is modified, save it!
221       CSI.push_back(CalleeSavedInfo(Reg));
222     }
223   }
224
225   if (CSI.empty())
226     return;   // Early exit if no callee saved registers are modified!
227
228   unsigned NumFixedSpillSlots;
229   const TargetFrameLowering::SpillSlot *FixedSpillSlots =
230     TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
231
232   // Now that we know which registers need to be saved and restored, allocate
233   // stack slots for them.
234   for (std::vector<CalleeSavedInfo>::iterator
235          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
236     unsigned Reg = I->getReg();
237     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
238
239     int FrameIdx;
240     if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
241       I->setFrameIdx(FrameIdx);
242       continue;
243     }
244
245     // Check to see if this physreg must be spilled to a particular stack slot
246     // on this target.
247     const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
248     while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
249            FixedSlot->Reg != Reg)
250       ++FixedSlot;
251
252     if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
253       // Nope, just spill it anywhere convenient.
254       unsigned Align = RC->getAlignment();
255       unsigned StackAlign = TFI->getStackAlignment();
256
257       // We may not be able to satisfy the desired alignment specification of
258       // the TargetRegisterClass if the stack alignment is smaller. Use the
259       // min.
260       Align = std::min(Align, StackAlign);
261       FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
262       if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
263       if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
264     } else {
265       // Spill it to the stack where we must.
266       FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
267     }
268
269     I->setFrameIdx(FrameIdx);
270   }
271
272   MFI->setCalleeSavedInfo(CSI);
273 }
274
275 /// insertCSRSpillsAndRestores - Insert spill and restore code for
276 /// callee saved registers used in the function, handling shrink wrapping.
277 ///
278 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
279   // Get callee saved register information.
280   MachineFrameInfo *MFI = Fn.getFrameInfo();
281   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
282
283   MFI->setCalleeSavedInfoValid(true);
284
285   // Early exit if no callee saved registers are modified!
286   if (CSI.empty())
287     return;
288
289   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
290   const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
291   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
292   MachineBasicBlock::iterator I;
293
294   if (!ShrinkWrapThisFunction) {
295     // Spill using target interface.
296     I = EntryBlock->begin();
297     if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
298       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
299         // Add the callee-saved register as live-in.
300         // It's killed at the spill.
301         EntryBlock->addLiveIn(CSI[i].getReg());
302
303         // Insert the spill to the stack frame.
304         unsigned Reg = CSI[i].getReg();
305         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
306         TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
307                                 CSI[i].getFrameIdx(), RC, TRI);
308       }
309     }
310
311     // Restore using target interface.
312     for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
313       MachineBasicBlock* MBB = ReturnBlocks[ri];
314       I = MBB->end(); --I;
315
316       // Skip over all terminator instructions, which are part of the return
317       // sequence.
318       MachineBasicBlock::iterator I2 = I;
319       while (I2 != MBB->begin() && (--I2)->isTerminator())
320         I = I2;
321
322       bool AtStart = I == MBB->begin();
323       MachineBasicBlock::iterator BeforeI = I;
324       if (!AtStart)
325         --BeforeI;
326
327       // Restore all registers immediately before the return and any
328       // terminators that precede it.
329       if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
330         for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
331           unsigned Reg = CSI[i].getReg();
332           const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
333           TII.loadRegFromStackSlot(*MBB, I, Reg,
334                                    CSI[i].getFrameIdx(),
335                                    RC, TRI);
336           assert(I != MBB->begin() &&
337                  "loadRegFromStackSlot didn't insert any code!");
338           // Insert in reverse order.  loadRegFromStackSlot can insert
339           // multiple instructions.
340           if (AtStart)
341             I = MBB->begin();
342           else {
343             I = BeforeI;
344             ++I;
345           }
346         }
347       }
348     }
349     return;
350   }
351
352   // Insert spills.
353   std::vector<CalleeSavedInfo> blockCSI;
354   for (CSRegBlockMap::iterator BI = CSRSave.begin(),
355          BE = CSRSave.end(); BI != BE; ++BI) {
356     MachineBasicBlock* MBB = BI->first;
357     CSRegSet save = BI->second;
358
359     if (save.empty())
360       continue;
361
362     blockCSI.clear();
363     for (CSRegSet::iterator RI = save.begin(),
364            RE = save.end(); RI != RE; ++RI) {
365       blockCSI.push_back(CSI[*RI]);
366     }
367     assert(blockCSI.size() > 0 &&
368            "Could not collect callee saved register info");
369
370     I = MBB->begin();
371
372     // When shrink wrapping, use stack slot stores/loads.
373     for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
374       // Add the callee-saved register as live-in.
375       // It's killed at the spill.
376       MBB->addLiveIn(blockCSI[i].getReg());
377
378       // Insert the spill to the stack frame.
379       unsigned Reg = blockCSI[i].getReg();
380       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
381       TII.storeRegToStackSlot(*MBB, I, Reg,
382                               true,
383                               blockCSI[i].getFrameIdx(),
384                               RC, TRI);
385     }
386   }
387
388   for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
389          BE = CSRRestore.end(); BI != BE; ++BI) {
390     MachineBasicBlock* MBB = BI->first;
391     CSRegSet restore = BI->second;
392
393     if (restore.empty())
394       continue;
395
396     blockCSI.clear();
397     for (CSRegSet::iterator RI = restore.begin(),
398            RE = restore.end(); RI != RE; ++RI) {
399       blockCSI.push_back(CSI[*RI]);
400     }
401     assert(blockCSI.size() > 0 &&
402            "Could not find callee saved register info");
403
404     // If MBB is empty and needs restores, insert at the _beginning_.
405     if (MBB->empty()) {
406       I = MBB->begin();
407     } else {
408       I = MBB->end();
409       --I;
410
411       // Skip over all terminator instructions, which are part of the
412       // return sequence.
413       if (! I->isTerminator()) {
414         ++I;
415       } else {
416         MachineBasicBlock::iterator I2 = I;
417         while (I2 != MBB->begin() && (--I2)->isTerminator())
418           I = I2;
419       }
420     }
421
422     bool AtStart = I == MBB->begin();
423     MachineBasicBlock::iterator BeforeI = I;
424     if (!AtStart)
425       --BeforeI;
426
427     // Restore all registers immediately before the return and any
428     // terminators that precede it.
429     for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
430       unsigned Reg = blockCSI[i].getReg();
431       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
432       TII.loadRegFromStackSlot(*MBB, I, Reg,
433                                blockCSI[i].getFrameIdx(),
434                                RC, TRI);
435       assert(I != MBB->begin() &&
436              "loadRegFromStackSlot didn't insert any code!");
437       // Insert in reverse order.  loadRegFromStackSlot can insert
438       // multiple instructions.
439       if (AtStart)
440         I = MBB->begin();
441       else {
442         I = BeforeI;
443         ++I;
444       }
445     }
446   }
447 }
448
449 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
450 static inline void
451 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
452                   bool StackGrowsDown, int64_t &Offset,
453                   unsigned &MaxAlign) {
454   // If the stack grows down, add the object size to find the lowest address.
455   if (StackGrowsDown)
456     Offset += MFI->getObjectSize(FrameIdx);
457
458   unsigned Align = MFI->getObjectAlignment(FrameIdx);
459
460   // If the alignment of this object is greater than that of the stack, then
461   // increase the stack alignment to match.
462   MaxAlign = std::max(MaxAlign, Align);
463
464   // Adjust to alignment boundary.
465   Offset = (Offset + Align - 1) / Align * Align;
466
467   if (StackGrowsDown) {
468     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
469     MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
470   } else {
471     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
472     MFI->setObjectOffset(FrameIdx, Offset);
473     Offset += MFI->getObjectSize(FrameIdx);
474   }
475 }
476
477 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
478 /// abstract stack objects.
479 ///
480 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
481   const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
482
483   bool StackGrowsDown =
484     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
485
486   // Loop over all of the stack objects, assigning sequential addresses...
487   MachineFrameInfo *MFI = Fn.getFrameInfo();
488
489   // Start at the beginning of the local area.
490   // The Offset is the distance from the stack top in the direction
491   // of stack growth -- so it's always nonnegative.
492   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
493   if (StackGrowsDown)
494     LocalAreaOffset = -LocalAreaOffset;
495   assert(LocalAreaOffset >= 0
496          && "Local area offset should be in direction of stack growth");
497   int64_t Offset = LocalAreaOffset;
498
499   // If there are fixed sized objects that are preallocated in the local area,
500   // non-fixed objects can't be allocated right at the start of local area.
501   // We currently don't support filling in holes in between fixed sized
502   // objects, so we adjust 'Offset' to point to the end of last fixed sized
503   // preallocated object.
504   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
505     int64_t FixedOff;
506     if (StackGrowsDown) {
507       // The maximum distance from the stack pointer is at lower address of
508       // the object -- which is given by offset. For down growing stack
509       // the offset is negative, so we negate the offset to get the distance.
510       FixedOff = -MFI->getObjectOffset(i);
511     } else {
512       // The maximum distance from the start pointer is at the upper
513       // address of the object.
514       FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
515     }
516     if (FixedOff > Offset) Offset = FixedOff;
517   }
518
519   // First assign frame offsets to stack objects that are used to spill
520   // callee saved registers.
521   if (StackGrowsDown) {
522     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
523       // If the stack grows down, we need to add the size to find the lowest
524       // address of the object.
525       Offset += MFI->getObjectSize(i);
526
527       unsigned Align = MFI->getObjectAlignment(i);
528       // Adjust to alignment boundary
529       Offset = (Offset+Align-1)/Align*Align;
530
531       MFI->setObjectOffset(i, -Offset);        // Set the computed offset
532     }
533   } else {
534     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
535     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
536       unsigned Align = MFI->getObjectAlignment(i);
537       // Adjust to alignment boundary
538       Offset = (Offset+Align-1)/Align*Align;
539
540       MFI->setObjectOffset(i, Offset);
541       Offset += MFI->getObjectSize(i);
542     }
543   }
544
545   unsigned MaxAlign = MFI->getMaxAlignment();
546
547   // Make sure the special register scavenging spill slot is closest to the
548   // frame pointer if a frame pointer is required.
549   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
550   if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
551       !RegInfo->needsStackRealignment(Fn)) {
552     int SFI = RS->getScavengingFrameIndex();
553     if (SFI >= 0)
554       AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
555   }
556
557   // FIXME: Once this is working, then enable flag will change to a target
558   // check for whether the frame is large enough to want to use virtual
559   // frame index registers. Functions which don't want/need this optimization
560   // will continue to use the existing code path.
561   if (MFI->getUseLocalStackAllocationBlock()) {
562     unsigned Align = MFI->getLocalFrameMaxAlign();
563
564     // Adjust to alignment boundary.
565     Offset = (Offset + Align - 1) / Align * Align;
566
567     DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
568
569     // Resolve offsets for objects in the local block.
570     for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
571       std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
572       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
573       DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
574             FIOffset << "]\n");
575       MFI->setObjectOffset(Entry.first, FIOffset);
576     }
577     // Allocate the local block
578     Offset += MFI->getLocalFrameSize();
579
580     MaxAlign = std::max(Align, MaxAlign);
581   }
582
583   // Make sure that the stack protector comes before the local variables on the
584   // stack.
585   SmallSet<int, 16> LargeStackObjs;
586   if (MFI->getStackProtectorIndex() >= 0) {
587     AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
588                       Offset, MaxAlign);
589
590     // Assign large stack objects first.
591     for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
592       if (MFI->isObjectPreAllocated(i) &&
593           MFI->getUseLocalStackAllocationBlock())
594         continue;
595       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
596         continue;
597       if (RS && (int)i == RS->getScavengingFrameIndex())
598         continue;
599       if (MFI->isDeadObjectIndex(i))
600         continue;
601       if (MFI->getStackProtectorIndex() == (int)i)
602         continue;
603       if (!MFI->MayNeedStackProtector(i))
604         continue;
605
606       AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
607       LargeStackObjs.insert(i);
608     }
609   }
610
611   // Then assign frame offsets to stack objects that are not used to spill
612   // callee saved registers.
613   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
614     if (MFI->isObjectPreAllocated(i) &&
615         MFI->getUseLocalStackAllocationBlock())
616       continue;
617     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
618       continue;
619     if (RS && (int)i == RS->getScavengingFrameIndex())
620       continue;
621     if (MFI->isDeadObjectIndex(i))
622       continue;
623     if (MFI->getStackProtectorIndex() == (int)i)
624       continue;
625     if (LargeStackObjs.count(i))
626       continue;
627
628     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
629   }
630
631   // Make sure the special register scavenging spill slot is closest to the
632   // stack pointer.
633   if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
634              !RegInfo->useFPForScavengingIndex(Fn))) {
635     int SFI = RS->getScavengingFrameIndex();
636     if (SFI >= 0)
637       AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
638   }
639
640   if (!TFI.targetHandlesStackFrameRounding()) {
641     // If we have reserved argument space for call sites in the function
642     // immediately on entry to the current function, count it as part of the
643     // overall stack size.
644     if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
645       Offset += MFI->getMaxCallFrameSize();
646
647     // Round up the size to a multiple of the alignment.  If the function has
648     // any calls or alloca's, align to the target's StackAlignment value to
649     // ensure that the callee's frame or the alloca data is suitably aligned;
650     // otherwise, for leaf functions, align to the TransientStackAlignment
651     // value.
652     unsigned StackAlign;
653     if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
654         (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
655       StackAlign = TFI.getStackAlignment();
656     else
657       StackAlign = TFI.getTransientStackAlignment();
658
659     // If the frame pointer is eliminated, all frame offsets will be relative to
660     // SP not FP. Align to MaxAlign so this works.
661     StackAlign = std::max(StackAlign, MaxAlign);
662     unsigned AlignMask = StackAlign - 1;
663     Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
664   }
665
666   // Update frame info to pretend that this is part of the stack...
667   int64_t StackSize = Offset - LocalAreaOffset;
668   MFI->setStackSize(StackSize);
669   NumBytesStackSpace += StackSize;
670 }
671
672 /// insertPrologEpilogCode - Scan the function for modified callee saved
673 /// registers, insert spill code for these callee saved registers, then add
674 /// prolog and epilog code to the function.
675 ///
676 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
677   const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
678
679   // Add prologue to the function...
680   TFI.emitPrologue(Fn);
681
682   // Add epilogue to restore the callee-save registers in each exiting block
683   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
684     // If last instruction is a return instruction, add an epilogue
685     if (!I->empty() && I->back().isReturn())
686       TFI.emitEpilogue(Fn, *I);
687   }
688
689   // Emit additional code that is required to support segmented stacks, if
690   // we've been asked for it.  This, when linked with a runtime with support
691   // for segmented stacks (libgcc is one), will result in allocating stack
692   // space in small chunks instead of one large contiguous block.
693   if (Fn.getTarget().Options.EnableSegmentedStacks)
694     TFI.adjustForSegmentedStacks(Fn);
695
696   // Emit additional code that is required to explicitly handle the stack in
697   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
698   // approach is rather similar to that of Segmented Stacks, but it uses a
699   // different conditional check and another BIF for allocating more stack
700   // space.
701   if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
702     TFI.adjustForHiPEPrologue(Fn);
703 }
704
705 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
706 /// register references and actual offsets.
707 ///
708 void PEI::replaceFrameIndices(MachineFunction &Fn) {
709   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
710
711   const TargetMachine &TM = Fn.getTarget();
712   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
713   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
714   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
715   const TargetFrameLowering *TFI = TM.getFrameLowering();
716   bool StackGrowsDown =
717     TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
718   int FrameSetupOpcode   = TII.getCallFrameSetupOpcode();
719   int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
720
721   for (MachineFunction::iterator BB = Fn.begin(),
722          E = Fn.end(); BB != E; ++BB) {
723 #ifndef NDEBUG
724     int SPAdjCount = 0; // frame setup / destroy count.
725 #endif
726     int SPAdj = 0;  // SP offset due to call frame setup / destroy.
727     if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
728
729     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
730
731       if (I->getOpcode() == FrameSetupOpcode ||
732           I->getOpcode() == FrameDestroyOpcode) {
733 #ifndef NDEBUG
734         // Track whether we see even pairs of them
735         SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
736 #endif
737         // Remember how much SP has been adjusted to create the call
738         // frame.
739         int Size = I->getOperand(0).getImm();
740
741         if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
742             (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
743           Size = -Size;
744
745         SPAdj += Size;
746
747         MachineBasicBlock::iterator PrevI = BB->end();
748         if (I != BB->begin()) PrevI = prior(I);
749         TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
750
751         // Visit the instructions created by eliminateCallFramePseudoInstr().
752         if (PrevI == BB->end())
753           I = BB->begin();     // The replaced instr was the first in the block.
754         else
755           I = llvm::next(PrevI);
756         continue;
757       }
758
759       MachineInstr *MI = I;
760       bool DoIncr = true;
761       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
762         if (!MI->getOperand(i).isFI())
763             continue;
764
765         // Some instructions (e.g. inline asm instructions) can have
766         // multiple frame indices and/or cause eliminateFrameIndex
767         // to insert more than one instruction. We need the register
768         // scavenger to go through all of these instructions so that
769         // it can update its register information. We keep the
770         // iterator at the point before insertion so that we can
771         // revisit them in full.
772         bool AtBeginning = (I == BB->begin());
773         if (!AtBeginning) --I;
774
775         // If this instruction has a FrameIndex operand, we need to
776         // use that target machine register info object to eliminate
777         // it.
778         TRI.eliminateFrameIndex(MI, SPAdj, i,
779                                 FrameIndexVirtualScavenging ?  NULL : RS);
780
781         // Reset the iterator if we were at the beginning of the BB.
782         if (AtBeginning) {
783           I = BB->begin();
784           DoIncr = false;
785         }
786
787         MI = 0;
788         break;
789       }
790
791       if (DoIncr && I != BB->end()) ++I;
792
793       // Update register states.
794       if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
795     }
796
797     // If we have evenly matched pairs of frame setup / destroy instructions,
798     // make sure the adjustments come out to zero. If we don't have matched
799     // pairs, we can't be sure the missing bit isn't in another basic block
800     // due to a custom inserter playing tricks, so just asserting SPAdj==0
801     // isn't sufficient. See tMOVCC on Thumb1, for example.
802     assert((SPAdjCount || SPAdj == 0) &&
803            "Unbalanced call frame setup / destroy pairs?");
804   }
805 }
806
807 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
808 /// with physical registers. Use the register scavenger to find an
809 /// appropriate register to use.
810 ///
811 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
812 /// iterate over the vreg use list, which at this point only contains machine
813 /// operands for which eliminateFrameIndex need a new scratch reg.
814 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
815   // Run through the instructions and find any virtual registers.
816   for (MachineFunction::iterator BB = Fn.begin(),
817        E = Fn.end(); BB != E; ++BB) {
818     RS->enterBasicBlock(BB);
819
820     unsigned VirtReg = 0;
821     unsigned ScratchReg = 0;
822     int SPAdj = 0;
823
824     // The instruction stream may change in the loop, so check BB->end()
825     // directly.
826     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
827       MachineInstr *MI = I;
828       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
829         if (MI->getOperand(i).isReg()) {
830           MachineOperand &MO = MI->getOperand(i);
831           unsigned Reg = MO.getReg();
832           if (Reg == 0)
833             continue;
834           if (!TargetRegisterInfo::isVirtualRegister(Reg))
835             continue;
836
837           ++NumVirtualFrameRegs;
838
839           // Have we already allocated a scratch register for this virtual?
840           if (Reg != VirtReg) {
841             // When we first encounter a new virtual register, it
842             // must be a definition.
843             assert(MI->getOperand(i).isDef() &&
844                    "frame index virtual missing def!");
845             // Scavenge a new scratch register
846             VirtReg = Reg;
847             const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
848             ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
849             ++NumScavengedRegs;
850           }
851           // Replace this reference to the virtual register with the
852           // scratch register.
853           assert (ScratchReg && "Missing scratch register!");
854           MI->getOperand(i).setReg(ScratchReg);
855
856         }
857       }
858       RS->forward(I);
859       ++I;
860     }
861   }
862 }