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