1 //===- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function ---===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass is responsible for finalizing the functions frame layout, saving
10 // callee saved registers, and for emitting prolog & epilog code for the
13 // This pass must be run after register allocation. After this pass is
14 // executed, it is illegal to construct MO_FrameIndex operands.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineDominators.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineOperand.h"
37 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/RegisterScavenging.h"
40 #include "llvm/CodeGen/TargetFrameLowering.h"
41 #include "llvm/CodeGen/TargetInstrInfo.h"
42 #include "llvm/CodeGen/TargetOpcodes.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/WinEHFuncInfo.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/CallingConv.h"
48 #include "llvm/IR/DebugInfoMetadata.h"
49 #include "llvm/IR/DiagnosticInfo.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/InlineAsm.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/MC/MCRegisterInfo.h"
54 #include "llvm/Pass.h"
55 #include "llvm/Support/CodeGen.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/MathExtras.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Target/TargetMachine.h"
62 #include "llvm/Target/TargetOptions.h"
73 #define DEBUG_TYPE "prologepilog"
75 using MBBVector
= SmallVector
<MachineBasicBlock
*, 4>;
77 STATISTIC(NumLeafFuncWithSpills
, "Number of leaf functions with CSRs");
78 STATISTIC(NumFuncSeen
, "Number of functions seen in PEI");
83 class PEI
: public MachineFunctionPass
{
87 PEI() : MachineFunctionPass(ID
) {
88 initializePEIPass(*PassRegistry::getPassRegistry());
91 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
93 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
94 /// frame indexes with appropriate references.
95 bool runOnMachineFunction(MachineFunction
&MF
) override
;
100 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
101 // stack frame indexes.
102 unsigned MinCSFrameIndex
= std::numeric_limits
<unsigned>::max();
103 unsigned MaxCSFrameIndex
= 0;
105 // Save and Restore blocks of the current function. Typically there is a
106 // single save block, unless Windows EH funclets are involved.
107 MBBVector SaveBlocks
;
108 MBBVector RestoreBlocks
;
110 // Flag to control whether to use the register scavenger to resolve
111 // frame index materialization registers. Set according to
112 // TRI->requiresFrameIndexScavenging() for the current function.
113 bool FrameIndexVirtualScavenging
;
115 // Flag to control whether the scavenger should be passed even though
116 // FrameIndexVirtualScavenging is used.
117 bool FrameIndexEliminationScavenging
;
120 MachineOptimizationRemarkEmitter
*ORE
= nullptr;
122 void calculateCallFrameInfo(MachineFunction
&MF
);
123 void calculateSaveRestoreBlocks(MachineFunction
&MF
);
124 void spillCalleeSavedRegs(MachineFunction
&MF
);
126 void calculateFrameObjectOffsets(MachineFunction
&MF
);
127 void replaceFrameIndices(MachineFunction
&MF
);
128 void replaceFrameIndices(MachineBasicBlock
*BB
, MachineFunction
&MF
,
130 void insertPrologEpilogCode(MachineFunction
&MF
);
133 } // end anonymous namespace
137 char &llvm::PrologEpilogCodeInserterID
= PEI::ID
;
139 static cl::opt
<unsigned>
140 WarnStackSize("warn-stack-size", cl::Hidden
, cl::init((unsigned)-1),
141 cl::desc("Warn for stack size bigger than the given"
144 INITIALIZE_PASS_BEGIN(PEI
, DEBUG_TYPE
, "Prologue/Epilogue Insertion", false,
146 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
147 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
148 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass
)
149 INITIALIZE_PASS_END(PEI
, DEBUG_TYPE
,
150 "Prologue/Epilogue Insertion & Frame Finalization", false,
153 MachineFunctionPass
*llvm::createPrologEpilogInserterPass() {
157 STATISTIC(NumBytesStackSpace
,
158 "Number of bytes used for stack in all functions");
160 void PEI::getAnalysisUsage(AnalysisUsage
&AU
) const {
161 AU
.setPreservesCFG();
162 AU
.addPreserved
<MachineLoopInfo
>();
163 AU
.addPreserved
<MachineDominatorTree
>();
164 AU
.addRequired
<MachineOptimizationRemarkEmitterPass
>();
165 MachineFunctionPass::getAnalysisUsage(AU
);
168 /// StackObjSet - A set of stack object indexes
169 using StackObjSet
= SmallSetVector
<int, 8>;
171 using SavedDbgValuesMap
=
172 SmallDenseMap
<MachineBasicBlock
*, SmallVector
<MachineInstr
*, 4>, 4>;
174 /// Stash DBG_VALUEs that describe parameters and which are placed at the start
175 /// of the block. Later on, after the prologue code has been emitted, the
176 /// stashed DBG_VALUEs will be reinserted at the start of the block.
177 static void stashEntryDbgValues(MachineBasicBlock
&MBB
,
178 SavedDbgValuesMap
&EntryDbgValues
) {
179 SmallVector
<const MachineInstr
*, 4> FrameIndexValues
;
181 for (auto &MI
: MBB
) {
182 if (!MI
.isDebugInstr())
184 if (!MI
.isDebugValue() || !MI
.getDebugVariable()->isParameter())
186 if (MI
.getOperand(0).isFI()) {
187 // We can only emit valid locations for frame indices after the frame
188 // setup, so do not stash away them.
189 FrameIndexValues
.push_back(&MI
);
192 const DILocalVariable
*Var
= MI
.getDebugVariable();
193 const DIExpression
*Expr
= MI
.getDebugExpression();
194 auto Overlaps
= [Var
, Expr
](const MachineInstr
*DV
) {
195 return Var
== DV
->getDebugVariable() &&
196 Expr
->fragmentsOverlap(DV
->getDebugExpression());
198 // See if the debug value overlaps with any preceding debug value that will
199 // not be stashed. If that is the case, then we can't stash this value, as
200 // we would then reorder the values at reinsertion.
201 if (llvm::none_of(FrameIndexValues
, Overlaps
))
202 EntryDbgValues
[&MBB
].push_back(&MI
);
205 // Remove stashed debug values from the block.
206 if (EntryDbgValues
.count(&MBB
))
207 for (auto *MI
: EntryDbgValues
[&MBB
])
208 MI
->removeFromParent();
211 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
212 /// frame indexes with appropriate references.
213 bool PEI::runOnMachineFunction(MachineFunction
&MF
) {
215 const Function
&F
= MF
.getFunction();
216 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
217 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
219 RS
= TRI
->requiresRegisterScavenging(MF
) ? new RegScavenger() : nullptr;
220 FrameIndexVirtualScavenging
= TRI
->requiresFrameIndexScavenging(MF
);
221 ORE
= &getAnalysis
<MachineOptimizationRemarkEmitterPass
>().getORE();
223 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
224 // function's frame information. Also eliminates call frame pseudo
226 calculateCallFrameInfo(MF
);
228 // Determine placement of CSR spill/restore code and prolog/epilog code:
229 // place all spills in the entry block, all restores in return blocks.
230 calculateSaveRestoreBlocks(MF
);
232 // Stash away DBG_VALUEs that should not be moved by insertion of prolog code.
233 SavedDbgValuesMap EntryDbgValues
;
234 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
235 stashEntryDbgValues(*SaveBlock
, EntryDbgValues
);
237 // Handle CSR spilling and restoring, for targets that need it.
238 if (MF
.getTarget().usesPhysRegsForPEI())
239 spillCalleeSavedRegs(MF
);
241 // Allow the target machine to make final modifications to the function
242 // before the frame layout is finalized.
243 TFI
->processFunctionBeforeFrameFinalized(MF
, RS
);
245 // Calculate actual frame offsets for all abstract stack objects...
246 calculateFrameObjectOffsets(MF
);
248 // Add prolog and epilog code to the function. This function is required
249 // to align the stack frame as necessary for any stack variables or
250 // called functions. Because of this, calculateCalleeSavedRegisters()
251 // must be called before this function in order to set the AdjustsStack
252 // and MaxCallFrameSize variables.
253 if (!F
.hasFnAttribute(Attribute::Naked
))
254 insertPrologEpilogCode(MF
);
256 // Reinsert stashed debug values at the start of the entry blocks.
257 for (auto &I
: EntryDbgValues
)
258 I
.first
->insert(I
.first
->begin(), I
.second
.begin(), I
.second
.end());
260 // Replace all MO_FrameIndex operands with physical register references
261 // and actual offsets.
263 replaceFrameIndices(MF
);
265 // If register scavenging is needed, as we've enabled doing it as a
266 // post-pass, scavenge the virtual registers that frame index elimination
268 if (TRI
->requiresRegisterScavenging(MF
) && FrameIndexVirtualScavenging
)
269 scavengeFrameVirtualRegs(MF
, *RS
);
271 // Warn on stack size when we exceeds the given limit.
272 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
273 uint64_t StackSize
= MFI
.getStackSize();
274 if (WarnStackSize
.getNumOccurrences() > 0 && WarnStackSize
< StackSize
) {
275 DiagnosticInfoStackSize
DiagStackSize(F
, StackSize
);
276 F
.getContext().diagnose(DiagStackSize
);
279 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "StackSize",
280 MF
.getFunction().getSubprogram(),
282 << ore::NV("NumStackBytes", StackSize
) << " stack bytes in function";
287 RestoreBlocks
.clear();
288 MFI
.setSavePoint(nullptr);
289 MFI
.setRestorePoint(nullptr);
293 /// Calculate the MaxCallFrameSize and AdjustsStack
294 /// variables for the function's frame information and eliminate call frame
295 /// pseudo instructions.
296 void PEI::calculateCallFrameInfo(MachineFunction
&MF
) {
297 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
298 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
299 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
301 unsigned MaxCallFrameSize
= 0;
302 bool AdjustsStack
= MFI
.adjustsStack();
304 // Get the function call frame set-up and tear-down instruction opcode
305 unsigned FrameSetupOpcode
= TII
.getCallFrameSetupOpcode();
306 unsigned FrameDestroyOpcode
= TII
.getCallFrameDestroyOpcode();
308 // Early exit for targets which have no call frame setup/destroy pseudo
310 if (FrameSetupOpcode
== ~0u && FrameDestroyOpcode
== ~0u)
313 std::vector
<MachineBasicBlock::iterator
> FrameSDOps
;
314 for (MachineFunction::iterator BB
= MF
.begin(), E
= MF
.end(); BB
!= E
; ++BB
)
315 for (MachineBasicBlock::iterator I
= BB
->begin(); I
!= BB
->end(); ++I
)
316 if (TII
.isFrameInstr(*I
)) {
317 unsigned Size
= TII
.getFrameSize(*I
);
318 if (Size
> MaxCallFrameSize
) MaxCallFrameSize
= Size
;
320 FrameSDOps
.push_back(I
);
321 } else if (I
->isInlineAsm()) {
322 // Some inline asm's need a stack frame, as indicated by operand 1.
323 unsigned ExtraInfo
= I
->getOperand(InlineAsm::MIOp_ExtraInfo
).getImm();
324 if (ExtraInfo
& InlineAsm::Extra_IsAlignStack
)
328 assert(!MFI
.isMaxCallFrameSizeComputed() ||
329 (MFI
.getMaxCallFrameSize() == MaxCallFrameSize
&&
330 MFI
.adjustsStack() == AdjustsStack
));
331 MFI
.setAdjustsStack(AdjustsStack
);
332 MFI
.setMaxCallFrameSize(MaxCallFrameSize
);
334 for (std::vector
<MachineBasicBlock::iterator
>::iterator
335 i
= FrameSDOps
.begin(), e
= FrameSDOps
.end(); i
!= e
; ++i
) {
336 MachineBasicBlock::iterator I
= *i
;
338 // If call frames are not being included as part of the stack frame, and
339 // the target doesn't indicate otherwise, remove the call frame pseudos
340 // here. The sub/add sp instruction pairs are still inserted, but we don't
341 // need to track the SP adjustment for frame index elimination.
342 if (TFI
->canSimplifyCallFramePseudos(MF
))
343 TFI
->eliminateCallFramePseudoInstr(MF
, *I
->getParent(), I
);
347 /// Compute the sets of entry and return blocks for saving and restoring
348 /// callee-saved registers, and placing prolog and epilog code.
349 void PEI::calculateSaveRestoreBlocks(MachineFunction
&MF
) {
350 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
352 // Even when we do not change any CSR, we still want to insert the
353 // prologue and epilogue of the function.
354 // So set the save points for those.
356 // Use the points found by shrink-wrapping, if any.
357 if (MFI
.getSavePoint()) {
358 SaveBlocks
.push_back(MFI
.getSavePoint());
359 assert(MFI
.getRestorePoint() && "Both restore and save must be set");
360 MachineBasicBlock
*RestoreBlock
= MFI
.getRestorePoint();
361 // If RestoreBlock does not have any successor and is not a return block
362 // then the end point is unreachable and we do not need to insert any
364 if (!RestoreBlock
->succ_empty() || RestoreBlock
->isReturnBlock())
365 RestoreBlocks
.push_back(RestoreBlock
);
369 // Save refs to entry and return blocks.
370 SaveBlocks
.push_back(&MF
.front());
371 for (MachineBasicBlock
&MBB
: MF
) {
372 if (MBB
.isEHFuncletEntry())
373 SaveBlocks
.push_back(&MBB
);
374 if (MBB
.isReturnBlock())
375 RestoreBlocks
.push_back(&MBB
);
379 static void assignCalleeSavedSpillSlots(MachineFunction
&F
,
380 const BitVector
&SavedRegs
,
381 unsigned &MinCSFrameIndex
,
382 unsigned &MaxCSFrameIndex
) {
383 if (SavedRegs
.empty())
386 const TargetRegisterInfo
*RegInfo
= F
.getSubtarget().getRegisterInfo();
387 const MCPhysReg
*CSRegs
= F
.getRegInfo().getCalleeSavedRegs();
389 std::vector
<CalleeSavedInfo
> CSI
;
390 for (unsigned i
= 0; CSRegs
[i
]; ++i
) {
391 unsigned Reg
= CSRegs
[i
];
392 if (SavedRegs
.test(Reg
))
393 CSI
.push_back(CalleeSavedInfo(Reg
));
396 const TargetFrameLowering
*TFI
= F
.getSubtarget().getFrameLowering();
397 MachineFrameInfo
&MFI
= F
.getFrameInfo();
398 if (!TFI
->assignCalleeSavedSpillSlots(F
, RegInfo
, CSI
)) {
399 // If target doesn't implement this, use generic code.
402 return; // Early exit if no callee saved registers are modified!
404 unsigned NumFixedSpillSlots
;
405 const TargetFrameLowering::SpillSlot
*FixedSpillSlots
=
406 TFI
->getCalleeSavedSpillSlots(NumFixedSpillSlots
);
408 // Now that we know which registers need to be saved and restored, allocate
409 // stack slots for them.
410 for (auto &CS
: CSI
) {
411 // If the target has spilled this register to another register, we don't
412 // need to allocate a stack slot.
413 if (CS
.isSpilledToReg())
416 unsigned Reg
= CS
.getReg();
417 const TargetRegisterClass
*RC
= RegInfo
->getMinimalPhysRegClass(Reg
);
420 if (RegInfo
->hasReservedSpillSlot(F
, Reg
, FrameIdx
)) {
421 CS
.setFrameIdx(FrameIdx
);
425 // Check to see if this physreg must be spilled to a particular stack slot
427 const TargetFrameLowering::SpillSlot
*FixedSlot
= FixedSpillSlots
;
428 while (FixedSlot
!= FixedSpillSlots
+ NumFixedSpillSlots
&&
429 FixedSlot
->Reg
!= Reg
)
432 unsigned Size
= RegInfo
->getSpillSize(*RC
);
433 if (FixedSlot
== FixedSpillSlots
+ NumFixedSpillSlots
) {
434 // Nope, just spill it anywhere convenient.
435 unsigned Align
= RegInfo
->getSpillAlignment(*RC
);
436 unsigned StackAlign
= TFI
->getStackAlignment();
438 // We may not be able to satisfy the desired alignment specification of
439 // the TargetRegisterClass if the stack alignment is smaller. Use the
441 Align
= std::min(Align
, StackAlign
);
442 FrameIdx
= MFI
.CreateStackObject(Size
, Align
, true);
443 if ((unsigned)FrameIdx
< MinCSFrameIndex
) MinCSFrameIndex
= FrameIdx
;
444 if ((unsigned)FrameIdx
> MaxCSFrameIndex
) MaxCSFrameIndex
= FrameIdx
;
446 // Spill it to the stack where we must.
447 FrameIdx
= MFI
.CreateFixedSpillStackObject(Size
, FixedSlot
->Offset
);
450 CS
.setFrameIdx(FrameIdx
);
454 MFI
.setCalleeSavedInfo(CSI
);
457 /// Helper function to update the liveness information for the callee-saved
459 static void updateLiveness(MachineFunction
&MF
) {
460 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
461 // Visited will contain all the basic blocks that are in the region
462 // where the callee saved registers are alive:
463 // - Anything that is not Save or Restore -> LiveThrough.
465 // - Restore -> LiveOut.
466 // The live-out is not attached to the block, so no need to keep
467 // Restore in this set.
468 SmallPtrSet
<MachineBasicBlock
*, 8> Visited
;
469 SmallVector
<MachineBasicBlock
*, 8> WorkList
;
470 MachineBasicBlock
*Entry
= &MF
.front();
471 MachineBasicBlock
*Save
= MFI
.getSavePoint();
477 WorkList
.push_back(Entry
);
478 Visited
.insert(Entry
);
480 Visited
.insert(Save
);
482 MachineBasicBlock
*Restore
= MFI
.getRestorePoint();
484 // By construction Restore cannot be visited, otherwise it
485 // means there exists a path to Restore that does not go
487 WorkList
.push_back(Restore
);
489 while (!WorkList
.empty()) {
490 const MachineBasicBlock
*CurBB
= WorkList
.pop_back_val();
491 // By construction, the region that is after the save point is
492 // dominated by the Save and post-dominated by the Restore.
493 if (CurBB
== Save
&& Save
!= Restore
)
495 // Enqueue all the successors not already visited.
496 // Those are by construction either before Save or after Restore.
497 for (MachineBasicBlock
*SuccBB
: CurBB
->successors())
498 if (Visited
.insert(SuccBB
).second
)
499 WorkList
.push_back(SuccBB
);
502 const std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
504 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
505 for (unsigned i
= 0, e
= CSI
.size(); i
!= e
; ++i
) {
506 for (MachineBasicBlock
*MBB
: Visited
) {
507 MCPhysReg Reg
= CSI
[i
].getReg();
508 // Add the callee-saved register as live-in.
509 // It's killed at the spill.
510 if (!MRI
.isReserved(Reg
) && !MBB
->isLiveIn(Reg
))
513 // If callee-saved register is spilled to another register rather than
514 // spilling to stack, the destination register has to be marked as live for
515 // each MBB between the prologue and epilogue so that it is not clobbered
516 // before it is reloaded in the epilogue. The Visited set contains all
517 // blocks outside of the region delimited by prologue/epilogue.
518 if (CSI
[i
].isSpilledToReg()) {
519 for (MachineBasicBlock
&MBB
: MF
) {
520 if (Visited
.count(&MBB
))
522 MCPhysReg DstReg
= CSI
[i
].getDstReg();
523 if (!MBB
.isLiveIn(DstReg
))
524 MBB
.addLiveIn(DstReg
);
531 /// Insert restore code for the callee-saved registers used in the function.
532 static void insertCSRSaves(MachineBasicBlock
&SaveBlock
,
533 ArrayRef
<CalleeSavedInfo
> CSI
) {
534 MachineFunction
&MF
= *SaveBlock
.getParent();
535 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
536 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
537 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
539 MachineBasicBlock::iterator I
= SaveBlock
.begin();
540 if (!TFI
->spillCalleeSavedRegisters(SaveBlock
, I
, CSI
, TRI
)) {
541 for (const CalleeSavedInfo
&CS
: CSI
) {
542 // Insert the spill to the stack frame.
543 unsigned Reg
= CS
.getReg();
544 const TargetRegisterClass
*RC
= TRI
->getMinimalPhysRegClass(Reg
);
545 TII
.storeRegToStackSlot(SaveBlock
, I
, Reg
, true, CS
.getFrameIdx(), RC
,
551 /// Insert restore code for the callee-saved registers used in the function.
552 static void insertCSRRestores(MachineBasicBlock
&RestoreBlock
,
553 std::vector
<CalleeSavedInfo
> &CSI
) {
554 MachineFunction
&MF
= *RestoreBlock
.getParent();
555 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
556 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
557 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
559 // Restore all registers immediately before the return and any
560 // terminators that precede it.
561 MachineBasicBlock::iterator I
= RestoreBlock
.getFirstTerminator();
563 if (!TFI
->restoreCalleeSavedRegisters(RestoreBlock
, I
, CSI
, TRI
)) {
564 for (const CalleeSavedInfo
&CI
: reverse(CSI
)) {
565 unsigned Reg
= CI
.getReg();
566 const TargetRegisterClass
*RC
= TRI
->getMinimalPhysRegClass(Reg
);
567 TII
.loadRegFromStackSlot(RestoreBlock
, I
, Reg
, CI
.getFrameIdx(), RC
, TRI
);
568 assert(I
!= RestoreBlock
.begin() &&
569 "loadRegFromStackSlot didn't insert any code!");
570 // Insert in reverse order. loadRegFromStackSlot can insert
571 // multiple instructions.
576 void PEI::spillCalleeSavedRegs(MachineFunction
&MF
) {
577 // We can't list this requirement in getRequiredProperties because some
578 // targets (WebAssembly) use virtual registers past this point, and the pass
579 // pipeline is set up without giving the passes a chance to look at the
581 // FIXME: Find a way to express this in getRequiredProperties.
582 assert(MF
.getProperties().hasProperty(
583 MachineFunctionProperties::Property::NoVRegs
));
585 const Function
&F
= MF
.getFunction();
586 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
587 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
588 MinCSFrameIndex
= std::numeric_limits
<unsigned>::max();
591 // Determine which of the registers in the callee save list should be saved.
593 TFI
->determineCalleeSaves(MF
, SavedRegs
, RS
);
595 // Assign stack slots for any callee-saved registers that must be spilled.
596 assignCalleeSavedSpillSlots(MF
, SavedRegs
, MinCSFrameIndex
, MaxCSFrameIndex
);
598 // Add the code to save and restore the callee saved registers.
599 if (!F
.hasFnAttribute(Attribute::Naked
)) {
600 MFI
.setCalleeSavedInfoValid(true);
602 std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
605 NumLeafFuncWithSpills
++;
607 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
) {
608 insertCSRSaves(*SaveBlock
, CSI
);
609 // Update the live-in information of all the blocks up to the save
613 for (MachineBasicBlock
*RestoreBlock
: RestoreBlocks
)
614 insertCSRRestores(*RestoreBlock
, CSI
);
619 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
621 AdjustStackOffset(MachineFrameInfo
&MFI
, int FrameIdx
,
622 bool StackGrowsDown
, int64_t &Offset
,
623 unsigned &MaxAlign
, unsigned Skew
) {
624 // If the stack grows down, add the object size to find the lowest address.
626 Offset
+= MFI
.getObjectSize(FrameIdx
);
628 unsigned Align
= MFI
.getObjectAlignment(FrameIdx
);
630 // If the alignment of this object is greater than that of the stack, then
631 // increase the stack alignment to match.
632 MaxAlign
= std::max(MaxAlign
, Align
);
634 // Adjust to alignment boundary.
635 Offset
= alignTo(Offset
, Align
, Skew
);
637 if (StackGrowsDown
) {
638 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") at SP[" << -Offset
640 MFI
.setObjectOffset(FrameIdx
, -Offset
); // Set the computed offset
642 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") at SP[" << Offset
644 MFI
.setObjectOffset(FrameIdx
, Offset
);
645 Offset
+= MFI
.getObjectSize(FrameIdx
);
649 /// Compute which bytes of fixed and callee-save stack area are unused and keep
650 /// track of them in StackBytesFree.
652 computeFreeStackSlots(MachineFrameInfo
&MFI
, bool StackGrowsDown
,
653 unsigned MinCSFrameIndex
, unsigned MaxCSFrameIndex
,
654 int64_t FixedCSEnd
, BitVector
&StackBytesFree
) {
655 // Avoid undefined int64_t -> int conversion below in extreme case.
656 if (FixedCSEnd
> std::numeric_limits
<int>::max())
659 StackBytesFree
.resize(FixedCSEnd
, true);
661 SmallVector
<int, 16> AllocatedFrameSlots
;
662 // Add fixed objects.
663 for (int i
= MFI
.getObjectIndexBegin(); i
!= 0; ++i
)
664 // StackSlot scavenging is only implemented for the default stack.
665 if (MFI
.getStackID(i
) == 0)
666 AllocatedFrameSlots
.push_back(i
);
667 // Add callee-save objects.
668 for (int i
= MinCSFrameIndex
; i
<= (int)MaxCSFrameIndex
; ++i
)
669 if (MFI
.getStackID(i
) == 0)
670 AllocatedFrameSlots
.push_back(i
);
672 for (int i
: AllocatedFrameSlots
) {
673 // These are converted from int64_t, but they should always fit in int
674 // because of the FixedCSEnd check above.
675 int ObjOffset
= MFI
.getObjectOffset(i
);
676 int ObjSize
= MFI
.getObjectSize(i
);
677 int ObjStart
, ObjEnd
;
678 if (StackGrowsDown
) {
679 // ObjOffset is negative when StackGrowsDown is true.
680 ObjStart
= -ObjOffset
- ObjSize
;
683 ObjStart
= ObjOffset
;
684 ObjEnd
= ObjOffset
+ ObjSize
;
686 // Ignore fixed holes that are in the previous stack frame.
688 StackBytesFree
.reset(ObjStart
, ObjEnd
);
692 /// Assign frame object to an unused portion of the stack in the fixed stack
693 /// object range. Return true if the allocation was successful.
694 static inline bool scavengeStackSlot(MachineFrameInfo
&MFI
, int FrameIdx
,
695 bool StackGrowsDown
, unsigned MaxAlign
,
696 BitVector
&StackBytesFree
) {
697 if (MFI
.isVariableSizedObjectIndex(FrameIdx
))
700 if (StackBytesFree
.none()) {
701 // clear it to speed up later scavengeStackSlot calls to
702 // StackBytesFree.none()
703 StackBytesFree
.clear();
707 unsigned ObjAlign
= MFI
.getObjectAlignment(FrameIdx
);
708 if (ObjAlign
> MaxAlign
)
711 int64_t ObjSize
= MFI
.getObjectSize(FrameIdx
);
713 for (FreeStart
= StackBytesFree
.find_first(); FreeStart
!= -1;
714 FreeStart
= StackBytesFree
.find_next(FreeStart
)) {
716 // Check that free space has suitable alignment.
717 unsigned ObjStart
= StackGrowsDown
? FreeStart
+ ObjSize
: FreeStart
;
718 if (alignTo(ObjStart
, ObjAlign
) != ObjStart
)
721 if (FreeStart
+ ObjSize
> StackBytesFree
.size())
724 bool AllBytesFree
= true;
725 for (unsigned Byte
= 0; Byte
< ObjSize
; ++Byte
)
726 if (!StackBytesFree
.test(FreeStart
+ Byte
)) {
727 AllBytesFree
= false;
737 if (StackGrowsDown
) {
738 int ObjStart
= -(FreeStart
+ ObjSize
);
739 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") scavenged at SP["
740 << ObjStart
<< "]\n");
741 MFI
.setObjectOffset(FrameIdx
, ObjStart
);
743 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") scavenged at SP["
744 << FreeStart
<< "]\n");
745 MFI
.setObjectOffset(FrameIdx
, FreeStart
);
748 StackBytesFree
.reset(FreeStart
, FreeStart
+ ObjSize
);
752 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
753 /// those required to be close to the Stack Protector) to stack offsets.
755 AssignProtectedObjSet(const StackObjSet
&UnassignedObjs
,
756 SmallSet
<int, 16> &ProtectedObjs
,
757 MachineFrameInfo
&MFI
, bool StackGrowsDown
,
758 int64_t &Offset
, unsigned &MaxAlign
, unsigned Skew
) {
760 for (StackObjSet::const_iterator I
= UnassignedObjs
.begin(),
761 E
= UnassignedObjs
.end(); I
!= E
; ++I
) {
763 AdjustStackOffset(MFI
, i
, StackGrowsDown
, Offset
, MaxAlign
, Skew
);
764 ProtectedObjs
.insert(i
);
768 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
769 /// abstract stack objects.
770 void PEI::calculateFrameObjectOffsets(MachineFunction
&MF
) {
771 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
773 bool StackGrowsDown
=
774 TFI
.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown
;
776 // Loop over all of the stack objects, assigning sequential addresses...
777 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
779 // Start at the beginning of the local area.
780 // The Offset is the distance from the stack top in the direction
781 // of stack growth -- so it's always nonnegative.
782 int LocalAreaOffset
= TFI
.getOffsetOfLocalArea();
784 LocalAreaOffset
= -LocalAreaOffset
;
785 assert(LocalAreaOffset
>= 0
786 && "Local area offset should be in direction of stack growth");
787 int64_t Offset
= LocalAreaOffset
;
789 // Skew to be applied to alignment.
790 unsigned Skew
= TFI
.getStackAlignmentSkew(MF
);
792 #ifdef EXPENSIVE_CHECKS
793 for (unsigned i
= 0, e
= MFI
.getObjectIndexEnd(); i
!= e
; ++i
)
794 if (!MFI
.isDeadObjectIndex(i
) && MFI
.getStackID(i
) == 0)
795 assert(MFI
.getObjectAlignment(i
) <= MFI
.getMaxAlignment() &&
796 "MaxAlignment is invalid");
799 // If there are fixed sized objects that are preallocated in the local area,
800 // non-fixed objects can't be allocated right at the start of local area.
801 // Adjust 'Offset' to point to the end of last fixed sized preallocated
803 for (int i
= MFI
.getObjectIndexBegin(); i
!= 0; ++i
) {
804 if (MFI
.getStackID(i
)) // Only allocate objects on the default stack.
808 if (StackGrowsDown
) {
809 // The maximum distance from the stack pointer is at lower address of
810 // the object -- which is given by offset. For down growing stack
811 // the offset is negative, so we negate the offset to get the distance.
812 FixedOff
= -MFI
.getObjectOffset(i
);
814 // The maximum distance from the start pointer is at the upper
815 // address of the object.
816 FixedOff
= MFI
.getObjectOffset(i
) + MFI
.getObjectSize(i
);
818 if (FixedOff
> Offset
) Offset
= FixedOff
;
821 // First assign frame offsets to stack objects that are used to spill
822 // callee saved registers.
823 if (StackGrowsDown
) {
824 for (unsigned i
= MinCSFrameIndex
; i
<= MaxCSFrameIndex
; ++i
) {
825 if (MFI
.getStackID(i
)) // Only allocate objects on the default stack.
828 // If the stack grows down, we need to add the size to find the lowest
829 // address of the object.
830 Offset
+= MFI
.getObjectSize(i
);
832 unsigned Align
= MFI
.getObjectAlignment(i
);
833 // Adjust to alignment boundary
834 Offset
= alignTo(Offset
, Align
, Skew
);
836 LLVM_DEBUG(dbgs() << "alloc FI(" << i
<< ") at SP[" << -Offset
<< "]\n");
837 MFI
.setObjectOffset(i
, -Offset
); // Set the computed offset
839 } else if (MaxCSFrameIndex
>= MinCSFrameIndex
) {
840 // Be careful about underflow in comparisons agains MinCSFrameIndex.
841 for (unsigned i
= MaxCSFrameIndex
; i
!= MinCSFrameIndex
- 1; --i
) {
842 if (MFI
.getStackID(i
)) // Only allocate objects on the default stack.
845 if (MFI
.isDeadObjectIndex(i
))
848 unsigned Align
= MFI
.getObjectAlignment(i
);
849 // Adjust to alignment boundary
850 Offset
= alignTo(Offset
, Align
, Skew
);
852 LLVM_DEBUG(dbgs() << "alloc FI(" << i
<< ") at SP[" << Offset
<< "]\n");
853 MFI
.setObjectOffset(i
, Offset
);
854 Offset
+= MFI
.getObjectSize(i
);
858 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
860 int64_t FixedCSEnd
= Offset
;
861 unsigned MaxAlign
= MFI
.getMaxAlignment();
863 // Make sure the special register scavenging spill slot is closest to the
864 // incoming stack pointer if a frame pointer is required and is closer
865 // to the incoming rather than the final stack pointer.
866 const TargetRegisterInfo
*RegInfo
= MF
.getSubtarget().getRegisterInfo();
867 bool EarlyScavengingSlots
= (TFI
.hasFP(MF
) &&
868 TFI
.isFPCloseToIncomingSP() &&
869 RegInfo
->useFPForScavengingIndex(MF
) &&
870 !RegInfo
->needsStackRealignment(MF
));
871 if (RS
&& EarlyScavengingSlots
) {
872 SmallVector
<int, 2> SFIs
;
873 RS
->getScavengingFrameIndices(SFIs
);
874 for (SmallVectorImpl
<int>::iterator I
= SFIs
.begin(),
875 IE
= SFIs
.end(); I
!= IE
; ++I
)
876 AdjustStackOffset(MFI
, *I
, StackGrowsDown
, Offset
, MaxAlign
, Skew
);
879 // FIXME: Once this is working, then enable flag will change to a target
880 // check for whether the frame is large enough to want to use virtual
881 // frame index registers. Functions which don't want/need this optimization
882 // will continue to use the existing code path.
883 if (MFI
.getUseLocalStackAllocationBlock()) {
884 unsigned Align
= MFI
.getLocalFrameMaxAlign();
886 // Adjust to alignment boundary.
887 Offset
= alignTo(Offset
, Align
, Skew
);
889 LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset
<< "\n");
891 // Resolve offsets for objects in the local block.
892 for (unsigned i
= 0, e
= MFI
.getLocalFrameObjectCount(); i
!= e
; ++i
) {
893 std::pair
<int, int64_t> Entry
= MFI
.getLocalFrameObjectMap(i
);
894 int64_t FIOffset
= (StackGrowsDown
? -Offset
: Offset
) + Entry
.second
;
895 LLVM_DEBUG(dbgs() << "alloc FI(" << Entry
.first
<< ") at SP[" << FIOffset
897 MFI
.setObjectOffset(Entry
.first
, FIOffset
);
899 // Allocate the local block
900 Offset
+= MFI
.getLocalFrameSize();
902 MaxAlign
= std::max(Align
, MaxAlign
);
905 // Retrieve the Exception Handler registration node.
906 int EHRegNodeFrameIndex
= std::numeric_limits
<int>::max();
907 if (const WinEHFuncInfo
*FuncInfo
= MF
.getWinEHFuncInfo())
908 EHRegNodeFrameIndex
= FuncInfo
->EHRegNodeFrameIndex
;
910 // Make sure that the stack protector comes before the local variables on the
912 SmallSet
<int, 16> ProtectedObjs
;
913 if (MFI
.getStackProtectorIndex() >= 0) {
914 StackObjSet LargeArrayObjs
;
915 StackObjSet SmallArrayObjs
;
916 StackObjSet AddrOfObjs
;
918 AdjustStackOffset(MFI
, MFI
.getStackProtectorIndex(), StackGrowsDown
,
919 Offset
, MaxAlign
, Skew
);
921 // Assign large stack objects first.
922 for (unsigned i
= 0, e
= MFI
.getObjectIndexEnd(); i
!= e
; ++i
) {
923 if (MFI
.isObjectPreAllocated(i
) &&
924 MFI
.getUseLocalStackAllocationBlock())
926 if (i
>= MinCSFrameIndex
&& i
<= MaxCSFrameIndex
)
928 if (RS
&& RS
->isScavengingFrameIndex((int)i
))
930 if (MFI
.isDeadObjectIndex(i
))
932 if (MFI
.getStackProtectorIndex() == (int)i
||
933 EHRegNodeFrameIndex
== (int)i
)
935 if (MFI
.getStackID(i
)) // Only allocate objects on the default stack.
938 switch (MFI
.getObjectSSPLayout(i
)) {
939 case MachineFrameInfo::SSPLK_None
:
941 case MachineFrameInfo::SSPLK_SmallArray
:
942 SmallArrayObjs
.insert(i
);
944 case MachineFrameInfo::SSPLK_AddrOf
:
945 AddrOfObjs
.insert(i
);
947 case MachineFrameInfo::SSPLK_LargeArray
:
948 LargeArrayObjs
.insert(i
);
951 llvm_unreachable("Unexpected SSPLayoutKind.");
954 AssignProtectedObjSet(LargeArrayObjs
, ProtectedObjs
, MFI
, StackGrowsDown
,
955 Offset
, MaxAlign
, Skew
);
956 AssignProtectedObjSet(SmallArrayObjs
, ProtectedObjs
, MFI
, StackGrowsDown
,
957 Offset
, MaxAlign
, Skew
);
958 AssignProtectedObjSet(AddrOfObjs
, ProtectedObjs
, MFI
, StackGrowsDown
,
959 Offset
, MaxAlign
, Skew
);
962 SmallVector
<int, 8> ObjectsToAllocate
;
964 // Then prepare to assign frame offsets to stack objects that are not used to
965 // spill callee saved registers.
966 for (unsigned i
= 0, e
= MFI
.getObjectIndexEnd(); i
!= e
; ++i
) {
967 if (MFI
.isObjectPreAllocated(i
) && MFI
.getUseLocalStackAllocationBlock())
969 if (i
>= MinCSFrameIndex
&& i
<= MaxCSFrameIndex
)
971 if (RS
&& RS
->isScavengingFrameIndex((int)i
))
973 if (MFI
.isDeadObjectIndex(i
))
975 if (MFI
.getStackProtectorIndex() == (int)i
||
976 EHRegNodeFrameIndex
== (int)i
)
978 if (ProtectedObjs
.count(i
))
980 if (MFI
.getStackID(i
)) // Only allocate objects on the default stack.
983 // Add the objects that we need to allocate to our working set.
984 ObjectsToAllocate
.push_back(i
);
987 // Allocate the EH registration node first if one is present.
988 if (EHRegNodeFrameIndex
!= std::numeric_limits
<int>::max())
989 AdjustStackOffset(MFI
, EHRegNodeFrameIndex
, StackGrowsDown
, Offset
,
992 // Give the targets a chance to order the objects the way they like it.
993 if (MF
.getTarget().getOptLevel() != CodeGenOpt::None
&&
994 MF
.getTarget().Options
.StackSymbolOrdering
)
995 TFI
.orderFrameObjects(MF
, ObjectsToAllocate
);
997 // Keep track of which bytes in the fixed and callee-save range are used so we
998 // can use the holes when allocating later stack objects. Only do this if
999 // stack protector isn't being used and the target requests it and we're
1001 BitVector StackBytesFree
;
1002 if (!ObjectsToAllocate
.empty() &&
1003 MF
.getTarget().getOptLevel() != CodeGenOpt::None
&&
1004 MFI
.getStackProtectorIndex() < 0 && TFI
.enableStackSlotScavenging(MF
))
1005 computeFreeStackSlots(MFI
, StackGrowsDown
, MinCSFrameIndex
, MaxCSFrameIndex
,
1006 FixedCSEnd
, StackBytesFree
);
1008 // Now walk the objects and actually assign base offsets to them.
1009 for (auto &Object
: ObjectsToAllocate
)
1010 if (!scavengeStackSlot(MFI
, Object
, StackGrowsDown
, MaxAlign
,
1012 AdjustStackOffset(MFI
, Object
, StackGrowsDown
, Offset
, MaxAlign
, Skew
);
1014 // Make sure the special register scavenging spill slot is closest to the
1016 if (RS
&& !EarlyScavengingSlots
) {
1017 SmallVector
<int, 2> SFIs
;
1018 RS
->getScavengingFrameIndices(SFIs
);
1019 for (SmallVectorImpl
<int>::iterator I
= SFIs
.begin(),
1020 IE
= SFIs
.end(); I
!= IE
; ++I
)
1021 AdjustStackOffset(MFI
, *I
, StackGrowsDown
, Offset
, MaxAlign
, Skew
);
1024 if (!TFI
.targetHandlesStackFrameRounding()) {
1025 // If we have reserved argument space for call sites in the function
1026 // immediately on entry to the current function, count it as part of the
1027 // overall stack size.
1028 if (MFI
.adjustsStack() && TFI
.hasReservedCallFrame(MF
))
1029 Offset
+= MFI
.getMaxCallFrameSize();
1031 // Round up the size to a multiple of the alignment. If the function has
1032 // any calls or alloca's, align to the target's StackAlignment value to
1033 // ensure that the callee's frame or the alloca data is suitably aligned;
1034 // otherwise, for leaf functions, align to the TransientStackAlignment
1036 unsigned StackAlign
;
1037 if (MFI
.adjustsStack() || MFI
.hasVarSizedObjects() ||
1038 (RegInfo
->needsStackRealignment(MF
) && MFI
.getObjectIndexEnd() != 0))
1039 StackAlign
= TFI
.getStackAlignment();
1041 StackAlign
= TFI
.getTransientStackAlignment();
1043 // If the frame pointer is eliminated, all frame offsets will be relative to
1044 // SP not FP. Align to MaxAlign so this works.
1045 StackAlign
= std::max(StackAlign
, MaxAlign
);
1046 Offset
= alignTo(Offset
, StackAlign
, Skew
);
1049 // Update frame info to pretend that this is part of the stack...
1050 int64_t StackSize
= Offset
- LocalAreaOffset
;
1051 MFI
.setStackSize(StackSize
);
1052 NumBytesStackSpace
+= StackSize
;
1055 /// insertPrologEpilogCode - Scan the function for modified callee saved
1056 /// registers, insert spill code for these callee saved registers, then add
1057 /// prolog and epilog code to the function.
1058 void PEI::insertPrologEpilogCode(MachineFunction
&MF
) {
1059 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
1061 // Add prologue to the function...
1062 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1063 TFI
.emitPrologue(MF
, *SaveBlock
);
1065 // Add epilogue to restore the callee-save registers in each exiting block.
1066 for (MachineBasicBlock
*RestoreBlock
: RestoreBlocks
)
1067 TFI
.emitEpilogue(MF
, *RestoreBlock
);
1069 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1070 TFI
.inlineStackProbe(MF
, *SaveBlock
);
1072 // Emit additional code that is required to support segmented stacks, if
1073 // we've been asked for it. This, when linked with a runtime with support
1074 // for segmented stacks (libgcc is one), will result in allocating stack
1075 // space in small chunks instead of one large contiguous block.
1076 if (MF
.shouldSplitStack()) {
1077 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1078 TFI
.adjustForSegmentedStacks(MF
, *SaveBlock
);
1079 // Record that there are split-stack functions, so we will emit a
1080 // special section to tell the linker.
1081 MF
.getMMI().setHasSplitStack(true);
1083 MF
.getMMI().setHasNosplitStack(true);
1085 // Emit additional code that is required to explicitly handle the stack in
1086 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1087 // approach is rather similar to that of Segmented Stacks, but it uses a
1088 // different conditional check and another BIF for allocating more stack
1090 if (MF
.getFunction().getCallingConv() == CallingConv::HiPE
)
1091 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1092 TFI
.adjustForHiPEPrologue(MF
, *SaveBlock
);
1095 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1096 /// register references and actual offsets.
1097 void PEI::replaceFrameIndices(MachineFunction
&MF
) {
1098 const auto &ST
= MF
.getSubtarget();
1099 const TargetFrameLowering
&TFI
= *ST
.getFrameLowering();
1100 if (!TFI
.needsFrameIndexResolution(MF
))
1103 const TargetRegisterInfo
*TRI
= ST
.getRegisterInfo();
1105 // Allow the target to determine this after knowing the frame size.
1106 FrameIndexEliminationScavenging
= (RS
&& !FrameIndexVirtualScavenging
) ||
1107 TRI
->requiresFrameIndexReplacementScavenging(MF
);
1109 // Store SPAdj at exit of a basic block.
1110 SmallVector
<int, 8> SPState
;
1111 SPState
.resize(MF
.getNumBlockIDs());
1112 df_iterator_default_set
<MachineBasicBlock
*> Reachable
;
1114 // Iterate over the reachable blocks in DFS order.
1115 for (auto DFI
= df_ext_begin(&MF
, Reachable
), DFE
= df_ext_end(&MF
, Reachable
);
1116 DFI
!= DFE
; ++DFI
) {
1118 // Check the exit state of the DFS stack predecessor.
1119 if (DFI
.getPathLength() >= 2) {
1120 MachineBasicBlock
*StackPred
= DFI
.getPath(DFI
.getPathLength() - 2);
1121 assert(Reachable
.count(StackPred
) &&
1122 "DFS stack predecessor is already visited.\n");
1123 SPAdj
= SPState
[StackPred
->getNumber()];
1125 MachineBasicBlock
*BB
= *DFI
;
1126 replaceFrameIndices(BB
, MF
, SPAdj
);
1127 SPState
[BB
->getNumber()] = SPAdj
;
1130 // Handle the unreachable blocks.
1131 for (auto &BB
: MF
) {
1132 if (Reachable
.count(&BB
))
1133 // Already handled in DFS traversal.
1136 replaceFrameIndices(&BB
, MF
, SPAdj
);
1140 void PEI::replaceFrameIndices(MachineBasicBlock
*BB
, MachineFunction
&MF
,
1142 assert(MF
.getSubtarget().getRegisterInfo() &&
1143 "getRegisterInfo() must be implemented!");
1144 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
1145 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1146 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
1148 if (RS
&& FrameIndexEliminationScavenging
)
1149 RS
->enterBasicBlock(*BB
);
1151 bool InsideCallSequence
= false;
1153 for (MachineBasicBlock::iterator I
= BB
->begin(); I
!= BB
->end(); ) {
1154 if (TII
.isFrameInstr(*I
)) {
1155 InsideCallSequence
= TII
.isFrameSetup(*I
);
1156 SPAdj
+= TII
.getSPAdjust(*I
);
1157 I
= TFI
->eliminateCallFramePseudoInstr(MF
, *BB
, I
);
1161 MachineInstr
&MI
= *I
;
1163 bool DidFinishLoop
= true;
1164 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
1165 if (!MI
.getOperand(i
).isFI())
1168 // Frame indices in debug values are encoded in a target independent
1169 // way with simply the frame index and offset rather than any
1170 // target-specific addressing mode.
1171 if (MI
.isDebugValue()) {
1172 assert(i
== 0 && "Frame indices can only appear as the first "
1173 "operand of a DBG_VALUE machine instruction");
1175 unsigned FrameIdx
= MI
.getOperand(0).getIndex();
1176 unsigned Size
= MF
.getFrameInfo().getObjectSize(FrameIdx
);
1179 TFI
->getFrameIndexReference(MF
, FrameIdx
, Reg
);
1180 MI
.getOperand(0).ChangeToRegister(Reg
, false /*isDef*/);
1181 MI
.getOperand(0).setIsDebug();
1183 const DIExpression
*DIExpr
= MI
.getDebugExpression();
1184 // If we have DBG_VALUE that is indirect and has a Implicit location
1185 // expression need to insert a deref before prepending a Memory
1186 // location expression. Also after doing this we change the DBG_VALUE
1188 if (MI
.isIndirectDebugValue() && DIExpr
->isImplicit()) {
1189 SmallVector
<uint64_t, 2> Ops
= {dwarf::DW_OP_deref_size
, Size
};
1190 DIExpr
= DIExpression::prependOpcodes(DIExpr
, Ops
, DIExpression::WithStackValue
);
1191 // Make the DBG_VALUE direct.
1192 MI
.getOperand(1).ChangeToRegister(0, false);
1194 DIExpr
= DIExpression::prepend(DIExpr
, DIExpression::NoDeref
, Offset
);
1195 MI
.getOperand(3).setMetadata(DIExpr
);
1199 // TODO: This code should be commoned with the code for
1200 // PATCHPOINT. There's no good reason for the difference in
1201 // implementation other than historical accident. The only
1202 // remaining difference is the unconditional use of the stack
1203 // pointer as the base register.
1204 if (MI
.getOpcode() == TargetOpcode::STATEPOINT
) {
1205 assert((!MI
.isDebugValue() || i
== 0) &&
1206 "Frame indicies can only appear as the first operand of a "
1207 "DBG_VALUE machine instruction");
1209 MachineOperand
&Offset
= MI
.getOperand(i
+ 1);
1210 int refOffset
= TFI
->getFrameIndexReferencePreferSP(
1211 MF
, MI
.getOperand(i
).getIndex(), Reg
, /*IgnoreSPUpdates*/ false);
1212 Offset
.setImm(Offset
.getImm() + refOffset
+ SPAdj
);
1213 MI
.getOperand(i
).ChangeToRegister(Reg
, false /*isDef*/);
1217 // Some instructions (e.g. inline asm instructions) can have
1218 // multiple frame indices and/or cause eliminateFrameIndex
1219 // to insert more than one instruction. We need the register
1220 // scavenger to go through all of these instructions so that
1221 // it can update its register information. We keep the
1222 // iterator at the point before insertion so that we can
1223 // revisit them in full.
1224 bool AtBeginning
= (I
== BB
->begin());
1225 if (!AtBeginning
) --I
;
1227 // If this instruction has a FrameIndex operand, we need to
1228 // use that target machine register info object to eliminate
1230 TRI
.eliminateFrameIndex(MI
, SPAdj
, i
,
1231 FrameIndexEliminationScavenging
? RS
: nullptr);
1233 // Reset the iterator if we were at the beginning of the BB.
1239 DidFinishLoop
= false;
1243 // If we are looking at a call sequence, we need to keep track of
1244 // the SP adjustment made by each instruction in the sequence.
1245 // This includes both the frame setup/destroy pseudos (handled above),
1246 // as well as other instructions that have side effects w.r.t the SP.
1247 // Note that this must come after eliminateFrameIndex, because
1248 // if I itself referred to a frame index, we shouldn't count its own
1250 if (DidFinishLoop
&& InsideCallSequence
)
1251 SPAdj
+= TII
.getSPAdjust(MI
);
1253 if (DoIncr
&& I
!= BB
->end()) ++I
;
1255 // Update register states.
1256 if (RS
&& FrameIndexEliminationScavenging
&& DidFinishLoop
)