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