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