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