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