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