1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
14 // This pass must be run after register allocation. After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
17 //===----------------------------------------------------------------------===//
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"
48 #define DEBUG_TYPE "pei"
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);
57 static void doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS);
60 class PEI : public MachineFunctionPass {
63 PEI() : MachineFunctionPass(ID) {
64 initializePEIPass(*PassRegistry::getPassRegistry());
67 void getAnalysisUsage(AnalysisUsage &AU) const override;
69 MachineFunctionProperties getRequiredProperties() const override {
70 MachineFunctionProperties MFP;
72 MFP.set(MachineFunctionProperties::Property::NoVRegs);
76 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
77 /// frame indexes with appropriate references.
79 bool runOnMachineFunction(MachineFunction &Fn) override;
82 std::function<void(MachineFunction &MF, RegScavenger *RS,
83 unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex,
84 const MBBVector &SaveBlocks,
85 const MBBVector &RestoreBlocks)>
86 SpillCalleeSavedRegisters;
87 std::function<void(MachineFunction &MF, RegScavenger *RS)>
88 ScavengeFrameVirtualRegs;
90 bool UsesCalleeSaves = false;
94 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
95 // stack frame indexes.
96 unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max();
97 unsigned MaxCSFrameIndex = 0;
99 // Save and Restore blocks of the current function. Typically there is a
100 // single save block, unless Windows EH funclets are involved.
101 MBBVector SaveBlocks;
102 MBBVector RestoreBlocks;
104 // Flag to control whether to use the register scavenger to resolve
105 // frame index materialization registers. Set according to
106 // TRI->requiresFrameIndexScavenging() for the current function.
107 bool FrameIndexVirtualScavenging;
109 // Flag to control whether the scavenger should be passed even though
110 // FrameIndexVirtualScavenging is used.
111 bool FrameIndexEliminationScavenging;
113 void calculateCallFrameInfo(MachineFunction &Fn);
114 void calculateSaveRestoreBlocks(MachineFunction &Fn);
116 void calculateFrameObjectOffsets(MachineFunction &Fn);
117 void replaceFrameIndices(MachineFunction &Fn);
118 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
120 void insertPrologEpilogCode(MachineFunction &Fn);
125 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
127 static cl::opt<unsigned>
128 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
129 cl::desc("Warn for stack size bigger than the given"
132 INITIALIZE_PASS_BEGIN(PEI, "prologepilog", "Prologue/Epilogue Insertion", false,
134 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
135 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
136 INITIALIZE_PASS_DEPENDENCY(StackProtector)
137 INITIALIZE_PASS_END(PEI, "prologepilog",
138 "Prologue/Epilogue Insertion & Frame Finalization", false,
141 MachineFunctionPass *llvm::createPrologEpilogInserterPass() {
145 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
146 STATISTIC(NumBytesStackSpace,
147 "Number of bytes used for stack in all functions");
149 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
150 AU.setPreservesCFG();
151 AU.addPreserved<MachineLoopInfo>();
152 AU.addPreserved<MachineDominatorTree>();
153 AU.addRequired<StackProtector>();
154 MachineFunctionPass::getAnalysisUsage(AU);
158 /// StackObjSet - A set of stack object indexes
159 typedef SmallSetVector<int, 8> StackObjSet;
161 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
162 /// frame indexes with appropriate references.
164 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
165 if (!SpillCalleeSavedRegisters) {
166 const TargetMachine &TM = Fn.getTarget();
167 if (!TM.usesPhysRegsForPEI()) {
168 SpillCalleeSavedRegisters = [](MachineFunction &, RegScavenger *,
169 unsigned &, unsigned &, const MBBVector &,
170 const MBBVector &) {};
171 ScavengeFrameVirtualRegs = [](MachineFunction &, RegScavenger *) {};
173 SpillCalleeSavedRegisters = doSpillCalleeSavedRegs;
174 ScavengeFrameVirtualRegs = doScavengeFrameVirtualRegs;
175 UsesCalleeSaves = true;
179 const Function* F = Fn.getFunction();
180 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
181 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
183 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
184 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
185 FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) ||
186 TRI->requiresFrameIndexReplacementScavenging(Fn);
188 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
189 // function's frame information. Also eliminates call frame pseudo
191 calculateCallFrameInfo(Fn);
193 // Determine placement of CSR spill/restore code and prolog/epilog code:
194 // place all spills in the entry block, all restores in return blocks.
195 calculateSaveRestoreBlocks(Fn);
197 // Handle CSR spilling and restoring, for targets that need it.
198 SpillCalleeSavedRegisters(Fn, RS, MinCSFrameIndex, MaxCSFrameIndex,
199 SaveBlocks, RestoreBlocks);
201 // Allow the target machine to make final modifications to the function
202 // before the frame layout is finalized.
203 TFI->processFunctionBeforeFrameFinalized(Fn, RS);
205 // Calculate actual frame offsets for all abstract stack objects...
206 calculateFrameObjectOffsets(Fn);
208 // Add prolog and epilog code to the function. This function is required
209 // to align the stack frame as necessary for any stack variables or
210 // called functions. Because of this, calculateCalleeSavedRegisters()
211 // must be called before this function in order to set the AdjustsStack
212 // and MaxCallFrameSize variables.
213 if (!F->hasFnAttribute(Attribute::Naked))
214 insertPrologEpilogCode(Fn);
216 // Replace all MO_FrameIndex operands with physical register references
217 // and actual offsets.
219 replaceFrameIndices(Fn);
221 // If register scavenging is needed, as we've enabled doing it as a
222 // post-pass, scavenge the virtual registers that frame index elimination
224 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) {
225 ScavengeFrameVirtualRegs(Fn, RS);
227 // Clear any vregs created by virtual scavenging.
228 Fn.getRegInfo().clearVirtRegs();
231 // Warn on stack size when we exceeds the given limit.
232 MachineFrameInfo &MFI = Fn.getFrameInfo();
233 uint64_t StackSize = MFI.getStackSize();
234 if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
235 DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
236 F->getContext().diagnose(DiagStackSize);
241 RestoreBlocks.clear();
242 MFI.setSavePoint(nullptr);
243 MFI.setRestorePoint(nullptr);
247 /// Calculate the MaxCallFrameSize and AdjustsStack
248 /// variables for the function's frame information and eliminate call frame
249 /// pseudo instructions.
250 void PEI::calculateCallFrameInfo(MachineFunction &Fn) {
251 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
252 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
253 MachineFrameInfo &MFI = Fn.getFrameInfo();
255 unsigned MaxCallFrameSize = 0;
256 bool AdjustsStack = MFI.adjustsStack();
258 // Get the function call frame set-up and tear-down instruction opcode
259 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
260 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
262 // Early exit for targets which have no call frame setup/destroy pseudo
264 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
267 std::vector<MachineBasicBlock::iterator> FrameSDOps;
268 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
269 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
270 if (TII.isFrameInstr(*I)) {
271 unsigned Size = TII.getFrameSize(*I);
272 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
274 FrameSDOps.push_back(I);
275 } else if (I->isInlineAsm()) {
276 // Some inline asm's need a stack frame, as indicated by operand 1.
277 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
278 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
282 assert(!MFI.isMaxCallFrameSizeComputed() ||
283 (MFI.getMaxCallFrameSize() == MaxCallFrameSize &&
284 MFI.adjustsStack() == AdjustsStack));
285 MFI.setAdjustsStack(AdjustsStack);
286 MFI.setMaxCallFrameSize(MaxCallFrameSize);
288 for (std::vector<MachineBasicBlock::iterator>::iterator
289 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
290 MachineBasicBlock::iterator I = *i;
292 // If call frames are not being included as part of the stack frame, and
293 // the target doesn't indicate otherwise, remove the call frame pseudos
294 // here. The sub/add sp instruction pairs are still inserted, but we don't
295 // need to track the SP adjustment for frame index elimination.
296 if (TFI->canSimplifyCallFramePseudos(Fn))
297 TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
301 /// Compute the sets of entry and return blocks for saving and restoring
302 /// callee-saved registers, and placing prolog and epilog code.
303 void PEI::calculateSaveRestoreBlocks(MachineFunction &Fn) {
304 const MachineFrameInfo &MFI = Fn.getFrameInfo();
306 // Even when we do not change any CSR, we still want to insert the
307 // prologue and epilogue of the function.
308 // So set the save points for those.
310 // Use the points found by shrink-wrapping, if any.
311 if (MFI.getSavePoint()) {
312 SaveBlocks.push_back(MFI.getSavePoint());
313 assert(MFI.getRestorePoint() && "Both restore and save must be set");
314 MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
315 // If RestoreBlock does not have any successor and is not a return block
316 // then the end point is unreachable and we do not need to insert any
318 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
319 RestoreBlocks.push_back(RestoreBlock);
323 // Save refs to entry and return blocks.
324 SaveBlocks.push_back(&Fn.front());
325 for (MachineBasicBlock &MBB : Fn) {
326 if (MBB.isEHFuncletEntry())
327 SaveBlocks.push_back(&MBB);
328 if (MBB.isReturnBlock())
329 RestoreBlocks.push_back(&MBB);
333 static void assignCalleeSavedSpillSlots(MachineFunction &F,
334 const BitVector &SavedRegs,
335 unsigned &MinCSFrameIndex,
336 unsigned &MaxCSFrameIndex) {
337 if (SavedRegs.empty())
340 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
341 const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
343 std::vector<CalleeSavedInfo> CSI;
344 for (unsigned i = 0; CSRegs[i]; ++i) {
345 unsigned Reg = CSRegs[i];
346 if (SavedRegs.test(Reg))
347 CSI.push_back(CalleeSavedInfo(Reg));
350 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
351 MachineFrameInfo &MFI = F.getFrameInfo();
352 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
353 // If target doesn't implement this, use generic code.
356 return; // Early exit if no callee saved registers are modified!
358 unsigned NumFixedSpillSlots;
359 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
360 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
362 // Now that we know which registers need to be saved and restored, allocate
363 // stack slots for them.
364 for (auto &CS : CSI) {
365 unsigned Reg = CS.getReg();
366 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
369 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
370 CS.setFrameIdx(FrameIdx);
374 // Check to see if this physreg must be spilled to a particular stack slot
376 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
377 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
378 FixedSlot->Reg != Reg)
381 unsigned Size = RegInfo->getSpillSize(*RC);
382 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
383 // Nope, just spill it anywhere convenient.
384 unsigned Align = RegInfo->getSpillAlignment(*RC);
385 unsigned StackAlign = TFI->getStackAlignment();
387 // We may not be able to satisfy the desired alignment specification of
388 // the TargetRegisterClass if the stack alignment is smaller. Use the
390 Align = std::min(Align, StackAlign);
391 FrameIdx = MFI.CreateStackObject(Size, Align, true);
392 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
393 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
395 // Spill it to the stack where we must.
396 FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
399 CS.setFrameIdx(FrameIdx);
403 MFI.setCalleeSavedInfo(CSI);
406 /// Helper function to update the liveness information for the callee-saved
408 static void updateLiveness(MachineFunction &MF) {
409 MachineFrameInfo &MFI = MF.getFrameInfo();
410 // Visited will contain all the basic blocks that are in the region
411 // where the callee saved registers are alive:
412 // - Anything that is not Save or Restore -> LiveThrough.
414 // - Restore -> LiveOut.
415 // The live-out is not attached to the block, so no need to keep
416 // Restore in this set.
417 SmallPtrSet<MachineBasicBlock *, 8> Visited;
418 SmallVector<MachineBasicBlock *, 8> WorkList;
419 MachineBasicBlock *Entry = &MF.front();
420 MachineBasicBlock *Save = MFI.getSavePoint();
426 WorkList.push_back(Entry);
427 Visited.insert(Entry);
429 Visited.insert(Save);
431 MachineBasicBlock *Restore = MFI.getRestorePoint();
433 // By construction Restore cannot be visited, otherwise it
434 // means there exists a path to Restore that does not go
436 WorkList.push_back(Restore);
438 while (!WorkList.empty()) {
439 const MachineBasicBlock *CurBB = WorkList.pop_back_val();
440 // By construction, the region that is after the save point is
441 // dominated by the Save and post-dominated by the Restore.
442 if (CurBB == Save && Save != Restore)
444 // Enqueue all the successors not already visited.
445 // Those are by construction either before Save or after Restore.
446 for (MachineBasicBlock *SuccBB : CurBB->successors())
447 if (Visited.insert(SuccBB).second)
448 WorkList.push_back(SuccBB);
451 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
453 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
454 for (MachineBasicBlock *MBB : Visited) {
455 MCPhysReg Reg = CSI[i].getReg();
456 // Add the callee-saved register as live-in.
457 // It's killed at the spill.
458 if (!MBB->isLiveIn(Reg))
464 /// insertCSRSpillsAndRestores - Insert spill and restore code for
465 /// callee saved registers used in the function.
467 static void insertCSRSpillsAndRestores(MachineFunction &Fn,
468 const MBBVector &SaveBlocks,
469 const MBBVector &RestoreBlocks) {
470 // Get callee saved register information.
471 MachineFrameInfo &MFI = Fn.getFrameInfo();
472 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
474 MFI.setCalleeSavedInfoValid(true);
476 // Early exit if no callee saved registers are modified!
480 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
481 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
482 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
483 MachineBasicBlock::iterator I;
485 // Spill using target interface.
486 for (MachineBasicBlock *SaveBlock : SaveBlocks) {
487 I = SaveBlock->begin();
488 if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
489 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
490 // Insert the spill to the stack frame.
491 unsigned Reg = CSI[i].getReg();
492 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
493 TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
497 // Update the live-in information of all the blocks up to the save point.
501 // Restore using target interface.
502 for (MachineBasicBlock *MBB : RestoreBlocks) {
505 // Skip over all terminator instructions, which are part of the return
507 MachineBasicBlock::iterator I2 = I;
508 while (I2 != MBB->begin() && (--I2)->isTerminator())
511 bool AtStart = I == MBB->begin();
512 MachineBasicBlock::iterator BeforeI = I;
516 // Restore all registers immediately before the return and any
517 // terminators that precede it.
518 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
519 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
520 unsigned Reg = CSI[i].getReg();
521 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
522 TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
523 assert(I != MBB->begin() &&
524 "loadRegFromStackSlot didn't insert any code!");
525 // Insert in reverse order. loadRegFromStackSlot can insert
526 // multiple instructions.
538 static void doSpillCalleeSavedRegs(MachineFunction &Fn, RegScavenger *RS,
539 unsigned &MinCSFrameIndex,
540 unsigned &MaxCSFrameIndex,
541 const MBBVector &SaveBlocks,
542 const MBBVector &RestoreBlocks) {
543 const Function *F = Fn.getFunction();
544 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
545 MinCSFrameIndex = std::numeric_limits<unsigned>::max();
548 // Determine which of the registers in the callee save list should be saved.
550 TFI->determineCalleeSaves(Fn, SavedRegs, RS);
552 // Assign stack slots for any callee-saved registers that must be spilled.
553 assignCalleeSavedSpillSlots(Fn, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex);
555 // Add the code to save and restore the callee saved registers.
556 if (!F->hasFnAttribute(Attribute::Naked))
557 insertCSRSpillsAndRestores(Fn, SaveBlocks, RestoreBlocks);
560 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
562 AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
563 bool StackGrowsDown, int64_t &Offset,
564 unsigned &MaxAlign, unsigned Skew) {
565 // If the stack grows down, add the object size to find the lowest address.
567 Offset += MFI.getObjectSize(FrameIdx);
569 unsigned Align = MFI.getObjectAlignment(FrameIdx);
571 // If the alignment of this object is greater than that of the stack, then
572 // increase the stack alignment to match.
573 MaxAlign = std::max(MaxAlign, Align);
575 // Adjust to alignment boundary.
576 Offset = alignTo(Offset, Align, Skew);
578 if (StackGrowsDown) {
579 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
580 MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
582 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
583 MFI.setObjectOffset(FrameIdx, Offset);
584 Offset += MFI.getObjectSize(FrameIdx);
588 /// Compute which bytes of fixed and callee-save stack area are unused and keep
589 /// track of them in StackBytesFree.
592 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
593 unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
594 int64_t FixedCSEnd, BitVector &StackBytesFree) {
595 // Avoid undefined int64_t -> int conversion below in extreme case.
596 if (FixedCSEnd > std::numeric_limits<int>::max())
599 StackBytesFree.resize(FixedCSEnd, true);
601 SmallVector<int, 16> AllocatedFrameSlots;
602 // Add fixed objects.
603 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
604 AllocatedFrameSlots.push_back(i);
605 // Add callee-save objects.
606 for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
607 AllocatedFrameSlots.push_back(i);
609 for (int i : AllocatedFrameSlots) {
610 // These are converted from int64_t, but they should always fit in int
611 // because of the FixedCSEnd check above.
612 int ObjOffset = MFI.getObjectOffset(i);
613 int ObjSize = MFI.getObjectSize(i);
614 int ObjStart, ObjEnd;
615 if (StackGrowsDown) {
616 // ObjOffset is negative when StackGrowsDown is true.
617 ObjStart = -ObjOffset - ObjSize;
620 ObjStart = ObjOffset;
621 ObjEnd = ObjOffset + ObjSize;
623 // Ignore fixed holes that are in the previous stack frame.
625 StackBytesFree.reset(ObjStart, ObjEnd);
629 /// Assign frame object to an unused portion of the stack in the fixed stack
630 /// object range. Return true if the allocation was successful.
632 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
633 bool StackGrowsDown, unsigned MaxAlign,
634 BitVector &StackBytesFree) {
635 if (MFI.isVariableSizedObjectIndex(FrameIdx))
638 if (StackBytesFree.none()) {
639 // clear it to speed up later scavengeStackSlot calls to
640 // StackBytesFree.none()
641 StackBytesFree.clear();
645 unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx);
646 if (ObjAlign > MaxAlign)
649 int64_t ObjSize = MFI.getObjectSize(FrameIdx);
651 for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
652 FreeStart = StackBytesFree.find_next(FreeStart)) {
654 // Check that free space has suitable alignment.
655 unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
656 if (alignTo(ObjStart, ObjAlign) != ObjStart)
659 if (FreeStart + ObjSize > StackBytesFree.size())
662 bool AllBytesFree = true;
663 for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
664 if (!StackBytesFree.test(FreeStart + Byte)) {
665 AllBytesFree = false;
675 if (StackGrowsDown) {
676 int ObjStart = -(FreeStart + ObjSize);
677 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << ObjStart
679 MFI.setObjectOffset(FrameIdx, ObjStart);
681 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << FreeStart
683 MFI.setObjectOffset(FrameIdx, FreeStart);
686 StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
690 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
691 /// those required to be close to the Stack Protector) to stack offsets.
693 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
694 SmallSet<int, 16> &ProtectedObjs,
695 MachineFrameInfo &MFI, bool StackGrowsDown,
696 int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
698 for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
699 E = UnassignedObjs.end(); I != E; ++I) {
701 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
702 ProtectedObjs.insert(i);
706 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
707 /// abstract stack objects.
709 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
710 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
711 StackProtector *SP = &getAnalysis<StackProtector>();
713 bool StackGrowsDown =
714 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
716 // Loop over all of the stack objects, assigning sequential addresses...
717 MachineFrameInfo &MFI = Fn.getFrameInfo();
719 // Start at the beginning of the local area.
720 // The Offset is the distance from the stack top in the direction
721 // of stack growth -- so it's always nonnegative.
722 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
724 LocalAreaOffset = -LocalAreaOffset;
725 assert(LocalAreaOffset >= 0
726 && "Local area offset should be in direction of stack growth");
727 int64_t Offset = LocalAreaOffset;
729 // Skew to be applied to alignment.
730 unsigned Skew = TFI.getStackAlignmentSkew(Fn);
732 // If there are fixed sized objects that are preallocated in the local area,
733 // non-fixed objects can't be allocated right at the start of local area.
734 // Adjust 'Offset' to point to the end of last fixed sized preallocated
736 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
738 if (StackGrowsDown) {
739 // The maximum distance from the stack pointer is at lower address of
740 // the object -- which is given by offset. For down growing stack
741 // the offset is negative, so we negate the offset to get the distance.
742 FixedOff = -MFI.getObjectOffset(i);
744 // The maximum distance from the start pointer is at the upper
745 // address of the object.
746 FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
748 if (FixedOff > Offset) Offset = FixedOff;
751 // First assign frame offsets to stack objects that are used to spill
752 // callee saved registers.
753 if (StackGrowsDown) {
754 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
755 // If the stack grows down, we need to add the size to find the lowest
756 // address of the object.
757 Offset += MFI.getObjectSize(i);
759 unsigned Align = MFI.getObjectAlignment(i);
760 // Adjust to alignment boundary
761 Offset = alignTo(Offset, Align, Skew);
763 DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
764 MFI.setObjectOffset(i, -Offset); // Set the computed offset
766 } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
767 // Be careful about underflow in comparisons agains MinCSFrameIndex.
768 for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
769 if (MFI.isDeadObjectIndex(i))
772 unsigned Align = MFI.getObjectAlignment(i);
773 // Adjust to alignment boundary
774 Offset = alignTo(Offset, Align, Skew);
776 DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
777 MFI.setObjectOffset(i, Offset);
778 Offset += MFI.getObjectSize(i);
782 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
784 int64_t FixedCSEnd = Offset;
785 unsigned MaxAlign = MFI.getMaxAlignment();
787 // Make sure the special register scavenging spill slot is closest to the
788 // incoming stack pointer if a frame pointer is required and is closer
789 // to the incoming rather than the final stack pointer.
790 const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
791 bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
792 TFI.isFPCloseToIncomingSP() &&
793 RegInfo->useFPForScavengingIndex(Fn) &&
794 !RegInfo->needsStackRealignment(Fn));
795 if (RS && EarlyScavengingSlots) {
796 SmallVector<int, 2> SFIs;
797 RS->getScavengingFrameIndices(SFIs);
798 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
799 IE = SFIs.end(); I != IE; ++I)
800 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
803 // FIXME: Once this is working, then enable flag will change to a target
804 // check for whether the frame is large enough to want to use virtual
805 // frame index registers. Functions which don't want/need this optimization
806 // will continue to use the existing code path.
807 if (MFI.getUseLocalStackAllocationBlock()) {
808 unsigned Align = MFI.getLocalFrameMaxAlign();
810 // Adjust to alignment boundary.
811 Offset = alignTo(Offset, Align, Skew);
813 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
815 // Resolve offsets for objects in the local block.
816 for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
817 std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
818 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
819 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
821 MFI.setObjectOffset(Entry.first, FIOffset);
823 // Allocate the local block
824 Offset += MFI.getLocalFrameSize();
826 MaxAlign = std::max(Align, MaxAlign);
829 // Retrieve the Exception Handler registration node.
830 int EHRegNodeFrameIndex = INT_MAX;
831 if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo())
832 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
834 // Make sure that the stack protector comes before the local variables on the
836 SmallSet<int, 16> ProtectedObjs;
837 if (MFI.getStackProtectorIndex() >= 0) {
838 StackObjSet LargeArrayObjs;
839 StackObjSet SmallArrayObjs;
840 StackObjSet AddrOfObjs;
842 AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), StackGrowsDown,
843 Offset, MaxAlign, Skew);
845 // Assign large stack objects first.
846 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
847 if (MFI.isObjectPreAllocated(i) &&
848 MFI.getUseLocalStackAllocationBlock())
850 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
852 if (RS && RS->isScavengingFrameIndex((int)i))
854 if (MFI.isDeadObjectIndex(i))
856 if (MFI.getStackProtectorIndex() == (int)i ||
857 EHRegNodeFrameIndex == (int)i)
860 switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) {
861 case StackProtector::SSPLK_None:
863 case StackProtector::SSPLK_SmallArray:
864 SmallArrayObjs.insert(i);
866 case StackProtector::SSPLK_AddrOf:
867 AddrOfObjs.insert(i);
869 case StackProtector::SSPLK_LargeArray:
870 LargeArrayObjs.insert(i);
873 llvm_unreachable("Unexpected SSPLayoutKind.");
876 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
877 Offset, MaxAlign, Skew);
878 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
879 Offset, MaxAlign, Skew);
880 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
881 Offset, MaxAlign, Skew);
884 SmallVector<int, 8> ObjectsToAllocate;
886 // Then prepare to assign frame offsets to stack objects that are not used to
887 // spill callee saved registers.
888 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
889 if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock())
891 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
893 if (RS && RS->isScavengingFrameIndex((int)i))
895 if (MFI.isDeadObjectIndex(i))
897 if (MFI.getStackProtectorIndex() == (int)i ||
898 EHRegNodeFrameIndex == (int)i)
900 if (ProtectedObjs.count(i))
903 // Add the objects that we need to allocate to our working set.
904 ObjectsToAllocate.push_back(i);
907 // Allocate the EH registration node first if one is present.
908 if (EHRegNodeFrameIndex != INT_MAX)
909 AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
912 // Give the targets a chance to order the objects the way they like it.
913 if (Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
914 Fn.getTarget().Options.StackSymbolOrdering)
915 TFI.orderFrameObjects(Fn, ObjectsToAllocate);
917 // Keep track of which bytes in the fixed and callee-save range are used so we
918 // can use the holes when allocating later stack objects. Only do this if
919 // stack protector isn't being used and the target requests it and we're
921 BitVector StackBytesFree;
922 if (!ObjectsToAllocate.empty() &&
923 Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
924 MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(Fn))
925 computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex,
926 FixedCSEnd, StackBytesFree);
928 // Now walk the objects and actually assign base offsets to them.
929 for (auto &Object : ObjectsToAllocate)
930 if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
932 AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
934 // Make sure the special register scavenging spill slot is closest to the
936 if (RS && !EarlyScavengingSlots) {
937 SmallVector<int, 2> SFIs;
938 RS->getScavengingFrameIndices(SFIs);
939 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
940 IE = SFIs.end(); I != IE; ++I)
941 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
944 if (!TFI.targetHandlesStackFrameRounding()) {
945 // If we have reserved argument space for call sites in the function
946 // immediately on entry to the current function, count it as part of the
947 // overall stack size.
948 if (MFI.adjustsStack() && TFI.hasReservedCallFrame(Fn))
949 Offset += MFI.getMaxCallFrameSize();
951 // Round up the size to a multiple of the alignment. If the function has
952 // any calls or alloca's, align to the target's StackAlignment value to
953 // ensure that the callee's frame or the alloca data is suitably aligned;
954 // otherwise, for leaf functions, align to the TransientStackAlignment
957 if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
958 (RegInfo->needsStackRealignment(Fn) && MFI.getObjectIndexEnd() != 0))
959 StackAlign = TFI.getStackAlignment();
961 StackAlign = TFI.getTransientStackAlignment();
963 // If the frame pointer is eliminated, all frame offsets will be relative to
964 // SP not FP. Align to MaxAlign so this works.
965 StackAlign = std::max(StackAlign, MaxAlign);
966 Offset = alignTo(Offset, StackAlign, Skew);
969 // Update frame info to pretend that this is part of the stack...
970 int64_t StackSize = Offset - LocalAreaOffset;
971 MFI.setStackSize(StackSize);
972 NumBytesStackSpace += StackSize;
975 /// insertPrologEpilogCode - Scan the function for modified callee saved
976 /// registers, insert spill code for these callee saved registers, then add
977 /// prolog and epilog code to the function.
979 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
980 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
982 // Add prologue to the function...
983 for (MachineBasicBlock *SaveBlock : SaveBlocks)
984 TFI.emitPrologue(Fn, *SaveBlock);
986 // Add epilogue to restore the callee-save registers in each exiting block.
987 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
988 TFI.emitEpilogue(Fn, *RestoreBlock);
990 for (MachineBasicBlock *SaveBlock : SaveBlocks)
991 TFI.inlineStackProbe(Fn, *SaveBlock);
993 // Emit additional code that is required to support segmented stacks, if
994 // we've been asked for it. This, when linked with a runtime with support
995 // for segmented stacks (libgcc is one), will result in allocating stack
996 // space in small chunks instead of one large contiguous block.
997 if (Fn.shouldSplitStack()) {
998 for (MachineBasicBlock *SaveBlock : SaveBlocks)
999 TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
1002 // Emit additional code that is required to explicitly handle the stack in
1003 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1004 // approach is rather similar to that of Segmented Stacks, but it uses a
1005 // different conditional check and another BIF for allocating more stack
1007 if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
1008 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1009 TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
1012 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1013 /// register references and actual offsets.
1015 void PEI::replaceFrameIndices(MachineFunction &Fn) {
1016 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
1017 if (!TFI.needsFrameIndexResolution(Fn)) return;
1019 // Store SPAdj at exit of a basic block.
1020 SmallVector<int, 8> SPState;
1021 SPState.resize(Fn.getNumBlockIDs());
1022 df_iterator_default_set<MachineBasicBlock*> Reachable;
1024 // Iterate over the reachable blocks in DFS order.
1025 for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
1026 DFI != DFE; ++DFI) {
1028 // Check the exit state of the DFS stack predecessor.
1029 if (DFI.getPathLength() >= 2) {
1030 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1031 assert(Reachable.count(StackPred) &&
1032 "DFS stack predecessor is already visited.\n");
1033 SPAdj = SPState[StackPred->getNumber()];
1035 MachineBasicBlock *BB = *DFI;
1036 replaceFrameIndices(BB, Fn, SPAdj);
1037 SPState[BB->getNumber()] = SPAdj;
1040 // Handle the unreachable blocks.
1041 for (auto &BB : Fn) {
1042 if (Reachable.count(&BB))
1043 // Already handled in DFS traversal.
1046 replaceFrameIndices(&BB, Fn, SPAdj);
1050 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
1052 assert(Fn.getSubtarget().getRegisterInfo() &&
1053 "getRegisterInfo() must be implemented!");
1054 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
1055 const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
1056 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
1058 if (RS && FrameIndexEliminationScavenging)
1059 RS->enterBasicBlock(*BB);
1061 bool InsideCallSequence = false;
1063 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1065 if (TII.isFrameInstr(*I)) {
1066 InsideCallSequence = TII.isFrameSetup(*I);
1067 SPAdj += TII.getSPAdjust(*I);
1068 I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
1072 MachineInstr &MI = *I;
1074 bool DidFinishLoop = true;
1075 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1076 if (!MI.getOperand(i).isFI())
1079 // Frame indices in debug values are encoded in a target independent
1080 // way with simply the frame index and offset rather than any
1081 // target-specific addressing mode.
1082 if (MI.isDebugValue()) {
1083 assert(i == 0 && "Frame indices can only appear as the first "
1084 "operand of a DBG_VALUE machine instruction");
1086 MachineOperand &Offset = MI.getOperand(1);
1089 TFI->getFrameIndexReference(Fn, MI.getOperand(0).getIndex(), Reg));
1090 MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
1094 // TODO: This code should be commoned with the code for
1095 // PATCHPOINT. There's no good reason for the difference in
1096 // implementation other than historical accident. The only
1097 // remaining difference is the unconditional use of the stack
1098 // pointer as the base register.
1099 if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1100 assert((!MI.isDebugValue() || i == 0) &&
1101 "Frame indicies can only appear as the first operand of a "
1102 "DBG_VALUE machine instruction");
1104 MachineOperand &Offset = MI.getOperand(i + 1);
1105 int refOffset = TFI->getFrameIndexReferencePreferSP(
1106 Fn, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1107 Offset.setImm(Offset.getImm() + refOffset);
1108 MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
1112 // Some instructions (e.g. inline asm instructions) can have
1113 // multiple frame indices and/or cause eliminateFrameIndex
1114 // to insert more than one instruction. We need the register
1115 // scavenger to go through all of these instructions so that
1116 // it can update its register information. We keep the
1117 // iterator at the point before insertion so that we can
1118 // revisit them in full.
1119 bool AtBeginning = (I == BB->begin());
1120 if (!AtBeginning) --I;
1122 // If this instruction has a FrameIndex operand, we need to
1123 // use that target machine register info object to eliminate
1125 TRI.eliminateFrameIndex(MI, SPAdj, i,
1126 FrameIndexEliminationScavenging ? RS : nullptr);
1128 // Reset the iterator if we were at the beginning of the BB.
1134 DidFinishLoop = false;
1138 // If we are looking at a call sequence, we need to keep track of
1139 // the SP adjustment made by each instruction in the sequence.
1140 // This includes both the frame setup/destroy pseudos (handled above),
1141 // as well as other instructions that have side effects w.r.t the SP.
1142 // Note that this must come after eliminateFrameIndex, because
1143 // if I itself referred to a frame index, we shouldn't count its own
1145 if (DidFinishLoop && InsideCallSequence)
1146 SPAdj += TII.getSPAdjust(MI);
1148 if (DoIncr && I != BB->end()) ++I;
1150 // Update register states.
1151 if (RS && FrameIndexEliminationScavenging && DidFinishLoop)
1156 /// doScavengeFrameVirtualRegs - Replace all frame index virtual registers
1157 /// with physical registers. Use the register scavenger to find an
1158 /// appropriate register to use.
1160 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
1161 /// iterate over the vreg use list, which at this point only contains machine
1162 /// operands for which eliminateFrameIndex need a new scratch reg.
1164 doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS) {
1165 // Run through the instructions and find any virtual registers.
1166 MachineRegisterInfo &MRI = MF.getRegInfo();
1167 for (MachineBasicBlock &MBB : MF) {
1168 RS->enterBasicBlock(MBB);
1172 // The instruction stream may change in the loop, so check MBB.end()
1174 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ) {
1175 // We might end up here again with a NULL iterator if we scavenged a
1176 // register for which we inserted spill code for definition by what was
1177 // originally the first instruction in MBB.
1178 if (I == MachineBasicBlock::iterator(nullptr))
1181 const MachineInstr &MI = *I;
1182 MachineBasicBlock::iterator J = std::next(I);
1183 MachineBasicBlock::iterator P =
1184 I == MBB.begin() ? MachineBasicBlock::iterator(nullptr)
1187 // RS should process this instruction before we might scavenge at this
1188 // location. This is because we might be replacing a virtual register
1189 // defined by this instruction, and if so, registers killed by this
1190 // instruction are available, and defined registers are not.
1193 for (const MachineOperand &MO : MI.operands()) {
1196 unsigned Reg = MO.getReg();
1197 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1200 // When we first encounter a new virtual register, it
1201 // must be a definition.
1202 assert(MO.isDef() && "frame index virtual missing def!");
1203 // Scavenge a new scratch register
1204 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
1205 unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1209 // Replace this reference to the virtual register with the
1210 // scratch register.
1211 assert(ScratchReg && "Missing scratch register!");
1212 MRI.replaceRegWith(Reg, ScratchReg);
1214 // Because this instruction was processed by the RS before this
1215 // register was allocated, make sure that the RS now records the
1216 // register as being used.
1217 RS->setRegUsed(ScratchReg);
1220 // If the scavenger needed to use one of its spill slots, the
1221 // spill code will have been inserted in between I and J. This is a
1222 // problem because we need the spill code before I: Move I to just
1224 if (I != std::prev(J)) {
1225 MBB.splice(J, &MBB, I);
1227 // Before we move I, we need to prepare the RS to visit I again.
1228 // Specifically, RS will assert if it sees uses of registers that
1229 // it believes are undefined. Because we have already processed
1230 // register kills in I, when it visits I again, it will believe that
1231 // those registers are undefined. To avoid this situation, unprocess
1232 // the instruction I.
1233 assert(RS->getCurrentPosition() == I &&
1234 "The register scavenger has an unexpected position");
1242 MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);