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