CFIInstrInserter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. //===------ CFIInstrInserter.cpp - Insert additional CFI instructions -----===//
  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. /// \file This pass verifies incoming and outgoing CFA information of basic
  10. /// blocks. CFA information is information about offset and register set by CFI
  11. /// directives, valid at the start and end of a basic block. This pass checks
  12. /// that outgoing information of predecessors matches incoming information of
  13. /// their successors. Then it checks if blocks have correct CFA calculation rule
  14. /// set and inserts additional CFI instruction at their beginnings if they
  15. /// don't. CFI instructions are inserted if basic blocks have incorrect offset
  16. /// or register set by previous blocks, as a result of a non-linear layout of
  17. /// blocks in a function.
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/ADT/DepthFirstIterator.h"
  20. #include "llvm/CodeGen/MachineFunctionPass.h"
  21. #include "llvm/CodeGen/MachineInstrBuilder.h"
  22. #include "llvm/CodeGen/MachineModuleInfo.h"
  23. #include "llvm/CodeGen/Passes.h"
  24. #include "llvm/CodeGen/TargetFrameLowering.h"
  25. #include "llvm/CodeGen/TargetInstrInfo.h"
  26. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  27. #include "llvm/Target/TargetMachine.h"
  28. using namespace llvm;
  29. static cl::opt<bool> VerifyCFI("verify-cfiinstrs",
  30. cl::desc("Verify Call Frame Information instructions"),
  31. cl::init(false),
  32. cl::Hidden);
  33. namespace {
  34. class CFIInstrInserter : public MachineFunctionPass {
  35. public:
  36. static char ID;
  37. CFIInstrInserter() : MachineFunctionPass(ID) {
  38. initializeCFIInstrInserterPass(*PassRegistry::getPassRegistry());
  39. }
  40. void getAnalysisUsage(AnalysisUsage &AU) const override {
  41. AU.setPreservesAll();
  42. MachineFunctionPass::getAnalysisUsage(AU);
  43. }
  44. bool runOnMachineFunction(MachineFunction &MF) override {
  45. if (!MF.getMMI().hasDebugInfo() &&
  46. !MF.getFunction().needsUnwindTableEntry())
  47. return false;
  48. MBBVector.resize(MF.getNumBlockIDs());
  49. calculateCFAInfo(MF);
  50. if (VerifyCFI) {
  51. if (unsigned ErrorNum = verify(MF))
  52. report_fatal_error("Found " + Twine(ErrorNum) +
  53. " in/out CFI information errors.");
  54. }
  55. bool insertedCFI = insertCFIInstrs(MF);
  56. MBBVector.clear();
  57. return insertedCFI;
  58. }
  59. private:
  60. struct MBBCFAInfo {
  61. MachineBasicBlock *MBB;
  62. /// Value of cfa offset valid at basic block entry.
  63. int IncomingCFAOffset = -1;
  64. /// Value of cfa offset valid at basic block exit.
  65. int OutgoingCFAOffset = -1;
  66. /// Value of cfa register valid at basic block entry.
  67. unsigned IncomingCFARegister = 0;
  68. /// Value of cfa register valid at basic block exit.
  69. unsigned OutgoingCFARegister = 0;
  70. /// If in/out cfa offset and register values for this block have already
  71. /// been set or not.
  72. bool Processed = false;
  73. };
  74. /// Contains cfa offset and register values valid at entry and exit of basic
  75. /// blocks.
  76. std::vector<MBBCFAInfo> MBBVector;
  77. /// Calculate cfa offset and register values valid at entry and exit for all
  78. /// basic blocks in a function.
  79. void calculateCFAInfo(MachineFunction &MF);
  80. /// Calculate cfa offset and register values valid at basic block exit by
  81. /// checking the block for CFI instructions. Block's incoming CFA info remains
  82. /// the same.
  83. void calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo);
  84. /// Update in/out cfa offset and register values for successors of the basic
  85. /// block.
  86. void updateSuccCFAInfo(MBBCFAInfo &MBBInfo);
  87. /// Check if incoming CFA information of a basic block matches outgoing CFA
  88. /// information of the previous block. If it doesn't, insert CFI instruction
  89. /// at the beginning of the block that corrects the CFA calculation rule for
  90. /// that block.
  91. bool insertCFIInstrs(MachineFunction &MF);
  92. /// Return the cfa offset value that should be set at the beginning of a MBB
  93. /// if needed. The negated value is needed when creating CFI instructions that
  94. /// set absolute offset.
  95. int getCorrectCFAOffset(MachineBasicBlock *MBB) {
  96. return -MBBVector[MBB->getNumber()].IncomingCFAOffset;
  97. }
  98. void report(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ);
  99. /// Go through each MBB in a function and check that outgoing offset and
  100. /// register of its predecessors match incoming offset and register of that
  101. /// MBB, as well as that incoming offset and register of its successors match
  102. /// outgoing offset and register of the MBB.
  103. unsigned verify(MachineFunction &MF);
  104. };
  105. } // namespace
  106. char CFIInstrInserter::ID = 0;
  107. INITIALIZE_PASS(CFIInstrInserter, "cfi-instr-inserter",
  108. "Check CFA info and insert CFI instructions if needed", false,
  109. false)
  110. FunctionPass *llvm::createCFIInstrInserter() { return new CFIInstrInserter(); }
  111. void CFIInstrInserter::calculateCFAInfo(MachineFunction &MF) {
  112. // Initial CFA offset value i.e. the one valid at the beginning of the
  113. // function.
  114. int InitialOffset =
  115. MF.getSubtarget().getFrameLowering()->getInitialCFAOffset(MF);
  116. // Initial CFA register value i.e. the one valid at the beginning of the
  117. // function.
  118. unsigned InitialRegister =
  119. MF.getSubtarget().getFrameLowering()->getInitialCFARegister(MF);
  120. // Initialize MBBMap.
  121. for (MachineBasicBlock &MBB : MF) {
  122. MBBCFAInfo MBBInfo;
  123. MBBInfo.MBB = &MBB;
  124. MBBInfo.IncomingCFAOffset = InitialOffset;
  125. MBBInfo.OutgoingCFAOffset = InitialOffset;
  126. MBBInfo.IncomingCFARegister = InitialRegister;
  127. MBBInfo.OutgoingCFARegister = InitialRegister;
  128. MBBVector[MBB.getNumber()] = MBBInfo;
  129. }
  130. // Set in/out cfa info for all blocks in the function. This traversal is based
  131. // on the assumption that the first block in the function is the entry block
  132. // i.e. that it has initial cfa offset and register values as incoming CFA
  133. // information.
  134. for (MachineBasicBlock &MBB : MF) {
  135. if (MBBVector[MBB.getNumber()].Processed) continue;
  136. updateSuccCFAInfo(MBBVector[MBB.getNumber()]);
  137. }
  138. }
  139. void CFIInstrInserter::calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo) {
  140. // Outgoing cfa offset set by the block.
  141. int SetOffset = MBBInfo.IncomingCFAOffset;
  142. // Outgoing cfa register set by the block.
  143. unsigned SetRegister = MBBInfo.IncomingCFARegister;
  144. const std::vector<MCCFIInstruction> &Instrs =
  145. MBBInfo.MBB->getParent()->getFrameInstructions();
  146. // Determine cfa offset and register set by the block.
  147. for (MachineInstr &MI : *MBBInfo.MBB) {
  148. if (MI.isCFIInstruction()) {
  149. unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
  150. const MCCFIInstruction &CFI = Instrs[CFIIndex];
  151. switch (CFI.getOperation()) {
  152. case MCCFIInstruction::OpDefCfaRegister:
  153. SetRegister = CFI.getRegister();
  154. break;
  155. case MCCFIInstruction::OpDefCfaOffset:
  156. SetOffset = CFI.getOffset();
  157. break;
  158. case MCCFIInstruction::OpAdjustCfaOffset:
  159. SetOffset += CFI.getOffset();
  160. break;
  161. case MCCFIInstruction::OpDefCfa:
  162. SetRegister = CFI.getRegister();
  163. SetOffset = CFI.getOffset();
  164. break;
  165. case MCCFIInstruction::OpRememberState:
  166. // TODO: Add support for handling cfi_remember_state.
  167. #ifndef NDEBUG
  168. report_fatal_error(
  169. "Support for cfi_remember_state not implemented! Value of CFA "
  170. "may be incorrect!\n");
  171. #endif
  172. break;
  173. case MCCFIInstruction::OpRestoreState:
  174. // TODO: Add support for handling cfi_restore_state.
  175. #ifndef NDEBUG
  176. report_fatal_error(
  177. "Support for cfi_restore_state not implemented! Value of CFA may "
  178. "be incorrect!\n");
  179. #endif
  180. break;
  181. // Other CFI directives do not affect CFA value.
  182. case MCCFIInstruction::OpSameValue:
  183. case MCCFIInstruction::OpOffset:
  184. case MCCFIInstruction::OpRelOffset:
  185. case MCCFIInstruction::OpEscape:
  186. case MCCFIInstruction::OpRestore:
  187. case MCCFIInstruction::OpUndefined:
  188. case MCCFIInstruction::OpRegister:
  189. case MCCFIInstruction::OpWindowSave:
  190. case MCCFIInstruction::OpNegateRAState:
  191. case MCCFIInstruction::OpGnuArgsSize:
  192. break;
  193. }
  194. }
  195. }
  196. MBBInfo.Processed = true;
  197. // Update outgoing CFA info.
  198. MBBInfo.OutgoingCFAOffset = SetOffset;
  199. MBBInfo.OutgoingCFARegister = SetRegister;
  200. }
  201. void CFIInstrInserter::updateSuccCFAInfo(MBBCFAInfo &MBBInfo) {
  202. SmallVector<MachineBasicBlock *, 4> Stack;
  203. Stack.push_back(MBBInfo.MBB);
  204. do {
  205. MachineBasicBlock *Current = Stack.pop_back_val();
  206. MBBCFAInfo &CurrentInfo = MBBVector[Current->getNumber()];
  207. if (CurrentInfo.Processed)
  208. continue;
  209. calculateOutgoingCFAInfo(CurrentInfo);
  210. for (auto *Succ : CurrentInfo.MBB->successors()) {
  211. MBBCFAInfo &SuccInfo = MBBVector[Succ->getNumber()];
  212. if (!SuccInfo.Processed) {
  213. SuccInfo.IncomingCFAOffset = CurrentInfo.OutgoingCFAOffset;
  214. SuccInfo.IncomingCFARegister = CurrentInfo.OutgoingCFARegister;
  215. Stack.push_back(Succ);
  216. }
  217. }
  218. } while (!Stack.empty());
  219. }
  220. bool CFIInstrInserter::insertCFIInstrs(MachineFunction &MF) {
  221. const MBBCFAInfo *PrevMBBInfo = &MBBVector[MF.front().getNumber()];
  222. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  223. bool InsertedCFIInstr = false;
  224. for (MachineBasicBlock &MBB : MF) {
  225. // Skip the first MBB in a function
  226. if (MBB.getNumber() == MF.front().getNumber()) continue;
  227. const MBBCFAInfo &MBBInfo = MBBVector[MBB.getNumber()];
  228. auto MBBI = MBBInfo.MBB->begin();
  229. DebugLoc DL = MBBInfo.MBB->findDebugLoc(MBBI);
  230. if (PrevMBBInfo->OutgoingCFAOffset != MBBInfo.IncomingCFAOffset) {
  231. // If both outgoing offset and register of a previous block don't match
  232. // incoming offset and register of this block, add a def_cfa instruction
  233. // with the correct offset and register for this block.
  234. if (PrevMBBInfo->OutgoingCFARegister != MBBInfo.IncomingCFARegister) {
  235. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
  236. nullptr, MBBInfo.IncomingCFARegister, getCorrectCFAOffset(&MBB)));
  237. BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  238. .addCFIIndex(CFIIndex);
  239. // If outgoing offset of a previous block doesn't match incoming offset
  240. // of this block, add a def_cfa_offset instruction with the correct
  241. // offset for this block.
  242. } else {
  243. unsigned CFIIndex =
  244. MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(
  245. nullptr, getCorrectCFAOffset(&MBB)));
  246. BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  247. .addCFIIndex(CFIIndex);
  248. }
  249. InsertedCFIInstr = true;
  250. // If outgoing register of a previous block doesn't match incoming
  251. // register of this block, add a def_cfa_register instruction with the
  252. // correct register for this block.
  253. } else if (PrevMBBInfo->OutgoingCFARegister !=
  254. MBBInfo.IncomingCFARegister) {
  255. unsigned CFIIndex =
  256. MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
  257. nullptr, MBBInfo.IncomingCFARegister));
  258. BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  259. .addCFIIndex(CFIIndex);
  260. InsertedCFIInstr = true;
  261. }
  262. PrevMBBInfo = &MBBInfo;
  263. }
  264. return InsertedCFIInstr;
  265. }
  266. void CFIInstrInserter::report(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ) {
  267. errs() << "*** Inconsistent CFA register and/or offset between pred and succ "
  268. "***\n";
  269. errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
  270. << " in " << Pred.MBB->getParent()->getName()
  271. << " outgoing CFA Reg:" << Pred.OutgoingCFARegister << "\n";
  272. errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
  273. << " in " << Pred.MBB->getParent()->getName()
  274. << " outgoing CFA Offset:" << Pred.OutgoingCFAOffset << "\n";
  275. errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
  276. << " incoming CFA Reg:" << Succ.IncomingCFARegister << "\n";
  277. errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
  278. << " incoming CFA Offset:" << Succ.IncomingCFAOffset << "\n";
  279. }
  280. unsigned CFIInstrInserter::verify(MachineFunction &MF) {
  281. unsigned ErrorNum = 0;
  282. for (auto *CurrMBB : depth_first(&MF)) {
  283. const MBBCFAInfo &CurrMBBInfo = MBBVector[CurrMBB->getNumber()];
  284. for (MachineBasicBlock *Succ : CurrMBB->successors()) {
  285. const MBBCFAInfo &SuccMBBInfo = MBBVector[Succ->getNumber()];
  286. // Check that incoming offset and register values of successors match the
  287. // outgoing offset and register values of CurrMBB
  288. if (SuccMBBInfo.IncomingCFAOffset != CurrMBBInfo.OutgoingCFAOffset ||
  289. SuccMBBInfo.IncomingCFARegister != CurrMBBInfo.OutgoingCFARegister) {
  290. // Inconsistent offsets/registers are ok for 'noreturn' blocks because
  291. // we don't generate epilogues inside such blocks.
  292. if (SuccMBBInfo.MBB->succ_empty() && !SuccMBBInfo.MBB->isReturnBlock())
  293. continue;
  294. report(CurrMBBInfo, SuccMBBInfo);
  295. ErrorNum++;
  296. }
  297. }
  298. }
  299. return ErrorNum;
  300. }