CFIInstrInserter.cpp 13 KB

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