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