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