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