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 for functions using a personality function from a runtime
12 // provided by MSVC. Functions with other personality functions are left alone
13 // and may be prepared by other passes. In particular, all supported MSVC
14 // personality functions require cleanup code to be outlined, and the C++
15 // personality requires catch handler code to be outlined.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/TinyPtrVector.h"
26 #include "llvm/Analysis/CFG.h"
27 #include "llvm/Analysis/LibCallSemantics.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/CodeGen/WinEHFuncInfo.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PatternMatch.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
47 using namespace llvm::PatternMatch;
49 #define DEBUG_TYPE "winehprepare"
53 // This map is used to model frame variable usage during outlining, to
54 // construct a structure type to hold the frame variables in a frame
55 // allocation block, and to remap the frame variable allocas (including
56 // spill locations as needed) to GEPs that get the variable from the
57 // frame allocation structure.
58 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
60 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
62 AllocaInst *getCatchObjectSentinel() {
63 return static_cast<AllocaInst *>(nullptr) + 1;
66 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
68 class LandingPadActions;
71 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
72 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
74 class WinEHPrepare : public FunctionPass {
76 static char ID; // Pass identification, replacement for typeid.
77 WinEHPrepare(const TargetMachine *TM = nullptr)
80 TheTriple = TM->getTargetTriple();
83 bool runOnFunction(Function &Fn) override;
85 bool doFinalization(Module &M) override;
87 void getAnalysisUsage(AnalysisUsage &AU) const override;
89 const char *getPassName() const override {
90 return "Windows exception handling preparation";
94 bool prepareExceptionHandlers(Function &F,
95 SmallVectorImpl<LandingPadInst *> &LPads);
96 void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
97 void promoteLandingPadValues(LandingPadInst *LPad);
98 void demoteValuesLiveAcrossHandlers(Function &F,
99 SmallVectorImpl<LandingPadInst *> &LPads);
100 void findSEHEHReturnPoints(Function &F,
101 SetVector<BasicBlock *> &EHReturnBlocks);
102 void findCXXEHReturnPoints(Function &F,
103 SetVector<BasicBlock *> &EHReturnBlocks);
104 void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
105 SetVector<BasicBlock*> &Targets);
106 void completeNestedLandingPad(Function *ParentFn,
107 LandingPadInst *OutlinedLPad,
108 const LandingPadInst *OriginalLPad,
109 FrameVarInfoMap &VarInfo);
110 Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
111 const Twine &Name, Module *M, Value *&ParentFP);
112 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
113 LandingPadInst *LPad, BasicBlock *StartBB,
114 FrameVarInfoMap &VarInfo);
115 void addStubInvokeToHandlerIfNeeded(Function *Handler);
117 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
118 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
119 VisitedBlockSet &VisitedBlocks);
120 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
123 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
125 bool prepareExplicitEH(Function &F);
126 void numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB);
130 // All fields are reset by runOnFunction.
131 DominatorTree *DT = nullptr;
132 const TargetLibraryInfo *LibInfo = nullptr;
133 EHPersonality Personality = EHPersonality::Unknown;
134 CatchHandlerMapTy CatchHandlerMap;
135 CleanupHandlerMapTy CleanupHandlerMap;
136 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
137 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
138 SmallPtrSet<BasicBlock *, 4> EHBlocks;
139 SetVector<BasicBlock *> EHReturnBlocks;
141 // This maps landing pad instructions found in outlined handlers to
142 // the landing pad instruction in the parent function from which they
143 // were cloned. The cloned/nested landing pad is used as the key
144 // because the landing pad may be cloned into multiple handlers.
145 // This map will be used to add the llvm.eh.actions call to the nested
146 // landing pads after all handlers have been outlined.
147 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
149 // This maps blocks in the parent function which are destinations of
150 // catch handlers to cloned blocks in (other) outlined handlers. This
151 // handles the case where a nested landing pads has a catch handler that
152 // returns to a handler function rather than the parent function.
153 // The original block is used as the key here because there should only
154 // ever be one handler function from which the cloned block is not pruned.
155 // The original block will be pruned from the parent function after all
156 // handlers have been outlined. This map will be used to adjust the
157 // return instructions of handlers which return to the block that was
158 // outlined into a handler. This is done after all handlers have been
159 // outlined but before the outlined code is pruned from the parent function.
160 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
162 // Map from outlined handler to call to parent local address. Only used for
164 DenseMap<Function *, Value *> HandlerToParentFP;
166 AllocaInst *SEHExceptionCodeSlot = nullptr;
168 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
169 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
172 class WinEHFrameVariableMaterializer : public ValueMaterializer {
174 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
175 FrameVarInfoMap &FrameVarInfo);
176 ~WinEHFrameVariableMaterializer() override {}
178 Value *materializeValueFor(Value *V) override;
180 void escapeCatchObject(Value *V);
183 FrameVarInfoMap &FrameVarInfo;
187 class LandingPadMap {
189 LandingPadMap() : OriginLPad(nullptr) {}
190 void mapLandingPad(const LandingPadInst *LPad);
192 bool isInitialized() { return OriginLPad != nullptr; }
194 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
195 bool isLandingPadSpecificInst(const Instruction *Inst) const;
197 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
198 Value *SelectorValue) const;
201 const LandingPadInst *OriginLPad;
202 // We will normally only see one of each of these instructions, but
203 // if more than one occurs for some reason we can handle that.
204 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
205 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
208 class WinEHCloningDirectorBase : public CloningDirector {
210 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
211 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
212 : Materializer(HandlerFn, ParentFP, VarInfo),
213 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
214 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
215 LPadMap(LPadMap), ParentFP(ParentFP) {}
217 CloningAction handleInstruction(ValueToValueMapTy &VMap,
218 const Instruction *Inst,
219 BasicBlock *NewBB) override;
221 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
222 const Instruction *Inst,
223 BasicBlock *NewBB) = 0;
224 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
225 const Instruction *Inst,
226 BasicBlock *NewBB) = 0;
227 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
228 const Instruction *Inst,
229 BasicBlock *NewBB) = 0;
230 virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
231 const IndirectBrInst *IBr,
232 BasicBlock *NewBB) = 0;
233 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
234 const InvokeInst *Invoke,
235 BasicBlock *NewBB) = 0;
236 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
237 const ResumeInst *Resume,
238 BasicBlock *NewBB) = 0;
239 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
240 const CmpInst *Compare,
241 BasicBlock *NewBB) = 0;
242 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
243 const LandingPadInst *LPad,
244 BasicBlock *NewBB) = 0;
246 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
249 WinEHFrameVariableMaterializer Materializer;
250 Type *SelectorIDType;
252 LandingPadMap &LPadMap;
254 /// The value representing the parent frame pointer.
258 class WinEHCatchDirector : public WinEHCloningDirectorBase {
261 Function *CatchFn, Value *ParentFP, Value *Selector,
262 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
263 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
264 DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
265 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
266 CurrentSelector(Selector->stripPointerCasts()),
267 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
268 DT(DT), EHBlocks(EHBlocks) {}
270 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
271 const Instruction *Inst,
272 BasicBlock *NewBB) override;
273 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
274 BasicBlock *NewBB) override;
275 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
276 const Instruction *Inst,
277 BasicBlock *NewBB) override;
278 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
279 const IndirectBrInst *IBr,
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, const CmpInst *Compare,
286 BasicBlock *NewBB) override;
287 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
288 const LandingPadInst *LPad,
289 BasicBlock *NewBB) override;
291 Value *getExceptionVar() { return ExceptionObjectVar; }
292 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
295 Value *CurrentSelector;
297 Value *ExceptionObjectVar;
298 TinyPtrVector<BasicBlock *> ReturnTargets;
300 // This will be a reference to the field of the same name in the WinEHPrepare
301 // object which instantiates this WinEHCatchDirector object.
302 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
304 SmallPtrSetImpl<BasicBlock *> &EHBlocks;
307 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
309 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
310 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
311 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
314 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
315 const Instruction *Inst,
316 BasicBlock *NewBB) override;
317 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
318 BasicBlock *NewBB) override;
319 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
320 const Instruction *Inst,
321 BasicBlock *NewBB) override;
322 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
323 const IndirectBrInst *IBr,
324 BasicBlock *NewBB) override;
325 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
326 BasicBlock *NewBB) override;
327 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
328 BasicBlock *NewBB) override;
329 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
330 BasicBlock *NewBB) override;
331 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
332 const LandingPadInst *LPad,
333 BasicBlock *NewBB) override;
336 class LandingPadActions {
338 LandingPadActions() : HasCleanupHandlers(false) {}
340 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
341 void insertCleanupHandler(CleanupHandler *Action) {
342 Actions.push_back(Action);
343 HasCleanupHandlers = true;
346 bool includesCleanup() const { return HasCleanupHandlers; }
348 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
349 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
350 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
353 // Note that this class does not own the ActionHandler objects in this vector.
354 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
355 // in the WinEHPrepare class.
356 SmallVector<ActionHandler *, 4> Actions;
357 bool HasCleanupHandlers;
360 } // end anonymous namespace
362 char WinEHPrepare::ID = 0;
363 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
366 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
367 return new WinEHPrepare(TM);
370 bool WinEHPrepare::runOnFunction(Function &Fn) {
371 if (!Fn.hasPersonalityFn())
374 // No need to prepare outlined handlers.
375 if (Fn.hasFnAttribute("wineh-parent"))
378 // Classify the personality to see what kind of preparation we need.
379 Personality = classifyEHPersonality(Fn.getPersonalityFn());
381 // Do nothing if this is not an MSVC personality.
382 if (!isMSVCEHPersonality(Personality))
385 SmallVector<LandingPadInst *, 4> LPads;
386 SmallVector<ResumeInst *, 4> Resumes;
387 bool ForExplicitEH = false;
388 for (BasicBlock &BB : Fn) {
389 if (auto *LP = BB.getLandingPadInst()) {
391 } else if (BB.getFirstNonPHI()->isEHPad()) {
392 ForExplicitEH = true;
395 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
396 Resumes.push_back(Resume);
400 return prepareExplicitEH(Fn);
402 // No need to prepare functions that lack landing pads.
406 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
407 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
409 // If there were any landing pads, prepareExceptionHandlers will make changes.
410 prepareExceptionHandlers(Fn, LPads);
414 bool WinEHPrepare::doFinalization(Module &M) { return false; }
416 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
417 AU.addRequired<DominatorTreeWrapperPass>();
418 AU.addRequired<TargetLibraryInfoWrapperPass>();
421 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
422 Constant *&Selector, BasicBlock *&NextBB);
424 // Finds blocks reachable from the starting set Worklist. Does not follow unwind
425 // edges or blocks listed in StopPoints.
426 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
427 SetVector<BasicBlock *> &Worklist,
428 const SetVector<BasicBlock *> *StopPoints) {
429 while (!Worklist.empty()) {
430 BasicBlock *BB = Worklist.pop_back_val();
432 // Don't cross blocks that we should stop at.
433 if (StopPoints && StopPoints->count(BB))
436 if (!ReachableBBs.insert(BB).second)
437 continue; // Already visited.
439 // Don't follow unwind edges of invokes.
440 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
441 Worklist.insert(II->getNormalDest());
445 // Otherwise, follow all successors.
446 Worklist.insert(succ_begin(BB), succ_end(BB));
450 // Attempt to find an instruction where a block can be split before
451 // a call to llvm.eh.begincatch and its operands. If the block
452 // begins with the begincatch call or one of its adjacent operands
453 // the block will not be split.
454 static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
456 // If the begincatch call is already the first instruction in the block,
458 Instruction *FirstNonPHI = BB->getFirstNonPHI();
459 if (II == FirstNonPHI)
462 // If either operand is in the same basic block as the instruction and
463 // isn't used by another instruction before the begincatch call, include it
464 // in the split block.
465 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
466 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
468 Instruction *I = II->getPrevNode();
469 Instruction *LastI = II;
471 while (I == Op0 || I == Op1) {
472 // If the block begins with one of the operands and there are no other
473 // instructions between the operand and the begincatch call, don't split.
474 if (I == FirstNonPHI)
478 I = I->getPrevNode();
481 // If there is at least one instruction in the block before the begincatch
482 // call and its operands, split the block at either the begincatch or
487 /// Find all points where exceptional control rejoins normal control flow via
488 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
489 void WinEHPrepare::findCXXEHReturnPoints(
490 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
491 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
492 BasicBlock *BB = BBI;
493 for (Instruction &I : *BB) {
494 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
495 Instruction *SplitPt =
496 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
498 // Split the block before the llvm.eh.begincatch call to allow
499 // cleanup and catch code to be distinguished later.
500 // Do not update BBI because we still need to process the
501 // portion of the block that we are splitting off.
502 SplitBlock(BB, SplitPt, DT);
506 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
507 // Split the block after the call to llvm.eh.endcatch if there is
508 // anything other than an unconditional branch, or if the successor
509 // starts with a phi.
510 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
511 if (!Br || !Br->isUnconditional() ||
512 isa<PHINode>(Br->getSuccessor(0)->begin())) {
513 DEBUG(dbgs() << "splitting block " << BB->getName()
514 << " with llvm.eh.endcatch\n");
515 BBI = SplitBlock(BB, I.getNextNode(), DT);
517 // The next BB is normal control flow.
518 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
525 static bool isCatchAllLandingPad(const BasicBlock *BB) {
526 const LandingPadInst *LP = BB->getLandingPadInst();
529 unsigned N = LP->getNumClauses();
530 return (N > 0 && LP->isCatch(N - 1) &&
531 isa<ConstantPointerNull>(LP->getClause(N - 1)));
534 /// Find all points where exceptions control rejoins normal control flow via
535 /// selector dispatch.
536 void WinEHPrepare::findSEHEHReturnPoints(
537 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
538 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
539 BasicBlock *BB = BBI;
540 // If the landingpad is a catch-all, treat the whole lpad as if it is
541 // reachable from normal control flow.
542 // FIXME: This is imprecise. We need a better way of identifying where a
543 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
545 if (isCatchAllLandingPad(BB)) {
546 EHReturnBlocks.insert(BB);
550 BasicBlock *CatchHandler;
553 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
554 // Split the edge if there are multiple predecessors. This creates a place
555 // where we can insert EH recovery code.
556 if (!CatchHandler->getSinglePredecessor()) {
557 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
558 << " to " << CatchHandler->getName() << '\n');
559 BBI = CatchHandler = SplitCriticalEdge(
560 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
562 EHReturnBlocks.insert(CatchHandler);
567 void WinEHPrepare::identifyEHBlocks(Function &F,
568 SmallVectorImpl<LandingPadInst *> &LPads) {
569 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
570 << F.getName() << '\n');
572 // Build a set of all non-exceptional blocks and exceptional blocks.
573 // - Non-exceptional blocks are blocks reachable from the entry block while
574 // not following invoke unwind edges.
575 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
576 // not follow llvm.eh.endcatch blocks, which mark a transition from
577 // exceptional to normal control.
579 if (Personality == EHPersonality::MSVC_CXX)
580 findCXXEHReturnPoints(F, EHReturnBlocks);
582 findSEHEHReturnPoints(F, EHReturnBlocks);
585 dbgs() << "identified the following blocks as EH return points:\n";
586 for (BasicBlock *BB : EHReturnBlocks)
587 dbgs() << " " << BB->getName() << '\n';
590 // Join points should not have phis at this point, unless they are a
591 // landingpad, in which case we will demote their phis later.
593 for (BasicBlock *BB : EHReturnBlocks)
594 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
595 "non-lpad EH return block has phi");
598 // Normal blocks are the blocks reachable from the entry block and all EH
600 SetVector<BasicBlock *> Worklist;
601 Worklist = EHReturnBlocks;
602 Worklist.insert(&F.getEntryBlock());
603 findReachableBlocks(NormalBlocks, Worklist, nullptr);
605 dbgs() << "marked the following blocks as normal:\n";
606 for (BasicBlock *BB : NormalBlocks)
607 dbgs() << " " << BB->getName() << '\n';
610 // Exceptional blocks are the blocks reachable from landingpads that don't
611 // cross EH return points.
613 for (auto *LPI : LPads)
614 Worklist.insert(LPI->getParent());
615 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
617 dbgs() << "marked the following blocks as exceptional:\n";
618 for (BasicBlock *BB : EHBlocks)
619 dbgs() << " " << BB->getName() << '\n';
624 /// Ensure that all values live into and out of exception handlers are stored
626 /// FIXME: This falls down when values are defined in one handler and live into
627 /// another handler. For example, a cleanup defines a value used only by a
629 void WinEHPrepare::demoteValuesLiveAcrossHandlers(
630 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
631 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
632 << F.getName() << '\n');
634 // identifyEHBlocks() should have been called before this function.
635 assert(!NormalBlocks.empty());
637 // Try to avoid demoting EH pointer and selector values. They get in the way
638 // of our pattern matching.
639 SmallPtrSet<Instruction *, 10> EHVals;
640 for (BasicBlock &BB : F) {
641 LandingPadInst *LP = BB.getLandingPadInst();
645 for (User *U : LP->users()) {
646 auto *EI = dyn_cast<ExtractValueInst>(U);
650 for (User *U2 : EI->users()) {
651 if (auto *PN = dyn_cast<PHINode>(U2))
657 SetVector<Argument *> ArgsToDemote;
658 SetVector<Instruction *> InstrsToDemote;
659 for (BasicBlock &BB : F) {
660 bool IsNormalBB = NormalBlocks.count(&BB);
661 bool IsEHBB = EHBlocks.count(&BB);
662 if (!IsNormalBB && !IsEHBB)
663 continue; // Blocks that are neither normal nor EH are unreachable.
664 for (Instruction &I : BB) {
665 for (Value *Op : I.operands()) {
666 // Don't demote static allocas, constants, and labels.
667 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
669 auto *AI = dyn_cast<AllocaInst>(Op);
670 if (AI && AI->isStaticAlloca())
673 if (auto *Arg = dyn_cast<Argument>(Op)) {
675 DEBUG(dbgs() << "Demoting argument " << *Arg
676 << " used by EH instr: " << I << "\n");
677 ArgsToDemote.insert(Arg);
682 // Don't demote EH values.
683 auto *OpI = cast<Instruction>(Op);
684 if (EHVals.count(OpI))
687 BasicBlock *OpBB = OpI->getParent();
688 // If a value is produced and consumed in the same BB, we don't need to
692 bool IsOpNormalBB = NormalBlocks.count(OpBB);
693 bool IsOpEHBB = EHBlocks.count(OpBB);
694 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
696 dbgs() << "Demoting instruction live in-out from EH:\n";
697 dbgs() << "Instr: " << *OpI << '\n';
698 dbgs() << "User: " << I << '\n';
700 InstrsToDemote.insert(OpI);
706 // Demote values live into and out of handlers.
707 // FIXME: This demotion is inefficient. We should insert spills at the point
708 // of definition, insert one reload in each handler that uses the value, and
709 // insert reloads in the BB used to rejoin normal control flow.
710 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
711 for (Instruction *I : InstrsToDemote)
712 DemoteRegToStack(*I, false, AllocaInsertPt);
714 // Demote arguments separately, and only for uses in EH blocks.
715 for (Argument *Arg : ArgsToDemote) {
716 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
717 Arg->getName() + ".reg2mem", AllocaInsertPt);
718 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
719 for (User *U : Users) {
720 auto *I = dyn_cast<Instruction>(U);
721 if (I && EHBlocks.count(I->getParent())) {
722 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
723 U->replaceUsesOfWith(Arg, Reload);
726 new StoreInst(Arg, Slot, AllocaInsertPt);
729 // Demote landingpad phis, as the landingpad will be removed from the machine
731 for (LandingPadInst *LPI : LPads) {
732 BasicBlock *BB = LPI->getParent();
733 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
734 DemotePHIToStack(Phi, AllocaInsertPt);
737 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
738 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
741 bool WinEHPrepare::prepareExceptionHandlers(
742 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
743 // Don't run on functions that are already prepared.
744 for (LandingPadInst *LPad : LPads) {
745 BasicBlock *LPadBB = LPad->getParent();
746 for (Instruction &Inst : *LPadBB)
747 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
751 identifyEHBlocks(F, LPads);
752 demoteValuesLiveAcrossHandlers(F, LPads);
754 // These containers are used to re-map frame variables that are used in
755 // outlined catch and cleanup handlers. They will be populated as the
756 // handlers are outlined.
757 FrameVarInfoMap FrameVarInfo;
759 bool HandlersOutlined = false;
761 Module *M = F.getParent();
762 LLVMContext &Context = M->getContext();
764 // Create a new function to receive the handler contents.
765 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
766 Type *Int32Type = Type::getInt32Ty(Context);
767 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
769 if (isAsynchronousEHPersonality(Personality)) {
770 // FIXME: Switch the ehptr type to i32 and then switch this.
771 SEHExceptionCodeSlot =
772 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
773 F.getEntryBlock().getFirstInsertionPt());
776 // In order to handle the case where one outlined catch handler returns
777 // to a block within another outlined catch handler that would otherwise
778 // be unreachable, we need to outline the nested landing pad before we
779 // outline the landing pad which encloses it.
780 if (!isAsynchronousEHPersonality(Personality))
781 std::sort(LPads.begin(), LPads.end(),
782 [this](LandingPadInst *const &L, LandingPadInst *const &R) {
783 return DT->properlyDominates(R->getParent(), L->getParent());
786 // This container stores the llvm.eh.recover and IndirectBr instructions
787 // that make up the body of each landing pad after it has been outlined.
788 // We need to defer the population of the target list for the indirectbr
789 // until all landing pads have been outlined so that we can handle the
790 // case of blocks in the target that are reached only from nested
792 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
794 for (LandingPadInst *LPad : LPads) {
795 // Look for evidence that this landingpad has already been processed.
796 bool LPadHasActionList = false;
797 BasicBlock *LPadBB = LPad->getParent();
798 for (Instruction &Inst : *LPadBB) {
799 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
800 LPadHasActionList = true;
805 // If we've already outlined the handlers for this landingpad,
806 // there's nothing more to do here.
807 if (LPadHasActionList)
810 // If either of the values in the aggregate returned by the landing pad is
811 // extracted and stored to memory, promote the stored value to a register.
812 promoteLandingPadValues(LPad);
814 LandingPadActions Actions;
815 mapLandingPadBlocks(LPad, Actions);
817 HandlersOutlined |= !Actions.actions().empty();
818 for (ActionHandler *Action : Actions) {
819 if (Action->hasBeenProcessed())
821 BasicBlock *StartBB = Action->getStartBlock();
823 // SEH doesn't do any outlining for catches. Instead, pass the handler
824 // basic block addr to llvm.eh.actions and list the block as a return
826 if (isAsynchronousEHPersonality(Personality)) {
827 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
828 processSEHCatchHandler(CatchAction, StartBB);
833 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
836 // Split the block after the landingpad instruction so that it is just a
837 // call to llvm.eh.actions followed by indirectbr.
838 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
839 SplitBlock(LPadBB, LPad->getNextNode(), DT);
840 // Erase the branch inserted by the split so we can insert indirectbr.
841 LPadBB->getTerminator()->eraseFromParent();
843 // Replace all extracted values with undef and ultimately replace the
844 // landingpad with undef.
845 SmallVector<Instruction *, 4> SEHCodeUses;
846 SmallVector<Instruction *, 4> EHUndefs;
847 for (User *U : LPad->users()) {
848 auto *E = dyn_cast<ExtractValueInst>(U);
851 assert(E->getNumIndices() == 1 &&
852 "Unexpected operation: extracting both landing pad values");
853 unsigned Idx = *E->idx_begin();
854 assert((Idx == 0 || Idx == 1) && "unexpected index");
855 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
856 SEHCodeUses.push_back(E);
858 EHUndefs.push_back(E);
860 for (Instruction *E : EHUndefs) {
861 E->replaceAllUsesWith(UndefValue::get(E->getType()));
862 E->eraseFromParent();
864 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
866 // Rewrite uses of the exception pointer to loads of an alloca.
867 while (!SEHCodeUses.empty()) {
868 Instruction *E = SEHCodeUses.pop_back_val();
869 SmallVector<Use *, 4> Uses;
870 for (Use &U : E->uses())
872 for (Use *U : Uses) {
873 auto *I = cast<Instruction>(U->getUser());
874 if (isa<ResumeInst>(I))
876 if (auto *Phi = dyn_cast<PHINode>(I))
877 SEHCodeUses.push_back(Phi);
879 U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
881 E->replaceAllUsesWith(UndefValue::get(E->getType()));
882 E->eraseFromParent();
885 // Add a call to describe the actions for this landing pad.
886 std::vector<Value *> ActionArgs;
887 for (ActionHandler *Action : Actions) {
888 // Action codes from docs are: 0 cleanup, 1 catch.
889 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
890 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
891 ActionArgs.push_back(CatchAction->getSelector());
892 // Find the frame escape index of the exception object alloca in the
894 int FrameEscapeIdx = -1;
895 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
896 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
897 auto I = FrameVarInfo.find(EHObj);
898 assert(I != FrameVarInfo.end() &&
899 "failed to map llvm.eh.begincatch var");
900 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
902 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
904 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
906 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
909 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
911 SetVector<BasicBlock *> ReturnTargets;
912 for (ActionHandler *Action : Actions) {
913 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
914 const auto &CatchTargets = CatchAction->getReturnTargets();
915 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
918 IndirectBrInst *Branch =
919 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
920 for (BasicBlock *Target : ReturnTargets)
921 Branch->addDestination(Target);
923 if (!isAsynchronousEHPersonality(Personality)) {
924 // C++ EH must repopulate the targets later to handle the case of
925 // targets that are reached indirectly through nested landing pads.
926 LPadImpls.push_back(std::make_pair(Recover, Branch));
929 } // End for each landingpad
931 // If nothing got outlined, there is no more processing to be done.
932 if (!HandlersOutlined)
935 // Replace any nested landing pad stubs with the correct action handler.
936 // This must be done before we remove unreachable blocks because it
937 // cleans up references to outlined blocks that will be deleted.
938 for (auto &LPadPair : NestedLPtoOriginalLP)
939 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
940 NestedLPtoOriginalLP.clear();
942 // Update the indirectbr instructions' target lists if necessary.
943 SetVector<BasicBlock*> CheckedTargets;
944 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
945 for (auto &LPadImplPair : LPadImpls) {
946 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
947 IndirectBrInst *Branch = LPadImplPair.second;
949 // Get a list of handlers called by
950 parseEHActions(Recover, ActionList);
952 // Add an indirect branch listing possible successors of the catch handlers.
953 SetVector<BasicBlock *> ReturnTargets;
954 for (const auto &Action : ActionList) {
955 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
956 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
957 getPossibleReturnTargets(&F, Handler, ReturnTargets);
961 // Clear any targets we already knew about.
962 for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
963 BasicBlock *KnownTarget = Branch->getDestination(I);
964 if (ReturnTargets.count(KnownTarget))
965 ReturnTargets.remove(KnownTarget);
967 for (BasicBlock *Target : ReturnTargets) {
968 Branch->addDestination(Target);
969 // The target may be a block that we excepted to get pruned.
970 // If it is, it may contain a call to llvm.eh.endcatch.
971 if (CheckedTargets.insert(Target)) {
972 // Earlier preparations guarantee that all calls to llvm.eh.endcatch
973 // will be followed by an unconditional branch.
974 auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
975 if (Br && Br->isUnconditional() &&
976 Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
977 Instruction *Prev = Br->getPrevNode();
978 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
979 Prev->eraseFromParent();
986 F.addFnAttr("wineh-parent", F.getName());
988 // Delete any blocks that were only used by handlers that were outlined above.
989 removeUnreachableBlocks(F);
991 BasicBlock *Entry = &F.getEntryBlock();
992 IRBuilder<> Builder(F.getParent()->getContext());
993 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
995 Function *FrameEscapeFn =
996 Intrinsic::getDeclaration(M, Intrinsic::localescape);
997 Function *RecoverFrameFn =
998 Intrinsic::getDeclaration(M, Intrinsic::localrecover);
999 SmallVector<Value *, 8> AllocasToEscape;
1001 // Scan the entry block for an existing call to llvm.localescape. We need to
1002 // keep escaping those objects.
1003 for (Instruction &I : F.front()) {
1004 auto *II = dyn_cast<IntrinsicInst>(&I);
1005 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1006 auto Args = II->arg_operands();
1007 AllocasToEscape.append(Args.begin(), Args.end());
1008 II->eraseFromParent();
1013 // Finally, replace all of the temporary allocas for frame variables used in
1014 // the outlined handlers with calls to llvm.localrecover.
1015 for (auto &VarInfoEntry : FrameVarInfo) {
1016 Value *ParentVal = VarInfoEntry.first;
1017 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
1018 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
1020 // FIXME: We should try to sink unescaped allocas from the parent frame into
1021 // the child frame. If the alloca is escaped, we have to use the lifetime
1022 // markers to ensure that the alloca is only live within the child frame.
1024 // Add this alloca to the list of things to escape.
1025 AllocasToEscape.push_back(ParentAlloca);
1027 // Next replace all outlined allocas that are mapped to it.
1028 for (AllocaInst *TempAlloca : Allocas) {
1029 if (TempAlloca == getCatchObjectSentinel())
1030 continue; // Skip catch parameter sentinels.
1031 Function *HandlerFn = TempAlloca->getParent()->getParent();
1032 llvm::Value *FP = HandlerToParentFP[HandlerFn];
1035 // FIXME: Sink this localrecover into the blocks where it is used.
1036 Builder.SetInsertPoint(TempAlloca);
1037 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1038 Value *RecoverArgs[] = {
1039 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
1040 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
1041 Instruction *RecoveredAlloca =
1042 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1044 // Add a pointer bitcast if the alloca wasn't an i8.
1045 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1046 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
1047 RecoveredAlloca = cast<Instruction>(
1048 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
1050 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1051 TempAlloca->removeFromParent();
1052 RecoveredAlloca->takeName(TempAlloca);
1055 } // End for each FrameVarInfo entry.
1057 // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
1059 Builder.SetInsertPoint(&F.getEntryBlock().back());
1060 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1062 if (SEHExceptionCodeSlot) {
1063 if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1064 SmallPtrSet<BasicBlock *, 4> UserBlocks;
1065 for (User *U : SEHExceptionCodeSlot->users()) {
1066 if (auto *Inst = dyn_cast<Instruction>(U))
1067 UserBlocks.insert(Inst->getParent());
1069 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
1070 // After the promotion, kill off dead instructions.
1071 for (BasicBlock *BB : UserBlocks)
1072 SimplifyInstructionsInBlock(BB, LibInfo);
1076 // Clean up the handler action maps we created for this function
1077 DeleteContainerSeconds(CatchHandlerMap);
1078 CatchHandlerMap.clear();
1079 DeleteContainerSeconds(CleanupHandlerMap);
1080 CleanupHandlerMap.clear();
1081 HandlerToParentFP.clear();
1084 SEHExceptionCodeSlot = nullptr;
1086 NormalBlocks.clear();
1087 EHReturnBlocks.clear();
1089 return HandlersOutlined;
1092 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1093 // If the return values of the landing pad instruction are extracted and
1094 // stored to memory, we want to promote the store locations to reg values.
1095 SmallVector<AllocaInst *, 2> EHAllocas;
1097 // The landingpad instruction returns an aggregate value. Typically, its
1098 // value will be passed to a pair of extract value instructions and the
1099 // results of those extracts are often passed to store instructions.
1100 // In unoptimized code the stored value will often be loaded and then stored
1102 for (auto *U : LPad->users()) {
1103 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1107 for (auto *EU : Extract->users()) {
1108 if (auto *Store = dyn_cast<StoreInst>(EU)) {
1109 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1110 EHAllocas.push_back(AV);
1115 // We can't do this without a dominator tree.
1118 if (!EHAllocas.empty()) {
1119 PromoteMemToReg(EHAllocas, *DT);
1123 // After promotion, some extracts may be trivially dead. Remove them.
1124 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1125 for (auto *U : Users)
1126 RecursivelyDeleteTriviallyDeadInstructions(U);
1129 void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1131 SetVector<BasicBlock*> &Targets) {
1132 for (BasicBlock &BB : *HandlerF) {
1133 // If the handler contains landing pads, check for any
1134 // handlers that may return directly to a block in the
1136 if (auto *LPI = BB.getLandingPadInst()) {
1137 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
1138 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
1139 parseEHActions(Recover, ActionList);
1140 for (const auto &Action : ActionList) {
1141 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
1142 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1143 getPossibleReturnTargets(ParentF, NestedF, Targets);
1148 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1152 // Handler functions must always return a block address.
1153 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1155 // If this is the handler for a nested landing pad, the
1156 // return address may have been remapped to a block in the
1157 // parent handler. We're not interested in those.
1158 if (BA->getFunction() != ParentF)
1161 Targets.insert(BA->getBasicBlock());
1165 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1166 LandingPadInst *OutlinedLPad,
1167 const LandingPadInst *OriginalLPad,
1168 FrameVarInfoMap &FrameVarInfo) {
1169 // Get the nested block and erase the unreachable instruction that was
1170 // temporarily inserted as its terminator.
1171 LLVMContext &Context = ParentFn->getContext();
1172 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
1173 // If the nested landing pad was outlined before the landing pad that enclosed
1174 // it, it will already be in outlined form. In that case, we just need to see
1175 // if the returns and the enclosing branch instruction need to be updated.
1176 IndirectBrInst *Branch =
1177 dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1179 // If the landing pad wasn't in outlined form, it should be a stub with
1180 // an unreachable terminator.
1181 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1182 OutlinedBB->getTerminator()->eraseFromParent();
1183 // That should leave OutlinedLPad as the last instruction in its block.
1184 assert(&OutlinedBB->back() == OutlinedLPad);
1187 // The original landing pad will have already had its action intrinsic
1188 // built by the outlining loop. We need to clone that into the outlined
1189 // location. It may also be necessary to add references to the exception
1190 // variables to the outlined handler in which this landing pad is nested
1191 // and remap return instructions in the nested handlers that should return
1192 // to an address in the outlined handler.
1193 Function *OutlinedHandlerFn = OutlinedBB->getParent();
1194 BasicBlock::const_iterator II = OriginalLPad;
1196 // The instruction after the landing pad should now be a call to eh.actions.
1197 const Instruction *Recover = II;
1198 const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
1200 // Remap the return target in the nested handler.
1201 SmallVector<BlockAddress *, 4> ActionTargets;
1202 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
1203 parseEHActions(EHActions, ActionList);
1204 for (const auto &Action : ActionList) {
1205 auto *Catch = dyn_cast<CatchHandler>(Action.get());
1208 // The dyn_cast to function here selects C++ catch handlers and skips
1209 // SEH catch handlers.
1210 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1213 // Visit all the return instructions, looking for places that return
1214 // to a location within OutlinedHandlerFn.
1215 for (BasicBlock &NestedHandlerBB : *Handler) {
1216 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1220 // Handler functions must always return a block address.
1221 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1222 // The original target will have been in the main parent function,
1223 // but if it is the address of a block that has been outlined, it
1224 // should be a block that was outlined into OutlinedHandlerFn.
1225 assert(BA->getFunction() == ParentFn);
1227 // Ignore targets that aren't part of an outlined handler function.
1228 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1231 // If the return value is the address ofF a block that we
1232 // previously outlined into the parent handler function, replace
1233 // the return instruction and add the mapped target to the list
1234 // of possible return addresses.
1235 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1236 assert(MappedBB->getParent() == OutlinedHandlerFn);
1237 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1238 Ret->eraseFromParent();
1239 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1240 ActionTargets.push_back(NewBA);
1246 // If the landing pad was already in outlined form, just update its targets.
1247 for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1248 Branch->removeDestination(I);
1249 // Add the previously collected action targets.
1250 for (auto *Target : ActionTargets)
1251 Branch->addDestination(Target->getBasicBlock());
1253 // If the landing pad was previously stubbed out, fill in its outlined form.
1254 IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1255 OutlinedBB->getInstList().push_back(NewEHActions);
1257 // Insert an indirect branch into the outlined landing pad BB.
1258 IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1259 // Add the previously collected action targets.
1260 for (auto *Target : ActionTargets)
1261 IBr->addDestination(Target->getBasicBlock());
1265 // This function examines a block to determine whether the block ends with a
1266 // conditional branch to a catch handler based on a selector comparison.
1267 // This function is used both by the WinEHPrepare::findSelectorComparison() and
1268 // WinEHCleanupDirector::handleTypeIdFor().
1269 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1270 Constant *&Selector, BasicBlock *&NextBB) {
1271 ICmpInst::Predicate Pred;
1272 BasicBlock *TBB, *FBB;
1275 if (!match(BB->getTerminator(),
1276 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1280 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1281 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1284 if (Pred == CmpInst::ICMP_EQ) {
1290 if (Pred == CmpInst::ICMP_NE) {
1299 static bool isCatchBlock(BasicBlock *BB) {
1300 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1302 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1308 static BasicBlock *createStubLandingPad(Function *Handler) {
1309 // FIXME: Finish this!
1310 LLVMContext &Context = Handler->getContext();
1311 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1312 Handler->getBasicBlockList().push_back(StubBB);
1313 IRBuilder<> Builder(StubBB);
1314 LandingPadInst *LPad = Builder.CreateLandingPad(
1315 llvm::StructType::get(Type::getInt8PtrTy(Context),
1316 Type::getInt32Ty(Context), nullptr),
1318 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1319 Function *ActionIntrin =
1320 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
1321 Builder.CreateCall(ActionIntrin, {}, "recover");
1322 LPad->setCleanup(true);
1323 Builder.CreateUnreachable();
1327 // Cycles through the blocks in an outlined handler function looking for an
1328 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1329 // landing pad if none is found. The code that generates the .xdata tables for
1330 // the handler needs at least one landing pad to identify the parent function's
1332 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
1333 ReturnInst *Ret = nullptr;
1334 UnreachableInst *Unreached = nullptr;
1335 for (BasicBlock &BB : *Handler) {
1336 TerminatorInst *Terminator = BB.getTerminator();
1337 // If we find an invoke, there is nothing to be done.
1338 auto *II = dyn_cast<InvokeInst>(Terminator);
1341 // If we've already recorded a return instruction, keep looking for invokes.
1343 Ret = dyn_cast<ReturnInst>(Terminator);
1344 // If we haven't recorded an unreachable instruction, try this terminator.
1346 Unreached = dyn_cast<UnreachableInst>(Terminator);
1349 // If we got this far, the handler contains no invokes. We should have seen
1350 // at least one return or unreachable instruction. We'll insert an invoke of
1351 // llvm.donothing ahead of that instruction.
1352 assert(Ret || Unreached);
1353 TerminatorInst *Term;
1358 BasicBlock *OldRetBB = Term->getParent();
1359 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
1360 // SplitBlock adds an unconditional branch instruction at the end of the
1361 // parent block. We want to replace that with an invoke call, so we can
1363 OldRetBB->getTerminator()->eraseFromParent();
1364 BasicBlock *StubLandingPad = createStubLandingPad(Handler);
1366 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1367 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1370 // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1371 // usually doesn't build LLVM IR, so that's probably the wrong place.
1372 Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1373 const Twine &Name, Module *M,
1375 // x64 uses a two-argument prototype where the parent FP is the second
1376 // argument. x86 uses no arguments, just the incoming EBP value.
1377 LLVMContext &Context = M->getContext();
1378 Type *Int8PtrType = Type::getInt8PtrTy(Context);
1379 FunctionType *FnType;
1380 if (TheTriple.getArch() == Triple::x86_64) {
1381 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1382 FnType = FunctionType::get(RetTy, ArgTys, false);
1384 FnType = FunctionType::get(RetTy, None, false);
1388 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1389 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1390 Handler->getBasicBlockList().push_front(Entry);
1391 if (TheTriple.getArch() == Triple::x86_64) {
1392 ParentFP = &(Handler->getArgumentList().back());
1395 Function *FrameAddressFn =
1396 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
1397 Function *RecoverFPFn =
1398 Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1399 IRBuilder<> Builder(&Handler->getEntryBlock());
1401 Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1402 Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1403 ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
1408 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1409 LandingPadInst *LPad, BasicBlock *StartBB,
1410 FrameVarInfoMap &VarInfo) {
1411 Module *M = SrcFn->getParent();
1412 LLVMContext &Context = M->getContext();
1413 Type *Int8PtrType = Type::getInt8PtrTy(Context);
1415 // Create a new function to receive the handler contents.
1418 if (Action->getType() == Catch) {
1419 Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
1422 Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
1423 SrcFn->getName() + ".cleanup", M, ParentFP);
1425 Handler->setPersonalityFn(SrcFn->getPersonalityFn());
1426 HandlerToParentFP[Handler] = ParentFP;
1427 Handler->addFnAttr("wineh-parent", SrcFn->getName());
1428 BasicBlock *Entry = &Handler->getEntryBlock();
1430 // Generate a standard prolog to setup the frame recovery structure.
1431 IRBuilder<> Builder(Context);
1432 Builder.SetInsertPoint(Entry);
1433 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1435 std::unique_ptr<WinEHCloningDirectorBase> Director;
1437 ValueToValueMapTy VMap;
1439 LandingPadMap &LPadMap = LPadMaps[LPad];
1440 if (!LPadMap.isInitialized())
1441 LPadMap.mapLandingPad(LPad);
1442 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1443 Constant *Sel = CatchAction->getSelector();
1444 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1445 LPadMap, NestedLPtoOriginalLP, DT,
1447 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1448 ConstantInt::get(Type::getInt32Ty(Context), 1));
1451 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
1452 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1453 UndefValue::get(Type::getInt32Ty(Context)));
1456 SmallVector<ReturnInst *, 8> Returns;
1457 ClonedCodeInfo OutlinedFunctionInfo;
1459 // If the start block contains PHI nodes, we need to map them.
1460 BasicBlock::iterator II = StartBB->begin();
1461 while (auto *PN = dyn_cast<PHINode>(II)) {
1462 bool Mapped = false;
1463 // Look for PHI values that we have already mapped (such as the selector).
1464 for (Value *Val : PN->incoming_values()) {
1465 if (VMap.count(Val)) {
1466 VMap[PN] = VMap[Val];
1470 // If we didn't find a match for this value, map it as an undef.
1472 VMap[PN] = UndefValue::get(PN->getType());
1477 // The landing pad value may be used by PHI nodes. It will ultimately be
1478 // eliminated, but we need it in the map for intermediate handling.
1479 VMap[LPad] = UndefValue::get(LPad->getType());
1481 // Skip over PHIs and, if applicable, landingpad instructions.
1482 II = StartBB->getFirstInsertionPt();
1484 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1485 /*ModuleLevelChanges=*/false, Returns, "",
1486 &OutlinedFunctionInfo, Director.get());
1488 // Move all the instructions in the cloned "entry" block into our entry block.
1489 // Depending on how the parent function was laid out, the block that will
1490 // correspond to the outlined entry block may not be the first block in the
1491 // list. We can recognize it, however, as the cloned block which has no
1492 // predecessors. Any other block wouldn't have been cloned if it didn't
1493 // have a predecessor which was also cloned.
1494 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
1495 while (!pred_empty(ClonedIt))
1497 BasicBlock *ClonedEntryBB = ClonedIt;
1498 assert(ClonedEntryBB);
1499 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1500 ClonedEntryBB->eraseFromParent();
1502 // Make sure we can identify the handler's personality later.
1503 addStubInvokeToHandlerIfNeeded(Handler);
1505 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1506 WinEHCatchDirector *CatchDirector =
1507 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1508 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1509 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1511 // Look for blocks that are not part of the landing pad that we just
1512 // outlined but terminate with a call to llvm.eh.endcatch and a
1513 // branch to a block that is in the handler we just outlined.
1514 // These blocks will be part of a nested landing pad that intends to
1515 // return to an address in this handler. This case is best handled
1516 // after both landing pads have been outlined, so for now we'll just
1517 // save the association of the blocks in LPadTargetBlocks. The
1518 // return instructions which are created from these branches will be
1519 // replaced after all landing pads have been outlined.
1520 for (const auto MapEntry : VMap) {
1521 // VMap maps all values and blocks that were just cloned, but dead
1522 // blocks which were pruned will map to nullptr.
1523 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1525 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1526 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1527 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1528 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1530 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1532 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1533 // This would indicate that a nested landing pad wants to return
1534 // to a block that is outlined into two different handlers.
1535 assert(!LPadTargetBlocks.count(MappedBB));
1536 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1540 } // End if (CatchAction)
1542 Action->setHandlerBlockOrFunc(Handler);
1547 /// This BB must end in a selector dispatch. All we need to do is pass the
1548 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1550 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1551 BasicBlock *StartBB) {
1552 BasicBlock *HandlerBB;
1555 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1557 // If this was EH dispatch, this must be a conditional branch to the handler
1559 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1560 // leading to crashes if some optimization hoists stuff here.
1561 assert(CatchAction->getSelector() && HandlerBB &&
1562 "expected catch EH dispatch");
1564 // This must be a catch-all. Split the block after the landingpad.
1565 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1566 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
1568 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1569 Function *EHCodeFn = Intrinsic::getDeclaration(
1570 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
1571 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
1572 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1573 Builder.CreateStore(Code, SEHExceptionCodeSlot);
1574 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1575 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1576 CatchAction->setReturnTargets(Targets);
1579 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1580 // Each instance of this class should only ever be used to map a single
1582 assert(OriginLPad == nullptr || OriginLPad == LPad);
1584 // If the landing pad has already been mapped, there's nothing more to do.
1585 if (OriginLPad == LPad)
1590 // The landingpad instruction returns an aggregate value. Typically, its
1591 // value will be passed to a pair of extract value instructions and the
1592 // results of those extracts will have been promoted to reg values before
1593 // this routine is called.
1594 for (auto *U : LPad->users()) {
1595 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1598 assert(Extract->getNumIndices() == 1 &&
1599 "Unexpected operation: extracting both landing pad values");
1600 unsigned int Idx = *(Extract->idx_begin());
1601 assert((Idx == 0 || Idx == 1) &&
1602 "Unexpected operation: extracting an unknown landing pad element");
1604 ExtractedEHPtrs.push_back(Extract);
1605 } else if (Idx == 1) {
1606 ExtractedSelectors.push_back(Extract);
1611 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1612 return BB->getLandingPadInst() == OriginLPad;
1615 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1616 if (Inst == OriginLPad)
1618 for (auto *Extract : ExtractedEHPtrs) {
1619 if (Inst == Extract)
1622 for (auto *Extract : ExtractedSelectors) {
1623 if (Inst == Extract)
1629 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1630 Value *SelectorValue) const {
1631 // Remap all landing pad extract instructions to the specified values.
1632 for (auto *Extract : ExtractedEHPtrs)
1633 VMap[Extract] = EHPtrValue;
1634 for (auto *Extract : ExtractedSelectors)
1635 VMap[Extract] = SelectorValue;
1638 static bool isLocalAddressCall(const Value *V) {
1639 return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
1642 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1643 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1644 // If this is one of the boilerplate landing pad instructions, skip it.
1645 // The instruction will have already been remapped in VMap.
1646 if (LPadMap.isLandingPadSpecificInst(Inst))
1647 return CloningDirector::SkipInstruction;
1649 // Nested landing pads that have not already been outlined will be cloned as
1650 // stubs, with just the landingpad instruction and an unreachable instruction.
1651 // When all landingpads have been outlined, we'll replace this with the
1652 // llvm.eh.actions call and indirect branch created when the landing pad was
1654 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1655 return handleLandingPad(VMap, LPad, NewBB);
1658 // Nested landing pads that have already been outlined will be cloned in their
1659 // outlined form, but we need to intercept the ibr instruction to filter out
1660 // targets that do not return to the handler we are outlining.
1661 if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1662 return handleIndirectBr(VMap, IBr, NewBB);
1665 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1666 return handleInvoke(VMap, Invoke, NewBB);
1668 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1669 return handleResume(VMap, Resume, NewBB);
1671 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1672 return handleCompare(VMap, Cmp, NewBB);
1674 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1675 return handleBeginCatch(VMap, Inst, NewBB);
1676 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1677 return handleEndCatch(VMap, Inst, NewBB);
1678 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1679 return handleTypeIdFor(VMap, Inst, NewBB);
1681 // When outlining llvm.localaddress(), remap that to the second argument,
1682 // which is the FP of the parent.
1683 if (isLocalAddressCall(Inst)) {
1684 VMap[Inst] = ParentFP;
1685 return CloningDirector::SkipInstruction;
1688 // Continue with the default cloning behavior.
1689 return CloningDirector::CloneInstruction;
1692 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1693 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1694 // If the instruction after the landing pad is a call to llvm.eh.actions
1695 // the landing pad has already been outlined. In this case, we should
1696 // clone it because it may return to a block in the handler we are
1697 // outlining now that would otherwise be unreachable. The landing pads
1698 // are sorted before outlining begins to enable this case to work
1700 const Instruction *NextI = LPad->getNextNode();
1701 if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1702 return CloningDirector::CloneInstruction;
1704 // If the landing pad hasn't been outlined yet, the landing pad we are
1705 // outlining now does not dominate it and so it cannot return to a block
1706 // in this handler. In that case, we can just insert a stub landing
1707 // pad now and patch it up later.
1708 Instruction *NewInst = LPad->clone();
1709 if (LPad->hasName())
1710 NewInst->setName(LPad->getName());
1711 // Save this correlation for later processing.
1712 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1713 VMap[LPad] = NewInst;
1714 BasicBlock::InstListType &InstList = NewBB->getInstList();
1715 InstList.push_back(NewInst);
1716 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1717 return CloningDirector::StopCloningBB;
1720 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1721 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1722 // The argument to the call is some form of the first element of the
1723 // landingpad aggregate value, but that doesn't matter. It isn't used
1725 // The second argument is an outparameter where the exception object will be
1726 // stored. Typically the exception object is a scalar, but it can be an
1727 // aggregate when catching by value.
1728 // FIXME: Leave something behind to indicate where the exception object lives
1729 // for this handler. Should it be part of llvm.eh.actions?
1730 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1731 "llvm.eh.begincatch found while "
1732 "outlining catch handler.");
1733 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1734 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1735 return CloningDirector::SkipInstruction;
1736 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1737 "catch parameter is not static alloca");
1738 Materializer.escapeCatchObject(ExceptionObjectVar);
1739 return CloningDirector::SkipInstruction;
1742 CloningDirector::CloningAction
1743 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1744 const Instruction *Inst, BasicBlock *NewBB) {
1745 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1746 // It might be interesting to track whether or not we are inside a catch
1747 // function, but that might make the algorithm more brittle than it needs
1750 // The end catch call can occur in one of two places: either in a
1751 // landingpad block that is part of the catch handlers exception mechanism,
1752 // or at the end of the catch block. However, a catch-all handler may call
1753 // end catch from the original landing pad. If the call occurs in a nested
1754 // landing pad block, we must skip it and continue so that the landing pad
1756 auto *ParentBB = IntrinCall->getParent();
1757 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1758 return CloningDirector::SkipInstruction;
1760 // If an end catch occurs anywhere else we want to terminate the handler
1761 // with a return to the code that follows the endcatch call. If the
1762 // next instruction is not an unconditional branch, we need to split the
1763 // block to provide a clear target for the return instruction.
1764 BasicBlock *ContinueBB;
1765 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1766 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1767 if (!Branch || !Branch->isUnconditional()) {
1768 // We're interrupting the cloning process at this location, so the
1769 // const_cast we're doing here will not cause a problem.
1770 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1771 const_cast<Instruction *>(cast<Instruction>(Next)));
1773 ContinueBB = Branch->getSuccessor(0);
1776 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1777 ReturnTargets.push_back(ContinueBB);
1779 // We just added a terminator to the cloned block.
1780 // Tell the caller to stop processing the current basic block so that
1781 // the branch instruction will be skipped.
1782 return CloningDirector::StopCloningBB;
1785 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1786 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1787 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1788 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1789 // This causes a replacement that will collapse the landing pad CFG based
1790 // on the filter function we intend to match.
1791 if (Selector == CurrentSelector)
1792 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1794 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1795 // Tell the caller not to clone this instruction.
1796 return CloningDirector::SkipInstruction;
1799 CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1800 ValueToValueMapTy &VMap,
1801 const IndirectBrInst *IBr,
1802 BasicBlock *NewBB) {
1803 // If this indirect branch is not part of a landing pad block, just clone it.
1804 const BasicBlock *ParentBB = IBr->getParent();
1805 if (!ParentBB->isLandingPad())
1806 return CloningDirector::CloneInstruction;
1808 // If it is part of a landing pad, we want to filter out target blocks
1809 // that are not part of the handler we are outlining.
1810 const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1812 // Save this correlation for later processing.
1813 NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1815 // We should only get here for landing pads that have already been outlined.
1816 assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1818 // Copy the indirectbr, but only include targets that were previously
1819 // identified as EH blocks and are dominated by the nested landing pad.
1820 SetVector<const BasicBlock *> ReturnTargets;
1821 for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1822 auto *TargetBB = IBr->getDestination(I);
1823 if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1824 DT->dominates(ParentBB, TargetBB)) {
1825 DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n");
1826 ReturnTargets.insert(TargetBB);
1829 IndirectBrInst *NewBranch =
1830 IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1831 ReturnTargets.size(), NewBB);
1832 for (auto *Target : ReturnTargets)
1833 NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1835 // The operands and targets of the branch instruction are remapped later
1836 // because it is a terminator. Tell the cloning code to clone the
1837 // blocks we just added to the target list.
1838 return CloningDirector::CloneSuccessors;
1841 CloningDirector::CloningAction
1842 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1843 const InvokeInst *Invoke, BasicBlock *NewBB) {
1844 return CloningDirector::CloneInstruction;
1847 CloningDirector::CloningAction
1848 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1849 const ResumeInst *Resume, BasicBlock *NewBB) {
1850 // Resume instructions shouldn't be reachable from catch handlers.
1851 // We still need to handle it, but it will be pruned.
1852 BasicBlock::InstListType &InstList = NewBB->getInstList();
1853 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1854 return CloningDirector::StopCloningBB;
1857 CloningDirector::CloningAction
1858 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1859 const CmpInst *Compare, BasicBlock *NewBB) {
1860 const IntrinsicInst *IntrinCall = nullptr;
1861 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1862 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1863 } else if (match(Compare->getOperand(1),
1864 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1865 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1868 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1869 // This causes a replacement that will collapse the landing pad CFG based
1870 // on the filter function we intend to match.
1871 if (Selector == CurrentSelector->stripPointerCasts()) {
1872 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1874 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1876 return CloningDirector::SkipInstruction;
1878 return CloningDirector::CloneInstruction;
1881 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1882 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1883 // The MS runtime will terminate the process if an exception occurs in a
1884 // cleanup handler, so we shouldn't encounter landing pads in the actual
1885 // cleanup code, but they may appear in catch blocks. Depending on where
1886 // we started cloning we may see one, but it will get dropped during dead
1888 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1889 VMap[LPad] = NewInst;
1890 BasicBlock::InstListType &InstList = NewBB->getInstList();
1891 InstList.push_back(NewInst);
1892 return CloningDirector::StopCloningBB;
1895 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1896 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1897 // Cleanup code may flow into catch blocks or the catch block may be part
1898 // of a branch that will be optimized away. We'll insert a return
1899 // instruction now, but it may be pruned before the cloning process is
1901 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1902 return CloningDirector::StopCloningBB;
1905 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1906 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1907 // Cleanup handlers nested within catch handlers may begin with a call to
1908 // eh.endcatch. We can just ignore that instruction.
1909 return CloningDirector::SkipInstruction;
1912 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1913 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1914 // If we encounter a selector comparison while cloning a cleanup handler,
1915 // we want to stop cloning immediately. Anything after the dispatch
1916 // will be outlined into a different handler.
1917 BasicBlock *CatchHandler;
1920 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1921 CatchHandler, Selector, NextBB)) {
1922 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1923 return CloningDirector::StopCloningBB;
1925 // If eg.typeid.for is called for any other reason, it can be ignored.
1926 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1927 return CloningDirector::SkipInstruction;
1930 CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1931 ValueToValueMapTy &VMap,
1932 const IndirectBrInst *IBr,
1933 BasicBlock *NewBB) {
1934 // No special handling is required for cleanup cloning.
1935 return CloningDirector::CloneInstruction;
1938 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1939 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1940 // All invokes in cleanup handlers can be replaced with calls.
1941 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1942 // Insert a normal call instruction...
1944 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1945 Invoke->getName(), NewBB);
1946 NewCall->setCallingConv(Invoke->getCallingConv());
1947 NewCall->setAttributes(Invoke->getAttributes());
1948 NewCall->setDebugLoc(Invoke->getDebugLoc());
1949 VMap[Invoke] = NewCall;
1951 // Remap the operands.
1952 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1954 // Insert an unconditional branch to the normal destination.
1955 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1957 // The unwind destination won't be cloned into the new function, so
1958 // we don't need to clean up its phi nodes.
1960 // We just added a terminator to the cloned block.
1961 // Tell the caller to stop processing the current basic block.
1962 return CloningDirector::CloneSuccessors;
1965 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1966 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1967 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1969 // We just added a terminator to the cloned block.
1970 // Tell the caller to stop processing the current basic block so that
1971 // the branch instruction will be skipped.
1972 return CloningDirector::StopCloningBB;
1975 CloningDirector::CloningAction
1976 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1977 const CmpInst *Compare, BasicBlock *NewBB) {
1978 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1979 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1980 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1981 return CloningDirector::SkipInstruction;
1983 return CloningDirector::CloneInstruction;
1986 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1987 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
1988 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1989 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1991 // New allocas should be inserted in the entry block, but after the parent FP
1992 // is established if it is an instruction.
1993 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
1994 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
1995 InsertPoint = FPInst->getNextNode();
1996 Builder.SetInsertPoint(EntryBB, InsertPoint);
1999 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
2000 // If we're asked to materialize a static alloca, we temporarily create an
2001 // alloca in the outlined function and add this to the FrameVarInfo map. When
2002 // all the outlining is complete, we'll replace these temporary allocas with
2003 // calls to llvm.localrecover.
2004 if (auto *AV = dyn_cast<AllocaInst>(V)) {
2005 assert(AV->isStaticAlloca() &&
2006 "cannot materialize un-demoted dynamic alloca");
2007 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
2008 Builder.Insert(NewAlloca, AV->getName());
2009 FrameVarInfo[AV].push_back(NewAlloca);
2013 if (isa<Instruction>(V) || isa<Argument>(V)) {
2014 Function *Parent = isa<Instruction>(V)
2015 ? cast<Instruction>(V)->getParent()->getParent()
2016 : cast<Argument>(V)->getParent();
2018 << "Failed to demote instruction used in exception handler of function "
2019 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
2020 errs() << " " << *V << '\n';
2021 report_fatal_error("WinEHPrepare failed to demote instruction");
2024 // Don't materialize other values.
2028 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2029 // Catch parameter objects have to live in the parent frame. When we see a use
2030 // of a catch parameter, add a sentinel to the multimap to indicate that it's
2031 // used from another handler. This will prevent us from trying to sink the
2032 // alloca into the handler and ensure that the catch parameter is present in
2033 // the call to llvm.localescape.
2034 FrameVarInfo[V].push_back(getCatchObjectSentinel());
2037 // This function maps the catch and cleanup handlers that are reachable from the
2038 // specified landing pad. The landing pad sequence will have this basic shape:
2040 // <cleanup handler>
2041 // <selector comparison>
2043 // <cleanup handler>
2044 // <selector comparison>
2046 // <cleanup handler>
2049 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
2050 // any arbitrary control flow, but all paths through the cleanup code must
2051 // eventually reach the next selector comparison and no path can skip to a
2052 // different selector comparisons, though some paths may terminate abnormally.
2053 // Therefore, we will use a depth first search from the start of any given
2054 // cleanup block and stop searching when we find the next selector comparison.
2056 // If the landingpad instruction does not have a catch clause, we will assume
2057 // that any instructions other than selector comparisons and catch handlers can
2058 // be ignored. In practice, these will only be the boilerplate instructions.
2060 // The catch handlers may also have any control structure, but we are only
2061 // interested in the start of the catch handlers, so we don't need to actually
2062 // follow the flow of the catch handlers. The start of the catch handlers can
2063 // be located from the compare instructions, but they can be skipped in the
2064 // flow by following the contrary branch.
2065 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2066 LandingPadActions &Actions) {
2067 unsigned int NumClauses = LPad->getNumClauses();
2068 unsigned int HandlersFound = 0;
2069 BasicBlock *BB = LPad->getParent();
2071 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2073 if (NumClauses == 0) {
2074 findCleanupHandlers(Actions, BB, nullptr);
2078 VisitedBlockSet VisitedBlocks;
2080 while (HandlersFound != NumClauses) {
2081 BasicBlock *NextBB = nullptr;
2083 // Skip over filter clauses.
2084 if (LPad->isFilter(HandlersFound)) {
2089 // See if the clause we're looking for is a catch-all.
2090 // If so, the catch begins immediately.
2091 Constant *ExpectedSelector =
2092 LPad->getClause(HandlersFound)->stripPointerCasts();
2093 if (isa<ConstantPointerNull>(ExpectedSelector)) {
2094 // The catch all must occur last.
2095 assert(HandlersFound == NumClauses - 1);
2097 // There can be additional selector dispatches in the call chain that we
2099 BasicBlock *CatchBlock = nullptr;
2101 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2102 DEBUG(dbgs() << " Found extra catch dispatch in block "
2103 << CatchBlock->getName() << "\n");
2107 // Add the catch handler to the action list.
2108 CatchHandler *Action = nullptr;
2109 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2110 // If the CatchHandlerMap already has an entry for this BB, re-use it.
2111 Action = CatchHandlerMap[BB];
2112 assert(Action->getSelector() == ExpectedSelector);
2114 // We don't expect a selector dispatch, but there may be a call to
2115 // llvm.eh.begincatch, which separates catch handling code from
2116 // cleanup code in the same control flow. This call looks for the
2117 // begincatch intrinsic.
2118 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2120 // For C++ EH, check if there is any interesting cleanup code before
2121 // we begin the catch. This is important because cleanups cannot
2122 // rethrow exceptions but code called from catches can. For SEH, it
2123 // isn't important if some finally code before a catch-all is executed
2124 // out of line or after recovering from the exception.
2125 if (Personality == EHPersonality::MSVC_CXX)
2126 findCleanupHandlers(Actions, BB, BB);
2128 // If an action was not found, it means that the control flows
2129 // directly into the catch-all handler and there is no cleanup code.
2130 // That's an expected situation and we must create a catch action.
2131 // Since this is a catch-all handler, the selector won't actually
2132 // appear in the code anywhere. ExpectedSelector here is the constant
2133 // null ptr that we got from the landing pad instruction.
2134 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2135 CatchHandlerMap[BB] = Action;
2138 Actions.insertCatchHandler(Action);
2139 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
2142 // Once we reach a catch-all, don't expect to hit a resume instruction.
2147 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
2148 assert(CatchAction);
2150 // See if there is any interesting code executed before the dispatch.
2151 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
2153 // When the source program contains multiple nested try blocks the catch
2154 // handlers can get strung together in such a way that we can encounter
2155 // a dispatch for a selector that we've already had a handler for.
2156 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2159 // Add the catch handler to the action list.
2160 DEBUG(dbgs() << " Found catch dispatch in block "
2161 << CatchAction->getStartBlock()->getName() << "\n");
2162 Actions.insertCatchHandler(CatchAction);
2164 // Under some circumstances optimized IR will flow unconditionally into a
2165 // handler block without checking the selector. This can only happen if
2166 // the landing pad has a catch-all handler and the handler for the
2167 // preceeding catch clause is identical to the catch-call handler
2168 // (typically an empty catch). In this case, the handler must be shared
2169 // by all remaining clauses.
2170 if (isa<ConstantPointerNull>(
2171 CatchAction->getSelector()->stripPointerCasts())) {
2172 DEBUG(dbgs() << " Applying early catch-all handler in block "
2173 << CatchAction->getStartBlock()->getName()
2174 << " to all remaining clauses.\n");
2175 Actions.insertCatchHandler(CatchAction);
2179 DEBUG(dbgs() << " Found extra catch dispatch in block "
2180 << CatchAction->getStartBlock()->getName() << "\n");
2183 // Move on to the block after the catch handler.
2187 // If we didn't wind up in a catch-all, see if there is any interesting code
2188 // executed before the resume.
2189 findCleanupHandlers(Actions, BB, BB);
2191 // It's possible that some optimization moved code into a landingpad that
2193 // previously being used for cleanup. If that happens, we need to execute
2195 // extra code from a cleanup handler.
2196 if (Actions.includesCleanup() && !LPad->isCleanup())
2197 LPad->setCleanup(true);
2200 // This function searches starting with the input block for the next
2201 // block that terminates with a branch whose condition is based on a selector
2202 // comparison. This may be the input block. See the mapLandingPadBlocks
2203 // comments for a discussion of control flow assumptions.
2205 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2206 BasicBlock *&NextBB,
2207 VisitedBlockSet &VisitedBlocks) {
2208 // See if we've already found a catch handler use it.
2209 // Call count() first to avoid creating a null entry for blocks
2210 // we haven't seen before.
2211 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2212 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2213 NextBB = Action->getNextBB();
2217 // VisitedBlocks applies only to the current search. We still
2218 // need to consider blocks that we've visited while mapping other
2220 VisitedBlocks.insert(BB);
2222 BasicBlock *CatchBlock = nullptr;
2223 Constant *Selector = nullptr;
2225 // If this is the first time we've visited this block from any landing pad
2226 // look to see if it is a selector dispatch block.
2227 if (!CatchHandlerMap.count(BB)) {
2228 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2229 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2230 CatchHandlerMap[BB] = Action;
2233 // If we encounter a block containing an llvm.eh.begincatch before we
2234 // find a selector dispatch block, the handler is assumed to be
2235 // reached unconditionally. This happens for catch-all blocks, but
2236 // it can also happen for other catch handlers that have been combined
2237 // with the catch-all handler during optimization.
2238 if (isCatchBlock(BB)) {
2239 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2240 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2241 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2242 CatchHandlerMap[BB] = Action;
2247 // Visit each successor, looking for the dispatch.
2248 // FIXME: We expect to find the dispatch quickly, so this will probably
2249 // work better as a breadth first search.
2250 for (BasicBlock *Succ : successors(BB)) {
2251 if (VisitedBlocks.count(Succ))
2254 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2261 // These are helper functions to combine repeated code from findCleanupHandlers.
2262 static void createCleanupHandler(LandingPadActions &Actions,
2263 CleanupHandlerMapTy &CleanupHandlerMap,
2265 CleanupHandler *Action = new CleanupHandler(BB);
2266 CleanupHandlerMap[BB] = Action;
2267 Actions.insertCleanupHandler(Action);
2268 DEBUG(dbgs() << " Found cleanup code in block "
2269 << Action->getStartBlock()->getName() << "\n");
2272 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2273 Instruction *MaybeCall) {
2274 // Look for finally blocks that Clang has already outlined for us.
2275 // %fp = call i8* @llvm.localaddress()
2276 // call void @"fin$parent"(iN 1, i8* %fp)
2277 if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
2278 MaybeCall = MaybeCall->getNextNode();
2279 CallSite FinallyCall(MaybeCall);
2280 if (!FinallyCall || FinallyCall.arg_size() != 2)
2282 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2284 if (!isLocalAddressCall(FinallyCall.getArgument(1)))
2289 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2290 // Skip single ubr blocks.
2291 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2292 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2293 if (Br && Br->isUnconditional())
2294 BB = Br->getSuccessor(0);
2301 // This function searches starting with the input block for the next block that
2302 // contains code that is not part of a catch handler and would not be eliminated
2303 // during handler outlining.
2305 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2306 BasicBlock *StartBB, BasicBlock *EndBB) {
2307 // Here we will skip over the following:
2309 // landing pad prolog:
2311 // Unconditional branches
2313 // Selector dispatch
2317 // Anything else marks the start of an interesting block
2319 BasicBlock *BB = StartBB;
2320 // Anything other than an unconditional branch will kick us out of this loop
2321 // one way or another.
2323 BB = followSingleUnconditionalBranches(BB);
2324 // If we've already scanned this block, don't scan it again. If it is
2325 // a cleanup block, there will be an action in the CleanupHandlerMap.
2326 // If we've scanned it and it is not a cleanup block, there will be a
2327 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2328 // be no entry in the CleanupHandlerMap. We must call count() first to
2329 // avoid creating a null entry for blocks we haven't scanned.
2330 if (CleanupHandlerMap.count(BB)) {
2331 if (auto *Action = CleanupHandlerMap[BB]) {
2332 Actions.insertCleanupHandler(Action);
2333 DEBUG(dbgs() << " Found cleanup code in block "
2334 << Action->getStartBlock()->getName() << "\n");
2335 // FIXME: This cleanup might chain into another, and we need to discover
2339 // Here we handle the case where the cleanup handler map contains a
2340 // value for this block but the value is a nullptr. This means that
2341 // we have previously analyzed the block and determined that it did
2342 // not contain any cleanup code. Based on the earlier analysis, we
2343 // know the block must end in either an unconditional branch, a
2344 // resume or a conditional branch that is predicated on a comparison
2345 // with a selector. Either the resume or the selector dispatch
2346 // would terminate the search for cleanup code, so the unconditional
2347 // branch is the only case for which we might need to continue
2349 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2350 if (SuccBB == BB || SuccBB == EndBB)
2357 // Create an entry in the cleanup handler map for this block. Initially
2358 // we create an entry that says this isn't a cleanup block. If we find
2359 // cleanup code, the caller will replace this entry.
2360 CleanupHandlerMap[BB] = nullptr;
2362 TerminatorInst *Terminator = BB->getTerminator();
2364 // Landing pad blocks have extra instructions we need to accept.
2365 LandingPadMap *LPadMap = nullptr;
2366 if (BB->isLandingPad()) {
2367 LandingPadInst *LPad = BB->getLandingPadInst();
2368 LPadMap = &LPadMaps[LPad];
2369 if (!LPadMap->isInitialized())
2370 LPadMap->mapLandingPad(LPad);
2373 // Look for the bare resume pattern:
2374 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2375 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
2376 // resume { i8*, i32 } %lpad.val2
2377 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2378 InsertValueInst *Insert1 = nullptr;
2379 InsertValueInst *Insert2 = nullptr;
2380 Value *ResumeVal = Resume->getOperand(0);
2381 // If the resume value isn't a phi or landingpad value, it should be a
2382 // series of insertions. Identify them so we can avoid them when scanning
2384 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
2385 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
2387 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2388 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2390 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2392 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2394 Instruction *Inst = II;
2395 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2397 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2399 if (!Inst->hasOneUse() ||
2400 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
2401 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2407 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
2408 if (Branch && Branch->isConditional()) {
2409 // Look for the selector dispatch.
2410 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2411 // %matches = icmp eq i32 %sel, %2
2412 // br i1 %matches, label %catch14, label %eh.resume
2413 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2414 if (!Compare || !Compare->isEquality())
2415 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2416 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2418 Instruction *Inst = II;
2419 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2421 if (Inst == Compare || Inst == Branch)
2423 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2425 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2427 // The selector dispatch block should always terminate our search.
2428 assert(BB == EndBB);
2432 if (isAsynchronousEHPersonality(Personality)) {
2433 // If this is a landingpad block, split the block at the first non-landing
2435 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2437 while (MaybeCall != BB->getTerminator() &&
2438 LPadMap->isLandingPadSpecificInst(MaybeCall))
2439 MaybeCall = MaybeCall->getNextNode();
2442 // Look for outlined finally calls on x64, since those happen to match the
2443 // prototype provided by the runtime.
2444 if (TheTriple.getArch() == Triple::x86_64) {
2445 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2446 Function *Fin = FinallyCall.getCalledFunction();
2447 assert(Fin && "outlined finally call should be direct");
2448 auto *Action = new CleanupHandler(BB);
2449 Action->setHandlerBlockOrFunc(Fin);
2450 Actions.insertCleanupHandler(Action);
2451 CleanupHandlerMap[BB] = Action;
2452 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2453 << Fin->getName() << " in block "
2454 << Action->getStartBlock()->getName() << "\n");
2456 // Split the block if there were more interesting instructions and
2457 // look for finally calls in the normal successor block.
2458 BasicBlock *SuccBB = BB;
2459 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2460 FinallyCall.getInstruction()->getNextNode() !=
2461 BB->getTerminator()) {
2463 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
2465 if (FinallyCall.isInvoke()) {
2466 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2469 SuccBB = BB->getUniqueSuccessor();
2471 "splitOutlinedFinallyCalls didn't insert a branch");
2482 // Anything else is either a catch block or interesting cleanup code.
2483 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2485 Instruction *Inst = II;
2486 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2488 // Unconditional branches fall through to this loop.
2491 // If this is a catch block, there is no cleanup code to be found.
2492 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2494 // If this a nested landing pad, it may contain an endcatch call.
2495 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2497 // Anything else makes this interesting cleanup code.
2498 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2501 // Only unconditional branches in empty blocks should get this far.
2502 assert(Branch && Branch->isUnconditional());
2505 BB = Branch->getSuccessor(0);
2509 // This is a public function, declared in WinEHFuncInfo.h and is also
2510 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2511 void llvm::parseEHActions(
2512 const IntrinsicInst *II,
2513 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
2514 assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2515 "attempted to parse non eh.actions intrinsic");
2516 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2517 uint64_t ActionKind =
2518 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2519 if (ActionKind == /*catch=*/1) {
2520 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2521 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2522 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2523 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2525 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2526 /*NextBB=*/nullptr);
2527 CH->setHandlerBlockOrFunc(Handler);
2528 CH->setExceptionVarIndex(EHObjIndexVal);
2529 Actions.push_back(std::move(CH));
2530 } else if (ActionKind == 0) {
2531 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2533 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
2534 CH->setHandlerBlockOrFunc(Handler);
2535 Actions.push_back(std::move(CH));
2537 llvm_unreachable("Expected either a catch or cleanup handler!");
2540 std::reverse(Actions.begin(), Actions.end());
2544 struct WinEHNumbering {
2545 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
2546 CurrentBaseState(-1), NextState(0) {}
2548 WinEHFuncInfo &FuncInfo;
2549 int CurrentBaseState;
2552 SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
2553 SmallPtrSet<const Function *, 4> VisitedHandlers;
2555 int currentEHNumber() const {
2556 return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
2559 void createUnwindMapEntry(int ToState, ActionHandler *AH);
2560 void createTryBlockMapEntry(int TryLow, int TryHigh,
2561 ArrayRef<CatchHandler *> Handlers);
2562 void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2563 ImmutableCallSite CS);
2564 void popUnmatchedActions(int FirstMismatch);
2565 void calculateStateNumbers(const Function &F);
2566 void findActionRootLPads(const Function &F);
2570 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
2571 WinEHUnwindMapEntry UME;
2572 UME.ToState = ToState;
2573 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
2574 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
2576 UME.Cleanup = nullptr;
2577 FuncInfo.UnwindMap.push_back(UME);
2580 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
2581 ArrayRef<CatchHandler *> Handlers) {
2582 // See if we already have an entry for this set of handlers.
2583 // This is using iterators rather than a range-based for loop because
2584 // if we find the entry we're looking for we'll need the iterator to erase it.
2585 int NumHandlers = Handlers.size();
2586 auto I = FuncInfo.TryBlockMap.begin();
2587 auto E = FuncInfo.TryBlockMap.end();
2588 for ( ; I != E; ++I) {
2590 if (Entry.HandlerArray.size() != (size_t)NumHandlers)
2593 for (N = 0; N < NumHandlers; ++N) {
2594 if (Entry.HandlerArray[N].Handler != Handlers[N]->getHandlerBlockOrFunc())
2595 break; // breaks out of inner loop
2597 // If all the handlers match, this is what we were looking for.
2598 if (N == NumHandlers) {
2603 // If we found an existing entry for this set of handlers, extend the range
2604 // but move the entry to the end of the map vector. The order of entries
2605 // in the map is critical to the way that the runtime finds handlers.
2606 // FIXME: Depending on what has happened with block ordering, this may
2607 // incorrectly combine entries that should remain separate.
2609 // Copy the existing entry.
2610 WinEHTryBlockMapEntry Entry = *I;
2611 Entry.TryLow = std::min(TryLow, Entry.TryLow);
2612 Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
2613 assert(Entry.TryLow <= Entry.TryHigh);
2614 // Erase the old entry and add this one to the back.
2615 FuncInfo.TryBlockMap.erase(I);
2616 FuncInfo.TryBlockMap.push_back(Entry);
2620 // If we didn't find an entry, create a new one.
2621 WinEHTryBlockMapEntry TBME;
2622 TBME.TryLow = TryLow;
2623 TBME.TryHigh = TryHigh;
2624 assert(TBME.TryLow <= TBME.TryHigh);
2625 for (CatchHandler *CH : Handlers) {
2626 WinEHHandlerType HT;
2627 if (CH->getSelector()->isNullValue()) {
2628 HT.Adjectives = 0x40;
2629 HT.TypeDescriptor = nullptr;
2631 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
2632 // Selectors are always pointers to GlobalVariables with 'struct' type.
2633 // The struct has two fields, adjectives and a type descriptor.
2634 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2636 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2638 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2640 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
2641 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
2642 TBME.HandlerArray.push_back(HT);
2644 FuncInfo.TryBlockMap.push_back(TBME);
2647 static void print_name(const Value *V) {
2650 DEBUG(dbgs() << "null");
2654 if (const auto *F = dyn_cast<Function>(V))
2655 DEBUG(dbgs() << F->getName());
2661 void WinEHNumbering::processCallSite(
2662 MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2663 ImmutableCallSite CS) {
2664 DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
2666 print_name(CS ? CS.getCalledValue() : nullptr);
2667 DEBUG(dbgs() << '\n');
2669 DEBUG(dbgs() << "HandlerStack: \n");
2670 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2671 DEBUG(dbgs() << " ");
2672 print_name(HandlerStack[I]->getHandlerBlockOrFunc());
2673 DEBUG(dbgs() << '\n');
2675 DEBUG(dbgs() << "Actions: \n");
2676 for (int I = 0, E = Actions.size(); I < E; ++I) {
2677 DEBUG(dbgs() << " ");
2678 print_name(Actions[I]->getHandlerBlockOrFunc());
2679 DEBUG(dbgs() << '\n');
2681 int FirstMismatch = 0;
2682 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
2684 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
2685 Actions[FirstMismatch]->getHandlerBlockOrFunc())
2689 // Remove unmatched actions from the stack and process their EH states.
2690 popUnmatchedActions(FirstMismatch);
2692 DEBUG(dbgs() << "Pushing actions for CallSite: ");
2693 print_name(CS ? CS.getCalledValue() : nullptr);
2694 DEBUG(dbgs() << '\n');
2696 bool LastActionWasCatch = false;
2697 const LandingPadInst *LastRootLPad = nullptr;
2698 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
2699 // We can reuse eh states when pushing two catches for the same invoke.
2700 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
2701 auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
2702 // Various conditions can lead to a handler being popped from the
2703 // stack and re-pushed later. That shouldn't create a new state.
2704 // FIXME: Can code optimization lead to re-used handlers?
2705 if (FuncInfo.HandlerEnclosedState.count(Handler)) {
2706 // If we already assigned the state enclosed by this handler re-use it.
2707 Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
2710 const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
2711 if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
2712 DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
2713 Actions[I]->setEHState(currentEHNumber());
2715 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
2716 print_name(Actions[I]->getHandlerBlockOrFunc());
2717 DEBUG(dbgs() << ") with EH state " << NextState << "\n");
2718 createUnwindMapEntry(currentEHNumber(), Actions[I].get());
2719 DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
2720 Actions[I]->setEHState(NextState);
2723 HandlerStack.push_back(std::move(Actions[I]));
2724 LastActionWasCatch = CurrActionIsCatch;
2725 LastRootLPad = RootLPad;
2728 // This is used to defer numbering states for a handler until after the
2729 // last time it appears in an invoke action list.
2730 if (CS.isInvoke()) {
2731 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2732 auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
2733 if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
2735 FuncInfo.LastInvokeVisited[Handler] = true;
2736 DEBUG(dbgs() << "Last invoke of ");
2737 print_name(Handler);
2738 DEBUG(dbgs() << " has been visited.\n");
2742 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
2743 print_name(CS ? CS.getCalledValue() : nullptr);
2744 DEBUG(dbgs() << '\n');
2747 void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
2748 // Don't recurse while we are looping over the handler stack. Instead, defer
2749 // the numbering of the catch handlers until we are done popping.
2750 SmallVector<CatchHandler *, 4> PoppedCatches;
2751 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
2752 std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
2753 if (isa<CatchHandler>(Handler.get()))
2754 PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
2757 int TryHigh = NextState - 1;
2758 int LastTryLowIdx = 0;
2759 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
2760 CatchHandler *CH = PoppedCatches[I];
2761 DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
2762 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
2763 int TryLow = CH->getEHState();
2765 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
2766 DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
2767 for (size_t J = 0; J < Handlers.size(); ++J) {
2768 DEBUG(dbgs() << ", ");
2769 print_name(Handlers[J]->getHandlerBlockOrFunc());
2771 DEBUG(dbgs() << ")\n");
2772 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
2773 LastTryLowIdx = I + 1;
2777 for (CatchHandler *CH : PoppedCatches) {
2778 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
2779 if (FuncInfo.LastInvokeVisited[F]) {
2780 DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
2782 DEBUG(dbgs() << '\n');
2783 FuncInfo.HandlerBaseState[F] = NextState;
2784 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
2786 createUnwindMapEntry(currentEHNumber(), nullptr);
2788 calculateStateNumbers(*F);
2791 DEBUG(dbgs() << "Deferring handling of ");
2793 DEBUG(dbgs() << " until last invoke visited.\n");
2800 void WinEHNumbering::calculateStateNumbers(const Function &F) {
2801 auto I = VisitedHandlers.insert(&F);
2803 return; // We've already visited this handler, don't renumber it.
2805 int OldBaseState = CurrentBaseState;
2806 if (FuncInfo.HandlerBaseState.count(&F)) {
2807 CurrentBaseState = FuncInfo.HandlerBaseState[&F];
2810 size_t SavedHandlerStackSize = HandlerStack.size();
2812 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
2813 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2814 for (const BasicBlock &BB : F) {
2815 for (const Instruction &I : BB) {
2816 const auto *CI = dyn_cast<CallInst>(&I);
2817 if (!CI || CI->doesNotThrow())
2819 processCallSite(None, CI);
2821 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2824 const LandingPadInst *LPI = II->getLandingPadInst();
2825 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2828 parseEHActions(ActionsCall, ActionList);
2829 if (ActionList.empty())
2831 processCallSite(ActionList, II);
2833 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
2834 DEBUG(dbgs() << "Assigning state " << currentEHNumber()
2835 << " to landing pad at " << LPI->getParent()->getName()
2839 // Pop any actions that were pushed on the stack for this function.
2840 popUnmatchedActions(SavedHandlerStackSize);
2842 DEBUG(dbgs() << "Assigning max state " << NextState - 1
2843 << " to " << F.getName() << '\n');
2844 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
2846 CurrentBaseState = OldBaseState;
2849 // This function follows the same basic traversal as calculateStateNumbers
2850 // but it is necessary to identify the root landing pad associated
2851 // with each action before we start assigning state numbers.
2852 void WinEHNumbering::findActionRootLPads(const Function &F) {
2853 auto I = VisitedHandlers.insert(&F);
2855 return; // We've already visited this handler, don't revisit it.
2857 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2858 for (const BasicBlock &BB : F) {
2859 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2862 const LandingPadInst *LPI = II->getLandingPadInst();
2863 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2867 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
2868 parseEHActions(ActionsCall, ActionList);
2869 if (ActionList.empty())
2871 for (int I = 0, E = ActionList.size(); I < E; ++I) {
2873 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
2874 FuncInfo.LastInvoke[Handler] = II;
2875 // Don't replace the root landing pad if we previously saw this
2876 // handler in a different function.
2877 if (FuncInfo.RootLPad.count(Handler) &&
2878 FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
2880 DEBUG(dbgs() << "Setting root lpad for ");
2881 print_name(Handler);
2882 DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
2883 FuncInfo.RootLPad[Handler] = LPI;
2886 // Walk the actions again and look for nested handlers. This has to
2887 // happen after all of the actions have been processed in the current
2889 for (int I = 0, E = ActionList.size(); I < E; ++I)
2891 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
2892 findActionRootLPads(*Handler);
2897 void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
2898 WinEHFuncInfo &FuncInfo) {
2899 // Return if it's already been done.
2900 if (!FuncInfo.LandingPadStateMap.empty())
2903 WinEHNumbering Num(FuncInfo);
2904 Num.findActionRootLPads(*ParentFn);
2905 // The VisitedHandlers list is used by both findActionRootLPads and
2906 // calculateStateNumbers, but both functions need to visit all handlers.
2907 Num.VisitedHandlers.clear();
2908 Num.calculateStateNumbers(*ParentFn);
2909 // Pop everything on the handler stack.
2910 // It may be necessary to call this more than once because a handler can
2911 // be pushed on the stack as a result of clearing the stack.
2912 while (!Num.HandlerStack.empty())
2913 Num.processCallSite(None, ImmutableCallSite());
2916 void WinEHPrepare::numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB) {
2917 Instruction *FirstNonPHI = FuncletBB->getFirstNonPHI();
2918 bool IsCatch = isa<CatchPadInst>(FirstNonPHI);
2919 bool IsCleanup = isa<CleanupPadInst>(FirstNonPHI);
2921 // Initialize the worklist with the funclet's entry point.
2922 std::vector<BasicBlock *> Worklist;
2923 Worklist.push_back(InitialBB);
2925 while (!Worklist.empty()) {
2926 BasicBlock *BB = Worklist.back();
2927 Worklist.pop_back();
2929 // There can be only one "pad" basic block in the funclet: the initial one.
2930 if (BB != FuncletBB && BB->isEHPad())
2933 // Add 'FuncletBB' as a possible color for 'BB'.
2934 if (BlockColors[BB].insert(FuncletBB).second == false) {
2935 // Skip basic blocks which we have already visited.
2939 FuncletBlocks[FuncletBB].insert(BB);
2941 Instruction *Terminator = BB->getTerminator();
2942 // The catchret's successors cannot be part of the funclet.
2943 if (IsCatch && isa<CatchReturnInst>(Terminator))
2945 // The cleanupret's successors cannot be part of the funclet.
2946 if (IsCleanup && isa<CleanupReturnInst>(Terminator))
2949 Worklist.insert(Worklist.end(), succ_begin(BB), succ_end(BB));
2953 bool WinEHPrepare::prepareExplicitEH(Function &F) {
2954 // Remove unreachable blocks. It is not valuable to assign them a color and
2955 // their existence can trick us into thinking values are alive when they are
2957 removeUnreachableBlocks(F);
2959 BasicBlock *EntryBlock = &F.getEntryBlock();
2961 // Number everything starting from the entry block.
2962 numberFunclet(EntryBlock, EntryBlock);
2964 for (BasicBlock &BB : F) {
2965 // Remove single entry PHIs to simplify preparation.
2966 if (auto *PN = dyn_cast<PHINode>(BB.begin()))
2967 if (PN->getNumIncomingValues() == 1)
2968 FoldSingleEntryPHINodes(&BB);
2970 // EH pad instructions are always the first non-PHI nodes in a block if they
2971 // are at all present.
2972 Instruction *I = BB.getFirstNonPHI();
2974 numberFunclet(&BB, &BB);
2976 // It is possible for a normal basic block to only be reachable via an
2977 // exceptional basic block. The successor of a catchret is the only case
2978 // where this is possible.
2979 if (auto *CRI = dyn_cast<CatchReturnInst>(BB.getTerminator()))
2980 numberFunclet(CRI->getSuccessor(), EntryBlock);
2983 // Strip PHI nodes off of EH pads.
2984 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
2985 BasicBlock *BB = FI++;
2986 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
2989 Instruction *I = BI++;
2990 auto *PN = dyn_cast<PHINode>(I);
2993 auto *SpillSlot = new AllocaInst(I->getType(), nullptr,
2994 Twine(I->getName(), ".wineh.phispill"),
2995 EntryBlock->begin());
2997 // Iterate over each operand inserting a store in each predecessor.
2998 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
2999 new StoreInst(P->getIncomingValue(i), Slot,
3000 P->getIncomingBlock(i)->getTerminator());
3004 // Turn all inter-funclet uses of a Value into loads and stores.
3005 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3006 BasicBlock *BB = FI++;
3007 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3008 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3009 Instruction *I = BI++;
3010 // Funclets are permitted to use static allocas.
3011 if (auto *AI = dyn_cast<AllocaInst>(I))
3012 if (AI->isStaticAlloca())
3015 // FIXME: Our spill-placement algorithm is incredibly naive. We should
3016 // try to sink+hoist as much as possible to avoid redundant stores and reloads.
3017 DenseMap<BasicBlock *, Value *> Loads;
3018 AllocaInst *SpillSlot = nullptr;
3019 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3022 auto *UsingInst = cast<Instruction>(U.getUser());
3023 BasicBlock *UsingBB = UsingInst->getParent();
3025 // Is the Use inside a block which is colored with a subset of the Def?
3026 // If so, we don't need to escape the Def because we will clone
3027 // ourselves our own private copy.
3028 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
3029 if (std::includes(ColorsForBB.begin(), ColorsForBB.end(),
3030 ColorsForUsingBB.begin(), ColorsForUsingBB.end()))
3033 // Lazilly create the spill slot. We spill immediately after the value
3034 // in the BasicBlock.
3035 // FIXME: This can be improved to spill at the block exit points.
3037 SpillSlot = new AllocaInst(I->getType(), nullptr,
3038 Twine(I->getName(), ".wineh.spillslot"),
3039 EntryBlock->begin());
3041 if (auto *PN = dyn_cast<PHINode>(UsingInst)) {
3042 // If this is a PHI node, we can't insert a load of the value before
3043 // the use. Instead insert the load in the predecessor block
3044 // corresponding to the incoming value.
3046 // Note that if there are multiple edges from a basic block to this
3047 // PHI node that we cannot have multiple loads. The problem is that
3048 // the resulting PHI node will have multiple values (from each load)
3049 // coming in from the same block, which is illegal SSA form.
3050 // For this reason, we keep track of and reuse loads we insert.
3051 BasicBlock *IncomingBlock = PN->getIncomingBlock(U);
3052 Value *&V = Loads[IncomingBlock];
3053 // Insert the load into the predecessor block
3055 V = new LoadInst(SpillSlot, Twine(I->getName(), ".wineh.reload"),
3057 IncomingBlock->getTerminator());
3060 // Reload right before the old use.
3061 // FIXME: This can be improved to reload at a block entry point.
3063 new LoadInst(SpillSlot, Twine(I->getName(), ".wineh.reload"),
3064 /*Volatile=*/false, UsingInst);
3069 // Insert stores of the computed value into the stack slot.
3070 // We have to be careful if I is an invoke instruction,
3071 // because we can't insert the store AFTER the terminator instruction.
3072 BasicBlock::iterator InsertPt;
3073 if (!isa<TerminatorInst>(I)) {
3076 // Don't insert before PHI nodes or EH pad instrs.
3077 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
3080 auto *II = cast<InvokeInst>(I);
3081 // We cannot demote invoke instructions to the stack if their normal
3082 // edge is critical. Therefore, split the critical edge and create a
3083 // basic block into which the store can be inserted.
3084 if (!II->getNormalDest()->getSinglePredecessor()) {
3085 unsigned SuccNum = GetSuccessorNumber(BB, II->getNormalDest());
3086 assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
3087 BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
3088 assert(NewBlock && "Unable to split critical edge.");
3089 // Update the color mapping for the newly split edge.
3090 std::set<BasicBlock *> &ColorsForUsingBB =
3091 BlockColors[II->getParent()];
3092 BlockColors[NewBlock] = ColorsForUsingBB;
3093 for (BasicBlock *FuncletPad : ColorsForUsingBB)
3094 FuncletBlocks[FuncletPad].insert(NewBlock);
3096 InsertPt = II->getNormalDest()->getFirstInsertionPt();
3098 new StoreInst(I, SpillSlot, InsertPt);
3103 // We need to clone all blocks which belong to multiple funclets. Values are
3104 // remapped throughout the funclet to propogate both the new instructions
3105 // *and* the new basic blocks themselves.
3106 for (auto &Funclet : FuncletBlocks) {
3107 BasicBlock *FuncletPadBB = Funclet.first;
3108 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3110 std::map<BasicBlock *, BasicBlock *> Orig2Clone;
3111 ValueToValueMapTy VMap;
3112 for (BasicBlock *BB : BlocksInFunclet) {
3113 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3114 // We don't need to do anything if the block is monochromatic.
3115 size_t NumColorsForBB = ColorsForBB.size();
3116 if (NumColorsForBB == 1)
3119 // Create a new basic block and copy instructions into it!
3120 BasicBlock *CBB = CloneBasicBlock(
3121 BB, VMap, Twine(".for.", FuncletPadBB->getName()), &F);
3123 // Add basic block mapping.
3126 // Record delta operations that we need to perform to our color mappings.
3127 Orig2Clone[BB] = CBB;
3130 // Update our color mappings to reflect that one block has lost a color and
3131 // another has gained a color.
3132 for (auto &BBMapping : Orig2Clone) {
3133 BasicBlock *OldBlock = BBMapping.first;
3134 BasicBlock *NewBlock = BBMapping.second;
3136 BlocksInFunclet.insert(NewBlock);
3137 BlockColors[NewBlock].insert(FuncletPadBB);
3139 BlocksInFunclet.erase(OldBlock);
3140 BlockColors[OldBlock].erase(FuncletPadBB);
3143 // Loop over all of the instructions in the function, fixing up operand
3144 // references as we go. This uses VMap to do all the hard work.
3145 for (BasicBlock *BB : BlocksInFunclet)
3146 // Loop over all instructions, fixing each one as we find it...
3147 for (Instruction &I : *BB)
3148 RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
3150 // Our PHI nodes have stale predecessors after we have cloned our new blocks
3151 // into the CFG. Fix this by removing the stale predecessors.
3152 for (BasicBlock *BB : BlocksInFunclet) {
3153 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3154 Instruction *I = BI++;
3155 auto *PN = dyn_cast<PHINode>(I);
3156 // All the PHI nodes are bunched together at the start of the BB.
3157 // Stop once we've hit a non-PHI.
3161 // Create a list of all the incoming PHI values we'd like to remove.
3162 // This is done in two steps to avoid iterator invalidation issues.
3163 std::vector<unsigned> IndicesToRemove;
3164 for (unsigned Idx = 0, E = PN->getNumIncomingValues(); Idx != E;
3166 BasicBlock *PredBB = PN->getIncomingBlock(Idx);
3167 if (BlockColors[PredBB].count(FuncletPadBB) == 0)
3168 IndicesToRemove.push_back(Idx);
3170 // Remove incoming values in the reverse order to prevent invalidating
3171 // *successive* index.
3172 for (auto I = IndicesToRemove.rbegin(), E = IndicesToRemove.rend();
3174 PN->removeIncomingValue(*I);
3179 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
3181 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3182 BasicBlock *BB = FI++;
3183 SimplifyInstructionsInBlock(BB);
3184 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
3185 MergeBlockIntoPredecessor(BB);
3188 // TODO: Do something about cleanupblocks which branch to implausible
3191 // We might have some unreachable blocks after cleaning up some impossible
3193 removeUnreachableBlocks(F);
3195 // Recolor the CFG to verify that all is well.
3196 for (BasicBlock &BB : F) {
3197 size_t NumColors = BlockColors[&BB].size();
3198 assert(NumColors == 1 && "Expected monochromatic BB!");
3200 report_fatal_error("Uncolored BB!");
3202 report_fatal_error("Multicolor BB!");
3203 bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
3204 assert(!EHPadHasPHI && "EH Pad still has a PHI!");
3206 report_fatal_error("EH Pad still has a PHI!");
3209 BlockColors.clear();
3210 FuncletBlocks.clear();