EH: Prune unreachable resume instructions during Dwarf EH preparation
[oota-llvm.git] / lib / CodeGen / WinEHPrepare.cpp
1 //===-- WinEHPrepare - 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 lowers LLVM IR exception handling into something closer to what the
11 // backend wants. It snifs the personality function to see which kind of
12 // preparation is necessary. If the personality function uses the Itanium LSDA,
13 // this pass delegates to the DWARF EH preparation pass.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/Analysis/LibCallSemantics.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Transforms/Utils/Cloning.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 #include <memory>
29
30 using namespace llvm;
31 using namespace llvm::PatternMatch;
32
33 #define DEBUG_TYPE "winehprepare"
34
35 namespace {
36 class WinEHPrepare : public FunctionPass {
37   std::unique_ptr<FunctionPass> DwarfPrepare;
38
39 public:
40   static char ID; // Pass identification, replacement for typeid.
41   WinEHPrepare(const TargetMachine *TM = nullptr)
42       : FunctionPass(ID), DwarfPrepare(createDwarfEHPass(TM)) {}
43
44   bool runOnFunction(Function &Fn) override;
45
46   bool doFinalization(Module &M) override;
47
48   void getAnalysisUsage(AnalysisUsage &AU) const override;
49
50   const char *getPassName() const override {
51     return "Windows exception handling preparation";
52   }
53
54 private:
55   bool prepareCPPEHHandlers(Function &F,
56                             SmallVectorImpl<LandingPadInst *> &LPads);
57   bool outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
58                            LandingPadInst *LPad, StructType *EHDataStructTy);
59 };
60
61 class WinEHCatchDirector : public CloningDirector {
62 public:
63   WinEHCatchDirector(LandingPadInst *LPI, Value *Selector, Value *EHObj)
64       : LPI(LPI), CurrentSelector(Selector->stripPointerCasts()), EHObj(EHObj),
65         SelectorIDType(Type::getInt32Ty(LPI->getContext())),
66         Int8PtrType(Type::getInt8PtrTy(LPI->getContext())) {}
67
68   CloningAction handleInstruction(ValueToValueMapTy &VMap,
69                                   const Instruction *Inst,
70                                   BasicBlock *NewBB) override;
71
72 private:
73   LandingPadInst *LPI;
74   Value *CurrentSelector;
75   Value *EHObj;
76   Type *SelectorIDType;
77   Type *Int8PtrType;
78
79   const Value *ExtractedEHPtr;
80   const Value *ExtractedSelector;
81   const Value *EHPtrStoreAddr;
82   const Value *SelectorStoreAddr;
83 };
84 } // end anonymous namespace
85
86 char WinEHPrepare::ID = 0;
87 INITIALIZE_TM_PASS_BEGIN(WinEHPrepare, "winehprepare",
88                          "Prepare Windows exceptions", false, false)
89 INITIALIZE_PASS_DEPENDENCY(DwarfEHPrepare)
90 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
91 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
92 INITIALIZE_TM_PASS_END(WinEHPrepare, "winehprepare",
93                        "Prepare Windows exceptions", false, false)
94
95 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
96   return new WinEHPrepare(TM);
97 }
98
99 static bool isMSVCPersonality(EHPersonality Pers) {
100   return Pers == EHPersonality::MSVC_Win64SEH ||
101          Pers == EHPersonality::MSVC_CXX;
102 }
103
104 bool WinEHPrepare::runOnFunction(Function &Fn) {
105   SmallVector<LandingPadInst *, 4> LPads;
106   SmallVector<ResumeInst *, 4> Resumes;
107   for (BasicBlock &BB : Fn) {
108     if (auto *LP = BB.getLandingPadInst())
109       LPads.push_back(LP);
110     if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
111       Resumes.push_back(Resume);
112   }
113
114   // No need to prepare functions that lack landing pads.
115   if (LPads.empty())
116     return false;
117
118   // Classify the personality to see what kind of preparation we need.
119   EHPersonality Pers = classifyEHPersonality(LPads.back()->getPersonalityFn());
120
121   // Delegate through to the DWARF pass if this is unrecognized.
122   if (!isMSVCPersonality(Pers)) {
123     // Use the resolver from our pass manager in the dwarf pass.
124     assert(getResolver());
125     DwarfPrepare->setResolver(getResolver());
126     return DwarfPrepare->runOnFunction(Fn);
127   }
128
129   // FIXME: This only returns true if the C++ EH handlers were outlined.
130   //        When that code is complete, it should always return whatever
131   //        prepareCPPEHHandlers returns.
132   if (Pers == EHPersonality::MSVC_CXX && prepareCPPEHHandlers(Fn, LPads))
133     return true;
134
135   // FIXME: SEH Cleanups are unimplemented. Replace them with unreachable.
136   if (Resumes.empty())
137     return false;
138
139   for (ResumeInst *Resume : Resumes) {
140     IRBuilder<>(Resume).CreateUnreachable();
141     Resume->eraseFromParent();
142   }
143
144   return true;
145 }
146
147 bool WinEHPrepare::doFinalization(Module &M) {
148   return DwarfPrepare->doFinalization(M);
149 }
150
151 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
152   DwarfPrepare->getAnalysisUsage(AU);
153 }
154
155 bool WinEHPrepare::prepareCPPEHHandlers(
156     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
157   // FIXME: Find all frame variable references in the handlers
158   //        to populate the structure elements.
159   SmallVector<Type *, 2> AllocStructTys;
160   AllocStructTys.push_back(Type::getInt32Ty(F.getContext()));   // EH state
161   AllocStructTys.push_back(Type::getInt8PtrTy(F.getContext())); // EH object
162   StructType *EHDataStructTy =
163       StructType::create(F.getContext(), AllocStructTys, 
164                          "struct." + F.getName().str() + ".ehdata");
165   bool HandlersOutlined = false;
166
167   for (LandingPadInst *LPad : LPads) {
168     // Look for evidence that this landingpad has already been processed.
169     bool LPadHasActionList = false;
170     BasicBlock *LPadBB = LPad->getParent();
171     for (Instruction &Inst : LPadBB->getInstList()) {
172       // FIXME: Make this an intrinsic.
173       if (auto *Call = dyn_cast<CallInst>(&Inst))
174         if (Call->getCalledFunction()->getName() == "llvm.eh.actions") {
175           LPadHasActionList = true;
176           break;
177         }
178     }
179
180     // If we've already outlined the handlers for this landingpad,
181     // there's nothing more to do here.
182     if (LPadHasActionList)
183       continue;
184
185     for (unsigned Idx = 0, NumClauses = LPad->getNumClauses(); Idx < NumClauses;
186          ++Idx) {
187       if (LPad->isCatch(Idx))
188         HandlersOutlined =
189             outlineCatchHandler(&F, LPad->getClause(Idx), LPad, EHDataStructTy);
190     } // End for each clause
191   }   // End for each landingpad
192
193   return HandlersOutlined;
194 }
195
196 bool WinEHPrepare::outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
197                                        LandingPadInst *LPad,
198                                        StructType *EHDataStructTy) {
199   Module *M = SrcFn->getParent();
200   LLVMContext &Context = M->getContext();
201
202   // Create a new function to receive the handler contents.
203   Type *Int8PtrType = Type::getInt8PtrTy(Context);
204   std::vector<Type *> ArgTys;
205   ArgTys.push_back(Int8PtrType);
206   ArgTys.push_back(Int8PtrType);
207   FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
208   Function *CatchHandler = Function::Create(
209       FnType, GlobalVariable::ExternalLinkage, SrcFn->getName() + ".catch", M);
210
211   // Generate a standard prolog to setup the frame recovery structure.
212   IRBuilder<> Builder(Context);
213   BasicBlock *Entry = BasicBlock::Create(Context, "catch.entry");
214   CatchHandler->getBasicBlockList().push_front(Entry);
215   Builder.SetInsertPoint(Entry);
216   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
217
218   // The outlined handler will be called with the parent's frame pointer as
219   // its second argument. To enable the handler to access variables from
220   // the parent frame, we use that pointer to get locate a special block
221   // of memory that was allocated using llvm.eh.allocateframe for this
222   // purpose.  During the outlining process we will determine which frame
223   // variables are used in handlers and create a structure that maps these
224   // variables into the frame allocation block.
225   //
226   // The frame allocation block also contains an exception state variable
227   // used by the runtime and a pointer to the exception object pointer
228   // which will be filled in by the runtime for use in the handler.
229   Function *RecoverFrameFn =
230       Intrinsic::getDeclaration(M, Intrinsic::framerecover);
231   Value *RecoverArgs[] = {Builder.CreateBitCast(SrcFn, Int8PtrType, ""),
232                           &(CatchHandler->getArgumentList().back())};
233   CallInst *EHAlloc =
234       Builder.CreateCall(RecoverFrameFn, RecoverArgs, "eh.alloc");
235   Value *EHData =
236       Builder.CreateBitCast(EHAlloc, EHDataStructTy->getPointerTo(), "ehdata");
237   Value *EHObjPtr =
238       Builder.CreateConstInBoundsGEP2_32(EHData, 0, 1, "eh.obj.ptr");
239
240   // This will give us a raw pointer to the exception object, which
241   // corresponds to the formal parameter of the catch statement.  If the
242   // handler uses this object, we will generate code during the outlining
243   // process to cast the pointer to the appropriate type and deference it
244   // as necessary.  The un-outlined landing pad code represents the
245   // exception object as the result of the llvm.eh.begincatch call.
246   Value *EHObj = Builder.CreateLoad(EHObjPtr, false, "eh.obj");
247
248   ValueToValueMapTy VMap;
249
250   // FIXME: Map other values referenced in the filter handler.
251
252   WinEHCatchDirector Director(LPad, SelectorType, EHObj);
253
254   SmallVector<ReturnInst *, 8> Returns;
255   ClonedCodeInfo InlinedFunctionInfo;
256
257   BasicBlock::iterator II = LPad;
258
259   CloneAndPruneIntoFromInst(CatchHandler, SrcFn, ++II, VMap,
260                             /*ModuleLevelChanges=*/false, Returns, "",
261                             &InlinedFunctionInfo,
262                             SrcFn->getParent()->getDataLayout(), &Director);
263
264   // Move all the instructions in the first cloned block into our entry block.
265   BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
266   Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
267   FirstClonedBB->eraseFromParent();
268
269   return true;
270 }
271
272 CloningDirector::CloningAction WinEHCatchDirector::handleInstruction(
273     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
274   // Intercept instructions which extract values from the landing pad aggregate.
275   if (auto *Extract = dyn_cast<ExtractValueInst>(Inst)) {
276     if (Extract->getAggregateOperand() == LPI) {
277       assert(Extract->getNumIndices() == 1 &&
278              "Unexpected operation: extracting both landing pad values");
279       assert((*(Extract->idx_begin()) == 0 || *(Extract->idx_begin()) == 1) &&
280              "Unexpected operation: extracting an unknown landing pad element");
281
282       if (*(Extract->idx_begin()) == 0) {
283         // Element 0 doesn't directly corresponds to anything in the WinEH scheme.
284         // It will be stored to a memory location, then later loaded and finally
285         // the loaded value will be used as the argument to an llvm.eh.begincatch
286         // call.  We're tracking it here so that we can skip the store and load.
287         ExtractedEHPtr = Inst;
288       } else {
289         // Element 1 corresponds to the filter selector.  We'll map it to 1 for
290         // matching purposes, but it will also probably be stored to memory and
291         // reloaded, so we need to track the instuction so that we can map the
292         // loaded value too.
293         VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
294         ExtractedSelector = Inst;
295       }
296
297       // Tell the caller not to clone this instruction.
298       return CloningDirector::SkipInstruction;
299     }
300     // Other extract value instructions just get cloned.
301     return CloningDirector::CloneInstruction;
302   }
303
304   if (auto *Store = dyn_cast<StoreInst>(Inst)) {
305     // Look for and suppress stores of the extracted landingpad values.
306     const Value *StoredValue = Store->getValueOperand();
307     if (StoredValue == ExtractedEHPtr) {
308       EHPtrStoreAddr = Store->getPointerOperand();
309       return CloningDirector::SkipInstruction;
310     }
311     if (StoredValue == ExtractedSelector) {
312       SelectorStoreAddr = Store->getPointerOperand();
313       return CloningDirector::SkipInstruction;
314     }
315
316     // Any other store just gets cloned.
317     return CloningDirector::CloneInstruction;
318   }
319
320   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
321     // Look for loads of (previously suppressed) landingpad values.
322     // The EHPtr load can be ignored (it should only be used as
323     // an argument to llvm.eh.begincatch), but the selector value
324     // needs to be mapped to a constant value of 1 to be used to
325     // simplify the branching to always flow to the current handler.
326     const Value *LoadAddr = Load->getPointerOperand();
327     if (LoadAddr == EHPtrStoreAddr) {
328       VMap[Inst] = UndefValue::get(Int8PtrType);
329       return CloningDirector::SkipInstruction;
330     }
331     if (LoadAddr == SelectorStoreAddr) {
332       VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
333       return CloningDirector::SkipInstruction;
334     }
335
336     // Any other loads just get cloned.
337     return CloningDirector::CloneInstruction;
338   }
339
340   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) {
341     // The argument to the call is some form of the first element of the
342     // landingpad aggregate value, but that doesn't matter.  It isn't used
343     // here.
344     // The return value of this instruction, however, is used to access the
345     // EH object pointer.  We have generated an instruction to get that value
346     // from the EH alloc block, so we can just map to that here.
347     VMap[Inst] = EHObj;
348     return CloningDirector::SkipInstruction;
349   }
350   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) {
351     auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
352     // It might be interesting to track whether or not we are inside a catch
353     // function, but that might make the algorithm more brittle than it needs
354     // to be.
355
356     // The end catch call can occur in one of two places: either in a
357     // landingpad
358     // block that is part of the catch handlers exception mechanism, or at the
359     // end of the catch block.  If it occurs in a landing pad, we must skip it
360     // and continue so that the landing pad gets cloned.
361     // FIXME: This case isn't fully supported yet and shouldn't turn up in any
362     //        of the test cases until it is.
363     if (IntrinCall->getParent()->isLandingPad())
364       return CloningDirector::SkipInstruction;
365
366     // If an end catch occurs anywhere else the next instruction should be an
367     // unconditional branch instruction that we want to replace with a return
368     // to the the address of the branch target.
369     const BasicBlock *EndCatchBB = IntrinCall->getParent();
370     const TerminatorInst *Terminator = EndCatchBB->getTerminator();
371     const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
372     assert(Branch && Branch->isUnconditional());
373     assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
374             BasicBlock::const_iterator(Branch));
375
376     ReturnInst::Create(NewBB->getContext(),
377                         BlockAddress::get(Branch->getSuccessor(0)), NewBB);
378
379     // We just added a terminator to the cloned block.
380     // Tell the caller to stop processing the current basic block so that
381     // the branch instruction will be skipped.
382     return CloningDirector::StopCloningBB;
383   }
384   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) {
385     auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
386     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
387     // This causes a replacement that will collapse the landing pad CFG based
388     // on the filter function we intend to match.
389     if (Selector == CurrentSelector)
390       VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
391     else
392       VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
393     // Tell the caller not to clone this instruction.
394     return CloningDirector::SkipInstruction;
395   }
396
397   // Continue with the default cloning behavior.
398   return CloningDirector::CloneInstruction;
399 }