]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/PrologEpilogInserter.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303197, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / PrologEpilogInserter.cpp
1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
12 // function.
13 //
14 // This pass must be run after register allocation.  After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/RegisterScavenging.h"
31 #include "llvm/CodeGen/StackProtector.h"
32 #include "llvm/CodeGen/WinEHFuncInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetFrameLowering.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include <climits>
45
46 using namespace llvm;
47
48 #define DEBUG_TYPE "pei"
49
50 typedef SmallVector<MachineBasicBlock *, 4> MBBVector;
51 static void doSpillCalleeSavedRegs(MachineFunction &MF, RegScavenger *RS,
52                                    unsigned &MinCSFrameIndex,
53                                    unsigned &MaxCXFrameIndex,
54                                    const MBBVector &SaveBlocks,
55                                    const MBBVector &RestoreBlocks);
56
57 static void doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS);
58
59 namespace {
60 class PEI : public MachineFunctionPass {
61 public:
62   static char ID;
63   explicit PEI(const TargetMachine *TM = nullptr) : MachineFunctionPass(ID) {
64     initializePEIPass(*PassRegistry::getPassRegistry());
65
66     if (TM && (!TM->usesPhysRegsForPEI())) {
67       SpillCalleeSavedRegisters = [](MachineFunction &, RegScavenger *,
68                                      unsigned &, unsigned &, const MBBVector &,
69                                      const MBBVector &) {};
70       ScavengeFrameVirtualRegs = [](MachineFunction &, RegScavenger *) {};
71     } else {
72       SpillCalleeSavedRegisters = doSpillCalleeSavedRegs;
73       ScavengeFrameVirtualRegs = doScavengeFrameVirtualRegs;
74       UsesCalleeSaves = true;
75     }
76   }
77
78   void getAnalysisUsage(AnalysisUsage &AU) const override;
79
80   MachineFunctionProperties getRequiredProperties() const override {
81     MachineFunctionProperties MFP;
82     if (UsesCalleeSaves)
83       MFP.set(MachineFunctionProperties::Property::NoVRegs);
84     return MFP;
85   }
86
87   /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
88   /// frame indexes with appropriate references.
89   ///
90   bool runOnMachineFunction(MachineFunction &Fn) override;
91
92 private:
93   std::function<void(MachineFunction &MF, RegScavenger *RS,
94                      unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex,
95                      const MBBVector &SaveBlocks,
96                      const MBBVector &RestoreBlocks)>
97       SpillCalleeSavedRegisters;
98   std::function<void(MachineFunction &MF, RegScavenger *RS)>
99       ScavengeFrameVirtualRegs;
100
101   bool UsesCalleeSaves = false;
102
103   RegScavenger *RS;
104
105   // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
106   // stack frame indexes.
107   unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max();
108   unsigned MaxCSFrameIndex = 0;
109
110   // Save and Restore blocks of the current function. Typically there is a
111   // single save block, unless Windows EH funclets are involved.
112   MBBVector SaveBlocks;
113   MBBVector RestoreBlocks;
114
115   // Flag to control whether to use the register scavenger to resolve
116   // frame index materialization registers. Set according to
117   // TRI->requiresFrameIndexScavenging() for the current function.
118   bool FrameIndexVirtualScavenging;
119
120   // Flag to control whether the scavenger should be passed even though
121   // FrameIndexVirtualScavenging is used.
122   bool FrameIndexEliminationScavenging;
123
124   void calculateCallFrameInfo(MachineFunction &Fn);
125   void calculateSaveRestoreBlocks(MachineFunction &Fn);
126
127   void calculateFrameObjectOffsets(MachineFunction &Fn);
128   void replaceFrameIndices(MachineFunction &Fn);
129   void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
130                            int &SPAdj);
131   void insertPrologEpilogCode(MachineFunction &Fn);
132 };
133 } // namespace
134
135 char PEI::ID = 0;
136 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
137
138 static cl::opt<unsigned>
139 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
140               cl::desc("Warn for stack size bigger than the given"
141                        " number"));
142
143 INITIALIZE_TM_PASS_BEGIN(PEI, "prologepilog", "Prologue/Epilogue Insertion",
144                          false, false)
145 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
146 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
147 INITIALIZE_PASS_DEPENDENCY(StackProtector)
148 INITIALIZE_TM_PASS_END(PEI, "prologepilog",
149                        "Prologue/Epilogue Insertion & Frame Finalization",
150                        false, false)
151
152 MachineFunctionPass *
153 llvm::createPrologEpilogInserterPass(const TargetMachine *TM) {
154   return new PEI(TM);
155 }
156
157 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
158 STATISTIC(NumBytesStackSpace,
159           "Number of bytes used for stack in all functions");
160
161 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
162   AU.setPreservesCFG();
163   AU.addPreserved<MachineLoopInfo>();
164   AU.addPreserved<MachineDominatorTree>();
165   AU.addRequired<StackProtector>();
166   MachineFunctionPass::getAnalysisUsage(AU);
167 }
168
169
170 /// StackObjSet - A set of stack object indexes
171 typedef SmallSetVector<int, 8> StackObjSet;
172
173 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
174 /// frame indexes with appropriate references.
175 ///
176 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
177   const Function* F = Fn.getFunction();
178   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
179   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
180
181   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
182   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
183   FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) ||
184     TRI->requiresFrameIndexReplacementScavenging(Fn);
185
186   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
187   // function's frame information. Also eliminates call frame pseudo
188   // instructions.
189   calculateCallFrameInfo(Fn);
190
191   // Determine placement of CSR spill/restore code and prolog/epilog code:
192   // place all spills in the entry block, all restores in return blocks.
193   calculateSaveRestoreBlocks(Fn);
194
195   // Handle CSR spilling and restoring, for targets that need it.
196   SpillCalleeSavedRegisters(Fn, RS, MinCSFrameIndex, MaxCSFrameIndex,
197                             SaveBlocks, RestoreBlocks);
198
199   // Allow the target machine to make final modifications to the function
200   // before the frame layout is finalized.
201   TFI->processFunctionBeforeFrameFinalized(Fn, RS);
202
203   // Calculate actual frame offsets for all abstract stack objects...
204   calculateFrameObjectOffsets(Fn);
205
206   // Add prolog and epilog code to the function.  This function is required
207   // to align the stack frame as necessary for any stack variables or
208   // called functions.  Because of this, calculateCalleeSavedRegisters()
209   // must be called before this function in order to set the AdjustsStack
210   // and MaxCallFrameSize variables.
211   if (!F->hasFnAttribute(Attribute::Naked))
212     insertPrologEpilogCode(Fn);
213
214   // Replace all MO_FrameIndex operands with physical register references
215   // and actual offsets.
216   //
217   replaceFrameIndices(Fn);
218
219   // If register scavenging is needed, as we've enabled doing it as a
220   // post-pass, scavenge the virtual registers that frame index elimination
221   // inserted.
222   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) {
223       ScavengeFrameVirtualRegs(Fn, RS);
224
225       // Clear any vregs created by virtual scavenging.
226       Fn.getRegInfo().clearVirtRegs();
227   }
228
229   // Warn on stack size when we exceeds the given limit.
230   MachineFrameInfo &MFI = Fn.getFrameInfo();
231   uint64_t StackSize = MFI.getStackSize();
232   if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
233     DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
234     F->getContext().diagnose(DiagStackSize);
235   }
236
237   delete RS;
238   SaveBlocks.clear();
239   RestoreBlocks.clear();
240   MFI.setSavePoint(nullptr);
241   MFI.setRestorePoint(nullptr);
242   return true;
243 }
244
245 /// Calculate the MaxCallFrameSize and AdjustsStack
246 /// variables for the function's frame information and eliminate call frame
247 /// pseudo instructions.
248 void PEI::calculateCallFrameInfo(MachineFunction &Fn) {
249   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
250   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
251   MachineFrameInfo &MFI = Fn.getFrameInfo();
252
253   unsigned MaxCallFrameSize = 0;
254   bool AdjustsStack = MFI.adjustsStack();
255
256   // Get the function call frame set-up and tear-down instruction opcode
257   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
258   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
259
260   // Early exit for targets which have no call frame setup/destroy pseudo
261   // instructions.
262   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
263     return;
264
265   std::vector<MachineBasicBlock::iterator> FrameSDOps;
266   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
267     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
268       if (TII.isFrameInstr(*I)) {
269         unsigned Size = TII.getFrameSize(*I);
270         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
271         AdjustsStack = true;
272         FrameSDOps.push_back(I);
273       } else if (I->isInlineAsm()) {
274         // Some inline asm's need a stack frame, as indicated by operand 1.
275         unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
276         if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
277           AdjustsStack = true;
278       }
279
280   assert(!MFI.isMaxCallFrameSizeComputed() ||
281          (MFI.getMaxCallFrameSize() == MaxCallFrameSize &&
282           MFI.adjustsStack() == AdjustsStack));
283   MFI.setAdjustsStack(AdjustsStack);
284   MFI.setMaxCallFrameSize(MaxCallFrameSize);
285
286   for (std::vector<MachineBasicBlock::iterator>::iterator
287          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
288     MachineBasicBlock::iterator I = *i;
289
290     // If call frames are not being included as part of the stack frame, and
291     // the target doesn't indicate otherwise, remove the call frame pseudos
292     // here. The sub/add sp instruction pairs are still inserted, but we don't
293     // need to track the SP adjustment for frame index elimination.
294     if (TFI->canSimplifyCallFramePseudos(Fn))
295       TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
296   }
297 }
298
299 /// Compute the sets of entry and return blocks for saving and restoring
300 /// callee-saved registers, and placing prolog and epilog code.
301 void PEI::calculateSaveRestoreBlocks(MachineFunction &Fn) {
302   const MachineFrameInfo &MFI = Fn.getFrameInfo();
303
304   // Even when we do not change any CSR, we still want to insert the
305   // prologue and epilogue of the function.
306   // So set the save points for those.
307
308   // Use the points found by shrink-wrapping, if any.
309   if (MFI.getSavePoint()) {
310     SaveBlocks.push_back(MFI.getSavePoint());
311     assert(MFI.getRestorePoint() && "Both restore and save must be set");
312     MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
313     // If RestoreBlock does not have any successor and is not a return block
314     // then the end point is unreachable and we do not need to insert any
315     // epilogue.
316     if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
317       RestoreBlocks.push_back(RestoreBlock);
318     return;
319   }
320
321   // Save refs to entry and return blocks.
322   SaveBlocks.push_back(&Fn.front());
323   for (MachineBasicBlock &MBB : Fn) {
324     if (MBB.isEHFuncletEntry())
325       SaveBlocks.push_back(&MBB);
326     if (MBB.isReturnBlock())
327       RestoreBlocks.push_back(&MBB);
328   }
329 }
330
331 static void assignCalleeSavedSpillSlots(MachineFunction &F,
332                                         const BitVector &SavedRegs,
333                                         unsigned &MinCSFrameIndex,
334                                         unsigned &MaxCSFrameIndex) {
335   if (SavedRegs.empty())
336     return;
337
338   const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
339   const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
340
341   std::vector<CalleeSavedInfo> CSI;
342   for (unsigned i = 0; CSRegs[i]; ++i) {
343     unsigned Reg = CSRegs[i];
344     if (SavedRegs.test(Reg))
345       CSI.push_back(CalleeSavedInfo(Reg));
346   }
347
348   const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
349   MachineFrameInfo &MFI = F.getFrameInfo();
350   if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
351     // If target doesn't implement this, use generic code.
352
353     if (CSI.empty())
354       return; // Early exit if no callee saved registers are modified!
355
356     unsigned NumFixedSpillSlots;
357     const TargetFrameLowering::SpillSlot *FixedSpillSlots =
358         TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
359
360     // Now that we know which registers need to be saved and restored, allocate
361     // stack slots for them.
362     for (auto &CS : CSI) {
363       unsigned Reg = CS.getReg();
364       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
365
366       int FrameIdx;
367       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
368         CS.setFrameIdx(FrameIdx);
369         continue;
370       }
371
372       // Check to see if this physreg must be spilled to a particular stack slot
373       // on this target.
374       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
375       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
376              FixedSlot->Reg != Reg)
377         ++FixedSlot;
378
379       unsigned Size = RegInfo->getSpillSize(*RC);
380       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
381         // Nope, just spill it anywhere convenient.
382         unsigned Align = RegInfo->getSpillAlignment(*RC);
383         unsigned StackAlign = TFI->getStackAlignment();
384
385         // We may not be able to satisfy the desired alignment specification of
386         // the TargetRegisterClass if the stack alignment is smaller. Use the
387         // min.
388         Align = std::min(Align, StackAlign);
389         FrameIdx = MFI.CreateStackObject(Size, Align, true);
390         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
391         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
392       } else {
393         // Spill it to the stack where we must.
394         FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
395       }
396
397       CS.setFrameIdx(FrameIdx);
398     }
399   }
400
401   MFI.setCalleeSavedInfo(CSI);
402 }
403
404 /// Helper function to update the liveness information for the callee-saved
405 /// registers.
406 static void updateLiveness(MachineFunction &MF) {
407   MachineFrameInfo &MFI = MF.getFrameInfo();
408   // Visited will contain all the basic blocks that are in the region
409   // where the callee saved registers are alive:
410   // - Anything that is not Save or Restore -> LiveThrough.
411   // - Save -> LiveIn.
412   // - Restore -> LiveOut.
413   // The live-out is not attached to the block, so no need to keep
414   // Restore in this set.
415   SmallPtrSet<MachineBasicBlock *, 8> Visited;
416   SmallVector<MachineBasicBlock *, 8> WorkList;
417   MachineBasicBlock *Entry = &MF.front();
418   MachineBasicBlock *Save = MFI.getSavePoint();
419
420   if (!Save)
421     Save = Entry;
422
423   if (Entry != Save) {
424     WorkList.push_back(Entry);
425     Visited.insert(Entry);
426   }
427   Visited.insert(Save);
428
429   MachineBasicBlock *Restore = MFI.getRestorePoint();
430   if (Restore)
431     // By construction Restore cannot be visited, otherwise it
432     // means there exists a path to Restore that does not go
433     // through Save.
434     WorkList.push_back(Restore);
435
436   while (!WorkList.empty()) {
437     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
438     // By construction, the region that is after the save point is
439     // dominated by the Save and post-dominated by the Restore.
440     if (CurBB == Save && Save != Restore)
441       continue;
442     // Enqueue all the successors not already visited.
443     // Those are by construction either before Save or after Restore.
444     for (MachineBasicBlock *SuccBB : CurBB->successors())
445       if (Visited.insert(SuccBB).second)
446         WorkList.push_back(SuccBB);
447   }
448
449   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
450
451   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
452     for (MachineBasicBlock *MBB : Visited) {
453       MCPhysReg Reg = CSI[i].getReg();
454       // Add the callee-saved register as live-in.
455       // It's killed at the spill.
456       if (!MBB->isLiveIn(Reg))
457         MBB->addLiveIn(Reg);
458     }
459   }
460 }
461
462 /// insertCSRSpillsAndRestores - Insert spill and restore code for
463 /// callee saved registers used in the function.
464 ///
465 static void insertCSRSpillsAndRestores(MachineFunction &Fn,
466                                        const MBBVector &SaveBlocks,
467                                        const MBBVector &RestoreBlocks) {
468   // Get callee saved register information.
469   MachineFrameInfo &MFI = Fn.getFrameInfo();
470   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
471
472   MFI.setCalleeSavedInfoValid(true);
473
474   // Early exit if no callee saved registers are modified!
475   if (CSI.empty())
476     return;
477
478   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
479   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
480   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
481   MachineBasicBlock::iterator I;
482
483   // Spill using target interface.
484   for (MachineBasicBlock *SaveBlock : SaveBlocks) {
485     I = SaveBlock->begin();
486     if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
487       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
488         // Insert the spill to the stack frame.
489         unsigned Reg = CSI[i].getReg();
490         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
491         TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
492                                 RC, TRI);
493       }
494     }
495     // Update the live-in information of all the blocks up to the save point.
496     updateLiveness(Fn);
497   }
498
499   // Restore using target interface.
500   for (MachineBasicBlock *MBB : RestoreBlocks) {
501     I = MBB->end();
502
503     // Skip over all terminator instructions, which are part of the return
504     // sequence.
505     MachineBasicBlock::iterator I2 = I;
506     while (I2 != MBB->begin() && (--I2)->isTerminator())
507       I = I2;
508
509     bool AtStart = I == MBB->begin();
510     MachineBasicBlock::iterator BeforeI = I;
511     if (!AtStart)
512       --BeforeI;
513
514     // Restore all registers immediately before the return and any
515     // terminators that precede it.
516     if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
517       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
518         unsigned Reg = CSI[i].getReg();
519         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
520         TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
521         assert(I != MBB->begin() &&
522                "loadRegFromStackSlot didn't insert any code!");
523         // Insert in reverse order.  loadRegFromStackSlot can insert
524         // multiple instructions.
525         if (AtStart)
526           I = MBB->begin();
527         else {
528           I = BeforeI;
529           ++I;
530         }
531       }
532     }
533   }
534 }
535
536 static void doSpillCalleeSavedRegs(MachineFunction &Fn, RegScavenger *RS,
537                                    unsigned &MinCSFrameIndex,
538                                    unsigned &MaxCSFrameIndex,
539                                    const MBBVector &SaveBlocks,
540                                    const MBBVector &RestoreBlocks) {
541   const Function *F = Fn.getFunction();
542   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
543   MinCSFrameIndex = std::numeric_limits<unsigned>::max();
544   MaxCSFrameIndex = 0;
545
546   // Determine which of the registers in the callee save list should be saved.
547   BitVector SavedRegs;
548   TFI->determineCalleeSaves(Fn, SavedRegs, RS);
549
550   // Assign stack slots for any callee-saved registers that must be spilled.
551   assignCalleeSavedSpillSlots(Fn, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex);
552
553   // Add the code to save and restore the callee saved registers.
554   if (!F->hasFnAttribute(Attribute::Naked))
555     insertCSRSpillsAndRestores(Fn, SaveBlocks, RestoreBlocks);
556 }
557
558 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
559 static inline void
560 AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
561                   bool StackGrowsDown, int64_t &Offset,
562                   unsigned &MaxAlign, unsigned Skew) {
563   // If the stack grows down, add the object size to find the lowest address.
564   if (StackGrowsDown)
565     Offset += MFI.getObjectSize(FrameIdx);
566
567   unsigned Align = MFI.getObjectAlignment(FrameIdx);
568
569   // If the alignment of this object is greater than that of the stack, then
570   // increase the stack alignment to match.
571   MaxAlign = std::max(MaxAlign, Align);
572
573   // Adjust to alignment boundary.
574   Offset = alignTo(Offset, Align, Skew);
575
576   if (StackGrowsDown) {
577     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
578     MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
579   } else {
580     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
581     MFI.setObjectOffset(FrameIdx, Offset);
582     Offset += MFI.getObjectSize(FrameIdx);
583   }
584 }
585
586 /// Compute which bytes of fixed and callee-save stack area are unused and keep
587 /// track of them in StackBytesFree.
588 ///
589 static inline void
590 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
591                       unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
592                       int64_t FixedCSEnd, BitVector &StackBytesFree) {
593   // Avoid undefined int64_t -> int conversion below in extreme case.
594   if (FixedCSEnd > std::numeric_limits<int>::max())
595     return;
596
597   StackBytesFree.resize(FixedCSEnd, true);
598
599   SmallVector<int, 16> AllocatedFrameSlots;
600   // Add fixed objects.
601   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
602     AllocatedFrameSlots.push_back(i);
603   // Add callee-save objects.
604   for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
605     AllocatedFrameSlots.push_back(i);
606
607   for (int i : AllocatedFrameSlots) {
608     // These are converted from int64_t, but they should always fit in int
609     // because of the FixedCSEnd check above.
610     int ObjOffset = MFI.getObjectOffset(i);
611     int ObjSize = MFI.getObjectSize(i);
612     int ObjStart, ObjEnd;
613     if (StackGrowsDown) {
614       // ObjOffset is negative when StackGrowsDown is true.
615       ObjStart = -ObjOffset - ObjSize;
616       ObjEnd = -ObjOffset;
617     } else {
618       ObjStart = ObjOffset;
619       ObjEnd = ObjOffset + ObjSize;
620     }
621     // Ignore fixed holes that are in the previous stack frame.
622     if (ObjEnd > 0)
623       StackBytesFree.reset(ObjStart, ObjEnd);
624   }
625 }
626
627 /// Assign frame object to an unused portion of the stack in the fixed stack
628 /// object range.  Return true if the allocation was successful.
629 ///
630 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
631                                      bool StackGrowsDown, unsigned MaxAlign,
632                                      BitVector &StackBytesFree) {
633   if (MFI.isVariableSizedObjectIndex(FrameIdx))
634     return false;
635
636   if (StackBytesFree.none()) {
637     // clear it to speed up later scavengeStackSlot calls to
638     // StackBytesFree.none()
639     StackBytesFree.clear();
640     return false;
641   }
642
643   unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx);
644   if (ObjAlign > MaxAlign)
645     return false;
646
647   int64_t ObjSize = MFI.getObjectSize(FrameIdx);
648   int FreeStart;
649   for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
650        FreeStart = StackBytesFree.find_next(FreeStart)) {
651
652     // Check that free space has suitable alignment.
653     unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
654     if (alignTo(ObjStart, ObjAlign) != ObjStart)
655       continue;
656
657     if (FreeStart + ObjSize > StackBytesFree.size())
658       return false;
659
660     bool AllBytesFree = true;
661     for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
662       if (!StackBytesFree.test(FreeStart + Byte)) {
663         AllBytesFree = false;
664         break;
665       }
666     if (AllBytesFree)
667       break;
668   }
669
670   if (FreeStart == -1)
671     return false;
672
673   if (StackGrowsDown) {
674     int ObjStart = -(FreeStart + ObjSize);
675     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << ObjStart
676                  << "]\n");
677     MFI.setObjectOffset(FrameIdx, ObjStart);
678   } else {
679     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << FreeStart
680                  << "]\n");
681     MFI.setObjectOffset(FrameIdx, FreeStart);
682   }
683
684   StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
685   return true;
686 }
687
688 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
689 /// those required to be close to the Stack Protector) to stack offsets.
690 static void
691 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
692                       SmallSet<int, 16> &ProtectedObjs,
693                       MachineFrameInfo &MFI, bool StackGrowsDown,
694                       int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
695
696   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
697         E = UnassignedObjs.end(); I != E; ++I) {
698     int i = *I;
699     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
700     ProtectedObjs.insert(i);
701   }
702 }
703
704 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
705 /// abstract stack objects.
706 ///
707 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
708   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
709   StackProtector *SP = &getAnalysis<StackProtector>();
710
711   bool StackGrowsDown =
712     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
713
714   // Loop over all of the stack objects, assigning sequential addresses...
715   MachineFrameInfo &MFI = Fn.getFrameInfo();
716
717   // Start at the beginning of the local area.
718   // The Offset is the distance from the stack top in the direction
719   // of stack growth -- so it's always nonnegative.
720   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
721   if (StackGrowsDown)
722     LocalAreaOffset = -LocalAreaOffset;
723   assert(LocalAreaOffset >= 0
724          && "Local area offset should be in direction of stack growth");
725   int64_t Offset = LocalAreaOffset;
726
727   // Skew to be applied to alignment.
728   unsigned Skew = TFI.getStackAlignmentSkew(Fn);
729
730   // If there are fixed sized objects that are preallocated in the local area,
731   // non-fixed objects can't be allocated right at the start of local area.
732   // Adjust 'Offset' to point to the end of last fixed sized preallocated
733   // object.
734   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
735     int64_t FixedOff;
736     if (StackGrowsDown) {
737       // The maximum distance from the stack pointer is at lower address of
738       // the object -- which is given by offset. For down growing stack
739       // the offset is negative, so we negate the offset to get the distance.
740       FixedOff = -MFI.getObjectOffset(i);
741     } else {
742       // The maximum distance from the start pointer is at the upper
743       // address of the object.
744       FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
745     }
746     if (FixedOff > Offset) Offset = FixedOff;
747   }
748
749   // First assign frame offsets to stack objects that are used to spill
750   // callee saved registers.
751   if (StackGrowsDown) {
752     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
753       // If the stack grows down, we need to add the size to find the lowest
754       // address of the object.
755       Offset += MFI.getObjectSize(i);
756
757       unsigned Align = MFI.getObjectAlignment(i);
758       // Adjust to alignment boundary
759       Offset = alignTo(Offset, Align, Skew);
760
761       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
762       MFI.setObjectOffset(i, -Offset);        // Set the computed offset
763     }
764   } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
765     // Be careful about underflow in comparisons agains MinCSFrameIndex.
766     for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
767       if (MFI.isDeadObjectIndex(i))
768         continue;
769
770       unsigned Align = MFI.getObjectAlignment(i);
771       // Adjust to alignment boundary
772       Offset = alignTo(Offset, Align, Skew);
773
774       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
775       MFI.setObjectOffset(i, Offset);
776       Offset += MFI.getObjectSize(i);
777     }
778   }
779
780   // FixedCSEnd is the stack offset to the end of the fixed and callee-save
781   // stack area.
782   int64_t FixedCSEnd = Offset;
783   unsigned MaxAlign = MFI.getMaxAlignment();
784
785   // Make sure the special register scavenging spill slot is closest to the
786   // incoming stack pointer if a frame pointer is required and is closer
787   // to the incoming rather than the final stack pointer.
788   const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
789   bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
790                                TFI.isFPCloseToIncomingSP() &&
791                                RegInfo->useFPForScavengingIndex(Fn) &&
792                                !RegInfo->needsStackRealignment(Fn));
793   if (RS && EarlyScavengingSlots) {
794     SmallVector<int, 2> SFIs;
795     RS->getScavengingFrameIndices(SFIs);
796     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
797            IE = SFIs.end(); I != IE; ++I)
798       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
799   }
800
801   // FIXME: Once this is working, then enable flag will change to a target
802   // check for whether the frame is large enough to want to use virtual
803   // frame index registers. Functions which don't want/need this optimization
804   // will continue to use the existing code path.
805   if (MFI.getUseLocalStackAllocationBlock()) {
806     unsigned Align = MFI.getLocalFrameMaxAlign();
807
808     // Adjust to alignment boundary.
809     Offset = alignTo(Offset, Align, Skew);
810
811     DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
812
813     // Resolve offsets for objects in the local block.
814     for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
815       std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
816       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
817       DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
818             FIOffset << "]\n");
819       MFI.setObjectOffset(Entry.first, FIOffset);
820     }
821     // Allocate the local block
822     Offset += MFI.getLocalFrameSize();
823
824     MaxAlign = std::max(Align, MaxAlign);
825   }
826
827   // Retrieve the Exception Handler registration node.
828   int EHRegNodeFrameIndex = INT_MAX;
829   if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo())
830     EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
831
832   // Make sure that the stack protector comes before the local variables on the
833   // stack.
834   SmallSet<int, 16> ProtectedObjs;
835   if (MFI.getStackProtectorIndex() >= 0) {
836     StackObjSet LargeArrayObjs;
837     StackObjSet SmallArrayObjs;
838     StackObjSet AddrOfObjs;
839
840     AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), StackGrowsDown,
841                       Offset, MaxAlign, Skew);
842
843     // Assign large stack objects first.
844     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
845       if (MFI.isObjectPreAllocated(i) &&
846           MFI.getUseLocalStackAllocationBlock())
847         continue;
848       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
849         continue;
850       if (RS && RS->isScavengingFrameIndex((int)i))
851         continue;
852       if (MFI.isDeadObjectIndex(i))
853         continue;
854       if (MFI.getStackProtectorIndex() == (int)i ||
855           EHRegNodeFrameIndex == (int)i)
856         continue;
857
858       switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) {
859       case StackProtector::SSPLK_None:
860         continue;
861       case StackProtector::SSPLK_SmallArray:
862         SmallArrayObjs.insert(i);
863         continue;
864       case StackProtector::SSPLK_AddrOf:
865         AddrOfObjs.insert(i);
866         continue;
867       case StackProtector::SSPLK_LargeArray:
868         LargeArrayObjs.insert(i);
869         continue;
870       }
871       llvm_unreachable("Unexpected SSPLayoutKind.");
872     }
873
874     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
875                           Offset, MaxAlign, Skew);
876     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
877                           Offset, MaxAlign, Skew);
878     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
879                           Offset, MaxAlign, Skew);
880   }
881
882   SmallVector<int, 8> ObjectsToAllocate;
883
884   // Then prepare to assign frame offsets to stack objects that are not used to
885   // spill callee saved registers.
886   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
887     if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock())
888       continue;
889     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
890       continue;
891     if (RS && RS->isScavengingFrameIndex((int)i))
892       continue;
893     if (MFI.isDeadObjectIndex(i))
894       continue;
895     if (MFI.getStackProtectorIndex() == (int)i ||
896         EHRegNodeFrameIndex == (int)i)
897       continue;
898     if (ProtectedObjs.count(i))
899       continue;
900
901     // Add the objects that we need to allocate to our working set.
902     ObjectsToAllocate.push_back(i);
903   }
904
905   // Allocate the EH registration node first if one is present.
906   if (EHRegNodeFrameIndex != INT_MAX)
907     AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
908                       MaxAlign, Skew);
909
910   // Give the targets a chance to order the objects the way they like it.
911   if (Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
912       Fn.getTarget().Options.StackSymbolOrdering)
913     TFI.orderFrameObjects(Fn, ObjectsToAllocate);
914
915   // Keep track of which bytes in the fixed and callee-save range are used so we
916   // can use the holes when allocating later stack objects.  Only do this if
917   // stack protector isn't being used and the target requests it and we're
918   // optimizing.
919   BitVector StackBytesFree;
920   if (!ObjectsToAllocate.empty() &&
921       Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
922       MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(Fn))
923     computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex,
924                           FixedCSEnd, StackBytesFree);
925
926   // Now walk the objects and actually assign base offsets to them.
927   for (auto &Object : ObjectsToAllocate)
928     if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
929                            StackBytesFree))
930       AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
931
932   // Make sure the special register scavenging spill slot is closest to the
933   // stack pointer.
934   if (RS && !EarlyScavengingSlots) {
935     SmallVector<int, 2> SFIs;
936     RS->getScavengingFrameIndices(SFIs);
937     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
938            IE = SFIs.end(); I != IE; ++I)
939       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
940   }
941
942   if (!TFI.targetHandlesStackFrameRounding()) {
943     // If we have reserved argument space for call sites in the function
944     // immediately on entry to the current function, count it as part of the
945     // overall stack size.
946     if (MFI.adjustsStack() && TFI.hasReservedCallFrame(Fn))
947       Offset += MFI.getMaxCallFrameSize();
948
949     // Round up the size to a multiple of the alignment.  If the function has
950     // any calls or alloca's, align to the target's StackAlignment value to
951     // ensure that the callee's frame or the alloca data is suitably aligned;
952     // otherwise, for leaf functions, align to the TransientStackAlignment
953     // value.
954     unsigned StackAlign;
955     if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
956         (RegInfo->needsStackRealignment(Fn) && MFI.getObjectIndexEnd() != 0))
957       StackAlign = TFI.getStackAlignment();
958     else
959       StackAlign = TFI.getTransientStackAlignment();
960
961     // If the frame pointer is eliminated, all frame offsets will be relative to
962     // SP not FP. Align to MaxAlign so this works.
963     StackAlign = std::max(StackAlign, MaxAlign);
964     Offset = alignTo(Offset, StackAlign, Skew);
965   }
966
967   // Update frame info to pretend that this is part of the stack...
968   int64_t StackSize = Offset - LocalAreaOffset;
969   MFI.setStackSize(StackSize);
970   NumBytesStackSpace += StackSize;
971 }
972
973 /// insertPrologEpilogCode - Scan the function for modified callee saved
974 /// registers, insert spill code for these callee saved registers, then add
975 /// prolog and epilog code to the function.
976 ///
977 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
978   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
979
980   // Add prologue to the function...
981   for (MachineBasicBlock *SaveBlock : SaveBlocks)
982     TFI.emitPrologue(Fn, *SaveBlock);
983
984   // Add epilogue to restore the callee-save registers in each exiting block.
985   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
986     TFI.emitEpilogue(Fn, *RestoreBlock);
987
988   for (MachineBasicBlock *SaveBlock : SaveBlocks)
989     TFI.inlineStackProbe(Fn, *SaveBlock);
990
991   // Emit additional code that is required to support segmented stacks, if
992   // we've been asked for it.  This, when linked with a runtime with support
993   // for segmented stacks (libgcc is one), will result in allocating stack
994   // space in small chunks instead of one large contiguous block.
995   if (Fn.shouldSplitStack()) {
996     for (MachineBasicBlock *SaveBlock : SaveBlocks)
997       TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
998   }
999
1000   // Emit additional code that is required to explicitly handle the stack in
1001   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1002   // approach is rather similar to that of Segmented Stacks, but it uses a
1003   // different conditional check and another BIF for allocating more stack
1004   // space.
1005   if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
1006     for (MachineBasicBlock *SaveBlock : SaveBlocks)
1007       TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
1008 }
1009
1010 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1011 /// register references and actual offsets.
1012 ///
1013 void PEI::replaceFrameIndices(MachineFunction &Fn) {
1014   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
1015   if (!TFI.needsFrameIndexResolution(Fn)) return;
1016
1017   // Store SPAdj at exit of a basic block.
1018   SmallVector<int, 8> SPState;
1019   SPState.resize(Fn.getNumBlockIDs());
1020   df_iterator_default_set<MachineBasicBlock*> Reachable;
1021
1022   // Iterate over the reachable blocks in DFS order.
1023   for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
1024        DFI != DFE; ++DFI) {
1025     int SPAdj = 0;
1026     // Check the exit state of the DFS stack predecessor.
1027     if (DFI.getPathLength() >= 2) {
1028       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1029       assert(Reachable.count(StackPred) &&
1030              "DFS stack predecessor is already visited.\n");
1031       SPAdj = SPState[StackPred->getNumber()];
1032     }
1033     MachineBasicBlock *BB = *DFI;
1034     replaceFrameIndices(BB, Fn, SPAdj);
1035     SPState[BB->getNumber()] = SPAdj;
1036   }
1037
1038   // Handle the unreachable blocks.
1039   for (auto &BB : Fn) {
1040     if (Reachable.count(&BB))
1041       // Already handled in DFS traversal.
1042       continue;
1043     int SPAdj = 0;
1044     replaceFrameIndices(&BB, Fn, SPAdj);
1045   }
1046 }
1047
1048 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
1049                               int &SPAdj) {
1050   assert(Fn.getSubtarget().getRegisterInfo() &&
1051          "getRegisterInfo() must be implemented!");
1052   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
1053   const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
1054   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
1055
1056   if (RS && FrameIndexEliminationScavenging)
1057     RS->enterBasicBlock(*BB);
1058
1059   bool InsideCallSequence = false;
1060
1061   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1062
1063     if (TII.isFrameInstr(*I)) {
1064       InsideCallSequence = TII.isFrameSetup(*I);
1065       SPAdj += TII.getSPAdjust(*I);
1066       I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
1067       continue;
1068     }
1069
1070     MachineInstr &MI = *I;
1071     bool DoIncr = true;
1072     bool DidFinishLoop = true;
1073     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1074       if (!MI.getOperand(i).isFI())
1075         continue;
1076
1077       // Frame indices in debug values are encoded in a target independent
1078       // way with simply the frame index and offset rather than any
1079       // target-specific addressing mode.
1080       if (MI.isDebugValue()) {
1081         assert(i == 0 && "Frame indices can only appear as the first "
1082                          "operand of a DBG_VALUE machine instruction");
1083         unsigned Reg;
1084         MachineOperand &Offset = MI.getOperand(1);
1085         Offset.setImm(
1086             Offset.getImm() +
1087             TFI->getFrameIndexReference(Fn, MI.getOperand(0).getIndex(), Reg));
1088         MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
1089         continue;
1090       }
1091
1092       // TODO: This code should be commoned with the code for
1093       // PATCHPOINT. There's no good reason for the difference in
1094       // implementation other than historical accident.  The only
1095       // remaining difference is the unconditional use of the stack
1096       // pointer as the base register.
1097       if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1098         assert((!MI.isDebugValue() || i == 0) &&
1099                "Frame indicies can only appear as the first operand of a "
1100                "DBG_VALUE machine instruction");
1101         unsigned Reg;
1102         MachineOperand &Offset = MI.getOperand(i + 1);
1103         int refOffset = TFI->getFrameIndexReferencePreferSP(
1104             Fn, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1105         Offset.setImm(Offset.getImm() + refOffset);
1106         MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
1107         continue;
1108       }
1109
1110       // Some instructions (e.g. inline asm instructions) can have
1111       // multiple frame indices and/or cause eliminateFrameIndex
1112       // to insert more than one instruction. We need the register
1113       // scavenger to go through all of these instructions so that
1114       // it can update its register information. We keep the
1115       // iterator at the point before insertion so that we can
1116       // revisit them in full.
1117       bool AtBeginning = (I == BB->begin());
1118       if (!AtBeginning) --I;
1119
1120       // If this instruction has a FrameIndex operand, we need to
1121       // use that target machine register info object to eliminate
1122       // it.
1123       TRI.eliminateFrameIndex(MI, SPAdj, i,
1124                               FrameIndexEliminationScavenging ?  RS : nullptr);
1125
1126       // Reset the iterator if we were at the beginning of the BB.
1127       if (AtBeginning) {
1128         I = BB->begin();
1129         DoIncr = false;
1130       }
1131
1132       DidFinishLoop = false;
1133       break;
1134     }
1135
1136     // If we are looking at a call sequence, we need to keep track of
1137     // the SP adjustment made by each instruction in the sequence.
1138     // This includes both the frame setup/destroy pseudos (handled above),
1139     // as well as other instructions that have side effects w.r.t the SP.
1140     // Note that this must come after eliminateFrameIndex, because
1141     // if I itself referred to a frame index, we shouldn't count its own
1142     // adjustment.
1143     if (DidFinishLoop && InsideCallSequence)
1144       SPAdj += TII.getSPAdjust(MI);
1145
1146     if (DoIncr && I != BB->end()) ++I;
1147
1148     // Update register states.
1149     if (RS && FrameIndexEliminationScavenging && DidFinishLoop)
1150       RS->forward(MI);
1151   }
1152 }
1153
1154 /// doScavengeFrameVirtualRegs - Replace all frame index virtual registers
1155 /// with physical registers. Use the register scavenger to find an
1156 /// appropriate register to use.
1157 ///
1158 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
1159 /// iterate over the vreg use list, which at this point only contains machine
1160 /// operands for which eliminateFrameIndex need a new scratch reg.
1161 static void
1162 doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS) {
1163   // Run through the instructions and find any virtual registers.
1164   MachineRegisterInfo &MRI = MF.getRegInfo();
1165   for (MachineBasicBlock &MBB : MF) {
1166     RS->enterBasicBlock(MBB);
1167
1168     int SPAdj = 0;
1169
1170     // The instruction stream may change in the loop, so check MBB.end()
1171     // directly.
1172     for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ) {
1173       // We might end up here again with a NULL iterator if we scavenged a
1174       // register for which we inserted spill code for definition by what was
1175       // originally the first instruction in MBB.
1176       if (I == MachineBasicBlock::iterator(nullptr))
1177         I = MBB.begin();
1178
1179       const MachineInstr &MI = *I;
1180       MachineBasicBlock::iterator J = std::next(I);
1181       MachineBasicBlock::iterator P =
1182                          I == MBB.begin() ? MachineBasicBlock::iterator(nullptr)
1183                                           : std::prev(I);
1184
1185       // RS should process this instruction before we might scavenge at this
1186       // location. This is because we might be replacing a virtual register
1187       // defined by this instruction, and if so, registers killed by this
1188       // instruction are available, and defined registers are not.
1189       RS->forward(I);
1190
1191       for (const MachineOperand &MO : MI.operands()) {
1192         if (!MO.isReg())
1193           continue;
1194         unsigned Reg = MO.getReg();
1195         if (!TargetRegisterInfo::isVirtualRegister(Reg))
1196           continue;
1197
1198         // When we first encounter a new virtual register, it
1199         // must be a definition.
1200         assert(MO.isDef() && "frame index virtual missing def!");
1201         // Scavenge a new scratch register
1202         const TargetRegisterClass *RC = MRI.getRegClass(Reg);
1203         unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1204
1205         ++NumScavengedRegs;
1206
1207         // Replace this reference to the virtual register with the
1208         // scratch register.
1209         assert(ScratchReg && "Missing scratch register!");
1210         MRI.replaceRegWith(Reg, ScratchReg);
1211
1212         // Because this instruction was processed by the RS before this
1213         // register was allocated, make sure that the RS now records the
1214         // register as being used.
1215         RS->setRegUsed(ScratchReg);
1216       }
1217
1218       // If the scavenger needed to use one of its spill slots, the
1219       // spill code will have been inserted in between I and J. This is a
1220       // problem because we need the spill code before I: Move I to just
1221       // prior to J.
1222       if (I != std::prev(J)) {
1223         MBB.splice(J, &MBB, I);
1224
1225         // Before we move I, we need to prepare the RS to visit I again.
1226         // Specifically, RS will assert if it sees uses of registers that
1227         // it believes are undefined. Because we have already processed
1228         // register kills in I, when it visits I again, it will believe that
1229         // those registers are undefined. To avoid this situation, unprocess
1230         // the instruction I.
1231         assert(RS->getCurrentPosition() == I &&
1232           "The register scavenger has an unexpected position");
1233         I = P;
1234         RS->unprocess(P);
1235       } else
1236         ++I;
1237     }
1238   }
1239
1240   MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
1241 }