DwarfEHPrepare.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. //===- DwarfEHPrepare - Prepare exception handling for code generation ----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass mulches exception handling code into a form adapted to code
  10. // generation. Required if using dwarf exception handling.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/BitVector.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/ADT/Triple.h"
  17. #include "llvm/Analysis/CFG.h"
  18. #include "llvm/Analysis/DomTreeUpdater.h"
  19. #include "llvm/Analysis/EHPersonalities.h"
  20. #include "llvm/Analysis/TargetTransformInfo.h"
  21. #include "llvm/CodeGen/RuntimeLibcalls.h"
  22. #include "llvm/CodeGen/TargetLowering.h"
  23. #include "llvm/CodeGen/TargetPassConfig.h"
  24. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  25. #include "llvm/IR/BasicBlock.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DebugInfoMetadata.h"
  28. #include "llvm/IR/DerivedTypes.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/Function.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/IR/Type.h"
  34. #include "llvm/InitializePasses.h"
  35. #include "llvm/Pass.h"
  36. #include "llvm/Support/Casting.h"
  37. #include "llvm/Target/TargetMachine.h"
  38. #include "llvm/Transforms/Utils/Local.h"
  39. #include <cstddef>
  40. using namespace llvm;
  41. #define DEBUG_TYPE "dwarfehprepare"
  42. STATISTIC(NumResumesLowered, "Number of resume calls lowered");
  43. STATISTIC(NumCleanupLandingPadsUnreachable,
  44. "Number of cleanup landing pads found unreachable");
  45. STATISTIC(NumCleanupLandingPadsRemaining,
  46. "Number of cleanup landing pads remaining");
  47. STATISTIC(NumNoUnwind, "Number of functions with nounwind");
  48. STATISTIC(NumUnwind, "Number of functions with unwind");
  49. namespace {
  50. class DwarfEHPrepare {
  51. CodeGenOpt::Level OptLevel;
  52. Function &F;
  53. const TargetLowering &TLI;
  54. DomTreeUpdater *DTU;
  55. const TargetTransformInfo *TTI;
  56. const Triple &TargetTriple;
  57. /// Return the exception object from the value passed into
  58. /// the 'resume' instruction (typically an aggregate). Clean up any dead
  59. /// instructions, including the 'resume' instruction.
  60. Value *GetExceptionObject(ResumeInst *RI);
  61. /// Replace resumes that are not reachable from a cleanup landing pad with
  62. /// unreachable and then simplify those blocks.
  63. size_t
  64. pruneUnreachableResumes(SmallVectorImpl<ResumeInst *> &Resumes,
  65. SmallVectorImpl<LandingPadInst *> &CleanupLPads);
  66. /// Convert the ResumeInsts that are still present
  67. /// into calls to the appropriate _Unwind_Resume function.
  68. bool InsertUnwindResumeCalls();
  69. public:
  70. DwarfEHPrepare(CodeGenOpt::Level OptLevel_, Function &F_,
  71. const TargetLowering &TLI_, DomTreeUpdater *DTU_,
  72. const TargetTransformInfo *TTI_, const Triple &TargetTriple_)
  73. : OptLevel(OptLevel_), F(F_), TLI(TLI_), DTU(DTU_), TTI(TTI_),
  74. TargetTriple(TargetTriple_) {}
  75. bool run();
  76. };
  77. } // namespace
  78. Value *DwarfEHPrepare::GetExceptionObject(ResumeInst *RI) {
  79. Value *V = RI->getOperand(0);
  80. Value *ExnObj = nullptr;
  81. InsertValueInst *SelIVI = dyn_cast<InsertValueInst>(V);
  82. LoadInst *SelLoad = nullptr;
  83. InsertValueInst *ExcIVI = nullptr;
  84. bool EraseIVIs = false;
  85. if (SelIVI) {
  86. if (SelIVI->getNumIndices() == 1 && *SelIVI->idx_begin() == 1) {
  87. ExcIVI = dyn_cast<InsertValueInst>(SelIVI->getOperand(0));
  88. if (ExcIVI && isa<UndefValue>(ExcIVI->getOperand(0)) &&
  89. ExcIVI->getNumIndices() == 1 && *ExcIVI->idx_begin() == 0) {
  90. ExnObj = ExcIVI->getOperand(1);
  91. SelLoad = dyn_cast<LoadInst>(SelIVI->getOperand(1));
  92. EraseIVIs = true;
  93. }
  94. }
  95. }
  96. if (!ExnObj)
  97. ExnObj = ExtractValueInst::Create(RI->getOperand(0), 0, "exn.obj", RI);
  98. RI->eraseFromParent();
  99. if (EraseIVIs) {
  100. if (SelIVI->use_empty())
  101. SelIVI->eraseFromParent();
  102. if (ExcIVI->use_empty())
  103. ExcIVI->eraseFromParent();
  104. if (SelLoad && SelLoad->use_empty())
  105. SelLoad->eraseFromParent();
  106. }
  107. return ExnObj;
  108. }
  109. size_t DwarfEHPrepare::pruneUnreachableResumes(
  110. SmallVectorImpl<ResumeInst *> &Resumes,
  111. SmallVectorImpl<LandingPadInst *> &CleanupLPads) {
  112. assert(DTU && "Should have DomTreeUpdater here.");
  113. BitVector ResumeReachable(Resumes.size());
  114. size_t ResumeIndex = 0;
  115. for (auto *RI : Resumes) {
  116. for (auto *LP : CleanupLPads) {
  117. if (isPotentiallyReachable(LP, RI, nullptr, &DTU->getDomTree())) {
  118. ResumeReachable.set(ResumeIndex);
  119. break;
  120. }
  121. }
  122. ++ResumeIndex;
  123. }
  124. // If everything is reachable, there is no change.
  125. if (ResumeReachable.all())
  126. return Resumes.size();
  127. LLVMContext &Ctx = F.getContext();
  128. // Otherwise, insert unreachable instructions and call simplifycfg.
  129. size_t ResumesLeft = 0;
  130. for (size_t I = 0, E = Resumes.size(); I < E; ++I) {
  131. ResumeInst *RI = Resumes[I];
  132. if (ResumeReachable[I]) {
  133. Resumes[ResumesLeft++] = RI;
  134. } else {
  135. BasicBlock *BB = RI->getParent();
  136. new UnreachableInst(Ctx, RI);
  137. RI->eraseFromParent();
  138. simplifyCFG(BB, *TTI, DTU);
  139. }
  140. }
  141. Resumes.resize(ResumesLeft);
  142. return ResumesLeft;
  143. }
  144. bool DwarfEHPrepare::InsertUnwindResumeCalls() {
  145. SmallVector<ResumeInst *, 16> Resumes;
  146. SmallVector<LandingPadInst *, 16> CleanupLPads;
  147. if (F.doesNotThrow())
  148. NumNoUnwind++;
  149. else
  150. NumUnwind++;
  151. for (BasicBlock &BB : F) {
  152. if (auto *RI = dyn_cast<ResumeInst>(BB.getTerminator()))
  153. Resumes.push_back(RI);
  154. if (auto *LP = BB.getLandingPadInst())
  155. if (LP->isCleanup())
  156. CleanupLPads.push_back(LP);
  157. }
  158. NumCleanupLandingPadsRemaining += CleanupLPads.size();
  159. if (Resumes.empty())
  160. return false;
  161. // Check the personality, don't do anything if it's scope-based.
  162. EHPersonality Pers = classifyEHPersonality(F.getPersonalityFn());
  163. if (isScopedEHPersonality(Pers))
  164. return false;
  165. LLVMContext &Ctx = F.getContext();
  166. size_t ResumesLeft = Resumes.size();
  167. if (OptLevel != CodeGenOpt::None) {
  168. ResumesLeft = pruneUnreachableResumes(Resumes, CleanupLPads);
  169. #if LLVM_ENABLE_STATS
  170. unsigned NumRemainingLPs = 0;
  171. for (BasicBlock &BB : F) {
  172. if (auto *LP = BB.getLandingPadInst())
  173. if (LP->isCleanup())
  174. NumRemainingLPs++;
  175. }
  176. NumCleanupLandingPadsUnreachable += CleanupLPads.size() - NumRemainingLPs;
  177. NumCleanupLandingPadsRemaining -= CleanupLPads.size() - NumRemainingLPs;
  178. #endif
  179. }
  180. if (ResumesLeft == 0)
  181. return true; // We pruned them all.
  182. // RewindFunction - _Unwind_Resume or the target equivalent.
  183. FunctionCallee RewindFunction;
  184. CallingConv::ID RewindFunctionCallingConv;
  185. FunctionType *FTy;
  186. const char *RewindName;
  187. bool DoesRewindFunctionNeedExceptionObject;
  188. if ((Pers == EHPersonality::GNU_CXX || Pers == EHPersonality::GNU_CXX_SjLj) &&
  189. TargetTriple.isTargetEHABICompatible()) {
  190. RewindName = TLI.getLibcallName(RTLIB::CXA_END_CLEANUP);
  191. FTy = FunctionType::get(Type::getVoidTy(Ctx), false);
  192. RewindFunctionCallingConv =
  193. TLI.getLibcallCallingConv(RTLIB::CXA_END_CLEANUP);
  194. DoesRewindFunctionNeedExceptionObject = false;
  195. } else {
  196. RewindName = TLI.getLibcallName(RTLIB::UNWIND_RESUME);
  197. FTy =
  198. FunctionType::get(Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx), false);
  199. RewindFunctionCallingConv = TLI.getLibcallCallingConv(RTLIB::UNWIND_RESUME);
  200. DoesRewindFunctionNeedExceptionObject = true;
  201. }
  202. RewindFunction = F.getParent()->getOrInsertFunction(RewindName, FTy);
  203. // Create the basic block where the _Unwind_Resume call will live.
  204. if (ResumesLeft == 1) {
  205. // Instead of creating a new BB and PHI node, just append the call to
  206. // _Unwind_Resume to the end of the single resume block.
  207. ResumeInst *RI = Resumes.front();
  208. BasicBlock *UnwindBB = RI->getParent();
  209. Value *ExnObj = GetExceptionObject(RI);
  210. llvm::SmallVector<Value *, 1> RewindFunctionArgs;
  211. if (DoesRewindFunctionNeedExceptionObject)
  212. RewindFunctionArgs.push_back(ExnObj);
  213. // Call the rewind function.
  214. CallInst *CI =
  215. CallInst::Create(RewindFunction, RewindFunctionArgs, "", UnwindBB);
  216. // The verifier requires that all calls of debug-info-bearing functions
  217. // from debug-info-bearing functions have a debug location (for inlining
  218. // purposes). Assign a dummy location to satisfy the constraint.
  219. Function *RewindFn = dyn_cast<Function>(RewindFunction.getCallee());
  220. if (RewindFn && RewindFn->getSubprogram())
  221. if (DISubprogram *SP = F.getSubprogram())
  222. CI->setDebugLoc(DILocation::get(SP->getContext(), 0, 0, SP));
  223. CI->setCallingConv(RewindFunctionCallingConv);
  224. // We never expect _Unwind_Resume to return.
  225. CI->setDoesNotReturn();
  226. new UnreachableInst(Ctx, UnwindBB);
  227. return true;
  228. }
  229. std::vector<DominatorTree::UpdateType> Updates;
  230. Updates.reserve(Resumes.size());
  231. llvm::SmallVector<Value *, 1> RewindFunctionArgs;
  232. BasicBlock *UnwindBB = BasicBlock::Create(Ctx, "unwind_resume", &F);
  233. PHINode *PN = PHINode::Create(Type::getInt8PtrTy(Ctx), ResumesLeft, "exn.obj",
  234. UnwindBB);
  235. // Extract the exception object from the ResumeInst and add it to the PHI node
  236. // that feeds the _Unwind_Resume call.
  237. for (ResumeInst *RI : Resumes) {
  238. BasicBlock *Parent = RI->getParent();
  239. BranchInst::Create(UnwindBB, Parent);
  240. Updates.push_back({DominatorTree::Insert, Parent, UnwindBB});
  241. Value *ExnObj = GetExceptionObject(RI);
  242. PN->addIncoming(ExnObj, Parent);
  243. ++NumResumesLowered;
  244. }
  245. if (DoesRewindFunctionNeedExceptionObject)
  246. RewindFunctionArgs.push_back(PN);
  247. // Call the function.
  248. CallInst *CI =
  249. CallInst::Create(RewindFunction, RewindFunctionArgs, "", UnwindBB);
  250. CI->setCallingConv(RewindFunctionCallingConv);
  251. // We never expect _Unwind_Resume to return.
  252. CI->setDoesNotReturn();
  253. new UnreachableInst(Ctx, UnwindBB);
  254. if (DTU)
  255. DTU->applyUpdates(Updates);
  256. return true;
  257. }
  258. bool DwarfEHPrepare::run() {
  259. bool Changed = InsertUnwindResumeCalls();
  260. return Changed;
  261. }
  262. static bool prepareDwarfEH(CodeGenOpt::Level OptLevel, Function &F,
  263. const TargetLowering &TLI, DominatorTree *DT,
  264. const TargetTransformInfo *TTI,
  265. const Triple &TargetTriple) {
  266. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  267. return DwarfEHPrepare(OptLevel, F, TLI, DT ? &DTU : nullptr, TTI,
  268. TargetTriple)
  269. .run();
  270. }
  271. namespace {
  272. class DwarfEHPrepareLegacyPass : public FunctionPass {
  273. CodeGenOpt::Level OptLevel;
  274. public:
  275. static char ID; // Pass identification, replacement for typeid.
  276. DwarfEHPrepareLegacyPass(CodeGenOpt::Level OptLevel = CodeGenOpt::Default)
  277. : FunctionPass(ID), OptLevel(OptLevel) {}
  278. bool runOnFunction(Function &F) override {
  279. const TargetMachine &TM =
  280. getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
  281. const TargetLowering &TLI = *TM.getSubtargetImpl(F)->getTargetLowering();
  282. DominatorTree *DT = nullptr;
  283. const TargetTransformInfo *TTI = nullptr;
  284. if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
  285. DT = &DTWP->getDomTree();
  286. if (OptLevel != CodeGenOpt::None) {
  287. if (!DT)
  288. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  289. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  290. }
  291. return prepareDwarfEH(OptLevel, F, TLI, DT, TTI, TM.getTargetTriple());
  292. }
  293. void getAnalysisUsage(AnalysisUsage &AU) const override {
  294. AU.addRequired<TargetPassConfig>();
  295. AU.addRequired<TargetTransformInfoWrapperPass>();
  296. if (OptLevel != CodeGenOpt::None) {
  297. AU.addRequired<DominatorTreeWrapperPass>();
  298. AU.addRequired<TargetTransformInfoWrapperPass>();
  299. }
  300. AU.addPreserved<DominatorTreeWrapperPass>();
  301. }
  302. StringRef getPassName() const override {
  303. return "Exception handling preparation";
  304. }
  305. };
  306. } // end anonymous namespace
  307. char DwarfEHPrepareLegacyPass::ID = 0;
  308. INITIALIZE_PASS_BEGIN(DwarfEHPrepareLegacyPass, DEBUG_TYPE,
  309. "Prepare DWARF exceptions", false, false)
  310. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  311. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  312. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  313. INITIALIZE_PASS_END(DwarfEHPrepareLegacyPass, DEBUG_TYPE,
  314. "Prepare DWARF exceptions", false, false)
  315. FunctionPass *llvm::createDwarfEHPass(CodeGenOpt::Level OptLevel) {
  316. return new DwarfEHPrepareLegacyPass(OptLevel);
  317. }