1 //===-- WinEHPrepare - 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 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.
15 //===----------------------------------------------------------------------===//
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"
31 using namespace llvm::PatternMatch;
33 #define DEBUG_TYPE "winehprepare"
36 class WinEHPrepare : public FunctionPass {
37 std::unique_ptr<FunctionPass> DwarfPrepare;
40 static char ID; // Pass identification, replacement for typeid.
41 WinEHPrepare(const TargetMachine *TM = nullptr)
42 : FunctionPass(ID), DwarfPrepare(createDwarfEHPass(TM)) {}
44 bool runOnFunction(Function &Fn) override;
46 bool doFinalization(Module &M) override;
48 void getAnalysisUsage(AnalysisUsage &AU) const override;
50 const char *getPassName() const override {
51 return "Windows exception handling preparation";
55 bool prepareCPPEHHandlers(Function &F,
56 SmallVectorImpl<LandingPadInst *> &LPads);
57 bool outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
58 LandingPadInst *LPad, StructType *EHDataStructTy);
61 class WinEHCatchDirector : public CloningDirector {
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() {}
69 CloningAction handleInstruction(ValueToValueMapTy &VMap,
70 const Instruction *Inst,
71 BasicBlock *NewBB) override;
75 Value *CurrentSelector;
80 const Value *ExtractedEHPtr;
81 const Value *ExtractedSelector;
82 const Value *EHPtrStoreAddr;
83 const Value *SelectorStoreAddr;
85 } // end anonymous namespace
87 char WinEHPrepare::ID = 0;
88 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
91 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
92 return new WinEHPrepare(TM);
95 static bool isMSVCPersonality(EHPersonality Pers) {
96 return Pers == EHPersonality::MSVC_Win64SEH ||
97 Pers == EHPersonality::MSVC_CXX;
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())
106 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
107 Resumes.push_back(Resume);
110 // No need to prepare functions that lack landing pads.
114 // Classify the personality to see what kind of preparation we need.
115 EHPersonality Pers = classifyEHPersonality(LPads.back()->getPersonalityFn());
117 // Delegate through to the DWARF pass if this is unrecognized.
118 if (!isMSVCPersonality(Pers))
119 return DwarfPrepare->runOnFunction(Fn);
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))
127 // FIXME: SEH Cleanups are unimplemented. Replace them with unreachable.
131 for (ResumeInst *Resume : Resumes) {
132 IRBuilder<>(Resume).CreateUnreachable();
133 Resume->eraseFromParent();
139 bool WinEHPrepare::doFinalization(Module &M) {
140 return DwarfPrepare->doFinalization(M);
143 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
144 DwarfPrepare->getAnalysisUsage(AU);
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;
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;
172 // If we've already outlined the handlers for this landingpad,
173 // there's nothing more to do here.
174 if (LPadHasActionList)
177 for (unsigned Idx = 0, NumClauses = LPad->getNumClauses(); Idx < NumClauses;
179 if (LPad->isCatch(Idx))
181 outlineCatchHandler(&F, LPad->getClause(Idx), LPad, EHDataStructTy);
182 } // End for each clause
183 } // End for each landingpad
185 return HandlersOutlined;
188 bool WinEHPrepare::outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
189 LandingPadInst *LPad,
190 StructType *EHDataStructTy) {
191 Module *M = SrcFn->getParent();
192 LLVMContext &Context = M->getContext();
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);
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());
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.
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())};
226 Builder.CreateCall(RecoverFrameFn, RecoverArgs, "eh.alloc");
228 Builder.CreateBitCast(EHAlloc, EHDataStructTy->getPointerTo(), "ehdata");
230 Builder.CreateConstInBoundsGEP2_32(EHData, 0, 1, "eh.obj.ptr");
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");
240 ValueToValueMapTy VMap;
242 // FIXME: Map other values referenced in the filter handler.
244 WinEHCatchDirector Director(LPad, SelectorType, EHObj);
246 SmallVector<ReturnInst *, 8> Returns;
247 ClonedCodeInfo InlinedFunctionInfo;
249 BasicBlock::iterator II = LPad;
251 CloneAndPruneIntoFromInst(CatchHandler, SrcFn, ++II, VMap,
252 /*ModuleLevelChanges=*/false, Returns, "",
253 &InlinedFunctionInfo,
254 SrcFn->getParent()->getDataLayout(), &Director);
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();
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");
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;
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
285 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
286 ExtractedSelector = Inst;
289 // Tell the caller not to clone this instruction.
290 return CloningDirector::SkipInstruction;
292 // Other extract value instructions just get cloned.
293 return CloningDirector::CloneInstruction;
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;
303 if (StoredValue == ExtractedSelector) {
304 SelectorStoreAddr = Store->getPointerOperand();
305 return CloningDirector::SkipInstruction;
308 // Any other store just gets cloned.
309 return CloningDirector::CloneInstruction;
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;
323 if (LoadAddr == SelectorStoreAddr) {
324 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
325 return CloningDirector::SkipInstruction;
328 // Any other loads just get cloned.
329 return CloningDirector::CloneInstruction;
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
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.
340 return CloningDirector::SkipInstruction;
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
348 // The end catch call can occur in one of two places: either in a
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;
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));
368 ReturnInst::Create(NewBB->getContext(),
369 BlockAddress::get(Branch->getSuccessor(0)), NewBB);
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;
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);
384 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
385 // Tell the caller not to clone this instruction.
386 return CloningDirector::SkipInstruction;
389 // Continue with the default cloning behavior.
390 return CloningDirector::CloneInstruction;