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