LLVM  8.0.1
CFIInstrInserter.cpp
Go to the documentation of this file.
1 //===------ CFIInstrInserter.cpp - Insert additional CFI instructions -----===//
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 /// \file This pass verifies incoming and outgoing CFA information of basic
11 /// blocks. CFA information is information about offset and register set by CFI
12 /// directives, valid at the start and end of a basic block. This pass checks
13 /// that outgoing information of predecessors matches incoming information of
14 /// their successors. Then it checks if blocks have correct CFA calculation rule
15 /// set and inserts additional CFI instruction at their beginnings if they
16 /// don't. CFI instructions are inserted if basic blocks have incorrect offset
17 /// or register set by previous blocks, as a result of a non-linear layout of
18 /// blocks in a function.
19 //===----------------------------------------------------------------------===//
20 
25 #include "llvm/CodeGen/Passes.h"
30 using namespace llvm;
31 
32 static cl::opt<bool> VerifyCFI("verify-cfiinstrs",
33  cl::desc("Verify Call Frame Information instructions"),
34  cl::init(false),
35  cl::Hidden);
36 
37 namespace {
38 class CFIInstrInserter : public MachineFunctionPass {
39  public:
40  static char ID;
41 
42  CFIInstrInserter() : MachineFunctionPass(ID) {
44  }
45 
46  void getAnalysisUsage(AnalysisUsage &AU) const override {
47  AU.setPreservesAll();
49  }
50 
51  bool runOnMachineFunction(MachineFunction &MF) override {
52  if (!MF.getMMI().hasDebugInfo() &&
54  return false;
55 
57  calculateCFAInfo(MF);
58 
59  if (VerifyCFI) {
60  if (unsigned ErrorNum = verify(MF))
61  report_fatal_error("Found " + Twine(ErrorNum) +
62  " in/out CFI information errors.");
63  }
64  bool insertedCFI = insertCFIInstrs(MF);
65  MBBVector.clear();
66  return insertedCFI;
67  }
68 
69  private:
70  struct MBBCFAInfo {
71  MachineBasicBlock *MBB;
72  /// Value of cfa offset valid at basic block entry.
73  int IncomingCFAOffset = -1;
74  /// Value of cfa offset valid at basic block exit.
75  int OutgoingCFAOffset = -1;
76  /// Value of cfa register valid at basic block entry.
77  unsigned IncomingCFARegister = 0;
78  /// Value of cfa register valid at basic block exit.
79  unsigned OutgoingCFARegister = 0;
80  /// If in/out cfa offset and register values for this block have already
81  /// been set or not.
82  bool Processed = false;
83  };
84 
85  /// Contains cfa offset and register values valid at entry and exit of basic
86  /// blocks.
87  std::vector<MBBCFAInfo> MBBVector;
88 
89  /// Calculate cfa offset and register values valid at entry and exit for all
90  /// basic blocks in a function.
91  void calculateCFAInfo(MachineFunction &MF);
92  /// Calculate cfa offset and register values valid at basic block exit by
93  /// checking the block for CFI instructions. Block's incoming CFA info remains
94  /// the same.
95  void calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo);
96  /// Update in/out cfa offset and register values for successors of the basic
97  /// block.
98  void updateSuccCFAInfo(MBBCFAInfo &MBBInfo);
99 
100  /// Check if incoming CFA information of a basic block matches outgoing CFA
101  /// information of the previous block. If it doesn't, insert CFI instruction
102  /// at the beginning of the block that corrects the CFA calculation rule for
103  /// that block.
104  bool insertCFIInstrs(MachineFunction &MF);
105  /// Return the cfa offset value that should be set at the beginning of a MBB
106  /// if needed. The negated value is needed when creating CFI instructions that
107  /// set absolute offset.
108  int getCorrectCFAOffset(MachineBasicBlock *MBB) {
109  return -MBBVector[MBB->getNumber()].IncomingCFAOffset;
110  }
111 
112  void report(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ);
113  /// Go through each MBB in a function and check that outgoing offset and
114  /// register of its predecessors match incoming offset and register of that
115  /// MBB, as well as that incoming offset and register of its successors match
116  /// outgoing offset and register of the MBB.
117  unsigned verify(MachineFunction &MF);
118 };
119 } // namespace
120 
121 char CFIInstrInserter::ID = 0;
122 INITIALIZE_PASS(CFIInstrInserter, "cfi-instr-inserter",
123  "Check CFA info and insert CFI instructions if needed", false,
124  false)
125 FunctionPass *llvm::createCFIInstrInserter() { return new CFIInstrInserter(); }
126 
127 void CFIInstrInserter::calculateCFAInfo(MachineFunction &MF) {
128  // Initial CFA offset value i.e. the one valid at the beginning of the
129  // function.
130  int InitialOffset =
132  // Initial CFA register value i.e. the one valid at the beginning of the
133  // function.
134  unsigned InitialRegister =
136 
137  // Initialize MBBMap.
138  for (MachineBasicBlock &MBB : MF) {
139  MBBCFAInfo MBBInfo;
140  MBBInfo.MBB = &MBB;
141  MBBInfo.IncomingCFAOffset = InitialOffset;
142  MBBInfo.OutgoingCFAOffset = InitialOffset;
143  MBBInfo.IncomingCFARegister = InitialRegister;
144  MBBInfo.OutgoingCFARegister = InitialRegister;
145  MBBVector[MBB.getNumber()] = MBBInfo;
146  }
147 
148  // Set in/out cfa info for all blocks in the function. This traversal is based
149  // on the assumption that the first block in the function is the entry block
150  // i.e. that it has initial cfa offset and register values as incoming CFA
151  // information.
152  for (MachineBasicBlock &MBB : MF) {
153  if (MBBVector[MBB.getNumber()].Processed) continue;
154  updateSuccCFAInfo(MBBVector[MBB.getNumber()]);
155  }
156 }
157 
158 void CFIInstrInserter::calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo) {
159  // Outgoing cfa offset set by the block.
160  int SetOffset = MBBInfo.IncomingCFAOffset;
161  // Outgoing cfa register set by the block.
162  unsigned SetRegister = MBBInfo.IncomingCFARegister;
163  const std::vector<MCCFIInstruction> &Instrs =
164  MBBInfo.MBB->getParent()->getFrameInstructions();
165 
166  // Determine cfa offset and register set by the block.
167  for (MachineInstr &MI : *MBBInfo.MBB) {
168  if (MI.isCFIInstruction()) {
169  unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
170  const MCCFIInstruction &CFI = Instrs[CFIIndex];
171  switch (CFI.getOperation()) {
173  SetRegister = CFI.getRegister();
174  break;
176  SetOffset = CFI.getOffset();
177  break;
179  SetOffset += CFI.getOffset();
180  break;
182  SetRegister = CFI.getRegister();
183  SetOffset = CFI.getOffset();
184  break;
186  // TODO: Add support for handling cfi_remember_state.
187 #ifndef NDEBUG
189  "Support for cfi_remember_state not implemented! Value of CFA "
190  "may be incorrect!\n");
191 #endif
192  break;
194  // TODO: Add support for handling cfi_restore_state.
195 #ifndef NDEBUG
197  "Support for cfi_restore_state not implemented! Value of CFA may "
198  "be incorrect!\n");
199 #endif
200  break;
201  // Other CFI directives do not affect CFA value.
212  break;
213  }
214  }
215  }
216 
217  MBBInfo.Processed = true;
218 
219  // Update outgoing CFA info.
220  MBBInfo.OutgoingCFAOffset = SetOffset;
221  MBBInfo.OutgoingCFARegister = SetRegister;
222 }
223 
224 void CFIInstrInserter::updateSuccCFAInfo(MBBCFAInfo &MBBInfo) {
226  Stack.push_back(MBBInfo.MBB);
227 
228  do {
229  MachineBasicBlock *Current = Stack.pop_back_val();
230  MBBCFAInfo &CurrentInfo = MBBVector[Current->getNumber()];
231  if (CurrentInfo.Processed)
232  continue;
233 
234  calculateOutgoingCFAInfo(CurrentInfo);
235  for (auto *Succ : CurrentInfo.MBB->successors()) {
236  MBBCFAInfo &SuccInfo = MBBVector[Succ->getNumber()];
237  if (!SuccInfo.Processed) {
238  SuccInfo.IncomingCFAOffset = CurrentInfo.OutgoingCFAOffset;
239  SuccInfo.IncomingCFARegister = CurrentInfo.OutgoingCFARegister;
240  Stack.push_back(Succ);
241  }
242  }
243  } while (!Stack.empty());
244 }
245 
246 bool CFIInstrInserter::insertCFIInstrs(MachineFunction &MF) {
247  const MBBCFAInfo *PrevMBBInfo = &MBBVector[MF.front().getNumber()];
249  bool InsertedCFIInstr = false;
250 
251  for (MachineBasicBlock &MBB : MF) {
252  // Skip the first MBB in a function
253  if (MBB.getNumber() == MF.front().getNumber()) continue;
254 
255  const MBBCFAInfo &MBBInfo = MBBVector[MBB.getNumber()];
256  auto MBBI = MBBInfo.MBB->begin();
257  DebugLoc DL = MBBInfo.MBB->findDebugLoc(MBBI);
258 
259  if (PrevMBBInfo->OutgoingCFAOffset != MBBInfo.IncomingCFAOffset) {
260  // If both outgoing offset and register of a previous block don't match
261  // incoming offset and register of this block, add a def_cfa instruction
262  // with the correct offset and register for this block.
263  if (PrevMBBInfo->OutgoingCFARegister != MBBInfo.IncomingCFARegister) {
264  unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
265  nullptr, MBBInfo.IncomingCFARegister, getCorrectCFAOffset(&MBB)));
266  BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
267  .addCFIIndex(CFIIndex);
268  // If outgoing offset of a previous block doesn't match incoming offset
269  // of this block, add a def_cfa_offset instruction with the correct
270  // offset for this block.
271  } else {
272  unsigned CFIIndex =
273  MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(
274  nullptr, getCorrectCFAOffset(&MBB)));
275  BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
276  .addCFIIndex(CFIIndex);
277  }
278  InsertedCFIInstr = true;
279  // If outgoing register of a previous block doesn't match incoming
280  // register of this block, add a def_cfa_register instruction with the
281  // correct register for this block.
282  } else if (PrevMBBInfo->OutgoingCFARegister !=
283  MBBInfo.IncomingCFARegister) {
284  unsigned CFIIndex =
286  nullptr, MBBInfo.IncomingCFARegister));
287  BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
288  .addCFIIndex(CFIIndex);
289  InsertedCFIInstr = true;
290  }
291  PrevMBBInfo = &MBBInfo;
292  }
293  return InsertedCFIInstr;
294 }
295 
296 void CFIInstrInserter::report(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ) {
297  errs() << "*** Inconsistent CFA register and/or offset between pred and succ "
298  "***\n";
299  errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
300  << " in " << Pred.MBB->getParent()->getName()
301  << " outgoing CFA Reg:" << Pred.OutgoingCFARegister << "\n";
302  errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
303  << " in " << Pred.MBB->getParent()->getName()
304  << " outgoing CFA Offset:" << Pred.OutgoingCFAOffset << "\n";
305  errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
306  << " incoming CFA Reg:" << Succ.IncomingCFARegister << "\n";
307  errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
308  << " incoming CFA Offset:" << Succ.IncomingCFAOffset << "\n";
309 }
310 
312  unsigned ErrorNum = 0;
313  for (auto *CurrMBB : depth_first(&MF)) {
314  const MBBCFAInfo &CurrMBBInfo = MBBVector[CurrMBB->getNumber()];
315  for (MachineBasicBlock *Succ : CurrMBB->successors()) {
316  const MBBCFAInfo &SuccMBBInfo = MBBVector[Succ->getNumber()];
317  // Check that incoming offset and register values of successors match the
318  // outgoing offset and register values of CurrMBB
319  if (SuccMBBInfo.IncomingCFAOffset != CurrMBBInfo.OutgoingCFAOffset ||
320  SuccMBBInfo.IncomingCFARegister != CurrMBBInfo.OutgoingCFARegister) {
321  // Inconsistent offsets/registers are ok for 'noreturn' blocks because
322  // we don't generate epilogues inside such blocks.
323  if (SuccMBBInfo.MBB->succ_empty() && !SuccMBBInfo.MBB->isReturnBlock())
324  continue;
325  report(CurrMBBInfo, SuccMBBInfo);
326  ErrorNum++;
327  }
328  }
329  }
330  return ErrorNum;
331 }
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool hasDebugInfo() const
Returns true if valid debug info is present.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:24
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID&#39;s allocated.
bool isCFIInstruction() const
Definition: MachineInstr.h:990
A debug info location.
Definition: DebugLoc.h:34
MachineModuleInfo & getMMI() const
static MCCFIInstruction createDefCfaOffset(MCSymbol *L, int Offset)
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition: MCDwarf.h:475
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
const HexagonInstrInfo * TII
unsigned getCFIIndex() const
SmallVector< MachineBasicBlock *, 4 > MBBVector
static cl::opt< bool > VerifyCFI("verify-cfiinstrs", cl::desc("Verify Call Frame Information instructions"), cl::init(false), cl::Hidden)
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
virtual const TargetInstrInfo * getInstrInfo() const
TargetInstrInfo - Interface to description of machine instruction set.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
static MCCFIInstruction createDefCfa(MCSymbol *L, unsigned Register, int Offset)
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it...
Definition: MCDwarf.h:461
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.
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register)
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition: MCDwarf.h:468
int getOffset() const
Definition: MCDwarf.h:574
Represent the analysis usage information of a pass.
OpType getOperation() const
Definition: MCDwarf.h:558
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
void initializeCFIInstrInserterPass(PassRegistry &)
const MachineBasicBlock & front() const
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
unsigned getRegister() const
Definition: MCDwarf.h:561
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:381
const Function & getFunction() const
Return the LLVM function that this machine code represents.
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition: Function.h:573
void setPreservesAll()
Set by analyses that do not transform their input at all.
Representation of each machine instruction.
Definition: MachineInstr.h:64
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:45
INITIALIZE_PASS(CFIInstrInserter, "cfi-instr-inserter", "Check CFA info and insert CFI instructions if needed", false, false) FunctionPass *llvm
virtual const TargetFrameLowering * getFrameLowering() const
iterator_range< df_iterator< T > > depth_first(const T &G)
IRTranslator LLVM IR MI
ppc ctr loops verify
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:414
FunctionPass * createCFIInstrInserter()
Creates CFI Instruction Inserter pass.
virtual int getInitialCFAOffset(const MachineFunction &MF) const
Return initial CFA offset value i.e.
virtual unsigned getInitialCFARegister(const MachineFunction &MF) const
Return initial CFA register value i.e.
void resize(size_type N)
Definition: SmallVector.h:351