xref: /llvm-project/llvm/lib/CodeGen/PrologEpilogInserter.cpp (revision fc018ebb608ee0c1239b405460e49f1835ab6175)
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 INITIALIZE_PASS_BEGIN(PEI, DEBUG_TYPE, "Prologue/Epilogue Insertion", false,
142                       false)
143 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
144 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
145 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
146 INITIALIZE_PASS_END(PEI, DEBUG_TYPE,
147                     "Prologue/Epilogue Insertion & Frame Finalization", false,
148                     false)
149 
150 MachineFunctionPass *llvm::createPrologEpilogInserterPass() {
151   return new PEI();
152 }
153 
154 STATISTIC(NumBytesStackSpace,
155           "Number of bytes used for stack in all functions");
156 
157 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
158   AU.setPreservesCFG();
159   AU.addPreserved<MachineLoopInfo>();
160   AU.addPreserved<MachineDominatorTree>();
161   AU.addRequired<MachineOptimizationRemarkEmitterPass>();
162   MachineFunctionPass::getAnalysisUsage(AU);
163 }
164 
165 /// StackObjSet - A set of stack object indexes
166 using StackObjSet = SmallSetVector<int, 8>;
167 
168 using SavedDbgValuesMap =
169     SmallDenseMap<MachineBasicBlock *, SmallVector<MachineInstr *, 4>, 4>;
170 
171 /// Stash DBG_VALUEs that describe parameters and which are placed at the start
172 /// of the block. Later on, after the prologue code has been emitted, the
173 /// stashed DBG_VALUEs will be reinserted at the start of the block.
174 static void stashEntryDbgValues(MachineBasicBlock &MBB,
175                                 SavedDbgValuesMap &EntryDbgValues) {
176   SmallVector<const MachineInstr *, 4> FrameIndexValues;
177 
178   for (auto &MI : MBB) {
179     if (!MI.isDebugInstr())
180       break;
181     if (!MI.isDebugValue() || !MI.getDebugVariable()->isParameter())
182       continue;
183     if (any_of(MI.debug_operands(),
184                [](const MachineOperand &MO) { return MO.isFI(); })) {
185       // We can only emit valid locations for frame indices after the frame
186       // setup, so do not stash away them.
187       FrameIndexValues.push_back(&MI);
188       continue;
189     }
190     const DILocalVariable *Var = MI.getDebugVariable();
191     const DIExpression *Expr = MI.getDebugExpression();
192     auto Overlaps = [Var, Expr](const MachineInstr *DV) {
193       return Var == DV->getDebugVariable() &&
194              Expr->fragmentsOverlap(DV->getDebugExpression());
195     };
196     // See if the debug value overlaps with any preceding debug value that will
197     // not be stashed. If that is the case, then we can't stash this value, as
198     // we would then reorder the values at reinsertion.
199     if (llvm::none_of(FrameIndexValues, Overlaps))
200       EntryDbgValues[&MBB].push_back(&MI);
201   }
202 
203   // Remove stashed debug values from the block.
204   if (EntryDbgValues.count(&MBB))
205     for (auto *MI : EntryDbgValues[&MBB])
206       MI->removeFromParent();
207 }
208 
209 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
210 /// frame indexes with appropriate references.
211 bool PEI::runOnMachineFunction(MachineFunction &MF) {
212   NumFuncSeen++;
213   const Function &F = MF.getFunction();
214   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
215   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
216 
217   RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr;
218   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(MF);
219   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
220 
221   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
222   // function's frame information. Also eliminates call frame pseudo
223   // instructions.
224   calculateCallFrameInfo(MF);
225 
226   // Determine placement of CSR spill/restore code and prolog/epilog code:
227   // place all spills in the entry block, all restores in return blocks.
228   calculateSaveRestoreBlocks(MF);
229 
230   // Stash away DBG_VALUEs that should not be moved by insertion of prolog code.
231   SavedDbgValuesMap EntryDbgValues;
232   for (MachineBasicBlock *SaveBlock : SaveBlocks)
233     stashEntryDbgValues(*SaveBlock, EntryDbgValues);
234 
235   // Handle CSR spilling and restoring, for targets that need it.
236   if (MF.getTarget().usesPhysRegsForValues())
237     spillCalleeSavedRegs(MF);
238 
239   // Allow the target machine to make final modifications to the function
240   // before the frame layout is finalized.
241   TFI->processFunctionBeforeFrameFinalized(MF, RS);
242 
243   // Calculate actual frame offsets for all abstract stack objects...
244   calculateFrameObjectOffsets(MF);
245 
246   // Add prolog and epilog code to the function.  This function is required
247   // to align the stack frame as necessary for any stack variables or
248   // called functions.  Because of this, calculateCalleeSavedRegisters()
249   // must be called before this function in order to set the AdjustsStack
250   // and MaxCallFrameSize variables.
251   if (!F.hasFnAttribute(Attribute::Naked))
252     insertPrologEpilogCode(MF);
253 
254   // Reinsert stashed debug values at the start of the entry blocks.
255   for (auto &I : EntryDbgValues)
256     I.first->insert(I.first->begin(), I.second.begin(), I.second.end());
257 
258   // Allow the target machine to make final modifications to the function
259   // before the frame layout is finalized.
260   TFI->processFunctionBeforeFrameIndicesReplaced(MF, RS);
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 
277   unsigned Threshold = MF.getFunction().getParent()->getWarnStackSize();
278   if (StackSize > Threshold) {
279     DiagnosticInfoStackSize DiagStackSize(F, StackSize);
280     F.getContext().diagnose(DiagStackSize);
281   }
282   ORE->emit([&]() {
283     return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "StackSize",
284                                              MF.getFunction().getSubprogram(),
285                                              &MF.front())
286            << ore::NV("NumStackBytes", StackSize) << " stack bytes in function";
287   });
288 
289   delete RS;
290   SaveBlocks.clear();
291   RestoreBlocks.clear();
292   MFI.setSavePoint(nullptr);
293   MFI.setRestorePoint(nullptr);
294   return true;
295 }
296 
297 /// Calculate the MaxCallFrameSize and AdjustsStack
298 /// variables for the function's frame information and eliminate call frame
299 /// pseudo instructions.
300 void PEI::calculateCallFrameInfo(MachineFunction &MF) {
301   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
302   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
303   MachineFrameInfo &MFI = MF.getFrameInfo();
304 
305   unsigned MaxCallFrameSize = 0;
306   bool AdjustsStack = MFI.adjustsStack();
307 
308   // Get the function call frame set-up and tear-down instruction opcode
309   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
310   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
311 
312   // Early exit for targets which have no call frame setup/destroy pseudo
313   // instructions.
314   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
315     return;
316 
317   std::vector<MachineBasicBlock::iterator> FrameSDOps;
318   for (MachineBasicBlock &BB : MF)
319     for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I)
320       if (TII.isFrameInstr(*I)) {
321         unsigned Size = TII.getFrameSize(*I);
322         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
323         AdjustsStack = true;
324         FrameSDOps.push_back(I);
325       } else if (I->isInlineAsm()) {
326         // Some inline asm's need a stack frame, as indicated by operand 1.
327         unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
328         if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
329           AdjustsStack = true;
330       }
331 
332   assert(!MFI.isMaxCallFrameSizeComputed() ||
333          (MFI.getMaxCallFrameSize() == MaxCallFrameSize &&
334           MFI.adjustsStack() == AdjustsStack));
335   MFI.setAdjustsStack(AdjustsStack);
336   MFI.setMaxCallFrameSize(MaxCallFrameSize);
337 
338   for (MachineBasicBlock::iterator I : FrameSDOps) {
339     // If call frames are not being included as part of the stack frame, and
340     // the target doesn't indicate otherwise, remove the call frame pseudos
341     // here. The sub/add sp instruction pairs are still inserted, but we don't
342     // need to track the SP adjustment for frame index elimination.
343     if (TFI->canSimplifyCallFramePseudos(MF))
344       TFI->eliminateCallFramePseudoInstr(MF, *I->getParent(), I);
345   }
346 }
347 
348 /// Compute the sets of entry and return blocks for saving and restoring
349 /// callee-saved registers, and placing prolog and epilog code.
350 void PEI::calculateSaveRestoreBlocks(MachineFunction &MF) {
351   const MachineFrameInfo &MFI = MF.getFrameInfo();
352 
353   // Even when we do not change any CSR, we still want to insert the
354   // prologue and epilogue of the function.
355   // So set the save points for those.
356 
357   // Use the points found by shrink-wrapping, if any.
358   if (MFI.getSavePoint()) {
359     SaveBlocks.push_back(MFI.getSavePoint());
360     assert(MFI.getRestorePoint() && "Both restore and save must be set");
361     MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
362     // If RestoreBlock does not have any successor and is not a return block
363     // then the end point is unreachable and we do not need to insert any
364     // epilogue.
365     if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
366       RestoreBlocks.push_back(RestoreBlock);
367     return;
368   }
369 
370   // Save refs to entry and return blocks.
371   SaveBlocks.push_back(&MF.front());
372   for (MachineBasicBlock &MBB : MF) {
373     if (MBB.isEHFuncletEntry())
374       SaveBlocks.push_back(&MBB);
375     if (MBB.isReturnBlock())
376       RestoreBlocks.push_back(&MBB);
377   }
378 }
379 
380 static void assignCalleeSavedSpillSlots(MachineFunction &F,
381                                         const BitVector &SavedRegs,
382                                         unsigned &MinCSFrameIndex,
383                                         unsigned &MaxCSFrameIndex) {
384   if (SavedRegs.empty())
385     return;
386 
387   const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
388   const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
389 
390   std::vector<CalleeSavedInfo> CSI;
391   for (unsigned i = 0; CSRegs[i]; ++i) {
392     unsigned Reg = CSRegs[i];
393     if (SavedRegs.test(Reg))
394       CSI.push_back(CalleeSavedInfo(Reg));
395   }
396 
397   const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
398   MachineFrameInfo &MFI = F.getFrameInfo();
399   if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI, MinCSFrameIndex,
400                                         MaxCSFrameIndex)) {
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         Align Alignment = RegInfo->getSpillAlign(*RC);
438         // We may not be able to satisfy the desired alignment specification of
439         // the TargetRegisterClass if the stack alignment is smaller. Use the
440         // min.
441         Alignment = std::min(Alignment, TFI->getStackAlign());
442         FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
443         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
444         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
445       } else {
446         // Spill it to the stack where we must.
447         FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
448       }
449 
450       CS.setFrameIdx(FrameIdx);
451     }
452   }
453 
454   MFI.setCalleeSavedInfo(CSI);
455 }
456 
457 /// Helper function to update the liveness information for the callee-saved
458 /// registers.
459 static void updateLiveness(MachineFunction &MF) {
460   MachineFrameInfo &MFI = MF.getFrameInfo();
461   // Visited will contain all the basic blocks that are in the region
462   // where the callee saved registers are alive:
463   // - Anything that is not Save or Restore -> LiveThrough.
464   // - Save -> LiveIn.
465   // - Restore -> LiveOut.
466   // The live-out is not attached to the block, so no need to keep
467   // Restore in this set.
468   SmallPtrSet<MachineBasicBlock *, 8> Visited;
469   SmallVector<MachineBasicBlock *, 8> WorkList;
470   MachineBasicBlock *Entry = &MF.front();
471   MachineBasicBlock *Save = MFI.getSavePoint();
472 
473   if (!Save)
474     Save = Entry;
475 
476   if (Entry != Save) {
477     WorkList.push_back(Entry);
478     Visited.insert(Entry);
479   }
480   Visited.insert(Save);
481 
482   MachineBasicBlock *Restore = MFI.getRestorePoint();
483   if (Restore)
484     // By construction Restore cannot be visited, otherwise it
485     // means there exists a path to Restore that does not go
486     // through Save.
487     WorkList.push_back(Restore);
488 
489   while (!WorkList.empty()) {
490     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
491     // By construction, the region that is after the save point is
492     // dominated by the Save and post-dominated by the Restore.
493     if (CurBB == Save && Save != Restore)
494       continue;
495     // Enqueue all the successors not already visited.
496     // Those are by construction either before Save or after Restore.
497     for (MachineBasicBlock *SuccBB : CurBB->successors())
498       if (Visited.insert(SuccBB).second)
499         WorkList.push_back(SuccBB);
500   }
501 
502   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
503 
504   MachineRegisterInfo &MRI = MF.getRegInfo();
505   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
506     for (MachineBasicBlock *MBB : Visited) {
507       MCPhysReg Reg = CSI[i].getReg();
508       // Add the callee-saved register as live-in.
509       // It's killed at the spill.
510       if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg))
511         MBB->addLiveIn(Reg);
512     }
513     // If callee-saved register is spilled to another register rather than
514     // spilling to stack, the destination register has to be marked as live for
515     // each MBB between the prologue and epilogue so that it is not clobbered
516     // before it is reloaded in the epilogue. The Visited set contains all
517     // blocks outside of the region delimited by prologue/epilogue.
518     if (CSI[i].isSpilledToReg()) {
519       for (MachineBasicBlock &MBB : MF) {
520         if (Visited.count(&MBB))
521           continue;
522         MCPhysReg DstReg = CSI[i].getDstReg();
523         if (!MBB.isLiveIn(DstReg))
524           MBB.addLiveIn(DstReg);
525       }
526     }
527   }
528 
529 }
530 
531 /// Insert restore code for the callee-saved registers used in the function.
532 static void insertCSRSaves(MachineBasicBlock &SaveBlock,
533                            ArrayRef<CalleeSavedInfo> CSI) {
534   MachineFunction &MF = *SaveBlock.getParent();
535   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
536   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
537   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
538 
539   MachineBasicBlock::iterator I = SaveBlock.begin();
540   if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) {
541     for (const CalleeSavedInfo &CS : CSI) {
542       // Insert the spill to the stack frame.
543       unsigned Reg = CS.getReg();
544 
545       if (CS.isSpilledToReg()) {
546         BuildMI(SaveBlock, I, DebugLoc(),
547                 TII.get(TargetOpcode::COPY), CS.getDstReg())
548           .addReg(Reg, getKillRegState(true));
549       } else {
550         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
551         TII.storeRegToStackSlot(SaveBlock, I, Reg, true, CS.getFrameIdx(), RC,
552                                 TRI);
553       }
554     }
555   }
556 }
557 
558 /// Insert restore code for the callee-saved registers used in the function.
559 static void insertCSRRestores(MachineBasicBlock &RestoreBlock,
560                               std::vector<CalleeSavedInfo> &CSI) {
561   MachineFunction &MF = *RestoreBlock.getParent();
562   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
563   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
564   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
565 
566   // Restore all registers immediately before the return and any
567   // terminators that precede it.
568   MachineBasicBlock::iterator I = RestoreBlock.getFirstTerminator();
569 
570   if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) {
571     for (const CalleeSavedInfo &CI : reverse(CSI)) {
572       unsigned Reg = CI.getReg();
573       if (CI.isSpilledToReg()) {
574         BuildMI(RestoreBlock, I, DebugLoc(), TII.get(TargetOpcode::COPY), Reg)
575           .addReg(CI.getDstReg(), getKillRegState(true));
576       } else {
577         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
578         TII.loadRegFromStackSlot(RestoreBlock, I, Reg, CI.getFrameIdx(), RC, TRI);
579         assert(I != RestoreBlock.begin() &&
580                "loadRegFromStackSlot didn't insert any code!");
581         // Insert in reverse order.  loadRegFromStackSlot can insert
582         // multiple instructions.
583       }
584     }
585   }
586 }
587 
588 void PEI::spillCalleeSavedRegs(MachineFunction &MF) {
589   // We can't list this requirement in getRequiredProperties because some
590   // targets (WebAssembly) use virtual registers past this point, and the pass
591   // pipeline is set up without giving the passes a chance to look at the
592   // TargetMachine.
593   // FIXME: Find a way to express this in getRequiredProperties.
594   assert(MF.getProperties().hasProperty(
595       MachineFunctionProperties::Property::NoVRegs));
596 
597   const Function &F = MF.getFunction();
598   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
599   MachineFrameInfo &MFI = MF.getFrameInfo();
600   MinCSFrameIndex = std::numeric_limits<unsigned>::max();
601   MaxCSFrameIndex = 0;
602 
603   // Determine which of the registers in the callee save list should be saved.
604   BitVector SavedRegs;
605   TFI->determineCalleeSaves(MF, SavedRegs, RS);
606 
607   // Assign stack slots for any callee-saved registers that must be spilled.
608   assignCalleeSavedSpillSlots(MF, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex);
609 
610   // Add the code to save and restore the callee saved registers.
611   if (!F.hasFnAttribute(Attribute::Naked)) {
612     MFI.setCalleeSavedInfoValid(true);
613 
614     std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
615     if (!CSI.empty()) {
616       if (!MFI.hasCalls())
617         NumLeafFuncWithSpills++;
618 
619       for (MachineBasicBlock *SaveBlock : SaveBlocks)
620         insertCSRSaves(*SaveBlock, CSI);
621 
622       // Update the live-in information of all the blocks up to the save point.
623       updateLiveness(MF);
624 
625       for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
626         insertCSRRestores(*RestoreBlock, CSI);
627     }
628   }
629 }
630 
631 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
632 static inline void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
633                                      bool StackGrowsDown, int64_t &Offset,
634                                      Align &MaxAlign, unsigned Skew) {
635   // If the stack grows down, add the object size to find the lowest address.
636   if (StackGrowsDown)
637     Offset += MFI.getObjectSize(FrameIdx);
638 
639   Align Alignment = MFI.getObjectAlign(FrameIdx);
640 
641   // If the alignment of this object is greater than that of the stack, then
642   // increase the stack alignment to match.
643   MaxAlign = std::max(MaxAlign, Alignment);
644 
645   // Adjust to alignment boundary.
646   Offset = alignTo(Offset, Alignment, Skew);
647 
648   if (StackGrowsDown) {
649     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset
650                       << "]\n");
651     MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
652   } else {
653     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset
654                       << "]\n");
655     MFI.setObjectOffset(FrameIdx, Offset);
656     Offset += MFI.getObjectSize(FrameIdx);
657   }
658 }
659 
660 /// Compute which bytes of fixed and callee-save stack area are unused and keep
661 /// track of them in StackBytesFree.
662 static inline void
663 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
664                       unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
665                       int64_t FixedCSEnd, BitVector &StackBytesFree) {
666   // Avoid undefined int64_t -> int conversion below in extreme case.
667   if (FixedCSEnd > std::numeric_limits<int>::max())
668     return;
669 
670   StackBytesFree.resize(FixedCSEnd, true);
671 
672   SmallVector<int, 16> AllocatedFrameSlots;
673   // Add fixed objects.
674   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
675     // StackSlot scavenging is only implemented for the default stack.
676     if (MFI.getStackID(i) == TargetStackID::Default)
677       AllocatedFrameSlots.push_back(i);
678   // Add callee-save objects if there are any.
679   if (MinCSFrameIndex <= MaxCSFrameIndex) {
680     for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
681       if (MFI.getStackID(i) == TargetStackID::Default)
682         AllocatedFrameSlots.push_back(i);
683   }
684 
685   for (int i : AllocatedFrameSlots) {
686     // These are converted from int64_t, but they should always fit in int
687     // because of the FixedCSEnd check above.
688     int ObjOffset = MFI.getObjectOffset(i);
689     int ObjSize = MFI.getObjectSize(i);
690     int ObjStart, ObjEnd;
691     if (StackGrowsDown) {
692       // ObjOffset is negative when StackGrowsDown is true.
693       ObjStart = -ObjOffset - ObjSize;
694       ObjEnd = -ObjOffset;
695     } else {
696       ObjStart = ObjOffset;
697       ObjEnd = ObjOffset + ObjSize;
698     }
699     // Ignore fixed holes that are in the previous stack frame.
700     if (ObjEnd > 0)
701       StackBytesFree.reset(ObjStart, ObjEnd);
702   }
703 }
704 
705 /// Assign frame object to an unused portion of the stack in the fixed stack
706 /// object range.  Return true if the allocation was successful.
707 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
708                                      bool StackGrowsDown, Align MaxAlign,
709                                      BitVector &StackBytesFree) {
710   if (MFI.isVariableSizedObjectIndex(FrameIdx))
711     return false;
712 
713   if (StackBytesFree.none()) {
714     // clear it to speed up later scavengeStackSlot calls to
715     // StackBytesFree.none()
716     StackBytesFree.clear();
717     return false;
718   }
719 
720   Align ObjAlign = MFI.getObjectAlign(FrameIdx);
721   if (ObjAlign > MaxAlign)
722     return false;
723 
724   int64_t ObjSize = MFI.getObjectSize(FrameIdx);
725   int FreeStart;
726   for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
727        FreeStart = StackBytesFree.find_next(FreeStart)) {
728 
729     // Check that free space has suitable alignment.
730     unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
731     if (alignTo(ObjStart, ObjAlign) != ObjStart)
732       continue;
733 
734     if (FreeStart + ObjSize > StackBytesFree.size())
735       return false;
736 
737     bool AllBytesFree = true;
738     for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
739       if (!StackBytesFree.test(FreeStart + Byte)) {
740         AllBytesFree = false;
741         break;
742       }
743     if (AllBytesFree)
744       break;
745   }
746 
747   if (FreeStart == -1)
748     return false;
749 
750   if (StackGrowsDown) {
751     int ObjStart = -(FreeStart + ObjSize);
752     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
753                       << ObjStart << "]\n");
754     MFI.setObjectOffset(FrameIdx, ObjStart);
755   } else {
756     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
757                       << FreeStart << "]\n");
758     MFI.setObjectOffset(FrameIdx, FreeStart);
759   }
760 
761   StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
762   return true;
763 }
764 
765 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
766 /// those required to be close to the Stack Protector) to stack offsets.
767 static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
768                                   SmallSet<int, 16> &ProtectedObjs,
769                                   MachineFrameInfo &MFI, bool StackGrowsDown,
770                                   int64_t &Offset, Align &MaxAlign,
771                                   unsigned Skew) {
772 
773   for (int i : UnassignedObjs) {
774     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
775     ProtectedObjs.insert(i);
776   }
777 }
778 
779 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
780 /// abstract stack objects.
781 void PEI::calculateFrameObjectOffsets(MachineFunction &MF) {
782   const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
783 
784   bool StackGrowsDown =
785     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
786 
787   // Loop over all of the stack objects, assigning sequential addresses...
788   MachineFrameInfo &MFI = MF.getFrameInfo();
789 
790   // Start at the beginning of the local area.
791   // The Offset is the distance from the stack top in the direction
792   // of stack growth -- so it's always nonnegative.
793   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
794   if (StackGrowsDown)
795     LocalAreaOffset = -LocalAreaOffset;
796   assert(LocalAreaOffset >= 0
797          && "Local area offset should be in direction of stack growth");
798   int64_t Offset = LocalAreaOffset;
799 
800   // Skew to be applied to alignment.
801   unsigned Skew = TFI.getStackAlignmentSkew(MF);
802 
803 #ifdef EXPENSIVE_CHECKS
804   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i)
805     if (!MFI.isDeadObjectIndex(i) &&
806         MFI.getStackID(i) == TargetStackID::Default)
807       assert(MFI.getObjectAlign(i) <= MFI.getMaxAlign() &&
808              "MaxAlignment is invalid");
809 #endif
810 
811   // If there are fixed sized objects that are preallocated in the local area,
812   // non-fixed objects can't be allocated right at the start of local area.
813   // Adjust 'Offset' to point to the end of last fixed sized preallocated
814   // object.
815   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
816     if (MFI.getStackID(i) !=
817         TargetStackID::Default) // Only allocate objects on the default stack.
818       continue;
819 
820     int64_t FixedOff;
821     if (StackGrowsDown) {
822       // The maximum distance from the stack pointer is at lower address of
823       // the object -- which is given by offset. For down growing stack
824       // the offset is negative, so we negate the offset to get the distance.
825       FixedOff = -MFI.getObjectOffset(i);
826     } else {
827       // The maximum distance from the start pointer is at the upper
828       // address of the object.
829       FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
830     }
831     if (FixedOff > Offset) Offset = FixedOff;
832   }
833 
834   // First assign frame offsets to stack objects that are used to spill
835   // callee saved registers.
836   if (StackGrowsDown && MaxCSFrameIndex >= MinCSFrameIndex) {
837     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
838       if (MFI.getStackID(i) !=
839           TargetStackID::Default) // Only allocate objects on the default stack.
840         continue;
841 
842       // If the stack grows down, we need to add the size to find the lowest
843       // address of the object.
844       Offset += MFI.getObjectSize(i);
845 
846       // Adjust to alignment boundary
847       Offset = alignTo(Offset, MFI.getObjectAlign(i), Skew);
848 
849       LLVM_DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
850       MFI.setObjectOffset(i, -Offset);        // Set the computed offset
851     }
852   } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
853     // Be careful about underflow in comparisons agains MinCSFrameIndex.
854     for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
855       if (MFI.getStackID(i) !=
856           TargetStackID::Default) // Only allocate objects on the default stack.
857         continue;
858 
859       if (MFI.isDeadObjectIndex(i))
860         continue;
861 
862       // Adjust to alignment boundary
863       Offset = alignTo(Offset, MFI.getObjectAlign(i), Skew);
864 
865       LLVM_DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
866       MFI.setObjectOffset(i, Offset);
867       Offset += MFI.getObjectSize(i);
868     }
869   }
870 
871   // FixedCSEnd is the stack offset to the end of the fixed and callee-save
872   // stack area.
873   int64_t FixedCSEnd = Offset;
874   Align MaxAlign = MFI.getMaxAlign();
875 
876   // Make sure the special register scavenging spill slot is closest to the
877   // incoming stack pointer if a frame pointer is required and is closer
878   // to the incoming rather than the final stack pointer.
879   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
880   bool EarlyScavengingSlots = (TFI.hasFP(MF) && TFI.isFPCloseToIncomingSP() &&
881                                RegInfo->useFPForScavengingIndex(MF) &&
882                                !RegInfo->hasStackRealignment(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->hasStackRealignment(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 (StackGrowsDown && OffsetBeforeAlignment != Offset && RS &&
1080         !EarlyScavengingSlots) {
1081       SmallVector<int, 2> SFIs;
1082       RS->getScavengingFrameIndices(SFIs);
1083       LLVM_DEBUG(if (!SFIs.empty()) llvm::dbgs()
1084                      << "Adjusting emergency spill slots!\n";);
1085       int64_t Delta = Offset - OffsetBeforeAlignment;
1086       for (int SFI : SFIs) {
1087         LLVM_DEBUG(llvm::dbgs()
1088                        << "Adjusting offset of emergency spill slot #" << SFI
1089                        << " from " << MFI.getObjectOffset(SFI););
1090         MFI.setObjectOffset(SFI, MFI.getObjectOffset(SFI) - Delta);
1091         LLVM_DEBUG(llvm::dbgs() << " to " << MFI.getObjectOffset(SFI) << "\n";);
1092       }
1093     }
1094   }
1095 
1096   // Update frame info to pretend that this is part of the stack...
1097   int64_t StackSize = Offset - LocalAreaOffset;
1098   MFI.setStackSize(StackSize);
1099   NumBytesStackSpace += StackSize;
1100 }
1101 
1102 /// insertPrologEpilogCode - Scan the function for modified callee saved
1103 /// registers, insert spill code for these callee saved registers, then add
1104 /// prolog and epilog code to the function.
1105 void PEI::insertPrologEpilogCode(MachineFunction &MF) {
1106   const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1107 
1108   // Add prologue to the function...
1109   for (MachineBasicBlock *SaveBlock : SaveBlocks)
1110     TFI.emitPrologue(MF, *SaveBlock);
1111 
1112   // Add epilogue to restore the callee-save registers in each exiting block.
1113   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
1114     TFI.emitEpilogue(MF, *RestoreBlock);
1115 
1116   for (MachineBasicBlock *SaveBlock : SaveBlocks)
1117     TFI.inlineStackProbe(MF, *SaveBlock);
1118 
1119   // Emit additional code that is required to support segmented stacks, if
1120   // we've been asked for it.  This, when linked with a runtime with support
1121   // for segmented stacks (libgcc is one), will result in allocating stack
1122   // space in small chunks instead of one large contiguous block.
1123   if (MF.shouldSplitStack()) {
1124     for (MachineBasicBlock *SaveBlock : SaveBlocks)
1125       TFI.adjustForSegmentedStacks(MF, *SaveBlock);
1126     // Record that there are split-stack functions, so we will emit a
1127     // special section to tell the linker.
1128     MF.getMMI().setHasSplitStack(true);
1129   } else
1130     MF.getMMI().setHasNosplitStack(true);
1131 
1132   // Emit additional code that is required to explicitly handle the stack in
1133   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1134   // approach is rather similar to that of Segmented Stacks, but it uses a
1135   // different conditional check and another BIF for allocating more stack
1136   // space.
1137   if (MF.getFunction().getCallingConv() == CallingConv::HiPE)
1138     for (MachineBasicBlock *SaveBlock : SaveBlocks)
1139       TFI.adjustForHiPEPrologue(MF, *SaveBlock);
1140 }
1141 
1142 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1143 /// register references and actual offsets.
1144 void PEI::replaceFrameIndices(MachineFunction &MF) {
1145   const auto &ST = MF.getSubtarget();
1146   const TargetFrameLowering &TFI = *ST.getFrameLowering();
1147   if (!TFI.needsFrameIndexResolution(MF))
1148     return;
1149 
1150   const TargetRegisterInfo *TRI = ST.getRegisterInfo();
1151 
1152   // Allow the target to determine this after knowing the frame size.
1153   FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) ||
1154     TRI->requiresFrameIndexReplacementScavenging(MF);
1155 
1156   // Store SPAdj at exit of a basic block.
1157   SmallVector<int, 8> SPState;
1158   SPState.resize(MF.getNumBlockIDs());
1159   df_iterator_default_set<MachineBasicBlock*> Reachable;
1160 
1161   // Iterate over the reachable blocks in DFS order.
1162   for (auto DFI = df_ext_begin(&MF, Reachable), DFE = df_ext_end(&MF, Reachable);
1163        DFI != DFE; ++DFI) {
1164     int SPAdj = 0;
1165     // Check the exit state of the DFS stack predecessor.
1166     if (DFI.getPathLength() >= 2) {
1167       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1168       assert(Reachable.count(StackPred) &&
1169              "DFS stack predecessor is already visited.\n");
1170       SPAdj = SPState[StackPred->getNumber()];
1171     }
1172     MachineBasicBlock *BB = *DFI;
1173     replaceFrameIndices(BB, MF, SPAdj);
1174     SPState[BB->getNumber()] = SPAdj;
1175   }
1176 
1177   // Handle the unreachable blocks.
1178   for (auto &BB : MF) {
1179     if (Reachable.count(&BB))
1180       // Already handled in DFS traversal.
1181       continue;
1182     int SPAdj = 0;
1183     replaceFrameIndices(&BB, MF, SPAdj);
1184   }
1185 }
1186 
1187 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
1188                               int &SPAdj) {
1189   assert(MF.getSubtarget().getRegisterInfo() &&
1190          "getRegisterInfo() must be implemented!");
1191   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1192   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1193   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1194 
1195   if (RS && FrameIndexEliminationScavenging)
1196     RS->enterBasicBlock(*BB);
1197 
1198   bool InsideCallSequence = false;
1199 
1200   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1201     if (TII.isFrameInstr(*I)) {
1202       InsideCallSequence = TII.isFrameSetup(*I);
1203       SPAdj += TII.getSPAdjust(*I);
1204       I = TFI->eliminateCallFramePseudoInstr(MF, *BB, I);
1205       continue;
1206     }
1207 
1208     MachineInstr &MI = *I;
1209     bool DoIncr = true;
1210     bool DidFinishLoop = true;
1211     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1212       if (!MI.getOperand(i).isFI())
1213         continue;
1214 
1215       // Frame indices in debug values are encoded in a target independent
1216       // way with simply the frame index and offset rather than any
1217       // target-specific addressing mode.
1218       if (MI.isDebugValue()) {
1219         MachineOperand &Op = MI.getOperand(i);
1220         assert(
1221             MI.isDebugOperand(&Op) &&
1222             "Frame indices can only appear as a debug operand in a DBG_VALUE*"
1223             " machine instruction");
1224         Register Reg;
1225         unsigned FrameIdx = Op.getIndex();
1226         unsigned Size = MF.getFrameInfo().getObjectSize(FrameIdx);
1227 
1228         StackOffset Offset =
1229             TFI->getFrameIndexReference(MF, FrameIdx, Reg);
1230         Op.ChangeToRegister(Reg, false /*isDef*/);
1231         Op.setIsDebug();
1232 
1233         const DIExpression *DIExpr = MI.getDebugExpression();
1234 
1235         // If we have a direct DBG_VALUE, and its location expression isn't
1236         // currently complex, then adding an offset will morph it into a
1237         // complex location that is interpreted as being a memory address.
1238         // This changes a pointer-valued variable to dereference that pointer,
1239         // which is incorrect. Fix by adding DW_OP_stack_value.
1240 
1241         if (MI.isNonListDebugValue()) {
1242           unsigned PrependFlags = DIExpression::ApplyOffset;
1243           if (!MI.isIndirectDebugValue() && !DIExpr->isComplex())
1244             PrependFlags |= DIExpression::StackValue;
1245 
1246           // If we have DBG_VALUE that is indirect and has a Implicit location
1247           // expression need to insert a deref before prepending a Memory
1248           // location expression. Also after doing this we change the DBG_VALUE
1249           // to be direct.
1250           if (MI.isIndirectDebugValue() && DIExpr->isImplicit()) {
1251             SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
1252             bool WithStackValue = true;
1253             DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1254             // Make the DBG_VALUE direct.
1255             MI.getDebugOffset().ChangeToRegister(0, false);
1256           }
1257           DIExpr = TRI.prependOffsetExpression(DIExpr, PrependFlags, Offset);
1258         } else {
1259           // The debug operand at DebugOpIndex was a frame index at offset
1260           // `Offset`; now the operand has been replaced with the frame
1261           // register, we must add Offset with `register x, plus Offset`.
1262           unsigned DebugOpIndex = MI.getDebugOperandIndex(&Op);
1263           SmallVector<uint64_t, 3> Ops;
1264           TRI.getOffsetOpcodes(Offset, Ops);
1265           DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, DebugOpIndex);
1266         }
1267         MI.getDebugExpressionOp().setMetadata(DIExpr);
1268         continue;
1269       } else if (MI.isDebugPHI()) {
1270         // Allow stack ref to continue onwards.
1271         continue;
1272       }
1273 
1274       // TODO: This code should be commoned with the code for
1275       // PATCHPOINT. There's no good reason for the difference in
1276       // implementation other than historical accident.  The only
1277       // remaining difference is the unconditional use of the stack
1278       // pointer as the base register.
1279       if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1280         assert((!MI.isDebugValue() || i == 0) &&
1281                "Frame indicies can only appear as the first operand of a "
1282                "DBG_VALUE machine instruction");
1283         Register Reg;
1284         MachineOperand &Offset = MI.getOperand(i + 1);
1285         StackOffset refOffset = TFI->getFrameIndexReferencePreferSP(
1286             MF, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1287         assert(!refOffset.getScalable() &&
1288                "Frame offsets with a scalable component are not supported");
1289         Offset.setImm(Offset.getImm() + refOffset.getFixed() + SPAdj);
1290         MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
1291         continue;
1292       }
1293 
1294       // Some instructions (e.g. inline asm instructions) can have
1295       // multiple frame indices and/or cause eliminateFrameIndex
1296       // to insert more than one instruction. We need the register
1297       // scavenger to go through all of these instructions so that
1298       // it can update its register information. We keep the
1299       // iterator at the point before insertion so that we can
1300       // revisit them in full.
1301       bool AtBeginning = (I == BB->begin());
1302       if (!AtBeginning) --I;
1303 
1304       // If this instruction has a FrameIndex operand, we need to
1305       // use that target machine register info object to eliminate
1306       // it.
1307       TRI.eliminateFrameIndex(MI, SPAdj, i,
1308                               FrameIndexEliminationScavenging ?  RS : nullptr);
1309 
1310       // Reset the iterator if we were at the beginning of the BB.
1311       if (AtBeginning) {
1312         I = BB->begin();
1313         DoIncr = false;
1314       }
1315 
1316       DidFinishLoop = false;
1317       break;
1318     }
1319 
1320     // If we are looking at a call sequence, we need to keep track of
1321     // the SP adjustment made by each instruction in the sequence.
1322     // This includes both the frame setup/destroy pseudos (handled above),
1323     // as well as other instructions that have side effects w.r.t the SP.
1324     // Note that this must come after eliminateFrameIndex, because
1325     // if I itself referred to a frame index, we shouldn't count its own
1326     // adjustment.
1327     if (DidFinishLoop && InsideCallSequence)
1328       SPAdj += TII.getSPAdjust(MI);
1329 
1330     if (DoIncr && I != BB->end()) ++I;
1331 
1332     // Update register states.
1333     if (RS && FrameIndexEliminationScavenging && DidFinishLoop)
1334       RS->forward(MI);
1335   }
1336 }
1337