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