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