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/ADT/MapVector.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/TinyPtrVector.h"
22 #include "llvm/Analysis/LibCallSemantics.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Cloning.h"
35 #include "llvm/Transforms/Utils/Local.h"
39 using namespace llvm::PatternMatch;
41 #define DEBUG_TYPE "winehprepare"
45 // This map is used to model frame variable usage during outlining, to
46 // construct a structure type to hold the frame variables in a frame
47 // allocation block, and to remap the frame variable allocas (including
48 // spill locations as needed) to GEPs that get the variable from the
49 // frame allocation structure.
50 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
52 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
54 enum ActionType { Catch, Cleanup };
56 class LandingPadActions;
62 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
63 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
65 class WinEHPrepare : public FunctionPass {
66 std::unique_ptr<FunctionPass> DwarfPrepare;
69 static char ID; // Pass identification, replacement for typeid.
70 WinEHPrepare(const TargetMachine *TM = nullptr)
71 : FunctionPass(ID), DwarfPrepare(createDwarfEHPass(TM)) {}
73 bool runOnFunction(Function &Fn) override;
75 bool doFinalization(Module &M) override;
77 void getAnalysisUsage(AnalysisUsage &AU) const override;
79 const char *getPassName() const override {
80 return "Windows exception handling preparation";
84 bool prepareCPPEHHandlers(Function &F,
85 SmallVectorImpl<LandingPadInst *> &LPads);
86 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
87 LandingPadInst *LPad, BasicBlock *StartBB,
88 FrameVarInfoMap &VarInfo);
90 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
91 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
92 VisitedBlockSet &VisitedBlocks);
93 CleanupHandler *findCleanupHandler(BasicBlock *StartBB, BasicBlock *EndBB);
95 CatchHandlerMapTy CatchHandlerMap;
96 CleanupHandlerMapTy CleanupHandlerMap;
97 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
100 class WinEHFrameVariableMaterializer : public ValueMaterializer {
102 WinEHFrameVariableMaterializer(Function *OutlinedFn,
103 FrameVarInfoMap &FrameVarInfo);
104 ~WinEHFrameVariableMaterializer() {}
106 virtual Value *materializeValueFor(Value *V) override;
109 FrameVarInfoMap &FrameVarInfo;
113 class LandingPadMap {
115 LandingPadMap() : OriginLPad(nullptr) {}
116 void mapLandingPad(const LandingPadInst *LPad);
118 bool isInitialized() { return OriginLPad != nullptr; }
120 bool mapIfEHPtrLoad(const LoadInst *Load) {
121 return mapIfEHLoad(Load, EHPtrStores, EHPtrStoreAddrs);
123 bool mapIfSelectorLoad(const LoadInst *Load) {
124 return mapIfEHLoad(Load, SelectorStores, SelectorStoreAddrs);
127 bool isLandingPadSpecificInst(const Instruction *Inst) const;
129 void remapSelector(ValueToValueMapTy &VMap, Value *MappedValue) const;
132 bool mapIfEHLoad(const LoadInst *Load,
133 SmallVectorImpl<const StoreInst *> &Stores,
134 SmallVectorImpl<const Value *> &StoreAddrs);
136 const LandingPadInst *OriginLPad;
137 // We will normally only see one of each of these instructions, but
138 // if more than one occurs for some reason we can handle that.
139 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
140 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
142 // In optimized code, there will typically be at most one instance of
143 // each of the following, but in unoptimized IR it is not uncommon
144 // for the values to be stored, loaded and then stored again. In that
145 // case we will create a second entry for each store and store address.
146 SmallVector<const StoreInst *, 2> EHPtrStores;
147 SmallVector<const StoreInst *, 2> SelectorStores;
148 SmallVector<const Value *, 2> EHPtrStoreAddrs;
149 SmallVector<const Value *, 2> SelectorStoreAddrs;
152 class WinEHCloningDirectorBase : public CloningDirector {
154 WinEHCloningDirectorBase(Function *HandlerFn,
155 FrameVarInfoMap &VarInfo,
156 LandingPadMap &LPadMap)
157 : Materializer(HandlerFn, VarInfo),
158 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
159 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
162 CloningAction handleInstruction(ValueToValueMapTy &VMap,
163 const Instruction *Inst,
164 BasicBlock *NewBB) override;
166 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
167 const Instruction *Inst,
168 BasicBlock *NewBB) = 0;
169 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
170 const Instruction *Inst,
171 BasicBlock *NewBB) = 0;
172 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
173 const Instruction *Inst,
174 BasicBlock *NewBB) = 0;
175 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
176 const InvokeInst *Invoke,
177 BasicBlock *NewBB) = 0;
178 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
179 const ResumeInst *Resume,
180 BasicBlock *NewBB) = 0;
182 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
185 WinEHFrameVariableMaterializer Materializer;
186 Type *SelectorIDType;
188 LandingPadMap &LPadMap;
191 class WinEHCatchDirector : public WinEHCloningDirectorBase {
193 WinEHCatchDirector(Function *CatchFn, Value *Selector,
194 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
195 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
196 CurrentSelector(Selector->stripPointerCasts()),
197 ExceptionObjectVar(nullptr) {}
199 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
200 const Instruction *Inst,
201 BasicBlock *NewBB) override;
202 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
203 BasicBlock *NewBB) override;
204 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
205 const Instruction *Inst,
206 BasicBlock *NewBB) override;
207 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
208 BasicBlock *NewBB) override;
209 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
210 BasicBlock *NewBB) override;
212 const Value *getExceptionVar() { return ExceptionObjectVar; }
213 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
216 Value *CurrentSelector;
218 const Value *ExceptionObjectVar;
219 TinyPtrVector<BasicBlock *> ReturnTargets;
222 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
224 WinEHCleanupDirector(Function *CleanupFn,
225 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
226 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
228 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
229 const Instruction *Inst,
230 BasicBlock *NewBB) override;
231 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
232 BasicBlock *NewBB) override;
233 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
234 const Instruction *Inst,
235 BasicBlock *NewBB) override;
236 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
237 BasicBlock *NewBB) override;
238 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
239 BasicBlock *NewBB) override;
242 class ActionHandler {
244 ActionHandler(BasicBlock *BB, ActionType Type)
245 : StartBB(BB), Type(Type), OutlinedFn(nullptr) {}
247 ActionType getType() const { return Type; }
248 BasicBlock *getStartBlock() const { return StartBB; }
250 bool hasBeenOutlined() { return OutlinedFn != nullptr; }
252 void setOutlinedFunction(Function *F) { OutlinedFn = F; }
253 Function *getOutlinedFunction() { return OutlinedFn; }
258 Function *OutlinedFn;
261 class CatchHandler : public ActionHandler {
263 CatchHandler(BasicBlock *BB, Constant *Selector, BasicBlock *NextBB)
264 : Selector(Selector), NextBB(NextBB), ExceptionObjectVar(nullptr),
265 ActionHandler(BB, ActionType::Catch) {}
267 // Method for support type inquiry through isa, cast, and dyn_cast:
268 static inline bool classof(const ActionHandler *H) {
269 return H->getType() == ActionType::Catch;
272 Constant *getSelector() const { return Selector; }
273 BasicBlock *getNextBB() const { return NextBB; }
275 const Value *getExceptionVar() { return ExceptionObjectVar; }
276 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
278 void setExceptionVar(const Value *Val) { ExceptionObjectVar = Val; }
279 void setReturnTargets(TinyPtrVector<BasicBlock *> &Targets) {
280 ReturnTargets = Targets;
286 const Value *ExceptionObjectVar;
287 TinyPtrVector<BasicBlock *> ReturnTargets;
290 class CleanupHandler : public ActionHandler {
292 CleanupHandler(BasicBlock *BB) : ActionHandler(BB, ActionType::Cleanup) {}
294 // Method for support type inquiry through isa, cast, and dyn_cast:
295 static inline bool classof(const ActionHandler *H) {
296 return H->getType() == ActionType::Cleanup;
300 class LandingPadActions {
302 LandingPadActions() : HasCleanupHandlers(false) {}
304 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
305 void insertCleanupHandler(CleanupHandler *Action) {
306 Actions.push_back(Action);
307 HasCleanupHandlers = true;
310 bool includesCleanup() const { return HasCleanupHandlers; }
312 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
313 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
316 // Note that this class does not own the ActionHandler objects in this vector.
317 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
318 // in the WinEHPrepare class.
319 SmallVector<ActionHandler *, 4> Actions;
320 bool HasCleanupHandlers;
323 } // end anonymous namespace
325 char WinEHPrepare::ID = 0;
326 INITIALIZE_TM_PASS_BEGIN(WinEHPrepare, "winehprepare",
327 "Prepare Windows exceptions", false, false)
328 INITIALIZE_PASS_DEPENDENCY(DwarfEHPrepare)
329 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
330 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
331 INITIALIZE_TM_PASS_END(WinEHPrepare, "winehprepare",
332 "Prepare Windows exceptions", false, false)
334 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
335 return new WinEHPrepare(TM);
338 static bool isMSVCPersonality(EHPersonality Pers) {
339 return Pers == EHPersonality::MSVC_Win64SEH ||
340 Pers == EHPersonality::MSVC_CXX;
343 bool WinEHPrepare::runOnFunction(Function &Fn) {
344 SmallVector<LandingPadInst *, 4> LPads;
345 SmallVector<ResumeInst *, 4> Resumes;
346 for (BasicBlock &BB : Fn) {
347 if (auto *LP = BB.getLandingPadInst())
349 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
350 Resumes.push_back(Resume);
353 // No need to prepare functions that lack landing pads.
357 // Classify the personality to see what kind of preparation we need.
358 EHPersonality Pers = classifyEHPersonality(LPads.back()->getPersonalityFn());
360 // Delegate through to the DWARF pass if this is unrecognized.
361 if (!isMSVCPersonality(Pers)) {
362 if (!DwarfPrepare->getResolver()) {
363 // Build an AnalysisResolver with the analyses needed by DwarfEHPrepare.
364 // It will take ownership of the AnalysisResolver.
365 assert(getResolver());
366 auto *AR = new AnalysisResolver(getResolver()->getPMDataManager());
367 AR->addAnalysisImplsPair(
368 &TargetTransformInfoWrapperPass::ID,
369 getResolver()->findImplPass(&TargetTransformInfoWrapperPass::ID));
370 AR->addAnalysisImplsPair(
371 &DominatorTreeWrapperPass::ID,
372 getResolver()->findImplPass(&DominatorTreeWrapperPass::ID));
373 DwarfPrepare->setResolver(AR);
376 return DwarfPrepare->runOnFunction(Fn);
379 // FIXME: This only returns true if the C++ EH handlers were outlined.
380 // When that code is complete, it should always return whatever
381 // prepareCPPEHHandlers returns.
382 if (Pers == EHPersonality::MSVC_CXX && prepareCPPEHHandlers(Fn, LPads))
385 // FIXME: SEH Cleanups are unimplemented. Replace them with unreachable.
389 for (ResumeInst *Resume : Resumes) {
390 IRBuilder<>(Resume).CreateUnreachable();
391 Resume->eraseFromParent();
397 bool WinEHPrepare::doFinalization(Module &M) {
398 return DwarfPrepare->doFinalization(M);
401 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
402 DwarfPrepare->getAnalysisUsage(AU);
405 bool WinEHPrepare::prepareCPPEHHandlers(
406 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
407 // These containers are used to re-map frame variables that are used in
408 // outlined catch and cleanup handlers. They will be populated as the
409 // handlers are outlined.
410 FrameVarInfoMap FrameVarInfo;
412 bool HandlersOutlined = false;
414 Module *M = F.getParent();
415 LLVMContext &Context = M->getContext();
417 // FIXME: Make this an intrinsic.
418 // Create a new function to receive the handler contents.
419 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
420 Type *Int32Type = Type::getInt32Ty(Context);
421 FunctionType *ActionTy = FunctionType::get(Int8PtrType, true);
422 Value *ActionIntrin = M->getOrInsertFunction("llvm.eh.actions", ActionTy);
424 for (LandingPadInst *LPad : LPads) {
425 // Look for evidence that this landingpad has already been processed.
426 bool LPadHasActionList = false;
427 BasicBlock *LPadBB = LPad->getParent();
428 for (Instruction &Inst : LPadBB->getInstList()) {
429 // FIXME: Make this an intrinsic.
430 if (auto *Call = dyn_cast<CallInst>(&Inst)) {
431 if (Call->getCalledFunction()->getName() == "llvm.eh.actions") {
432 LPadHasActionList = true;
436 // FIXME: This is here to help with the development of nested landing pad
437 // outlining. It should be removed when that is finished.
438 if (isa<UnreachableInst>(Inst)) {
439 LPadHasActionList = true;
444 // If we've already outlined the handlers for this landingpad,
445 // there's nothing more to do here.
446 if (LPadHasActionList)
449 LandingPadActions Actions;
450 mapLandingPadBlocks(LPad, Actions);
452 for (ActionHandler *Action : Actions) {
453 if (Action->hasBeenOutlined())
455 BasicBlock *StartBB = Action->getStartBlock();
456 if (outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo)) {
457 HandlersOutlined = true;
459 } // End for each Action
461 // FIXME: We need a guard against partially outlined functions.
462 if (!HandlersOutlined)
465 // Replace the landing pad with a new llvm.eh.action based landing pad.
466 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
467 assert(!isa<PHINode>(LPadBB->begin()));
468 Instruction *NewLPad = LPad->clone();
469 NewLPadBB->getInstList().push_back(NewLPad);
470 while (!pred_empty(LPadBB)) {
471 auto *pred = *pred_begin(LPadBB);
472 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
473 Invoke->setUnwindDest(NewLPadBB);
476 // Add a call to describe the actions for this landing pad.
477 std::vector<Value *> ActionArgs;
478 ActionArgs.push_back(NewLPad);
479 for (ActionHandler *Action : Actions) {
480 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
481 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
482 ActionArgs.push_back(CatchAction->getSelector());
483 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
485 ActionArgs.push_back(EHObj);
487 ActionArgs.push_back(ConstantPointerNull::get(Int8PtrType));
489 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
491 Constant *HandlerPtr =
492 ConstantExpr::getBitCast(Action->getOutlinedFunction(), Int8PtrType);
493 ActionArgs.push_back(HandlerPtr);
496 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
498 // Add an indirect branch listing possible successors of the catch handlers.
499 IndirectBrInst *Branch = IndirectBrInst::Create(Recover, 0, NewLPadBB);
500 for (ActionHandler *Action : Actions) {
501 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
502 for (auto *Target : CatchAction->getReturnTargets()) {
503 Branch->addDestination(Target);
507 } // End for each landingpad
509 // If nothing got outlined, there is no more processing to be done.
510 if (!HandlersOutlined)
513 // Delete any blocks that were only used by handlers that were outlined above.
514 removeUnreachableBlocks(F);
516 BasicBlock *Entry = &F.getEntryBlock();
517 IRBuilder<> Builder(F.getParent()->getContext());
518 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
520 Function *FrameEscapeFn =
521 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
522 Function *RecoverFrameFn =
523 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
525 // Finally, replace all of the temporary allocas for frame variables used in
526 // the outlined handlers with calls to llvm.framerecover.
527 BasicBlock::iterator II = Entry->getFirstInsertionPt();
528 Instruction *AllocaInsertPt = II;
529 SmallVector<Value *, 8> AllocasToEscape;
530 for (auto &VarInfoEntry : FrameVarInfo) {
531 Value *ParentVal = VarInfoEntry.first;
532 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
534 // If the mapped value isn't already an alloca, we need to spill it if it
535 // is a computed value or copy it if it is an argument.
536 AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
538 if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
539 // Lower this argument to a copy and then demote that to the stack.
540 // We can't just use the argument location because the handler needs
541 // it to be in the frame allocation block.
542 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
543 Value *TrueValue = ConstantInt::getTrue(Context);
544 Value *UndefValue = UndefValue::get(Arg->getType());
546 SelectInst::Create(TrueValue, Arg, UndefValue,
547 Arg->getName() + ".tmp", AllocaInsertPt);
548 Arg->replaceAllUsesWith(SI);
549 // Reset the select operand, because it was clobbered by the RAUW above.
550 SI->setOperand(1, Arg);
551 ParentAlloca = DemoteRegToStack(*SI, true, SI);
552 } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
553 ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
555 Instruction *ParentInst = cast<Instruction>(ParentVal);
556 // FIXME: This is a work-around to temporarily handle the case where an
557 // instruction that is only used in handlers is not sunk.
558 // Without uses, DemoteRegToStack would just eliminate the value.
559 // This will fail if ParentInst is an invoke.
560 if (ParentInst->getNumUses() == 0) {
561 BasicBlock::iterator InsertPt = ParentInst;
564 new AllocaInst(ParentInst->getType(), nullptr,
565 ParentInst->getName() + ".reg2mem", InsertPt);
566 new StoreInst(ParentInst, ParentAlloca, InsertPt);
568 ParentAlloca = DemoteRegToStack(*ParentInst, true, ParentInst);
573 // If the parent alloca is no longer used and only one of the handlers used
574 // it, erase the parent and leave the copy in the outlined handler.
575 if (ParentAlloca->getNumUses() == 0 && Allocas.size() == 1) {
576 ParentAlloca->eraseFromParent();
580 // Add this alloca to the list of things to escape.
581 AllocasToEscape.push_back(ParentAlloca);
583 // Next replace all outlined allocas that are mapped to it.
584 for (AllocaInst *TempAlloca : Allocas) {
585 Function *HandlerFn = TempAlloca->getParent()->getParent();
586 // FIXME: Sink this GEP into the blocks where it is used.
587 Builder.SetInsertPoint(TempAlloca);
588 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
589 Value *RecoverArgs[] = {
590 Builder.CreateBitCast(&F, Int8PtrType, ""),
591 &(HandlerFn->getArgumentList().back()),
592 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
593 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
594 // Add a pointer bitcast if the alloca wasn't an i8.
595 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
596 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
598 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
600 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
601 TempAlloca->removeFromParent();
602 RecoveredAlloca->takeName(TempAlloca);
605 } // End for each FrameVarInfo entry.
607 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
609 Builder.SetInsertPoint(&F.getEntryBlock().back());
610 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
612 // Clean up the handler action maps we created for this function
613 DeleteContainerSeconds(CatchHandlerMap);
614 CatchHandlerMap.clear();
615 DeleteContainerSeconds(CleanupHandlerMap);
616 CleanupHandlerMap.clear();
618 return HandlersOutlined;
621 // This function examines a block to determine whether the block ends with a
622 // conditional branch to a catch handler based on a selector comparison.
623 // This function is used both by the WinEHPrepare::findSelectorComparison() and
624 // WinEHCleanupDirector::handleTypeIdFor().
625 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
626 Constant *&Selector, BasicBlock *&NextBB) {
627 ICmpInst::Predicate Pred;
628 BasicBlock *TBB, *FBB;
631 if (!match(BB->getTerminator(),
632 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
636 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
637 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
640 if (Pred == CmpInst::ICMP_EQ) {
646 if (Pred == CmpInst::ICMP_NE) {
655 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
656 LandingPadInst *LPad, BasicBlock *StartBB,
657 FrameVarInfoMap &VarInfo) {
658 Module *M = SrcFn->getParent();
659 LLVMContext &Context = M->getContext();
661 // Create a new function to receive the handler contents.
662 Type *Int8PtrType = Type::getInt8PtrTy(Context);
663 std::vector<Type *> ArgTys;
664 ArgTys.push_back(Int8PtrType);
665 ArgTys.push_back(Int8PtrType);
667 if (Action->getType() == Catch) {
668 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
669 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
670 SrcFn->getName() + ".catch", M);
672 FunctionType *FnType =
673 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
674 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
675 SrcFn->getName() + ".cleanup", M);
678 // Generate a standard prolog to setup the frame recovery structure.
679 IRBuilder<> Builder(Context);
680 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
681 Handler->getBasicBlockList().push_front(Entry);
682 Builder.SetInsertPoint(Entry);
683 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
685 std::unique_ptr<WinEHCloningDirectorBase> Director;
687 ValueToValueMapTy VMap;
689 LandingPadMap &LPadMap = LPadMaps[LPad];
690 if (!LPadMap.isInitialized())
691 LPadMap.mapLandingPad(LPad);
692 if (Action->getType() == Catch) {
693 Constant *SelectorType = cast<CatchHandler>(Action)->getSelector();
695 new WinEHCatchDirector(Handler, SelectorType, VarInfo, LPadMap));
696 LPadMap.remapSelector(VMap, ConstantInt::get( Type::getInt32Ty(Context), 1));
698 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
701 SmallVector<ReturnInst *, 8> Returns;
702 ClonedCodeInfo OutlinedFunctionInfo;
704 // Skip over PHIs and, if applicable, landingpad instructions.
705 BasicBlock::iterator II = StartBB->getFirstInsertionPt();
707 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
708 /*ModuleLevelChanges=*/false, Returns, "",
709 &OutlinedFunctionInfo, Director.get());
711 // Move all the instructions in the first cloned block into our entry block.
712 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
713 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
714 FirstClonedBB->eraseFromParent();
716 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
717 WinEHCatchDirector *CatchDirector =
718 reinterpret_cast<WinEHCatchDirector *>(Director.get());
719 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
720 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
723 Action->setOutlinedFunction(Handler);
728 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
729 // Each instance of this class should only ever be used to map a single
731 assert(OriginLPad == nullptr || OriginLPad == LPad);
733 // If the landing pad has already been mapped, there's nothing more to do.
734 if (OriginLPad == LPad)
739 // The landingpad instruction returns an aggregate value. Typically, its
740 // value will be passed to a pair of extract value instructions and the
741 // results of those extracts are often passed to store instructions.
742 // In unoptimized code the stored value will often be loaded and then stored
744 for (auto *U : LPad->users()) {
745 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
748 assert(Extract->getNumIndices() == 1 &&
749 "Unexpected operation: extracting both landing pad values");
750 unsigned int Idx = *(Extract->idx_begin());
751 assert((Idx == 0 || Idx == 1) &&
752 "Unexpected operation: extracting an unknown landing pad element");
754 // Element 0 doesn't directly corresponds to anything in the WinEH
756 // It will be stored to a memory location, then later loaded and finally
757 // the loaded value will be used as the argument to an
758 // llvm.eh.begincatch
759 // call. We're tracking it here so that we can skip the store and load.
760 ExtractedEHPtrs.push_back(Extract);
761 } else if (Idx == 1) {
762 // Element 1 corresponds to the filter selector. We'll map it to 1 for
763 // matching purposes, but it will also probably be stored to memory and
764 // reloaded, so we need to track the instuction so that we can map the
766 ExtractedSelectors.push_back(Extract);
769 // Look for stores of the extracted values.
770 for (auto *EU : Extract->users()) {
771 if (auto *Store = dyn_cast<StoreInst>(EU)) {
773 SelectorStores.push_back(Store);
774 SelectorStoreAddrs.push_back(Store->getPointerOperand());
776 EHPtrStores.push_back(Store);
777 EHPtrStoreAddrs.push_back(Store->getPointerOperand());
784 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
785 if (Inst == OriginLPad)
787 for (auto *Extract : ExtractedEHPtrs) {
791 for (auto *Extract : ExtractedSelectors) {
795 for (auto *Store : EHPtrStores) {
799 for (auto *Store : SelectorStores) {
807 void LandingPadMap::remapSelector(ValueToValueMapTy &VMap,
808 Value *MappedValue) const {
809 // Remap all selector extract instructions to the specified value.
810 for (auto *Extract : ExtractedSelectors)
811 VMap[Extract] = MappedValue;
814 bool LandingPadMap::mapIfEHLoad(const LoadInst *Load,
815 SmallVectorImpl<const StoreInst *> &Stores,
816 SmallVectorImpl<const Value *> &StoreAddrs) {
817 // This makes the assumption that a store we've previously seen dominates
818 // this load instruction. That might seem like a rather huge assumption,
819 // but given the way that landingpads are constructed its fairly safe.
820 // FIXME: Add debug/assert code that verifies this.
821 const Value *LoadAddr = Load->getPointerOperand();
822 for (auto *StoreAddr : StoreAddrs) {
823 if (LoadAddr == StoreAddr) {
824 // Handle the common debug scenario where this loaded value is stored
825 // to a different location.
826 for (auto *U : Load->users()) {
827 if (auto *Store = dyn_cast<StoreInst>(U)) {
828 Stores.push_back(Store);
829 StoreAddrs.push_back(Store->getPointerOperand());
838 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
839 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
840 // If this is one of the boilerplate landing pad instructions, skip it.
841 // The instruction will have already been remapped in VMap.
842 if (LPadMap.isLandingPadSpecificInst(Inst))
843 return CloningDirector::SkipInstruction;
845 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
846 // Look for loads of (previously suppressed) landingpad values.
847 // The EHPtr load can be mapped to an undef value as it should only be used
848 // as an argument to llvm.eh.begincatch, but the selector value needs to be
849 // mapped to a constant value of 1. This value will be used to simplify the
850 // branching to always flow to the current handler.
851 if (LPadMap.mapIfSelectorLoad(Load)) {
852 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
853 return CloningDirector::SkipInstruction;
855 if (LPadMap.mapIfEHPtrLoad(Load)) {
856 VMap[Inst] = UndefValue::get(Int8PtrType);
857 return CloningDirector::SkipInstruction;
860 // Any other loads just get cloned.
861 return CloningDirector::CloneInstruction;
864 // Nested landing pads will be cloned as stubs, with just the
865 // landingpad instruction and an unreachable instruction. When
866 // all landingpads have been outlined, we'll replace this with the
867 // llvm.eh.actions call and indirect branch created when the
868 // landing pad was outlined.
869 if (auto *NestedLPad = dyn_cast<LandingPadInst>(Inst)) {
870 Instruction *NewInst = NestedLPad->clone();
871 if (NestedLPad->hasName())
872 NewInst->setName(NestedLPad->getName());
873 // FIXME: Store this mapping somewhere else also.
874 VMap[NestedLPad] = NewInst;
875 BasicBlock::InstListType &InstList = NewBB->getInstList();
876 InstList.push_back(NewInst);
877 InstList.push_back(new UnreachableInst(NewBB->getContext()));
878 return CloningDirector::StopCloningBB;
881 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
882 return handleInvoke(VMap, Invoke, NewBB);
884 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
885 return handleResume(VMap, Resume, NewBB);
887 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
888 return handleBeginCatch(VMap, Inst, NewBB);
889 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
890 return handleEndCatch(VMap, Inst, NewBB);
891 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
892 return handleTypeIdFor(VMap, Inst, NewBB);
894 // Continue with the default cloning behavior.
895 return CloningDirector::CloneInstruction;
898 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
899 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
900 // The argument to the call is some form of the first element of the
901 // landingpad aggregate value, but that doesn't matter. It isn't used
903 // The second argument is an outparameter where the exception object will be
904 // stored. Typically the exception object is a scalar, but it can be an
905 // aggregate when catching by value.
906 // FIXME: Leave something behind to indicate where the exception object lives
907 // for this handler. Should it be part of llvm.eh.actions?
908 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
909 "llvm.eh.begincatch found while "
910 "outlining catch handler.");
911 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
912 return CloningDirector::SkipInstruction;
915 CloningDirector::CloningAction
916 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
917 const Instruction *Inst, BasicBlock *NewBB) {
918 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
919 // It might be interesting to track whether or not we are inside a catch
920 // function, but that might make the algorithm more brittle than it needs
923 // The end catch call can occur in one of two places: either in a
924 // landingpad block that is part of the catch handlers exception mechanism,
925 // or at the end of the catch block. If it occurs in a landing pad, we must
926 // skip it and continue so that the landing pad gets cloned.
927 // FIXME: This case isn't fully supported yet and shouldn't turn up in any
928 // of the test cases until it is.
929 if (IntrinCall->getParent()->isLandingPad())
930 return CloningDirector::SkipInstruction;
932 // If an end catch occurs anywhere else the next instruction should be an
933 // unconditional branch instruction that we want to replace with a return
934 // to the the address of the branch target.
935 const BasicBlock *EndCatchBB = IntrinCall->getParent();
936 const TerminatorInst *Terminator = EndCatchBB->getTerminator();
937 const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
938 assert(Branch && Branch->isUnconditional());
939 assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
940 BasicBlock::const_iterator(Branch));
942 BasicBlock *ContinueLabel = Branch->getSuccessor(0);
943 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueLabel),
945 ReturnTargets.push_back(ContinueLabel);
947 // We just added a terminator to the cloned block.
948 // Tell the caller to stop processing the current basic block so that
949 // the branch instruction will be skipped.
950 return CloningDirector::StopCloningBB;
953 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
954 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
955 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
956 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
957 // This causes a replacement that will collapse the landing pad CFG based
958 // on the filter function we intend to match.
959 if (Selector == CurrentSelector)
960 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
962 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
963 // Tell the caller not to clone this instruction.
964 return CloningDirector::SkipInstruction;
967 CloningDirector::CloningAction
968 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
969 const InvokeInst *Invoke, BasicBlock *NewBB) {
970 return CloningDirector::CloneInstruction;
973 CloningDirector::CloningAction
974 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
975 const ResumeInst *Resume, BasicBlock *NewBB) {
976 // Resume instructions shouldn't be reachable from catch handlers.
977 // We still need to handle it, but it will be pruned.
978 BasicBlock::InstListType &InstList = NewBB->getInstList();
979 InstList.push_back(new UnreachableInst(NewBB->getContext()));
980 return CloningDirector::StopCloningBB;
983 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
984 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
985 // Catch blocks within cleanup handlers will always be unreachable.
986 // We'll insert an unreachable instruction now, but it will be pruned
987 // before the cloning process is complete.
988 BasicBlock::InstListType &InstList = NewBB->getInstList();
989 InstList.push_back(new UnreachableInst(NewBB->getContext()));
990 return CloningDirector::StopCloningBB;
993 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
994 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
995 // Catch blocks within cleanup handlers will always be unreachable.
996 // We'll insert an unreachable instruction now, but it will be pruned
997 // before the cloning process is complete.
998 BasicBlock::InstListType &InstList = NewBB->getInstList();
999 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1000 return CloningDirector::StopCloningBB;
1003 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1004 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1005 // If we encounter a selector comparison while cloning a cleanup handler,
1006 // we want to stop cloning immediately. Anything after the dispatch
1007 // will be outlined into a different handler.
1008 BasicBlock *CatchHandler;
1011 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1012 CatchHandler, Selector, NextBB)) {
1013 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1014 return CloningDirector::StopCloningBB;
1016 // If eg.typeid.for is called for any other reason, it can be ignored.
1017 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1018 return CloningDirector::SkipInstruction;
1021 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1022 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1023 // All invokes in cleanup handlers can be replaced with calls.
1024 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1025 // Insert a normal call instruction...
1027 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1028 Invoke->getName(), NewBB);
1029 NewCall->setCallingConv(Invoke->getCallingConv());
1030 NewCall->setAttributes(Invoke->getAttributes());
1031 NewCall->setDebugLoc(Invoke->getDebugLoc());
1032 VMap[Invoke] = NewCall;
1034 // Insert an unconditional branch to the normal destination.
1035 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1037 // The unwind destination won't be cloned into the new function, so
1038 // we don't need to clean up its phi nodes.
1040 // We just added a terminator to the cloned block.
1041 // Tell the caller to stop processing the current basic block.
1042 return CloningDirector::StopCloningBB;
1045 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1046 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1047 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1049 // We just added a terminator to the cloned block.
1050 // Tell the caller to stop processing the current basic block so that
1051 // the branch instruction will be skipped.
1052 return CloningDirector::StopCloningBB;
1055 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1056 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1057 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1058 Builder.SetInsertPoint(&OutlinedFn->getEntryBlock());
1061 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1062 // If we're asked to materialize a value that is an instruction, we
1063 // temporarily create an alloca in the outlined function and add this
1064 // to the FrameVarInfo map. When all the outlining is complete, we'll
1065 // collect these into a structure, spilling non-alloca values in the
1066 // parent frame as necessary, and replace these temporary allocas with
1067 // GEPs referencing the frame allocation block.
1069 // If the value is an alloca, the mapping is direct.
1070 if (auto *AV = dyn_cast<AllocaInst>(V)) {
1071 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1072 Builder.Insert(NewAlloca, AV->getName());
1073 FrameVarInfo[AV].push_back(NewAlloca);
1077 // For other types of instructions or arguments, we need an alloca based on
1078 // the value's type and a load of the alloca. The alloca will be replaced
1079 // by a GEP, but the load will stay. In the parent function, the value will
1080 // be spilled to a location in the frame allocation block.
1081 if (isa<Instruction>(V) || isa<Argument>(V)) {
1082 AllocaInst *NewAlloca =
1083 Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
1084 FrameVarInfo[V].push_back(NewAlloca);
1085 LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1089 // Don't materialize other values.
1093 // This function maps the catch and cleanup handlers that are reachable from the
1094 // specified landing pad. The landing pad sequence will have this basic shape:
1096 // <cleanup handler>
1097 // <selector comparison>
1099 // <cleanup handler>
1100 // <selector comparison>
1102 // <cleanup handler>
1105 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1106 // any arbitrary control flow, but all paths through the cleanup code must
1107 // eventually reach the next selector comparison and no path can skip to a
1108 // different selector comparisons, though some paths may terminate abnormally.
1109 // Therefore, we will use a depth first search from the start of any given
1110 // cleanup block and stop searching when we find the next selector comparison.
1112 // If the landingpad instruction does not have a catch clause, we will assume
1113 // that any instructions other than selector comparisons and catch handlers can
1114 // be ignored. In practice, these will only be the boilerplate instructions.
1116 // The catch handlers may also have any control structure, but we are only
1117 // interested in the start of the catch handlers, so we don't need to actually
1118 // follow the flow of the catch handlers. The start of the catch handlers can
1119 // be located from the compare instructions, but they can be skipped in the
1120 // flow by following the contrary branch.
1121 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1122 LandingPadActions &Actions) {
1123 unsigned int NumClauses = LPad->getNumClauses();
1124 unsigned int HandlersFound = 0;
1125 BasicBlock *BB = LPad->getParent();
1127 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1129 if (NumClauses == 0) {
1130 // This landing pad contains only cleanup code.
1131 CleanupHandler *Action = new CleanupHandler(BB);
1132 CleanupHandlerMap[BB] = Action;
1133 Actions.insertCleanupHandler(Action);
1134 DEBUG(dbgs() << " Assuming cleanup code in block " << BB->getName()
1136 assert(LPad->isCleanup());
1140 VisitedBlockSet VisitedBlocks;
1142 while (HandlersFound != NumClauses) {
1143 Constant *Selector = nullptr;
1144 BasicBlock *NextBB = nullptr;
1146 // See if the clause we're looking for is a catch-all.
1147 // If so, the catch begins immediately.
1148 if (isa<ConstantPointerNull>(LPad->getClause(HandlersFound))) {
1149 // The catch all must occur last.
1150 assert(HandlersFound == NumClauses - 1);
1152 // See if there is any interesting code executed before the catch.
1153 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1154 // Add a cleanup entry to the list
1155 Actions.insertCleanupHandler(CleanupAction);
1156 DEBUG(dbgs() << " Found cleanup code in block "
1157 << CleanupAction->getStartBlock()->getName() << "\n");
1160 // Add the catch handler to the action list.
1161 CatchHandler *Action =
1162 new CatchHandler(BB, LPad->getClause(HandlersFound), nullptr);
1163 CatchHandlerMap[BB] = Action;
1164 Actions.insertCatchHandler(Action);
1165 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1170 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1171 // See if there is any interesting code executed before the dispatch.
1172 if (auto *CleanupAction =
1173 findCleanupHandler(BB, CatchAction->getStartBlock())) {
1174 // Add a cleanup entry to the list
1175 Actions.insertCleanupHandler(CleanupAction);
1176 DEBUG(dbgs() << " Found cleanup code in block "
1177 << CleanupAction->getStartBlock()->getName() << "\n");
1180 assert(CatchAction);
1183 // Add the catch handler to the action list.
1184 Actions.insertCatchHandler(CatchAction);
1185 DEBUG(dbgs() << " Found catch dispatch in block "
1186 << CatchAction->getStartBlock()->getName() << "\n");
1188 // Move on to the block after the catch handler.
1192 // See if there is any interesting code executed before the resume.
1193 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1194 // Add a cleanup entry to the list
1195 Actions.insertCleanupHandler(CleanupAction);
1196 DEBUG(dbgs() << " Found cleanup code in block "
1197 << CleanupAction->getStartBlock()->getName() << "\n");
1200 // It's possible that some optimization moved code into a landingpad that
1202 // previously being used for cleanup. If that happens, we need to execute
1204 // extra code from a cleanup handler.
1205 if (Actions.includesCleanup() && !LPad->isCleanup())
1206 LPad->setCleanup(true);
1209 // This function searches starting with the input block for the next
1210 // block that terminates with a branch whose condition is based on a selector
1211 // comparison. This may be the input block. See the mapLandingPadBlocks
1212 // comments for a discussion of control flow assumptions.
1214 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1215 BasicBlock *&NextBB,
1216 VisitedBlockSet &VisitedBlocks) {
1217 // See if we've already found a catch handler use it.
1218 // Call count() first to avoid creating a null entry for blocks
1219 // we haven't seen before.
1220 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1221 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1222 NextBB = Action->getNextBB();
1226 // VisitedBlocks applies only to the current search. We still
1227 // need to consider blocks that we've visited while mapping other
1229 VisitedBlocks.insert(BB);
1231 BasicBlock *CatchBlock = nullptr;
1232 Constant *Selector = nullptr;
1234 // If this is the first time we've visited this block from any landing pad
1235 // look to see if it is a selector dispatch block.
1236 if (!CatchHandlerMap.count(BB)) {
1237 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1238 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1239 CatchHandlerMap[BB] = Action;
1244 // Visit each successor, looking for the dispatch.
1245 // FIXME: We expect to find the dispatch quickly, so this will probably
1246 // work better as a breadth first search.
1247 for (BasicBlock *Succ : successors(BB)) {
1248 if (VisitedBlocks.count(Succ))
1251 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1258 // These are helper functions to combine repeated code from findCleanupHandler.
1259 static CleanupHandler *createCleanupHandler(CleanupHandlerMapTy &CleanupHandlerMap,
1261 CleanupHandler *Action = new CleanupHandler(BB);
1262 CleanupHandlerMap[BB] = Action;
1266 // This function searches starting with the input block for the next block that
1267 // contains code that is not part of a catch handler and would not be eliminated
1268 // during handler outlining.
1270 CleanupHandler *WinEHPrepare::findCleanupHandler(BasicBlock *StartBB,
1271 BasicBlock *EndBB) {
1272 // Here we will skip over the following:
1274 // landing pad prolog:
1276 // Unconditional branches
1278 // Selector dispatch
1282 // Anything else marks the start of an interesting block
1284 BasicBlock *BB = StartBB;
1285 // Anything other than an unconditional branch will kick us out of this loop
1286 // one way or another.
1288 // If we've already scanned this block, don't scan it again. If it is
1289 // a cleanup block, there will be an action in the CleanupHandlerMap.
1290 // If we've scanned it and it is not a cleanup block, there will be a
1291 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1292 // be no entry in the CleanupHandlerMap. We must call count() first to
1293 // avoid creating a null entry for blocks we haven't scanned.
1294 if (CleanupHandlerMap.count(BB)) {
1295 if (auto *Action = CleanupHandlerMap[BB]) {
1296 return cast<CleanupHandler>(Action);
1298 // Here we handle the case where the cleanup handler map contains a
1299 // value for this block but the value is a nullptr. This means that
1300 // we have previously analyzed the block and determined that it did
1301 // not contain any cleanup code. Based on the earlier analysis, we
1302 // know the the block must end in either an unconditional branch, a
1303 // resume or a conditional branch that is predicated on a comparison
1304 // with a selector. Either the resume or the selector dispatch
1305 // would terminate the search for cleanup code, so the unconditional
1306 // branch is the only case for which we might need to continue
1311 if (!match(BB->getTerminator(), m_UnconditionalBr(SuccBB)))
1318 // Create an entry in the cleanup handler map for this block. Initially
1319 // we create an entry that says this isn't a cleanup block. If we find
1320 // cleanup code, the caller will replace this entry.
1321 CleanupHandlerMap[BB] = nullptr;
1323 TerminatorInst *Terminator = BB->getTerminator();
1325 // Landing pad blocks have extra instructions we need to accept.
1326 LandingPadMap *LPadMap = nullptr;
1327 if (BB->isLandingPad()) {
1328 LandingPadInst *LPad = BB->getLandingPadInst();
1329 LPadMap = &LPadMaps[LPad];
1330 if (!LPadMap->isInitialized())
1331 LPadMap->mapLandingPad(LPad);
1334 // Look for the bare resume pattern:
1335 // %exn2 = load i8** %exn.slot
1336 // %sel2 = load i32* %ehselector.slot
1337 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn2, 0
1338 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel2, 1
1339 // resume { i8*, i32 } %lpad.val2
1340 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1341 InsertValueInst *Insert1 = nullptr;
1342 InsertValueInst *Insert2 = nullptr;
1343 if (!isa<PHINode>(Resume->getOperand(0))) {
1344 Insert2 = dyn_cast<InsertValueInst>(Resume->getOperand(0));
1346 return createCleanupHandler(CleanupHandlerMap, BB);
1347 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1349 return createCleanupHandler(CleanupHandlerMap, BB);
1351 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1353 Instruction *Inst = II;
1354 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1356 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1358 if (!Inst->hasOneUse() ||
1359 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1360 return createCleanupHandler(CleanupHandlerMap, BB);
1366 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1368 if (Branch->isConditional()) {
1369 // Look for the selector dispatch.
1370 // %sel = load i32* %ehselector.slot
1371 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1372 // %matches = icmp eq i32 %sel12, %2
1373 // br i1 %matches, label %catch14, label %eh.resume
1374 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1375 if (!Compare || !Compare->isEquality())
1376 return createCleanupHandler(CleanupHandlerMap, BB);
1377 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1380 Instruction *Inst = II;
1381 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1383 if (Inst == Compare || Inst == Branch)
1385 if (!Inst->hasOneUse() || (Inst->user_back() != Compare))
1386 return createCleanupHandler(CleanupHandlerMap, BB);
1387 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1389 if (!isa<LoadInst>(Inst))
1390 return createCleanupHandler(CleanupHandlerMap, BB);
1392 // The selector dispatch block should always terminate our search.
1393 assert(BB == EndBB);
1396 // Look for empty blocks with unconditional branches.
1397 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1400 Instruction *Inst = II;
1401 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1405 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1407 // Anything else makes this interesting cleanup code.
1408 return createCleanupHandler(CleanupHandlerMap, BB);
1412 // The branch was unconditional.
1413 BB = Branch->getSuccessor(0);
1415 } // End else of if branch was conditional
1418 // Anything else makes this interesting cleanup code.
1419 return createCleanupHandler(CleanupHandlerMap, BB);