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