LLVM  5.0.0
PrologEpilogInserter.cpp
Go to the documentation of this file.
1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
12 // function.
13 //
14 // This pass must be run after register allocation. After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
29 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/Support/Debug.h"
44 #include <climits>
45 
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "prologepilog"
49 
52  unsigned &MinCSFrameIndex,
53  unsigned &MaxCXFrameIndex,
54  const MBBVector &SaveBlocks,
55  const MBBVector &RestoreBlocks);
56 
57 namespace {
58 class PEI : public MachineFunctionPass {
59 public:
60  static char ID;
61  PEI() : MachineFunctionPass(ID) {
63  }
64 
65  void getAnalysisUsage(AnalysisUsage &AU) const override;
66 
67  MachineFunctionProperties getRequiredProperties() const override {
69  if (UsesCalleeSaves)
71  return MFP;
72  }
73 
74  /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
75  /// frame indexes with appropriate references.
76  ///
77  bool runOnMachineFunction(MachineFunction &Fn) override;
78 
79 private:
81  unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex,
82  const MBBVector &SaveBlocks,
83  const MBBVector &RestoreBlocks)>
84  SpillCalleeSavedRegisters;
85  std::function<void(MachineFunction &MF, RegScavenger &RS)>
86  ScavengeFrameVirtualRegs;
87 
88  bool UsesCalleeSaves = false;
89 
90  RegScavenger *RS;
91 
92  // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
93  // stack frame indexes.
94  unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max();
95  unsigned MaxCSFrameIndex = 0;
96 
97  // Save and Restore blocks of the current function. Typically there is a
98  // single save block, unless Windows EH funclets are involved.
99  MBBVector SaveBlocks;
100  MBBVector RestoreBlocks;
101 
102  // Flag to control whether to use the register scavenger to resolve
103  // frame index materialization registers. Set according to
104  // TRI->requiresFrameIndexScavenging() for the current function.
105  bool FrameIndexVirtualScavenging;
106 
107  // Flag to control whether the scavenger should be passed even though
108  // FrameIndexVirtualScavenging is used.
109  bool FrameIndexEliminationScavenging;
110 
111  void calculateCallFrameInfo(MachineFunction &Fn);
112  void calculateSaveRestoreBlocks(MachineFunction &Fn);
113 
114  void calculateFrameObjectOffsets(MachineFunction &Fn);
115  void replaceFrameIndices(MachineFunction &Fn);
116  void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
117  int &SPAdj);
118  void insertPrologEpilogCode(MachineFunction &Fn);
119 };
120 } // namespace
121 
122 char PEI::ID = 0;
124 
125 static cl::opt<unsigned>
126 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
127  cl::desc("Warn for stack size bigger than the given"
128  " number"));
129 
130 INITIALIZE_PASS_BEGIN(PEI, DEBUG_TYPE, "Prologue/Epilogue Insertion", false,
131  false)
136  "Prologue/Epilogue Insertion & Frame Finalization", false,
137  false)
138 
140  return new PEI();
141 }
142 
143 STATISTIC(NumBytesStackSpace,
144  "Number of bytes used for stack in all functions");
145 
146 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
147  AU.setPreservesCFG();
152 }
153 
154 
155 /// StackObjSet - A set of stack object indexes
157 
158 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
159 /// frame indexes with appropriate references.
160 ///
161 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
162  if (!SpillCalleeSavedRegisters) {
163  const TargetMachine &TM = Fn.getTarget();
164  if (!TM.usesPhysRegsForPEI()) {
165  SpillCalleeSavedRegisters = [](MachineFunction &, RegScavenger *,
166  unsigned &, unsigned &, const MBBVector &,
167  const MBBVector &) {};
168  ScavengeFrameVirtualRegs = [](MachineFunction &, RegScavenger &) {};
169  } else {
170  SpillCalleeSavedRegisters = doSpillCalleeSavedRegs;
171  ScavengeFrameVirtualRegs = scavengeFrameVirtualRegs;
172  UsesCalleeSaves = true;
173  }
174  }
175 
176  const Function* F = Fn.getFunction();
177  const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
179 
180  RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
181  FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
182  FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) ||
184 
185  // Calculate the MaxCallFrameSize and AdjustsStack variables for the
186  // function's frame information. Also eliminates call frame pseudo
187  // instructions.
188  calculateCallFrameInfo(Fn);
189 
190  // Determine placement of CSR spill/restore code and prolog/epilog code:
191  // place all spills in the entry block, all restores in return blocks.
192  calculateSaveRestoreBlocks(Fn);
193 
194  // Handle CSR spilling and restoring, for targets that need it.
195  SpillCalleeSavedRegisters(Fn, RS, MinCSFrameIndex, MaxCSFrameIndex,
196  SaveBlocks, RestoreBlocks);
197 
198  // Allow the target machine to make final modifications to the function
199  // before the frame layout is finalized.
201 
202  // Calculate actual frame offsets for all abstract stack objects...
203  calculateFrameObjectOffsets(Fn);
204 
205  // Add prolog and epilog code to the function. This function is required
206  // to align the stack frame as necessary for any stack variables or
207  // called functions. Because of this, calculateCalleeSavedRegisters()
208  // must be called before this function in order to set the AdjustsStack
209  // and MaxCallFrameSize variables.
210  if (!F->hasFnAttribute(Attribute::Naked))
211  insertPrologEpilogCode(Fn);
212 
213  // Replace all MO_FrameIndex operands with physical register references
214  // and actual offsets.
215  //
216  replaceFrameIndices(Fn);
217 
218  // If register scavenging is needed, as we've enabled doing it as a
219  // post-pass, scavenge the virtual registers that frame index elimination
220  // inserted.
221  if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) {
222  ScavengeFrameVirtualRegs(Fn, *RS);
223 
224  // Clear any vregs created by virtual scavenging.
225  Fn.getRegInfo().clearVirtRegs();
226  }
227 
228  // Warn on stack size when we exceeds the given limit.
229  MachineFrameInfo &MFI = Fn.getFrameInfo();
230  uint64_t StackSize = MFI.getStackSize();
231  if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
232  DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
233  F->getContext().diagnose(DiagStackSize);
234  }
235 
236  delete RS;
237  SaveBlocks.clear();
238  RestoreBlocks.clear();
239  MFI.setSavePoint(nullptr);
240  MFI.setRestorePoint(nullptr);
241  return true;
242 }
243 
244 /// Calculate the MaxCallFrameSize and AdjustsStack
245 /// variables for the function's frame information and eliminate call frame
246 /// pseudo instructions.
247 void PEI::calculateCallFrameInfo(MachineFunction &Fn) {
248  const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
250  MachineFrameInfo &MFI = Fn.getFrameInfo();
251 
252  unsigned MaxCallFrameSize = 0;
253  bool AdjustsStack = MFI.adjustsStack();
254 
255  // Get the function call frame set-up and tear-down instruction opcode
256  unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
257  unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
258 
259  // Early exit for targets which have no call frame setup/destroy pseudo
260  // instructions.
261  if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
262  return;
263 
264  std::vector<MachineBasicBlock::iterator> FrameSDOps;
265  for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
266  for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
267  if (TII.isFrameInstr(*I)) {
268  unsigned Size = TII.getFrameSize(*I);
269  if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
270  AdjustsStack = true;
271  FrameSDOps.push_back(I);
272  } else if (I->isInlineAsm()) {
273  // Some inline asm's need a stack frame, as indicated by operand 1.
274  unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
275  if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
276  AdjustsStack = true;
277  }
278 
280  (MFI.getMaxCallFrameSize() == MaxCallFrameSize &&
281  MFI.adjustsStack() == AdjustsStack));
282  MFI.setAdjustsStack(AdjustsStack);
283  MFI.setMaxCallFrameSize(MaxCallFrameSize);
284 
285  for (std::vector<MachineBasicBlock::iterator>::iterator
286  i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
288 
289  // If call frames are not being included as part of the stack frame, and
290  // the target doesn't indicate otherwise, remove the call frame pseudos
291  // here. The sub/add sp instruction pairs are still inserted, but we don't
292  // need to track the SP adjustment for frame index elimination.
293  if (TFI->canSimplifyCallFramePseudos(Fn))
294  TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
295  }
296 }
297 
298 /// Compute the sets of entry and return blocks for saving and restoring
299 /// callee-saved registers, and placing prolog and epilog code.
300 void PEI::calculateSaveRestoreBlocks(MachineFunction &Fn) {
301  const MachineFrameInfo &MFI = Fn.getFrameInfo();
302 
303  // Even when we do not change any CSR, we still want to insert the
304  // prologue and epilogue of the function.
305  // So set the save points for those.
306 
307  // Use the points found by shrink-wrapping, if any.
308  if (MFI.getSavePoint()) {
309  SaveBlocks.push_back(MFI.getSavePoint());
310  assert(MFI.getRestorePoint() && "Both restore and save must be set");
311  MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
312  // If RestoreBlock does not have any successor and is not a return block
313  // then the end point is unreachable and we do not need to insert any
314  // epilogue.
315  if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
316  RestoreBlocks.push_back(RestoreBlock);
317  return;
318  }
319 
320  // Save refs to entry and return blocks.
321  SaveBlocks.push_back(&Fn.front());
322  for (MachineBasicBlock &MBB : Fn) {
323  if (MBB.isEHFuncletEntry())
324  SaveBlocks.push_back(&MBB);
325  if (MBB.isReturnBlock())
326  RestoreBlocks.push_back(&MBB);
327  }
328 }
329 
331  const BitVector &SavedRegs,
332  unsigned &MinCSFrameIndex,
333  unsigned &MaxCSFrameIndex) {
334  if (SavedRegs.empty())
335  return;
336 
337  const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
338  const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
339 
340  std::vector<CalleeSavedInfo> CSI;
341  for (unsigned i = 0; CSRegs[i]; ++i) {
342  unsigned Reg = CSRegs[i];
343  if (SavedRegs.test(Reg))
344  CSI.push_back(CalleeSavedInfo(Reg));
345  }
346 
348  MachineFrameInfo &MFI = F.getFrameInfo();
349  if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
350  // If target doesn't implement this, use generic code.
351 
352  if (CSI.empty())
353  return; // Early exit if no callee saved registers are modified!
354 
355  unsigned NumFixedSpillSlots;
356  const TargetFrameLowering::SpillSlot *FixedSpillSlots =
357  TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
358 
359  // Now that we know which registers need to be saved and restored, allocate
360  // stack slots for them.
361  for (auto &CS : CSI) {
362  unsigned Reg = CS.getReg();
363  const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
364 
365  int FrameIdx;
366  if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
367  CS.setFrameIdx(FrameIdx);
368  continue;
369  }
370 
371  // Check to see if this physreg must be spilled to a particular stack slot
372  // on this target.
373  const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
374  while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
375  FixedSlot->Reg != Reg)
376  ++FixedSlot;
377 
378  unsigned Size = RegInfo->getSpillSize(*RC);
379  if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
380  // Nope, just spill it anywhere convenient.
381  unsigned Align = RegInfo->getSpillAlignment(*RC);
382  unsigned StackAlign = TFI->getStackAlignment();
383 
384  // We may not be able to satisfy the desired alignment specification of
385  // the TargetRegisterClass if the stack alignment is smaller. Use the
386  // min.
387  Align = std::min(Align, StackAlign);
388  FrameIdx = MFI.CreateStackObject(Size, Align, true);
389  if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
390  if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
391  } else {
392  // Spill it to the stack where we must.
393  FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
394  }
395 
396  CS.setFrameIdx(FrameIdx);
397  }
398  }
399 
400  MFI.setCalleeSavedInfo(CSI);
401 }
402 
403 /// Helper function to update the liveness information for the callee-saved
404 /// registers.
405 static void updateLiveness(MachineFunction &MF) {
406  MachineFrameInfo &MFI = MF.getFrameInfo();
407  // Visited will contain all the basic blocks that are in the region
408  // where the callee saved registers are alive:
409  // - Anything that is not Save or Restore -> LiveThrough.
410  // - Save -> LiveIn.
411  // - Restore -> LiveOut.
412  // The live-out is not attached to the block, so no need to keep
413  // Restore in this set.
416  MachineBasicBlock *Entry = &MF.front();
417  MachineBasicBlock *Save = MFI.getSavePoint();
418 
419  if (!Save)
420  Save = Entry;
421 
422  if (Entry != Save) {
423  WorkList.push_back(Entry);
424  Visited.insert(Entry);
425  }
426  Visited.insert(Save);
427 
428  MachineBasicBlock *Restore = MFI.getRestorePoint();
429  if (Restore)
430  // By construction Restore cannot be visited, otherwise it
431  // means there exists a path to Restore that does not go
432  // through Save.
433  WorkList.push_back(Restore);
434 
435  while (!WorkList.empty()) {
436  const MachineBasicBlock *CurBB = WorkList.pop_back_val();
437  // By construction, the region that is after the save point is
438  // dominated by the Save and post-dominated by the Restore.
439  if (CurBB == Save && Save != Restore)
440  continue;
441  // Enqueue all the successors not already visited.
442  // Those are by construction either before Save or after Restore.
443  for (MachineBasicBlock *SuccBB : CurBB->successors())
444  if (Visited.insert(SuccBB).second)
445  WorkList.push_back(SuccBB);
446  }
447 
448  const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
449 
451  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
452  for (MachineBasicBlock *MBB : Visited) {
453  MCPhysReg Reg = CSI[i].getReg();
454  // Add the callee-saved register as live-in.
455  // It's killed at the spill.
456  if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg))
457  MBB->addLiveIn(Reg);
458  }
459  }
460 }
461 
462 /// insertCSRSpillsAndRestores - Insert spill and restore code for
463 /// callee saved registers used in the function.
464 ///
466  const MBBVector &SaveBlocks,
467  const MBBVector &RestoreBlocks) {
468  // Get callee saved register information.
469  MachineFrameInfo &MFI = Fn.getFrameInfo();
470  const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
471 
472  MFI.setCalleeSavedInfoValid(true);
473 
474  // Early exit if no callee saved registers are modified!
475  if (CSI.empty())
476  return;
477 
478  const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
480  const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
482 
483  // Spill using target interface.
484  for (MachineBasicBlock *SaveBlock : SaveBlocks) {
485  I = SaveBlock->begin();
486  if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
487  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
488  // Insert the spill to the stack frame.
489  unsigned Reg = CSI[i].getReg();
490  const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
491  TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
492  RC, TRI);
493  }
494  }
495  // Update the live-in information of all the blocks up to the save point.
496  updateLiveness(Fn);
497  }
498 
499  // Restore using target interface.
500  for (MachineBasicBlock *MBB : RestoreBlocks) {
501  I = MBB->end();
502 
503  // Skip over all terminator instructions, which are part of the return
504  // sequence.
506  while (I2 != MBB->begin() && (--I2)->isTerminator())
507  I = I2;
508 
509  bool AtStart = I == MBB->begin();
510  MachineBasicBlock::iterator BeforeI = I;
511  if (!AtStart)
512  --BeforeI;
513 
514  // Restore all registers immediately before the return and any
515  // terminators that precede it.
516  if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
517  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
518  unsigned Reg = CSI[i].getReg();
519  const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
520  TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
521  assert(I != MBB->begin() &&
522  "loadRegFromStackSlot didn't insert any code!");
523  // Insert in reverse order. loadRegFromStackSlot can insert
524  // multiple instructions.
525  if (AtStart)
526  I = MBB->begin();
527  else {
528  I = BeforeI;
529  ++I;
530  }
531  }
532  }
533  }
534 }
535 
537  unsigned &MinCSFrameIndex,
538  unsigned &MaxCSFrameIndex,
539  const MBBVector &SaveBlocks,
540  const MBBVector &RestoreBlocks) {
541  const Function *F = Fn.getFunction();
543  MinCSFrameIndex = std::numeric_limits<unsigned>::max();
544  MaxCSFrameIndex = 0;
545 
546  // Determine which of the registers in the callee save list should be saved.
547  BitVector SavedRegs;
548  TFI->determineCalleeSaves(Fn, SavedRegs, RS);
549 
550  // Assign stack slots for any callee-saved registers that must be spilled.
551  assignCalleeSavedSpillSlots(Fn, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex);
552 
553  // Add the code to save and restore the callee saved registers.
554  if (!F->hasFnAttribute(Attribute::Naked))
555  insertCSRSpillsAndRestores(Fn, SaveBlocks, RestoreBlocks);
556 }
557 
558 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
559 static inline void
561  bool StackGrowsDown, int64_t &Offset,
562  unsigned &MaxAlign, unsigned Skew) {
563  // If the stack grows down, add the object size to find the lowest address.
564  if (StackGrowsDown)
565  Offset += MFI.getObjectSize(FrameIdx);
566 
567  unsigned Align = MFI.getObjectAlignment(FrameIdx);
568 
569  // If the alignment of this object is greater than that of the stack, then
570  // increase the stack alignment to match.
571  MaxAlign = std::max(MaxAlign, Align);
572 
573  // Adjust to alignment boundary.
574  Offset = alignTo(Offset, Align, Skew);
575 
576  if (StackGrowsDown) {
577  DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
578  MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
579  } else {
580  DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
581  MFI.setObjectOffset(FrameIdx, Offset);
582  Offset += MFI.getObjectSize(FrameIdx);
583  }
584 }
585 
586 /// Compute which bytes of fixed and callee-save stack area are unused and keep
587 /// track of them in StackBytesFree.
588 ///
589 static inline void
590 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
591  unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
592  int64_t FixedCSEnd, BitVector &StackBytesFree) {
593  // Avoid undefined int64_t -> int conversion below in extreme case.
594  if (FixedCSEnd > std::numeric_limits<int>::max())
595  return;
596 
597  StackBytesFree.resize(FixedCSEnd, true);
598 
599  SmallVector<int, 16> AllocatedFrameSlots;
600  // Add fixed objects.
601  for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
602  AllocatedFrameSlots.push_back(i);
603  // Add callee-save objects.
604  for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
605  AllocatedFrameSlots.push_back(i);
606 
607  for (int i : AllocatedFrameSlots) {
608  // These are converted from int64_t, but they should always fit in int
609  // because of the FixedCSEnd check above.
610  int ObjOffset = MFI.getObjectOffset(i);
611  int ObjSize = MFI.getObjectSize(i);
612  int ObjStart, ObjEnd;
613  if (StackGrowsDown) {
614  // ObjOffset is negative when StackGrowsDown is true.
615  ObjStart = -ObjOffset - ObjSize;
616  ObjEnd = -ObjOffset;
617  } else {
618  ObjStart = ObjOffset;
619  ObjEnd = ObjOffset + ObjSize;
620  }
621  // Ignore fixed holes that are in the previous stack frame.
622  if (ObjEnd > 0)
623  StackBytesFree.reset(ObjStart, ObjEnd);
624  }
625 }
626 
627 /// Assign frame object to an unused portion of the stack in the fixed stack
628 /// object range. Return true if the allocation was successful.
629 ///
630 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
631  bool StackGrowsDown, unsigned MaxAlign,
632  BitVector &StackBytesFree) {
633  if (MFI.isVariableSizedObjectIndex(FrameIdx))
634  return false;
635 
636  if (StackBytesFree.none()) {
637  // clear it to speed up later scavengeStackSlot calls to
638  // StackBytesFree.none()
639  StackBytesFree.clear();
640  return false;
641  }
642 
643  unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx);
644  if (ObjAlign > MaxAlign)
645  return false;
646 
647  int64_t ObjSize = MFI.getObjectSize(FrameIdx);
648  int FreeStart;
649  for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
650  FreeStart = StackBytesFree.find_next(FreeStart)) {
651 
652  // Check that free space has suitable alignment.
653  unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
654  if (alignTo(ObjStart, ObjAlign) != ObjStart)
655  continue;
656 
657  if (FreeStart + ObjSize > StackBytesFree.size())
658  return false;
659 
660  bool AllBytesFree = true;
661  for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
662  if (!StackBytesFree.test(FreeStart + Byte)) {
663  AllBytesFree = false;
664  break;
665  }
666  if (AllBytesFree)
667  break;
668  }
669 
670  if (FreeStart == -1)
671  return false;
672 
673  if (StackGrowsDown) {
674  int ObjStart = -(FreeStart + ObjSize);
675  DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << ObjStart
676  << "]\n");
677  MFI.setObjectOffset(FrameIdx, ObjStart);
678  } else {
679  DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << FreeStart
680  << "]\n");
681  MFI.setObjectOffset(FrameIdx, FreeStart);
682  }
683 
684  StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
685  return true;
686 }
687 
688 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
689 /// those required to be close to the Stack Protector) to stack offsets.
690 static void
691 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
692  SmallSet<int, 16> &ProtectedObjs,
693  MachineFrameInfo &MFI, bool StackGrowsDown,
694  int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
695 
696  for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
697  E = UnassignedObjs.end(); I != E; ++I) {
698  int i = *I;
699  AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
700  ProtectedObjs.insert(i);
701  }
702 }
703 
704 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
705 /// abstract stack objects.
706 ///
707 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
709  StackProtector *SP = &getAnalysis<StackProtector>();
710 
711  bool StackGrowsDown =
713 
714  // Loop over all of the stack objects, assigning sequential addresses...
715  MachineFrameInfo &MFI = Fn.getFrameInfo();
716 
717  // Start at the beginning of the local area.
718  // The Offset is the distance from the stack top in the direction
719  // of stack growth -- so it's always nonnegative.
720  int LocalAreaOffset = TFI.getOffsetOfLocalArea();
721  if (StackGrowsDown)
722  LocalAreaOffset = -LocalAreaOffset;
723  assert(LocalAreaOffset >= 0
724  && "Local area offset should be in direction of stack growth");
725  int64_t Offset = LocalAreaOffset;
726 
727  // Skew to be applied to alignment.
728  unsigned Skew = TFI.getStackAlignmentSkew(Fn);
729 
730  // If there are fixed sized objects that are preallocated in the local area,
731  // non-fixed objects can't be allocated right at the start of local area.
732  // Adjust 'Offset' to point to the end of last fixed sized preallocated
733  // object.
734  for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
735  int64_t FixedOff;
736  if (StackGrowsDown) {
737  // The maximum distance from the stack pointer is at lower address of
738  // the object -- which is given by offset. For down growing stack
739  // the offset is negative, so we negate the offset to get the distance.
740  FixedOff = -MFI.getObjectOffset(i);
741  } else {
742  // The maximum distance from the start pointer is at the upper
743  // address of the object.
744  FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
745  }
746  if (FixedOff > Offset) Offset = FixedOff;
747  }
748 
749  // First assign frame offsets to stack objects that are used to spill
750  // callee saved registers.
751  if (StackGrowsDown) {
752  for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
753  // If the stack grows down, we need to add the size to find the lowest
754  // address of the object.
755  Offset += MFI.getObjectSize(i);
756 
757  unsigned Align = MFI.getObjectAlignment(i);
758  // Adjust to alignment boundary
759  Offset = alignTo(Offset, Align, Skew);
760 
761  DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
762  MFI.setObjectOffset(i, -Offset); // Set the computed offset
763  }
764  } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
765  // Be careful about underflow in comparisons agains MinCSFrameIndex.
766  for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
767  if (MFI.isDeadObjectIndex(i))
768  continue;
769 
770  unsigned Align = MFI.getObjectAlignment(i);
771  // Adjust to alignment boundary
772  Offset = alignTo(Offset, Align, Skew);
773 
774  DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
775  MFI.setObjectOffset(i, Offset);
776  Offset += MFI.getObjectSize(i);
777  }
778  }
779 
780  // FixedCSEnd is the stack offset to the end of the fixed and callee-save
781  // stack area.
782  int64_t FixedCSEnd = Offset;
783  unsigned MaxAlign = MFI.getMaxAlignment();
784 
785  // Make sure the special register scavenging spill slot is closest to the
786  // incoming stack pointer if a frame pointer is required and is closer
787  // to the incoming rather than the final stack pointer.
788  const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
789  bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
790  TFI.isFPCloseToIncomingSP() &&
791  RegInfo->useFPForScavengingIndex(Fn) &&
792  !RegInfo->needsStackRealignment(Fn));
793  if (RS && EarlyScavengingSlots) {
794  SmallVector<int, 2> SFIs;
795  RS->getScavengingFrameIndices(SFIs);
796  for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
797  IE = SFIs.end(); I != IE; ++I)
798  AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
799  }
800 
801  // FIXME: Once this is working, then enable flag will change to a target
802  // check for whether the frame is large enough to want to use virtual
803  // frame index registers. Functions which don't want/need this optimization
804  // will continue to use the existing code path.
806  unsigned Align = MFI.getLocalFrameMaxAlign();
807 
808  // Adjust to alignment boundary.
809  Offset = alignTo(Offset, Align, Skew);
810 
811  DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
812 
813  // Resolve offsets for objects in the local block.
814  for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
815  std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
816  int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
817  DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
818  FIOffset << "]\n");
819  MFI.setObjectOffset(Entry.first, FIOffset);
820  }
821  // Allocate the local block
822  Offset += MFI.getLocalFrameSize();
823 
824  MaxAlign = std::max(Align, MaxAlign);
825  }
826 
827  // Retrieve the Exception Handler registration node.
828  int EHRegNodeFrameIndex = INT_MAX;
829  if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo())
830  EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
831 
832  // Make sure that the stack protector comes before the local variables on the
833  // stack.
834  SmallSet<int, 16> ProtectedObjs;
835  if (MFI.getStackProtectorIndex() >= 0) {
836  StackObjSet LargeArrayObjs;
837  StackObjSet SmallArrayObjs;
838  StackObjSet AddrOfObjs;
839 
840  AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), StackGrowsDown,
841  Offset, MaxAlign, Skew);
842 
843  // Assign large stack objects first.
844  for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
845  if (MFI.isObjectPreAllocated(i) &&
847  continue;
848  if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
849  continue;
850  if (RS && RS->isScavengingFrameIndex((int)i))
851  continue;
852  if (MFI.isDeadObjectIndex(i))
853  continue;
854  if (MFI.getStackProtectorIndex() == (int)i ||
855  EHRegNodeFrameIndex == (int)i)
856  continue;
857 
858  switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) {
860  continue;
862  SmallArrayObjs.insert(i);
863  continue;
865  AddrOfObjs.insert(i);
866  continue;
868  LargeArrayObjs.insert(i);
869  continue;
870  }
871  llvm_unreachable("Unexpected SSPLayoutKind.");
872  }
873 
874  AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
875  Offset, MaxAlign, Skew);
876  AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
877  Offset, MaxAlign, Skew);
878  AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
879  Offset, MaxAlign, Skew);
880  }
881 
882  SmallVector<int, 8> ObjectsToAllocate;
883 
884  // Then prepare to assign frame offsets to stack objects that are not used to
885  // spill callee saved registers.
886  for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
888  continue;
889  if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
890  continue;
891  if (RS && RS->isScavengingFrameIndex((int)i))
892  continue;
893  if (MFI.isDeadObjectIndex(i))
894  continue;
895  if (MFI.getStackProtectorIndex() == (int)i ||
896  EHRegNodeFrameIndex == (int)i)
897  continue;
898  if (ProtectedObjs.count(i))
899  continue;
900 
901  // Add the objects that we need to allocate to our working set.
902  ObjectsToAllocate.push_back(i);
903  }
904 
905  // Allocate the EH registration node first if one is present.
906  if (EHRegNodeFrameIndex != INT_MAX)
907  AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
908  MaxAlign, Skew);
909 
910  // Give the targets a chance to order the objects the way they like it.
911  if (Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
913  TFI.orderFrameObjects(Fn, ObjectsToAllocate);
914 
915  // Keep track of which bytes in the fixed and callee-save range are used so we
916  // can use the holes when allocating later stack objects. Only do this if
917  // stack protector isn't being used and the target requests it and we're
918  // optimizing.
919  BitVector StackBytesFree;
920  if (!ObjectsToAllocate.empty() &&
923  computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex,
924  FixedCSEnd, StackBytesFree);
925 
926  // Now walk the objects and actually assign base offsets to them.
927  for (auto &Object : ObjectsToAllocate)
928  if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
929  StackBytesFree))
930  AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
931 
932  // Make sure the special register scavenging spill slot is closest to the
933  // stack pointer.
934  if (RS && !EarlyScavengingSlots) {
935  SmallVector<int, 2> SFIs;
936  RS->getScavengingFrameIndices(SFIs);
937  for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
938  IE = SFIs.end(); I != IE; ++I)
939  AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
940  }
941 
942  if (!TFI.targetHandlesStackFrameRounding()) {
943  // If we have reserved argument space for call sites in the function
944  // immediately on entry to the current function, count it as part of the
945  // overall stack size.
946  if (MFI.adjustsStack() && TFI.hasReservedCallFrame(Fn))
947  Offset += MFI.getMaxCallFrameSize();
948 
949  // Round up the size to a multiple of the alignment. If the function has
950  // any calls or alloca's, align to the target's StackAlignment value to
951  // ensure that the callee's frame or the alloca data is suitably aligned;
952  // otherwise, for leaf functions, align to the TransientStackAlignment
953  // value.
954  unsigned StackAlign;
955  if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
956  (RegInfo->needsStackRealignment(Fn) && MFI.getObjectIndexEnd() != 0))
957  StackAlign = TFI.getStackAlignment();
958  else
959  StackAlign = TFI.getTransientStackAlignment();
960 
961  // If the frame pointer is eliminated, all frame offsets will be relative to
962  // SP not FP. Align to MaxAlign so this works.
963  StackAlign = std::max(StackAlign, MaxAlign);
964  Offset = alignTo(Offset, StackAlign, Skew);
965  }
966 
967  // Update frame info to pretend that this is part of the stack...
968  int64_t StackSize = Offset - LocalAreaOffset;
969  MFI.setStackSize(StackSize);
970  NumBytesStackSpace += StackSize;
971 }
972 
973 /// insertPrologEpilogCode - Scan the function for modified callee saved
974 /// registers, insert spill code for these callee saved registers, then add
975 /// prolog and epilog code to the function.
976 ///
977 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
979 
980  // Add prologue to the function...
981  for (MachineBasicBlock *SaveBlock : SaveBlocks)
982  TFI.emitPrologue(Fn, *SaveBlock);
983 
984  // Add epilogue to restore the callee-save registers in each exiting block.
985  for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
986  TFI.emitEpilogue(Fn, *RestoreBlock);
987 
988  for (MachineBasicBlock *SaveBlock : SaveBlocks)
989  TFI.inlineStackProbe(Fn, *SaveBlock);
990 
991  // Emit additional code that is required to support segmented stacks, if
992  // we've been asked for it. This, when linked with a runtime with support
993  // for segmented stacks (libgcc is one), will result in allocating stack
994  // space in small chunks instead of one large contiguous block.
995  if (Fn.shouldSplitStack()) {
996  for (MachineBasicBlock *SaveBlock : SaveBlocks)
997  TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
998  }
999 
1000  // Emit additional code that is required to explicitly handle the stack in
1001  // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1002  // approach is rather similar to that of Segmented Stacks, but it uses a
1003  // different conditional check and another BIF for allocating more stack
1004  // space.
1006  for (MachineBasicBlock *SaveBlock : SaveBlocks)
1007  TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
1008 }
1009 
1010 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1011 /// register references and actual offsets.
1012 ///
1013 void PEI::replaceFrameIndices(MachineFunction &Fn) {
1014  const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
1015  if (!TFI.needsFrameIndexResolution(Fn)) return;
1016 
1017  // Store SPAdj at exit of a basic block.
1018  SmallVector<int, 8> SPState;
1019  SPState.resize(Fn.getNumBlockIDs());
1021 
1022  // Iterate over the reachable blocks in DFS order.
1023  for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
1024  DFI != DFE; ++DFI) {
1025  int SPAdj = 0;
1026  // Check the exit state of the DFS stack predecessor.
1027  if (DFI.getPathLength() >= 2) {
1028  MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1029  assert(Reachable.count(StackPred) &&
1030  "DFS stack predecessor is already visited.\n");
1031  SPAdj = SPState[StackPred->getNumber()];
1032  }
1033  MachineBasicBlock *BB = *DFI;
1034  replaceFrameIndices(BB, Fn, SPAdj);
1035  SPState[BB->getNumber()] = SPAdj;
1036  }
1037 
1038  // Handle the unreachable blocks.
1039  for (auto &BB : Fn) {
1040  if (Reachable.count(&BB))
1041  // Already handled in DFS traversal.
1042  continue;
1043  int SPAdj = 0;
1044  replaceFrameIndices(&BB, Fn, SPAdj);
1045  }
1046 }
1047 
1048 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
1049  int &SPAdj) {
1051  "getRegisterInfo() must be implemented!");
1052  const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
1053  const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
1055 
1056  if (RS && FrameIndexEliminationScavenging)
1057  RS->enterBasicBlock(*BB);
1058 
1059  bool InsideCallSequence = false;
1060 
1061  for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1062 
1063  if (TII.isFrameInstr(*I)) {
1064  InsideCallSequence = TII.isFrameSetup(*I);
1065  SPAdj += TII.getSPAdjust(*I);
1066  I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
1067  continue;
1068  }
1069 
1070  MachineInstr &MI = *I;
1071  bool DoIncr = true;
1072  bool DidFinishLoop = true;
1073  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1074  if (!MI.getOperand(i).isFI())
1075  continue;
1076 
1077  // Frame indices in debug values are encoded in a target independent
1078  // way with simply the frame index and offset rather than any
1079  // target-specific addressing mode.
1080  if (MI.isDebugValue()) {
1081  assert(i == 0 && "Frame indices can only appear as the first "
1082  "operand of a DBG_VALUE machine instruction");
1083  unsigned Reg;
1084  MachineOperand &Offset = MI.getOperand(1);
1085  Offset.setImm(
1086  Offset.getImm() +
1087  TFI->getFrameIndexReference(Fn, MI.getOperand(0).getIndex(), Reg));
1088  MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
1089  continue;
1090  }
1091 
1092  // TODO: This code should be commoned with the code for
1093  // PATCHPOINT. There's no good reason for the difference in
1094  // implementation other than historical accident. The only
1095  // remaining difference is the unconditional use of the stack
1096  // pointer as the base register.
1097  if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1098  assert((!MI.isDebugValue() || i == 0) &&
1099  "Frame indicies can only appear as the first operand of a "
1100  "DBG_VALUE machine instruction");
1101  unsigned Reg;
1102  MachineOperand &Offset = MI.getOperand(i + 1);
1103  int refOffset = TFI->getFrameIndexReferencePreferSP(
1104  Fn, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1105  Offset.setImm(Offset.getImm() + refOffset);
1106  MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
1107  continue;
1108  }
1109 
1110  // Some instructions (e.g. inline asm instructions) can have
1111  // multiple frame indices and/or cause eliminateFrameIndex
1112  // to insert more than one instruction. We need the register
1113  // scavenger to go through all of these instructions so that
1114  // it can update its register information. We keep the
1115  // iterator at the point before insertion so that we can
1116  // revisit them in full.
1117  bool AtBeginning = (I == BB->begin());
1118  if (!AtBeginning) --I;
1119 
1120  // If this instruction has a FrameIndex operand, we need to
1121  // use that target machine register info object to eliminate
1122  // it.
1123  TRI.eliminateFrameIndex(MI, SPAdj, i,
1124  FrameIndexEliminationScavenging ? RS : nullptr);
1125 
1126  // Reset the iterator if we were at the beginning of the BB.
1127  if (AtBeginning) {
1128  I = BB->begin();
1129  DoIncr = false;
1130  }
1131 
1132  DidFinishLoop = false;
1133  break;
1134  }
1135 
1136  // If we are looking at a call sequence, we need to keep track of
1137  // the SP adjustment made by each instruction in the sequence.
1138  // This includes both the frame setup/destroy pseudos (handled above),
1139  // as well as other instructions that have side effects w.r.t the SP.
1140  // Note that this must come after eliminateFrameIndex, because
1141  // if I itself referred to a frame index, we shouldn't count its own
1142  // adjustment.
1143  if (DidFinishLoop && InsideCallSequence)
1144  SPAdj += TII.getSPAdjust(MI);
1145 
1146  if (DoIncr && I != BB->end()) ++I;
1147 
1148  // Update register states.
1149  if (RS && FrameIndexEliminationScavenging && DidFinishLoop)
1150  RS->forward(MI);
1151  }
1152 }
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:372
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
virtual void orderFrameObjects(const MachineFunction &MF, SmallVectorImpl< int > &objectsToAllocate) const
Order the symbols in the local stack frame.
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...
void setSavePoint(MachineBasicBlock *NewSave)
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:332
void setRestorePoint(MachineBasicBlock *NewRestore)
bool isFrameInstr(const MachineInstr &I) const
Returns true if the argument is a frame pseudo instruction.
size_type size() const
size - Returns the number of bits in this bitvector.
Definition: BitVector.h:170
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...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
void setCalleeSavedInfoValid(bool v)
STATISTIC(NumFunctions,"Total number of functions")
bool none() const
none - Returns true if none of the bits are set.
Definition: BitVector.h:202
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...
void ChangeToRegister(unsigned 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...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
MachineBasicBlock * getRestorePoint() const
int find_next(unsigned Prev) const
find_next - Returns the index of the next set bit following the "Prev" bit.
Definition: BitVector.h:340
virtual bool usesPhysRegsForPEI() const
True if the target uses physical regs at Prolog/Epilog insertion time.
unsigned getSpillAlignment(const TargetRegisterClass &RC) const
Return the minimum required alignment for a spill slot for a register of this class.
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...
virtual unsigned getStackAlignmentSkew(const MachineFunction &MF) const
Return the skew that has to be applied to stack alignment under certain conditions (e...
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
SmallVector< MachineBasicBlock *, 4 > MBBVector
virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const
Returns true if the target requires post PEI scavenging of registers for materializing frame index co...
virtual const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
iterator end()
Get an iterator to the end of the SetVector.
Definition: SetVector.h:93
bool isObjectPreAllocated(int ObjectIdx) const
Return true if the object was pre-allocated into the local block.
void clearVirtRegs()
clearVirtRegs - Remove all virtual registers (after physreg assignment).
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:186
iterator_range< succ_iterator > successors()
unsigned getMaxAlignment() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
Prologue Epilogue Insertion &Frame false
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects...
virtual bool targetHandlesStackFrameRounding() const
targetHandlesStackFrameRounding - Returns true if the target is responsible for rounding up the stack...
int64_t getLocalFrameSize() const
Get the size of the local object blob.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
virtual void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Replace a StackProbe stub (if any) with the actual probe code inline.
unsigned getCallFrameDestroyOpcode() const
Did not trigger a stack protector.
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
Definition: BitVector.h:367
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
INITIALIZE_PASS_BEGIN(PEI, DEBUG_TYPE,"Prologue/Epilogue Insertion", false, false) INITIALIZE_PASS_END(PEI
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
virtual bool hasFP(const MachineFunction &MF) const =0
hasFP - Return true if the specified function should have a dedicated frame pointer register...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
Reg
All possible values of the reg field in the ModR/M byte.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
The address of this allocation is exposed and triggered protection.
MachineFunctionPass * createPrologEpilogInserterPass()
virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const std::vector< CalleeSavedInfo > &CSI, const TargetRegisterInfo *TRI) const
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool Immutable=false)
Create a spill slot at a fixed location on the stack.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:282
void scavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger &RS)
Replaces all frame index virtual registers with physical registers.
const MachineBasicBlock & front() const
bool isVariableSizedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a variable sized object.
#define F(x, y, z)
Definition: MD5.cpp:55
int getObjectIndexBegin() const
Return the minimum frame object index.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:142
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
unsigned getCallFrameSetupOpcode() const
These methods return the opcode of the frame setup/destroy instructions if they exist (-1 otherwise)...
virtual bool needsFrameIndexResolution(const MachineFunction &MF) const
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 ...
unsigned getLocalFrameMaxAlign() const
Return the required alignment of the local object blob.
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition: SetVector.h:83
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...
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...
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...
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
int64_t getImm() const
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"))
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...
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...
unsigned getTransientStackAlignment() const
getTransientStackAlignment - This method returns the number of bytes to which the stack pointer must ...
int64_t getLocalFrameObjectCount() const
Return the number of objects allocated into the local object block.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:279
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
virtual bool requiresRegisterScavenging(const MachineFunction &MF) const
Returns true if the target requires (and can make use of) the register scavenger. ...
TargetInstrInfo - Interface to description of machine instruction set.
std::pair< int, int64_t > getLocalFrameObjectMap(int i) const
Get the local offset mapping for a for an object.
bool isDebugValue() const
Definition: MachineInstr.h:785
virtual void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
This file declares the machine register scavenger class.
bool getUseLocalStackAllocationBlock() const
Get whether the local allocation blob should be allocated together or let PEI allocate the locals in ...
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
unsigned const MachineRegisterInfo * MRI
void initializePEIPass(PassRegistry &)
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...
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.
bool isReserved(unsigned PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
void setStackSize(uint64_t Size)
Set the size of the stack.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:36
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:284
bool empty() const
empty - Tests whether there are no bits in this bitvector.
Definition: BitVector.h:167
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
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:372
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...
SmallSetVector< int, 8 > StackObjSet
StackObjSet - A set of stack object indexes.
Represent the analysis usage information of a pass.
df_ext_iterator< T, SetTy > df_ext_begin(const T &G, SetTy &S)
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
BitVector & reset()
Definition: BitVector.h:439
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
void setImm(int64_t immVal)
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.
SSPLayoutKind getSSPLayout(const AllocaInst *AI) const
static void assignCalleeSavedSpillSlots(MachineFunction &F, const BitVector &SavedRegs, unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex)
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:81
static void insertCSRSpillsAndRestores(MachineFunction &Fn, const MBBVector &SaveBlocks, const MBBVector &RestoreBlocks)
insertCSRSpillsAndRestores - Insert spill and restore code for callee saved registers used in the fun...
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...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
typename vector_type::const_iterator const_iterator
Definition: SetVector.h:50
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.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual const TargetFrameLowering * getFrameLowering() const
int64_t getFrameSize(const MachineInstr &I) const
Returns size of the frame associated with the given frame instruction.
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:298
static void doSpillCalleeSavedRegs(MachineFunction &MF, RegScavenger *RS, unsigned &MinCSFrameIndex, unsigned &MaxCXFrameIndex, const MBBVector &SaveBlocks, const MBBVector &RestoreBlocks)
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:423
bool isMaxCallFrameSizeComputed() const
#define E
Definition: LargeTest.cpp:27
virtual bool requiresFrameIndexReplacementScavenging(const MachineFunction &MF) const
Returns true if the target requires using the RegScavenger directly for frame elimination despite usi...
virtual void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
unsigned getObjectAlignment(int ObjectIdx) const
Return the alignment of the specified stack object.
bool test(unsigned Idx) const
Definition: BitVector.h:502
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
Prologue Epilogue Insertion &Frame Finalization
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:383
unsigned getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call...
Information about stack frame layout on the target.
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:382
virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const
canSimplifyCallFramePseudos - When possible, it's best to simplify the call frame pseudo ops before d...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:278
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...
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...
int getStackProtectorIndex() const
Return the index for the stack protector object.
char & PrologEpilogCodeInserterID
PrologEpilogCodeInserter - This pass inserts prolog and epilog code, and eliminates abstract frame re...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
MachineBasicBlock * getSavePoint() const
#define DEBUG_TYPE
Representation of each machine instruction.
Definition: MachineInstr.h:59
void setCalleeSavedInfo(const std::vector< CalleeSavedInfo > &CSI)
Used by prolog/epilog inserter to set the function's callee saved information.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:254
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
TargetOptions Options
Definition: TargetMachine.h:95
void push_back(MachineInstr *MI)
#define I(x, y, z)
Definition: MD5.cpp:58
virtual void adjustForSegmentedStacks(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Adjust the prologue to have the function use segmented stacks.
void setMaxCallFrameSize(unsigned S)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling...
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
int CreateStackObject(uint64_t Size, unsigned Alignment, bool isSS, const AllocaInst *Alloca=nullptr)
Create a new statically sized stack object, returning a nonnegative identifier to represent it...
virtual bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual const TargetInstrInfo * getInstrInfo() const
#define DEBUG(X)
Definition: Debug.h:118
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:56
print Print MemDeps of function
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
IRTranslator LLVM IR MI
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return 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...
int getObjectIndexEnd() const
Return one past the maximum frame object index.
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 ...
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
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...
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
Array or nested array >= SSP-buffer-size.
Properties which a MachineFunction may have at a given point in time.
Array or nested array < SSP-buffer-size.
virtual bool isFPCloseToIncomingSP() const
isFPCloseToIncomingSP - Return true if the frame pointer is close to the incoming stack pointer...
void resize(size_type N)
Definition: SmallVector.h:352