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