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