PrologEpilogInserter.cpp revision 60f445031000f4a264412387932fce0de1000f00
1//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass is responsible for finalizing the functions frame layout, saving
11// callee saved registers, and for emitting prolog & epilog code for the
12// function.
13//
14// This pass must be run after register allocation.  After this pass is
15// executed, it is illegal to construct MO_FrameIndex operands.
16//
17// This pass provides an optional shrink wrapping variant of prolog/epilog
18// insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp.
19//
20//===----------------------------------------------------------------------===//
21
22#include "PrologEpilogInserter.h"
23#include "llvm/CodeGen/MachineDominators.h"
24#include "llvm/CodeGen/MachineLoopInfo.h"
25#include "llvm/CodeGen/MachineInstr.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineModuleInfo.h"
28#include "llvm/CodeGen/MachineRegisterInfo.h"
29#include "llvm/CodeGen/RegisterScavenging.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetRegisterInfo.h"
32#include "llvm/Target/TargetFrameInfo.h"
33#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/ADT/IndexedMap.h"
37#include "llvm/ADT/STLExtras.h"
38#include <climits>
39
40using namespace llvm;
41
42char PEI::ID = 0;
43
44static RegisterPass<PEI>
45X("prologepilog", "Prologue/Epilogue Insertion");
46
47/// createPrologEpilogCodeInserter - This function returns a pass that inserts
48/// prolog and epilog code, and eliminates abstract frame references.
49///
50FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
51
52/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
53/// frame indexes with appropriate references.
54///
55bool PEI::runOnMachineFunction(MachineFunction &Fn) {
56  const Function* F = Fn.getFunction();
57  const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
58  RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
59  FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
60
61  // Get MachineModuleInfo so that we can track the construction of the
62  // frame.
63  if (MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>())
64    Fn.getFrameInfo()->setMachineModuleInfo(MMI);
65
66  // Calculate the MaxCallFrameSize and HasCalls variables for the function's
67  // frame information. Also eliminates call frame pseudo instructions.
68  calculateCallsInformation(Fn);
69
70  // Allow the target machine to make some adjustments to the function
71  // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
72  TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
73
74  // Scan the function for modified callee saved registers and insert spill code
75  // for any callee saved registers that are modified.
76  calculateCalleeSavedRegisters(Fn);
77
78  // Determine placement of CSR spill/restore code:
79  //  - with shrink wrapping, place spills and restores to tightly
80  //    enclose regions in the Machine CFG of the function where
81  //    they are used. Without shrink wrapping
82  //  - default (no shrink wrapping), place all spills in the
83  //    entry block, all restores in return blocks.
84  placeCSRSpillsAndRestores(Fn);
85
86  // Add the code to save and restore the callee saved registers
87  if (!F->hasFnAttr(Attribute::Naked))
88    insertCSRSpillsAndRestores(Fn);
89
90  // Allow the target machine to make final modifications to the function
91  // before the frame layout is finalized.
92  TRI->processFunctionBeforeFrameFinalized(Fn);
93
94  // Calculate actual frame offsets for all abstract stack objects...
95  calculateFrameObjectOffsets(Fn);
96
97  // Add prolog and epilog code to the function.  This function is required
98  // to align the stack frame as necessary for any stack variables or
99  // called functions.  Because of this, calculateCalleeSavedRegisters
100  // must be called before this function in order to set the HasCalls
101  // and MaxCallFrameSize variables.
102  if (!F->hasFnAttr(Attribute::Naked))
103    insertPrologEpilogCode(Fn);
104
105  // Replace all MO_FrameIndex operands with physical register references
106  // and actual offsets.
107  //
108  replaceFrameIndices(Fn);
109
110  // If register scavenging is needed, as we've enabled doing it as a
111  // post-pass, scavenge the virtual registers that frame index elimiation
112  // inserted.
113  if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
114    scavengeFrameVirtualRegs(Fn);
115
116  delete RS;
117  clearAllSets();
118  return true;
119}
120
121#if 0
122void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
123  AU.setPreservesCFG();
124  if (ShrinkWrapping || ShrinkWrapFunc != "") {
125    AU.addRequired<MachineLoopInfo>();
126    AU.addRequired<MachineDominatorTree>();
127  }
128  AU.addPreserved<MachineLoopInfo>();
129  AU.addPreserved<MachineDominatorTree>();
130  MachineFunctionPass::getAnalysisUsage(AU);
131}
132#endif
133
134/// calculateCallsInformation - Calculate the MaxCallFrameSize and HasCalls
135/// variables for the function's frame information and eliminate call frame
136/// pseudo instructions.
137void PEI::calculateCallsInformation(MachineFunction &Fn) {
138  const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
139  MachineFrameInfo *FFI = Fn.getFrameInfo();
140
141  unsigned MaxCallFrameSize = 0;
142  bool HasCalls = FFI->hasCalls();
143
144  // Get the function call frame set-up and tear-down instruction opcode
145  int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
146  int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
147
148  // Early exit for targets which have no call frame setup/destroy pseudo
149  // instructions.
150  if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
151    return;
152
153  std::vector<MachineBasicBlock::iterator> FrameSDOps;
154  for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
155    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
156      if (I->getOpcode() == FrameSetupOpcode ||
157          I->getOpcode() == FrameDestroyOpcode) {
158        assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
159               " instructions should have a single immediate argument!");
160        unsigned Size = I->getOperand(0).getImm();
161        if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
162        HasCalls = true;
163        FrameSDOps.push_back(I);
164      } else if (I->isInlineAsm()) {
165        // An InlineAsm might be a call; assume it is to get the stack frame
166        // aligned correctly for calls.
167        HasCalls = true;
168      }
169
170  FFI->setHasCalls(HasCalls);
171  FFI->setMaxCallFrameSize(MaxCallFrameSize);
172
173  for (std::vector<MachineBasicBlock::iterator>::iterator
174         i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
175    MachineBasicBlock::iterator I = *i;
176
177    // If call frames are not being included as part of the stack frame, and
178    // the target doesn't indicate otherwise, remove the call frame pseudos
179    // here. The sub/add sp instruction pairs are still inserted, but we don't
180    // need to track the SP adjustment for frame index elimination.
181    if (RegInfo->canSimplifyCallFramePseudos(Fn))
182      RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
183  }
184}
185
186
187/// calculateCalleeSavedRegisters - Scan the function for modified callee saved
188/// registers.
189void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
190  const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
191  const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
192  MachineFrameInfo *FFI = Fn.getFrameInfo();
193
194  // Get the callee saved register list...
195  const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
196
197  // These are used to keep track the callee-save area. Initialize them.
198  MinCSFrameIndex = INT_MAX;
199  MaxCSFrameIndex = 0;
200
201  // Early exit for targets which have no callee saved registers.
202  if (CSRegs == 0 || CSRegs[0] == 0)
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 = FFI->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 = FFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset,
269                                        true, false);
270    }
271
272    I->setFrameIdx(FrameIdx);
273  }
274
275  FFI->setCalleeSavedInfo(CSI);
276}
277
278/// insertCSRSpillsAndRestores - Insert spill and restore code for
279/// callee saved registers used in the function, handling shrink wrapping.
280///
281void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
282  // Get callee saved register information.
283  MachineFrameInfo *FFI = Fn.getFrameInfo();
284  const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
285
286  FFI->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  MachineBasicBlock::iterator I;
294
295  if (! ShrinkWrapThisFunction) {
296    // Spill using target interface.
297    I = EntryBlock->begin();
298    if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI)) {
299      for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
300        // Add the callee-saved register as live-in.
301        // It's killed at the spill.
302        EntryBlock->addLiveIn(CSI[i].getReg());
303
304        // Insert the spill to the stack frame.
305        TII.storeRegToStackSlot(*EntryBlock, I, CSI[i].getReg(), true,
306                                CSI[i].getFrameIdx(), CSI[i].getRegClass());
307      }
308    }
309
310    // Restore using target interface.
311    for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
312      MachineBasicBlock* MBB = ReturnBlocks[ri];
313      I = MBB->end(); --I;
314
315      // Skip over all terminator instructions, which are part of the return
316      // sequence.
317      MachineBasicBlock::iterator I2 = I;
318      while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
319        I = I2;
320
321      bool AtStart = I == MBB->begin();
322      MachineBasicBlock::iterator BeforeI = I;
323      if (!AtStart)
324        --BeforeI;
325
326      // Restore all registers immediately before the return and any
327      // terminators that preceed it.
328      if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI)) {
329        for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
330          TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
331                                   CSI[i].getFrameIdx(),
332                                   CSI[i].getRegClass());
333          assert(I != MBB->begin() &&
334                 "loadRegFromStackSlot didn't insert any code!");
335          // Insert in reverse order.  loadRegFromStackSlot can insert
336          // multiple instructions.
337          if (AtStart)
338            I = MBB->begin();
339          else {
340            I = BeforeI;
341            ++I;
342          }
343        }
344      }
345    }
346    return;
347  }
348
349  // Insert spills.
350  std::vector<CalleeSavedInfo> blockCSI;
351  for (CSRegBlockMap::iterator BI = CSRSave.begin(),
352         BE = CSRSave.end(); BI != BE; ++BI) {
353    MachineBasicBlock* MBB = BI->first;
354    CSRegSet save = BI->second;
355
356    if (save.empty())
357      continue;
358
359    blockCSI.clear();
360    for (CSRegSet::iterator RI = save.begin(),
361           RE = save.end(); RI != RE; ++RI) {
362      blockCSI.push_back(CSI[*RI]);
363    }
364    assert(blockCSI.size() > 0 &&
365           "Could not collect callee saved register info");
366
367    I = MBB->begin();
368
369    // When shrink wrapping, use stack slot stores/loads.
370    for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
371      // Add the callee-saved register as live-in.
372      // It's killed at the spill.
373      MBB->addLiveIn(blockCSI[i].getReg());
374
375      // Insert the spill to the stack frame.
376      TII.storeRegToStackSlot(*MBB, I, blockCSI[i].getReg(),
377                              true,
378                              blockCSI[i].getFrameIdx(),
379                              blockCSI[i].getRegClass());
380    }
381  }
382
383  for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
384         BE = CSRRestore.end(); BI != BE; ++BI) {
385    MachineBasicBlock* MBB = BI->first;
386    CSRegSet restore = BI->second;
387
388    if (restore.empty())
389      continue;
390
391    blockCSI.clear();
392    for (CSRegSet::iterator RI = restore.begin(),
393           RE = restore.end(); RI != RE; ++RI) {
394      blockCSI.push_back(CSI[*RI]);
395    }
396    assert(blockCSI.size() > 0 &&
397           "Could not find callee saved register info");
398
399    // If MBB is empty and needs restores, insert at the _beginning_.
400    if (MBB->empty()) {
401      I = MBB->begin();
402    } else {
403      I = MBB->end();
404      --I;
405
406      // Skip over all terminator instructions, which are part of the
407      // return sequence.
408      if (! I->getDesc().isTerminator()) {
409        ++I;
410      } else {
411        MachineBasicBlock::iterator I2 = I;
412        while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
413          I = I2;
414      }
415    }
416
417    bool AtStart = I == MBB->begin();
418    MachineBasicBlock::iterator BeforeI = I;
419    if (!AtStart)
420      --BeforeI;
421
422    // Restore all registers immediately before the return and any
423    // terminators that preceed it.
424    for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
425      TII.loadRegFromStackSlot(*MBB, I, blockCSI[i].getReg(),
426                               blockCSI[i].getFrameIdx(),
427                               blockCSI[i].getRegClass());
428      assert(I != MBB->begin() &&
429             "loadRegFromStackSlot didn't insert any code!");
430      // Insert in reverse order.  loadRegFromStackSlot can insert
431      // multiple instructions.
432      if (AtStart)
433        I = MBB->begin();
434      else {
435        I = BeforeI;
436        ++I;
437      }
438    }
439  }
440}
441
442/// AdjustStackOffset - Helper function used to adjust the stack frame offset.
443static inline void
444AdjustStackOffset(MachineFrameInfo *FFI, int FrameIdx,
445                  bool StackGrowsDown, int64_t &Offset,
446                  unsigned &MaxAlign) {
447  // If the stack grows down, add the object size to find the lowest address.
448  if (StackGrowsDown)
449    Offset += FFI->getObjectSize(FrameIdx);
450
451  unsigned Align = FFI->getObjectAlignment(FrameIdx);
452
453  // If the alignment of this object is greater than that of the stack, then
454  // increase the stack alignment to match.
455  MaxAlign = std::max(MaxAlign, Align);
456
457  // Adjust to alignment boundary.
458  Offset = (Offset + Align - 1) / Align * Align;
459
460  if (StackGrowsDown) {
461    FFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
462  } else {
463    FFI->setObjectOffset(FrameIdx, Offset);
464    Offset += FFI->getObjectSize(FrameIdx);
465  }
466}
467
468/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
469/// abstract stack objects.
470///
471void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
472  const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
473
474  bool StackGrowsDown =
475    TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
476
477  // Loop over all of the stack objects, assigning sequential addresses...
478  MachineFrameInfo *FFI = Fn.getFrameInfo();
479
480  // Start at the beginning of the local area.
481  // The Offset is the distance from the stack top in the direction
482  // of stack growth -- so it's always nonnegative.
483  int LocalAreaOffset = TFI.getOffsetOfLocalArea();
484  if (StackGrowsDown)
485    LocalAreaOffset = -LocalAreaOffset;
486  assert(LocalAreaOffset >= 0
487         && "Local area offset should be in direction of stack growth");
488  int64_t Offset = LocalAreaOffset;
489
490  // If there are fixed sized objects that are preallocated in the local area,
491  // non-fixed objects can't be allocated right at the start of local area.
492  // We currently don't support filling in holes in between fixed sized
493  // objects, so we adjust 'Offset' to point to the end of last fixed sized
494  // preallocated object.
495  for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
496    int64_t FixedOff;
497    if (StackGrowsDown) {
498      // The maximum distance from the stack pointer is at lower address of
499      // the object -- which is given by offset. For down growing stack
500      // the offset is negative, so we negate the offset to get the distance.
501      FixedOff = -FFI->getObjectOffset(i);
502    } else {
503      // The maximum distance from the start pointer is at the upper
504      // address of the object.
505      FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
506    }
507    if (FixedOff > Offset) Offset = FixedOff;
508  }
509
510  // First assign frame offsets to stack objects that are used to spill
511  // callee saved registers.
512  if (StackGrowsDown) {
513    for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
514      // If stack grows down, we need to add size of find the lowest
515      // address of the object.
516      Offset += FFI->getObjectSize(i);
517
518      unsigned Align = FFI->getObjectAlignment(i);
519      // Adjust to alignment boundary
520      Offset = (Offset+Align-1)/Align*Align;
521
522      FFI->setObjectOffset(i, -Offset);        // Set the computed offset
523    }
524  } else {
525    int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
526    for (int i = MaxCSFI; i >= MinCSFI ; --i) {
527      unsigned Align = FFI->getObjectAlignment(i);
528      // Adjust to alignment boundary
529      Offset = (Offset+Align-1)/Align*Align;
530
531      FFI->setObjectOffset(i, Offset);
532      Offset += FFI->getObjectSize(i);
533    }
534  }
535
536  unsigned MaxAlign = FFI->getMaxAlignment();
537
538  // Make sure the special register scavenging spill slot is closest to the
539  // frame pointer if a frame pointer is required.
540  const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
541  if (RS && RegInfo->hasFP(Fn) && !RegInfo->needsStackRealignment(Fn)) {
542    int SFI = RS->getScavengingFrameIndex();
543    if (SFI >= 0)
544      AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
545  }
546
547  // Make sure that the stack protector comes before the local variables on the
548  // stack.
549  if (FFI->getStackProtectorIndex() >= 0)
550    AdjustStackOffset(FFI, FFI->getStackProtectorIndex(), StackGrowsDown,
551                      Offset, MaxAlign);
552
553  // Then assign frame offsets to stack objects that are not used to spill
554  // callee saved registers.
555  for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
556    if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
557      continue;
558    if (RS && (int)i == RS->getScavengingFrameIndex())
559      continue;
560    if (FFI->isDeadObjectIndex(i))
561      continue;
562    if (FFI->getStackProtectorIndex() == (int)i)
563      continue;
564
565    AdjustStackOffset(FFI, i, StackGrowsDown, Offset, MaxAlign);
566  }
567
568  // Make sure the special register scavenging spill slot is closest to the
569  // stack pointer.
570  if (RS && (!RegInfo->hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) {
571    int SFI = RS->getScavengingFrameIndex();
572    if (SFI >= 0)
573      AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
574  }
575
576  if (!RegInfo->targetHandlesStackFrameRounding()) {
577    // If we have reserved argument space for call sites in the function
578    // immediately on entry to the current function, count it as part of the
579    // overall stack size.
580    if (FFI->hasCalls() && RegInfo->hasReservedCallFrame(Fn))
581      Offset += FFI->getMaxCallFrameSize();
582
583    // Round up the size to a multiple of the alignment.  If the function has
584    // any calls or alloca's, align to the target's StackAlignment value to
585    // ensure that the callee's frame or the alloca data is suitably aligned;
586    // otherwise, for leaf functions, align to the TransientStackAlignment
587    // value.
588    unsigned StackAlign;
589    if (FFI->hasCalls() || FFI->hasVarSizedObjects() ||
590        (RegInfo->needsStackRealignment(Fn) && FFI->getObjectIndexEnd() != 0))
591      StackAlign = TFI.getStackAlignment();
592    else
593      StackAlign = TFI.getTransientStackAlignment();
594    // If the frame pointer is eliminated, all frame offsets will be relative
595    // to SP not FP; align to MaxAlign so this works.
596    StackAlign = std::max(StackAlign, MaxAlign);
597    unsigned AlignMask = StackAlign - 1;
598    Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
599  }
600
601  // Update frame info to pretend that this is part of the stack...
602  FFI->setStackSize(Offset - LocalAreaOffset);
603}
604
605
606/// insertPrologEpilogCode - Scan the function for modified callee saved
607/// registers, insert spill code for these callee saved registers, then add
608/// prolog and epilog code to the function.
609///
610void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
611  const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
612
613  // Add prologue to the function...
614  TRI->emitPrologue(Fn);
615
616  // Add epilogue to restore the callee-save registers in each exiting block
617  for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
618    // If last instruction is a return instruction, add an epilogue
619    if (!I->empty() && I->back().getDesc().isReturn())
620      TRI->emitEpilogue(Fn, *I);
621  }
622}
623
624
625/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
626/// register references and actual offsets.
627///
628void 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          int 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.
721static MachineBasicBlock::iterator
722findLastUseReg(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.
754void 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    int PrevValue = 0;
768    MachineInstr *PrevLastUseMI = NULL;
769    unsigned PrevLastUseOp = 0;
770    bool trackingCurrentValue = false;
771    int SPAdj = 0;
772    int Value = 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 = Value = 0;
831
832            // If the scratch register from the last allocation is still
833            // available, see if the value matches. If it does, just re-use it.
834            if (trackingCurrentValue && havePrevValue && PrevValue == Value) {
835              // FIXME: This assumes that the instructions in the live range
836              // for the virtual register are exclusively for the purpose
837              // of populating the value in the register. That's reasonable
838              // for these frame index registers, but it's still a very, very
839              // strong assumption. rdar://7322732. Better would be to
840              // explicitly check each instruction in the range for references
841              // to the virtual register. Only delete those insns that
842              // touch the virtual register.
843
844              // Find the last use of the new virtual register. Remove all
845              // instruction between here and there, and update the current
846              // instruction to reference the last use insn instead.
847              MachineBasicBlock::iterator LastUseMI =
848                findLastUseReg(I, BB->end(), Reg);
849
850              // Remove all instructions up 'til the last use, since they're
851              // just calculating the value we already have.
852              BB->erase(I, LastUseMI);
853              I = LastUseMI;
854
855              // Extend the live range of the scratch register
856              PrevLastUseMI->getOperand(PrevLastUseOp).setIsKill(false);
857              RS->setUsed(CurrentScratchReg);
858              CurrentVirtReg = Reg;
859
860              // We deleted the instruction we were scanning the operands of.
861              // Jump back to the instruction iterator loop. Don't increment
862              // past this instruction since we updated the iterator already.
863              DoIncr = false;
864              break;
865            }
866
867            // Scavenge a new scratch register
868            CurrentVirtReg = Reg;
869            const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
870            CurrentScratchReg = RS->FindUnusedReg(RC);
871            if (CurrentScratchReg == 0)
872              // No register is "free". Scavenge a register.
873              CurrentScratchReg = RS->scavengeRegister(RC, I, SPAdj);
874
875            PrevValue = Value;
876          }
877          // replace this reference to the virtual register with the
878          // scratch register.
879          assert (CurrentScratchReg && "Missing scratch register!");
880          MI->getOperand(i).setReg(CurrentScratchReg);
881
882          if (MI->getOperand(i).isKill()) {
883            isKillInsn = true;
884            PrevLastUseOp = i;
885            PrevLastUseMI = MI;
886          }
887        }
888      }
889      // If this is the last use of the scratch, stop tracking it. The
890      // last use will be a kill operand in an instruction that does
891      // not also define the scratch register.
892      if (isKillInsn && !isDefInsn) {
893        CurrentVirtReg = 0;
894        havePrevValue = trackingCurrentValue;
895      }
896      // Similarly, notice if instruction clobbered the value in the
897      // register we're tracking for possible later reuse. This is noted
898      // above, but enforced here since the value is still live while we
899      // process the rest of the operands of the instruction.
900      if (clobbersScratchReg) {
901        havePrevValue = false;
902        CurrentScratchReg = 0;
903      }
904      if (DoIncr) {
905        RS->forward(I);
906        ++I;
907      }
908    }
909  }
910}
911