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/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/TinyPtrVector.h"
23 #include "llvm/Analysis/LibCallSemantics.h"
24 #include "llvm/CodeGen/WinEHFuncInfo.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
43 using namespace llvm::PatternMatch;
45 #define DEBUG_TYPE "winehprepare"
49 // This map is used to model frame variable usage during outlining, to
50 // construct a structure type to hold the frame variables in a frame
51 // allocation block, and to remap the frame variable allocas (including
52 // spill locations as needed) to GEPs that get the variable from the
53 // frame allocation structure.
54 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
56 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
58 AllocaInst *getCatchObjectSentinel() {
59 return static_cast<AllocaInst *>(nullptr) + 1;
62 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
64 class LandingPadActions;
67 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
68 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
70 class WinEHPrepare : public FunctionPass {
72 static char ID; // Pass identification, replacement for typeid.
73 WinEHPrepare(const TargetMachine *TM = nullptr)
74 : FunctionPass(ID), DT(nullptr) {}
76 bool runOnFunction(Function &Fn) override;
78 bool doFinalization(Module &M) override;
80 void getAnalysisUsage(AnalysisUsage &AU) const override;
82 const char *getPassName() const override {
83 return "Windows exception handling preparation";
87 bool prepareExceptionHandlers(Function &F,
88 SmallVectorImpl<LandingPadInst *> &LPads);
89 void promoteLandingPadValues(LandingPadInst *LPad);
90 void demoteValuesLiveAcrossHandlers(Function &F,
91 SmallVectorImpl<LandingPadInst *> &LPads);
92 void completeNestedLandingPad(Function *ParentFn,
93 LandingPadInst *OutlinedLPad,
94 const LandingPadInst *OriginalLPad,
95 FrameVarInfoMap &VarInfo);
96 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
97 LandingPadInst *LPad, BasicBlock *StartBB,
98 FrameVarInfoMap &VarInfo);
99 void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn);
101 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
102 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
103 VisitedBlockSet &VisitedBlocks);
104 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
107 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
109 // All fields are reset by runOnFunction.
111 EHPersonality Personality;
112 CatchHandlerMapTy CatchHandlerMap;
113 CleanupHandlerMapTy CleanupHandlerMap;
114 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
116 // This maps landing pad instructions found in outlined handlers to
117 // the landing pad instruction in the parent function from which they
118 // were cloned. The cloned/nested landing pad is used as the key
119 // because the landing pad may be cloned into multiple handlers.
120 // This map will be used to add the llvm.eh.actions call to the nested
121 // landing pads after all handlers have been outlined.
122 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
124 // This maps blocks in the parent function which are destinations of
125 // catch handlers to cloned blocks in (other) outlined handlers. This
126 // handles the case where a nested landing pads has a catch handler that
127 // returns to a handler function rather than the parent function.
128 // The original block is used as the key here because there should only
129 // ever be one handler function from which the cloned block is not pruned.
130 // The original block will be pruned from the parent function after all
131 // handlers have been outlined. This map will be used to adjust the
132 // return instructions of handlers which return to the block that was
133 // outlined into a handler. This is done after all handlers have been
134 // outlined but before the outlined code is pruned from the parent function.
135 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
138 class WinEHFrameVariableMaterializer : public ValueMaterializer {
140 WinEHFrameVariableMaterializer(Function *OutlinedFn,
141 FrameVarInfoMap &FrameVarInfo);
142 ~WinEHFrameVariableMaterializer() override {}
144 Value *materializeValueFor(Value *V) override;
146 void escapeCatchObject(Value *V);
149 FrameVarInfoMap &FrameVarInfo;
153 class LandingPadMap {
155 LandingPadMap() : OriginLPad(nullptr) {}
156 void mapLandingPad(const LandingPadInst *LPad);
158 bool isInitialized() { return OriginLPad != nullptr; }
160 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
161 bool isLandingPadSpecificInst(const Instruction *Inst) const;
163 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
164 Value *SelectorValue) const;
167 const LandingPadInst *OriginLPad;
168 // We will normally only see one of each of these instructions, but
169 // if more than one occurs for some reason we can handle that.
170 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
171 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
174 class WinEHCloningDirectorBase : public CloningDirector {
176 WinEHCloningDirectorBase(Function *HandlerFn, FrameVarInfoMap &VarInfo,
177 LandingPadMap &LPadMap)
178 : Materializer(HandlerFn, VarInfo),
179 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
180 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
182 auto AI = HandlerFn->getArgumentList().begin();
184 EstablisherFrame = AI;
187 CloningAction handleInstruction(ValueToValueMapTy &VMap,
188 const Instruction *Inst,
189 BasicBlock *NewBB) override;
191 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
192 const Instruction *Inst,
193 BasicBlock *NewBB) = 0;
194 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
195 const Instruction *Inst,
196 BasicBlock *NewBB) = 0;
197 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
198 const Instruction *Inst,
199 BasicBlock *NewBB) = 0;
200 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
201 const InvokeInst *Invoke,
202 BasicBlock *NewBB) = 0;
203 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
204 const ResumeInst *Resume,
205 BasicBlock *NewBB) = 0;
206 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
207 const CmpInst *Compare,
208 BasicBlock *NewBB) = 0;
209 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
210 const LandingPadInst *LPad,
211 BasicBlock *NewBB) = 0;
213 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
216 WinEHFrameVariableMaterializer Materializer;
217 Type *SelectorIDType;
219 LandingPadMap &LPadMap;
221 /// The value representing the parent frame pointer.
222 Value *EstablisherFrame;
225 class WinEHCatchDirector : public WinEHCloningDirectorBase {
228 Function *CatchFn, Value *Selector, FrameVarInfoMap &VarInfo,
229 LandingPadMap &LPadMap,
230 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
231 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
232 CurrentSelector(Selector->stripPointerCasts()),
233 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
235 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
236 const Instruction *Inst,
237 BasicBlock *NewBB) override;
238 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
239 BasicBlock *NewBB) override;
240 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
241 const Instruction *Inst,
242 BasicBlock *NewBB) override;
243 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
244 BasicBlock *NewBB) override;
245 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
246 BasicBlock *NewBB) override;
247 CloningAction handleCompare(ValueToValueMapTy &VMap,
248 const CmpInst *Compare, BasicBlock *NewBB) override;
249 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
250 const LandingPadInst *LPad,
251 BasicBlock *NewBB) override;
253 Value *getExceptionVar() { return ExceptionObjectVar; }
254 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
257 Value *CurrentSelector;
259 Value *ExceptionObjectVar;
260 TinyPtrVector<BasicBlock *> ReturnTargets;
262 // This will be a reference to the field of the same name in the WinEHPrepare
263 // object which instantiates this WinEHCatchDirector object.
264 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
267 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
269 WinEHCleanupDirector(Function *CleanupFn, FrameVarInfoMap &VarInfo,
270 LandingPadMap &LPadMap)
271 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
273 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
274 const Instruction *Inst,
275 BasicBlock *NewBB) override;
276 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
277 BasicBlock *NewBB) override;
278 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
279 const Instruction *Inst,
280 BasicBlock *NewBB) override;
281 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
282 BasicBlock *NewBB) override;
283 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
284 BasicBlock *NewBB) override;
285 CloningAction handleCompare(ValueToValueMapTy &VMap,
286 const CmpInst *Compare, BasicBlock *NewBB) override;
287 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
288 const LandingPadInst *LPad,
289 BasicBlock *NewBB) override;
292 class LandingPadActions {
294 LandingPadActions() : HasCleanupHandlers(false) {}
296 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
297 void insertCleanupHandler(CleanupHandler *Action) {
298 Actions.push_back(Action);
299 HasCleanupHandlers = true;
302 bool includesCleanup() const { return HasCleanupHandlers; }
304 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
305 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
306 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
309 // Note that this class does not own the ActionHandler objects in this vector.
310 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
311 // in the WinEHPrepare class.
312 SmallVector<ActionHandler *, 4> Actions;
313 bool HasCleanupHandlers;
316 } // end anonymous namespace
318 char WinEHPrepare::ID = 0;
319 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
322 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
323 return new WinEHPrepare(TM);
326 // FIXME: Remove this once the backend can handle the prepared IR.
328 SEHPrepare("sehprepare", cl::Hidden,
329 cl::desc("Prepare functions with SEH personalities"));
331 bool WinEHPrepare::runOnFunction(Function &Fn) {
332 // No need to prepare outlined handlers.
333 if (Fn.hasFnAttribute("wineh-parent"))
336 SmallVector<LandingPadInst *, 4> LPads;
337 SmallVector<ResumeInst *, 4> Resumes;
338 for (BasicBlock &BB : Fn) {
339 if (auto *LP = BB.getLandingPadInst())
341 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
342 Resumes.push_back(Resume);
345 // No need to prepare functions that lack landing pads.
349 // Classify the personality to see what kind of preparation we need.
350 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
352 // Do nothing if this is not an MSVC personality.
353 if (!isMSVCEHPersonality(Personality))
356 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
358 if (isAsynchronousEHPersonality(Personality) && !SEHPrepare) {
359 // Replace all resume instructions with unreachable.
360 // FIXME: Remove this once the backend can handle the prepared IR.
361 for (ResumeInst *Resume : Resumes) {
362 IRBuilder<>(Resume).CreateUnreachable();
363 Resume->eraseFromParent();
368 // If there were any landing pads, prepareExceptionHandlers will make changes.
369 prepareExceptionHandlers(Fn, LPads);
373 bool WinEHPrepare::doFinalization(Module &M) { return false; }
375 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
376 AU.addRequired<DominatorTreeWrapperPass>();
379 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
380 Constant *&Selector, BasicBlock *&NextBB);
382 // Finds blocks reachable from the starting set Worklist. Does not follow unwind
383 // edges or blocks listed in StopPoints.
384 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
385 SetVector<BasicBlock *> &Worklist,
386 const SetVector<BasicBlock *> *StopPoints) {
387 while (!Worklist.empty()) {
388 BasicBlock *BB = Worklist.pop_back_val();
390 // Don't cross blocks that we should stop at.
391 if (StopPoints && StopPoints->count(BB))
394 if (!ReachableBBs.insert(BB).second)
395 continue; // Already visited.
397 // Don't follow unwind edges of invokes.
398 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
399 Worklist.insert(II->getNormalDest());
403 // Otherwise, follow all successors.
404 Worklist.insert(succ_begin(BB), succ_end(BB));
408 /// Find all points where exceptional control rejoins normal control flow via
409 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
410 static void findCXXEHReturnPoints(Function &F,
411 SetVector<BasicBlock *> &EHReturnBlocks) {
412 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
413 BasicBlock *BB = BBI;
414 for (Instruction &I : *BB) {
415 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
416 // Split the block after the call to llvm.eh.endcatch if there is
417 // anything other than an unconditional branch, or if the successor
418 // starts with a phi.
419 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
420 if (!Br || !Br->isUnconditional() ||
421 isa<PHINode>(Br->getSuccessor(0)->begin())) {
422 DEBUG(dbgs() << "splitting block " << BB->getName()
423 << " with llvm.eh.endcatch\n");
424 BBI = BB->splitBasicBlock(I.getNextNode(), "ehreturn");
426 // The next BB is normal control flow.
427 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
434 static bool isCatchAllLandingPad(const BasicBlock *BB) {
435 const LandingPadInst *LP = BB->getLandingPadInst();
438 unsigned N = LP->getNumClauses();
439 return (N > 0 && LP->isCatch(N - 1) &&
440 isa<ConstantPointerNull>(LP->getClause(N - 1)));
443 /// Find all points where exceptions control rejoins normal control flow via
444 /// selector dispatch.
445 static void findSEHEHReturnPoints(Function &F,
446 SetVector<BasicBlock *> &EHReturnBlocks) {
447 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
448 BasicBlock *BB = BBI;
449 // If the landingpad is a catch-all, treat the whole lpad as if it is
450 // reachable from normal control flow.
451 // FIXME: This is imprecise. We need a better way of identifying where a
452 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
454 if (isCatchAllLandingPad(BB)) {
455 EHReturnBlocks.insert(BB);
459 BasicBlock *CatchHandler;
462 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
463 // Split the edge if there is a phi node. Returning from EH to a phi node
464 // is just as impossible as having a phi after an indirectbr.
465 if (isa<PHINode>(CatchHandler->begin())) {
466 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
467 << " to " << CatchHandler->getName() << '\n');
468 BBI = CatchHandler = SplitCriticalEdge(
469 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
471 EHReturnBlocks.insert(CatchHandler);
476 /// Ensure that all values live into and out of exception handlers are stored
478 /// FIXME: This falls down when values are defined in one handler and live into
479 /// another handler. For example, a cleanup defines a value used only by a
481 void WinEHPrepare::demoteValuesLiveAcrossHandlers(
482 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
483 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
484 << F.getName() << '\n');
486 // Build a set of all non-exceptional blocks and exceptional blocks.
487 // - Non-exceptional blocks are blocks reachable from the entry block while
488 // not following invoke unwind edges.
489 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
490 // not follow llvm.eh.endcatch blocks, which mark a transition from
491 // exceptional to normal control.
492 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
493 SmallPtrSet<BasicBlock *, 4> EHBlocks;
494 SetVector<BasicBlock *> EHReturnBlocks;
495 SetVector<BasicBlock *> Worklist;
497 if (Personality == EHPersonality::MSVC_CXX)
498 findCXXEHReturnPoints(F, EHReturnBlocks);
500 findSEHEHReturnPoints(F, EHReturnBlocks);
503 dbgs() << "identified the following blocks as EH return points:\n";
504 for (BasicBlock *BB : EHReturnBlocks)
505 dbgs() << " " << BB->getName() << '\n';
508 // Join points should not have phis at this point, unless they are a
509 // landingpad, in which case we will demote their phis later.
511 for (BasicBlock *BB : EHReturnBlocks)
512 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
513 "non-lpad EH return block has phi");
516 // Normal blocks are the blocks reachable from the entry block and all EH
518 Worklist = EHReturnBlocks;
519 Worklist.insert(&F.getEntryBlock());
520 findReachableBlocks(NormalBlocks, Worklist, nullptr);
522 dbgs() << "marked the following blocks as normal:\n";
523 for (BasicBlock *BB : NormalBlocks)
524 dbgs() << " " << BB->getName() << '\n';
527 // Exceptional blocks are the blocks reachable from landingpads that don't
528 // cross EH return points.
530 for (auto *LPI : LPads)
531 Worklist.insert(LPI->getParent());
532 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
534 dbgs() << "marked the following blocks as exceptional:\n";
535 for (BasicBlock *BB : EHBlocks)
536 dbgs() << " " << BB->getName() << '\n';
539 SetVector<Argument *> ArgsToDemote;
540 SetVector<Instruction *> InstrsToDemote;
541 for (BasicBlock &BB : F) {
542 bool IsNormalBB = NormalBlocks.count(&BB);
543 bool IsEHBB = EHBlocks.count(&BB);
544 if (!IsNormalBB && !IsEHBB)
545 continue; // Blocks that are neither normal nor EH are unreachable.
546 for (Instruction &I : BB) {
547 for (Value *Op : I.operands()) {
548 // Don't demote static allocas, constants, and labels.
549 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
551 auto *AI = dyn_cast<AllocaInst>(Op);
552 if (AI && AI->isStaticAlloca())
555 if (auto *Arg = dyn_cast<Argument>(Op)) {
557 DEBUG(dbgs() << "Demoting argument " << *Arg
558 << " used by EH instr: " << I << "\n");
559 ArgsToDemote.insert(Arg);
564 auto *OpI = cast<Instruction>(Op);
565 BasicBlock *OpBB = OpI->getParent();
566 // If a value is produced and consumed in the same BB, we don't need to
570 bool IsOpNormalBB = NormalBlocks.count(OpBB);
571 bool IsOpEHBB = EHBlocks.count(OpBB);
572 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
574 dbgs() << "Demoting instruction live in-out from EH:\n";
575 dbgs() << "Instr: " << *OpI << '\n';
576 dbgs() << "User: " << I << '\n';
578 InstrsToDemote.insert(OpI);
584 // Demote values live into and out of handlers.
585 // FIXME: This demotion is inefficient. We should insert spills at the point
586 // of definition, insert one reload in each handler that uses the value, and
587 // insert reloads in the BB used to rejoin normal control flow.
588 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
589 for (Instruction *I : InstrsToDemote)
590 DemoteRegToStack(*I, false, AllocaInsertPt);
592 // Demote arguments separately, and only for uses in EH blocks.
593 for (Argument *Arg : ArgsToDemote) {
594 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
595 Arg->getName() + ".reg2mem", AllocaInsertPt);
596 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
597 for (User *U : Users) {
598 auto *I = dyn_cast<Instruction>(U);
599 if (I && EHBlocks.count(I->getParent())) {
600 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
601 U->replaceUsesOfWith(Arg, Reload);
604 new StoreInst(Arg, Slot, AllocaInsertPt);
607 // Demote landingpad phis, as the landingpad will be removed from the machine
609 for (LandingPadInst *LPI : LPads) {
610 BasicBlock *BB = LPI->getParent();
611 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
612 DemotePHIToStack(Phi, AllocaInsertPt);
615 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
616 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
619 bool WinEHPrepare::prepareExceptionHandlers(
620 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
621 // Don't run on functions that are already prepared.
622 for (LandingPadInst *LPad : LPads) {
623 BasicBlock *LPadBB = LPad->getParent();
624 for (Instruction &Inst : *LPadBB)
625 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
629 demoteValuesLiveAcrossHandlers(F, LPads);
631 // These containers are used to re-map frame variables that are used in
632 // outlined catch and cleanup handlers. They will be populated as the
633 // handlers are outlined.
634 FrameVarInfoMap FrameVarInfo;
636 bool HandlersOutlined = false;
638 Module *M = F.getParent();
639 LLVMContext &Context = M->getContext();
641 // Create a new function to receive the handler contents.
642 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
643 Type *Int32Type = Type::getInt32Ty(Context);
644 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
646 for (LandingPadInst *LPad : LPads) {
647 // Look for evidence that this landingpad has already been processed.
648 bool LPadHasActionList = false;
649 BasicBlock *LPadBB = LPad->getParent();
650 for (Instruction &Inst : *LPadBB) {
651 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
652 LPadHasActionList = true;
657 // If we've already outlined the handlers for this landingpad,
658 // there's nothing more to do here.
659 if (LPadHasActionList)
662 // If either of the values in the aggregate returned by the landing pad is
663 // extracted and stored to memory, promote the stored value to a register.
664 promoteLandingPadValues(LPad);
666 LandingPadActions Actions;
667 mapLandingPadBlocks(LPad, Actions);
669 HandlersOutlined |= !Actions.actions().empty();
670 for (ActionHandler *Action : Actions) {
671 if (Action->hasBeenProcessed())
673 BasicBlock *StartBB = Action->getStartBlock();
675 // SEH doesn't do any outlining for catches. Instead, pass the handler
676 // basic block addr to llvm.eh.actions and list the block as a return
678 if (isAsynchronousEHPersonality(Personality)) {
679 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
680 processSEHCatchHandler(CatchAction, StartBB);
685 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
688 // Replace the landing pad with a new llvm.eh.action based landing pad.
689 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
690 assert(!isa<PHINode>(LPadBB->begin()));
691 auto *NewLPad = cast<LandingPadInst>(LPad->clone());
692 NewLPadBB->getInstList().push_back(NewLPad);
693 while (!pred_empty(LPadBB)) {
694 auto *pred = *pred_begin(LPadBB);
695 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
696 Invoke->setUnwindDest(NewLPadBB);
699 // Replace the mapping of any nested landing pad that previously mapped
700 // to this landing pad with a referenced to the cloned version.
701 for (auto &LPadPair : NestedLPtoOriginalLP) {
702 const LandingPadInst *OriginalLPad = LPadPair.second;
703 if (OriginalLPad == LPad) {
704 LPadPair.second = NewLPad;
708 // Replace all extracted values with undef and ultimately replace the
709 // landingpad with undef.
710 // FIXME: This doesn't handle SEH GetExceptionCode(). For now, we just give
711 // out undef until we figure out the codegen support.
712 SmallVector<Instruction *, 4> Extracts;
713 for (User *U : LPad->users()) {
714 auto *E = dyn_cast<ExtractValueInst>(U);
717 assert(E->getNumIndices() == 1 &&
718 "Unexpected operation: extracting both landing pad values");
719 unsigned Idx = E->getIndices()[0];
720 assert(Idx == 0 || Idx == 1);
721 Extracts.push_back(E);
723 for (Instruction *E : Extracts) {
724 E->replaceAllUsesWith(UndefValue::get(E->getType()));
725 E->eraseFromParent();
727 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
729 // Add a call to describe the actions for this landing pad.
730 std::vector<Value *> ActionArgs;
731 for (ActionHandler *Action : Actions) {
732 // Action codes from docs are: 0 cleanup, 1 catch.
733 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
734 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
735 ActionArgs.push_back(CatchAction->getSelector());
736 // Find the frame escape index of the exception object alloca in the
738 int FrameEscapeIdx = -1;
739 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
740 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
741 auto I = FrameVarInfo.find(EHObj);
742 assert(I != FrameVarInfo.end() &&
743 "failed to map llvm.eh.begincatch var");
744 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
746 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
748 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
750 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
753 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
755 // Add an indirect branch listing possible successors of the catch handlers.
756 SetVector<BasicBlock *> ReturnTargets;
757 for (ActionHandler *Action : Actions) {
758 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
759 const auto &CatchTargets = CatchAction->getReturnTargets();
760 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
763 IndirectBrInst *Branch =
764 IndirectBrInst::Create(Recover, ReturnTargets.size(), NewLPadBB);
765 for (BasicBlock *Target : ReturnTargets)
766 Branch->addDestination(Target);
767 } // End for each landingpad
769 // If nothing got outlined, there is no more processing to be done.
770 if (!HandlersOutlined)
773 // Replace any nested landing pad stubs with the correct action handler.
774 // This must be done before we remove unreachable blocks because it
775 // cleans up references to outlined blocks that will be deleted.
776 for (auto &LPadPair : NestedLPtoOriginalLP)
777 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
778 NestedLPtoOriginalLP.clear();
780 F.addFnAttr("wineh-parent", F.getName());
782 // Delete any blocks that were only used by handlers that were outlined above.
783 removeUnreachableBlocks(F);
785 BasicBlock *Entry = &F.getEntryBlock();
786 IRBuilder<> Builder(F.getParent()->getContext());
787 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
789 Function *FrameEscapeFn =
790 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
791 Function *RecoverFrameFn =
792 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
793 SmallVector<Value *, 8> AllocasToEscape;
795 // Scan the entry block for an existing call to llvm.frameescape. We need to
796 // keep escaping those objects.
797 for (Instruction &I : F.front()) {
798 auto *II = dyn_cast<IntrinsicInst>(&I);
799 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
800 auto Args = II->arg_operands();
801 AllocasToEscape.append(Args.begin(), Args.end());
802 II->eraseFromParent();
807 // Finally, replace all of the temporary allocas for frame variables used in
808 // the outlined handlers with calls to llvm.framerecover.
809 for (auto &VarInfoEntry : FrameVarInfo) {
810 Value *ParentVal = VarInfoEntry.first;
811 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
812 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
814 // FIXME: We should try to sink unescaped allocas from the parent frame into
815 // the child frame. If the alloca is escaped, we have to use the lifetime
816 // markers to ensure that the alloca is only live within the child frame.
818 // Add this alloca to the list of things to escape.
819 AllocasToEscape.push_back(ParentAlloca);
821 // Next replace all outlined allocas that are mapped to it.
822 for (AllocaInst *TempAlloca : Allocas) {
823 if (TempAlloca == getCatchObjectSentinel())
824 continue; // Skip catch parameter sentinels.
825 Function *HandlerFn = TempAlloca->getParent()->getParent();
826 // FIXME: Sink this GEP into the blocks where it is used.
827 Builder.SetInsertPoint(TempAlloca);
828 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
829 Value *RecoverArgs[] = {
830 Builder.CreateBitCast(&F, Int8PtrType, ""),
831 &(HandlerFn->getArgumentList().back()),
832 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
833 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
834 // Add a pointer bitcast if the alloca wasn't an i8.
835 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
836 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
838 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
840 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
841 TempAlloca->removeFromParent();
842 RecoveredAlloca->takeName(TempAlloca);
845 } // End for each FrameVarInfo entry.
847 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
849 Builder.SetInsertPoint(&F.getEntryBlock().back());
850 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
852 // Clean up the handler action maps we created for this function
853 DeleteContainerSeconds(CatchHandlerMap);
854 CatchHandlerMap.clear();
855 DeleteContainerSeconds(CleanupHandlerMap);
856 CleanupHandlerMap.clear();
858 return HandlersOutlined;
861 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
862 // If the return values of the landing pad instruction are extracted and
863 // stored to memory, we want to promote the store locations to reg values.
864 SmallVector<AllocaInst *, 2> EHAllocas;
866 // The landingpad instruction returns an aggregate value. Typically, its
867 // value will be passed to a pair of extract value instructions and the
868 // results of those extracts are often passed to store instructions.
869 // In unoptimized code the stored value will often be loaded and then stored
871 for (auto *U : LPad->users()) {
872 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
876 for (auto *EU : Extract->users()) {
877 if (auto *Store = dyn_cast<StoreInst>(EU)) {
878 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
879 EHAllocas.push_back(AV);
884 // We can't do this without a dominator tree.
887 if (!EHAllocas.empty()) {
888 PromoteMemToReg(EHAllocas, *DT);
892 // After promotion, some extracts may be trivially dead. Remove them.
893 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
894 for (auto *U : Users)
895 RecursivelyDeleteTriviallyDeadInstructions(U);
898 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
899 LandingPadInst *OutlinedLPad,
900 const LandingPadInst *OriginalLPad,
901 FrameVarInfoMap &FrameVarInfo) {
902 // Get the nested block and erase the unreachable instruction that was
903 // temporarily inserted as its terminator.
904 LLVMContext &Context = ParentFn->getContext();
905 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
906 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
907 OutlinedBB->getTerminator()->eraseFromParent();
908 // That should leave OutlinedLPad as the last instruction in its block.
909 assert(&OutlinedBB->back() == OutlinedLPad);
911 // The original landing pad will have already had its action intrinsic
912 // built by the outlining loop. We need to clone that into the outlined
913 // location. It may also be necessary to add references to the exception
914 // variables to the outlined handler in which this landing pad is nested
915 // and remap return instructions in the nested handlers that should return
916 // to an address in the outlined handler.
917 Function *OutlinedHandlerFn = OutlinedBB->getParent();
918 BasicBlock::const_iterator II = OriginalLPad;
920 // The instruction after the landing pad should now be a call to eh.actions.
921 const Instruction *Recover = II;
922 assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
923 IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
925 // Remap the exception variables into the outlined function.
926 WinEHFrameVariableMaterializer Materializer(OutlinedHandlerFn, FrameVarInfo);
927 SmallVector<BlockAddress *, 4> ActionTargets;
928 SmallVector<ActionHandler *, 4> ActionList;
929 parseEHActions(EHActions, ActionList);
930 for (auto *Action : ActionList) {
931 auto *Catch = dyn_cast<CatchHandler>(Action);
934 // The dyn_cast to function here selects C++ catch handlers and skips
935 // SEH catch handlers.
936 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
939 // Visit all the return instructions, looking for places that return
940 // to a location within OutlinedHandlerFn.
941 for (BasicBlock &NestedHandlerBB : *Handler) {
942 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
946 // Handler functions must always return a block address.
947 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
948 // The original target will have been in the main parent function,
949 // but if it is the address of a block that has been outlined, it
950 // should be a block that was outlined into OutlinedHandlerFn.
951 assert(BA->getFunction() == ParentFn);
953 // Ignore targets that aren't part of OutlinedHandlerFn.
954 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
957 // If the return value is the address ofF a block that we
958 // previously outlined into the parent handler function, replace
959 // the return instruction and add the mapped target to the list
960 // of possible return addresses.
961 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
962 assert(MappedBB->getParent() == OutlinedHandlerFn);
963 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
964 Ret->eraseFromParent();
965 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
966 ActionTargets.push_back(NewBA);
969 DeleteContainerPointers(ActionList);
971 OutlinedBB->getInstList().push_back(EHActions);
973 // Insert an indirect branch into the outlined landing pad BB.
974 IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
975 // Add the previously collected action targets.
976 for (auto *Target : ActionTargets)
977 IBr->addDestination(Target->getBasicBlock());
980 // This function examines a block to determine whether the block ends with a
981 // conditional branch to a catch handler based on a selector comparison.
982 // This function is used both by the WinEHPrepare::findSelectorComparison() and
983 // WinEHCleanupDirector::handleTypeIdFor().
984 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
985 Constant *&Selector, BasicBlock *&NextBB) {
986 ICmpInst::Predicate Pred;
987 BasicBlock *TBB, *FBB;
990 if (!match(BB->getTerminator(),
991 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
995 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
996 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
999 if (Pred == CmpInst::ICMP_EQ) {
1005 if (Pred == CmpInst::ICMP_NE) {
1014 static bool isCatchBlock(BasicBlock *BB) {
1015 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1017 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1023 static BasicBlock *createStubLandingPad(Function *Handler,
1024 Value *PersonalityFn) {
1025 // FIXME: Finish this!
1026 LLVMContext &Context = Handler->getContext();
1027 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1028 Handler->getBasicBlockList().push_back(StubBB);
1029 IRBuilder<> Builder(StubBB);
1030 LandingPadInst *LPad = Builder.CreateLandingPad(
1031 llvm::StructType::get(Type::getInt8PtrTy(Context),
1032 Type::getInt32Ty(Context), nullptr),
1034 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1035 Function *ActionIntrin = Intrinsic::getDeclaration(Handler->getParent(),
1036 Intrinsic::eh_actions);
1037 Builder.CreateCall(ActionIntrin, "recover");
1038 LPad->setCleanup(true);
1039 Builder.CreateUnreachable();
1043 // Cycles through the blocks in an outlined handler function looking for an
1044 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1045 // landing pad if none is found. The code that generates the .xdata tables for
1046 // the handler needs at least one landing pad to identify the parent function's
1048 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
1049 Value *PersonalityFn) {
1050 ReturnInst *Ret = nullptr;
1051 UnreachableInst *Unreached = nullptr;
1052 for (BasicBlock &BB : *Handler) {
1053 TerminatorInst *Terminator = BB.getTerminator();
1054 // If we find an invoke, there is nothing to be done.
1055 auto *II = dyn_cast<InvokeInst>(Terminator);
1058 // If we've already recorded a return instruction, keep looking for invokes.
1060 Ret = dyn_cast<ReturnInst>(Terminator);
1061 // If we haven't recorded an unreachable instruction, try this terminator.
1063 Unreached = dyn_cast<UnreachableInst>(Terminator);
1066 // If we got this far, the handler contains no invokes. We should have seen
1067 // at least one return or unreachable instruction. We'll insert an invoke of
1068 // llvm.donothing ahead of that instruction.
1069 assert(Ret || Unreached);
1070 TerminatorInst *Term;
1075 BasicBlock *OldRetBB = Term->getParent();
1076 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term);
1077 // SplitBlock adds an unconditional branch instruction at the end of the
1078 // parent block. We want to replace that with an invoke call, so we can
1080 OldRetBB->getTerminator()->eraseFromParent();
1081 BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
1083 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1084 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1087 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1088 LandingPadInst *LPad, BasicBlock *StartBB,
1089 FrameVarInfoMap &VarInfo) {
1090 Module *M = SrcFn->getParent();
1091 LLVMContext &Context = M->getContext();
1093 // Create a new function to receive the handler contents.
1094 Type *Int8PtrType = Type::getInt8PtrTy(Context);
1095 std::vector<Type *> ArgTys;
1096 ArgTys.push_back(Int8PtrType);
1097 ArgTys.push_back(Int8PtrType);
1099 if (Action->getType() == Catch) {
1100 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
1101 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
1102 SrcFn->getName() + ".catch", M);
1104 FunctionType *FnType =
1105 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
1106 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
1107 SrcFn->getName() + ".cleanup", M);
1110 Handler->addFnAttr("wineh-parent", SrcFn->getName());
1112 // Generate a standard prolog to setup the frame recovery structure.
1113 IRBuilder<> Builder(Context);
1114 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1115 Handler->getBasicBlockList().push_front(Entry);
1116 Builder.SetInsertPoint(Entry);
1117 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1119 std::unique_ptr<WinEHCloningDirectorBase> Director;
1121 ValueToValueMapTy VMap;
1123 LandingPadMap &LPadMap = LPadMaps[LPad];
1124 if (!LPadMap.isInitialized())
1125 LPadMap.mapLandingPad(LPad);
1126 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1127 Constant *Sel = CatchAction->getSelector();
1128 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
1129 NestedLPtoOriginalLP));
1130 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1131 ConstantInt::get(Type::getInt32Ty(Context), 1));
1133 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
1134 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1135 UndefValue::get(Type::getInt32Ty(Context)));
1138 SmallVector<ReturnInst *, 8> Returns;
1139 ClonedCodeInfo OutlinedFunctionInfo;
1141 // If the start block contains PHI nodes, we need to map them.
1142 BasicBlock::iterator II = StartBB->begin();
1143 while (auto *PN = dyn_cast<PHINode>(II)) {
1144 bool Mapped = false;
1145 // Look for PHI values that we have already mapped (such as the selector).
1146 for (Value *Val : PN->incoming_values()) {
1147 if (VMap.count(Val)) {
1148 VMap[PN] = VMap[Val];
1152 // If we didn't find a match for this value, map it as an undef.
1154 VMap[PN] = UndefValue::get(PN->getType());
1159 // The landing pad value may be used by PHI nodes. It will ultimately be
1160 // eliminated, but we need it in the map for intermediate handling.
1161 VMap[LPad] = UndefValue::get(LPad->getType());
1163 // Skip over PHIs and, if applicable, landingpad instructions.
1164 II = StartBB->getFirstInsertionPt();
1166 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1167 /*ModuleLevelChanges=*/false, Returns, "",
1168 &OutlinedFunctionInfo, Director.get());
1170 // Move all the instructions in the first cloned block into our entry block.
1171 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
1172 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
1173 FirstClonedBB->eraseFromParent();
1175 // Make sure we can identify the handler's personality later.
1176 addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
1178 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1179 WinEHCatchDirector *CatchDirector =
1180 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1181 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1182 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1184 // Look for blocks that are not part of the landing pad that we just
1185 // outlined but terminate with a call to llvm.eh.endcatch and a
1186 // branch to a block that is in the handler we just outlined.
1187 // These blocks will be part of a nested landing pad that intends to
1188 // return to an address in this handler. This case is best handled
1189 // after both landing pads have been outlined, so for now we'll just
1190 // save the association of the blocks in LPadTargetBlocks. The
1191 // return instructions which are created from these branches will be
1192 // replaced after all landing pads have been outlined.
1193 for (const auto MapEntry : VMap) {
1194 // VMap maps all values and blocks that were just cloned, but dead
1195 // blocks which were pruned will map to nullptr.
1196 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1198 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1199 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1200 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1201 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1203 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1205 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1206 // This would indicate that a nested landing pad wants to return
1207 // to a block that is outlined into two different handlers.
1208 assert(!LPadTargetBlocks.count(MappedBB));
1209 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1213 } // End if (CatchAction)
1215 Action->setHandlerBlockOrFunc(Handler);
1220 /// This BB must end in a selector dispatch. All we need to do is pass the
1221 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1223 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1224 BasicBlock *StartBB) {
1225 BasicBlock *HandlerBB;
1228 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1230 // If this was EH dispatch, this must be a conditional branch to the handler
1232 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1233 // leading to crashes if some optimization hoists stuff here.
1234 assert(CatchAction->getSelector() && HandlerBB &&
1235 "expected catch EH dispatch");
1237 // This must be a catch-all. Split the block after the landingpad.
1238 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1240 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
1242 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1243 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1244 CatchAction->setReturnTargets(Targets);
1247 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1248 // Each instance of this class should only ever be used to map a single
1250 assert(OriginLPad == nullptr || OriginLPad == LPad);
1252 // If the landing pad has already been mapped, there's nothing more to do.
1253 if (OriginLPad == LPad)
1258 // The landingpad instruction returns an aggregate value. Typically, its
1259 // value will be passed to a pair of extract value instructions and the
1260 // results of those extracts will have been promoted to reg values before
1261 // this routine is called.
1262 for (auto *U : LPad->users()) {
1263 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1266 assert(Extract->getNumIndices() == 1 &&
1267 "Unexpected operation: extracting both landing pad values");
1268 unsigned int Idx = *(Extract->idx_begin());
1269 assert((Idx == 0 || Idx == 1) &&
1270 "Unexpected operation: extracting an unknown landing pad element");
1272 ExtractedEHPtrs.push_back(Extract);
1273 } else if (Idx == 1) {
1274 ExtractedSelectors.push_back(Extract);
1279 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1280 return BB->getLandingPadInst() == OriginLPad;
1283 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1284 if (Inst == OriginLPad)
1286 for (auto *Extract : ExtractedEHPtrs) {
1287 if (Inst == Extract)
1290 for (auto *Extract : ExtractedSelectors) {
1291 if (Inst == Extract)
1297 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1298 Value *SelectorValue) const {
1299 // Remap all landing pad extract instructions to the specified values.
1300 for (auto *Extract : ExtractedEHPtrs)
1301 VMap[Extract] = EHPtrValue;
1302 for (auto *Extract : ExtractedSelectors)
1303 VMap[Extract] = SelectorValue;
1306 static bool isFrameAddressCall(const Value *V) {
1307 return match(const_cast<Value *>(V),
1308 m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1311 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1312 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1313 // If this is one of the boilerplate landing pad instructions, skip it.
1314 // The instruction will have already been remapped in VMap.
1315 if (LPadMap.isLandingPadSpecificInst(Inst))
1316 return CloningDirector::SkipInstruction;
1318 // Nested landing pads will be cloned as stubs, with just the
1319 // landingpad instruction and an unreachable instruction. When
1320 // all landingpads have been outlined, we'll replace this with the
1321 // llvm.eh.actions call and indirect branch created when the
1322 // landing pad was outlined.
1323 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1324 return handleLandingPad(VMap, LPad, NewBB);
1327 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1328 return handleInvoke(VMap, Invoke, NewBB);
1330 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1331 return handleResume(VMap, Resume, NewBB);
1333 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1334 return handleCompare(VMap, Cmp, NewBB);
1336 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1337 return handleBeginCatch(VMap, Inst, NewBB);
1338 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1339 return handleEndCatch(VMap, Inst, NewBB);
1340 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1341 return handleTypeIdFor(VMap, Inst, NewBB);
1343 // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1344 // which is the FP of the parent.
1345 if (isFrameAddressCall(Inst)) {
1346 VMap[Inst] = EstablisherFrame;
1347 return CloningDirector::SkipInstruction;
1350 // Continue with the default cloning behavior.
1351 return CloningDirector::CloneInstruction;
1354 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1355 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1356 Instruction *NewInst = LPad->clone();
1357 if (LPad->hasName())
1358 NewInst->setName(LPad->getName());
1359 // Save this correlation for later processing.
1360 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1361 VMap[LPad] = NewInst;
1362 BasicBlock::InstListType &InstList = NewBB->getInstList();
1363 InstList.push_back(NewInst);
1364 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1365 return CloningDirector::StopCloningBB;
1368 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1369 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1370 // The argument to the call is some form of the first element of the
1371 // landingpad aggregate value, but that doesn't matter. It isn't used
1373 // The second argument is an outparameter where the exception object will be
1374 // stored. Typically the exception object is a scalar, but it can be an
1375 // aggregate when catching by value.
1376 // FIXME: Leave something behind to indicate where the exception object lives
1377 // for this handler. Should it be part of llvm.eh.actions?
1378 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1379 "llvm.eh.begincatch found while "
1380 "outlining catch handler.");
1381 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1382 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1383 return CloningDirector::SkipInstruction;
1384 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1385 "catch parameter is not static alloca");
1386 Materializer.escapeCatchObject(ExceptionObjectVar);
1387 return CloningDirector::SkipInstruction;
1390 CloningDirector::CloningAction
1391 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1392 const Instruction *Inst, BasicBlock *NewBB) {
1393 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1394 // It might be interesting to track whether or not we are inside a catch
1395 // function, but that might make the algorithm more brittle than it needs
1398 // The end catch call can occur in one of two places: either in a
1399 // landingpad block that is part of the catch handlers exception mechanism,
1400 // or at the end of the catch block. However, a catch-all handler may call
1401 // end catch from the original landing pad. If the call occurs in a nested
1402 // landing pad block, we must skip it and continue so that the landing pad
1404 auto *ParentBB = IntrinCall->getParent();
1405 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1406 return CloningDirector::SkipInstruction;
1408 // If an end catch occurs anywhere else we want to terminate the handler
1409 // with a return to the code that follows the endcatch call. If the
1410 // next instruction is not an unconditional branch, we need to split the
1411 // block to provide a clear target for the return instruction.
1412 BasicBlock *ContinueBB;
1413 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1414 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1415 if (!Branch || !Branch->isUnconditional()) {
1416 // We're interrupting the cloning process at this location, so the
1417 // const_cast we're doing here will not cause a problem.
1418 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1419 const_cast<Instruction *>(cast<Instruction>(Next)));
1421 ContinueBB = Branch->getSuccessor(0);
1424 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1425 ReturnTargets.push_back(ContinueBB);
1427 // We just added a terminator to the cloned block.
1428 // Tell the caller to stop processing the current basic block so that
1429 // the branch instruction will be skipped.
1430 return CloningDirector::StopCloningBB;
1433 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1434 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1435 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1436 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1437 // This causes a replacement that will collapse the landing pad CFG based
1438 // on the filter function we intend to match.
1439 if (Selector == CurrentSelector)
1440 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1442 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1443 // Tell the caller not to clone this instruction.
1444 return CloningDirector::SkipInstruction;
1447 CloningDirector::CloningAction
1448 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1449 const InvokeInst *Invoke, BasicBlock *NewBB) {
1450 return CloningDirector::CloneInstruction;
1453 CloningDirector::CloningAction
1454 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1455 const ResumeInst *Resume, BasicBlock *NewBB) {
1456 // Resume instructions shouldn't be reachable from catch handlers.
1457 // We still need to handle it, but it will be pruned.
1458 BasicBlock::InstListType &InstList = NewBB->getInstList();
1459 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1460 return CloningDirector::StopCloningBB;
1463 CloningDirector::CloningAction
1464 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1465 const CmpInst *Compare, BasicBlock *NewBB) {
1466 const IntrinsicInst *IntrinCall = nullptr;
1467 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1468 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1469 } else if (match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1470 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1473 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1474 // This causes a replacement that will collapse the landing pad CFG based
1475 // on the filter function we intend to match.
1476 if (Selector == CurrentSelector->stripPointerCasts()) {
1477 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1480 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1482 return CloningDirector::SkipInstruction;
1484 return CloningDirector::CloneInstruction;
1487 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1488 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1489 // The MS runtime will terminate the process if an exception occurs in a
1490 // cleanup handler, so we shouldn't encounter landing pads in the actual
1491 // cleanup code, but they may appear in catch blocks. Depending on where
1492 // we started cloning we may see one, but it will get dropped during dead
1494 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1495 VMap[LPad] = NewInst;
1496 BasicBlock::InstListType &InstList = NewBB->getInstList();
1497 InstList.push_back(NewInst);
1498 return CloningDirector::StopCloningBB;
1501 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1502 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1503 // Cleanup code may flow into catch blocks or the catch block may be part
1504 // of a branch that will be optimized away. We'll insert a return
1505 // instruction now, but it may be pruned before the cloning process is
1507 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1508 return CloningDirector::StopCloningBB;
1511 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1512 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1513 // Cleanup handlers nested within catch handlers may begin with a call to
1514 // eh.endcatch. We can just ignore that instruction.
1515 return CloningDirector::SkipInstruction;
1518 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1519 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1520 // If we encounter a selector comparison while cloning a cleanup handler,
1521 // we want to stop cloning immediately. Anything after the dispatch
1522 // will be outlined into a different handler.
1523 BasicBlock *CatchHandler;
1526 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1527 CatchHandler, Selector, NextBB)) {
1528 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1529 return CloningDirector::StopCloningBB;
1531 // If eg.typeid.for is called for any other reason, it can be ignored.
1532 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1533 return CloningDirector::SkipInstruction;
1536 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1537 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1538 // All invokes in cleanup handlers can be replaced with calls.
1539 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1540 // Insert a normal call instruction...
1542 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1543 Invoke->getName(), NewBB);
1544 NewCall->setCallingConv(Invoke->getCallingConv());
1545 NewCall->setAttributes(Invoke->getAttributes());
1546 NewCall->setDebugLoc(Invoke->getDebugLoc());
1547 VMap[Invoke] = NewCall;
1549 // Remap the operands.
1550 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1552 // Insert an unconditional branch to the normal destination.
1553 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1555 // The unwind destination won't be cloned into the new function, so
1556 // we don't need to clean up its phi nodes.
1558 // We just added a terminator to the cloned block.
1559 // Tell the caller to stop processing the current basic block.
1560 return CloningDirector::CloneSuccessors;
1563 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1564 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1565 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1567 // We just added a terminator to the cloned block.
1568 // Tell the caller to stop processing the current basic block so that
1569 // the branch instruction will be skipped.
1570 return CloningDirector::StopCloningBB;
1573 CloningDirector::CloningAction
1574 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1575 const CmpInst *Compare, BasicBlock *NewBB) {
1576 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1577 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1578 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1579 return CloningDirector::SkipInstruction;
1581 return CloningDirector::CloneInstruction;
1585 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1586 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1587 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1588 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1589 Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
1592 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1593 // If we're asked to materialize a static alloca, we temporarily create an
1594 // alloca in the outlined function and add this to the FrameVarInfo map. When
1595 // all the outlining is complete, we'll replace these temporary allocas with
1596 // calls to llvm.framerecover.
1597 if (auto *AV = dyn_cast<AllocaInst>(V)) {
1598 assert(AV->isStaticAlloca() &&
1599 "cannot materialize un-demoted dynamic alloca");
1600 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1601 Builder.Insert(NewAlloca, AV->getName());
1602 FrameVarInfo[AV].push_back(NewAlloca);
1606 if (isa<Instruction>(V) || isa<Argument>(V)) {
1607 errs() << "Failed to demote instruction used in exception handler:\n";
1608 errs() << " " << *V << '\n';
1609 report_fatal_error("WinEHPrepare failed to demote instruction");
1612 // Don't materialize other values.
1616 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1617 // Catch parameter objects have to live in the parent frame. When we see a use
1618 // of a catch parameter, add a sentinel to the multimap to indicate that it's
1619 // used from another handler. This will prevent us from trying to sink the
1620 // alloca into the handler and ensure that the catch parameter is present in
1621 // the call to llvm.frameescape.
1622 FrameVarInfo[V].push_back(getCatchObjectSentinel());
1625 // This function maps the catch and cleanup handlers that are reachable from the
1626 // specified landing pad. The landing pad sequence will have this basic shape:
1628 // <cleanup handler>
1629 // <selector comparison>
1631 // <cleanup handler>
1632 // <selector comparison>
1634 // <cleanup handler>
1637 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1638 // any arbitrary control flow, but all paths through the cleanup code must
1639 // eventually reach the next selector comparison and no path can skip to a
1640 // different selector comparisons, though some paths may terminate abnormally.
1641 // Therefore, we will use a depth first search from the start of any given
1642 // cleanup block and stop searching when we find the next selector comparison.
1644 // If the landingpad instruction does not have a catch clause, we will assume
1645 // that any instructions other than selector comparisons and catch handlers can
1646 // be ignored. In practice, these will only be the boilerplate instructions.
1648 // The catch handlers may also have any control structure, but we are only
1649 // interested in the start of the catch handlers, so we don't need to actually
1650 // follow the flow of the catch handlers. The start of the catch handlers can
1651 // be located from the compare instructions, but they can be skipped in the
1652 // flow by following the contrary branch.
1653 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1654 LandingPadActions &Actions) {
1655 unsigned int NumClauses = LPad->getNumClauses();
1656 unsigned int HandlersFound = 0;
1657 BasicBlock *BB = LPad->getParent();
1659 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1661 if (NumClauses == 0) {
1662 findCleanupHandlers(Actions, BB, nullptr);
1666 VisitedBlockSet VisitedBlocks;
1668 while (HandlersFound != NumClauses) {
1669 BasicBlock *NextBB = nullptr;
1671 // See if the clause we're looking for is a catch-all.
1672 // If so, the catch begins immediately.
1673 Constant *ExpectedSelector = LPad->getClause(HandlersFound)->stripPointerCasts();
1674 if (isa<ConstantPointerNull>(ExpectedSelector)) {
1675 // The catch all must occur last.
1676 assert(HandlersFound == NumClauses - 1);
1678 // There can be additional selector dispatches in the call chain that we
1680 BasicBlock *CatchBlock = nullptr;
1682 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1683 DEBUG(dbgs() << " Found extra catch dispatch in block "
1684 << CatchBlock->getName() << "\n");
1688 // For C++ EH, check if there is any interesting cleanup code before we
1689 // begin the catch. This is important because cleanups cannot rethrow
1690 // exceptions but code called from catches can. For SEH, it isn't
1691 // important if some finally code before a catch-all is executed out of
1692 // line or after recovering from the exception.
1693 if (Personality == EHPersonality::MSVC_CXX)
1694 findCleanupHandlers(Actions, BB, BB);
1696 // Add the catch handler to the action list.
1697 CatchHandler *Action = nullptr;
1698 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1699 // If the CatchHandlerMap already has an entry for this BB, re-use it.
1700 Action = CatchHandlerMap[BB];
1701 assert(Action->getSelector() == ExpectedSelector);
1703 // Since this is a catch-all handler, the selector won't actually appear
1704 // in the code anywhere. ExpectedSelector here is the constant null ptr
1705 // that we got from the landing pad instruction.
1706 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1707 CatchHandlerMap[BB] = Action;
1709 Actions.insertCatchHandler(Action);
1710 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1713 // Once we reach a catch-all, don't expect to hit a resume instruction.
1718 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1719 assert(CatchAction);
1721 // See if there is any interesting code executed before the dispatch.
1722 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
1724 // When the source program contains multiple nested try blocks the catch
1725 // handlers can get strung together in such a way that we can encounter
1726 // a dispatch for a selector that we've already had a handler for.
1727 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1730 // Add the catch handler to the action list.
1731 DEBUG(dbgs() << " Found catch dispatch in block "
1732 << CatchAction->getStartBlock()->getName() << "\n");
1733 Actions.insertCatchHandler(CatchAction);
1735 // Under some circumstances optimized IR will flow unconditionally into a
1736 // handler block without checking the selector. This can only happen if
1737 // the landing pad has a catch-all handler and the handler for the
1738 // preceeding catch clause is identical to the catch-call handler
1739 // (typically an empty catch). In this case, the handler must be shared
1740 // by all remaining clauses.
1741 if (isa<ConstantPointerNull>(
1742 CatchAction->getSelector()->stripPointerCasts())) {
1743 DEBUG(dbgs() << " Applying early catch-all handler in block "
1744 << CatchAction->getStartBlock()->getName()
1745 << " to all remaining clauses.\n");
1746 Actions.insertCatchHandler(CatchAction);
1750 DEBUG(dbgs() << " Found extra catch dispatch in block "
1751 << CatchAction->getStartBlock()->getName() << "\n");
1754 // Move on to the block after the catch handler.
1758 // If we didn't wind up in a catch-all, see if there is any interesting code
1759 // executed before the resume.
1760 findCleanupHandlers(Actions, BB, BB);
1762 // It's possible that some optimization moved code into a landingpad that
1764 // previously being used for cleanup. If that happens, we need to execute
1766 // extra code from a cleanup handler.
1767 if (Actions.includesCleanup() && !LPad->isCleanup())
1768 LPad->setCleanup(true);
1771 // This function searches starting with the input block for the next
1772 // block that terminates with a branch whose condition is based on a selector
1773 // comparison. This may be the input block. See the mapLandingPadBlocks
1774 // comments for a discussion of control flow assumptions.
1776 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1777 BasicBlock *&NextBB,
1778 VisitedBlockSet &VisitedBlocks) {
1779 // See if we've already found a catch handler use it.
1780 // Call count() first to avoid creating a null entry for blocks
1781 // we haven't seen before.
1782 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1783 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1784 NextBB = Action->getNextBB();
1788 // VisitedBlocks applies only to the current search. We still
1789 // need to consider blocks that we've visited while mapping other
1791 VisitedBlocks.insert(BB);
1793 BasicBlock *CatchBlock = nullptr;
1794 Constant *Selector = nullptr;
1796 // If this is the first time we've visited this block from any landing pad
1797 // look to see if it is a selector dispatch block.
1798 if (!CatchHandlerMap.count(BB)) {
1799 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1800 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1801 CatchHandlerMap[BB] = Action;
1804 // If we encounter a block containing an llvm.eh.begincatch before we
1805 // find a selector dispatch block, the handler is assumed to be
1806 // reached unconditionally. This happens for catch-all blocks, but
1807 // it can also happen for other catch handlers that have been combined
1808 // with the catch-all handler during optimization.
1809 if (isCatchBlock(BB)) {
1810 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
1811 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
1812 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
1813 CatchHandlerMap[BB] = Action;
1818 // Visit each successor, looking for the dispatch.
1819 // FIXME: We expect to find the dispatch quickly, so this will probably
1820 // work better as a breadth first search.
1821 for (BasicBlock *Succ : successors(BB)) {
1822 if (VisitedBlocks.count(Succ))
1825 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1832 // These are helper functions to combine repeated code from findCleanupHandlers.
1833 static void createCleanupHandler(LandingPadActions &Actions,
1834 CleanupHandlerMapTy &CleanupHandlerMap,
1836 CleanupHandler *Action = new CleanupHandler(BB);
1837 CleanupHandlerMap[BB] = Action;
1838 Actions.insertCleanupHandler(Action);
1839 DEBUG(dbgs() << " Found cleanup code in block "
1840 << Action->getStartBlock()->getName() << "\n");
1843 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1844 Instruction *MaybeCall) {
1845 // Look for finally blocks that Clang has already outlined for us.
1846 // %fp = call i8* @llvm.frameaddress(i32 0)
1847 // call void @"fin$parent"(iN 1, i8* %fp)
1848 if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1849 MaybeCall = MaybeCall->getNextNode();
1850 CallSite FinallyCall(MaybeCall);
1851 if (!FinallyCall || FinallyCall.arg_size() != 2)
1853 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
1855 if (!isFrameAddressCall(FinallyCall.getArgument(1)))
1860 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
1861 // Skip single ubr blocks.
1862 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
1863 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
1864 if (Br && Br->isUnconditional())
1865 BB = Br->getSuccessor(0);
1872 // This function searches starting with the input block for the next block that
1873 // contains code that is not part of a catch handler and would not be eliminated
1874 // during handler outlining.
1876 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
1877 BasicBlock *StartBB, BasicBlock *EndBB) {
1878 // Here we will skip over the following:
1880 // landing pad prolog:
1882 // Unconditional branches
1884 // Selector dispatch
1888 // Anything else marks the start of an interesting block
1890 BasicBlock *BB = StartBB;
1891 // Anything other than an unconditional branch will kick us out of this loop
1892 // one way or another.
1894 BB = followSingleUnconditionalBranches(BB);
1895 // If we've already scanned this block, don't scan it again. If it is
1896 // a cleanup block, there will be an action in the CleanupHandlerMap.
1897 // If we've scanned it and it is not a cleanup block, there will be a
1898 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1899 // be no entry in the CleanupHandlerMap. We must call count() first to
1900 // avoid creating a null entry for blocks we haven't scanned.
1901 if (CleanupHandlerMap.count(BB)) {
1902 if (auto *Action = CleanupHandlerMap[BB]) {
1903 Actions.insertCleanupHandler(Action);
1904 DEBUG(dbgs() << " Found cleanup code in block "
1905 << Action->getStartBlock()->getName() << "\n");
1906 // FIXME: This cleanup might chain into another, and we need to discover
1910 // Here we handle the case where the cleanup handler map contains a
1911 // value for this block but the value is a nullptr. This means that
1912 // we have previously analyzed the block and determined that it did
1913 // not contain any cleanup code. Based on the earlier analysis, we
1914 // know the the block must end in either an unconditional branch, a
1915 // resume or a conditional branch that is predicated on a comparison
1916 // with a selector. Either the resume or the selector dispatch
1917 // would terminate the search for cleanup code, so the unconditional
1918 // branch is the only case for which we might need to continue
1920 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
1921 if (SuccBB == BB || SuccBB == EndBB)
1928 // Create an entry in the cleanup handler map for this block. Initially
1929 // we create an entry that says this isn't a cleanup block. If we find
1930 // cleanup code, the caller will replace this entry.
1931 CleanupHandlerMap[BB] = nullptr;
1933 TerminatorInst *Terminator = BB->getTerminator();
1935 // Landing pad blocks have extra instructions we need to accept.
1936 LandingPadMap *LPadMap = nullptr;
1937 if (BB->isLandingPad()) {
1938 LandingPadInst *LPad = BB->getLandingPadInst();
1939 LPadMap = &LPadMaps[LPad];
1940 if (!LPadMap->isInitialized())
1941 LPadMap->mapLandingPad(LPad);
1944 // Look for the bare resume pattern:
1945 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1946 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
1947 // resume { i8*, i32 } %lpad.val2
1948 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1949 InsertValueInst *Insert1 = nullptr;
1950 InsertValueInst *Insert2 = nullptr;
1951 Value *ResumeVal = Resume->getOperand(0);
1952 // If the resume value isn't a phi or landingpad value, it should be a
1953 // series of insertions. Identify them so we can avoid them when scanning
1955 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
1956 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1958 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1959 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1961 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1963 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1965 Instruction *Inst = II;
1966 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1968 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1970 if (!Inst->hasOneUse() ||
1971 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1972 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1978 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1979 if (Branch && Branch->isConditional()) {
1980 // Look for the selector dispatch.
1981 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1982 // %matches = icmp eq i32 %sel, %2
1983 // br i1 %matches, label %catch14, label %eh.resume
1984 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1985 if (!Compare || !Compare->isEquality())
1986 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1987 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1989 Instruction *Inst = II;
1990 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1992 if (Inst == Compare || Inst == Branch)
1994 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1996 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1998 // The selector dispatch block should always terminate our search.
1999 assert(BB == EndBB);
2003 if (isAsynchronousEHPersonality(Personality)) {
2004 // If this is a landingpad block, split the block at the first non-landing
2006 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2008 while (MaybeCall != BB->getTerminator() &&
2009 LPadMap->isLandingPadSpecificInst(MaybeCall))
2010 MaybeCall = MaybeCall->getNextNode();
2013 // Look for outlined finally calls.
2014 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2015 Function *Fin = FinallyCall.getCalledFunction();
2016 assert(Fin && "outlined finally call should be direct");
2017 auto *Action = new CleanupHandler(BB);
2018 Action->setHandlerBlockOrFunc(Fin);
2019 Actions.insertCleanupHandler(Action);
2020 CleanupHandlerMap[BB] = Action;
2021 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2022 << Fin->getName() << " in block "
2023 << Action->getStartBlock()->getName() << "\n");
2025 // Split the block if there were more interesting instructions and look
2026 // for finally calls in the normal successor block.
2027 BasicBlock *SuccBB = BB;
2028 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2029 FinallyCall.getInstruction()->getNextNode() != BB->getTerminator()) {
2030 SuccBB = BB->splitBasicBlock(FinallyCall.getInstruction()->getNextNode());
2032 if (FinallyCall.isInvoke()) {
2033 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
2035 SuccBB = BB->getUniqueSuccessor();
2036 assert(SuccBB && "splitOutlinedFinallyCalls didn't insert a branch");
2046 // Anything else is either a catch block or interesting cleanup code.
2047 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2049 Instruction *Inst = II;
2050 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2052 // Unconditional branches fall through to this loop.
2055 // If this is a catch block, there is no cleanup code to be found.
2056 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2058 // If this a nested landing pad, it may contain an endcatch call.
2059 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2061 // Anything else makes this interesting cleanup code.
2062 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2065 // Only unconditional branches in empty blocks should get this far.
2066 assert(Branch && Branch->isUnconditional());
2069 BB = Branch->getSuccessor(0);
2073 // This is a public function, declared in WinEHFuncInfo.h and is also
2074 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2075 void llvm::parseEHActions(const IntrinsicInst *II,
2076 SmallVectorImpl<ActionHandler *> &Actions) {
2077 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2078 uint64_t ActionKind =
2079 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2080 if (ActionKind == /*catch=*/1) {
2081 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2082 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2083 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2084 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2086 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
2087 CH->setHandlerBlockOrFunc(Handler);
2088 CH->setExceptionVarIndex(EHObjIndexVal);
2089 Actions.push_back(CH);
2090 } else if (ActionKind == 0) {
2091 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2093 auto *CH = new CleanupHandler(/*BB=*/nullptr);
2094 CH->setHandlerBlockOrFunc(Handler);
2095 Actions.push_back(CH);
2097 llvm_unreachable("Expected either a catch or cleanup handler!");
2100 std::reverse(Actions.begin(), Actions.end());