LLVM  10.0.0
PrologEpilogInserter.cpp
Go to the documentation of this file.
1 //===- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function ---===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass is responsible for finalizing the functions frame layout, saving
10 // callee saved registers, and for emitting prolog & epilog code for the
11 // function.
12 //
13 // This pass must be run after register allocation. After this pass is
14 // executed, it is illegal to construct MO_FrameIndex operands.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.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"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/CallingConv.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/InitializePasses.h"
55 #include "llvm/MC/MCRegisterInfo.h"
56 #include "llvm/Pass.h"
57 #include "llvm/Support/CodeGen.h"
59 #include "llvm/Support/Debug.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstdint>
68 #include <functional>
69 #include <limits>
70 #include <utility>
71 #include <vector>
72 
73 using namespace llvm;
74 
75 #define DEBUG_TYPE "prologepilog"
76 
78 
79 STATISTIC(NumLeafFuncWithSpills, "Number of leaf functions with CSRs");
80 STATISTIC(NumFuncSeen, "Number of functions seen in PEI");
81 
82 
83 namespace {
84 
85 class PEI : public MachineFunctionPass {
86 public:
87  static char ID;
88 
89  PEI() : MachineFunctionPass(ID) {
91  }
92 
93  void getAnalysisUsage(AnalysisUsage &AU) const override;
94 
95  /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
96  /// frame indexes with appropriate references.
97  bool runOnMachineFunction(MachineFunction &MF) override;
98 
99 private:
100  RegScavenger *RS;
101 
102  // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
103  // stack frame indexes.
104  unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max();
105  unsigned MaxCSFrameIndex = 0;
106 
107  // Save and Restore blocks of the current function. Typically there is a
108  // single save block, unless Windows EH funclets are involved.
109  MBBVector SaveBlocks;
110  MBBVector RestoreBlocks;
111 
112  // Flag to control whether to use the register scavenger to resolve
113  // frame index materialization registers. Set according to
114  // TRI->requiresFrameIndexScavenging() for the current function.
115  bool FrameIndexVirtualScavenging;
116 
117  // Flag to control whether the scavenger should be passed even though
118  // FrameIndexVirtualScavenging is used.
119  bool FrameIndexEliminationScavenging;
120 
121  // Emit remarks.
122  MachineOptimizationRemarkEmitter *ORE = nullptr;
123 
124  void calculateCallFrameInfo(MachineFunction &MF);
125  void calculateSaveRestoreBlocks(MachineFunction &MF);
126  void spillCalleeSavedRegs(MachineFunction &MF);
127 
128  void calculateFrameObjectOffsets(MachineFunction &MF);
129  void replaceFrameIndices(MachineFunction &MF);
130  void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
131  int &SPAdj);
132  void insertPrologEpilogCode(MachineFunction &MF);
133 };
134 
135 } // end anonymous namespace
136 
137 char PEI::ID = 0;
138 
140 
141 static cl::opt<unsigned>
142 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
143  cl::desc("Warn for stack size bigger than the given"
144  " number"));
145 
146 INITIALIZE_PASS_BEGIN(PEI, DEBUG_TYPE, "Prologue/Epilogue Insertion", false,
147  false)
152  "Prologue/Epilogue Insertion & Frame Finalization", false,
153  false)
154 
156  return new PEI();
157 }
158 
159 STATISTIC(NumBytesStackSpace,
160  "Number of bytes used for stack in all functions");
161 
162 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
163  AU.setPreservesCFG();
168 }
169 
170 /// StackObjSet - A set of stack object indexes
172 
173 using SavedDbgValuesMap =
175 
176 /// Stash DBG_VALUEs that describe parameters and which are placed at the start
177 /// of the block. Later on, after the prologue code has been emitted, the
178 /// stashed DBG_VALUEs will be reinserted at the start of the block.
180  SavedDbgValuesMap &EntryDbgValues) {
181  SmallVector<const MachineInstr *, 4> FrameIndexValues;
182 
183  for (auto &MI : MBB) {
184  if (!MI.isDebugInstr())
185  break;
186  if (!MI.isDebugValue() || !MI.getDebugVariable()->isParameter())
187  continue;
188  if (MI.getOperand(0).isFI()) {
189  // We can only emit valid locations for frame indices after the frame
190  // setup, so do not stash away them.
191  FrameIndexValues.push_back(&MI);
192  continue;
193  }
194  const DILocalVariable *Var = MI.getDebugVariable();
195  const DIExpression *Expr = MI.getDebugExpression();
196  auto Overlaps = [Var, Expr](const MachineInstr *DV) {
197  return Var == DV->getDebugVariable() &&
198  Expr->fragmentsOverlap(DV->getDebugExpression());
199  };
200  // See if the debug value overlaps with any preceding debug value that will
201  // not be stashed. If that is the case, then we can't stash this value, as
202  // we would then reorder the values at reinsertion.
203  if (llvm::none_of(FrameIndexValues, Overlaps))
204  EntryDbgValues[&MBB].push_back(&MI);
205  }
206 
207  // Remove stashed debug values from the block.
208  if (EntryDbgValues.count(&MBB))
209  for (auto *MI : EntryDbgValues[&MBB])
210  MI->removeFromParent();
211 }
212 
213 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
214 /// frame indexes with appropriate references.
215 bool PEI::runOnMachineFunction(MachineFunction &MF) {
216  NumFuncSeen++;
217  const Function &F = MF.getFunction();
220 
221  RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr;
222  FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(MF);
223  ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
224 
225  // Calculate the MaxCallFrameSize and AdjustsStack variables for the
226  // function's frame information. Also eliminates call frame pseudo
227  // instructions.
228  calculateCallFrameInfo(MF);
229 
230  // Determine placement of CSR spill/restore code and prolog/epilog code:
231  // place all spills in the entry block, all restores in return blocks.
232  calculateSaveRestoreBlocks(MF);
233 
234  // Stash away DBG_VALUEs that should not be moved by insertion of prolog code.
235  SavedDbgValuesMap EntryDbgValues;
236  for (MachineBasicBlock *SaveBlock : SaveBlocks)
237  stashEntryDbgValues(*SaveBlock, EntryDbgValues);
238 
239  // Handle CSR spilling and restoring, for targets that need it.
240  if (MF.getTarget().usesPhysRegsForPEI())
241  spillCalleeSavedRegs(MF);
242 
243  // Allow the target machine to make final modifications to the function
244  // before the frame layout is finalized.
246 
247  // Calculate actual frame offsets for all abstract stack objects...
248  calculateFrameObjectOffsets(MF);
249 
250  // Add prolog and epilog code to the function. This function is required
251  // to align the stack frame as necessary for any stack variables or
252  // called functions. Because of this, calculateCalleeSavedRegisters()
253  // must be called before this function in order to set the AdjustsStack
254  // and MaxCallFrameSize variables.
255  if (!F.hasFnAttribute(Attribute::Naked))
256  insertPrologEpilogCode(MF);
257 
258  // Reinsert stashed debug values at the start of the entry blocks.
259  for (auto &I : EntryDbgValues)
260  I.first->insert(I.first->begin(), I.second.begin(), I.second.end());
261 
262  // Replace all MO_FrameIndex operands with physical register references
263  // and actual offsets.
264  //
265  replaceFrameIndices(MF);
266 
267  // If register scavenging is needed, as we've enabled doing it as a
268  // post-pass, scavenge the virtual registers that frame index elimination
269  // inserted.
270  if (TRI->requiresRegisterScavenging(MF) && FrameIndexVirtualScavenging)
271  scavengeFrameVirtualRegs(MF, *RS);
272 
273  // Warn on stack size when we exceeds the given limit.
274  MachineFrameInfo &MFI = MF.getFrameInfo();
275  uint64_t StackSize = MFI.getStackSize();
276  if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
277  DiagnosticInfoStackSize DiagStackSize(F, StackSize);
278  F.getContext().diagnose(DiagStackSize);
279  }
280  ORE->emit([&]() {
281  return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "StackSize",
282  MF.getFunction().getSubprogram(),
283  &MF.front())
284  << ore::NV("NumStackBytes", StackSize) << " stack bytes in function";
285  });
286 
287  delete RS;
288  SaveBlocks.clear();
289  RestoreBlocks.clear();
290  MFI.setSavePoint(nullptr);
291  MFI.setRestorePoint(nullptr);
292  return true;
293 }
294 
295 /// Calculate the MaxCallFrameSize and AdjustsStack
296 /// variables for the function's frame information and eliminate call frame
297 /// pseudo instructions.
298 void PEI::calculateCallFrameInfo(MachineFunction &MF) {
299  const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
301  MachineFrameInfo &MFI = MF.getFrameInfo();
302 
303  unsigned MaxCallFrameSize = 0;
304  bool AdjustsStack = MFI.adjustsStack();
305 
306  // Get the function call frame set-up and tear-down instruction opcode
307  unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
308  unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
309 
310  // Early exit for targets which have no call frame setup/destroy pseudo
311  // instructions.
312  if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
313  return;
314 
315  std::vector<MachineBasicBlock::iterator> FrameSDOps;
316  for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
317  for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
318  if (TII.isFrameInstr(*I)) {
319  unsigned Size = TII.getFrameSize(*I);
320  if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
321  AdjustsStack = true;
322  FrameSDOps.push_back(I);
323  } else if (I->isInlineAsm()) {
324  // Some inline asm's need a stack frame, as indicated by operand 1.
325  unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
326  if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
327  AdjustsStack = true;
328  }
329 
331  (MFI.getMaxCallFrameSize() == MaxCallFrameSize &&
332  MFI.adjustsStack() == AdjustsStack));
333  MFI.setAdjustsStack(AdjustsStack);
334  MFI.setMaxCallFrameSize(MaxCallFrameSize);
335 
336  for (std::vector<MachineBasicBlock::iterator>::iterator
337  i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
339 
340  // If call frames are not being included as part of the stack frame, and
341  // the target doesn't indicate otherwise, remove the call frame pseudos
342  // here. The sub/add sp instruction pairs are still inserted, but we don't
343  // need to track the SP adjustment for frame index elimination.
344  if (TFI->canSimplifyCallFramePseudos(MF))
345  TFI->eliminateCallFramePseudoInstr(MF, *I->getParent(), I);
346  }
347 }
348 
349 /// Compute the sets of entry and return blocks for saving and restoring
350 /// callee-saved registers, and placing prolog and epilog code.
351 void PEI::calculateSaveRestoreBlocks(MachineFunction &MF) {
352  const MachineFrameInfo &MFI = MF.getFrameInfo();
353 
354  // Even when we do not change any CSR, we still want to insert the
355  // prologue and epilogue of the function.
356  // So set the save points for those.
357 
358  // Use the points found by shrink-wrapping, if any.
359  if (MFI.getSavePoint()) {
360  SaveBlocks.push_back(MFI.getSavePoint());
361  assert(MFI.getRestorePoint() && "Both restore and save must be set");
362  MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
363  // If RestoreBlock does not have any successor and is not a return block
364  // then the end point is unreachable and we do not need to insert any
365  // epilogue.
366  if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
367  RestoreBlocks.push_back(RestoreBlock);
368  return;
369  }
370 
371  // Save refs to entry and return blocks.
372  SaveBlocks.push_back(&MF.front());
373  for (MachineBasicBlock &MBB : MF) {
374  if (MBB.isEHFuncletEntry())
375  SaveBlocks.push_back(&MBB);
376  if (MBB.isReturnBlock())
377  RestoreBlocks.push_back(&MBB);
378  }
379 }
380 
382  const BitVector &SavedRegs,
383  unsigned &MinCSFrameIndex,
384  unsigned &MaxCSFrameIndex) {
385  if (SavedRegs.empty())
386  return;
387 
388  const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
389  const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
390 
391  std::vector<CalleeSavedInfo> CSI;
392  for (unsigned i = 0; CSRegs[i]; ++i) {
393  unsigned Reg = CSRegs[i];
394  if (SavedRegs.test(Reg))
395  CSI.push_back(CalleeSavedInfo(Reg));
396  }
397 
399  MachineFrameInfo &MFI = F.getFrameInfo();
400  if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
401  // If target doesn't implement this, use generic code.
402 
403  if (CSI.empty())
404  return; // Early exit if no callee saved registers are modified!
405 
406  unsigned NumFixedSpillSlots;
407  const TargetFrameLowering::SpillSlot *FixedSpillSlots =
408  TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
409 
410  // Now that we know which registers need to be saved and restored, allocate
411  // stack slots for them.
412  for (auto &CS : CSI) {
413  // If the target has spilled this register to another register, we don't
414  // need to allocate a stack slot.
415  if (CS.isSpilledToReg())
416  continue;
417 
418  unsigned Reg = CS.getReg();
419  const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
420 
421  int FrameIdx;
422  if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
423  CS.setFrameIdx(FrameIdx);
424  continue;
425  }
426 
427  // Check to see if this physreg must be spilled to a particular stack slot
428  // on this target.
429  const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
430  while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
431  FixedSlot->Reg != Reg)
432  ++FixedSlot;
433 
434  unsigned Size = RegInfo->getSpillSize(*RC);
435  if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
436  // Nope, just spill it anywhere convenient.
437  unsigned Align = RegInfo->getSpillAlignment(*RC);
438  unsigned StackAlign = TFI->getStackAlignment();
439 
440  // We may not be able to satisfy the desired alignment specification of
441  // the TargetRegisterClass if the stack alignment is smaller. Use the
442  // min.
443  Align = std::min(Align, StackAlign);
444  FrameIdx = MFI.CreateStackObject(Size, Align, true);
445  if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
446  if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
447  } else {
448  // Spill it to the stack where we must.
449  FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
450  }
451 
452  CS.setFrameIdx(FrameIdx);
453  }
454  }
455 
456  MFI.setCalleeSavedInfo(CSI);
457 }
458 
459 /// Helper function to update the liveness information for the callee-saved
460 /// registers.
461 static void updateLiveness(MachineFunction &MF) {
462  MachineFrameInfo &MFI = MF.getFrameInfo();
463  // Visited will contain all the basic blocks that are in the region
464  // where the callee saved registers are alive:
465  // - Anything that is not Save or Restore -> LiveThrough.
466  // - Save -> LiveIn.
467  // - Restore -> LiveOut.
468  // The live-out is not attached to the block, so no need to keep
469  // Restore in this set.
472  MachineBasicBlock *Entry = &MF.front();
473  MachineBasicBlock *Save = MFI.getSavePoint();
474 
475  if (!Save)
476  Save = Entry;
477 
478  if (Entry != Save) {
479  WorkList.push_back(Entry);
480  Visited.insert(Entry);
481  }
482  Visited.insert(Save);
483 
484  MachineBasicBlock *Restore = MFI.getRestorePoint();
485  if (Restore)
486  // By construction Restore cannot be visited, otherwise it
487  // means there exists a path to Restore that does not go
488  // through Save.
489  WorkList.push_back(Restore);
490 
491  while (!WorkList.empty()) {
492  const MachineBasicBlock *CurBB = WorkList.pop_back_val();
493  // By construction, the region that is after the save point is
494  // dominated by the Save and post-dominated by the Restore.
495  if (CurBB == Save && Save != Restore)
496  continue;
497  // Enqueue all the successors not already visited.
498  // Those are by construction either before Save or after Restore.
499  for (MachineBasicBlock *SuccBB : CurBB->successors())
500  if (Visited.insert(SuccBB).second)
501  WorkList.push_back(SuccBB);
502  }
503 
504  const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
505 
507  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
508  for (MachineBasicBlock *MBB : Visited) {
509  MCPhysReg Reg = CSI[i].getReg();
510  // Add the callee-saved register as live-in.
511  // It's killed at the spill.
512  if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg))
513  MBB->addLiveIn(Reg);
514  }
515  // If callee-saved register is spilled to another register rather than
516  // spilling to stack, the destination register has to be marked as live for
517  // each MBB between the prologue and epilogue so that it is not clobbered
518  // before it is reloaded in the epilogue. The Visited set contains all
519  // blocks outside of the region delimited by prologue/epilogue.
520  if (CSI[i].isSpilledToReg()) {
521  for (MachineBasicBlock &MBB : MF) {
522  if (Visited.count(&MBB))
523  continue;
524  MCPhysReg DstReg = CSI[i].getDstReg();
525  if (!MBB.isLiveIn(DstReg))
526  MBB.addLiveIn(DstReg);
527  }
528  }
529  }
530 
531 }
532 
533 /// Insert restore code for the callee-saved registers used in the function.
534 static void insertCSRSaves(MachineBasicBlock &SaveBlock,
536  MachineFunction &MF = *SaveBlock.getParent();
537  const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
540 
541  MachineBasicBlock::iterator I = SaveBlock.begin();
542  if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) {
543  for (const CalleeSavedInfo &CS : CSI) {
544  // Insert the spill to the stack frame.
545  unsigned Reg = CS.getReg();
546 
547  if (CS.isSpilledToReg()) {
548  BuildMI(SaveBlock, I, DebugLoc(),
549  TII.get(TargetOpcode::COPY), CS.getDstReg())
550  .addReg(Reg, getKillRegState(true));
551  } else {
552  const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
553  TII.storeRegToStackSlot(SaveBlock, I, Reg, true, CS.getFrameIdx(), RC,
554  TRI);
555  }
556  }
557  }
558 }
559 
560 /// Insert restore code for the callee-saved registers used in the function.
561 static void insertCSRRestores(MachineBasicBlock &RestoreBlock,
562  std::vector<CalleeSavedInfo> &CSI) {
563  MachineFunction &MF = *RestoreBlock.getParent();
564  const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
567 
568  // Restore all registers immediately before the return and any
569  // terminators that precede it.
571 
572  if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) {
573  for (const CalleeSavedInfo &CI : reverse(CSI)) {
574  unsigned Reg = CI.getReg();
575  if (CI.isSpilledToReg()) {
576  BuildMI(RestoreBlock, I, DebugLoc(), TII.get(TargetOpcode::COPY), Reg)
577  .addReg(CI.getDstReg(), getKillRegState(true));
578  } else {
579  const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
580  TII.loadRegFromStackSlot(RestoreBlock, I, Reg, CI.getFrameIdx(), RC, TRI);
581  assert(I != RestoreBlock.begin() &&
582  "loadRegFromStackSlot didn't insert any code!");
583  // Insert in reverse order. loadRegFromStackSlot can insert
584  // multiple instructions.
585  }
586  }
587  }
588 }
589 
590 void PEI::spillCalleeSavedRegs(MachineFunction &MF) {
591  // We can't list this requirement in getRequiredProperties because some
592  // targets (WebAssembly) use virtual registers past this point, and the pass
593  // pipeline is set up without giving the passes a chance to look at the
594  // TargetMachine.
595  // FIXME: Find a way to express this in getRequiredProperties.
598 
599  const Function &F = MF.getFunction();
601  MachineFrameInfo &MFI = MF.getFrameInfo();
602  MinCSFrameIndex = std::numeric_limits<unsigned>::max();
603  MaxCSFrameIndex = 0;
604 
605  // Determine which of the registers in the callee save list should be saved.
606  BitVector SavedRegs;
607  TFI->determineCalleeSaves(MF, SavedRegs, RS);
608 
609  // Assign stack slots for any callee-saved registers that must be spilled.
610  assignCalleeSavedSpillSlots(MF, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex);
611 
612  // Add the code to save and restore the callee saved registers.
613  if (!F.hasFnAttribute(Attribute::Naked)) {
614  MFI.setCalleeSavedInfoValid(true);
615 
616  std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
617  if (!CSI.empty()) {
618  if (!MFI.hasCalls())
619  NumLeafFuncWithSpills++;
620 
621  for (MachineBasicBlock *SaveBlock : SaveBlocks) {
622  insertCSRSaves(*SaveBlock, CSI);
623  // Update the live-in information of all the blocks up to the save
624  // point.
625  updateLiveness(MF);
626  }
627  for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
628  insertCSRRestores(*RestoreBlock, CSI);
629  }
630  }
631 }
632 
633 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
634 static inline void
636  bool StackGrowsDown, int64_t &Offset,
637  unsigned &MaxAlign, unsigned Skew) {
638  // If the stack grows down, add the object size to find the lowest address.
639  if (StackGrowsDown)
640  Offset += MFI.getObjectSize(FrameIdx);
641 
642  unsigned Align = MFI.getObjectAlignment(FrameIdx);
643 
644  // If the alignment of this object is greater than that of the stack, then
645  // increase the stack alignment to match.
646  MaxAlign = std::max(MaxAlign, Align);
647 
648  // Adjust to alignment boundary.
649  Offset = alignTo(Offset, Align, Skew);
650 
651  if (StackGrowsDown) {
652  LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset
653  << "]\n");
654  MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
655  } else {
656  LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset
657  << "]\n");
658  MFI.setObjectOffset(FrameIdx, Offset);
659  Offset += MFI.getObjectSize(FrameIdx);
660  }
661 }
662 
663 /// Compute which bytes of fixed and callee-save stack area are unused and keep
664 /// track of them in StackBytesFree.
665 static inline void
666 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
667  unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
668  int64_t FixedCSEnd, BitVector &StackBytesFree) {
669  // Avoid undefined int64_t -> int conversion below in extreme case.
670  if (FixedCSEnd > std::numeric_limits<int>::max())
671  return;
672 
673  StackBytesFree.resize(FixedCSEnd, true);
674 
675  SmallVector<int, 16> AllocatedFrameSlots;
676  // Add fixed objects.
677  for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
678  // StackSlot scavenging is only implemented for the default stack.
679  if (MFI.getStackID(i) == TargetStackID::Default)
680  AllocatedFrameSlots.push_back(i);
681  // Add callee-save objects.
682  for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
683  if (MFI.getStackID(i) == TargetStackID::Default)
684  AllocatedFrameSlots.push_back(i);
685 
686  for (int i : AllocatedFrameSlots) {
687  // These are converted from int64_t, but they should always fit in int
688  // because of the FixedCSEnd check above.
689  int ObjOffset = MFI.getObjectOffset(i);
690  int ObjSize = MFI.getObjectSize(i);
691  int ObjStart, ObjEnd;
692  if (StackGrowsDown) {
693  // ObjOffset is negative when StackGrowsDown is true.
694  ObjStart = -ObjOffset - ObjSize;
695  ObjEnd = -ObjOffset;
696  } else {
697  ObjStart = ObjOffset;
698  ObjEnd = ObjOffset + ObjSize;
699  }
700  // Ignore fixed holes that are in the previous stack frame.
701  if (ObjEnd > 0)
702  StackBytesFree.reset(ObjStart, ObjEnd);
703  }
704 }
705 
706 /// Assign frame object to an unused portion of the stack in the fixed stack
707 /// object range. Return true if the allocation was successful.
708 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
709  bool StackGrowsDown, unsigned MaxAlign,
710  BitVector &StackBytesFree) {
711  if (MFI.isVariableSizedObjectIndex(FrameIdx))
712  return false;
713 
714  if (StackBytesFree.none()) {
715  // clear it to speed up later scavengeStackSlot calls to
716  // StackBytesFree.none()
717  StackBytesFree.clear();
718  return false;
719  }
720 
721  unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx);
722  if (ObjAlign > MaxAlign)
723  return false;
724 
725  int64_t ObjSize = MFI.getObjectSize(FrameIdx);
726  int FreeStart;
727  for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
728  FreeStart = StackBytesFree.find_next(FreeStart)) {
729 
730  // Check that free space has suitable alignment.
731  unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
732  if (alignTo(ObjStart, ObjAlign) != ObjStart)
733  continue;
734 
735  if (FreeStart + ObjSize > StackBytesFree.size())
736  return false;
737 
738  bool AllBytesFree = true;
739  for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
740  if (!StackBytesFree.test(FreeStart + Byte)) {
741  AllBytesFree = false;
742  break;
743  }
744  if (AllBytesFree)
745  break;
746  }
747 
748  if (FreeStart == -1)
749  return false;
750 
751  if (StackGrowsDown) {
752  int ObjStart = -(FreeStart + ObjSize);
753  LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
754  << ObjStart << "]\n");
755  MFI.setObjectOffset(FrameIdx, ObjStart);
756  } else {
757  LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
758  << FreeStart << "]\n");
759  MFI.setObjectOffset(FrameIdx, FreeStart);
760  }
761 
762  StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
763  return true;
764 }
765 
766 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
767 /// those required to be close to the Stack Protector) to stack offsets.
768 static void
769 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
770  SmallSet<int, 16> &ProtectedObjs,
771  MachineFrameInfo &MFI, bool StackGrowsDown,
772  int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
773 
774  for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
775  E = UnassignedObjs.end(); I != E; ++I) {
776  int i = *I;
777  AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
778  ProtectedObjs.insert(i);
779  }
780 }
781 
782 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
783 /// abstract stack objects.
784 void PEI::calculateFrameObjectOffsets(MachineFunction &MF) {
786 
787  bool StackGrowsDown =
789 
790  // Loop over all of the stack objects, assigning sequential addresses...
791  MachineFrameInfo &MFI = MF.getFrameInfo();
792 
793  // Start at the beginning of the local area.
794  // The Offset is the distance from the stack top in the direction
795  // of stack growth -- so it's always nonnegative.
796  int LocalAreaOffset = TFI.getOffsetOfLocalArea();
797  if (StackGrowsDown)
798  LocalAreaOffset = -LocalAreaOffset;
799  assert(LocalAreaOffset >= 0
800  && "Local area offset should be in direction of stack growth");
801  int64_t Offset = LocalAreaOffset;
802 
803  // Skew to be applied to alignment.
804  unsigned Skew = TFI.getStackAlignmentSkew(MF);
805 
806 #ifdef EXPENSIVE_CHECKS
807  for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i)
808  if (!MFI.isDeadObjectIndex(i) &&
810  assert(MFI.getObjectAlignment(i) <= MFI.getMaxAlignment() &&
811  "MaxAlignment is invalid");
812 #endif
813 
814  // If there are fixed sized objects that are preallocated in the local area,
815  // non-fixed objects can't be allocated right at the start of local area.
816  // Adjust 'Offset' to point to the end of last fixed sized preallocated
817  // object.
818  for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
819  if (MFI.getStackID(i) !=
820  TargetStackID::Default) // Only allocate objects on the default stack.
821  continue;
822 
823  int64_t FixedOff;
824  if (StackGrowsDown) {
825  // The maximum distance from the stack pointer is at lower address of
826  // the object -- which is given by offset. For down growing stack
827  // the offset is negative, so we negate the offset to get the distance.
828  FixedOff = -MFI.getObjectOffset(i);
829  } else {
830  // The maximum distance from the start pointer is at the upper
831  // address of the object.
832  FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
833  }
834  if (FixedOff > Offset) Offset = FixedOff;
835  }
836 
837  // First assign frame offsets to stack objects that are used to spill
838  // callee saved registers.
839  if (StackGrowsDown) {
840  for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
841  if (MFI.getStackID(i) !=
842  TargetStackID::Default) // Only allocate objects on the default stack.
843  continue;
844 
845  // If the stack grows down, we need to add the size to find the lowest
846  // address of the object.
847  Offset += MFI.getObjectSize(i);
848 
849  unsigned Align = MFI.getObjectAlignment(i);
850  // Adjust to alignment boundary
851  Offset = alignTo(Offset, Align, Skew);
852 
853  LLVM_DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
854  MFI.setObjectOffset(i, -Offset); // Set the computed offset
855  }
856  } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
857  // Be careful about underflow in comparisons agains MinCSFrameIndex.
858  for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
859  if (MFI.getStackID(i) !=
860  TargetStackID::Default) // Only allocate objects on the default stack.
861  continue;
862 
863  if (MFI.isDeadObjectIndex(i))
864  continue;
865 
866  unsigned Align = MFI.getObjectAlignment(i);
867  // Adjust to alignment boundary
868  Offset = alignTo(Offset, Align, Skew);
869 
870  LLVM_DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
871  MFI.setObjectOffset(i, Offset);
872  Offset += MFI.getObjectSize(i);
873  }
874  }
875 
876  // FixedCSEnd is the stack offset to the end of the fixed and callee-save
877  // stack area.
878  int64_t FixedCSEnd = Offset;
879  unsigned MaxAlign = MFI.getMaxAlignment();
880 
881  // Make sure the special register scavenging spill slot is closest to the
882  // incoming stack pointer if a frame pointer is required and is closer
883  // to the incoming rather than the final stack pointer.
884  const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
885  bool EarlyScavengingSlots = (TFI.hasFP(MF) &&
886  TFI.isFPCloseToIncomingSP() &&
887  RegInfo->useFPForScavengingIndex(MF) &&
888  !RegInfo->needsStackRealignment(MF));
889  if (RS && EarlyScavengingSlots) {
890  SmallVector<int, 2> SFIs;
891  RS->getScavengingFrameIndices(SFIs);
892  for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
893  IE = SFIs.end(); I != IE; ++I)
894  AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
895  }
896 
897  // FIXME: Once this is working, then enable flag will change to a target
898  // check for whether the frame is large enough to want to use virtual
899  // frame index registers. Functions which don't want/need this optimization
900  // will continue to use the existing code path.
902  unsigned Align = MFI.getLocalFrameMaxAlign().value();
903 
904  // Adjust to alignment boundary.
905  Offset = alignTo(Offset, Align, Skew);
906 
907  LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
908 
909  // Resolve offsets for objects in the local block.
910  for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
911  std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
912  int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
913  LLVM_DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << FIOffset
914  << "]\n");
915  MFI.setObjectOffset(Entry.first, FIOffset);
916  }
917  // Allocate the local block
918  Offset += MFI.getLocalFrameSize();
919 
920  MaxAlign = std::max(Align, MaxAlign);
921  }
922 
923  // Retrieve the Exception Handler registration node.
924  int EHRegNodeFrameIndex = std::numeric_limits<int>::max();
925  if (const WinEHFuncInfo *FuncInfo = MF.getWinEHFuncInfo())
926  EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
927 
928  // Make sure that the stack protector comes before the local variables on the
929  // stack.
930  SmallSet<int, 16> ProtectedObjs;
931  if (MFI.hasStackProtectorIndex()) {
932  int StackProtectorFI = MFI.getStackProtectorIndex();
933  StackObjSet LargeArrayObjs;
934  StackObjSet SmallArrayObjs;
935  StackObjSet AddrOfObjs;
936 
937  // If we need a stack protector, we need to make sure that
938  // LocalStackSlotPass didn't already allocate a slot for it.
939  // If we are told to use the LocalStackAllocationBlock, the stack protector
940  // is expected to be already pre-allocated.
942  AdjustStackOffset(MFI, StackProtectorFI, StackGrowsDown, Offset, MaxAlign,
943  Skew);
944  else if (!MFI.isObjectPreAllocated(MFI.getStackProtectorIndex()))
946  "Stack protector not pre-allocated by LocalStackSlotPass.");
947 
948  // Assign large stack objects first.
949  for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
951  continue;
952  if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
953  continue;
954  if (RS && RS->isScavengingFrameIndex((int)i))
955  continue;
956  if (MFI.isDeadObjectIndex(i))
957  continue;
958  if (StackProtectorFI == (int)i || EHRegNodeFrameIndex == (int)i)
959  continue;
960  if (MFI.getStackID(i) !=
961  TargetStackID::Default) // Only allocate objects on the default stack.
962  continue;
963 
964  switch (MFI.getObjectSSPLayout(i)) {
966  continue;
968  SmallArrayObjs.insert(i);
969  continue;
971  AddrOfObjs.insert(i);
972  continue;
974  LargeArrayObjs.insert(i);
975  continue;
976  }
977  llvm_unreachable("Unexpected SSPLayoutKind.");
978  }
979 
980  // We expect **all** the protected stack objects to be pre-allocated by
981  // LocalStackSlotPass. If it turns out that PEI still has to allocate some
982  // of them, we may end up messing up the expected order of the objects.
984  !(LargeArrayObjs.empty() && SmallArrayObjs.empty() &&
985  AddrOfObjs.empty()))
986  llvm_unreachable("Found protected stack objects not pre-allocated by "
987  "LocalStackSlotPass.");
988 
989  AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
990  Offset, MaxAlign, Skew);
991  AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
992  Offset, MaxAlign, Skew);
993  AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
994  Offset, MaxAlign, Skew);
995  }
996 
997  SmallVector<int, 8> ObjectsToAllocate;
998 
999  // Then prepare to assign frame offsets to stack objects that are not used to
1000  // spill callee saved registers.
1001  for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1003  continue;
1004  if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
1005  continue;
1006  if (RS && RS->isScavengingFrameIndex((int)i))
1007  continue;
1008  if (MFI.isDeadObjectIndex(i))
1009  continue;
1010  if (MFI.getStackProtectorIndex() == (int)i || EHRegNodeFrameIndex == (int)i)
1011  continue;
1012  if (ProtectedObjs.count(i))
1013  continue;
1014  if (MFI.getStackID(i) !=
1015  TargetStackID::Default) // Only allocate objects on the default stack.
1016  continue;
1017 
1018  // Add the objects that we need to allocate to our working set.
1019  ObjectsToAllocate.push_back(i);
1020  }
1021 
1022  // Allocate the EH registration node first if one is present.
1023  if (EHRegNodeFrameIndex != std::numeric_limits<int>::max())
1024  AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
1025  MaxAlign, Skew);
1026 
1027  // Give the targets a chance to order the objects the way they like it.
1028  if (MF.getTarget().getOptLevel() != CodeGenOpt::None &&
1030  TFI.orderFrameObjects(MF, ObjectsToAllocate);
1031 
1032  // Keep track of which bytes in the fixed and callee-save range are used so we
1033  // can use the holes when allocating later stack objects. Only do this if
1034  // stack protector isn't being used and the target requests it and we're
1035  // optimizing.
1036  BitVector StackBytesFree;
1037  if (!ObjectsToAllocate.empty() &&
1040  computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex,
1041  FixedCSEnd, StackBytesFree);
1042 
1043  // Now walk the objects and actually assign base offsets to them.
1044  for (auto &Object : ObjectsToAllocate)
1045  if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
1046  StackBytesFree))
1047  AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
1048 
1049  // Make sure the special register scavenging spill slot is closest to the
1050  // stack pointer.
1051  if (RS && !EarlyScavengingSlots) {
1052  SmallVector<int, 2> SFIs;
1053  RS->getScavengingFrameIndices(SFIs);
1054  for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
1055  IE = SFIs.end(); I != IE; ++I)
1056  AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
1057  }
1058 
1059  if (!TFI.targetHandlesStackFrameRounding()) {
1060  // If we have reserved argument space for call sites in the function
1061  // immediately on entry to the current function, count it as part of the
1062  // overall stack size.
1063  if (MFI.adjustsStack() && TFI.hasReservedCallFrame(MF))
1064  Offset += MFI.getMaxCallFrameSize();
1065 
1066  // Round up the size to a multiple of the alignment. If the function has
1067  // any calls or alloca's, align to the target's StackAlignment value to
1068  // ensure that the callee's frame or the alloca data is suitably aligned;
1069  // otherwise, for leaf functions, align to the TransientStackAlignment
1070  // value.
1071  unsigned StackAlign;
1072  if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
1073  (RegInfo->needsStackRealignment(MF) && MFI.getObjectIndexEnd() != 0))
1074  StackAlign = TFI.getStackAlignment();
1075  else
1076  StackAlign = TFI.getTransientStackAlignment();
1077 
1078  // If the frame pointer is eliminated, all frame offsets will be relative to
1079  // SP not FP. Align to MaxAlign so this works.
1080  StackAlign = std::max(StackAlign, MaxAlign);
1081  Offset = alignTo(Offset, StackAlign, Skew);
1082  }
1083 
1084  // Update frame info to pretend that this is part of the stack...
1085  int64_t StackSize = Offset - LocalAreaOffset;
1086  MFI.setStackSize(StackSize);
1087  NumBytesStackSpace += StackSize;
1088 }
1089 
1090 /// insertPrologEpilogCode - Scan the function for modified callee saved
1091 /// registers, insert spill code for these callee saved registers, then add
1092 /// prolog and epilog code to the function.
1093 void PEI::insertPrologEpilogCode(MachineFunction &MF) {
1094  const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1095 
1096  // Add prologue to the function...
1097  for (MachineBasicBlock *SaveBlock : SaveBlocks)
1098  TFI.emitPrologue(MF, *SaveBlock);
1099 
1100  // Add epilogue to restore the callee-save registers in each exiting block.
1101  for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
1102  TFI.emitEpilogue(MF, *RestoreBlock);
1103 
1104  for (MachineBasicBlock *SaveBlock : SaveBlocks)
1105  TFI.inlineStackProbe(MF, *SaveBlock);
1106 
1107  // Emit additional code that is required to support segmented stacks, if
1108  // we've been asked for it. This, when linked with a runtime with support
1109  // for segmented stacks (libgcc is one), will result in allocating stack
1110  // space in small chunks instead of one large contiguous block.
1111  if (MF.shouldSplitStack()) {
1112  for (MachineBasicBlock *SaveBlock : SaveBlocks)
1113  TFI.adjustForSegmentedStacks(MF, *SaveBlock);
1114  // Record that there are split-stack functions, so we will emit a
1115  // special section to tell the linker.
1116  MF.getMMI().setHasSplitStack(true);
1117  } else
1118  MF.getMMI().setHasNosplitStack(true);
1119 
1120  // Emit additional code that is required to explicitly handle the stack in
1121  // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1122  // approach is rather similar to that of Segmented Stacks, but it uses a
1123  // different conditional check and another BIF for allocating more stack
1124  // space.
1126  for (MachineBasicBlock *SaveBlock : SaveBlocks)
1127  TFI.adjustForHiPEPrologue(MF, *SaveBlock);
1128 }
1129 
1130 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1131 /// register references and actual offsets.
1132 void PEI::replaceFrameIndices(MachineFunction &MF) {
1133  const auto &ST = MF.getSubtarget();
1134  const TargetFrameLowering &TFI = *ST.getFrameLowering();
1135  if (!TFI.needsFrameIndexResolution(MF))
1136  return;
1137 
1138  const TargetRegisterInfo *TRI = ST.getRegisterInfo();
1139 
1140  // Allow the target to determine this after knowing the frame size.
1141  FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) ||
1143 
1144  // Store SPAdj at exit of a basic block.
1145  SmallVector<int, 8> SPState;
1146  SPState.resize(MF.getNumBlockIDs());
1148 
1149  // Iterate over the reachable blocks in DFS order.
1150  for (auto DFI = df_ext_begin(&MF, Reachable), DFE = df_ext_end(&MF, Reachable);
1151  DFI != DFE; ++DFI) {
1152  int SPAdj = 0;
1153  // Check the exit state of the DFS stack predecessor.
1154  if (DFI.getPathLength() >= 2) {
1155  MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1156  assert(Reachable.count(StackPred) &&
1157  "DFS stack predecessor is already visited.\n");
1158  SPAdj = SPState[StackPred->getNumber()];
1159  }
1160  MachineBasicBlock *BB = *DFI;
1161  replaceFrameIndices(BB, MF, SPAdj);
1162  SPState[BB->getNumber()] = SPAdj;
1163  }
1164 
1165  // Handle the unreachable blocks.
1166  for (auto &BB : MF) {
1167  if (Reachable.count(&BB))
1168  // Already handled in DFS traversal.
1169  continue;
1170  int SPAdj = 0;
1171  replaceFrameIndices(&BB, MF, SPAdj);
1172  }
1173 }
1174 
1175 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
1176  int &SPAdj) {
1178  "getRegisterInfo() must be implemented!");
1179  const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1182 
1183  if (RS && FrameIndexEliminationScavenging)
1184  RS->enterBasicBlock(*BB);
1185 
1186  bool InsideCallSequence = false;
1187 
1188  for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1189  if (TII.isFrameInstr(*I)) {
1190  InsideCallSequence = TII.isFrameSetup(*I);
1191  SPAdj += TII.getSPAdjust(*I);
1192  I = TFI->eliminateCallFramePseudoInstr(MF, *BB, I);
1193  continue;
1194  }
1195 
1196  MachineInstr &MI = *I;
1197  bool DoIncr = true;
1198  bool DidFinishLoop = true;
1199  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1200  if (!MI.getOperand(i).isFI())
1201  continue;
1202 
1203  // Frame indices in debug values are encoded in a target independent
1204  // way with simply the frame index and offset rather than any
1205  // target-specific addressing mode.
1206  if (MI.isDebugValue()) {
1207  assert(i == 0 && "Frame indices can only appear as the first "
1208  "operand of a DBG_VALUE machine instruction");
1209  unsigned Reg;
1210  unsigned FrameIdx = MI.getOperand(0).getIndex();
1211  unsigned Size = MF.getFrameInfo().getObjectSize(FrameIdx);
1212 
1213  int64_t Offset =
1214  TFI->getFrameIndexReference(MF, FrameIdx, Reg);
1215  MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
1216  MI.getOperand(0).setIsDebug();
1217 
1218  const DIExpression *DIExpr = MI.getDebugExpression();
1219 
1220  // If we have a direct DBG_VALUE, and its location expression isn't
1221  // currently complex, then adding an offset will morph it into a
1222  // complex location that is interpreted as being a memory address.
1223  // This changes a pointer-valued variable to dereference that pointer,
1224  // which is incorrect. Fix by adding DW_OP_stack_value.
1225  unsigned PrependFlags = DIExpression::ApplyOffset;
1226  if (!MI.isIndirectDebugValue() && !DIExpr->isComplex())
1227  PrependFlags |= DIExpression::StackValue;
1228 
1229  // If we have DBG_VALUE that is indirect and has a Implicit location
1230  // expression need to insert a deref before prepending a Memory
1231  // location expression. Also after doing this we change the DBG_VALUE
1232  // to be direct.
1233  if (MI.isIndirectDebugValue() && DIExpr->isImplicit()) {
1234  SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
1235  bool WithStackValue = true;
1236  DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1237  // Make the DBG_VALUE direct.
1238  MI.getOperand(1).ChangeToRegister(0, false);
1239  }
1240  DIExpr = DIExpression::prepend(DIExpr, PrependFlags, Offset);
1241  MI.getOperand(3).setMetadata(DIExpr);
1242  continue;
1243  }
1244 
1245  // TODO: This code should be commoned with the code for
1246  // PATCHPOINT. There's no good reason for the difference in
1247  // implementation other than historical accident. The only
1248  // remaining difference is the unconditional use of the stack
1249  // pointer as the base register.
1250  if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1251  assert((!MI.isDebugValue() || i == 0) &&
1252  "Frame indicies can only appear as the first operand of a "
1253  "DBG_VALUE machine instruction");
1254  unsigned Reg;
1255  MachineOperand &Offset = MI.getOperand(i + 1);
1256  int refOffset = TFI->getFrameIndexReferencePreferSP(
1257  MF, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1258  Offset.setImm(Offset.getImm() + refOffset + SPAdj);
1259  MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
1260  continue;
1261  }
1262 
1263  // Some instructions (e.g. inline asm instructions) can have
1264  // multiple frame indices and/or cause eliminateFrameIndex
1265  // to insert more than one instruction. We need the register
1266  // scavenger to go through all of these instructions so that
1267  // it can update its register information. We keep the
1268  // iterator at the point before insertion so that we can
1269  // revisit them in full.
1270  bool AtBeginning = (I == BB->begin());
1271  if (!AtBeginning) --I;
1272 
1273  // If this instruction has a FrameIndex operand, we need to
1274  // use that target machine register info object to eliminate
1275  // it.
1276  TRI.eliminateFrameIndex(MI, SPAdj, i,
1277  FrameIndexEliminationScavenging ? RS : nullptr);
1278 
1279  // Reset the iterator if we were at the beginning of the BB.
1280  if (AtBeginning) {
1281  I = BB->begin();
1282  DoIncr = false;
1283  }
1284 
1285  DidFinishLoop = false;
1286  break;
1287  }
1288 
1289  // If we are looking at a call sequence, we need to keep track of
1290  // the SP adjustment made by each instruction in the sequence.
1291  // This includes both the frame setup/destroy pseudos (handled above),
1292  // as well as other instructions that have side effects w.r.t the SP.
1293  // Note that this must come after eliminateFrameIndex, because
1294  // if I itself referred to a frame index, we shouldn't count its own
1295  // adjustment.
1296  if (DidFinishLoop && InsideCallSequence)
1297  SPAdj += TII.getSPAdjust(MI);
1298 
1299  if (DoIncr && I != BB->end()) ++I;
1300 
1301  // Update register states.
1302  if (RS && FrameIndexEliminationScavenging && DidFinishLoop)
1303  RS->forward(MI);
1304  }
1305 }
unsigned StackSymbolOrdering
StackSymbolOrdering - When true, this will allow CodeGen to order the local stack symbols (for code s...
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition: BitVector.h:371
void setSavePoint(MachineBasicBlock *NewSave)
void setRestorePoint(MachineBasicBlock *NewRestore)
virtual bool requiresRegisterScavenging(const MachineFunction &MF) const
Returns true if the target requires (and can make use of) the register scavenger. ...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, bool StackGrowsDown, int64_t &Offset, unsigned &MaxAlign, unsigned Skew)
AdjustStackOffset - Helper function used to adjust the stack frame offset.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isReserved(Register PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
void setCalleeSavedInfoValid(bool v)
static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B)
Check if fragments overlap between a pair of FragmentInfos.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool empty() const
empty - Tests whether there are no bits in this bitvector.
Definition: BitVector.h:166
static void computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown, unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex, int64_t FixedCSEnd, BitVector &StackBytesFree)
Compute which bytes of fixed and callee-save stack area are unused and keep track of them in StackByt...
bool hasStackProtectorIndex() const
Did not trigger a stack protector.
virtual int getFrameIndexReference(const MachineFunction &MF, int FI, unsigned &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg, int &FrameIdx) const
Return true if target has reserved a spill slot in the stack frame of the given function for the spec...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID&#39;s allocated.
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
const MachineFunctionProperties & getProperties() const
Get the function properties.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
virtual void adjustForHiPEPrologue(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Adjust the prologue to add Erlang Run-Time System (ERTS) specific code in the assembly prologue to ex...
static void insertCSRSaves(MachineBasicBlock &SaveBlock, ArrayRef< CalleeSavedInfo > CSI)
Insert restore code for the callee-saved registers used in the function.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const
canSimplifyCallFramePseudos - When possible, it&#39;s best to simplify the call frame pseudo ops before d...
int64_t getLocalFrameSize() const
Get the size of the local object blob.
unsigned Reg
bool test(unsigned Idx) const
Definition: BitVector.h:501
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
virtual MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
F(f)
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
MachineModuleInfo & getMMI() const
unsigned getCallFrameDestroyOpcode() const
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
virtual int getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI, unsigned &FrameReg, bool IgnoreSPUpdates) const
Same as getFrameIndexReference, except that the stack pointer (as opposed to the frame pointer) will ...
iterator end()
Get an iterator to the end of the SetVector.
Definition: SetVector.h:92
unsigned getSpillSize(const TargetRegisterClass &RC) const
Return the size in bytes of the stack slot allocated to hold a spilled copy of a register from class ...
iterator_range< succ_iterator > successors()
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool isVariableSizedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a variable sized object.
static DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
unsigned getSpillAlignment(const TargetRegisterClass &RC) const
Return the minimum required alignment in bytes for a spill slot for a register of this class...
virtual const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
Definition: BitVector.h:366
std::pair< int, int64_t > getLocalFrameObjectMap(int i) const
Get the local offset mapping for a for an object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
virtual bool usesPhysRegsForPEI() const
True if the target uses physical regs at Prolog/Epilog insertion time.
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:429
MachineBasicBlock * getRestorePoint() const
int find_first() const
find_first - Returns the index of the first set bit, -1 if none of the bits are set.
Definition: BitVector.h:331
virtual bool hasFP(const MachineFunction &MF) const =0
hasFP - Return true if the specified function should have a dedicated frame pointer register...
virtual bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
The address of this allocation is exposed and triggered protection.
virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const
Returns true if the target requires post PEI scavenging of registers for materializing frame index co...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
static cl::opt< unsigned > WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned) -1), cl::desc("Warn for stack size bigger than the given" " number"))
int find_next(unsigned Prev) const
find_next - Returns the index of the next set bit following the "Prev" bit.
Definition: BitVector.h:339
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1196
This file contains the simple types necessary to represent the attributes associated with functions a...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:426
MachineFunctionPass * createPrologEpilogInserterPass()
virtual unsigned getStackAlignmentSkew(const MachineFunction &MF) const
Return the skew that has to be applied to stack alignment under certain conditions (e...
void scavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger &RS)
Replaces all frame index virtual registers with physical registers.
Diagnostic information for optimization analysis remarks.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:265
bool getUseLocalStackAllocationBlock() const
Get whether the local allocation blob should be allocated together or let PEI allocate the locals in ...
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:141
virtual bool targetHandlesStackFrameRounding() const
targetHandlesStackFrameRounding - Returns true if the target is responsible for rounding up the stack...
virtual bool needsFrameIndexResolution(const MachineFunction &MF) const
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition: SetVector.h:82
int getObjectIndexBegin() const
Return the minimum frame object index.
bool isObjectPreAllocated(int ObjectIdx) const
Return true if the object was pre-allocated into the local block.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
int getObjectIndexEnd() const
Return one past the maximum frame object index.
SSPLayoutKind getObjectSSPLayout(int ObjectIdx) const
virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI, int SPAdj, unsigned FIOperandNum, RegScavenger *RS=nullptr) const =0
This method must be overriden to eliminate abstract frame indices from instructions which may use the...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
virtual const TargetInstrInfo * getInstrInfo() const
static void stashEntryDbgValues(MachineBasicBlock &MBB, SavedDbgValuesMap &EntryDbgValues)
Stash DBG_VALUEs that describe parameters and which are placed at the start of the block...
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:86
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
unsigned getKillRegState(bool B)
virtual void adjustForSegmentedStacks(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Adjust the prologue to have the function use segmented stacks.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition: MCRegister.h:19
TargetInstrInfo - Interface to description of machine instruction set.
Array or nested array >= SSP-buffer-size.
virtual void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
unsigned getObjectAlignment(int ObjectIdx) const
Return the alignment of the specified stack object.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
This file declares the machine register scavenger class.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
unsigned const MachineRegisterInfo * MRI
void initializePEIPass(PassRegistry &)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1525
df_ext_iterator< T, SetTy > df_ext_end(const T &G, SetTy &S)
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void setStackSize(uint64_t Size)
Set the size of the stack.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
int getStackProtectorIndex() const
Return the index for the stack protector object.
unsigned getCallFrameSetupOpcode() const
These methods return the opcode of the frame setup/destroy instructions if they exist (-1 otherwise)...
bool isImplicit() const
Return whether this is an implicit location description.
Represent the analysis usage information of a pass.
df_ext_iterator< T, SetTy > df_ext_begin(const T &G, SetTy &S)
BitVector & reset()
Definition: BitVector.h:438
unsigned getMaxAlignment() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
constexpr double e
Definition: MathExtras.h:57
void setImm(int64_t immVal)
static DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
static bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx, bool StackGrowsDown, unsigned MaxAlign, BitVector &StackBytesFree)
Assign frame object to an unused portion of the stack in the fixed stack object range.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
static void assignCalleeSavedSpillSlots(MachineFunction &F, const BitVector &SavedRegs, unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex)
INITIALIZE_PASS_BEGIN(PEI, DEBUG_TYPE, "Prologue/Epilogue Insertion", false, false) INITIALIZE_PASS_END(PEI
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:223
Used in the streaming interface as the general argument type.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
const MachineBasicBlock & front() const
typename vector_type::const_iterator const_iterator
Definition: SetVector.h:49
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
virtual bool hasReservedCallFrame(const MachineFunction &MF) const
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required, we reserve argument space for call sites in the function immediately on entry to the current function.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:40
const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, std::vector< CalleeSavedInfo > &CSI, const TargetRegisterInfo *TRI) const
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
bool isComplex() const
Return whether the location is computed on the expression stack, meaning it cannot be a simple regist...
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:297
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
unsigned getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call...
The optimization diagnostic interface.
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:212
virtual void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
bool isDebugValue() const
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Prologue Epilogue Insertion &Frame Finalization
bool isFrameInstr(const MachineInstr &I) const
Returns true if the argument is a frame pseudo instruction.
Information about stack frame layout on the target.
int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool IsImmutable=false)
Create a spill slot at a fixed location on the stack.
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling...
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, std::vector< CalleeSavedInfo > &CSI)
Insert restore code for the callee-saved registers used in the function.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
int64_t getFrameSize(const MachineInstr &I) const
Returns size of the frame associated with the given frame instruction.
int64_t getImm() const
void setMetadata(const MDNode *MD)
DWARF expression.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
unsigned getTransientStackAlignment() const
getTransientStackAlignment - This method returns the number of bytes to which the stack pointer must ...
virtual bool useFPForScavengingIndex(const MachineFunction &MF) const
Returns true if the target wants to use frame pointer based accesses to spill to the scavenger emerge...
virtual void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const
Store the specified register of the given register class to the specified stack frame index...
char & PrologEpilogCodeInserterID
PrologEpilogCodeInserter - This pass inserts prolog and epilog code, and eliminates abstract frame re...
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
bool none() const
none - Returns true if none of the bits are set.
Definition: BitVector.h:201
#define DEBUG_TYPE
virtual bool isFPCloseToIncomingSP() const
isFPCloseToIncomingSP - Return true if the frame pointer is close to the incoming stack pointer...
Representation of each machine instruction.
Definition: MachineInstr.h:63
virtual bool enableStackSlotScavenging(const MachineFunction &MF) const
Returns true if the stack slot holes in the fixed and callee-save stack area should be used when allo...
void setCalleeSavedInfo(const std::vector< CalleeSavedInfo > &CSI)
Used by prolog/epilog inserter to set the function&#39;s callee saved information.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:163
virtual bool requiresFrameIndexReplacementScavenging(const MachineFunction &MF) const
Returns true if the target requires using the RegScavenger directly for frame elimination despite usi...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
TargetOptions Options
void push_back(MachineInstr *MI)
#define I(x, y, z)
Definition: MD5.cpp:58
void setMaxCallFrameSize(unsigned S)
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:72
void ChangeToRegister(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isDebug=false)
ChangeToRegister - Replace this operand with a new register operand of the specified value...
virtual const TargetFrameLowering * getFrameLowering() const
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const std::vector< CalleeSavedInfo > &CSI, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
size_type size() const
size - Returns the number of bits in this bitvector.
Definition: BitVector.h:169
uint32_t Size
Definition: Profile.cpp:46
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:145
const TargetRegisterClass * getMinimalPhysRegClass(unsigned Reg, MVT VT=MVT::Other) const
Returns the Register Class of a physical register of the given type, picking the most sub register cl...
virtual void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Replace a StackProbe stub (if any) with the actual probe code inline.
uint8_t getStackID(int ObjectIdx) const
Align getLocalFrameMaxAlign() const
Return the required alignment of the local object blob.
MachineBasicBlock * getSavePoint() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasProperty(Property P) const
int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it...
bool needsStackRealignment(const MachineFunction &MF) const
True if storage within the function requires the stack pointer to be aligned more than the normal cal...
Array or nested array < SSP-buffer-size.
const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
virtual void orderFrameObjects(const MachineFunction &MF, SmallVectorImpl< int > &objectsToAllocate) const
Order the symbols in the local stack frame.
bool isMaxCallFrameSizeComputed() const
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
IRTranslator LLVM IR MI
void setIsDebug(bool Val=true)
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:431
int64_t getLocalFrameObjectCount() const
Return the number of objects allocated into the local object block.
bool isIndirectDebugValue() const
A DBG_VALUE is indirect iff the first operand is a register and the second operand is an immediate...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects...
static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs, SmallSet< int, 16 > &ProtectedObjs, MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset, unsigned &MaxAlign, unsigned Skew)
AssignProtectedObjSet - Helper function to assign large stack objects (i.e., those required to be clo...
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
virtual void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const
Load the specified register of the given register class from the specified stack frame index...
bool hasCalls() const
Return true if the current function has any function calls.
void resize(size_type N)
Definition: SmallVector.h:344