DataLayout is mandatory, update the API to reflect it with references.
[oota-llvm.git] / lib / CodeGen / DwarfEHPrepare.cpp
1 //===-- DwarfEHPrepare - Prepare exception handling for code generation ---===//
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 // This pass mulches exception handling code into a form adapted to code
11 // generation. Required if using dwarf exception handling.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
28 using namespace llvm;
29
30 #define DEBUG_TYPE "dwarfehprepare"
31
32 STATISTIC(NumResumesLowered, "Number of resume calls lowered");
33
34 namespace {
35   class DwarfEHPrepare : public FunctionPass {
36     const TargetMachine *TM;
37
38     // RewindFunction - _Unwind_Resume or the target equivalent.
39     Constant *RewindFunction;
40
41     DominatorTree *DT;
42     const TargetLowering *TLI;
43
44     bool InsertUnwindResumeCalls(Function &Fn);
45     Value *GetExceptionObject(ResumeInst *RI);
46     size_t
47     pruneUnreachableResumes(Function &Fn,
48                             SmallVectorImpl<ResumeInst *> &Resumes,
49                             SmallVectorImpl<LandingPadInst *> &CleanupLPads);
50
51   public:
52     static char ID; // Pass identification, replacement for typeid.
53
54     // INITIALIZE_TM_PASS requires a default constructor, but it isn't used in
55     // practice.
56     DwarfEHPrepare()
57         : FunctionPass(ID), TM(nullptr), RewindFunction(nullptr), DT(nullptr),
58           TLI(nullptr) {}
59
60     DwarfEHPrepare(const TargetMachine *TM)
61         : FunctionPass(ID), TM(TM), RewindFunction(nullptr), DT(nullptr),
62           TLI(nullptr) {}
63
64     bool runOnFunction(Function &Fn) override;
65
66     bool doFinalization(Module &M) override {
67       RewindFunction = nullptr;
68       return false;
69     }
70
71     void getAnalysisUsage(AnalysisUsage &AU) const override;
72
73     const char *getPassName() const override {
74       return "Exception handling preparation";
75     }
76   };
77 } // end anonymous namespace
78
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)
86
87 FunctionPass *llvm::createDwarfEHPass(const TargetMachine *TM) {
88   return new DwarfEHPrepare(TM);
89 }
90
91 void DwarfEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
92   AU.addRequired<TargetTransformInfoWrapperPass>();
93   AU.addRequired<DominatorTreeWrapperPass>();
94 }
95
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;
106
107   if (SelIVI) {
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));
114         EraseIVIs = true;
115       }
116     }
117   }
118
119   if (!ExnObj)
120     ExnObj = ExtractValueInst::Create(RI->getOperand(0), 0, "exn.obj", RI);
121
122   RI->eraseFromParent();
123
124   if (EraseIVIs) {
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();
131   }
132
133   return ExnObj;
134 }
135
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);
147         break;
148       }
149     }
150     ++ResumeIndex;
151   }
152
153   // If everything is reachable, there is no change.
154   if (ResumeReachable.all())
155     return Resumes.size();
156
157   const TargetTransformInfo &TTI =
158       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn);
159   LLVMContext &Ctx = Fn.getContext();
160
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;
167     } else {
168       BasicBlock *BB = RI->getParent();
169       new UnreachableInst(Ctx, RI);
170       RI->eraseFromParent();
171       SimplifyCFG(BB, TTI, 1);
172     }
173   }
174   Resumes.resize(ResumesLeft);
175   return ResumesLeft;
176 }
177
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())
187       if (LP->isCleanup())
188         CleanupLPads.push_back(LP);
189   }
190
191   if (Resumes.empty())
192     return false;
193
194   LLVMContext &Ctx = Fn.getContext();
195
196   size_t ResumesLeft = pruneUnreachableResumes(Fn, Resumes, CleanupLPads);
197   if (ResumesLeft == 0)
198     return true; // We pruned them all.
199
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);
206   }
207
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);
215
216     // Call the _Unwind_Resume function.
217     CallInst *CI = CallInst::Create(RewindFunction, ExnObj, "", UnwindBB);
218     CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
219
220     // We never expect _Unwind_Resume to return.
221     new UnreachableInst(Ctx, UnwindBB);
222     return true;
223   }
224
225   BasicBlock *UnwindBB = BasicBlock::Create(Ctx, "unwind_resume", &Fn);
226   PHINode *PN = PHINode::Create(Type::getInt8PtrTy(Ctx), ResumesLeft,
227                                 "exn.obj", UnwindBB);
228
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);
234
235     Value *ExnObj = GetExceptionObject(RI);
236     PN->addIncoming(ExnObj, Parent);
237
238     ++NumResumesLowered;
239   }
240
241   // Call the function.
242   CallInst *CI = CallInst::Create(RewindFunction, PN, "", UnwindBB);
243   CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
244
245   // We never expect _Unwind_Resume to return.
246   new UnreachableInst(Ctx, UnwindBB);
247   return true;
248 }
249
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);
255   DT = nullptr;
256   TLI = nullptr;
257   return Changed;
258 }