Re-land "[WinEH] Add an EH registration and state insertion pass for 32-bit x86"
[oota-llvm.git] / lib / CodeGen / WinEHPrepare.cpp
1 //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass lowers LLVM IR exception handling into something closer to what the
11 // backend wants 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.
16 //
17 //===----------------------------------------------------------------------===//
18
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/LibCallSemantics.h"
27 #include "llvm/CodeGen/WinEHFuncInfo.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/Cloning.h"
40 #include "llvm/Transforms/Utils/Local.h"
41 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
42 #include <memory>
43
44 using namespace llvm;
45 using namespace llvm::PatternMatch;
46
47 #define DEBUG_TYPE "winehprepare"
48
49 namespace {
50
51 // This map is used to model frame variable usage during outlining, to
52 // construct a structure type to hold the frame variables in a frame
53 // allocation block, and to remap the frame variable allocas (including
54 // spill locations as needed) to GEPs that get the variable from the
55 // frame allocation structure.
56 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
57
58 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
59 // quite null.
60 AllocaInst *getCatchObjectSentinel() {
61   return static_cast<AllocaInst *>(nullptr) + 1;
62 }
63
64 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
65
66 class LandingPadActions;
67 class LandingPadMap;
68
69 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
70 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
71
72 class WinEHPrepare : public FunctionPass {
73 public:
74   static char ID; // Pass identification, replacement for typeid.
75   WinEHPrepare(const TargetMachine *TM = nullptr)
76       : FunctionPass(ID) {
77     if (TM)
78       TheTriple = Triple(TM->getTargetTriple());
79   }
80
81   bool runOnFunction(Function &Fn) override;
82
83   bool doFinalization(Module &M) override;
84
85   void getAnalysisUsage(AnalysisUsage &AU) const override;
86
87   const char *getPassName() const override {
88     return "Windows exception handling preparation";
89   }
90
91 private:
92   bool prepareExceptionHandlers(Function &F,
93                                 SmallVectorImpl<LandingPadInst *> &LPads);
94   void promoteLandingPadValues(LandingPadInst *LPad);
95   void demoteValuesLiveAcrossHandlers(Function &F,
96                                       SmallVectorImpl<LandingPadInst *> &LPads);
97   void findSEHEHReturnPoints(Function &F,
98                              SetVector<BasicBlock *> &EHReturnBlocks);
99   void findCXXEHReturnPoints(Function &F,
100                              SetVector<BasicBlock *> &EHReturnBlocks);
101   void completeNestedLandingPad(Function *ParentFn,
102                                 LandingPadInst *OutlinedLPad,
103                                 const LandingPadInst *OriginalLPad,
104                                 FrameVarInfoMap &VarInfo);
105   Function *createHandlerFunc(Type *RetTy, const Twine &Name, Module *M,
106                               Value *&ParentFP);
107   bool outlineHandler(ActionHandler *Action, Function *SrcFn,
108                       LandingPadInst *LPad, BasicBlock *StartBB,
109                       FrameVarInfoMap &VarInfo);
110   void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn);
111
112   void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
113   CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
114                                  VisitedBlockSet &VisitedBlocks);
115   void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
116                            BasicBlock *EndBB);
117
118   void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
119
120   Triple TheTriple;
121
122   // All fields are reset by runOnFunction.
123   DominatorTree *DT = nullptr;
124   EHPersonality Personality = EHPersonality::Unknown;
125   CatchHandlerMapTy CatchHandlerMap;
126   CleanupHandlerMapTy CleanupHandlerMap;
127   DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
128
129   // This maps landing pad instructions found in outlined handlers to
130   // the landing pad instruction in the parent function from which they
131   // were cloned.  The cloned/nested landing pad is used as the key
132   // because the landing pad may be cloned into multiple handlers.
133   // This map will be used to add the llvm.eh.actions call to the nested
134   // landing pads after all handlers have been outlined.
135   DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
136
137   // This maps blocks in the parent function which are destinations of
138   // catch handlers to cloned blocks in (other) outlined handlers. This
139   // handles the case where a nested landing pads has a catch handler that
140   // returns to a handler function rather than the parent function.
141   // The original block is used as the key here because there should only
142   // ever be one handler function from which the cloned block is not pruned.
143   // The original block will be pruned from the parent function after all
144   // handlers have been outlined.  This map will be used to adjust the
145   // return instructions of handlers which return to the block that was
146   // outlined into a handler.  This is done after all handlers have been
147   // outlined but before the outlined code is pruned from the parent function.
148   DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
149
150   // Map from outlined handler to call to llvm.frameaddress(1). Only used for
151   // 32-bit EH.
152   DenseMap<Function *, Value *> HandlerToParentFP;
153
154   AllocaInst *SEHExceptionCodeSlot = nullptr;
155 };
156
157 class WinEHFrameVariableMaterializer : public ValueMaterializer {
158 public:
159   WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
160                                  FrameVarInfoMap &FrameVarInfo);
161   ~WinEHFrameVariableMaterializer() override {}
162
163   Value *materializeValueFor(Value *V) override;
164
165   void escapeCatchObject(Value *V);
166
167 private:
168   FrameVarInfoMap &FrameVarInfo;
169   IRBuilder<> Builder;
170 };
171
172 class LandingPadMap {
173 public:
174   LandingPadMap() : OriginLPad(nullptr) {}
175   void mapLandingPad(const LandingPadInst *LPad);
176
177   bool isInitialized() { return OriginLPad != nullptr; }
178
179   bool isOriginLandingPadBlock(const BasicBlock *BB) const;
180   bool isLandingPadSpecificInst(const Instruction *Inst) const;
181
182   void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
183                      Value *SelectorValue) const;
184
185 private:
186   const LandingPadInst *OriginLPad;
187   // We will normally only see one of each of these instructions, but
188   // if more than one occurs for some reason we can handle that.
189   TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
190   TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
191 };
192
193 class WinEHCloningDirectorBase : public CloningDirector {
194 public:
195   WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
196                            FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
197       : Materializer(HandlerFn, ParentFP, VarInfo),
198         SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
199         Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
200         LPadMap(LPadMap), ParentFP(ParentFP) {}
201
202   CloningAction handleInstruction(ValueToValueMapTy &VMap,
203                                   const Instruction *Inst,
204                                   BasicBlock *NewBB) override;
205
206   virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
207                                          const Instruction *Inst,
208                                          BasicBlock *NewBB) = 0;
209   virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
210                                        const Instruction *Inst,
211                                        BasicBlock *NewBB) = 0;
212   virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
213                                         const Instruction *Inst,
214                                         BasicBlock *NewBB) = 0;
215   virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
216                                      const InvokeInst *Invoke,
217                                      BasicBlock *NewBB) = 0;
218   virtual CloningAction handleResume(ValueToValueMapTy &VMap,
219                                      const ResumeInst *Resume,
220                                      BasicBlock *NewBB) = 0;
221   virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
222                                       const CmpInst *Compare,
223                                       BasicBlock *NewBB) = 0;
224   virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
225                                          const LandingPadInst *LPad,
226                                          BasicBlock *NewBB) = 0;
227
228   ValueMaterializer *getValueMaterializer() override { return &Materializer; }
229
230 protected:
231   WinEHFrameVariableMaterializer Materializer;
232   Type *SelectorIDType;
233   Type *Int8PtrType;
234   LandingPadMap &LPadMap;
235
236   /// The value representing the parent frame pointer.
237   Value *ParentFP;
238 };
239
240 class WinEHCatchDirector : public WinEHCloningDirectorBase {
241 public:
242   WinEHCatchDirector(
243       Function *CatchFn, Value *ParentFP, Value *Selector,
244       FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
245       DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
246       : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
247         CurrentSelector(Selector->stripPointerCasts()),
248         ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
249
250   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
251                                  const Instruction *Inst,
252                                  BasicBlock *NewBB) override;
253   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
254                                BasicBlock *NewBB) override;
255   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
256                                 const Instruction *Inst,
257                                 BasicBlock *NewBB) override;
258   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
259                              BasicBlock *NewBB) override;
260   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
261                              BasicBlock *NewBB) override;
262   CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
263                               BasicBlock *NewBB) override;
264   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
265                                  const LandingPadInst *LPad,
266                                  BasicBlock *NewBB) override;
267
268   Value *getExceptionVar() { return ExceptionObjectVar; }
269   TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
270
271 private:
272   Value *CurrentSelector;
273
274   Value *ExceptionObjectVar;
275   TinyPtrVector<BasicBlock *> ReturnTargets;
276
277   // This will be a reference to the field of the same name in the WinEHPrepare
278   // object which instantiates this WinEHCatchDirector object.
279   DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
280 };
281
282 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
283 public:
284   WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
285                        FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
286       : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
287                                  LPadMap) {}
288
289   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
290                                  const Instruction *Inst,
291                                  BasicBlock *NewBB) override;
292   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
293                                BasicBlock *NewBB) override;
294   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
295                                 const Instruction *Inst,
296                                 BasicBlock *NewBB) override;
297   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
298                              BasicBlock *NewBB) override;
299   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
300                              BasicBlock *NewBB) override;
301   CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
302                               BasicBlock *NewBB) override;
303   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
304                                  const LandingPadInst *LPad,
305                                  BasicBlock *NewBB) override;
306 };
307
308 class LandingPadActions {
309 public:
310   LandingPadActions() : HasCleanupHandlers(false) {}
311
312   void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
313   void insertCleanupHandler(CleanupHandler *Action) {
314     Actions.push_back(Action);
315     HasCleanupHandlers = true;
316   }
317
318   bool includesCleanup() const { return HasCleanupHandlers; }
319
320   SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
321   SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
322   SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
323
324 private:
325   // Note that this class does not own the ActionHandler objects in this vector.
326   // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
327   // in the WinEHPrepare class.
328   SmallVector<ActionHandler *, 4> Actions;
329   bool HasCleanupHandlers;
330 };
331
332 } // end anonymous namespace
333
334 char WinEHPrepare::ID = 0;
335 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
336                    false, false)
337
338 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
339   return new WinEHPrepare(TM);
340 }
341
342 bool WinEHPrepare::runOnFunction(Function &Fn) {
343   // No need to prepare outlined handlers.
344   if (Fn.hasFnAttribute("wineh-parent"))
345     return false;
346
347   SmallVector<LandingPadInst *, 4> LPads;
348   SmallVector<ResumeInst *, 4> Resumes;
349   for (BasicBlock &BB : Fn) {
350     if (auto *LP = BB.getLandingPadInst())
351       LPads.push_back(LP);
352     if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
353       Resumes.push_back(Resume);
354   }
355
356   // No need to prepare functions that lack landing pads.
357   if (LPads.empty())
358     return false;
359
360   // Classify the personality to see what kind of preparation we need.
361   Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
362
363   // Do nothing if this is not an MSVC personality.
364   if (!isMSVCEHPersonality(Personality))
365     return false;
366
367   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
368
369   // If there were any landing pads, prepareExceptionHandlers will make changes.
370   prepareExceptionHandlers(Fn, LPads);
371   return true;
372 }
373
374 bool WinEHPrepare::doFinalization(Module &M) { return false; }
375
376 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
377   AU.addRequired<DominatorTreeWrapperPass>();
378 }
379
380 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
381                                Constant *&Selector, BasicBlock *&NextBB);
382
383 // Finds blocks reachable from the starting set Worklist. Does not follow unwind
384 // edges or blocks listed in StopPoints.
385 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
386                                 SetVector<BasicBlock *> &Worklist,
387                                 const SetVector<BasicBlock *> *StopPoints) {
388   while (!Worklist.empty()) {
389     BasicBlock *BB = Worklist.pop_back_val();
390
391     // Don't cross blocks that we should stop at.
392     if (StopPoints && StopPoints->count(BB))
393       continue;
394
395     if (!ReachableBBs.insert(BB).second)
396       continue; // Already visited.
397
398     // Don't follow unwind edges of invokes.
399     if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
400       Worklist.insert(II->getNormalDest());
401       continue;
402     }
403
404     // Otherwise, follow all successors.
405     Worklist.insert(succ_begin(BB), succ_end(BB));
406   }
407 }
408
409 // Attempt to find an instruction where a block can be split before
410 // a call to llvm.eh.begincatch and its operands.  If the block
411 // begins with the begincatch call or one of its adjacent operands
412 // the block will not be split.
413 static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
414                                              IntrinsicInst *II) {
415   // If the begincatch call is already the first instruction in the block,
416   // don't split.
417   Instruction *FirstNonPHI = BB->getFirstNonPHI();
418   if (II == FirstNonPHI)
419     return nullptr;
420
421   // If either operand is in the same basic block as the instruction and
422   // isn't used by another instruction before the begincatch call, include it
423   // in the split block.
424   auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
425   auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
426
427   Instruction *I = II->getPrevNode();
428   Instruction *LastI = II;
429
430   while (I == Op0 || I == Op1) {
431     // If the block begins with one of the operands and there are no other
432     // instructions between the operand and the begincatch call, don't split.
433     if (I == FirstNonPHI)
434       return nullptr;
435
436     LastI = I;
437     I = I->getPrevNode();
438   }
439
440   // If there is at least one instruction in the block before the begincatch
441   // call and its operands, split the block at either the begincatch or
442   // its operand.
443   return LastI;
444 }
445
446 /// Find all points where exceptional control rejoins normal control flow via
447 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
448 void WinEHPrepare::findCXXEHReturnPoints(
449     Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
450   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
451     BasicBlock *BB = BBI;
452     for (Instruction &I : *BB) {
453       if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
454         Instruction *SplitPt =
455             findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
456         if (SplitPt) {
457           // Split the block before the llvm.eh.begincatch call to allow
458           // cleanup and catch code to be distinguished later.
459           // Do not update BBI because we still need to process the
460           // portion of the block that we are splitting off.
461           SplitBlock(BB, SplitPt, DT);
462           break;
463         }
464       }
465       if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
466         // Split the block after the call to llvm.eh.endcatch if there is
467         // anything other than an unconditional branch, or if the successor
468         // starts with a phi.
469         auto *Br = dyn_cast<BranchInst>(I.getNextNode());
470         if (!Br || !Br->isUnconditional() ||
471             isa<PHINode>(Br->getSuccessor(0)->begin())) {
472           DEBUG(dbgs() << "splitting block " << BB->getName()
473                        << " with llvm.eh.endcatch\n");
474           BBI = SplitBlock(BB, I.getNextNode(), DT);
475         }
476         // The next BB is normal control flow.
477         EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
478         break;
479       }
480     }
481   }
482 }
483
484 static bool isCatchAllLandingPad(const BasicBlock *BB) {
485   const LandingPadInst *LP = BB->getLandingPadInst();
486   if (!LP)
487     return false;
488   unsigned N = LP->getNumClauses();
489   return (N > 0 && LP->isCatch(N - 1) &&
490           isa<ConstantPointerNull>(LP->getClause(N - 1)));
491 }
492
493 /// Find all points where exceptions control rejoins normal control flow via
494 /// selector dispatch.
495 void WinEHPrepare::findSEHEHReturnPoints(
496     Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
497   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
498     BasicBlock *BB = BBI;
499     // If the landingpad is a catch-all, treat the whole lpad as if it is
500     // reachable from normal control flow.
501     // FIXME: This is imprecise. We need a better way of identifying where a
502     // catch-all starts and cleanups stop. As far as LLVM is concerned, there
503     // is no difference.
504     if (isCatchAllLandingPad(BB)) {
505       EHReturnBlocks.insert(BB);
506       continue;
507     }
508
509     BasicBlock *CatchHandler;
510     BasicBlock *NextBB;
511     Constant *Selector;
512     if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
513       // Split the edge if there is a phi node. Returning from EH to a phi node
514       // is just as impossible as having a phi after an indirectbr.
515       if (isa<PHINode>(CatchHandler->begin())) {
516         DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
517                      << " to " << CatchHandler->getName() << '\n');
518         BBI = CatchHandler = SplitCriticalEdge(
519             BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
520       }
521       EHReturnBlocks.insert(CatchHandler);
522     }
523   }
524 }
525
526 /// Ensure that all values live into and out of exception handlers are stored
527 /// in memory.
528 /// FIXME: This falls down when values are defined in one handler and live into
529 /// another handler. For example, a cleanup defines a value used only by a
530 /// catch handler.
531 void WinEHPrepare::demoteValuesLiveAcrossHandlers(
532     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
533   DEBUG(dbgs() << "Demoting values live across exception handlers in function "
534                << F.getName() << '\n');
535
536   // Build a set of all non-exceptional blocks and exceptional blocks.
537   // - Non-exceptional blocks are blocks reachable from the entry block while
538   //   not following invoke unwind edges.
539   // - Exceptional blocks are blocks reachable from landingpads. Analysis does
540   //   not follow llvm.eh.endcatch blocks, which mark a transition from
541   //   exceptional to normal control.
542   SmallPtrSet<BasicBlock *, 4> NormalBlocks;
543   SmallPtrSet<BasicBlock *, 4> EHBlocks;
544   SetVector<BasicBlock *> EHReturnBlocks;
545   SetVector<BasicBlock *> Worklist;
546
547   if (Personality == EHPersonality::MSVC_CXX)
548     findCXXEHReturnPoints(F, EHReturnBlocks);
549   else
550     findSEHEHReturnPoints(F, EHReturnBlocks);
551
552   DEBUG({
553     dbgs() << "identified the following blocks as EH return points:\n";
554     for (BasicBlock *BB : EHReturnBlocks)
555       dbgs() << "  " << BB->getName() << '\n';
556   });
557
558 // Join points should not have phis at this point, unless they are a
559 // landingpad, in which case we will demote their phis later.
560 #ifndef NDEBUG
561   for (BasicBlock *BB : EHReturnBlocks)
562     assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
563            "non-lpad EH return block has phi");
564 #endif
565
566   // Normal blocks are the blocks reachable from the entry block and all EH
567   // return points.
568   Worklist = EHReturnBlocks;
569   Worklist.insert(&F.getEntryBlock());
570   findReachableBlocks(NormalBlocks, Worklist, nullptr);
571   DEBUG({
572     dbgs() << "marked the following blocks as normal:\n";
573     for (BasicBlock *BB : NormalBlocks)
574       dbgs() << "  " << BB->getName() << '\n';
575   });
576
577   // Exceptional blocks are the blocks reachable from landingpads that don't
578   // cross EH return points.
579   Worklist.clear();
580   for (auto *LPI : LPads)
581     Worklist.insert(LPI->getParent());
582   findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
583   DEBUG({
584     dbgs() << "marked the following blocks as exceptional:\n";
585     for (BasicBlock *BB : EHBlocks)
586       dbgs() << "  " << BB->getName() << '\n';
587   });
588
589   SetVector<Argument *> ArgsToDemote;
590   SetVector<Instruction *> InstrsToDemote;
591   for (BasicBlock &BB : F) {
592     bool IsNormalBB = NormalBlocks.count(&BB);
593     bool IsEHBB = EHBlocks.count(&BB);
594     if (!IsNormalBB && !IsEHBB)
595       continue; // Blocks that are neither normal nor EH are unreachable.
596     for (Instruction &I : BB) {
597       for (Value *Op : I.operands()) {
598         // Don't demote static allocas, constants, and labels.
599         if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
600           continue;
601         auto *AI = dyn_cast<AllocaInst>(Op);
602         if (AI && AI->isStaticAlloca())
603           continue;
604
605         if (auto *Arg = dyn_cast<Argument>(Op)) {
606           if (IsEHBB) {
607             DEBUG(dbgs() << "Demoting argument " << *Arg
608                          << " used by EH instr: " << I << "\n");
609             ArgsToDemote.insert(Arg);
610           }
611           continue;
612         }
613
614         auto *OpI = cast<Instruction>(Op);
615         BasicBlock *OpBB = OpI->getParent();
616         // If a value is produced and consumed in the same BB, we don't need to
617         // demote it.
618         if (OpBB == &BB)
619           continue;
620         bool IsOpNormalBB = NormalBlocks.count(OpBB);
621         bool IsOpEHBB = EHBlocks.count(OpBB);
622         if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
623           DEBUG({
624             dbgs() << "Demoting instruction live in-out from EH:\n";
625             dbgs() << "Instr: " << *OpI << '\n';
626             dbgs() << "User: " << I << '\n';
627           });
628           InstrsToDemote.insert(OpI);
629         }
630       }
631     }
632   }
633
634   // Demote values live into and out of handlers.
635   // FIXME: This demotion is inefficient. We should insert spills at the point
636   // of definition, insert one reload in each handler that uses the value, and
637   // insert reloads in the BB used to rejoin normal control flow.
638   Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
639   for (Instruction *I : InstrsToDemote)
640     DemoteRegToStack(*I, false, AllocaInsertPt);
641
642   // Demote arguments separately, and only for uses in EH blocks.
643   for (Argument *Arg : ArgsToDemote) {
644     auto *Slot = new AllocaInst(Arg->getType(), nullptr,
645                                 Arg->getName() + ".reg2mem", AllocaInsertPt);
646     SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
647     for (User *U : Users) {
648       auto *I = dyn_cast<Instruction>(U);
649       if (I && EHBlocks.count(I->getParent())) {
650         auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
651         U->replaceUsesOfWith(Arg, Reload);
652       }
653     }
654     new StoreInst(Arg, Slot, AllocaInsertPt);
655   }
656
657   // Demote landingpad phis, as the landingpad will be removed from the machine
658   // CFG.
659   for (LandingPadInst *LPI : LPads) {
660     BasicBlock *BB = LPI->getParent();
661     while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
662       DemotePHIToStack(Phi, AllocaInsertPt);
663   }
664
665   DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
666                << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
667 }
668
669 bool WinEHPrepare::prepareExceptionHandlers(
670     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
671   // Don't run on functions that are already prepared.
672   for (LandingPadInst *LPad : LPads) {
673     BasicBlock *LPadBB = LPad->getParent();
674     for (Instruction &Inst : *LPadBB)
675       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
676         return false;
677   }
678
679   demoteValuesLiveAcrossHandlers(F, LPads);
680
681   // These containers are used to re-map frame variables that are used in
682   // outlined catch and cleanup handlers.  They will be populated as the
683   // handlers are outlined.
684   FrameVarInfoMap FrameVarInfo;
685
686   bool HandlersOutlined = false;
687
688   Module *M = F.getParent();
689   LLVMContext &Context = M->getContext();
690
691   // Create a new function to receive the handler contents.
692   PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
693   Type *Int32Type = Type::getInt32Ty(Context);
694   Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
695
696   if (isAsynchronousEHPersonality(Personality)) {
697     // FIXME: Switch the ehptr type to i32 and then switch this.
698     SEHExceptionCodeSlot =
699         new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
700                        F.getEntryBlock().getFirstInsertionPt());
701   }
702
703   for (LandingPadInst *LPad : LPads) {
704     // Look for evidence that this landingpad has already been processed.
705     bool LPadHasActionList = false;
706     BasicBlock *LPadBB = LPad->getParent();
707     for (Instruction &Inst : *LPadBB) {
708       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
709         LPadHasActionList = true;
710         break;
711       }
712     }
713
714     // If we've already outlined the handlers for this landingpad,
715     // there's nothing more to do here.
716     if (LPadHasActionList)
717       continue;
718
719     // If either of the values in the aggregate returned by the landing pad is
720     // extracted and stored to memory, promote the stored value to a register.
721     promoteLandingPadValues(LPad);
722
723     LandingPadActions Actions;
724     mapLandingPadBlocks(LPad, Actions);
725
726     HandlersOutlined |= !Actions.actions().empty();
727     for (ActionHandler *Action : Actions) {
728       if (Action->hasBeenProcessed())
729         continue;
730       BasicBlock *StartBB = Action->getStartBlock();
731
732       // SEH doesn't do any outlining for catches. Instead, pass the handler
733       // basic block addr to llvm.eh.actions and list the block as a return
734       // target.
735       if (isAsynchronousEHPersonality(Personality)) {
736         if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
737           processSEHCatchHandler(CatchAction, StartBB);
738           continue;
739         }
740       }
741
742       outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
743     }
744
745     // Split the block after the landingpad instruction so that it is just a
746     // call to llvm.eh.actions followed by indirectbr.
747     assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
748     SplitBlock(LPadBB, LPad->getNextNode(), DT);
749     // Erase the branch inserted by the split so we can insert indirectbr.
750     LPadBB->getTerminator()->eraseFromParent();
751
752     // Replace all extracted values with undef and ultimately replace the
753     // landingpad with undef.
754     SmallVector<Instruction *, 4> SEHCodeUses;
755     SmallVector<Instruction *, 4> EHUndefs;
756     for (User *U : LPad->users()) {
757       auto *E = dyn_cast<ExtractValueInst>(U);
758       if (!E)
759         continue;
760       assert(E->getNumIndices() == 1 &&
761              "Unexpected operation: extracting both landing pad values");
762       unsigned Idx = *E->idx_begin();
763       assert((Idx == 0 || Idx == 1) && "unexpected index");
764       if (Idx == 0 && isAsynchronousEHPersonality(Personality))
765         SEHCodeUses.push_back(E);
766       else
767         EHUndefs.push_back(E);
768     }
769     for (Instruction *E : EHUndefs) {
770       E->replaceAllUsesWith(UndefValue::get(E->getType()));
771       E->eraseFromParent();
772     }
773     LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
774
775     // Rewrite uses of the exception pointer to loads of an alloca.
776     for (Instruction *E : SEHCodeUses) {
777       SmallVector<Use *, 4> Uses;
778       for (Use &U : E->uses())
779         Uses.push_back(&U);
780       for (Use *U : Uses) {
781         auto *I = cast<Instruction>(U->getUser());
782         if (isa<ResumeInst>(I))
783           continue;
784         LoadInst *LI;
785         if (auto *Phi = dyn_cast<PHINode>(I))
786           LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false,
787                             Phi->getIncomingBlock(*U));
788         else
789           LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I);
790         U->set(LI);
791       }
792       E->replaceAllUsesWith(UndefValue::get(E->getType()));
793       E->eraseFromParent();
794     }
795
796     // Add a call to describe the actions for this landing pad.
797     std::vector<Value *> ActionArgs;
798     for (ActionHandler *Action : Actions) {
799       // Action codes from docs are: 0 cleanup, 1 catch.
800       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
801         ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
802         ActionArgs.push_back(CatchAction->getSelector());
803         // Find the frame escape index of the exception object alloca in the
804         // parent.
805         int FrameEscapeIdx = -1;
806         Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
807         if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
808           auto I = FrameVarInfo.find(EHObj);
809           assert(I != FrameVarInfo.end() &&
810                  "failed to map llvm.eh.begincatch var");
811           FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
812         }
813         ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
814       } else {
815         ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
816       }
817       ActionArgs.push_back(Action->getHandlerBlockOrFunc());
818     }
819     CallInst *Recover =
820         CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
821
822     // Add an indirect branch listing possible successors of the catch handlers.
823     SetVector<BasicBlock *> ReturnTargets;
824     for (ActionHandler *Action : Actions) {
825       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
826         const auto &CatchTargets = CatchAction->getReturnTargets();
827         ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
828       }
829     }
830     IndirectBrInst *Branch =
831         IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
832     for (BasicBlock *Target : ReturnTargets)
833       Branch->addDestination(Target);
834   } // End for each landingpad
835
836   // If nothing got outlined, there is no more processing to be done.
837   if (!HandlersOutlined)
838     return false;
839
840   // Replace any nested landing pad stubs with the correct action handler.
841   // This must be done before we remove unreachable blocks because it
842   // cleans up references to outlined blocks that will be deleted.
843   for (auto &LPadPair : NestedLPtoOriginalLP)
844     completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
845   NestedLPtoOriginalLP.clear();
846
847   F.addFnAttr("wineh-parent", F.getName());
848
849   // Delete any blocks that were only used by handlers that were outlined above.
850   removeUnreachableBlocks(F);
851
852   BasicBlock *Entry = &F.getEntryBlock();
853   IRBuilder<> Builder(F.getParent()->getContext());
854   Builder.SetInsertPoint(Entry->getFirstInsertionPt());
855
856   Function *FrameEscapeFn =
857       Intrinsic::getDeclaration(M, Intrinsic::frameescape);
858   Function *RecoverFrameFn =
859       Intrinsic::getDeclaration(M, Intrinsic::framerecover);
860   SmallVector<Value *, 8> AllocasToEscape;
861
862   // Scan the entry block for an existing call to llvm.frameescape. We need to
863   // keep escaping those objects.
864   for (Instruction &I : F.front()) {
865     auto *II = dyn_cast<IntrinsicInst>(&I);
866     if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
867       auto Args = II->arg_operands();
868       AllocasToEscape.append(Args.begin(), Args.end());
869       II->eraseFromParent();
870       break;
871     }
872   }
873
874   // Finally, replace all of the temporary allocas for frame variables used in
875   // the outlined handlers with calls to llvm.framerecover.
876   for (auto &VarInfoEntry : FrameVarInfo) {
877     Value *ParentVal = VarInfoEntry.first;
878     TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
879     AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
880
881     // FIXME: We should try to sink unescaped allocas from the parent frame into
882     // the child frame. If the alloca is escaped, we have to use the lifetime
883     // markers to ensure that the alloca is only live within the child frame.
884
885     // Add this alloca to the list of things to escape.
886     AllocasToEscape.push_back(ParentAlloca);
887
888     // Next replace all outlined allocas that are mapped to it.
889     for (AllocaInst *TempAlloca : Allocas) {
890       if (TempAlloca == getCatchObjectSentinel())
891         continue; // Skip catch parameter sentinels.
892       Function *HandlerFn = TempAlloca->getParent()->getParent();
893       llvm::Value *FP = HandlerToParentFP[HandlerFn];
894       assert(FP);
895
896       // FIXME: Sink this framerecover into the blocks where it is used.
897       Builder.SetInsertPoint(TempAlloca);
898       Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
899       Value *RecoverArgs[] = {
900           Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
901           llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
902       Instruction *RecoveredAlloca =
903           Builder.CreateCall(RecoverFrameFn, RecoverArgs);
904
905       // Add a pointer bitcast if the alloca wasn't an i8.
906       if (RecoveredAlloca->getType() != TempAlloca->getType()) {
907         RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
908         RecoveredAlloca = cast<Instruction>(
909             Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
910       }
911       TempAlloca->replaceAllUsesWith(RecoveredAlloca);
912       TempAlloca->removeFromParent();
913       RecoveredAlloca->takeName(TempAlloca);
914       delete TempAlloca;
915     }
916   } // End for each FrameVarInfo entry.
917
918   // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
919   // block.
920   Builder.SetInsertPoint(&F.getEntryBlock().back());
921   Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
922
923   if (SEHExceptionCodeSlot) {
924     if (SEHExceptionCodeSlot->hasNUses(0))
925       SEHExceptionCodeSlot->eraseFromParent();
926     else if (isAllocaPromotable(SEHExceptionCodeSlot))
927       PromoteMemToReg(SEHExceptionCodeSlot, *DT);
928   }
929
930   // Clean up the handler action maps we created for this function
931   DeleteContainerSeconds(CatchHandlerMap);
932   CatchHandlerMap.clear();
933   DeleteContainerSeconds(CleanupHandlerMap);
934   CleanupHandlerMap.clear();
935   HandlerToParentFP.clear();
936   DT = nullptr;
937
938   return HandlersOutlined;
939 }
940
941 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
942   // If the return values of the landing pad instruction are extracted and
943   // stored to memory, we want to promote the store locations to reg values.
944   SmallVector<AllocaInst *, 2> EHAllocas;
945
946   // The landingpad instruction returns an aggregate value.  Typically, its
947   // value will be passed to a pair of extract value instructions and the
948   // results of those extracts are often passed to store instructions.
949   // In unoptimized code the stored value will often be loaded and then stored
950   // again.
951   for (auto *U : LPad->users()) {
952     ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
953     if (!Extract)
954       continue;
955
956     for (auto *EU : Extract->users()) {
957       if (auto *Store = dyn_cast<StoreInst>(EU)) {
958         auto *AV = cast<AllocaInst>(Store->getPointerOperand());
959         EHAllocas.push_back(AV);
960       }
961     }
962   }
963
964   // We can't do this without a dominator tree.
965   assert(DT);
966
967   if (!EHAllocas.empty()) {
968     PromoteMemToReg(EHAllocas, *DT);
969     EHAllocas.clear();
970   }
971
972   // After promotion, some extracts may be trivially dead. Remove them.
973   SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
974   for (auto *U : Users)
975     RecursivelyDeleteTriviallyDeadInstructions(U);
976 }
977
978 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
979                                             LandingPadInst *OutlinedLPad,
980                                             const LandingPadInst *OriginalLPad,
981                                             FrameVarInfoMap &FrameVarInfo) {
982   // Get the nested block and erase the unreachable instruction that was
983   // temporarily inserted as its terminator.
984   LLVMContext &Context = ParentFn->getContext();
985   BasicBlock *OutlinedBB = OutlinedLPad->getParent();
986   assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
987   OutlinedBB->getTerminator()->eraseFromParent();
988   // That should leave OutlinedLPad as the last instruction in its block.
989   assert(&OutlinedBB->back() == OutlinedLPad);
990
991   // The original landing pad will have already had its action intrinsic
992   // built by the outlining loop.  We need to clone that into the outlined
993   // location.  It may also be necessary to add references to the exception
994   // variables to the outlined handler in which this landing pad is nested
995   // and remap return instructions in the nested handlers that should return
996   // to an address in the outlined handler.
997   Function *OutlinedHandlerFn = OutlinedBB->getParent();
998   BasicBlock::const_iterator II = OriginalLPad;
999   ++II;
1000   // The instruction after the landing pad should now be a call to eh.actions.
1001   const Instruction *Recover = II;
1002   assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
1003   IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
1004
1005   // Remap the exception variables into the outlined function.
1006   SmallVector<BlockAddress *, 4> ActionTargets;
1007   SmallVector<ActionHandler *, 4> ActionList;
1008   parseEHActions(EHActions, ActionList);
1009   for (auto *Action : ActionList) {
1010     auto *Catch = dyn_cast<CatchHandler>(Action);
1011     if (!Catch)
1012       continue;
1013     // The dyn_cast to function here selects C++ catch handlers and skips
1014     // SEH catch handlers.
1015     auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1016     if (!Handler)
1017       continue;
1018     // Visit all the return instructions, looking for places that return
1019     // to a location within OutlinedHandlerFn.
1020     for (BasicBlock &NestedHandlerBB : *Handler) {
1021       auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1022       if (!Ret)
1023         continue;
1024
1025       // Handler functions must always return a block address.
1026       BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1027       // The original target will have been in the main parent function,
1028       // but if it is the address of a block that has been outlined, it
1029       // should be a block that was outlined into OutlinedHandlerFn.
1030       assert(BA->getFunction() == ParentFn);
1031
1032       // Ignore targets that aren't part of OutlinedHandlerFn.
1033       if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1034         continue;
1035
1036       // If the return value is the address ofF a block that we
1037       // previously outlined into the parent handler function, replace
1038       // the return instruction and add the mapped target to the list
1039       // of possible return addresses.
1040       BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1041       assert(MappedBB->getParent() == OutlinedHandlerFn);
1042       BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1043       Ret->eraseFromParent();
1044       ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1045       ActionTargets.push_back(NewBA);
1046     }
1047   }
1048   DeleteContainerPointers(ActionList);
1049   ActionList.clear();
1050   OutlinedBB->getInstList().push_back(EHActions);
1051
1052   // Insert an indirect branch into the outlined landing pad BB.
1053   IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
1054   // Add the previously collected action targets.
1055   for (auto *Target : ActionTargets)
1056     IBr->addDestination(Target->getBasicBlock());
1057 }
1058
1059 // This function examines a block to determine whether the block ends with a
1060 // conditional branch to a catch handler based on a selector comparison.
1061 // This function is used both by the WinEHPrepare::findSelectorComparison() and
1062 // WinEHCleanupDirector::handleTypeIdFor().
1063 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1064                                Constant *&Selector, BasicBlock *&NextBB) {
1065   ICmpInst::Predicate Pred;
1066   BasicBlock *TBB, *FBB;
1067   Value *LHS, *RHS;
1068
1069   if (!match(BB->getTerminator(),
1070              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1071     return false;
1072
1073   if (!match(LHS,
1074              m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1075       !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1076     return false;
1077
1078   if (Pred == CmpInst::ICMP_EQ) {
1079     CatchHandler = TBB;
1080     NextBB = FBB;
1081     return true;
1082   }
1083
1084   if (Pred == CmpInst::ICMP_NE) {
1085     CatchHandler = FBB;
1086     NextBB = TBB;
1087     return true;
1088   }
1089
1090   return false;
1091 }
1092
1093 static bool isCatchBlock(BasicBlock *BB) {
1094   for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1095        II != IE; ++II) {
1096     if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1097       return true;
1098   }
1099   return false;
1100 }
1101
1102 static BasicBlock *createStubLandingPad(Function *Handler,
1103                                         Value *PersonalityFn) {
1104   // FIXME: Finish this!
1105   LLVMContext &Context = Handler->getContext();
1106   BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1107   Handler->getBasicBlockList().push_back(StubBB);
1108   IRBuilder<> Builder(StubBB);
1109   LandingPadInst *LPad = Builder.CreateLandingPad(
1110       llvm::StructType::get(Type::getInt8PtrTy(Context),
1111                             Type::getInt32Ty(Context), nullptr),
1112       PersonalityFn, 0);
1113   // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1114   Function *ActionIntrin =
1115       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
1116   Builder.CreateCall(ActionIntrin, "recover");
1117   LPad->setCleanup(true);
1118   Builder.CreateUnreachable();
1119   return StubBB;
1120 }
1121
1122 // Cycles through the blocks in an outlined handler function looking for an
1123 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1124 // landing pad if none is found.  The code that generates the .xdata tables for
1125 // the handler needs at least one landing pad to identify the parent function's
1126 // personality.
1127 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
1128                                                   Value *PersonalityFn) {
1129   ReturnInst *Ret = nullptr;
1130   UnreachableInst *Unreached = nullptr;
1131   for (BasicBlock &BB : *Handler) {
1132     TerminatorInst *Terminator = BB.getTerminator();
1133     // If we find an invoke, there is nothing to be done.
1134     auto *II = dyn_cast<InvokeInst>(Terminator);
1135     if (II)
1136       return;
1137     // If we've already recorded a return instruction, keep looking for invokes.
1138     if (!Ret)
1139       Ret = dyn_cast<ReturnInst>(Terminator);
1140     // If we haven't recorded an unreachable instruction, try this terminator.
1141     if (!Unreached)
1142       Unreached = dyn_cast<UnreachableInst>(Terminator);
1143   }
1144
1145   // If we got this far, the handler contains no invokes.  We should have seen
1146   // at least one return or unreachable instruction.  We'll insert an invoke of
1147   // llvm.donothing ahead of that instruction.
1148   assert(Ret || Unreached);
1149   TerminatorInst *Term;
1150   if (Ret)
1151     Term = Ret;
1152   else
1153     Term = Unreached;
1154   BasicBlock *OldRetBB = Term->getParent();
1155   BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
1156   // SplitBlock adds an unconditional branch instruction at the end of the
1157   // parent block.  We want to replace that with an invoke call, so we can
1158   // erase it now.
1159   OldRetBB->getTerminator()->eraseFromParent();
1160   BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
1161   Function *F =
1162       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1163   InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1164 }
1165
1166 // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1167 // usually doesn't build LLVM IR, so that's probably the wrong place.
1168 Function *WinEHPrepare::createHandlerFunc(Type *RetTy, const Twine &Name,
1169                                           Module *M, Value *&ParentFP) {
1170   // x64 uses a two-argument prototype where the parent FP is the second
1171   // argument. x86 uses no arguments, just the incoming EBP value.
1172   LLVMContext &Context = M->getContext();
1173   FunctionType *FnType;
1174   if (TheTriple.getArch() == Triple::x86_64) {
1175     Type *Int8PtrType = Type::getInt8PtrTy(Context);
1176     Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1177     FnType = FunctionType::get(RetTy, ArgTys, false);
1178   } else {
1179     FnType = FunctionType::get(RetTy, None, false);
1180   }
1181
1182   Function *Handler =
1183       Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1184   BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1185   Handler->getBasicBlockList().push_front(Entry);
1186   if (TheTriple.getArch() == Triple::x86_64) {
1187     ParentFP = &(Handler->getArgumentList().back());
1188   } else {
1189     assert(M);
1190     Function *FrameAddressFn =
1191         Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
1192     Value *Args[1] = {ConstantInt::get(Type::getInt32Ty(Context), 1)};
1193     ParentFP = CallInst::Create(FrameAddressFn, Args, "parent_fp",
1194                                 &Handler->getEntryBlock());
1195   }
1196   return Handler;
1197 }
1198
1199 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1200                                   LandingPadInst *LPad, BasicBlock *StartBB,
1201                                   FrameVarInfoMap &VarInfo) {
1202   Module *M = SrcFn->getParent();
1203   LLVMContext &Context = M->getContext();
1204   Type *Int8PtrType = Type::getInt8PtrTy(Context);
1205
1206   // Create a new function to receive the handler contents.
1207   Value *ParentFP;
1208   Function *Handler;
1209   if (Action->getType() == Catch) {
1210     Handler = createHandlerFunc(Int8PtrType, SrcFn->getName() + ".catch", M,
1211                                 ParentFP);
1212   } else {
1213     Handler = createHandlerFunc(Type::getVoidTy(Context),
1214                                 SrcFn->getName() + ".cleanup", M, ParentFP);
1215   }
1216   HandlerToParentFP[Handler] = ParentFP;
1217   Handler->addFnAttr("wineh-parent", SrcFn->getName());
1218   BasicBlock *Entry = &Handler->getEntryBlock();
1219
1220   // Generate a standard prolog to setup the frame recovery structure.
1221   IRBuilder<> Builder(Context);
1222   Builder.SetInsertPoint(Entry);
1223   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1224
1225   std::unique_ptr<WinEHCloningDirectorBase> Director;
1226
1227   ValueToValueMapTy VMap;
1228
1229   LandingPadMap &LPadMap = LPadMaps[LPad];
1230   if (!LPadMap.isInitialized())
1231     LPadMap.mapLandingPad(LPad);
1232   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1233     Constant *Sel = CatchAction->getSelector();
1234     Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel,
1235                                           VarInfo, LPadMap,
1236                                           NestedLPtoOriginalLP));
1237     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1238                           ConstantInt::get(Type::getInt32Ty(Context), 1));
1239   } else {
1240     Director.reset(
1241         new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
1242     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1243                           UndefValue::get(Type::getInt32Ty(Context)));
1244   }
1245
1246   SmallVector<ReturnInst *, 8> Returns;
1247   ClonedCodeInfo OutlinedFunctionInfo;
1248
1249   // If the start block contains PHI nodes, we need to map them.
1250   BasicBlock::iterator II = StartBB->begin();
1251   while (auto *PN = dyn_cast<PHINode>(II)) {
1252     bool Mapped = false;
1253     // Look for PHI values that we have already mapped (such as the selector).
1254     for (Value *Val : PN->incoming_values()) {
1255       if (VMap.count(Val)) {
1256         VMap[PN] = VMap[Val];
1257         Mapped = true;
1258       }
1259     }
1260     // If we didn't find a match for this value, map it as an undef.
1261     if (!Mapped) {
1262       VMap[PN] = UndefValue::get(PN->getType());
1263     }
1264     ++II;
1265   }
1266
1267   // The landing pad value may be used by PHI nodes.  It will ultimately be
1268   // eliminated, but we need it in the map for intermediate handling.
1269   VMap[LPad] = UndefValue::get(LPad->getType());
1270
1271   // Skip over PHIs and, if applicable, landingpad instructions.
1272   II = StartBB->getFirstInsertionPt();
1273
1274   CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1275                             /*ModuleLevelChanges=*/false, Returns, "",
1276                             &OutlinedFunctionInfo, Director.get());
1277
1278   // Move all the instructions in the cloned "entry" block into our entry block.
1279   // Depending on how the parent function was laid out, the block that will
1280   // correspond to the outlined entry block may not be the first block in the
1281   // list.  We can recognize it, however, as the cloned block which has no
1282   // predecessors.  Any other block wouldn't have been cloned if it didn't
1283   // have a predecessor which was also cloned.
1284   Function::iterator ClonedIt = std::next(Function::iterator(Entry));
1285   while (!pred_empty(ClonedIt))
1286     ++ClonedIt;
1287   BasicBlock *ClonedEntryBB = ClonedIt;
1288   assert(ClonedEntryBB);
1289   Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1290   ClonedEntryBB->eraseFromParent();
1291
1292   // Make sure we can identify the handler's personality later.
1293   addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
1294
1295   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1296     WinEHCatchDirector *CatchDirector =
1297         reinterpret_cast<WinEHCatchDirector *>(Director.get());
1298     CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1299     CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1300
1301     // Look for blocks that are not part of the landing pad that we just
1302     // outlined but terminate with a call to llvm.eh.endcatch and a
1303     // branch to a block that is in the handler we just outlined.
1304     // These blocks will be part of a nested landing pad that intends to
1305     // return to an address in this handler.  This case is best handled
1306     // after both landing pads have been outlined, so for now we'll just
1307     // save the association of the blocks in LPadTargetBlocks.  The
1308     // return instructions which are created from these branches will be
1309     // replaced after all landing pads have been outlined.
1310     for (const auto MapEntry : VMap) {
1311       // VMap maps all values and blocks that were just cloned, but dead
1312       // blocks which were pruned will map to nullptr.
1313       if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1314         continue;
1315       const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1316       for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1317         auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1318         if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1319           continue;
1320         BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1321         --II;
1322         if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1323           // This would indicate that a nested landing pad wants to return
1324           // to a block that is outlined into two different handlers.
1325           assert(!LPadTargetBlocks.count(MappedBB));
1326           LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1327         }
1328       }
1329     }
1330   } // End if (CatchAction)
1331
1332   Action->setHandlerBlockOrFunc(Handler);
1333
1334   return true;
1335 }
1336
1337 /// This BB must end in a selector dispatch. All we need to do is pass the
1338 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1339 /// target.
1340 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1341                                           BasicBlock *StartBB) {
1342   BasicBlock *HandlerBB;
1343   BasicBlock *NextBB;
1344   Constant *Selector;
1345   bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1346   if (Res) {
1347     // If this was EH dispatch, this must be a conditional branch to the handler
1348     // block.
1349     // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1350     // leading to crashes if some optimization hoists stuff here.
1351     assert(CatchAction->getSelector() && HandlerBB &&
1352            "expected catch EH dispatch");
1353   } else {
1354     // This must be a catch-all. Split the block after the landingpad.
1355     assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1356     HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
1357   }
1358   IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1359   Function *EHCodeFn = Intrinsic::getDeclaration(
1360       StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
1361   Value *Code = Builder.CreateCall(EHCodeFn, "sehcode");
1362   Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1363   Builder.CreateStore(Code, SEHExceptionCodeSlot);
1364   CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1365   TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1366   CatchAction->setReturnTargets(Targets);
1367 }
1368
1369 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1370   // Each instance of this class should only ever be used to map a single
1371   // landing pad.
1372   assert(OriginLPad == nullptr || OriginLPad == LPad);
1373
1374   // If the landing pad has already been mapped, there's nothing more to do.
1375   if (OriginLPad == LPad)
1376     return;
1377
1378   OriginLPad = LPad;
1379
1380   // The landingpad instruction returns an aggregate value.  Typically, its
1381   // value will be passed to a pair of extract value instructions and the
1382   // results of those extracts will have been promoted to reg values before
1383   // this routine is called.
1384   for (auto *U : LPad->users()) {
1385     const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1386     if (!Extract)
1387       continue;
1388     assert(Extract->getNumIndices() == 1 &&
1389            "Unexpected operation: extracting both landing pad values");
1390     unsigned int Idx = *(Extract->idx_begin());
1391     assert((Idx == 0 || Idx == 1) &&
1392            "Unexpected operation: extracting an unknown landing pad element");
1393     if (Idx == 0) {
1394       ExtractedEHPtrs.push_back(Extract);
1395     } else if (Idx == 1) {
1396       ExtractedSelectors.push_back(Extract);
1397     }
1398   }
1399 }
1400
1401 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1402   return BB->getLandingPadInst() == OriginLPad;
1403 }
1404
1405 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1406   if (Inst == OriginLPad)
1407     return true;
1408   for (auto *Extract : ExtractedEHPtrs) {
1409     if (Inst == Extract)
1410       return true;
1411   }
1412   for (auto *Extract : ExtractedSelectors) {
1413     if (Inst == Extract)
1414       return true;
1415   }
1416   return false;
1417 }
1418
1419 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1420                                   Value *SelectorValue) const {
1421   // Remap all landing pad extract instructions to the specified values.
1422   for (auto *Extract : ExtractedEHPtrs)
1423     VMap[Extract] = EHPtrValue;
1424   for (auto *Extract : ExtractedSelectors)
1425     VMap[Extract] = SelectorValue;
1426 }
1427
1428 static bool isFrameAddressCall(const Value *V) {
1429   return match(const_cast<Value *>(V),
1430                m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1431 }
1432
1433 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1434     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1435   // If this is one of the boilerplate landing pad instructions, skip it.
1436   // The instruction will have already been remapped in VMap.
1437   if (LPadMap.isLandingPadSpecificInst(Inst))
1438     return CloningDirector::SkipInstruction;
1439
1440   // Nested landing pads will be cloned as stubs, with just the
1441   // landingpad instruction and an unreachable instruction. When
1442   // all landingpads have been outlined, we'll replace this with the
1443   // llvm.eh.actions call and indirect branch created when the
1444   // landing pad was outlined.
1445   if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1446     return handleLandingPad(VMap, LPad, NewBB);
1447   }
1448
1449   if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1450     return handleInvoke(VMap, Invoke, NewBB);
1451
1452   if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1453     return handleResume(VMap, Resume, NewBB);
1454
1455   if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1456     return handleCompare(VMap, Cmp, NewBB);
1457
1458   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1459     return handleBeginCatch(VMap, Inst, NewBB);
1460   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1461     return handleEndCatch(VMap, Inst, NewBB);
1462   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1463     return handleTypeIdFor(VMap, Inst, NewBB);
1464
1465   // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1466   // which is the FP of the parent.
1467   if (isFrameAddressCall(Inst)) {
1468     VMap[Inst] = ParentFP;
1469     return CloningDirector::SkipInstruction;
1470   }
1471
1472   // Continue with the default cloning behavior.
1473   return CloningDirector::CloneInstruction;
1474 }
1475
1476 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1477     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1478   Instruction *NewInst = LPad->clone();
1479   if (LPad->hasName())
1480     NewInst->setName(LPad->getName());
1481   // Save this correlation for later processing.
1482   NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1483   VMap[LPad] = NewInst;
1484   BasicBlock::InstListType &InstList = NewBB->getInstList();
1485   InstList.push_back(NewInst);
1486   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1487   return CloningDirector::StopCloningBB;
1488 }
1489
1490 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1491     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1492   // The argument to the call is some form of the first element of the
1493   // landingpad aggregate value, but that doesn't matter.  It isn't used
1494   // here.
1495   // The second argument is an outparameter where the exception object will be
1496   // stored. Typically the exception object is a scalar, but it can be an
1497   // aggregate when catching by value.
1498   // FIXME: Leave something behind to indicate where the exception object lives
1499   // for this handler. Should it be part of llvm.eh.actions?
1500   assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1501                                           "llvm.eh.begincatch found while "
1502                                           "outlining catch handler.");
1503   ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1504   if (isa<ConstantPointerNull>(ExceptionObjectVar))
1505     return CloningDirector::SkipInstruction;
1506   assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1507          "catch parameter is not static alloca");
1508   Materializer.escapeCatchObject(ExceptionObjectVar);
1509   return CloningDirector::SkipInstruction;
1510 }
1511
1512 CloningDirector::CloningAction
1513 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1514                                    const Instruction *Inst, BasicBlock *NewBB) {
1515   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1516   // It might be interesting to track whether or not we are inside a catch
1517   // function, but that might make the algorithm more brittle than it needs
1518   // to be.
1519
1520   // The end catch call can occur in one of two places: either in a
1521   // landingpad block that is part of the catch handlers exception mechanism,
1522   // or at the end of the catch block.  However, a catch-all handler may call
1523   // end catch from the original landing pad.  If the call occurs in a nested
1524   // landing pad block, we must skip it and continue so that the landing pad
1525   // gets cloned.
1526   auto *ParentBB = IntrinCall->getParent();
1527   if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1528     return CloningDirector::SkipInstruction;
1529
1530   // If an end catch occurs anywhere else we want to terminate the handler
1531   // with a return to the code that follows the endcatch call.  If the
1532   // next instruction is not an unconditional branch, we need to split the
1533   // block to provide a clear target for the return instruction.
1534   BasicBlock *ContinueBB;
1535   auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1536   const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1537   if (!Branch || !Branch->isUnconditional()) {
1538     // We're interrupting the cloning process at this location, so the
1539     // const_cast we're doing here will not cause a problem.
1540     ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1541                             const_cast<Instruction *>(cast<Instruction>(Next)));
1542   } else {
1543     ContinueBB = Branch->getSuccessor(0);
1544   }
1545
1546   ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1547   ReturnTargets.push_back(ContinueBB);
1548
1549   // We just added a terminator to the cloned block.
1550   // Tell the caller to stop processing the current basic block so that
1551   // the branch instruction will be skipped.
1552   return CloningDirector::StopCloningBB;
1553 }
1554
1555 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1556     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1557   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1558   Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1559   // This causes a replacement that will collapse the landing pad CFG based
1560   // on the filter function we intend to match.
1561   if (Selector == CurrentSelector)
1562     VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1563   else
1564     VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1565   // Tell the caller not to clone this instruction.
1566   return CloningDirector::SkipInstruction;
1567 }
1568
1569 CloningDirector::CloningAction
1570 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1571                                  const InvokeInst *Invoke, BasicBlock *NewBB) {
1572   return CloningDirector::CloneInstruction;
1573 }
1574
1575 CloningDirector::CloningAction
1576 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1577                                  const ResumeInst *Resume, BasicBlock *NewBB) {
1578   // Resume instructions shouldn't be reachable from catch handlers.
1579   // We still need to handle it, but it will be pruned.
1580   BasicBlock::InstListType &InstList = NewBB->getInstList();
1581   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1582   return CloningDirector::StopCloningBB;
1583 }
1584
1585 CloningDirector::CloningAction
1586 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1587                                   const CmpInst *Compare, BasicBlock *NewBB) {
1588   const IntrinsicInst *IntrinCall = nullptr;
1589   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1590     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1591   } else if (match(Compare->getOperand(1),
1592                    m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1593     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1594   }
1595   if (IntrinCall) {
1596     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1597     // This causes a replacement that will collapse the landing pad CFG based
1598     // on the filter function we intend to match.
1599     if (Selector == CurrentSelector->stripPointerCasts()) {
1600       VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1601     } else {
1602       VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1603     }
1604     return CloningDirector::SkipInstruction;
1605   }
1606   return CloningDirector::CloneInstruction;
1607 }
1608
1609 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1610     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1611   // The MS runtime will terminate the process if an exception occurs in a
1612   // cleanup handler, so we shouldn't encounter landing pads in the actual
1613   // cleanup code, but they may appear in catch blocks.  Depending on where
1614   // we started cloning we may see one, but it will get dropped during dead
1615   // block pruning.
1616   Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1617   VMap[LPad] = NewInst;
1618   BasicBlock::InstListType &InstList = NewBB->getInstList();
1619   InstList.push_back(NewInst);
1620   return CloningDirector::StopCloningBB;
1621 }
1622
1623 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1624     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1625   // Cleanup code may flow into catch blocks or the catch block may be part
1626   // of a branch that will be optimized away.  We'll insert a return
1627   // instruction now, but it may be pruned before the cloning process is
1628   // complete.
1629   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1630   return CloningDirector::StopCloningBB;
1631 }
1632
1633 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1634     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1635   // Cleanup handlers nested within catch handlers may begin with a call to
1636   // eh.endcatch.  We can just ignore that instruction.
1637   return CloningDirector::SkipInstruction;
1638 }
1639
1640 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1641     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1642   // If we encounter a selector comparison while cloning a cleanup handler,
1643   // we want to stop cloning immediately.  Anything after the dispatch
1644   // will be outlined into a different handler.
1645   BasicBlock *CatchHandler;
1646   Constant *Selector;
1647   BasicBlock *NextBB;
1648   if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1649                          CatchHandler, Selector, NextBB)) {
1650     ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1651     return CloningDirector::StopCloningBB;
1652   }
1653   // If eg.typeid.for is called for any other reason, it can be ignored.
1654   VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1655   return CloningDirector::SkipInstruction;
1656 }
1657
1658 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1659     ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1660   // All invokes in cleanup handlers can be replaced with calls.
1661   SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1662   // Insert a normal call instruction...
1663   CallInst *NewCall =
1664       CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1665                        Invoke->getName(), NewBB);
1666   NewCall->setCallingConv(Invoke->getCallingConv());
1667   NewCall->setAttributes(Invoke->getAttributes());
1668   NewCall->setDebugLoc(Invoke->getDebugLoc());
1669   VMap[Invoke] = NewCall;
1670
1671   // Remap the operands.
1672   llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1673
1674   // Insert an unconditional branch to the normal destination.
1675   BranchInst::Create(Invoke->getNormalDest(), NewBB);
1676
1677   // The unwind destination won't be cloned into the new function, so
1678   // we don't need to clean up its phi nodes.
1679
1680   // We just added a terminator to the cloned block.
1681   // Tell the caller to stop processing the current basic block.
1682   return CloningDirector::CloneSuccessors;
1683 }
1684
1685 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1686     ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1687   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1688
1689   // We just added a terminator to the cloned block.
1690   // Tell the caller to stop processing the current basic block so that
1691   // the branch instruction will be skipped.
1692   return CloningDirector::StopCloningBB;
1693 }
1694
1695 CloningDirector::CloningAction
1696 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1697                                     const CmpInst *Compare, BasicBlock *NewBB) {
1698   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1699       match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1700     VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1701     return CloningDirector::SkipInstruction;
1702   }
1703   return CloningDirector::CloneInstruction;
1704 }
1705
1706 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1707     Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
1708     : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1709   BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1710
1711   // New allocas should be inserted in the entry block, but after the parent FP
1712   // is established if it is an instruction.
1713   Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
1714   if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
1715     InsertPoint = FPInst->getNextNode();
1716   Builder.SetInsertPoint(EntryBB, InsertPoint);
1717 }
1718
1719 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1720   // If we're asked to materialize a static alloca, we temporarily create an
1721   // alloca in the outlined function and add this to the FrameVarInfo map.  When
1722   // all the outlining is complete, we'll replace these temporary allocas with
1723   // calls to llvm.framerecover.
1724   if (auto *AV = dyn_cast<AllocaInst>(V)) {
1725     assert(AV->isStaticAlloca() &&
1726            "cannot materialize un-demoted dynamic alloca");
1727     AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1728     Builder.Insert(NewAlloca, AV->getName());
1729     FrameVarInfo[AV].push_back(NewAlloca);
1730     return NewAlloca;
1731   }
1732
1733   if (isa<Instruction>(V) || isa<Argument>(V)) {
1734     errs() << "Failed to demote instruction used in exception handler:\n";
1735     errs() << "  " << *V << '\n';
1736     report_fatal_error("WinEHPrepare failed to demote instruction");
1737   }
1738
1739   // Don't materialize other values.
1740   return nullptr;
1741 }
1742
1743 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1744   // Catch parameter objects have to live in the parent frame. When we see a use
1745   // of a catch parameter, add a sentinel to the multimap to indicate that it's
1746   // used from another handler. This will prevent us from trying to sink the
1747   // alloca into the handler and ensure that the catch parameter is present in
1748   // the call to llvm.frameescape.
1749   FrameVarInfo[V].push_back(getCatchObjectSentinel());
1750 }
1751
1752 // This function maps the catch and cleanup handlers that are reachable from the
1753 // specified landing pad. The landing pad sequence will have this basic shape:
1754 //
1755 //  <cleanup handler>
1756 //  <selector comparison>
1757 //  <catch handler>
1758 //  <cleanup handler>
1759 //  <selector comparison>
1760 //  <catch handler>
1761 //  <cleanup handler>
1762 //  ...
1763 //
1764 // Any of the cleanup slots may be absent.  The cleanup slots may be occupied by
1765 // any arbitrary control flow, but all paths through the cleanup code must
1766 // eventually reach the next selector comparison and no path can skip to a
1767 // different selector comparisons, though some paths may terminate abnormally.
1768 // Therefore, we will use a depth first search from the start of any given
1769 // cleanup block and stop searching when we find the next selector comparison.
1770 //
1771 // If the landingpad instruction does not have a catch clause, we will assume
1772 // that any instructions other than selector comparisons and catch handlers can
1773 // be ignored.  In practice, these will only be the boilerplate instructions.
1774 //
1775 // The catch handlers may also have any control structure, but we are only
1776 // interested in the start of the catch handlers, so we don't need to actually
1777 // follow the flow of the catch handlers.  The start of the catch handlers can
1778 // be located from the compare instructions, but they can be skipped in the
1779 // flow by following the contrary branch.
1780 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1781                                        LandingPadActions &Actions) {
1782   unsigned int NumClauses = LPad->getNumClauses();
1783   unsigned int HandlersFound = 0;
1784   BasicBlock *BB = LPad->getParent();
1785
1786   DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1787
1788   if (NumClauses == 0) {
1789     findCleanupHandlers(Actions, BB, nullptr);
1790     return;
1791   }
1792
1793   VisitedBlockSet VisitedBlocks;
1794
1795   while (HandlersFound != NumClauses) {
1796     BasicBlock *NextBB = nullptr;
1797
1798     // Skip over filter clauses.
1799     if (LPad->isFilter(HandlersFound)) {
1800       ++HandlersFound;
1801       continue;
1802     }
1803
1804     // See if the clause we're looking for is a catch-all.
1805     // If so, the catch begins immediately.
1806     Constant *ExpectedSelector =
1807         LPad->getClause(HandlersFound)->stripPointerCasts();
1808     if (isa<ConstantPointerNull>(ExpectedSelector)) {
1809       // The catch all must occur last.
1810       assert(HandlersFound == NumClauses - 1);
1811
1812       // There can be additional selector dispatches in the call chain that we
1813       // need to ignore.
1814       BasicBlock *CatchBlock = nullptr;
1815       Constant *Selector;
1816       while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1817         DEBUG(dbgs() << "  Found extra catch dispatch in block "
1818                      << CatchBlock->getName() << "\n");
1819         BB = NextBB;
1820       }
1821
1822       // Add the catch handler to the action list.
1823       CatchHandler *Action = nullptr;
1824       if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1825         // If the CatchHandlerMap already has an entry for this BB, re-use it.
1826         Action = CatchHandlerMap[BB];
1827         assert(Action->getSelector() == ExpectedSelector);
1828       } else {
1829         // We don't expect a selector dispatch, but there may be a call to
1830         // llvm.eh.begincatch, which separates catch handling code from
1831         // cleanup code in the same control flow.  This call looks for the
1832         // begincatch intrinsic.
1833         Action = findCatchHandler(BB, NextBB, VisitedBlocks);
1834         if (Action) {
1835           // For C++ EH, check if there is any interesting cleanup code before
1836           // we begin the catch. This is important because cleanups cannot
1837           // rethrow exceptions but code called from catches can. For SEH, it
1838           // isn't important if some finally code before a catch-all is executed
1839           // out of line or after recovering from the exception.
1840           if (Personality == EHPersonality::MSVC_CXX)
1841             findCleanupHandlers(Actions, BB, BB);
1842         } else {
1843           // If an action was not found, it means that the control flows
1844           // directly into the catch-all handler and there is no cleanup code.
1845           // That's an expected situation and we must create a catch action.
1846           // Since this is a catch-all handler, the selector won't actually
1847           // appear in the code anywhere.  ExpectedSelector here is the constant
1848           // null ptr that we got from the landing pad instruction.
1849           Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1850           CatchHandlerMap[BB] = Action;
1851         }
1852       }
1853       Actions.insertCatchHandler(Action);
1854       DEBUG(dbgs() << "  Catch all handler at block " << BB->getName() << "\n");
1855       ++HandlersFound;
1856
1857       // Once we reach a catch-all, don't expect to hit a resume instruction.
1858       BB = nullptr;
1859       break;
1860     }
1861
1862     CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1863     assert(CatchAction);
1864
1865     // See if there is any interesting code executed before the dispatch.
1866     findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
1867
1868     // When the source program contains multiple nested try blocks the catch
1869     // handlers can get strung together in such a way that we can encounter
1870     // a dispatch for a selector that we've already had a handler for.
1871     if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1872       ++HandlersFound;
1873
1874       // Add the catch handler to the action list.
1875       DEBUG(dbgs() << "  Found catch dispatch in block "
1876                    << CatchAction->getStartBlock()->getName() << "\n");
1877       Actions.insertCatchHandler(CatchAction);
1878     } else {
1879       // Under some circumstances optimized IR will flow unconditionally into a
1880       // handler block without checking the selector.  This can only happen if
1881       // the landing pad has a catch-all handler and the handler for the
1882       // preceeding catch clause is identical to the catch-call handler
1883       // (typically an empty catch).  In this case, the handler must be shared
1884       // by all remaining clauses.
1885       if (isa<ConstantPointerNull>(
1886               CatchAction->getSelector()->stripPointerCasts())) {
1887         DEBUG(dbgs() << "  Applying early catch-all handler in block "
1888                      << CatchAction->getStartBlock()->getName()
1889                      << "  to all remaining clauses.\n");
1890         Actions.insertCatchHandler(CatchAction);
1891         return;
1892       }
1893
1894       DEBUG(dbgs() << "  Found extra catch dispatch in block "
1895                    << CatchAction->getStartBlock()->getName() << "\n");
1896     }
1897
1898     // Move on to the block after the catch handler.
1899     BB = NextBB;
1900   }
1901
1902   // If we didn't wind up in a catch-all, see if there is any interesting code
1903   // executed before the resume.
1904   findCleanupHandlers(Actions, BB, BB);
1905
1906   // It's possible that some optimization moved code into a landingpad that
1907   // wasn't
1908   // previously being used for cleanup.  If that happens, we need to execute
1909   // that
1910   // extra code from a cleanup handler.
1911   if (Actions.includesCleanup() && !LPad->isCleanup())
1912     LPad->setCleanup(true);
1913 }
1914
1915 // This function searches starting with the input block for the next
1916 // block that terminates with a branch whose condition is based on a selector
1917 // comparison.  This may be the input block.  See the mapLandingPadBlocks
1918 // comments for a discussion of control flow assumptions.
1919 //
1920 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1921                                              BasicBlock *&NextBB,
1922                                              VisitedBlockSet &VisitedBlocks) {
1923   // See if we've already found a catch handler use it.
1924   // Call count() first to avoid creating a null entry for blocks
1925   // we haven't seen before.
1926   if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1927     CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1928     NextBB = Action->getNextBB();
1929     return Action;
1930   }
1931
1932   // VisitedBlocks applies only to the current search.  We still
1933   // need to consider blocks that we've visited while mapping other
1934   // landing pads.
1935   VisitedBlocks.insert(BB);
1936
1937   BasicBlock *CatchBlock = nullptr;
1938   Constant *Selector = nullptr;
1939
1940   // If this is the first time we've visited this block from any landing pad
1941   // look to see if it is a selector dispatch block.
1942   if (!CatchHandlerMap.count(BB)) {
1943     if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1944       CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1945       CatchHandlerMap[BB] = Action;
1946       return Action;
1947     }
1948     // If we encounter a block containing an llvm.eh.begincatch before we
1949     // find a selector dispatch block, the handler is assumed to be
1950     // reached unconditionally.  This happens for catch-all blocks, but
1951     // it can also happen for other catch handlers that have been combined
1952     // with the catch-all handler during optimization.
1953     if (isCatchBlock(BB)) {
1954       PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
1955       Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
1956       CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
1957       CatchHandlerMap[BB] = Action;
1958       return Action;
1959     }
1960   }
1961
1962   // Visit each successor, looking for the dispatch.
1963   // FIXME: We expect to find the dispatch quickly, so this will probably
1964   //        work better as a breadth first search.
1965   for (BasicBlock *Succ : successors(BB)) {
1966     if (VisitedBlocks.count(Succ))
1967       continue;
1968
1969     CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1970     if (Action)
1971       return Action;
1972   }
1973   return nullptr;
1974 }
1975
1976 // These are helper functions to combine repeated code from findCleanupHandlers.
1977 static void createCleanupHandler(LandingPadActions &Actions,
1978                                  CleanupHandlerMapTy &CleanupHandlerMap,
1979                                  BasicBlock *BB) {
1980   CleanupHandler *Action = new CleanupHandler(BB);
1981   CleanupHandlerMap[BB] = Action;
1982   Actions.insertCleanupHandler(Action);
1983   DEBUG(dbgs() << "  Found cleanup code in block "
1984                << Action->getStartBlock()->getName() << "\n");
1985 }
1986
1987 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1988                                          Instruction *MaybeCall) {
1989   // Look for finally blocks that Clang has already outlined for us.
1990   //   %fp = call i8* @llvm.frameaddress(i32 0)
1991   //   call void @"fin$parent"(iN 1, i8* %fp)
1992   if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1993     MaybeCall = MaybeCall->getNextNode();
1994   CallSite FinallyCall(MaybeCall);
1995   if (!FinallyCall || FinallyCall.arg_size() != 2)
1996     return CallSite();
1997   if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
1998     return CallSite();
1999   if (!isFrameAddressCall(FinallyCall.getArgument(1)))
2000     return CallSite();
2001   return FinallyCall;
2002 }
2003
2004 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2005   // Skip single ubr blocks.
2006   while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2007     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2008     if (Br && Br->isUnconditional())
2009       BB = Br->getSuccessor(0);
2010     else
2011       return BB;
2012   }
2013   return BB;
2014 }
2015
2016 // This function searches starting with the input block for the next block that
2017 // contains code that is not part of a catch handler and would not be eliminated
2018 // during handler outlining.
2019 //
2020 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2021                                        BasicBlock *StartBB, BasicBlock *EndBB) {
2022   // Here we will skip over the following:
2023   //
2024   // landing pad prolog:
2025   //
2026   // Unconditional branches
2027   //
2028   // Selector dispatch
2029   //
2030   // Resume pattern
2031   //
2032   // Anything else marks the start of an interesting block
2033
2034   BasicBlock *BB = StartBB;
2035   // Anything other than an unconditional branch will kick us out of this loop
2036   // one way or another.
2037   while (BB) {
2038     BB = followSingleUnconditionalBranches(BB);
2039     // If we've already scanned this block, don't scan it again.  If it is
2040     // a cleanup block, there will be an action in the CleanupHandlerMap.
2041     // If we've scanned it and it is not a cleanup block, there will be a
2042     // nullptr in the CleanupHandlerMap.  If we have not scanned it, there will
2043     // be no entry in the CleanupHandlerMap.  We must call count() first to
2044     // avoid creating a null entry for blocks we haven't scanned.
2045     if (CleanupHandlerMap.count(BB)) {
2046       if (auto *Action = CleanupHandlerMap[BB]) {
2047         Actions.insertCleanupHandler(Action);
2048         DEBUG(dbgs() << "  Found cleanup code in block "
2049                      << Action->getStartBlock()->getName() << "\n");
2050         // FIXME: This cleanup might chain into another, and we need to discover
2051         // that.
2052         return;
2053       } else {
2054         // Here we handle the case where the cleanup handler map contains a
2055         // value for this block but the value is a nullptr.  This means that
2056         // we have previously analyzed the block and determined that it did
2057         // not contain any cleanup code.  Based on the earlier analysis, we
2058         // know the the block must end in either an unconditional branch, a
2059         // resume or a conditional branch that is predicated on a comparison
2060         // with a selector.  Either the resume or the selector dispatch
2061         // would terminate the search for cleanup code, so the unconditional
2062         // branch is the only case for which we might need to continue
2063         // searching.
2064         BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2065         if (SuccBB == BB || SuccBB == EndBB)
2066           return;
2067         BB = SuccBB;
2068         continue;
2069       }
2070     }
2071
2072     // Create an entry in the cleanup handler map for this block.  Initially
2073     // we create an entry that says this isn't a cleanup block.  If we find
2074     // cleanup code, the caller will replace this entry.
2075     CleanupHandlerMap[BB] = nullptr;
2076
2077     TerminatorInst *Terminator = BB->getTerminator();
2078
2079     // Landing pad blocks have extra instructions we need to accept.
2080     LandingPadMap *LPadMap = nullptr;
2081     if (BB->isLandingPad()) {
2082       LandingPadInst *LPad = BB->getLandingPadInst();
2083       LPadMap = &LPadMaps[LPad];
2084       if (!LPadMap->isInitialized())
2085         LPadMap->mapLandingPad(LPad);
2086     }
2087
2088     // Look for the bare resume pattern:
2089     //   %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2090     //   %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
2091     //   resume { i8*, i32 } %lpad.val2
2092     if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2093       InsertValueInst *Insert1 = nullptr;
2094       InsertValueInst *Insert2 = nullptr;
2095       Value *ResumeVal = Resume->getOperand(0);
2096       // If the resume value isn't a phi or landingpad value, it should be a
2097       // series of insertions. Identify them so we can avoid them when scanning
2098       // for cleanups.
2099       if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
2100         Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
2101         if (!Insert2)
2102           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2103         Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2104         if (!Insert1)
2105           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2106       }
2107       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2108            II != IE; ++II) {
2109         Instruction *Inst = II;
2110         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2111           continue;
2112         if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2113           continue;
2114         if (!Inst->hasOneUse() ||
2115             (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
2116           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2117         }
2118       }
2119       return;
2120     }
2121
2122     BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
2123     if (Branch && Branch->isConditional()) {
2124       // Look for the selector dispatch.
2125       //   %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2126       //   %matches = icmp eq i32 %sel, %2
2127       //   br i1 %matches, label %catch14, label %eh.resume
2128       CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2129       if (!Compare || !Compare->isEquality())
2130         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2131       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2132            II != IE; ++II) {
2133         Instruction *Inst = II;
2134         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2135           continue;
2136         if (Inst == Compare || Inst == Branch)
2137           continue;
2138         if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2139           continue;
2140         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2141       }
2142       // The selector dispatch block should always terminate our search.
2143       assert(BB == EndBB);
2144       return;
2145     }
2146
2147     if (isAsynchronousEHPersonality(Personality)) {
2148       // If this is a landingpad block, split the block at the first non-landing
2149       // pad instruction.
2150       Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2151       if (LPadMap) {
2152         while (MaybeCall != BB->getTerminator() &&
2153                LPadMap->isLandingPadSpecificInst(MaybeCall))
2154           MaybeCall = MaybeCall->getNextNode();
2155       }
2156
2157       // Look for outlined finally calls.
2158       if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2159         Function *Fin = FinallyCall.getCalledFunction();
2160         assert(Fin && "outlined finally call should be direct");
2161         auto *Action = new CleanupHandler(BB);
2162         Action->setHandlerBlockOrFunc(Fin);
2163         Actions.insertCleanupHandler(Action);
2164         CleanupHandlerMap[BB] = Action;
2165         DEBUG(dbgs() << "  Found frontend-outlined finally call to "
2166                      << Fin->getName() << " in block "
2167                      << Action->getStartBlock()->getName() << "\n");
2168
2169         // Split the block if there were more interesting instructions and look
2170         // for finally calls in the normal successor block.
2171         BasicBlock *SuccBB = BB;
2172         if (FinallyCall.getInstruction() != BB->getTerminator() &&
2173             FinallyCall.getInstruction()->getNextNode() !=
2174                 BB->getTerminator()) {
2175           SuccBB =
2176               SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
2177         } else {
2178           if (FinallyCall.isInvoke()) {
2179             SuccBB =
2180                 cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
2181           } else {
2182             SuccBB = BB->getUniqueSuccessor();
2183             assert(SuccBB &&
2184                    "splitOutlinedFinallyCalls didn't insert a branch");
2185           }
2186         }
2187         BB = SuccBB;
2188         if (BB == EndBB)
2189           return;
2190         continue;
2191       }
2192     }
2193
2194     // Anything else is either a catch block or interesting cleanup code.
2195     for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2196          II != IE; ++II) {
2197       Instruction *Inst = II;
2198       if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2199         continue;
2200       // Unconditional branches fall through to this loop.
2201       if (Inst == Branch)
2202         continue;
2203       // If this is a catch block, there is no cleanup code to be found.
2204       if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2205         return;
2206       // If this a nested landing pad, it may contain an endcatch call.
2207       if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2208         return;
2209       // Anything else makes this interesting cleanup code.
2210       return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2211     }
2212
2213     // Only unconditional branches in empty blocks should get this far.
2214     assert(Branch && Branch->isUnconditional());
2215     if (BB == EndBB)
2216       return;
2217     BB = Branch->getSuccessor(0);
2218   }
2219 }
2220
2221 // This is a public function, declared in WinEHFuncInfo.h and is also
2222 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2223 void llvm::parseEHActions(const IntrinsicInst *II,
2224                           SmallVectorImpl<ActionHandler *> &Actions) {
2225   for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2226     uint64_t ActionKind =
2227         cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2228     if (ActionKind == /*catch=*/1) {
2229       auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2230       ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2231       int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2232       Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2233       I += 4;
2234       auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
2235       CH->setHandlerBlockOrFunc(Handler);
2236       CH->setExceptionVarIndex(EHObjIndexVal);
2237       Actions.push_back(CH);
2238     } else if (ActionKind == 0) {
2239       Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2240       I += 2;
2241       auto *CH = new CleanupHandler(/*BB=*/nullptr);
2242       CH->setHandlerBlockOrFunc(Handler);
2243       Actions.push_back(CH);
2244     } else {
2245       llvm_unreachable("Expected either a catch or cleanup handler!");
2246     }
2247   }
2248   std::reverse(Actions.begin(), Actions.end());
2249 }