[WinEH] Fixes for a few cppeh failures.
[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
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 BasicBlock *createStubLandingPad(Function *Handler,
774                                         Value *PersonalityFn) {
775   // FIXME: Finish this!
776   LLVMContext &Context = Handler->getContext();
777   BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
778   Handler->getBasicBlockList().push_back(StubBB);
779   IRBuilder<> Builder(StubBB);
780   LandingPadInst *LPad = Builder.CreateLandingPad(
781       llvm::StructType::get(Type::getInt8PtrTy(Context),
782                             Type::getInt32Ty(Context), nullptr),
783       PersonalityFn, 0);
784   LPad->setCleanup(true);
785   Builder.CreateUnreachable();
786   return StubBB;
787 }
788
789 // Cycles through the blocks in an outlined handler function looking for an
790 // invoke instruction and inserts an invoke of llvm.donothing with an empty
791 // landing pad if none is found.  The code that generates the .xdata tables for
792 // the handler needs at least one landing pad to identify the parent function's
793 // personality.
794 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
795                                                   Value *PersonalityFn) {
796   ReturnInst *Ret = nullptr;
797   for (BasicBlock &BB : *Handler) {
798     TerminatorInst *Terminator = BB.getTerminator();
799     // If we find an invoke, there is nothing to be done.
800     auto *II = dyn_cast<InvokeInst>(Terminator);
801     if (II)
802       return;
803     // If we've already recorded a return instruction, keep looking for invokes.
804     if (Ret)
805       continue;
806     // If we haven't recorded a return instruction yet, try this terminator.
807     Ret = dyn_cast<ReturnInst>(Terminator);
808   }
809
810   // If we got this far, the handler contains no invokes.  We should have seen
811   // at least one return.  We'll insert an invoke of llvm.donothing ahead of
812   // that return.
813   assert(Ret);
814   BasicBlock *OldRetBB = Ret->getParent();
815   BasicBlock *NewRetBB = SplitBlock(OldRetBB, Ret);
816   // SplitBlock adds an unconditional branch instruction at the end of the
817   // parent block.  We want to replace that with an invoke call, so we can
818   // erase it now.
819   OldRetBB->getTerminator()->eraseFromParent();
820   BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
821   Function *F =
822       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
823   InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
824 }
825
826 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
827                                   LandingPadInst *LPad, BasicBlock *StartBB,
828                                   FrameVarInfoMap &VarInfo) {
829   Module *M = SrcFn->getParent();
830   LLVMContext &Context = M->getContext();
831
832   // Create a new function to receive the handler contents.
833   Type *Int8PtrType = Type::getInt8PtrTy(Context);
834   std::vector<Type *> ArgTys;
835   ArgTys.push_back(Int8PtrType);
836   ArgTys.push_back(Int8PtrType);
837   Function *Handler;
838   if (Action->getType() == Catch) {
839     FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
840     Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
841                                SrcFn->getName() + ".catch", M);
842   } else {
843     FunctionType *FnType =
844         FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
845     Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
846                                SrcFn->getName() + ".cleanup", M);
847   }
848
849   Handler->addFnAttr("wineh-parent", SrcFn->getName());
850
851   // Generate a standard prolog to setup the frame recovery structure.
852   IRBuilder<> Builder(Context);
853   BasicBlock *Entry = BasicBlock::Create(Context, "entry");
854   Handler->getBasicBlockList().push_front(Entry);
855   Builder.SetInsertPoint(Entry);
856   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
857
858   std::unique_ptr<WinEHCloningDirectorBase> Director;
859
860   ValueToValueMapTy VMap;
861
862   LandingPadMap &LPadMap = LPadMaps[LPad];
863   if (!LPadMap.isInitialized())
864     LPadMap.mapLandingPad(LPad);
865   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
866     Constant *Sel = CatchAction->getSelector();
867     Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
868                                           NestedLPtoOriginalLP));
869     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
870                           ConstantInt::get(Type::getInt32Ty(Context), 1));
871   } else {
872     Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
873     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
874                           UndefValue::get(Type::getInt32Ty(Context)));
875   }
876
877   SmallVector<ReturnInst *, 8> Returns;
878   ClonedCodeInfo OutlinedFunctionInfo;
879
880   // If the start block contains PHI nodes, we need to map them.
881   BasicBlock::iterator II = StartBB->begin();
882   while (auto *PN = dyn_cast<PHINode>(II)) {
883     bool Mapped = false;
884     // Look for PHI values that we have already mapped (such as the selector).
885     for (Value *Val : PN->incoming_values()) {
886       if (VMap.count(Val)) {
887         VMap[PN] = VMap[Val];
888         Mapped = true;
889       }
890     }
891     // If we didn't find a match for this value, map it as an undef.
892     if (!Mapped) {
893       VMap[PN] = UndefValue::get(PN->getType());
894     }
895     ++II;
896   }
897
898   // Skip over PHIs and, if applicable, landingpad instructions.
899   II = StartBB->getFirstInsertionPt();
900
901   CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
902                             /*ModuleLevelChanges=*/false, Returns, "",
903                             &OutlinedFunctionInfo, Director.get());
904
905   // Move all the instructions in the first cloned block into our entry block.
906   BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
907   Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
908   FirstClonedBB->eraseFromParent();
909
910   // Make sure we can identify the handler's personality later.
911   addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
912
913   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
914     WinEHCatchDirector *CatchDirector =
915         reinterpret_cast<WinEHCatchDirector *>(Director.get());
916     CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
917     CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
918
919     // Look for blocks that are not part of the landing pad that we just
920     // outlined but terminate with a call to llvm.eh.endcatch and a
921     // branch to a block that is in the handler we just outlined.
922     // These blocks will be part of a nested landing pad that intends to
923     // return to an address in this handler.  This case is best handled
924     // after both landing pads have been outlined, so for now we'll just
925     // save the association of the blocks in LPadTargetBlocks.  The
926     // return instructions which are created from these branches will be
927     // replaced after all landing pads have been outlined.
928     for (const auto MapEntry : VMap) {
929       // VMap maps all values and blocks that were just cloned, but dead
930       // blocks which were pruned will map to nullptr.
931       if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
932         continue;
933       const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
934       for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
935         auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
936         if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
937           continue;
938         BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
939         --II;
940         if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
941           // This would indicate that a nested landing pad wants to return
942           // to a block that is outlined into two different handlers.
943           assert(!LPadTargetBlocks.count(MappedBB));
944           LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
945         }
946       }
947     }
948   } // End if (CatchAction)
949
950   Action->setHandlerBlockOrFunc(Handler);
951
952   return true;
953 }
954
955 /// This BB must end in a selector dispatch. All we need to do is pass the
956 /// handler block to llvm.eh.actions and list it as a possible indirectbr
957 /// target.
958 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
959                                           BasicBlock *StartBB) {
960   BasicBlock *HandlerBB;
961   BasicBlock *NextBB;
962   Constant *Selector;
963   bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
964   if (Res) {
965     // If this was EH dispatch, this must be a conditional branch to the handler
966     // block.
967     // FIXME: Handle instructions in the dispatch block. Currently we drop them,
968     // leading to crashes if some optimization hoists stuff here.
969     assert(CatchAction->getSelector() && HandlerBB &&
970            "expected catch EH dispatch");
971   } else {
972     // This must be a catch-all. Split the block after the landingpad.
973     assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
974     HandlerBB =
975         StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
976   }
977   CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
978   TinyPtrVector<BasicBlock *> Targets(HandlerBB);
979   CatchAction->setReturnTargets(Targets);
980 }
981
982 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
983   // Each instance of this class should only ever be used to map a single
984   // landing pad.
985   assert(OriginLPad == nullptr || OriginLPad == LPad);
986
987   // If the landing pad has already been mapped, there's nothing more to do.
988   if (OriginLPad == LPad)
989     return;
990
991   OriginLPad = LPad;
992
993   // The landingpad instruction returns an aggregate value.  Typically, its
994   // value will be passed to a pair of extract value instructions and the
995   // results of those extracts will have been promoted to reg values before
996   // this routine is called.
997   for (auto *U : LPad->users()) {
998     const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
999     if (!Extract)
1000       continue;
1001     assert(Extract->getNumIndices() == 1 &&
1002            "Unexpected operation: extracting both landing pad values");
1003     unsigned int Idx = *(Extract->idx_begin());
1004     assert((Idx == 0 || Idx == 1) &&
1005            "Unexpected operation: extracting an unknown landing pad element");
1006     if (Idx == 0) {
1007       ExtractedEHPtrs.push_back(Extract);
1008     } else if (Idx == 1) {
1009       ExtractedSelectors.push_back(Extract);
1010     }
1011   }
1012 }
1013
1014 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1015   return BB->getLandingPadInst() == OriginLPad;
1016 }
1017
1018 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1019   if (Inst == OriginLPad)
1020     return true;
1021   for (auto *Extract : ExtractedEHPtrs) {
1022     if (Inst == Extract)
1023       return true;
1024   }
1025   for (auto *Extract : ExtractedSelectors) {
1026     if (Inst == Extract)
1027       return true;
1028   }
1029   return false;
1030 }
1031
1032 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1033                                   Value *SelectorValue) const {
1034   // Remap all landing pad extract instructions to the specified values.
1035   for (auto *Extract : ExtractedEHPtrs)
1036     VMap[Extract] = EHPtrValue;
1037   for (auto *Extract : ExtractedSelectors)
1038     VMap[Extract] = SelectorValue;
1039 }
1040
1041 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1042     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1043   // If this is one of the boilerplate landing pad instructions, skip it.
1044   // The instruction will have already been remapped in VMap.
1045   if (LPadMap.isLandingPadSpecificInst(Inst))
1046     return CloningDirector::SkipInstruction;
1047
1048   // Nested landing pads will be cloned as stubs, with just the
1049   // landingpad instruction and an unreachable instruction. When
1050   // all landingpads have been outlined, we'll replace this with the
1051   // llvm.eh.actions call and indirect branch created when the
1052   // landing pad was outlined.
1053   if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1054     return handleLandingPad(VMap, LPad, NewBB);
1055   }
1056
1057   if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1058     return handleInvoke(VMap, Invoke, NewBB);
1059
1060   if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1061     return handleResume(VMap, Resume, NewBB);
1062
1063   if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1064     return handleCompare(VMap, Cmp, NewBB);
1065
1066   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1067     return handleBeginCatch(VMap, Inst, NewBB);
1068   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1069     return handleEndCatch(VMap, Inst, NewBB);
1070   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1071     return handleTypeIdFor(VMap, Inst, NewBB);
1072
1073   // Continue with the default cloning behavior.
1074   return CloningDirector::CloneInstruction;
1075 }
1076
1077 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1078     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1079   Instruction *NewInst = LPad->clone();
1080   if (LPad->hasName())
1081     NewInst->setName(LPad->getName());
1082   // Save this correlation for later processing.
1083   NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1084   VMap[LPad] = NewInst;
1085   BasicBlock::InstListType &InstList = NewBB->getInstList();
1086   InstList.push_back(NewInst);
1087   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1088   return CloningDirector::StopCloningBB;
1089 }
1090
1091 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1092     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1093   // The argument to the call is some form of the first element of the
1094   // landingpad aggregate value, but that doesn't matter.  It isn't used
1095   // here.
1096   // The second argument is an outparameter where the exception object will be
1097   // stored. Typically the exception object is a scalar, but it can be an
1098   // aggregate when catching by value.
1099   // FIXME: Leave something behind to indicate where the exception object lives
1100   // for this handler. Should it be part of llvm.eh.actions?
1101   assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1102                                           "llvm.eh.begincatch found while "
1103                                           "outlining catch handler.");
1104   ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1105   if (isa<ConstantPointerNull>(ExceptionObjectVar))
1106     return CloningDirector::SkipInstruction;
1107   assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1108          "catch parameter is not static alloca");
1109   Materializer.escapeCatchObject(ExceptionObjectVar);
1110   return CloningDirector::SkipInstruction;
1111 }
1112
1113 CloningDirector::CloningAction
1114 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1115                                    const Instruction *Inst, BasicBlock *NewBB) {
1116   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1117   // It might be interesting to track whether or not we are inside a catch
1118   // function, but that might make the algorithm more brittle than it needs
1119   // to be.
1120
1121   // The end catch call can occur in one of two places: either in a
1122   // landingpad block that is part of the catch handlers exception mechanism,
1123   // or at the end of the catch block.  However, a catch-all handler may call
1124   // end catch from the original landing pad.  If the call occurs in a nested
1125   // landing pad block, we must skip it and continue so that the landing pad
1126   // gets cloned.
1127   auto *ParentBB = IntrinCall->getParent();
1128   if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1129     return CloningDirector::SkipInstruction;
1130
1131   // If an end catch occurs anywhere else we want to terminate the handler
1132   // with a return to the code that follows the endcatch call.  If the
1133   // next instruction is not an unconditional branch, we need to split the
1134   // block to provide a clear target for the return instruction.
1135   BasicBlock *ContinueBB;
1136   auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1137   const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1138   if (!Branch || !Branch->isUnconditional()) {
1139     // We're interrupting the cloning process at this location, so the
1140     // const_cast we're doing here will not cause a problem.
1141     ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1142                             const_cast<Instruction *>(cast<Instruction>(Next)));
1143   } else {
1144     ContinueBB = Branch->getSuccessor(0);
1145   }
1146
1147   ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1148   ReturnTargets.push_back(ContinueBB);
1149
1150   // We just added a terminator to the cloned block.
1151   // Tell the caller to stop processing the current basic block so that
1152   // the branch instruction will be skipped.
1153   return CloningDirector::StopCloningBB;
1154 }
1155
1156 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1157     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1158   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1159   Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1160   // This causes a replacement that will collapse the landing pad CFG based
1161   // on the filter function we intend to match.
1162   if (Selector == CurrentSelector)
1163     VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1164   else
1165     VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1166   // Tell the caller not to clone this instruction.
1167   return CloningDirector::SkipInstruction;
1168 }
1169
1170 CloningDirector::CloningAction
1171 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1172                                  const InvokeInst *Invoke, BasicBlock *NewBB) {
1173   return CloningDirector::CloneInstruction;
1174 }
1175
1176 CloningDirector::CloningAction
1177 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1178                                  const ResumeInst *Resume, BasicBlock *NewBB) {
1179   // Resume instructions shouldn't be reachable from catch handlers.
1180   // We still need to handle it, but it will be pruned.
1181   BasicBlock::InstListType &InstList = NewBB->getInstList();
1182   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1183   return CloningDirector::StopCloningBB;
1184 }
1185
1186 CloningDirector::CloningAction
1187 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1188                                   const CmpInst *Compare, BasicBlock *NewBB) {
1189   const IntrinsicInst *IntrinCall = nullptr;
1190   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1191     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1192   } else if (match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1193     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1194   }
1195   if (IntrinCall) {
1196     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1197     // This causes a replacement that will collapse the landing pad CFG based
1198     // on the filter function we intend to match.
1199     if (Selector == CurrentSelector->stripPointerCasts()) {
1200       VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1201     }
1202     else {
1203       VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1204     }
1205     return CloningDirector::SkipInstruction;
1206   }
1207   return CloningDirector::CloneInstruction;
1208 }
1209
1210 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1211     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1212   // The MS runtime will terminate the process if an exception occurs in a
1213   // cleanup handler, so we shouldn't encounter landing pads in the actual
1214   // cleanup code, but they may appear in catch blocks.  Depending on where
1215   // we started cloning we may see one, but it will get dropped during dead
1216   // block pruning.
1217   Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1218   VMap[LPad] = NewInst;
1219   BasicBlock::InstListType &InstList = NewBB->getInstList();
1220   InstList.push_back(NewInst);
1221   return CloningDirector::StopCloningBB;
1222 }
1223
1224 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1225     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1226   // Cleanup code may flow into catch blocks or the catch block may be part
1227   // of a branch that will be optimized away.  We'll insert a return
1228   // instruction now, but it may be pruned before the cloning process is
1229   // complete.
1230   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1231   return CloningDirector::StopCloningBB;
1232 }
1233
1234 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1235     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1236   // Cleanup handlers nested within catch handlers may begin with a call to
1237   // eh.endcatch.  We can just ignore that instruction.
1238   return CloningDirector::SkipInstruction;
1239 }
1240
1241 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1242     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1243   // If we encounter a selector comparison while cloning a cleanup handler,
1244   // we want to stop cloning immediately.  Anything after the dispatch
1245   // will be outlined into a different handler.
1246   BasicBlock *CatchHandler;
1247   Constant *Selector;
1248   BasicBlock *NextBB;
1249   if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1250                          CatchHandler, Selector, NextBB)) {
1251     ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1252     return CloningDirector::StopCloningBB;
1253   }
1254   // If eg.typeid.for is called for any other reason, it can be ignored.
1255   VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1256   return CloningDirector::SkipInstruction;
1257 }
1258
1259 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1260     ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1261   // All invokes in cleanup handlers can be replaced with calls.
1262   SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1263   // Insert a normal call instruction...
1264   CallInst *NewCall =
1265       CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1266                        Invoke->getName(), NewBB);
1267   NewCall->setCallingConv(Invoke->getCallingConv());
1268   NewCall->setAttributes(Invoke->getAttributes());
1269   NewCall->setDebugLoc(Invoke->getDebugLoc());
1270   VMap[Invoke] = NewCall;
1271
1272   // Remap the operands.
1273   llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1274
1275   // Insert an unconditional branch to the normal destination.
1276   BranchInst::Create(Invoke->getNormalDest(), NewBB);
1277
1278   // The unwind destination won't be cloned into the new function, so
1279   // we don't need to clean up its phi nodes.
1280
1281   // We just added a terminator to the cloned block.
1282   // Tell the caller to stop processing the current basic block.
1283   return CloningDirector::CloneSuccessors;
1284 }
1285
1286 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1287     ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1288   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1289
1290   // We just added a terminator to the cloned block.
1291   // Tell the caller to stop processing the current basic block so that
1292   // the branch instruction will be skipped.
1293   return CloningDirector::StopCloningBB;
1294 }
1295
1296 CloningDirector::CloningAction
1297 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1298                                     const CmpInst *Compare, BasicBlock *NewBB) {
1299   const IntrinsicInst *IntrinCall = nullptr;
1300   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1301       match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1302     VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1303     return CloningDirector::SkipInstruction;
1304   }
1305   return CloningDirector::CloneInstruction;
1306
1307 }
1308
1309 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1310     Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1311     : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1312   BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1313   Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
1314 }
1315
1316 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1317   // If we're asked to materialize a value that is an instruction, we
1318   // temporarily create an alloca in the outlined function and add this
1319   // to the FrameVarInfo map.  When all the outlining is complete, we'll
1320   // collect these into a structure, spilling non-alloca values in the
1321   // parent frame as necessary, and replace these temporary allocas with
1322   // GEPs referencing the frame allocation block.
1323
1324   // If the value is an alloca, the mapping is direct.
1325   if (auto *AV = dyn_cast<AllocaInst>(V)) {
1326     AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1327     Builder.Insert(NewAlloca, AV->getName());
1328     FrameVarInfo[AV].push_back(NewAlloca);
1329     return NewAlloca;
1330   }
1331
1332   // For other types of instructions or arguments, we need an alloca based on
1333   // the value's type and a load of the alloca.  The alloca will be replaced
1334   // by a GEP, but the load will stay.  In the parent function, the value will
1335   // be spilled to a location in the frame allocation block.
1336   if (isa<Instruction>(V) || isa<Argument>(V)) {
1337     AllocaInst *NewAlloca =
1338         Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
1339     FrameVarInfo[V].push_back(NewAlloca);
1340     LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1341     return NewLoad;
1342   }
1343
1344   // Don't materialize other values.
1345   return nullptr;
1346 }
1347
1348 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1349   // Catch parameter objects have to live in the parent frame. When we see a use
1350   // of a catch parameter, add a sentinel to the multimap to indicate that it's
1351   // used from another handler. This will prevent us from trying to sink the
1352   // alloca into the handler and ensure that the catch parameter is present in
1353   // the call to llvm.frameescape.
1354   FrameVarInfo[V].push_back(getCatchObjectSentinel());
1355 }
1356
1357 // This function maps the catch and cleanup handlers that are reachable from the
1358 // specified landing pad. The landing pad sequence will have this basic shape:
1359 //
1360 //  <cleanup handler>
1361 //  <selector comparison>
1362 //  <catch handler>
1363 //  <cleanup handler>
1364 //  <selector comparison>
1365 //  <catch handler>
1366 //  <cleanup handler>
1367 //  ...
1368 //
1369 // Any of the cleanup slots may be absent.  The cleanup slots may be occupied by
1370 // any arbitrary control flow, but all paths through the cleanup code must
1371 // eventually reach the next selector comparison and no path can skip to a
1372 // different selector comparisons, though some paths may terminate abnormally.
1373 // Therefore, we will use a depth first search from the start of any given
1374 // cleanup block and stop searching when we find the next selector comparison.
1375 //
1376 // If the landingpad instruction does not have a catch clause, we will assume
1377 // that any instructions other than selector comparisons and catch handlers can
1378 // be ignored.  In practice, these will only be the boilerplate instructions.
1379 //
1380 // The catch handlers may also have any control structure, but we are only
1381 // interested in the start of the catch handlers, so we don't need to actually
1382 // follow the flow of the catch handlers.  The start of the catch handlers can
1383 // be located from the compare instructions, but they can be skipped in the
1384 // flow by following the contrary branch.
1385 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1386                                        LandingPadActions &Actions) {
1387   unsigned int NumClauses = LPad->getNumClauses();
1388   unsigned int HandlersFound = 0;
1389   BasicBlock *BB = LPad->getParent();
1390
1391   DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1392
1393   if (NumClauses == 0) {
1394     findCleanupHandlers(Actions, BB, nullptr);
1395     return;
1396   }
1397
1398   VisitedBlockSet VisitedBlocks;
1399
1400   while (HandlersFound != NumClauses) {
1401     BasicBlock *NextBB = nullptr;
1402
1403     // See if the clause we're looking for is a catch-all.
1404     // If so, the catch begins immediately.
1405     Constant *ExpectedSelector = LPad->getClause(HandlersFound)->stripPointerCasts();
1406     if (isa<ConstantPointerNull>(ExpectedSelector)) {
1407       // The catch all must occur last.
1408       assert(HandlersFound == NumClauses - 1);
1409
1410       // There can be additional selector dispatches in the call chain that we
1411       // need to ignore.
1412       BasicBlock *CatchBlock = nullptr;
1413       Constant *Selector;
1414       while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1415         DEBUG(dbgs() << "  Found extra catch dispatch in block "
1416           << CatchBlock->getName() << "\n");
1417         BB = NextBB;
1418       }
1419
1420       // For C++ EH, check if there is any interesting cleanup code before we
1421       // begin the catch. This is important because cleanups cannot rethrow
1422       // exceptions but code called from catches can. For SEH, it isn't
1423       // important if some finally code before a catch-all is executed out of
1424       // line or after recovering from the exception.
1425       if (Personality == EHPersonality::MSVC_CXX)
1426         findCleanupHandlers(Actions, BB, BB);
1427
1428       // Add the catch handler to the action list.
1429       // Since this is a catch-all handler, the selector won't actually appear
1430       // in the code anywhere.  ExpectedSelector here is the constant null ptr
1431       // that we got from the landing pad instruction.
1432       CatchHandler *Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1433       CatchHandlerMap[BB] = Action;
1434       Actions.insertCatchHandler(Action);
1435       DEBUG(dbgs() << "  Catch all handler at block " << BB->getName() << "\n");
1436       ++HandlersFound;
1437
1438       // Once we reach a catch-all, don't expect to hit a resume instruction.
1439       BB = nullptr;
1440       break;
1441     }
1442
1443     CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1444     // See if there is any interesting code executed before the dispatch.
1445     findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
1446
1447     assert(CatchAction);
1448
1449     // When the source program contains multiple nested try blocks the catch
1450     // handlers can get strung together in such a way that we can encounter
1451     // a dispatch for a selector that we've already had a handler for.
1452     if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1453       ++HandlersFound;
1454
1455       // Add the catch handler to the action list.
1456       DEBUG(dbgs() << "  Found catch dispatch in block "
1457                    << CatchAction->getStartBlock()->getName() << "\n");
1458       Actions.insertCatchHandler(CatchAction);
1459     } else {
1460       DEBUG(dbgs() << "  Found extra catch dispatch in block "
1461                    << CatchAction->getStartBlock()->getName() << "\n");
1462     }
1463
1464     // Move on to the block after the catch handler.
1465     BB = NextBB;
1466   }
1467
1468   // If we didn't wind up in a catch-all, see if there is any interesting code
1469   // executed before the resume.
1470   findCleanupHandlers(Actions, BB, BB);
1471
1472   // It's possible that some optimization moved code into a landingpad that
1473   // wasn't
1474   // previously being used for cleanup.  If that happens, we need to execute
1475   // that
1476   // extra code from a cleanup handler.
1477   if (Actions.includesCleanup() && !LPad->isCleanup())
1478     LPad->setCleanup(true);
1479 }
1480
1481 // This function searches starting with the input block for the next
1482 // block that terminates with a branch whose condition is based on a selector
1483 // comparison.  This may be the input block.  See the mapLandingPadBlocks
1484 // comments for a discussion of control flow assumptions.
1485 //
1486 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1487                                              BasicBlock *&NextBB,
1488                                              VisitedBlockSet &VisitedBlocks) {
1489   // See if we've already found a catch handler use it.
1490   // Call count() first to avoid creating a null entry for blocks
1491   // we haven't seen before.
1492   if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1493     CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1494     NextBB = Action->getNextBB();
1495     return Action;
1496   }
1497
1498   // VisitedBlocks applies only to the current search.  We still
1499   // need to consider blocks that we've visited while mapping other
1500   // landing pads.
1501   VisitedBlocks.insert(BB);
1502
1503   BasicBlock *CatchBlock = nullptr;
1504   Constant *Selector = nullptr;
1505
1506   // If this is the first time we've visited this block from any landing pad
1507   // look to see if it is a selector dispatch block.
1508   if (!CatchHandlerMap.count(BB)) {
1509     if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1510       CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1511       CatchHandlerMap[BB] = Action;
1512       return Action;
1513     }
1514   }
1515
1516   // Visit each successor, looking for the dispatch.
1517   // FIXME: We expect to find the dispatch quickly, so this will probably
1518   //        work better as a breadth first search.
1519   for (BasicBlock *Succ : successors(BB)) {
1520     if (VisitedBlocks.count(Succ))
1521       continue;
1522
1523     CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1524     if (Action)
1525       return Action;
1526   }
1527   return nullptr;
1528 }
1529
1530 // These are helper functions to combine repeated code from findCleanupHandlers.
1531 static void createCleanupHandler(LandingPadActions &Actions,
1532                                  CleanupHandlerMapTy &CleanupHandlerMap,
1533                                  BasicBlock *BB) {
1534   CleanupHandler *Action = new CleanupHandler(BB);
1535   CleanupHandlerMap[BB] = Action;
1536   Actions.insertCleanupHandler(Action);
1537   DEBUG(dbgs() << "  Found cleanup code in block "
1538                << Action->getStartBlock()->getName() << "\n");
1539 }
1540
1541 static bool isFrameAddressCall(Value *V) {
1542   return match(V, m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1543 }
1544
1545 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1546                                          Instruction *MaybeCall) {
1547   // Look for finally blocks that Clang has already outlined for us.
1548   //   %fp = call i8* @llvm.frameaddress(i32 0)
1549   //   call void @"fin$parent"(iN 1, i8* %fp)
1550   if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1551     MaybeCall = MaybeCall->getNextNode();
1552   CallSite FinallyCall(MaybeCall);
1553   if (!FinallyCall || FinallyCall.arg_size() != 2)
1554     return CallSite();
1555   if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
1556     return CallSite();
1557   if (!isFrameAddressCall(FinallyCall.getArgument(1)))
1558     return CallSite();
1559   return FinallyCall;
1560 }
1561
1562 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
1563   // Skip single ubr blocks.
1564   while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
1565     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
1566     if (Br && Br->isUnconditional())
1567       BB = Br->getSuccessor(0);
1568     else
1569       return BB;
1570   }
1571   return BB;
1572 }
1573
1574 // This function searches starting with the input block for the next block that
1575 // contains code that is not part of a catch handler and would not be eliminated
1576 // during handler outlining.
1577 //
1578 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
1579                                        BasicBlock *StartBB, BasicBlock *EndBB) {
1580   // Here we will skip over the following:
1581   //
1582   // landing pad prolog:
1583   //
1584   // Unconditional branches
1585   //
1586   // Selector dispatch
1587   //
1588   // Resume pattern
1589   //
1590   // Anything else marks the start of an interesting block
1591
1592   BasicBlock *BB = StartBB;
1593   // Anything other than an unconditional branch will kick us out of this loop
1594   // one way or another.
1595   while (BB) {
1596     BB = followSingleUnconditionalBranches(BB);
1597     // If we've already scanned this block, don't scan it again.  If it is
1598     // a cleanup block, there will be an action in the CleanupHandlerMap.
1599     // If we've scanned it and it is not a cleanup block, there will be a
1600     // nullptr in the CleanupHandlerMap.  If we have not scanned it, there will
1601     // be no entry in the CleanupHandlerMap.  We must call count() first to
1602     // avoid creating a null entry for blocks we haven't scanned.
1603     if (CleanupHandlerMap.count(BB)) {
1604       if (auto *Action = CleanupHandlerMap[BB]) {
1605         Actions.insertCleanupHandler(Action);
1606         DEBUG(dbgs() << "  Found cleanup code in block "
1607               << Action->getStartBlock()->getName() << "\n");
1608         // FIXME: This cleanup might chain into another, and we need to discover
1609         // that.
1610         return;
1611       } else {
1612         // Here we handle the case where the cleanup handler map contains a
1613         // value for this block but the value is a nullptr.  This means that
1614         // we have previously analyzed the block and determined that it did
1615         // not contain any cleanup code.  Based on the earlier analysis, we
1616         // know the the block must end in either an unconditional branch, a
1617         // resume or a conditional branch that is predicated on a comparison
1618         // with a selector.  Either the resume or the selector dispatch
1619         // would terminate the search for cleanup code, so the unconditional
1620         // branch is the only case for which we might need to continue
1621         // searching.
1622         BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
1623         if (SuccBB == BB || SuccBB == EndBB)
1624           return;
1625         BB = SuccBB;
1626         continue;
1627       }
1628     }
1629
1630     // Create an entry in the cleanup handler map for this block.  Initially
1631     // we create an entry that says this isn't a cleanup block.  If we find
1632     // cleanup code, the caller will replace this entry.
1633     CleanupHandlerMap[BB] = nullptr;
1634
1635     TerminatorInst *Terminator = BB->getTerminator();
1636
1637     // Landing pad blocks have extra instructions we need to accept.
1638     LandingPadMap *LPadMap = nullptr;
1639     if (BB->isLandingPad()) {
1640       LandingPadInst *LPad = BB->getLandingPadInst();
1641       LPadMap = &LPadMaps[LPad];
1642       if (!LPadMap->isInitialized())
1643         LPadMap->mapLandingPad(LPad);
1644     }
1645
1646     // Look for the bare resume pattern:
1647     //   %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1648     //   %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
1649     //   resume { i8*, i32 } %lpad.val2
1650     if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1651       InsertValueInst *Insert1 = nullptr;
1652       InsertValueInst *Insert2 = nullptr;
1653       Value *ResumeVal = Resume->getOperand(0);
1654       // If the resume value isn't a phi or landingpad value, it should be a
1655       // series of insertions. Identify them so we can avoid them when scanning
1656       // for cleanups.
1657       if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
1658         Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1659         if (!Insert2)
1660           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1661         Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1662         if (!Insert1)
1663           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1664       }
1665       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1666            II != IE; ++II) {
1667         Instruction *Inst = II;
1668         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1669           continue;
1670         if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1671           continue;
1672         if (!Inst->hasOneUse() ||
1673             (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1674           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1675         }
1676       }
1677       return;
1678     }
1679
1680     BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1681     if (Branch && Branch->isConditional()) {
1682       // Look for the selector dispatch.
1683       //   %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1684       //   %matches = icmp eq i32 %sel, %2
1685       //   br i1 %matches, label %catch14, label %eh.resume
1686       CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1687       if (!Compare || !Compare->isEquality())
1688         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1689       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1690            II != IE; ++II) {
1691         Instruction *Inst = II;
1692         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1693           continue;
1694         if (Inst == Compare || Inst == Branch)
1695           continue;
1696         if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1697           continue;
1698         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1699       }
1700       // The selector dispatch block should always terminate our search.
1701       assert(BB == EndBB);
1702       return;
1703     }
1704
1705     if (isAsynchronousEHPersonality(Personality)) {
1706       // If this is a landingpad block, split the block at the first non-landing
1707       // pad instruction.
1708       Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
1709       if (LPadMap) {
1710         while (MaybeCall != BB->getTerminator() &&
1711                LPadMap->isLandingPadSpecificInst(MaybeCall))
1712           MaybeCall = MaybeCall->getNextNode();
1713       }
1714
1715       // Look for outlined finally calls.
1716       if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
1717         Function *Fin = FinallyCall.getCalledFunction();
1718         assert(Fin && "outlined finally call should be direct");
1719         auto *Action = new CleanupHandler(BB);
1720         Action->setHandlerBlockOrFunc(Fin);
1721         Actions.insertCleanupHandler(Action);
1722         CleanupHandlerMap[BB] = Action;
1723         DEBUG(dbgs() << "  Found frontend-outlined finally call to "
1724                      << Fin->getName() << " in block "
1725                      << Action->getStartBlock()->getName() << "\n");
1726
1727         // Split the block if there were more interesting instructions and look
1728         // for finally calls in the normal successor block.
1729         BasicBlock *SuccBB = BB;
1730         if (FinallyCall.getInstruction() != BB->getTerminator() &&
1731             FinallyCall.getInstruction()->getNextNode() != BB->getTerminator()) {
1732           SuccBB = BB->splitBasicBlock(FinallyCall.getInstruction()->getNextNode());
1733         } else {
1734           if (FinallyCall.isInvoke()) {
1735             SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
1736           } else {
1737             SuccBB = BB->getUniqueSuccessor();
1738             assert(SuccBB && "splitOutlinedFinallyCalls didn't insert a branch");
1739           }
1740         }
1741         BB = SuccBB;
1742         if (BB == EndBB)
1743           return;
1744         continue;
1745       }
1746     }
1747
1748     // Anything else is either a catch block or interesting cleanup code.
1749     for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1750          II != IE; ++II) {
1751       Instruction *Inst = II;
1752       if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1753         continue;
1754       // Unconditional branches fall through to this loop.
1755       if (Inst == Branch)
1756         continue;
1757       // If this is a catch block, there is no cleanup code to be found.
1758       if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1759         return;
1760       // If this a nested landing pad, it may contain an endcatch call.
1761       if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1762         return;
1763       // Anything else makes this interesting cleanup code.
1764       return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1765     }
1766
1767     // Only unconditional branches in empty blocks should get this far.
1768     assert(Branch && Branch->isUnconditional());
1769     if (BB == EndBB)
1770       return;
1771     BB = Branch->getSuccessor(0);
1772   }
1773 }
1774
1775 // This is a public function, declared in WinEHFuncInfo.h and is also
1776 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
1777 void llvm::parseEHActions(const IntrinsicInst *II,
1778                           SmallVectorImpl<ActionHandler *> &Actions) {
1779   for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
1780     uint64_t ActionKind =
1781         cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
1782     if (ActionKind == /*catch=*/1) {
1783       auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
1784       ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
1785       int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
1786       Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
1787       I += 4;
1788       auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
1789       CH->setHandlerBlockOrFunc(Handler);
1790       CH->setExceptionVarIndex(EHObjIndexVal);
1791       Actions.push_back(CH);
1792     } else if (ActionKind == 0) {
1793       Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
1794       I += 2;
1795       auto *CH = new CleanupHandler(/*BB=*/nullptr);
1796       CH->setHandlerBlockOrFunc(Handler);
1797       Actions.push_back(CH);
1798     } else {
1799       llvm_unreachable("Expected either a catch or cleanup handler!");
1800     }
1801   }
1802   std::reverse(Actions.begin(), Actions.end());
1803 }