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