1 //===-- DwarfEHPrepare - Prepare exception handling for code generation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass mulches exception handling code into a form adapted to code
11 // generation. Required if using dwarf exception handling.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/CFG.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetSubtargetInfo.h"
27 #include "llvm/Transforms/Utils/Local.h"
30 #define DEBUG_TYPE "dwarfehprepare"
32 STATISTIC(NumResumesLowered, "Number of resume calls lowered");
35 class DwarfEHPrepare : public FunctionPass {
36 const TargetMachine *TM;
38 // RewindFunction - _Unwind_Resume or the target equivalent.
39 Constant *RewindFunction;
42 const TargetLowering *TLI;
44 bool InsertUnwindResumeCalls(Function &Fn);
45 Value *GetExceptionObject(ResumeInst *RI);
47 pruneUnreachableResumes(Function &Fn,
48 SmallVectorImpl<ResumeInst *> &Resumes,
49 SmallVectorImpl<LandingPadInst *> &CleanupLPads);
52 static char ID; // Pass identification, replacement for typeid.
54 // INITIALIZE_TM_PASS requires a default constructor, but it isn't used in
57 : FunctionPass(ID), TM(nullptr), RewindFunction(nullptr), DT(nullptr),
60 DwarfEHPrepare(const TargetMachine *TM)
61 : FunctionPass(ID), TM(TM), RewindFunction(nullptr), DT(nullptr),
64 bool runOnFunction(Function &Fn) override;
66 bool doFinalization(Module &M) override {
67 RewindFunction = nullptr;
71 void getAnalysisUsage(AnalysisUsage &AU) const override;
73 const char *getPassName() const override {
74 return "Exception handling preparation";
77 } // end anonymous namespace
79 char DwarfEHPrepare::ID = 0;
80 INITIALIZE_TM_PASS_BEGIN(DwarfEHPrepare, "dwarfehprepare",
81 "Prepare DWARF exceptions", false, false)
82 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
83 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
84 INITIALIZE_TM_PASS_END(DwarfEHPrepare, "dwarfehprepare",
85 "Prepare DWARF exceptions", false, false)
87 FunctionPass *llvm::createDwarfEHPass(const TargetMachine *TM) {
88 return new DwarfEHPrepare(TM);
91 void DwarfEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addRequired<TargetTransformInfoWrapperPass>();
93 AU.addRequired<DominatorTreeWrapperPass>();
96 /// GetExceptionObject - Return the exception object from the value passed into
97 /// the 'resume' instruction (typically an aggregate). Clean up any dead
98 /// instructions, including the 'resume' instruction.
99 Value *DwarfEHPrepare::GetExceptionObject(ResumeInst *RI) {
100 Value *V = RI->getOperand(0);
101 Value *ExnObj = nullptr;
102 InsertValueInst *SelIVI = dyn_cast<InsertValueInst>(V);
103 LoadInst *SelLoad = nullptr;
104 InsertValueInst *ExcIVI = nullptr;
105 bool EraseIVIs = false;
108 if (SelIVI->getNumIndices() == 1 && *SelIVI->idx_begin() == 1) {
109 ExcIVI = dyn_cast<InsertValueInst>(SelIVI->getOperand(0));
110 if (ExcIVI && isa<UndefValue>(ExcIVI->getOperand(0)) &&
111 ExcIVI->getNumIndices() == 1 && *ExcIVI->idx_begin() == 0) {
112 ExnObj = ExcIVI->getOperand(1);
113 SelLoad = dyn_cast<LoadInst>(SelIVI->getOperand(1));
120 ExnObj = ExtractValueInst::Create(RI->getOperand(0), 0, "exn.obj", RI);
122 RI->eraseFromParent();
125 if (SelIVI->use_empty())
126 SelIVI->eraseFromParent();
127 if (ExcIVI->use_empty())
128 ExcIVI->eraseFromParent();
129 if (SelLoad && SelLoad->use_empty())
130 SelLoad->eraseFromParent();
136 /// Replace resumes that are not reachable from a cleanup landing pad with
137 /// unreachable and then simplify those blocks.
138 size_t DwarfEHPrepare::pruneUnreachableResumes(
139 Function &Fn, SmallVectorImpl<ResumeInst *> &Resumes,
140 SmallVectorImpl<LandingPadInst *> &CleanupLPads) {
141 BitVector ResumeReachable(Resumes.size());
142 size_t ResumeIndex = 0;
143 for (auto *RI : Resumes) {
144 for (auto *LP : CleanupLPads) {
145 if (isPotentiallyReachable(LP, RI, DT)) {
146 ResumeReachable.set(ResumeIndex);
153 // If everything is reachable, there is no change.
154 if (ResumeReachable.all())
155 return Resumes.size();
157 const TargetTransformInfo &TTI =
158 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn);
159 LLVMContext &Ctx = Fn.getContext();
161 // Otherwise, insert unreachable instructions and call simplifycfg.
162 size_t ResumesLeft = 0;
163 for (size_t I = 0, E = Resumes.size(); I < E; ++I) {
164 ResumeInst *RI = Resumes[I];
165 if (ResumeReachable[I]) {
166 Resumes[ResumesLeft++] = RI;
168 BasicBlock *BB = RI->getParent();
169 new UnreachableInst(Ctx, RI);
170 RI->eraseFromParent();
171 SimplifyCFG(BB, TTI, 1, TLI->getDataLayout());
174 Resumes.resize(ResumesLeft);
178 /// InsertUnwindResumeCalls - Convert the ResumeInsts that are still present
179 /// into calls to the appropriate _Unwind_Resume function.
180 bool DwarfEHPrepare::InsertUnwindResumeCalls(Function &Fn) {
181 SmallVector<ResumeInst*, 16> Resumes;
182 SmallVector<LandingPadInst*, 16> CleanupLPads;
183 for (BasicBlock &BB : Fn) {
184 if (auto *RI = dyn_cast<ResumeInst>(BB.getTerminator()))
185 Resumes.push_back(RI);
186 if (auto *LP = BB.getLandingPadInst())
188 CleanupLPads.push_back(LP);
194 LLVMContext &Ctx = Fn.getContext();
196 size_t ResumesLeft = pruneUnreachableResumes(Fn, Resumes, CleanupLPads);
197 if (ResumesLeft == 0)
198 return true; // We pruned them all.
200 // Find the rewind function if we didn't already.
201 if (!RewindFunction) {
202 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
203 Type::getInt8PtrTy(Ctx), false);
204 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
205 RewindFunction = Fn.getParent()->getOrInsertFunction(RewindName, FTy);
208 // Create the basic block where the _Unwind_Resume call will live.
209 if (ResumesLeft == 1) {
210 // Instead of creating a new BB and PHI node, just append the call to
211 // _Unwind_Resume to the end of the single resume block.
212 ResumeInst *RI = Resumes.front();
213 BasicBlock *UnwindBB = RI->getParent();
214 Value *ExnObj = GetExceptionObject(RI);
216 // Call the _Unwind_Resume function.
217 CallInst *CI = CallInst::Create(RewindFunction, ExnObj, "", UnwindBB);
218 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
220 // We never expect _Unwind_Resume to return.
221 new UnreachableInst(Ctx, UnwindBB);
225 BasicBlock *UnwindBB = BasicBlock::Create(Ctx, "unwind_resume", &Fn);
226 PHINode *PN = PHINode::Create(Type::getInt8PtrTy(Ctx), ResumesLeft,
227 "exn.obj", UnwindBB);
229 // Extract the exception object from the ResumeInst and add it to the PHI node
230 // that feeds the _Unwind_Resume call.
231 for (ResumeInst *RI : Resumes) {
232 BasicBlock *Parent = RI->getParent();
233 BranchInst::Create(UnwindBB, Parent);
235 Value *ExnObj = GetExceptionObject(RI);
236 PN->addIncoming(ExnObj, Parent);
241 // Call the function.
242 CallInst *CI = CallInst::Create(RewindFunction, PN, "", UnwindBB);
243 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
245 // We never expect _Unwind_Resume to return.
246 new UnreachableInst(Ctx, UnwindBB);
250 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
251 assert(TM && "DWARF EH preparation requires a target machine");
252 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
253 TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
254 bool Changed = InsertUnwindResumeCalls(Fn);