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().usesPhysRegsForPEI())
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   // Replace all MO_FrameIndex operands with physical register references
263   // and actual offsets.
264   //
265   replaceFrameIndices(MF);
266 
267   // If register scavenging is needed, as we've enabled doing it as a
268   // post-pass, scavenge the virtual registers that frame index elimination
269   // inserted.
270   if (TRI->requiresRegisterScavenging(MF) && FrameIndexVirtualScavenging)
271     scavengeFrameVirtualRegs(MF, *RS);
272 
273   // Warn on stack size when we exceeds the given limit.
274   MachineFrameInfo &MFI = MF.getFrameInfo();
275   uint64_t StackSize = MFI.getStackSize();
276   if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
277     DiagnosticInfoStackSize DiagStackSize(F, StackSize);
278     F.getContext().diagnose(DiagStackSize);
279   }
280   ORE->emit([&]() {
281     return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "StackSize",
282                                              MF.getFunction().getSubprogram(),
283                                              &MF.front())
284            << ore::NV("NumStackBytes", StackSize) << " stack bytes in function";
285   });
286 
287   delete RS;
288   SaveBlocks.clear();
289   RestoreBlocks.clear();
290   MFI.setSavePoint(nullptr);
291   MFI.setRestorePoint(nullptr);
292   return true;
293 }
294 
295 /// Calculate the MaxCallFrameSize and AdjustsStack
296 /// variables for the function's frame information and eliminate call frame
297 /// pseudo instructions.
298 void PEI::calculateCallFrameInfo(MachineFunction &MF) {
299   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
300   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
301   MachineFrameInfo &MFI = MF.getFrameInfo();
302 
303   unsigned MaxCallFrameSize = 0;
304   bool AdjustsStack = MFI.adjustsStack();
305 
306   // Get the function call frame set-up and tear-down instruction opcode
307   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
308   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
309 
310   // Early exit for targets which have no call frame setup/destroy pseudo
311   // instructions.
312   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
313     return;
314 
315   std::vector<MachineBasicBlock::iterator> FrameSDOps;
316   for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
317     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
318       if (TII.isFrameInstr(*I)) {
319         unsigned Size = TII.getFrameSize(*I);
320         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
321         AdjustsStack = true;
322         FrameSDOps.push_back(I);
323       } else if (I->isInlineAsm()) {
324         // Some inline asm's need a stack frame, as indicated by operand 1.
325         unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
326         if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
327           AdjustsStack = true;
328       }
329 
330   assert(!MFI.isMaxCallFrameSizeComputed() ||
331          (MFI.getMaxCallFrameSize() == MaxCallFrameSize &&
332           MFI.adjustsStack() == AdjustsStack));
333   MFI.setAdjustsStack(AdjustsStack);
334   MFI.setMaxCallFrameSize(MaxCallFrameSize);
335 
336   for (std::vector<MachineBasicBlock::iterator>::iterator
337          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
338     MachineBasicBlock::iterator I = *i;
339 
340     // If call frames are not being included as part of the stack frame, and
341     // the target doesn't indicate otherwise, remove the call frame pseudos
342     // here. The sub/add sp instruction pairs are still inserted, but we don't
343     // need to track the SP adjustment for frame index elimination.
344     if (TFI->canSimplifyCallFramePseudos(MF))
345       TFI->eliminateCallFramePseudoInstr(MF, *I->getParent(), I);
346   }
347 }
348 
349 /// Compute the sets of entry and return blocks for saving and restoring
350 /// callee-saved registers, and placing prolog and epilog code.
351 void PEI::calculateSaveRestoreBlocks(MachineFunction &MF) {
352   const MachineFrameInfo &MFI = MF.getFrameInfo();
353 
354   // Even when we do not change any CSR, we still want to insert the
355   // prologue and epilogue of the function.
356   // So set the save points for those.
357 
358   // Use the points found by shrink-wrapping, if any.
359   if (MFI.getSavePoint()) {
360     SaveBlocks.push_back(MFI.getSavePoint());
361     assert(MFI.getRestorePoint() && "Both restore and save must be set");
362     MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
363     // If RestoreBlock does not have any successor and is not a return block
364     // then the end point is unreachable and we do not need to insert any
365     // epilogue.
366     if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
367       RestoreBlocks.push_back(RestoreBlock);
368     return;
369   }
370 
371   // Save refs to entry and return blocks.
372   SaveBlocks.push_back(&MF.front());
373   for (MachineBasicBlock &MBB : MF) {
374     if (MBB.isEHFuncletEntry())
375       SaveBlocks.push_back(&MBB);
376     if (MBB.isReturnBlock())
377       RestoreBlocks.push_back(&MBB);
378   }
379 }
380 
381 static void assignCalleeSavedSpillSlots(MachineFunction &F,
382                                         const BitVector &SavedRegs,
383                                         unsigned &MinCSFrameIndex,
384                                         unsigned &MaxCSFrameIndex) {
385   if (SavedRegs.empty())
386     return;
387 
388   const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
389   const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
390 
391   std::vector<CalleeSavedInfo> CSI;
392   for (unsigned i = 0; CSRegs[i]; ++i) {
393     unsigned Reg = CSRegs[i];
394     if (SavedRegs.test(Reg))
395       CSI.push_back(CalleeSavedInfo(Reg));
396   }
397 
398   const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
399   MachineFrameInfo &MFI = F.getFrameInfo();
400   if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
401     // If target doesn't implement this, use generic code.
402 
403     if (CSI.empty())
404       return; // Early exit if no callee saved registers are modified!
405 
406     unsigned NumFixedSpillSlots;
407     const TargetFrameLowering::SpillSlot *FixedSpillSlots =
408         TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
409 
410     // Now that we know which registers need to be saved and restored, allocate
411     // stack slots for them.
412     for (auto &CS : CSI) {
413       // If the target has spilled this register to another register, we don't
414       // need to allocate a stack slot.
415       if (CS.isSpilledToReg())
416         continue;
417 
418       unsigned Reg = CS.getReg();
419       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
420 
421       int FrameIdx;
422       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
423         CS.setFrameIdx(FrameIdx);
424         continue;
425       }
426 
427       // Check to see if this physreg must be spilled to a particular stack slot
428       // on this target.
429       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
430       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
431              FixedSlot->Reg != Reg)
432         ++FixedSlot;
433 
434       unsigned Size = RegInfo->getSpillSize(*RC);
435       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
436         // Nope, just spill it anywhere convenient.
437         unsigned Align = RegInfo->getSpillAlignment(*RC);
438         unsigned StackAlign = TFI->getStackAlignment();
439 
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         Align = std::min(Align, StackAlign);
444         FrameIdx = MFI.CreateStackObject(Size, Align, 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         // Update the live-in information of all the blocks up to the save
624         // 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
635 AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
636                   bool StackGrowsDown, int64_t &Offset,
637                   unsigned &MaxAlign, unsigned Skew) {
638   // If the stack grows down, add the object size to find the lowest address.
639   if (StackGrowsDown)
640     Offset += MFI.getObjectSize(FrameIdx);
641 
642   unsigned Align = MFI.getObjectAlignment(FrameIdx);
643 
644   // If the alignment of this object is greater than that of the stack, then
645   // increase the stack alignment to match.
646   MaxAlign = std::max(MaxAlign, Align);
647 
648   // Adjust to alignment boundary.
649   Offset = alignTo(Offset, Align, Skew);
650 
651   if (StackGrowsDown) {
652     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset
653                       << "]\n");
654     MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
655   } else {
656     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset
657                       << "]\n");
658     MFI.setObjectOffset(FrameIdx, Offset);
659     Offset += MFI.getObjectSize(FrameIdx);
660   }
661 }
662 
663 /// Compute which bytes of fixed and callee-save stack area are unused and keep
664 /// track of them in StackBytesFree.
665 static inline void
666 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
667                       unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
668                       int64_t FixedCSEnd, BitVector &StackBytesFree) {
669   // Avoid undefined int64_t -> int conversion below in extreme case.
670   if (FixedCSEnd > std::numeric_limits<int>::max())
671     return;
672 
673   StackBytesFree.resize(FixedCSEnd, true);
674 
675   SmallVector<int, 16> AllocatedFrameSlots;
676   // Add fixed objects.
677   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
678     // StackSlot scavenging is only implemented for the default stack.
679     if (MFI.getStackID(i) == TargetStackID::Default)
680       AllocatedFrameSlots.push_back(i);
681   // Add callee-save objects.
682   for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
683     if (MFI.getStackID(i) == TargetStackID::Default)
684       AllocatedFrameSlots.push_back(i);
685 
686   for (int i : AllocatedFrameSlots) {
687     // These are converted from int64_t, but they should always fit in int
688     // because of the FixedCSEnd check above.
689     int ObjOffset = MFI.getObjectOffset(i);
690     int ObjSize = MFI.getObjectSize(i);
691     int ObjStart, ObjEnd;
692     if (StackGrowsDown) {
693       // ObjOffset is negative when StackGrowsDown is true.
694       ObjStart = -ObjOffset - ObjSize;
695       ObjEnd = -ObjOffset;
696     } else {
697       ObjStart = ObjOffset;
698       ObjEnd = ObjOffset + ObjSize;
699     }
700     // Ignore fixed holes that are in the previous stack frame.
701     if (ObjEnd > 0)
702       StackBytesFree.reset(ObjStart, ObjEnd);
703   }
704 }
705 
706 /// Assign frame object to an unused portion of the stack in the fixed stack
707 /// object range.  Return true if the allocation was successful.
708 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
709                                      bool StackGrowsDown, unsigned MaxAlign,
710                                      BitVector &StackBytesFree) {
711   if (MFI.isVariableSizedObjectIndex(FrameIdx))
712     return false;
713 
714   if (StackBytesFree.none()) {
715     // clear it to speed up later scavengeStackSlot calls to
716     // StackBytesFree.none()
717     StackBytesFree.clear();
718     return false;
719   }
720 
721   unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx);
722   if (ObjAlign > MaxAlign)
723     return false;
724 
725   int64_t ObjSize = MFI.getObjectSize(FrameIdx);
726   int FreeStart;
727   for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
728        FreeStart = StackBytesFree.find_next(FreeStart)) {
729 
730     // Check that free space has suitable alignment.
731     unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
732     if (alignTo(ObjStart, ObjAlign) != ObjStart)
733       continue;
734 
735     if (FreeStart + ObjSize > StackBytesFree.size())
736       return false;
737 
738     bool AllBytesFree = true;
739     for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
740       if (!StackBytesFree.test(FreeStart + Byte)) {
741         AllBytesFree = false;
742         break;
743       }
744     if (AllBytesFree)
745       break;
746   }
747 
748   if (FreeStart == -1)
749     return false;
750 
751   if (StackGrowsDown) {
752     int ObjStart = -(FreeStart + ObjSize);
753     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
754                       << ObjStart << "]\n");
755     MFI.setObjectOffset(FrameIdx, ObjStart);
756   } else {
757     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
758                       << FreeStart << "]\n");
759     MFI.setObjectOffset(FrameIdx, FreeStart);
760   }
761 
762   StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
763   return true;
764 }
765 
766 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
767 /// those required to be close to the Stack Protector) to stack offsets.
768 static void
769 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
770                       SmallSet<int, 16> &ProtectedObjs,
771                       MachineFrameInfo &MFI, bool StackGrowsDown,
772                       int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
773 
774   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
775         E = UnassignedObjs.end(); I != E; ++I) {
776     int i = *I;
777     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
778     ProtectedObjs.insert(i);
779   }
780 }
781 
782 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
783 /// abstract stack objects.
784 void PEI::calculateFrameObjectOffsets(MachineFunction &MF) {
785   const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
786 
787   bool StackGrowsDown =
788     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
789 
790   // Loop over all of the stack objects, assigning sequential addresses...
791   MachineFrameInfo &MFI = MF.getFrameInfo();
792 
793   // Start at the beginning of the local area.
794   // The Offset is the distance from the stack top in the direction
795   // of stack growth -- so it's always nonnegative.
796   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
797   if (StackGrowsDown)
798     LocalAreaOffset = -LocalAreaOffset;
799   assert(LocalAreaOffset >= 0
800          && "Local area offset should be in direction of stack growth");
801   int64_t Offset = LocalAreaOffset;
802 
803   // Skew to be applied to alignment.
804   unsigned Skew = TFI.getStackAlignmentSkew(MF);
805 
806 #ifdef EXPENSIVE_CHECKS
807   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i)
808     if (!MFI.isDeadObjectIndex(i) &&
809         MFI.getStackID(i) == TargetStackID::Default)
810       assert(MFI.getObjectAlignment(i) <= MFI.getMaxAlignment() &&
811              "MaxAlignment is invalid");
812 #endif
813 
814   // If there are fixed sized objects that are preallocated in the local area,
815   // non-fixed objects can't be allocated right at the start of local area.
816   // Adjust 'Offset' to point to the end of last fixed sized preallocated
817   // object.
818   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
819     if (MFI.getStackID(i) !=
820         TargetStackID::Default) // Only allocate objects on the default stack.
821       continue;
822 
823     int64_t FixedOff;
824     if (StackGrowsDown) {
825       // The maximum distance from the stack pointer is at lower address of
826       // the object -- which is given by offset. For down growing stack
827       // the offset is negative, so we negate the offset to get the distance.
828       FixedOff = -MFI.getObjectOffset(i);
829     } else {
830       // The maximum distance from the start pointer is at the upper
831       // address of the object.
832       FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
833     }
834     if (FixedOff > Offset) Offset = FixedOff;
835   }
836 
837   // First assign frame offsets to stack objects that are used to spill
838   // callee saved registers.
839   if (StackGrowsDown) {
840     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
841       if (MFI.getStackID(i) !=
842           TargetStackID::Default) // Only allocate objects on the default stack.
843         continue;
844 
845       // If the stack grows down, we need to add the size to find the lowest
846       // address of the object.
847       Offset += MFI.getObjectSize(i);
848 
849       unsigned Align = MFI.getObjectAlignment(i);
850       // Adjust to alignment boundary
851       Offset = alignTo(Offset, Align, Skew);
852 
853       LLVM_DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
854       MFI.setObjectOffset(i, -Offset);        // Set the computed offset
855     }
856   } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
857     // Be careful about underflow in comparisons agains MinCSFrameIndex.
858     for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
859       if (MFI.getStackID(i) !=
860           TargetStackID::Default) // Only allocate objects on the default stack.
861         continue;
862 
863       if (MFI.isDeadObjectIndex(i))
864         continue;
865 
866       unsigned Align = MFI.getObjectAlignment(i);
867       // Adjust to alignment boundary
868       Offset = alignTo(Offset, Align, Skew);
869 
870       LLVM_DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
871       MFI.setObjectOffset(i, Offset);
872       Offset += MFI.getObjectSize(i);
873     }
874   }
875 
876   // FixedCSEnd is the stack offset to the end of the fixed and callee-save
877   // stack area.
878   int64_t FixedCSEnd = Offset;
879   unsigned MaxAlign = MFI.getMaxAlignment();
880 
881   // Make sure the special register scavenging spill slot is closest to the
882   // incoming stack pointer if a frame pointer is required and is closer
883   // to the incoming rather than the final stack pointer.
884   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
885   bool EarlyScavengingSlots = (TFI.hasFP(MF) &&
886                                TFI.isFPCloseToIncomingSP() &&
887                                RegInfo->useFPForScavengingIndex(MF) &&
888                                !RegInfo->needsStackRealignment(MF));
889   if (RS && EarlyScavengingSlots) {
890     SmallVector<int, 2> SFIs;
891     RS->getScavengingFrameIndices(SFIs);
892     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
893            IE = SFIs.end(); I != IE; ++I)
894       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
895   }
896 
897   // FIXME: Once this is working, then enable flag will change to a target
898   // check for whether the frame is large enough to want to use virtual
899   // frame index registers. Functions which don't want/need this optimization
900   // will continue to use the existing code path.
901   if (MFI.getUseLocalStackAllocationBlock()) {
902     unsigned Align = MFI.getLocalFrameMaxAlign().value();
903 
904     // Adjust to alignment boundary.
905     Offset = alignTo(Offset, Align, Skew);
906 
907     LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
908 
909     // Resolve offsets for objects in the local block.
910     for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
911       std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
912       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
913       LLVM_DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << FIOffset
914                         << "]\n");
915       MFI.setObjectOffset(Entry.first, FIOffset);
916     }
917     // Allocate the local block
918     Offset += MFI.getLocalFrameSize();
919 
920     MaxAlign = std::max(Align, MaxAlign);
921   }
922 
923   // Retrieve the Exception Handler registration node.
924   int EHRegNodeFrameIndex = std::numeric_limits<int>::max();
925   if (const WinEHFuncInfo *FuncInfo = MF.getWinEHFuncInfo())
926     EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
927 
928   // Make sure that the stack protector comes before the local variables on the
929   // stack.
930   SmallSet<int, 16> ProtectedObjs;
931   if (MFI.hasStackProtectorIndex()) {
932     int StackProtectorFI = MFI.getStackProtectorIndex();
933     StackObjSet LargeArrayObjs;
934     StackObjSet SmallArrayObjs;
935     StackObjSet AddrOfObjs;
936 
937     // If we need a stack protector, we need to make sure that
938     // LocalStackSlotPass didn't already allocate a slot for it.
939     // If we are told to use the LocalStackAllocationBlock, the stack protector
940     // is expected to be already pre-allocated.
941     if (!MFI.getUseLocalStackAllocationBlock())
942       AdjustStackOffset(MFI, StackProtectorFI, StackGrowsDown, Offset, MaxAlign,
943                         Skew);
944     else if (!MFI.isObjectPreAllocated(MFI.getStackProtectorIndex()))
945       llvm_unreachable(
946           "Stack protector not pre-allocated by LocalStackSlotPass.");
947 
948     // Assign large stack objects first.
949     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
950       if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock())
951         continue;
952       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
953         continue;
954       if (RS && RS->isScavengingFrameIndex((int)i))
955         continue;
956       if (MFI.isDeadObjectIndex(i))
957         continue;
958       if (StackProtectorFI == (int)i || EHRegNodeFrameIndex == (int)i)
959         continue;
960       if (MFI.getStackID(i) !=
961           TargetStackID::Default) // Only allocate objects on the default stack.
962         continue;
963 
964       switch (MFI.getObjectSSPLayout(i)) {
965       case MachineFrameInfo::SSPLK_None:
966         continue;
967       case MachineFrameInfo::SSPLK_SmallArray:
968         SmallArrayObjs.insert(i);
969         continue;
970       case MachineFrameInfo::SSPLK_AddrOf:
971         AddrOfObjs.insert(i);
972         continue;
973       case MachineFrameInfo::SSPLK_LargeArray:
974         LargeArrayObjs.insert(i);
975         continue;
976       }
977       llvm_unreachable("Unexpected SSPLayoutKind.");
978     }
979 
980     // We expect **all** the protected stack objects to be pre-allocated by
981     // LocalStackSlotPass. If it turns out that PEI still has to allocate some
982     // of them, we may end up messing up the expected order of the objects.
983     if (MFI.getUseLocalStackAllocationBlock() &&
984         !(LargeArrayObjs.empty() && SmallArrayObjs.empty() &&
985           AddrOfObjs.empty()))
986       llvm_unreachable("Found protected stack objects not pre-allocated by "
987                        "LocalStackSlotPass.");
988 
989     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
990                           Offset, MaxAlign, Skew);
991     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
992                           Offset, MaxAlign, Skew);
993     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
994                           Offset, MaxAlign, Skew);
995   }
996 
997   SmallVector<int, 8> ObjectsToAllocate;
998 
999   // Then prepare to assign frame offsets to stack objects that are not used to
1000   // spill callee saved registers.
1001   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1002     if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock())
1003       continue;
1004     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
1005       continue;
1006     if (RS && RS->isScavengingFrameIndex((int)i))
1007       continue;
1008     if (MFI.isDeadObjectIndex(i))
1009       continue;
1010     if (MFI.getStackProtectorIndex() == (int)i || EHRegNodeFrameIndex == (int)i)
1011       continue;
1012     if (ProtectedObjs.count(i))
1013       continue;
1014     if (MFI.getStackID(i) !=
1015         TargetStackID::Default) // Only allocate objects on the default stack.
1016       continue;
1017 
1018     // Add the objects that we need to allocate to our working set.
1019     ObjectsToAllocate.push_back(i);
1020   }
1021 
1022   // Allocate the EH registration node first if one is present.
1023   if (EHRegNodeFrameIndex != std::numeric_limits<int>::max())
1024     AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
1025                       MaxAlign, Skew);
1026 
1027   // Give the targets a chance to order the objects the way they like it.
1028   if (MF.getTarget().getOptLevel() != CodeGenOpt::None &&
1029       MF.getTarget().Options.StackSymbolOrdering)
1030     TFI.orderFrameObjects(MF, ObjectsToAllocate);
1031 
1032   // Keep track of which bytes in the fixed and callee-save range are used so we
1033   // can use the holes when allocating later stack objects.  Only do this if
1034   // stack protector isn't being used and the target requests it and we're
1035   // optimizing.
1036   BitVector StackBytesFree;
1037   if (!ObjectsToAllocate.empty() &&
1038       MF.getTarget().getOptLevel() != CodeGenOpt::None &&
1039       MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(MF))
1040     computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex,
1041                           FixedCSEnd, StackBytesFree);
1042 
1043   // Now walk the objects and actually assign base offsets to them.
1044   for (auto &Object : ObjectsToAllocate)
1045     if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
1046                            StackBytesFree))
1047       AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
1048 
1049   // Make sure the special register scavenging spill slot is closest to the
1050   // stack pointer.
1051   if (RS && !EarlyScavengingSlots) {
1052     SmallVector<int, 2> SFIs;
1053     RS->getScavengingFrameIndices(SFIs);
1054     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
1055            IE = SFIs.end(); I != IE; ++I)
1056       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
1057   }
1058 
1059   if (!TFI.targetHandlesStackFrameRounding()) {
1060     // If we have reserved argument space for call sites in the function
1061     // immediately on entry to the current function, count it as part of the
1062     // overall stack size.
1063     if (MFI.adjustsStack() && TFI.hasReservedCallFrame(MF))
1064       Offset += MFI.getMaxCallFrameSize();
1065 
1066     // Round up the size to a multiple of the alignment.  If the function has
1067     // any calls or alloca's, align to the target's StackAlignment value to
1068     // ensure that the callee's frame or the alloca data is suitably aligned;
1069     // otherwise, for leaf functions, align to the TransientStackAlignment
1070     // value.
1071     unsigned StackAlign;
1072     if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
1073         (RegInfo->needsStackRealignment(MF) && MFI.getObjectIndexEnd() != 0))
1074       StackAlign = TFI.getStackAlignment();
1075     else
1076       StackAlign = TFI.getTransientStackAlignment();
1077 
1078     // If the frame pointer is eliminated, all frame offsets will be relative to
1079     // SP not FP. Align to MaxAlign so this works.
1080     StackAlign = std::max(StackAlign, MaxAlign);
1081     Offset = alignTo(Offset, StackAlign, Skew);
1082   }
1083 
1084   // Update frame info to pretend that this is part of the stack...
1085   int64_t StackSize = Offset - LocalAreaOffset;
1086   MFI.setStackSize(StackSize);
1087   NumBytesStackSpace += StackSize;
1088 }
1089 
1090 /// insertPrologEpilogCode - Scan the function for modified callee saved
1091 /// registers, insert spill code for these callee saved registers, then add
1092 /// prolog and epilog code to the function.
1093 void PEI::insertPrologEpilogCode(MachineFunction &MF) {
1094   const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1095 
1096   // Add prologue to the function...
1097   for (MachineBasicBlock *SaveBlock : SaveBlocks)
1098     TFI.emitPrologue(MF, *SaveBlock);
1099 
1100   // Add epilogue to restore the callee-save registers in each exiting block.
1101   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
1102     TFI.emitEpilogue(MF, *RestoreBlock);
1103 
1104   for (MachineBasicBlock *SaveBlock : SaveBlocks)
1105     TFI.inlineStackProbe(MF, *SaveBlock);
1106 
1107   // Emit additional code that is required to support segmented stacks, if
1108   // we've been asked for it.  This, when linked with a runtime with support
1109   // for segmented stacks (libgcc is one), will result in allocating stack
1110   // space in small chunks instead of one large contiguous block.
1111   if (MF.shouldSplitStack()) {
1112     for (MachineBasicBlock *SaveBlock : SaveBlocks)
1113       TFI.adjustForSegmentedStacks(MF, *SaveBlock);
1114     // Record that there are split-stack functions, so we will emit a
1115     // special section to tell the linker.
1116     MF.getMMI().setHasSplitStack(true);
1117   } else
1118     MF.getMMI().setHasNosplitStack(true);
1119 
1120   // Emit additional code that is required to explicitly handle the stack in
1121   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1122   // approach is rather similar to that of Segmented Stacks, but it uses a
1123   // different conditional check and another BIF for allocating more stack
1124   // space.
1125   if (MF.getFunction().getCallingConv() == CallingConv::HiPE)
1126     for (MachineBasicBlock *SaveBlock : SaveBlocks)
1127       TFI.adjustForHiPEPrologue(MF, *SaveBlock);
1128 }
1129 
1130 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1131 /// register references and actual offsets.
1132 void PEI::replaceFrameIndices(MachineFunction &MF) {
1133   const auto &ST = MF.getSubtarget();
1134   const TargetFrameLowering &TFI = *ST.getFrameLowering();
1135   if (!TFI.needsFrameIndexResolution(MF))
1136     return;
1137 
1138   const TargetRegisterInfo *TRI = ST.getRegisterInfo();
1139 
1140   // Allow the target to determine this after knowing the frame size.
1141   FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) ||
1142     TRI->requiresFrameIndexReplacementScavenging(MF);
1143 
1144   // Store SPAdj at exit of a basic block.
1145   SmallVector<int, 8> SPState;
1146   SPState.resize(MF.getNumBlockIDs());
1147   df_iterator_default_set<MachineBasicBlock*> Reachable;
1148 
1149   // Iterate over the reachable blocks in DFS order.
1150   for (auto DFI = df_ext_begin(&MF, Reachable), DFE = df_ext_end(&MF, Reachable);
1151        DFI != DFE; ++DFI) {
1152     int SPAdj = 0;
1153     // Check the exit state of the DFS stack predecessor.
1154     if (DFI.getPathLength() >= 2) {
1155       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1156       assert(Reachable.count(StackPred) &&
1157              "DFS stack predecessor is already visited.\n");
1158       SPAdj = SPState[StackPred->getNumber()];
1159     }
1160     MachineBasicBlock *BB = *DFI;
1161     replaceFrameIndices(BB, MF, SPAdj);
1162     SPState[BB->getNumber()] = SPAdj;
1163   }
1164 
1165   // Handle the unreachable blocks.
1166   for (auto &BB : MF) {
1167     if (Reachable.count(&BB))
1168       // Already handled in DFS traversal.
1169       continue;
1170     int SPAdj = 0;
1171     replaceFrameIndices(&BB, MF, SPAdj);
1172   }
1173 }
1174 
1175 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
1176                               int &SPAdj) {
1177   assert(MF.getSubtarget().getRegisterInfo() &&
1178          "getRegisterInfo() must be implemented!");
1179   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1180   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1181   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1182 
1183   if (RS && FrameIndexEliminationScavenging)
1184     RS->enterBasicBlock(*BB);
1185 
1186   bool InsideCallSequence = false;
1187 
1188   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1189     if (TII.isFrameInstr(*I)) {
1190       InsideCallSequence = TII.isFrameSetup(*I);
1191       SPAdj += TII.getSPAdjust(*I);
1192       I = TFI->eliminateCallFramePseudoInstr(MF, *BB, I);
1193       continue;
1194     }
1195 
1196     MachineInstr &MI = *I;
1197     bool DoIncr = true;
1198     bool DidFinishLoop = true;
1199     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1200       if (!MI.getOperand(i).isFI())
1201         continue;
1202 
1203       // Frame indices in debug values are encoded in a target independent
1204       // way with simply the frame index and offset rather than any
1205       // target-specific addressing mode.
1206       if (MI.isDebugValue()) {
1207         assert(i == 0 && "Frame indices can only appear as the first "
1208                          "operand of a DBG_VALUE machine instruction");
1209         unsigned Reg;
1210         unsigned FrameIdx = MI.getOperand(0).getIndex();
1211         unsigned Size = MF.getFrameInfo().getObjectSize(FrameIdx);
1212 
1213         int64_t Offset =
1214             TFI->getFrameIndexReference(MF, FrameIdx, Reg);
1215         MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
1216         MI.getOperand(0).setIsDebug();
1217 
1218         const DIExpression *DIExpr = MI.getDebugExpression();
1219 
1220         // If we have a direct DBG_VALUE, and its location expression isn't
1221         // currently complex, then adding an offset will morph it into a
1222         // complex location that is interpreted as being a memory address.
1223         // This changes a pointer-valued variable to dereference that pointer,
1224         // which is incorrect. Fix by adding DW_OP_stack_value.
1225         unsigned PrependFlags = DIExpression::ApplyOffset;
1226         if (!MI.isIndirectDebugValue() && !DIExpr->isComplex())
1227           PrependFlags |= DIExpression::StackValue;
1228 
1229         // If we have DBG_VALUE that is indirect and has a Implicit location
1230         // expression need to insert a deref before prepending a Memory
1231         // location expression. Also after doing this we change the DBG_VALUE
1232         // to be direct.
1233         if (MI.isIndirectDebugValue() && DIExpr->isImplicit()) {
1234           SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
1235           bool WithStackValue = true;
1236           DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1237           // Make the DBG_VALUE direct.
1238           MI.getOperand(1).ChangeToRegister(0, false);
1239         }
1240         DIExpr = DIExpression::prepend(DIExpr, PrependFlags, Offset);
1241         MI.getOperand(3).setMetadata(DIExpr);
1242         continue;
1243       }
1244 
1245       // TODO: This code should be commoned with the code for
1246       // PATCHPOINT. There's no good reason for the difference in
1247       // implementation other than historical accident.  The only
1248       // remaining difference is the unconditional use of the stack
1249       // pointer as the base register.
1250       if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1251         assert((!MI.isDebugValue() || i == 0) &&
1252                "Frame indicies can only appear as the first operand of a "
1253                "DBG_VALUE machine instruction");
1254         unsigned Reg;
1255         MachineOperand &Offset = MI.getOperand(i + 1);
1256         int refOffset = TFI->getFrameIndexReferencePreferSP(
1257             MF, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1258         Offset.setImm(Offset.getImm() + refOffset + SPAdj);
1259         MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
1260         continue;
1261       }
1262 
1263       // Some instructions (e.g. inline asm instructions) can have
1264       // multiple frame indices and/or cause eliminateFrameIndex
1265       // to insert more than one instruction. We need the register
1266       // scavenger to go through all of these instructions so that
1267       // it can update its register information. We keep the
1268       // iterator at the point before insertion so that we can
1269       // revisit them in full.
1270       bool AtBeginning = (I == BB->begin());
1271       if (!AtBeginning) --I;
1272 
1273       // If this instruction has a FrameIndex operand, we need to
1274       // use that target machine register info object to eliminate
1275       // it.
1276       TRI.eliminateFrameIndex(MI, SPAdj, i,
1277                               FrameIndexEliminationScavenging ?  RS : nullptr);
1278 
1279       // Reset the iterator if we were at the beginning of the BB.
1280       if (AtBeginning) {
1281         I = BB->begin();
1282         DoIncr = false;
1283       }
1284 
1285       DidFinishLoop = false;
1286       break;
1287     }
1288 
1289     // If we are looking at a call sequence, we need to keep track of
1290     // the SP adjustment made by each instruction in the sequence.
1291     // This includes both the frame setup/destroy pseudos (handled above),
1292     // as well as other instructions that have side effects w.r.t the SP.
1293     // Note that this must come after eliminateFrameIndex, because
1294     // if I itself referred to a frame index, we shouldn't count its own
1295     // adjustment.
1296     if (DidFinishLoop && InsideCallSequence)
1297       SPAdj += TII.getSPAdjust(MI);
1298 
1299     if (DoIncr && I != BB->end()) ++I;
1300 
1301     // Update register states.
1302     if (RS && FrameIndexEliminationScavenging && DidFinishLoop)
1303       RS->forward(MI);
1304   }
1305 }
1306