Rename "HasCalls" in MachineFrameInfo to "AdjustsStack" to better describe what
[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/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetFrameInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/ADT/IndexedMap.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include <climits>
38
39 using namespace llvm;
40
41 char PEI::ID = 0;
42
43 static RegisterPass<PEI>
44 X("prologepilog", "Prologue/Epilogue Insertion");
45
46 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
47 /// prolog and epilog code, and eliminates abstract frame references.
48 ///
49 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
50
51 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
52 /// frame indexes with appropriate references.
53 ///
54 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
55   const Function* F = Fn.getFunction();
56   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
57   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
58   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
59   FrameConstantRegMap.clear();
60
61   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
62   // function's frame information. Also eliminates call frame pseudo
63   // instructions.
64   calculateCallsInformation(Fn);
65
66   // Allow the target machine to make some adjustments to the function
67   // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
68   TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
69
70   // Scan the function for modified callee saved registers and insert spill code
71   // for any callee saved registers that are modified.
72   calculateCalleeSavedRegisters(Fn);
73
74   // Determine placement of CSR spill/restore code:
75   //  - with shrink wrapping, place spills and restores to tightly
76   //    enclose regions in the Machine CFG of the function where
77   //    they are used. Without shrink wrapping
78   //  - default (no shrink wrapping), place all spills in the
79   //    entry block, all restores in return blocks.
80   placeCSRSpillsAndRestores(Fn);
81
82   // Add the code to save and restore the callee saved registers
83   if (!F->hasFnAttr(Attribute::Naked))
84     insertCSRSpillsAndRestores(Fn);
85
86   // Allow the target machine to make final modifications to the function
87   // before the frame layout is finalized.
88   TRI->processFunctionBeforeFrameFinalized(Fn);
89
90   // Calculate actual frame offsets for all abstract stack objects...
91   calculateFrameObjectOffsets(Fn);
92
93   // Add prolog and epilog code to the function.  This function is required
94   // to align the stack frame as necessary for any stack variables or
95   // called functions.  Because of this, calculateCalleeSavedRegisters()
96   // must be called before this function in order to set the AdjustsStack
97   // and MaxCallFrameSize variables.
98   if (!F->hasFnAttr(Attribute::Naked))
99     insertPrologEpilogCode(Fn);
100
101   // Replace all MO_FrameIndex operands with physical register references
102   // and actual offsets.
103   //
104   replaceFrameIndices(Fn);
105
106   // If register scavenging is needed, as we've enabled doing it as a
107   // post-pass, scavenge the virtual registers that frame index elimiation
108   // inserted.
109   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
110     scavengeFrameVirtualRegs(Fn);
111
112   delete RS;
113   clearAllSets();
114   return true;
115 }
116
117 #if 0
118 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
119   AU.setPreservesCFG();
120   if (ShrinkWrapping || ShrinkWrapFunc != "") {
121     AU.addRequired<MachineLoopInfo>();
122     AU.addRequired<MachineDominatorTree>();
123   }
124   AU.addPreserved<MachineLoopInfo>();
125   AU.addPreserved<MachineDominatorTree>();
126   MachineFunctionPass::getAnalysisUsage(AU);
127 }
128 #endif
129
130 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
131 /// variables for the function's frame information and eliminate call frame
132 /// pseudo instructions.
133 void PEI::calculateCallsInformation(MachineFunction &Fn) {
134   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
135   MachineFrameInfo *MFI = Fn.getFrameInfo();
136
137   unsigned MaxCallFrameSize = 0;
138   bool AdjustsStack = MFI->adjustsStack();
139
140   // Get the function call frame set-up and tear-down instruction opcode
141   int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
142   int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
143
144   // Early exit for targets which have no call frame setup/destroy pseudo
145   // instructions.
146   if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
147     return;
148
149   std::vector<MachineBasicBlock::iterator> FrameSDOps;
150   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
151     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
152       if (I->getOpcode() == FrameSetupOpcode ||
153           I->getOpcode() == FrameDestroyOpcode) {
154         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
155                " instructions should have a single immediate argument!");
156         unsigned Size = I->getOperand(0).getImm();
157         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
158         AdjustsStack = true;
159         FrameSDOps.push_back(I);
160       } else if (I->isInlineAsm()) {
161         // An InlineAsm might be a call; assume it is to get the stack frame
162         // aligned correctly for calls.
163         AdjustsStack = true;
164       }
165
166   MFI->setAdjustsStack(AdjustsStack);
167   MFI->setMaxCallFrameSize(MaxCallFrameSize);
168
169   for (std::vector<MachineBasicBlock::iterator>::iterator
170          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
171     MachineBasicBlock::iterator I = *i;
172
173     // If call frames are not being included as part of the stack frame, and
174     // the target doesn't indicate otherwise, remove the call frame pseudos
175     // here. The sub/add sp instruction pairs are still inserted, but we don't
176     // need to track the SP adjustment for frame index elimination.
177     if (RegInfo->canSimplifyCallFramePseudos(Fn))
178       RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
179   }
180 }
181
182
183 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
184 /// registers.
185 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
186   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
187   const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
188   MachineFrameInfo *MFI = Fn.getFrameInfo();
189
190   // Get the callee saved register list...
191   const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
192
193   // These are used to keep track the callee-save area. Initialize them.
194   MinCSFrameIndex = INT_MAX;
195   MaxCSFrameIndex = 0;
196
197   // Early exit for targets which have no callee saved registers.
198   if (CSRegs == 0 || CSRegs[0] == 0)
199     return;
200
201   // In Naked functions we aren't going to save any registers.
202   if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
203     return;
204
205   // Figure out which *callee saved* registers are modified by the current
206   // function, thus needing to be saved and restored in the prolog/epilog.
207   const TargetRegisterClass * const *CSRegClasses =
208     RegInfo->getCalleeSavedRegClasses(&Fn);
209
210   std::vector<CalleeSavedInfo> CSI;
211   for (unsigned i = 0; CSRegs[i]; ++i) {
212     unsigned Reg = CSRegs[i];
213     if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
214       // If the reg is modified, save it!
215       CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
216     } else {
217       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
218            *AliasSet; ++AliasSet) {  // Check alias registers too.
219         if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
220           CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
221           break;
222         }
223       }
224     }
225   }
226
227   if (CSI.empty())
228     return;   // Early exit if no callee saved registers are modified!
229
230   unsigned NumFixedSpillSlots;
231   const TargetFrameInfo::SpillSlot *FixedSpillSlots =
232     TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
233
234   // Now that we know which registers need to be saved and restored, allocate
235   // stack slots for them.
236   for (std::vector<CalleeSavedInfo>::iterator
237          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
238     unsigned Reg = I->getReg();
239     const TargetRegisterClass *RC = I->getRegClass();
240
241     int FrameIdx;
242     if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
243       I->setFrameIdx(FrameIdx);
244       continue;
245     }
246
247     // Check to see if this physreg must be spilled to a particular stack slot
248     // on this target.
249     const TargetFrameInfo::SpillSlot *FixedSlot = FixedSpillSlots;
250     while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
251            FixedSlot->Reg != Reg)
252       ++FixedSlot;
253
254     if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
255       // Nope, just spill it anywhere convenient.
256       unsigned Align = RC->getAlignment();
257       unsigned StackAlign = TFI->getStackAlignment();
258
259       // We may not be able to satisfy the desired alignment specification of
260       // the TargetRegisterClass if the stack alignment is smaller. Use the
261       // min.
262       Align = std::min(Align, StackAlign);
263       FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
264       if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
265       if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
266     } else {
267       // Spill it to the stack where we must.
268       FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset,
269                                         true, false);
270     }
271
272     I->setFrameIdx(FrameIdx);
273   }
274
275   MFI->setCalleeSavedInfo(CSI);
276 }
277
278 /// insertCSRSpillsAndRestores - Insert spill and restore code for
279 /// callee saved registers used in the function, handling shrink wrapping.
280 ///
281 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
282   // Get callee saved register information.
283   MachineFrameInfo *MFI = Fn.getFrameInfo();
284   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
285
286   MFI->setCalleeSavedInfoValid(true);
287
288   // Early exit if no callee saved registers are modified!
289   if (CSI.empty())
290     return;
291
292   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
293   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
294   MachineBasicBlock::iterator I;
295
296   if (! ShrinkWrapThisFunction) {
297     // Spill using target interface.
298     I = EntryBlock->begin();
299     if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI)) {
300       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
301         // Add the callee-saved register as live-in.
302         // It's killed at the spill.
303         EntryBlock->addLiveIn(CSI[i].getReg());
304
305         // Insert the spill to the stack frame.
306         TII.storeRegToStackSlot(*EntryBlock, I, CSI[i].getReg(), true,
307                                 CSI[i].getFrameIdx(), CSI[i].getRegClass(),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)->getDesc().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 preceed it.
329       if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI)) {
330         for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
331           TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
332                                    CSI[i].getFrameIdx(),
333                                    CSI[i].getRegClass(), TRI);
334           assert(I != MBB->begin() &&
335                  "loadRegFromStackSlot didn't insert any code!");
336           // Insert in reverse order.  loadRegFromStackSlot can insert
337           // multiple instructions.
338           if (AtStart)
339             I = MBB->begin();
340           else {
341             I = BeforeI;
342             ++I;
343           }
344         }
345       }
346     }
347     return;
348   }
349
350   // Insert spills.
351   std::vector<CalleeSavedInfo> blockCSI;
352   for (CSRegBlockMap::iterator BI = CSRSave.begin(),
353          BE = CSRSave.end(); BI != BE; ++BI) {
354     MachineBasicBlock* MBB = BI->first;
355     CSRegSet save = BI->second;
356
357     if (save.empty())
358       continue;
359
360     blockCSI.clear();
361     for (CSRegSet::iterator RI = save.begin(),
362            RE = save.end(); RI != RE; ++RI) {
363       blockCSI.push_back(CSI[*RI]);
364     }
365     assert(blockCSI.size() > 0 &&
366            "Could not collect callee saved register info");
367
368     I = MBB->begin();
369
370     // When shrink wrapping, use stack slot stores/loads.
371     for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
372       // Add the callee-saved register as live-in.
373       // It's killed at the spill.
374       MBB->addLiveIn(blockCSI[i].getReg());
375
376       // Insert the spill to the stack frame.
377       TII.storeRegToStackSlot(*MBB, I, blockCSI[i].getReg(),
378                               true,
379                               blockCSI[i].getFrameIdx(),
380                               blockCSI[i].getRegClass(), TRI);
381     }
382   }
383
384   for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
385          BE = CSRRestore.end(); BI != BE; ++BI) {
386     MachineBasicBlock* MBB = BI->first;
387     CSRegSet restore = BI->second;
388
389     if (restore.empty())
390       continue;
391
392     blockCSI.clear();
393     for (CSRegSet::iterator RI = restore.begin(),
394            RE = restore.end(); RI != RE; ++RI) {
395       blockCSI.push_back(CSI[*RI]);
396     }
397     assert(blockCSI.size() > 0 &&
398            "Could not find callee saved register info");
399
400     // If MBB is empty and needs restores, insert at the _beginning_.
401     if (MBB->empty()) {
402       I = MBB->begin();
403     } else {
404       I = MBB->end();
405       --I;
406
407       // Skip over all terminator instructions, which are part of the
408       // return sequence.
409       if (! I->getDesc().isTerminator()) {
410         ++I;
411       } else {
412         MachineBasicBlock::iterator I2 = I;
413         while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
414           I = I2;
415       }
416     }
417
418     bool AtStart = I == MBB->begin();
419     MachineBasicBlock::iterator BeforeI = I;
420     if (!AtStart)
421       --BeforeI;
422
423     // Restore all registers immediately before the return and any
424     // terminators that preceed it.
425     for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
426       TII.loadRegFromStackSlot(*MBB, I, blockCSI[i].getReg(),
427                                blockCSI[i].getFrameIdx(),
428                                blockCSI[i].getRegClass(), TRI);
429       assert(I != MBB->begin() &&
430              "loadRegFromStackSlot didn't insert any code!");
431       // Insert in reverse order.  loadRegFromStackSlot can insert
432       // multiple instructions.
433       if (AtStart)
434         I = MBB->begin();
435       else {
436         I = BeforeI;
437         ++I;
438       }
439     }
440   }
441 }
442
443 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
444 static inline void
445 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
446                   bool StackGrowsDown, int64_t &Offset,
447                   unsigned &MaxAlign) {
448   // If the stack grows down, add the object size to find the lowest address.
449   if (StackGrowsDown)
450     Offset += MFI->getObjectSize(FrameIdx);
451
452   unsigned Align = MFI->getObjectAlignment(FrameIdx);
453
454   // If the alignment of this object is greater than that of the stack, then
455   // increase the stack alignment to match.
456   MaxAlign = std::max(MaxAlign, Align);
457
458   // Adjust to alignment boundary.
459   Offset = (Offset + Align - 1) / Align * Align;
460
461   if (StackGrowsDown) {
462     MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
463   } else {
464     MFI->setObjectOffset(FrameIdx, Offset);
465     Offset += MFI->getObjectSize(FrameIdx);
466   }
467 }
468
469 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
470 /// abstract stack objects.
471 ///
472 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
473   const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
474
475   bool StackGrowsDown =
476     TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
477
478   // Loop over all of the stack objects, assigning sequential addresses...
479   MachineFrameInfo *MFI = Fn.getFrameInfo();
480
481   // Start at the beginning of the local area.
482   // The Offset is the distance from the stack top in the direction
483   // of stack growth -- so it's always nonnegative.
484   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
485   if (StackGrowsDown)
486     LocalAreaOffset = -LocalAreaOffset;
487   assert(LocalAreaOffset >= 0
488          && "Local area offset should be in direction of stack growth");
489   int64_t Offset = LocalAreaOffset;
490
491   // If there are fixed sized objects that are preallocated in the local area,
492   // non-fixed objects can't be allocated right at the start of local area.
493   // We currently don't support filling in holes in between fixed sized
494   // objects, so we adjust 'Offset' to point to the end of last fixed sized
495   // preallocated object.
496   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
497     int64_t FixedOff;
498     if (StackGrowsDown) {
499       // The maximum distance from the stack pointer is at lower address of
500       // the object -- which is given by offset. For down growing stack
501       // the offset is negative, so we negate the offset to get the distance.
502       FixedOff = -MFI->getObjectOffset(i);
503     } else {
504       // The maximum distance from the start pointer is at the upper
505       // address of the object.
506       FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
507     }
508     if (FixedOff > Offset) Offset = FixedOff;
509   }
510
511   // First assign frame offsets to stack objects that are used to spill
512   // callee saved registers.
513   if (StackGrowsDown) {
514     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
515       // If the stack grows down, we need to add the size to find the lowest
516       // address of the object.
517       Offset += MFI->getObjectSize(i);
518
519       unsigned Align = MFI->getObjectAlignment(i);
520       // Adjust to alignment boundary
521       Offset = (Offset+Align-1)/Align*Align;
522
523       MFI->setObjectOffset(i, -Offset);        // Set the computed offset
524     }
525   } else {
526     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
527     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
528       unsigned Align = MFI->getObjectAlignment(i);
529       // Adjust to alignment boundary
530       Offset = (Offset+Align-1)/Align*Align;
531
532       MFI->setObjectOffset(i, Offset);
533       Offset += MFI->getObjectSize(i);
534     }
535   }
536
537   unsigned MaxAlign = MFI->getMaxAlignment();
538
539   // Make sure the special register scavenging spill slot is closest to the
540   // frame pointer if a frame pointer is required.
541   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
542   if (RS && RegInfo->hasFP(Fn) && !RegInfo->needsStackRealignment(Fn)) {
543     int SFI = RS->getScavengingFrameIndex();
544     if (SFI >= 0)
545       AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
546   }
547
548   // Make sure that the stack protector comes before the local variables on the
549   // stack.
550   if (MFI->getStackProtectorIndex() >= 0)
551     AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
552                       Offset, MaxAlign);
553
554   // Then assign frame offsets to stack objects that are not used to spill
555   // callee saved registers.
556   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
557     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
558       continue;
559     if (RS && (int)i == RS->getScavengingFrameIndex())
560       continue;
561     if (MFI->isDeadObjectIndex(i))
562       continue;
563     if (MFI->getStackProtectorIndex() == (int)i)
564       continue;
565
566     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
567   }
568
569   // Make sure the special register scavenging spill slot is closest to the
570   // stack pointer.
571   if (RS && (!RegInfo->hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) {
572     int SFI = RS->getScavengingFrameIndex();
573     if (SFI >= 0)
574       AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
575   }
576
577   if (!RegInfo->targetHandlesStackFrameRounding()) {
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 (MFI->adjustsStack() && RegInfo->hasReservedCallFrame(Fn))
582       Offset += MFI->getMaxCallFrameSize();
583
584     // Round up the size to a multiple of the alignment.  If the function has
585     // any calls or alloca's, align to the target's StackAlignment value to
586     // ensure that the callee's frame or the alloca data is suitably aligned;
587     // otherwise, for leaf functions, align to the TransientStackAlignment
588     // value.
589     unsigned StackAlign;
590     if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
591         (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
592       StackAlign = TFI.getStackAlignment();
593     else
594       StackAlign = TFI.getTransientStackAlignment();
595
596     // If the frame pointer is eliminated, all frame offsets will be relative to
597     // SP not FP. Align to MaxAlign so this works.
598     StackAlign = std::max(StackAlign, MaxAlign);
599     unsigned AlignMask = StackAlign - 1;
600     Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
601   }
602
603   // Update frame info to pretend that this is part of the stack...
604   MFI->setStackSize(Offset - LocalAreaOffset);
605 }
606
607 /// insertPrologEpilogCode - Scan the function for modified callee saved
608 /// registers, insert spill code for these callee saved registers, then add
609 /// prolog and epilog code to the function.
610 ///
611 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
612   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
613
614   // Add prologue to the function...
615   TRI->emitPrologue(Fn);
616
617   // Add epilogue to restore the callee-save registers in each exiting block
618   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
619     // If last instruction is a return instruction, add an epilogue
620     if (!I->empty() && I->back().getDesc().isReturn())
621       TRI->emitEpilogue(Fn, *I);
622   }
623 }
624
625 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
626 /// register references and actual offsets.
627 ///
628 void PEI::replaceFrameIndices(MachineFunction &Fn) {
629   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
630
631   const TargetMachine &TM = Fn.getTarget();
632   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
633   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
634   const TargetFrameInfo *TFI = TM.getFrameInfo();
635   bool StackGrowsDown =
636     TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
637   int FrameSetupOpcode   = TRI.getCallFrameSetupOpcode();
638   int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
639
640   for (MachineFunction::iterator BB = Fn.begin(),
641          E = Fn.end(); BB != E; ++BB) {
642     int SPAdj = 0;  // SP offset due to call frame setup / destroy.
643     if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
644
645     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
646
647       if (I->getOpcode() == FrameSetupOpcode ||
648           I->getOpcode() == FrameDestroyOpcode) {
649         // Remember how much SP has been adjusted to create the call
650         // frame.
651         int Size = I->getOperand(0).getImm();
652
653         if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
654             (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
655           Size = -Size;
656
657         SPAdj += Size;
658
659         MachineBasicBlock::iterator PrevI = BB->end();
660         if (I != BB->begin()) PrevI = prior(I);
661         TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
662
663         // Visit the instructions created by eliminateCallFramePseudoInstr().
664         if (PrevI == BB->end())
665           I = BB->begin();     // The replaced instr was the first in the block.
666         else
667           I = llvm::next(PrevI);
668         continue;
669       }
670
671       MachineInstr *MI = I;
672       bool DoIncr = true;
673       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
674         if (MI->getOperand(i).isFI()) {
675           // Some instructions (e.g. inline asm instructions) can have
676           // multiple frame indices and/or cause eliminateFrameIndex
677           // to insert more than one instruction. We need the register
678           // scavenger to go through all of these instructions so that
679           // it can update its register information. We keep the
680           // iterator at the point before insertion so that we can
681           // revisit them in full.
682           bool AtBeginning = (I == BB->begin());
683           if (!AtBeginning) --I;
684
685           // If this instruction has a FrameIndex operand, we need to
686           // use that target machine register info object to eliminate
687           // it.
688           TargetRegisterInfo::FrameIndexValue Value;
689           unsigned VReg =
690             TRI.eliminateFrameIndex(MI, SPAdj, &Value,
691                                     FrameIndexVirtualScavenging ?  NULL : RS);
692           if (VReg) {
693             assert (FrameIndexVirtualScavenging &&
694                     "Not scavenging, but virtual returned from "
695                     "eliminateFrameIndex()!");
696             FrameConstantRegMap[VReg] = FrameConstantEntry(Value, SPAdj);
697           }
698
699           // Reset the iterator if we were at the beginning of the BB.
700           if (AtBeginning) {
701             I = BB->begin();
702             DoIncr = false;
703           }
704
705           MI = 0;
706           break;
707         }
708
709       if (DoIncr && I != BB->end()) ++I;
710
711       // Update register states.
712       if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
713     }
714
715     assert(SPAdj == 0 && "Unbalanced call frame setup / destroy pairs?");
716   }
717 }
718
719 /// findLastUseReg - find the killing use of the specified register within
720 /// the instruciton range. Return the operand number of the kill in Operand.
721 static MachineBasicBlock::iterator
722 findLastUseReg(MachineBasicBlock::iterator I, MachineBasicBlock::iterator ME,
723                unsigned Reg) {
724   // Scan forward to find the last use of this virtual register
725   for (++I; I != ME; ++I) {
726     MachineInstr *MI = I;
727     bool isDefInsn = false;
728     bool isKillInsn = false;
729     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
730       if (MI->getOperand(i).isReg()) {
731         unsigned OpReg = MI->getOperand(i).getReg();
732         if (OpReg == 0 || !TargetRegisterInfo::isVirtualRegister(OpReg))
733           continue;
734         assert (OpReg == Reg
735                 && "overlapping use of scavenged index register!");
736         // If this is the killing use, we have a candidate.
737         if (MI->getOperand(i).isKill())
738           isKillInsn = true;
739         else if (MI->getOperand(i).isDef())
740           isDefInsn = true;
741       }
742     if (isKillInsn && !isDefInsn)
743       return I;
744   }
745   // If we hit the end of the basic block, there was no kill of
746   // the virtual register, which is wrong.
747   assert (0 && "scavenged index register never killed!");
748   return ME;
749 }
750
751 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
752 /// with physical registers. Use the register scavenger to find an
753 /// appropriate register to use.
754 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
755   // Run through the instructions and find any virtual registers.
756   for (MachineFunction::iterator BB = Fn.begin(),
757        E = Fn.end(); BB != E; ++BB) {
758     RS->enterBasicBlock(BB);
759
760     // FIXME: The logic flow in this function is still too convoluted.
761     // It needs a cleanup refactoring. Do that in preparation for tracking
762     // more than one scratch register value and using ranges to find
763     // available scratch registers.
764     unsigned CurrentVirtReg = 0;
765     unsigned CurrentScratchReg = 0;
766     bool havePrevValue = false;
767     TargetRegisterInfo::FrameIndexValue PrevValue(0,0);
768     TargetRegisterInfo::FrameIndexValue Value(0,0);
769     MachineInstr *PrevLastUseMI = NULL;
770     unsigned PrevLastUseOp = 0;
771     bool trackingCurrentValue = false;
772     int SPAdj = 0;
773
774     // The instruction stream may change in the loop, so check BB->end()
775     // directly.
776     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
777       MachineInstr *MI = I;
778       bool isDefInsn = false;
779       bool isKillInsn = false;
780       bool clobbersScratchReg = false;
781       bool DoIncr = true;
782       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
783         if (MI->getOperand(i).isReg()) {
784           MachineOperand &MO = MI->getOperand(i);
785           unsigned Reg = MO.getReg();
786           if (Reg == 0)
787             continue;
788           if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
789             // If we have a previous scratch reg, check and see if anything
790             // here kills whatever value is in there.
791             if (Reg == CurrentScratchReg) {
792               if (MO.isUse()) {
793                 // Two-address operands implicitly kill
794                 if (MO.isKill() || MI->isRegTiedToDefOperand(i))
795                   clobbersScratchReg = true;
796               } else {
797                 assert (MO.isDef());
798                 clobbersScratchReg = true;
799               }
800             }
801             continue;
802           }
803           // If this is a def, remember that this insn defines the value.
804           // This lets us properly consider insns which re-use the scratch
805           // register, such as r2 = sub r2, #imm, in the middle of the
806           // scratch range.
807           if (MO.isDef())
808             isDefInsn = true;
809
810           // Have we already allocated a scratch register for this virtual?
811           if (Reg != CurrentVirtReg) {
812             // When we first encounter a new virtual register, it
813             // must be a definition.
814             assert(MI->getOperand(i).isDef() &&
815                    "frame index virtual missing def!");
816             // We can't have nested virtual register live ranges because
817             // there's only a guarantee of one scavenged register at a time.
818             assert (CurrentVirtReg == 0 &&
819                     "overlapping frame index virtual registers!");
820
821             // If the target gave us information about what's in the register,
822             // we can use that to re-use scratch regs.
823             DenseMap<unsigned, FrameConstantEntry>::iterator Entry =
824               FrameConstantRegMap.find(Reg);
825             trackingCurrentValue = Entry != FrameConstantRegMap.end();
826             if (trackingCurrentValue) {
827               SPAdj = (*Entry).second.second;
828               Value = (*Entry).second.first;
829             } else {
830               SPAdj = 0;
831               Value.first = 0;
832               Value.second = 0;
833             }
834
835             // If the scratch register from the last allocation is still
836             // available, see if the value matches. If it does, just re-use it.
837             if (trackingCurrentValue && havePrevValue && PrevValue == Value) {
838               // FIXME: This assumes that the instructions in the live range
839               // for the virtual register are exclusively for the purpose
840               // of populating the value in the register. That's reasonable
841               // for these frame index registers, but it's still a very, very
842               // strong assumption. rdar://7322732. Better would be to
843               // explicitly check each instruction in the range for references
844               // to the virtual register. Only delete those insns that
845               // touch the virtual register.
846
847               // Find the last use of the new virtual register. Remove all
848               // instruction between here and there, and update the current
849               // instruction to reference the last use insn instead.
850               MachineBasicBlock::iterator LastUseMI =
851                 findLastUseReg(I, BB->end(), Reg);
852
853               // Remove all instructions up 'til the last use, since they're
854               // just calculating the value we already have.
855               BB->erase(I, LastUseMI);
856               I = LastUseMI;
857
858               // Extend the live range of the scratch register
859               PrevLastUseMI->getOperand(PrevLastUseOp).setIsKill(false);
860               RS->setUsed(CurrentScratchReg);
861               CurrentVirtReg = Reg;
862
863               // We deleted the instruction we were scanning the operands of.
864               // Jump back to the instruction iterator loop. Don't increment
865               // past this instruction since we updated the iterator already.
866               DoIncr = false;
867               break;
868             }
869
870             // Scavenge a new scratch register
871             CurrentVirtReg = Reg;
872             const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
873             CurrentScratchReg = RS->FindUnusedReg(RC);
874             if (CurrentScratchReg == 0)
875               // No register is "free". Scavenge a register.
876               CurrentScratchReg = RS->scavengeRegister(RC, I, SPAdj);
877
878             PrevValue = Value;
879           }
880           // replace this reference to the virtual register with the
881           // scratch register.
882           assert (CurrentScratchReg && "Missing scratch register!");
883           MI->getOperand(i).setReg(CurrentScratchReg);
884
885           if (MI->getOperand(i).isKill()) {
886             isKillInsn = true;
887             PrevLastUseOp = i;
888             PrevLastUseMI = MI;
889           }
890         }
891       }
892       // If this is the last use of the scratch, stop tracking it. The
893       // last use will be a kill operand in an instruction that does
894       // not also define the scratch register.
895       if (isKillInsn && !isDefInsn) {
896         CurrentVirtReg = 0;
897         havePrevValue = trackingCurrentValue;
898       }
899       // Similarly, notice if instruction clobbered the value in the
900       // register we're tracking for possible later reuse. This is noted
901       // above, but enforced here since the value is still live while we
902       // process the rest of the operands of the instruction.
903       if (clobbersScratchReg) {
904         havePrevValue = false;
905         CurrentScratchReg = 0;
906       }
907       if (DoIncr) {
908         RS->forward(I);
909         ++I;
910       }
911     }
912   }
913 }