xref: /llvm-project/llvm/lib/CodeGen/PrologEpilogInserter.cpp (revision 1eb473680a3dac9d75f44c2f4799b4cef8465e5f)
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 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/RegisterScavenging.h"
31 #include "llvm/CodeGen/StackProtector.h"
32 #include "llvm/CodeGen/WinEHFuncInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.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 "llvm/Target/TargetSubtargetInfo.h"
44 #include <climits>
45 
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "pei"
49 
50 typedef SmallVector<MachineBasicBlock *, 4> MBBVector;
51 static void doSpillCalleeSavedRegs(MachineFunction &MF, RegScavenger *RS,
52                                    unsigned &MinCSFrameIndex,
53                                    unsigned &MaxCXFrameIndex,
54                                    const MBBVector &SaveBlocks,
55                                    const MBBVector &RestoreBlocks);
56 
57 static void doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS);
58 
59 namespace {
60 class PEI : public MachineFunctionPass {
61 public:
62   static char ID;
63   explicit PEI(const TargetMachine *TM = nullptr) : MachineFunctionPass(ID) {
64     initializePEIPass(*PassRegistry::getPassRegistry());
65 
66     if (TM && (!TM->usesPhysRegsForPEI())) {
67       SpillCalleeSavedRegisters = [](MachineFunction &, RegScavenger *,
68                                      unsigned &, unsigned &, const MBBVector &,
69                                      const MBBVector &) {};
70       ScavengeFrameVirtualRegs = [](MachineFunction &, RegScavenger *) {};
71     } else {
72       SpillCalleeSavedRegisters = doSpillCalleeSavedRegs;
73       ScavengeFrameVirtualRegs = doScavengeFrameVirtualRegs;
74       UsesCalleeSaves = true;
75     }
76   }
77 
78   void getAnalysisUsage(AnalysisUsage &AU) const override;
79 
80   MachineFunctionProperties getRequiredProperties() const override {
81     MachineFunctionProperties MFP;
82     if (UsesCalleeSaves)
83       MFP.set(MachineFunctionProperties::Property::NoVRegs);
84     return MFP;
85   }
86 
87   /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
88   /// frame indexes with appropriate references.
89   ///
90   bool runOnMachineFunction(MachineFunction &Fn) override;
91 
92 private:
93   std::function<void(MachineFunction &MF, RegScavenger *RS,
94                      unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex,
95                      const MBBVector &SaveBlocks,
96                      const MBBVector &RestoreBlocks)>
97       SpillCalleeSavedRegisters;
98   std::function<void(MachineFunction &MF, RegScavenger *RS)>
99       ScavengeFrameVirtualRegs;
100 
101   bool UsesCalleeSaves = false;
102 
103   RegScavenger *RS;
104 
105   // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
106   // stack frame indexes.
107   unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max();
108   unsigned MaxCSFrameIndex = 0;
109 
110   // Save and Restore blocks of the current function. Typically there is a
111   // single save block, unless Windows EH funclets are involved.
112   MBBVector SaveBlocks;
113   MBBVector RestoreBlocks;
114 
115   // Flag to control whether to use the register scavenger to resolve
116   // frame index materialization registers. Set according to
117   // TRI->requiresFrameIndexScavenging() for the current function.
118   bool FrameIndexVirtualScavenging;
119 
120   void calculateCallFrameInfo(MachineFunction &Fn);
121   void calculateSaveRestoreBlocks(MachineFunction &Fn);
122 
123   void calculateFrameObjectOffsets(MachineFunction &Fn);
124   void replaceFrameIndices(MachineFunction &Fn);
125   void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
126                            int &SPAdj);
127   void insertPrologEpilogCode(MachineFunction &Fn);
128 };
129 } // namespace
130 
131 char PEI::ID = 0;
132 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
133 
134 static cl::opt<unsigned>
135 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
136               cl::desc("Warn for stack size bigger than the given"
137                        " number"));
138 
139 INITIALIZE_TM_PASS_BEGIN(PEI, "prologepilog", "Prologue/Epilogue Insertion",
140                          false, false)
141 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
142 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
143 INITIALIZE_PASS_DEPENDENCY(StackProtector)
144 INITIALIZE_TM_PASS_END(PEI, "prologepilog",
145                        "Prologue/Epilogue Insertion & Frame Finalization",
146                        false, false)
147 
148 MachineFunctionPass *
149 llvm::createPrologEpilogInserterPass(const TargetMachine *TM) {
150   return new PEI(TM);
151 }
152 
153 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
154 STATISTIC(NumBytesStackSpace,
155           "Number of bytes used for stack in all functions");
156 
157 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
158   AU.setPreservesCFG();
159   AU.addPreserved<MachineLoopInfo>();
160   AU.addPreserved<MachineDominatorTree>();
161   AU.addRequired<StackProtector>();
162   MachineFunctionPass::getAnalysisUsage(AU);
163 }
164 
165 
166 /// StackObjSet - A set of stack object indexes
167 typedef SmallSetVector<int, 8> StackObjSet;
168 
169 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
170 /// frame indexes with appropriate references.
171 ///
172 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
173   const Function* F = Fn.getFunction();
174   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
175   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
176 
177   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
178   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
179 
180   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
181   // function's frame information. Also eliminates call frame pseudo
182   // instructions.
183   calculateCallFrameInfo(Fn);
184 
185   // Determine placement of CSR spill/restore code and prolog/epilog code:
186   // place all spills in the entry block, all restores in return blocks.
187   calculateSaveRestoreBlocks(Fn);
188 
189   // Handle CSR spilling and restoring, for targets that need it.
190   SpillCalleeSavedRegisters(Fn, RS, MinCSFrameIndex, MaxCSFrameIndex,
191                             SaveBlocks, RestoreBlocks);
192 
193   // Allow the target machine to make final modifications to the function
194   // before the frame layout is finalized.
195   TFI->processFunctionBeforeFrameFinalized(Fn, RS);
196 
197   // Calculate actual frame offsets for all abstract stack objects...
198   calculateFrameObjectOffsets(Fn);
199 
200   // Add prolog and epilog code to the function.  This function is required
201   // to align the stack frame as necessary for any stack variables or
202   // called functions.  Because of this, calculateCalleeSavedRegisters()
203   // must be called before this function in order to set the AdjustsStack
204   // and MaxCallFrameSize variables.
205   if (!F->hasFnAttribute(Attribute::Naked))
206     insertPrologEpilogCode(Fn);
207 
208   // Replace all MO_FrameIndex operands with physical register references
209   // and actual offsets.
210   //
211   replaceFrameIndices(Fn);
212 
213   // If register scavenging is needed, as we've enabled doing it as a
214   // post-pass, scavenge the virtual registers that frame index elimination
215   // inserted.
216   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) {
217       ScavengeFrameVirtualRegs(Fn, RS);
218 
219       // Clear any vregs created by virtual scavenging.
220       Fn.getRegInfo().clearVirtRegs();
221   }
222 
223   // Warn on stack size when we exceeds the given limit.
224   MachineFrameInfo &MFI = Fn.getFrameInfo();
225   uint64_t StackSize = MFI.getStackSize();
226   if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
227     DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
228     F->getContext().diagnose(DiagStackSize);
229   }
230 
231   delete RS;
232   SaveBlocks.clear();
233   RestoreBlocks.clear();
234   MFI.setSavePoint(nullptr);
235   MFI.setRestorePoint(nullptr);
236   return true;
237 }
238 
239 /// Calculate the MaxCallFrameSize and AdjustsStack
240 /// variables for the function's frame information and eliminate call frame
241 /// pseudo instructions.
242 void PEI::calculateCallFrameInfo(MachineFunction &Fn) {
243   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
244   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
245   MachineFrameInfo &MFI = Fn.getFrameInfo();
246 
247   unsigned MaxCallFrameSize = 0;
248   bool AdjustsStack = MFI.adjustsStack();
249 
250   // Get the function call frame set-up and tear-down instruction opcode
251   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
252   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
253 
254   // Early exit for targets which have no call frame setup/destroy pseudo
255   // instructions.
256   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
257     return;
258 
259   std::vector<MachineBasicBlock::iterator> FrameSDOps;
260   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
261     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
262       if (I->getOpcode() == FrameSetupOpcode ||
263           I->getOpcode() == FrameDestroyOpcode) {
264         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
265                " instructions should have a single immediate argument!");
266         unsigned Size = I->getOperand(0).getImm();
267         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
268         AdjustsStack = true;
269         FrameSDOps.push_back(I);
270       } else if (I->isInlineAsm()) {
271         // Some inline asm's need a stack frame, as indicated by operand 1.
272         unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
273         if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
274           AdjustsStack = true;
275       }
276 
277   MFI.setAdjustsStack(AdjustsStack);
278   MFI.setMaxCallFrameSize(MaxCallFrameSize);
279 
280   for (std::vector<MachineBasicBlock::iterator>::iterator
281          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
282     MachineBasicBlock::iterator I = *i;
283 
284     // If call frames are not being included as part of the stack frame, and
285     // the target doesn't indicate otherwise, remove the call frame pseudos
286     // here. The sub/add sp instruction pairs are still inserted, but we don't
287     // need to track the SP adjustment for frame index elimination.
288     if (TFI->canSimplifyCallFramePseudos(Fn))
289       TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
290   }
291 }
292 
293 /// Compute the sets of entry and return blocks for saving and restoring
294 /// callee-saved registers, and placing prolog and epilog code.
295 void PEI::calculateSaveRestoreBlocks(MachineFunction &Fn) {
296   const MachineFrameInfo &MFI = Fn.getFrameInfo();
297 
298   // Even when we do not change any CSR, we still want to insert the
299   // prologue and epilogue of the function.
300   // So set the save points for those.
301 
302   // Use the points found by shrink-wrapping, if any.
303   if (MFI.getSavePoint()) {
304     SaveBlocks.push_back(MFI.getSavePoint());
305     assert(MFI.getRestorePoint() && "Both restore and save must be set");
306     MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
307     // If RestoreBlock does not have any successor and is not a return block
308     // then the end point is unreachable and we do not need to insert any
309     // epilogue.
310     if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
311       RestoreBlocks.push_back(RestoreBlock);
312     return;
313   }
314 
315   // Save refs to entry and return blocks.
316   SaveBlocks.push_back(&Fn.front());
317   for (MachineBasicBlock &MBB : Fn) {
318     if (MBB.isEHFuncletEntry())
319       SaveBlocks.push_back(&MBB);
320     if (MBB.isReturnBlock())
321       RestoreBlocks.push_back(&MBB);
322   }
323 }
324 
325 static void assignCalleeSavedSpillSlots(MachineFunction &F,
326                                         const BitVector &SavedRegs,
327                                         unsigned &MinCSFrameIndex,
328                                         unsigned &MaxCSFrameIndex) {
329   if (SavedRegs.empty())
330     return;
331 
332   const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
333   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
334 
335   std::vector<CalleeSavedInfo> CSI;
336   for (unsigned i = 0; CSRegs[i]; ++i) {
337     unsigned Reg = CSRegs[i];
338     if (SavedRegs.test(Reg))
339       CSI.push_back(CalleeSavedInfo(Reg));
340   }
341 
342   const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
343   MachineFrameInfo &MFI = F.getFrameInfo();
344   if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
345     // If target doesn't implement this, use generic code.
346 
347     if (CSI.empty())
348       return; // Early exit if no callee saved registers are modified!
349 
350     unsigned NumFixedSpillSlots;
351     const TargetFrameLowering::SpillSlot *FixedSpillSlots =
352         TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
353 
354     // Now that we know which registers need to be saved and restored, allocate
355     // stack slots for them.
356     for (auto &CS : CSI) {
357       unsigned Reg = CS.getReg();
358       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
359 
360       int FrameIdx;
361       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
362         CS.setFrameIdx(FrameIdx);
363         continue;
364       }
365 
366       // Check to see if this physreg must be spilled to a particular stack slot
367       // on this target.
368       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
369       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
370              FixedSlot->Reg != Reg)
371         ++FixedSlot;
372 
373       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
374         // Nope, just spill it anywhere convenient.
375         unsigned Align = RC->getAlignment();
376         unsigned StackAlign = TFI->getStackAlignment();
377 
378         // We may not be able to satisfy the desired alignment specification of
379         // the TargetRegisterClass if the stack alignment is smaller. Use the
380         // min.
381         Align = std::min(Align, StackAlign);
382         FrameIdx = MFI.CreateStackObject(RC->getSize(), Align, true);
383         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
384         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
385       } else {
386         // Spill it to the stack where we must.
387         FrameIdx =
388             MFI.CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
389       }
390 
391       CS.setFrameIdx(FrameIdx);
392     }
393   }
394 
395   MFI.setCalleeSavedInfo(CSI);
396 }
397 
398 /// Helper function to update the liveness information for the callee-saved
399 /// registers.
400 static void updateLiveness(MachineFunction &MF) {
401   MachineFrameInfo &MFI = MF.getFrameInfo();
402   // Visited will contain all the basic blocks that are in the region
403   // where the callee saved registers are alive:
404   // - Anything that is not Save or Restore -> LiveThrough.
405   // - Save -> LiveIn.
406   // - Restore -> LiveOut.
407   // The live-out is not attached to the block, so no need to keep
408   // Restore in this set.
409   SmallPtrSet<MachineBasicBlock *, 8> Visited;
410   SmallVector<MachineBasicBlock *, 8> WorkList;
411   MachineBasicBlock *Entry = &MF.front();
412   MachineBasicBlock *Save = MFI.getSavePoint();
413 
414   if (!Save)
415     Save = Entry;
416 
417   if (Entry != Save) {
418     WorkList.push_back(Entry);
419     Visited.insert(Entry);
420   }
421   Visited.insert(Save);
422 
423   MachineBasicBlock *Restore = MFI.getRestorePoint();
424   if (Restore)
425     // By construction Restore cannot be visited, otherwise it
426     // means there exists a path to Restore that does not go
427     // through Save.
428     WorkList.push_back(Restore);
429 
430   while (!WorkList.empty()) {
431     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
432     // By construction, the region that is after the save point is
433     // dominated by the Save and post-dominated by the Restore.
434     if (CurBB == Save && Save != Restore)
435       continue;
436     // Enqueue all the successors not already visited.
437     // Those are by construction either before Save or after Restore.
438     for (MachineBasicBlock *SuccBB : CurBB->successors())
439       if (Visited.insert(SuccBB).second)
440         WorkList.push_back(SuccBB);
441   }
442 
443   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
444 
445   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
446     for (MachineBasicBlock *MBB : Visited) {
447       MCPhysReg Reg = CSI[i].getReg();
448       // Add the callee-saved register as live-in.
449       // It's killed at the spill.
450       if (!MBB->isLiveIn(Reg))
451         MBB->addLiveIn(Reg);
452     }
453   }
454 }
455 
456 /// insertCSRSpillsAndRestores - Insert spill and restore code for
457 /// callee saved registers used in the function.
458 ///
459 static void insertCSRSpillsAndRestores(MachineFunction &Fn,
460                                        const MBBVector &SaveBlocks,
461                                        const MBBVector &RestoreBlocks) {
462   // Get callee saved register information.
463   MachineFrameInfo &MFI = Fn.getFrameInfo();
464   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
465 
466   MFI.setCalleeSavedInfoValid(true);
467 
468   // Early exit if no callee saved registers are modified!
469   if (CSI.empty())
470     return;
471 
472   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
473   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
474   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
475   MachineBasicBlock::iterator I;
476 
477   // Spill using target interface.
478   for (MachineBasicBlock *SaveBlock : SaveBlocks) {
479     I = SaveBlock->begin();
480     if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
481       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
482         // Insert the spill to the stack frame.
483         unsigned Reg = CSI[i].getReg();
484         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
485         TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
486                                 RC, TRI);
487       }
488     }
489     // Update the live-in information of all the blocks up to the save point.
490     updateLiveness(Fn);
491   }
492 
493   // Restore using target interface.
494   for (MachineBasicBlock *MBB : RestoreBlocks) {
495     I = MBB->end();
496 
497     // Skip over all terminator instructions, which are part of the return
498     // sequence.
499     MachineBasicBlock::iterator I2 = I;
500     while (I2 != MBB->begin() && (--I2)->isTerminator())
501       I = I2;
502 
503     bool AtStart = I == MBB->begin();
504     MachineBasicBlock::iterator BeforeI = I;
505     if (!AtStart)
506       --BeforeI;
507 
508     // Restore all registers immediately before the return and any
509     // terminators that precede it.
510     if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
511       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
512         unsigned Reg = CSI[i].getReg();
513         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
514         TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
515         assert(I != MBB->begin() &&
516                "loadRegFromStackSlot didn't insert any code!");
517         // Insert in reverse order.  loadRegFromStackSlot can insert
518         // multiple instructions.
519         if (AtStart)
520           I = MBB->begin();
521         else {
522           I = BeforeI;
523           ++I;
524         }
525       }
526     }
527   }
528 }
529 
530 static void doSpillCalleeSavedRegs(MachineFunction &Fn, RegScavenger *RS,
531                                    unsigned &MinCSFrameIndex,
532                                    unsigned &MaxCSFrameIndex,
533                                    const MBBVector &SaveBlocks,
534                                    const MBBVector &RestoreBlocks) {
535   const Function *F = Fn.getFunction();
536   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
537   MinCSFrameIndex = std::numeric_limits<unsigned>::max();
538   MaxCSFrameIndex = 0;
539 
540   // Determine which of the registers in the callee save list should be saved.
541   BitVector SavedRegs;
542   TFI->determineCalleeSaves(Fn, SavedRegs, RS);
543 
544   // Assign stack slots for any callee-saved registers that must be spilled.
545   assignCalleeSavedSpillSlots(Fn, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex);
546 
547   // Add the code to save and restore the callee saved registers.
548   if (!F->hasFnAttribute(Attribute::Naked))
549     insertCSRSpillsAndRestores(Fn, SaveBlocks, RestoreBlocks);
550 }
551 
552 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
553 static inline void
554 AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
555                   bool StackGrowsDown, int64_t &Offset,
556                   unsigned &MaxAlign, unsigned Skew) {
557   // If the stack grows down, add the object size to find the lowest address.
558   if (StackGrowsDown)
559     Offset += MFI.getObjectSize(FrameIdx);
560 
561   unsigned Align = MFI.getObjectAlignment(FrameIdx);
562 
563   // If the alignment of this object is greater than that of the stack, then
564   // increase the stack alignment to match.
565   MaxAlign = std::max(MaxAlign, Align);
566 
567   // Adjust to alignment boundary.
568   Offset = alignTo(Offset, Align, Skew);
569 
570   if (StackGrowsDown) {
571     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
572     MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
573   } else {
574     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
575     MFI.setObjectOffset(FrameIdx, Offset);
576     Offset += MFI.getObjectSize(FrameIdx);
577   }
578 }
579 
580 /// Compute which bytes of fixed and callee-save stack area are unused and keep
581 /// track of them in StackBytesFree.
582 ///
583 static inline void
584 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
585                       unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
586                       int64_t FixedCSEnd, BitVector &StackBytesFree) {
587   // Avoid undefined int64_t -> int conversion below in extreme case.
588   if (FixedCSEnd > std::numeric_limits<int>::max())
589     return;
590 
591   StackBytesFree.resize(FixedCSEnd, true);
592 
593   SmallVector<int, 16> AllocatedFrameSlots;
594   // Add fixed objects.
595   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
596     AllocatedFrameSlots.push_back(i);
597   // Add callee-save objects.
598   for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
599     AllocatedFrameSlots.push_back(i);
600 
601   for (int i : AllocatedFrameSlots) {
602     // These are converted from int64_t, but they should always fit in int
603     // because of the FixedCSEnd check above.
604     int ObjOffset = MFI.getObjectOffset(i);
605     int ObjSize = MFI.getObjectSize(i);
606     int ObjStart, ObjEnd;
607     if (StackGrowsDown) {
608       // ObjOffset is negative when StackGrowsDown is true.
609       ObjStart = -ObjOffset - ObjSize;
610       ObjEnd = -ObjOffset;
611     } else {
612       ObjStart = ObjOffset;
613       ObjEnd = ObjOffset + ObjSize;
614     }
615     // Ignore fixed holes that are in the previous stack frame.
616     if (ObjEnd > 0)
617       StackBytesFree.reset(ObjStart, ObjEnd);
618   }
619 }
620 
621 /// Assign frame object to an unused portion of the stack in the fixed stack
622 /// object range.  Return true if the allocation was successful.
623 ///
624 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
625                                      bool StackGrowsDown, unsigned MaxAlign,
626                                      BitVector &StackBytesFree) {
627   if (MFI.isVariableSizedObjectIndex(FrameIdx))
628     return false;
629 
630   if (StackBytesFree.none()) {
631     // clear it to speed up later scavengeStackSlot calls to
632     // StackBytesFree.none()
633     StackBytesFree.clear();
634     return false;
635   }
636 
637   unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx);
638   if (ObjAlign > MaxAlign)
639     return false;
640 
641   int64_t ObjSize = MFI.getObjectSize(FrameIdx);
642   int FreeStart;
643   for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
644        FreeStart = StackBytesFree.find_next(FreeStart)) {
645 
646     // Check that free space has suitable alignment.
647     unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
648     if (alignTo(ObjStart, ObjAlign) != ObjStart)
649       continue;
650 
651     if (FreeStart + ObjSize > StackBytesFree.size())
652       return false;
653 
654     bool AllBytesFree = true;
655     for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
656       if (!StackBytesFree.test(FreeStart + Byte)) {
657         AllBytesFree = false;
658         break;
659       }
660     if (AllBytesFree)
661       break;
662   }
663 
664   if (FreeStart == -1)
665     return false;
666 
667   if (StackGrowsDown) {
668     int ObjStart = -(FreeStart + ObjSize);
669     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << ObjStart
670                  << "]\n");
671     MFI.setObjectOffset(FrameIdx, ObjStart);
672   } else {
673     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << FreeStart
674                  << "]\n");
675     MFI.setObjectOffset(FrameIdx, FreeStart);
676   }
677 
678   StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
679   return true;
680 }
681 
682 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
683 /// those required to be close to the Stack Protector) to stack offsets.
684 static void
685 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
686                       SmallSet<int, 16> &ProtectedObjs,
687                       MachineFrameInfo &MFI, bool StackGrowsDown,
688                       int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
689 
690   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
691         E = UnassignedObjs.end(); I != E; ++I) {
692     int i = *I;
693     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
694     ProtectedObjs.insert(i);
695   }
696 }
697 
698 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
699 /// abstract stack objects.
700 ///
701 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
702   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
703   StackProtector *SP = &getAnalysis<StackProtector>();
704 
705   bool StackGrowsDown =
706     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
707 
708   // Loop over all of the stack objects, assigning sequential addresses...
709   MachineFrameInfo &MFI = Fn.getFrameInfo();
710 
711   // Start at the beginning of the local area.
712   // The Offset is the distance from the stack top in the direction
713   // of stack growth -- so it's always nonnegative.
714   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
715   if (StackGrowsDown)
716     LocalAreaOffset = -LocalAreaOffset;
717   assert(LocalAreaOffset >= 0
718          && "Local area offset should be in direction of stack growth");
719   int64_t Offset = LocalAreaOffset;
720 
721   // Skew to be applied to alignment.
722   unsigned Skew = TFI.getStackAlignmentSkew(Fn);
723 
724   // If there are fixed sized objects that are preallocated in the local area,
725   // non-fixed objects can't be allocated right at the start of local area.
726   // Adjust 'Offset' to point to the end of last fixed sized preallocated
727   // object.
728   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
729     int64_t FixedOff;
730     if (StackGrowsDown) {
731       // The maximum distance from the stack pointer is at lower address of
732       // the object -- which is given by offset. For down growing stack
733       // the offset is negative, so we negate the offset to get the distance.
734       FixedOff = -MFI.getObjectOffset(i);
735     } else {
736       // The maximum distance from the start pointer is at the upper
737       // address of the object.
738       FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
739     }
740     if (FixedOff > Offset) Offset = FixedOff;
741   }
742 
743   // First assign frame offsets to stack objects that are used to spill
744   // callee saved registers.
745   if (StackGrowsDown) {
746     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
747       // If the stack grows down, we need to add the size to find the lowest
748       // address of the object.
749       Offset += MFI.getObjectSize(i);
750 
751       unsigned Align = MFI.getObjectAlignment(i);
752       // Adjust to alignment boundary
753       Offset = alignTo(Offset, Align, Skew);
754 
755       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
756       MFI.setObjectOffset(i, -Offset);        // Set the computed offset
757     }
758   } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
759     // Be careful about underflow in comparisons agains MinCSFrameIndex.
760     for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
761       unsigned Align = MFI.getObjectAlignment(i);
762       // Adjust to alignment boundary
763       Offset = alignTo(Offset, Align, Skew);
764 
765       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
766       MFI.setObjectOffset(i, Offset);
767       Offset += MFI.getObjectSize(i);
768     }
769   }
770 
771   // FixedCSEnd is the stack offset to the end of the fixed and callee-save
772   // stack area.
773   int64_t FixedCSEnd = Offset;
774   unsigned MaxAlign = MFI.getMaxAlignment();
775 
776   // Make sure the special register scavenging spill slot is closest to the
777   // incoming stack pointer if a frame pointer is required and is closer
778   // to the incoming rather than the final stack pointer.
779   const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
780   bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
781                                TFI.isFPCloseToIncomingSP() &&
782                                RegInfo->useFPForScavengingIndex(Fn) &&
783                                !RegInfo->needsStackRealignment(Fn));
784   if (RS && EarlyScavengingSlots) {
785     SmallVector<int, 2> SFIs;
786     RS->getScavengingFrameIndices(SFIs);
787     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
788            IE = SFIs.end(); I != IE; ++I)
789       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
790   }
791 
792   // FIXME: Once this is working, then enable flag will change to a target
793   // check for whether the frame is large enough to want to use virtual
794   // frame index registers. Functions which don't want/need this optimization
795   // will continue to use the existing code path.
796   if (MFI.getUseLocalStackAllocationBlock()) {
797     unsigned Align = MFI.getLocalFrameMaxAlign();
798 
799     // Adjust to alignment boundary.
800     Offset = alignTo(Offset, Align, Skew);
801 
802     DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
803 
804     // Resolve offsets for objects in the local block.
805     for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
806       std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
807       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
808       DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
809             FIOffset << "]\n");
810       MFI.setObjectOffset(Entry.first, FIOffset);
811     }
812     // Allocate the local block
813     Offset += MFI.getLocalFrameSize();
814 
815     MaxAlign = std::max(Align, MaxAlign);
816   }
817 
818   // Retrieve the Exception Handler registration node.
819   int EHRegNodeFrameIndex = INT_MAX;
820   if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo())
821     EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
822 
823   // Make sure that the stack protector comes before the local variables on the
824   // stack.
825   SmallSet<int, 16> ProtectedObjs;
826   if (MFI.getStackProtectorIndex() >= 0) {
827     StackObjSet LargeArrayObjs;
828     StackObjSet SmallArrayObjs;
829     StackObjSet AddrOfObjs;
830 
831     AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), StackGrowsDown,
832                       Offset, MaxAlign, Skew);
833 
834     // Assign large stack objects first.
835     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
836       if (MFI.isObjectPreAllocated(i) &&
837           MFI.getUseLocalStackAllocationBlock())
838         continue;
839       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
840         continue;
841       if (RS && RS->isScavengingFrameIndex((int)i))
842         continue;
843       if (MFI.isDeadObjectIndex(i))
844         continue;
845       if (MFI.getStackProtectorIndex() == (int)i ||
846           EHRegNodeFrameIndex == (int)i)
847         continue;
848 
849       switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) {
850       case StackProtector::SSPLK_None:
851         continue;
852       case StackProtector::SSPLK_SmallArray:
853         SmallArrayObjs.insert(i);
854         continue;
855       case StackProtector::SSPLK_AddrOf:
856         AddrOfObjs.insert(i);
857         continue;
858       case StackProtector::SSPLK_LargeArray:
859         LargeArrayObjs.insert(i);
860         continue;
861       }
862       llvm_unreachable("Unexpected SSPLayoutKind.");
863     }
864 
865     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
866                           Offset, MaxAlign, Skew);
867     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
868                           Offset, MaxAlign, Skew);
869     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
870                           Offset, MaxAlign, Skew);
871   }
872 
873   SmallVector<int, 8> ObjectsToAllocate;
874 
875   // Then prepare to assign frame offsets to stack objects that are not used to
876   // spill callee saved registers.
877   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
878     if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock())
879       continue;
880     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
881       continue;
882     if (RS && RS->isScavengingFrameIndex((int)i))
883       continue;
884     if (MFI.isDeadObjectIndex(i))
885       continue;
886     if (MFI.getStackProtectorIndex() == (int)i ||
887         EHRegNodeFrameIndex == (int)i)
888       continue;
889     if (ProtectedObjs.count(i))
890       continue;
891 
892     // Add the objects that we need to allocate to our working set.
893     ObjectsToAllocate.push_back(i);
894   }
895 
896   // Allocate the EH registration node first if one is present.
897   if (EHRegNodeFrameIndex != INT_MAX)
898     AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
899                       MaxAlign, Skew);
900 
901   // Give the targets a chance to order the objects the way they like it.
902   if (Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
903       Fn.getTarget().Options.StackSymbolOrdering)
904     TFI.orderFrameObjects(Fn, ObjectsToAllocate);
905 
906   // Keep track of which bytes in the fixed and callee-save range are used so we
907   // can use the holes when allocating later stack objects.  Only do this if
908   // stack protector isn't being used and the target requests it and we're
909   // optimizing.
910   BitVector StackBytesFree;
911   if (!ObjectsToAllocate.empty() &&
912       Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
913       MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(Fn))
914     computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex,
915                           FixedCSEnd, StackBytesFree);
916 
917   // Now walk the objects and actually assign base offsets to them.
918   for (auto &Object : ObjectsToAllocate)
919     if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
920                            StackBytesFree))
921       AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
922 
923   // Make sure the special register scavenging spill slot is closest to the
924   // stack pointer.
925   if (RS && !EarlyScavengingSlots) {
926     SmallVector<int, 2> SFIs;
927     RS->getScavengingFrameIndices(SFIs);
928     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
929            IE = SFIs.end(); I != IE; ++I)
930       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
931   }
932 
933   if (!TFI.targetHandlesStackFrameRounding()) {
934     // If we have reserved argument space for call sites in the function
935     // immediately on entry to the current function, count it as part of the
936     // overall stack size.
937     if (MFI.adjustsStack() && TFI.hasReservedCallFrame(Fn))
938       Offset += MFI.getMaxCallFrameSize();
939 
940     // Round up the size to a multiple of the alignment.  If the function has
941     // any calls or alloca's, align to the target's StackAlignment value to
942     // ensure that the callee's frame or the alloca data is suitably aligned;
943     // otherwise, for leaf functions, align to the TransientStackAlignment
944     // value.
945     unsigned StackAlign;
946     if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
947         (RegInfo->needsStackRealignment(Fn) && MFI.getObjectIndexEnd() != 0))
948       StackAlign = TFI.getStackAlignment();
949     else
950       StackAlign = TFI.getTransientStackAlignment();
951 
952     // If the frame pointer is eliminated, all frame offsets will be relative to
953     // SP not FP. Align to MaxAlign so this works.
954     StackAlign = std::max(StackAlign, MaxAlign);
955     Offset = alignTo(Offset, StackAlign, Skew);
956   }
957 
958   // Update frame info to pretend that this is part of the stack...
959   int64_t StackSize = Offset - LocalAreaOffset;
960   MFI.setStackSize(StackSize);
961   NumBytesStackSpace += StackSize;
962 }
963 
964 /// insertPrologEpilogCode - Scan the function for modified callee saved
965 /// registers, insert spill code for these callee saved registers, then add
966 /// prolog and epilog code to the function.
967 ///
968 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
969   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
970 
971   // Add prologue to the function...
972   for (MachineBasicBlock *SaveBlock : SaveBlocks)
973     TFI.emitPrologue(Fn, *SaveBlock);
974 
975   // Add epilogue to restore the callee-save registers in each exiting block.
976   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
977     TFI.emitEpilogue(Fn, *RestoreBlock);
978 
979   for (MachineBasicBlock *SaveBlock : SaveBlocks)
980     TFI.inlineStackProbe(Fn, *SaveBlock);
981 
982   // Emit additional code that is required to support segmented stacks, if
983   // we've been asked for it.  This, when linked with a runtime with support
984   // for segmented stacks (libgcc is one), will result in allocating stack
985   // space in small chunks instead of one large contiguous block.
986   if (Fn.shouldSplitStack()) {
987     for (MachineBasicBlock *SaveBlock : SaveBlocks)
988       TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
989   }
990 
991   // Emit additional code that is required to explicitly handle the stack in
992   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
993   // approach is rather similar to that of Segmented Stacks, but it uses a
994   // different conditional check and another BIF for allocating more stack
995   // space.
996   if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
997     for (MachineBasicBlock *SaveBlock : SaveBlocks)
998       TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
999 }
1000 
1001 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1002 /// register references and actual offsets.
1003 ///
1004 void PEI::replaceFrameIndices(MachineFunction &Fn) {
1005   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
1006   if (!TFI.needsFrameIndexResolution(Fn)) return;
1007 
1008   // Store SPAdj at exit of a basic block.
1009   SmallVector<int, 8> SPState;
1010   SPState.resize(Fn.getNumBlockIDs());
1011   SmallPtrSet<MachineBasicBlock*, 8> Reachable;
1012 
1013   // Iterate over the reachable blocks in DFS order.
1014   for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
1015        DFI != DFE; ++DFI) {
1016     int SPAdj = 0;
1017     // Check the exit state of the DFS stack predecessor.
1018     if (DFI.getPathLength() >= 2) {
1019       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1020       assert(Reachable.count(StackPred) &&
1021              "DFS stack predecessor is already visited.\n");
1022       SPAdj = SPState[StackPred->getNumber()];
1023     }
1024     MachineBasicBlock *BB = *DFI;
1025     replaceFrameIndices(BB, Fn, SPAdj);
1026     SPState[BB->getNumber()] = SPAdj;
1027   }
1028 
1029   // Handle the unreachable blocks.
1030   for (auto &BB : Fn) {
1031     if (Reachable.count(&BB))
1032       // Already handled in DFS traversal.
1033       continue;
1034     int SPAdj = 0;
1035     replaceFrameIndices(&BB, Fn, SPAdj);
1036   }
1037 }
1038 
1039 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
1040                               int &SPAdj) {
1041   assert(Fn.getSubtarget().getRegisterInfo() &&
1042          "getRegisterInfo() must be implemented!");
1043   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
1044   const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
1045   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
1046   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
1047   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
1048 
1049   if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(*BB);
1050 
1051   bool InsideCallSequence = false;
1052 
1053   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1054 
1055     if (I->getOpcode() == FrameSetupOpcode ||
1056         I->getOpcode() == FrameDestroyOpcode) {
1057       InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
1058       SPAdj += TII.getSPAdjust(*I);
1059 
1060       I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
1061       continue;
1062     }
1063 
1064     MachineInstr &MI = *I;
1065     bool DoIncr = true;
1066     bool DidFinishLoop = true;
1067     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1068       if (!MI.getOperand(i).isFI())
1069         continue;
1070 
1071       // Frame indices in debug values are encoded in a target independent
1072       // way with simply the frame index and offset rather than any
1073       // target-specific addressing mode.
1074       if (MI.isDebugValue()) {
1075         assert(i == 0 && "Frame indices can only appear as the first "
1076                          "operand of a DBG_VALUE machine instruction");
1077         unsigned Reg;
1078         MachineOperand &Offset = MI.getOperand(1);
1079         Offset.setImm(
1080             Offset.getImm() +
1081             TFI->getFrameIndexReference(Fn, MI.getOperand(0).getIndex(), Reg));
1082         MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
1083         continue;
1084       }
1085 
1086       // TODO: This code should be commoned with the code for
1087       // PATCHPOINT. There's no good reason for the difference in
1088       // implementation other than historical accident.  The only
1089       // remaining difference is the unconditional use of the stack
1090       // pointer as the base register.
1091       if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1092         assert((!MI.isDebugValue() || i == 0) &&
1093                "Frame indicies can only appear as the first operand of a "
1094                "DBG_VALUE machine instruction");
1095         unsigned Reg;
1096         MachineOperand &Offset = MI.getOperand(i + 1);
1097         int refOffset = TFI->getFrameIndexReferencePreferSP(
1098             Fn, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1099         Offset.setImm(Offset.getImm() + refOffset);
1100         MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
1101         continue;
1102       }
1103 
1104       // Some instructions (e.g. inline asm instructions) can have
1105       // multiple frame indices and/or cause eliminateFrameIndex
1106       // to insert more than one instruction. We need the register
1107       // scavenger to go through all of these instructions so that
1108       // it can update its register information. We keep the
1109       // iterator at the point before insertion so that we can
1110       // revisit them in full.
1111       bool AtBeginning = (I == BB->begin());
1112       if (!AtBeginning) --I;
1113 
1114       // If this instruction has a FrameIndex operand, we need to
1115       // use that target machine register info object to eliminate
1116       // it.
1117       TRI.eliminateFrameIndex(MI, SPAdj, i,
1118                               FrameIndexVirtualScavenging ?  nullptr : RS);
1119 
1120       // Reset the iterator if we were at the beginning of the BB.
1121       if (AtBeginning) {
1122         I = BB->begin();
1123         DoIncr = false;
1124       }
1125 
1126       DidFinishLoop = false;
1127       break;
1128     }
1129 
1130     // If we are looking at a call sequence, we need to keep track of
1131     // the SP adjustment made by each instruction in the sequence.
1132     // This includes both the frame setup/destroy pseudos (handled above),
1133     // as well as other instructions that have side effects w.r.t the SP.
1134     // Note that this must come after eliminateFrameIndex, because
1135     // if I itself referred to a frame index, we shouldn't count its own
1136     // adjustment.
1137     if (DidFinishLoop && InsideCallSequence)
1138       SPAdj += TII.getSPAdjust(MI);
1139 
1140     if (DoIncr && I != BB->end()) ++I;
1141 
1142     // Update register states.
1143     if (RS && !FrameIndexVirtualScavenging && DidFinishLoop)
1144       RS->forward(MI);
1145   }
1146 }
1147 
1148 /// doScavengeFrameVirtualRegs - Replace all frame index virtual registers
1149 /// with physical registers. Use the register scavenger to find an
1150 /// appropriate register to use.
1151 ///
1152 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
1153 /// iterate over the vreg use list, which at this point only contains machine
1154 /// operands for which eliminateFrameIndex need a new scratch reg.
1155 static void
1156 doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS) {
1157   // Run through the instructions and find any virtual registers.
1158   MachineRegisterInfo &MRI = MF.getRegInfo();
1159   for (MachineBasicBlock &MBB : MF) {
1160     RS->enterBasicBlock(MBB);
1161 
1162     int SPAdj = 0;
1163 
1164     // The instruction stream may change in the loop, so check MBB.end()
1165     // directly.
1166     for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ) {
1167       // We might end up here again with a NULL iterator if we scavenged a
1168       // register for which we inserted spill code for definition by what was
1169       // originally the first instruction in MBB.
1170       if (I == MachineBasicBlock::iterator(nullptr))
1171         I = MBB.begin();
1172 
1173       const MachineInstr &MI = *I;
1174       MachineBasicBlock::iterator J = std::next(I);
1175       MachineBasicBlock::iterator P =
1176                          I == MBB.begin() ? MachineBasicBlock::iterator(nullptr)
1177                                           : std::prev(I);
1178 
1179       // RS should process this instruction before we might scavenge at this
1180       // location. This is because we might be replacing a virtual register
1181       // defined by this instruction, and if so, registers killed by this
1182       // instruction are available, and defined registers are not.
1183       RS->forward(I);
1184 
1185       for (const MachineOperand &MO : MI.operands()) {
1186         if (!MO.isReg())
1187           continue;
1188         unsigned Reg = MO.getReg();
1189         if (!TargetRegisterInfo::isVirtualRegister(Reg))
1190           continue;
1191 
1192         // When we first encounter a new virtual register, it
1193         // must be a definition.
1194         assert(MO.isDef() && "frame index virtual missing def!");
1195         // Scavenge a new scratch register
1196         const TargetRegisterClass *RC = MRI.getRegClass(Reg);
1197         unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1198 
1199         ++NumScavengedRegs;
1200 
1201         // Replace this reference to the virtual register with the
1202         // scratch register.
1203         assert(ScratchReg && "Missing scratch register!");
1204         MRI.replaceRegWith(Reg, ScratchReg);
1205 
1206         // Because this instruction was processed by the RS before this
1207         // register was allocated, make sure that the RS now records the
1208         // register as being used.
1209         RS->setRegUsed(ScratchReg);
1210       }
1211 
1212       // If the scavenger needed to use one of its spill slots, the
1213       // spill code will have been inserted in between I and J. This is a
1214       // problem because we need the spill code before I: Move I to just
1215       // prior to J.
1216       if (I != std::prev(J)) {
1217         MBB.splice(J, &MBB, I);
1218 
1219         // Before we move I, we need to prepare the RS to visit I again.
1220         // Specifically, RS will assert if it sees uses of registers that
1221         // it believes are undefined. Because we have already processed
1222         // register kills in I, when it visits I again, it will believe that
1223         // those registers are undefined. To avoid this situation, unprocess
1224         // the instruction I.
1225         assert(RS->getCurrentPosition() == I &&
1226           "The register scavenger has an unexpected position");
1227         I = P;
1228         RS->unprocess(P);
1229       } else
1230         ++I;
1231     }
1232   }
1233 }
1234