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