[SEH] Emit 32-bit SEH tables for the new EH IR
[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 for functions using a personality function from a runtime
12 // provided by MSVC. Functions with other personality functions are left alone
13 // and may be prepared by other passes. In particular, all supported MSVC
14 // personality functions require cleanup code to be outlined, and the C++
15 // personality requires catch handler code to be outlined.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/TinyPtrVector.h"
26 #include "llvm/Analysis/CFG.h"
27 #include "llvm/Analysis/LibCallSemantics.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/CodeGen/WinEHFuncInfo.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PatternMatch.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
44 #include <memory>
45
46 using namespace llvm;
47 using namespace llvm::PatternMatch;
48
49 #define DEBUG_TYPE "winehprepare"
50
51 namespace {
52
53 // This map is used to model frame variable usage during outlining, to
54 // construct a structure type to hold the frame variables in a frame
55 // allocation block, and to remap the frame variable allocas (including
56 // spill locations as needed) to GEPs that get the variable from the
57 // frame allocation structure.
58 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
59
60 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
61 // quite null.
62 AllocaInst *getCatchObjectSentinel() {
63   return static_cast<AllocaInst *>(nullptr) + 1;
64 }
65
66 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
67
68 class LandingPadActions;
69 class LandingPadMap;
70
71 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
72 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
73
74 class WinEHPrepare : public FunctionPass {
75 public:
76   static char ID; // Pass identification, replacement for typeid.
77   WinEHPrepare(const TargetMachine *TM = nullptr)
78       : FunctionPass(ID) {
79     if (TM)
80       TheTriple = TM->getTargetTriple();
81   }
82
83   bool runOnFunction(Function &Fn) override;
84
85   bool doFinalization(Module &M) override;
86
87   void getAnalysisUsage(AnalysisUsage &AU) const override;
88
89   const char *getPassName() const override {
90     return "Windows exception handling preparation";
91   }
92
93 private:
94   bool prepareExceptionHandlers(Function &F,
95                                 SmallVectorImpl<LandingPadInst *> &LPads);
96   void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
97   void promoteLandingPadValues(LandingPadInst *LPad);
98   void demoteValuesLiveAcrossHandlers(Function &F,
99                                       SmallVectorImpl<LandingPadInst *> &LPads);
100   void findSEHEHReturnPoints(Function &F,
101                              SetVector<BasicBlock *> &EHReturnBlocks);
102   void findCXXEHReturnPoints(Function &F,
103                              SetVector<BasicBlock *> &EHReturnBlocks);
104   void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
105                                 SetVector<BasicBlock*> &Targets);
106   void completeNestedLandingPad(Function *ParentFn,
107                                 LandingPadInst *OutlinedLPad,
108                                 const LandingPadInst *OriginalLPad,
109                                 FrameVarInfoMap &VarInfo);
110   Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
111                               const Twine &Name, Module *M, Value *&ParentFP);
112   bool outlineHandler(ActionHandler *Action, Function *SrcFn,
113                       LandingPadInst *LPad, BasicBlock *StartBB,
114                       FrameVarInfoMap &VarInfo);
115   void addStubInvokeToHandlerIfNeeded(Function *Handler);
116
117   void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
118   CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
119                                  VisitedBlockSet &VisitedBlocks);
120   void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
121                            BasicBlock *EndBB);
122
123   void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
124   void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
125   void
126   insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
127                  SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
128   AllocaInst *insertPHILoads(PHINode *PN, Function &F);
129   void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
130                           DenseMap<BasicBlock *, Value *> &Loads, Function &F);
131   void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB,
132                           Function &F);
133   bool prepareExplicitEH(Function &F,
134                          SmallVectorImpl<BasicBlock *> &EntryBlocks);
135   void colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks);
136
137   Triple TheTriple;
138
139   // All fields are reset by runOnFunction.
140   DominatorTree *DT = nullptr;
141   const TargetLibraryInfo *LibInfo = nullptr;
142   EHPersonality Personality = EHPersonality::Unknown;
143   CatchHandlerMapTy CatchHandlerMap;
144   CleanupHandlerMapTy CleanupHandlerMap;
145   DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
146   SmallPtrSet<BasicBlock *, 4> NormalBlocks;
147   SmallPtrSet<BasicBlock *, 4> EHBlocks;
148   SetVector<BasicBlock *> EHReturnBlocks;
149
150   // This maps landing pad instructions found in outlined handlers to
151   // the landing pad instruction in the parent function from which they
152   // were cloned.  The cloned/nested landing pad is used as the key
153   // because the landing pad may be cloned into multiple handlers.
154   // This map will be used to add the llvm.eh.actions call to the nested
155   // landing pads after all handlers have been outlined.
156   DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
157
158   // This maps blocks in the parent function which are destinations of
159   // catch handlers to cloned blocks in (other) outlined handlers. This
160   // handles the case where a nested landing pads has a catch handler that
161   // returns to a handler function rather than the parent function.
162   // The original block is used as the key here because there should only
163   // ever be one handler function from which the cloned block is not pruned.
164   // The original block will be pruned from the parent function after all
165   // handlers have been outlined.  This map will be used to adjust the
166   // return instructions of handlers which return to the block that was
167   // outlined into a handler.  This is done after all handlers have been
168   // outlined but before the outlined code is pruned from the parent function.
169   DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
170
171   // Map from outlined handler to call to parent local address. Only used for
172   // 32-bit EH.
173   DenseMap<Function *, Value *> HandlerToParentFP;
174
175   AllocaInst *SEHExceptionCodeSlot = nullptr;
176
177   std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
178   std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
179   std::map<BasicBlock *, std::set<BasicBlock *>> FuncletChildren;
180 };
181
182 class WinEHFrameVariableMaterializer : public ValueMaterializer {
183 public:
184   WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
185                                  FrameVarInfoMap &FrameVarInfo);
186   ~WinEHFrameVariableMaterializer() override {}
187
188   Value *materializeValueFor(Value *V) override;
189
190   void escapeCatchObject(Value *V);
191
192 private:
193   FrameVarInfoMap &FrameVarInfo;
194   IRBuilder<> Builder;
195 };
196
197 class LandingPadMap {
198 public:
199   LandingPadMap() : OriginLPad(nullptr) {}
200   void mapLandingPad(const LandingPadInst *LPad);
201
202   bool isInitialized() { return OriginLPad != nullptr; }
203
204   bool isOriginLandingPadBlock(const BasicBlock *BB) const;
205   bool isLandingPadSpecificInst(const Instruction *Inst) const;
206
207   void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
208                      Value *SelectorValue) const;
209
210 private:
211   const LandingPadInst *OriginLPad;
212   // We will normally only see one of each of these instructions, but
213   // if more than one occurs for some reason we can handle that.
214   TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
215   TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
216 };
217
218 class WinEHCloningDirectorBase : public CloningDirector {
219 public:
220   WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
221                            FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
222       : Materializer(HandlerFn, ParentFP, VarInfo),
223         SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
224         Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
225         LPadMap(LPadMap), ParentFP(ParentFP) {}
226
227   CloningAction handleInstruction(ValueToValueMapTy &VMap,
228                                   const Instruction *Inst,
229                                   BasicBlock *NewBB) override;
230
231   virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
232                                          const Instruction *Inst,
233                                          BasicBlock *NewBB) = 0;
234   virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
235                                        const Instruction *Inst,
236                                        BasicBlock *NewBB) = 0;
237   virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
238                                         const Instruction *Inst,
239                                         BasicBlock *NewBB) = 0;
240   virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
241                                          const IndirectBrInst *IBr,
242                                          BasicBlock *NewBB) = 0;
243   virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
244                                      const InvokeInst *Invoke,
245                                      BasicBlock *NewBB) = 0;
246   virtual CloningAction handleResume(ValueToValueMapTy &VMap,
247                                      const ResumeInst *Resume,
248                                      BasicBlock *NewBB) = 0;
249   virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
250                                       const CmpInst *Compare,
251                                       BasicBlock *NewBB) = 0;
252   virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
253                                          const LandingPadInst *LPad,
254                                          BasicBlock *NewBB) = 0;
255
256   ValueMaterializer *getValueMaterializer() override { return &Materializer; }
257
258 protected:
259   WinEHFrameVariableMaterializer Materializer;
260   Type *SelectorIDType;
261   Type *Int8PtrType;
262   LandingPadMap &LPadMap;
263
264   /// The value representing the parent frame pointer.
265   Value *ParentFP;
266 };
267
268 class WinEHCatchDirector : public WinEHCloningDirectorBase {
269 public:
270   WinEHCatchDirector(
271       Function *CatchFn, Value *ParentFP, Value *Selector,
272       FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
273       DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
274       DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
275       : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
276         CurrentSelector(Selector->stripPointerCasts()),
277         ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
278         DT(DT), EHBlocks(EHBlocks) {}
279
280   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
281                                  const Instruction *Inst,
282                                  BasicBlock *NewBB) override;
283   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
284                                BasicBlock *NewBB) override;
285   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
286                                 const Instruction *Inst,
287                                 BasicBlock *NewBB) override;
288   CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
289                                  const IndirectBrInst *IBr,
290                                  BasicBlock *NewBB) override;
291   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
292                              BasicBlock *NewBB) override;
293   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
294                              BasicBlock *NewBB) override;
295   CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
296                               BasicBlock *NewBB) override;
297   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
298                                  const LandingPadInst *LPad,
299                                  BasicBlock *NewBB) override;
300
301   Value *getExceptionVar() { return ExceptionObjectVar; }
302   TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
303
304 private:
305   Value *CurrentSelector;
306
307   Value *ExceptionObjectVar;
308   TinyPtrVector<BasicBlock *> ReturnTargets;
309
310   // This will be a reference to the field of the same name in the WinEHPrepare
311   // object which instantiates this WinEHCatchDirector object.
312   DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
313   DominatorTree *DT;
314   SmallPtrSetImpl<BasicBlock *> &EHBlocks;
315 };
316
317 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
318 public:
319   WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
320                        FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
321       : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
322                                  LPadMap) {}
323
324   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
325                                  const Instruction *Inst,
326                                  BasicBlock *NewBB) override;
327   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
328                                BasicBlock *NewBB) override;
329   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
330                                 const Instruction *Inst,
331                                 BasicBlock *NewBB) override;
332   CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
333                                  const IndirectBrInst *IBr,
334                                  BasicBlock *NewBB) override;
335   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
336                              BasicBlock *NewBB) override;
337   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
338                              BasicBlock *NewBB) override;
339   CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
340                               BasicBlock *NewBB) override;
341   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
342                                  const LandingPadInst *LPad,
343                                  BasicBlock *NewBB) override;
344 };
345
346 class LandingPadActions {
347 public:
348   LandingPadActions() : HasCleanupHandlers(false) {}
349
350   void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
351   void insertCleanupHandler(CleanupHandler *Action) {
352     Actions.push_back(Action);
353     HasCleanupHandlers = true;
354   }
355
356   bool includesCleanup() const { return HasCleanupHandlers; }
357
358   SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
359   SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
360   SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
361
362 private:
363   // Note that this class does not own the ActionHandler objects in this vector.
364   // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
365   // in the WinEHPrepare class.
366   SmallVector<ActionHandler *, 4> Actions;
367   bool HasCleanupHandlers;
368 };
369
370 } // end anonymous namespace
371
372 char WinEHPrepare::ID = 0;
373 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
374                    false, false)
375
376 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
377   return new WinEHPrepare(TM);
378 }
379
380 bool WinEHPrepare::runOnFunction(Function &Fn) {
381   if (!Fn.hasPersonalityFn())
382     return false;
383
384   // No need to prepare outlined handlers.
385   if (Fn.hasFnAttribute("wineh-parent"))
386     return false;
387
388   // Classify the personality to see what kind of preparation we need.
389   Personality = classifyEHPersonality(Fn.getPersonalityFn());
390
391   // Do nothing if this is not an MSVC personality.
392   if (!isMSVCEHPersonality(Personality))
393     return false;
394
395   SmallVector<LandingPadInst *, 4> LPads;
396   SmallVector<ResumeInst *, 4> Resumes;
397   SmallVector<BasicBlock *, 4> EntryBlocks;
398   bool ForExplicitEH = false;
399   for (BasicBlock &BB : Fn) {
400     Instruction *First = BB.getFirstNonPHI();
401     if (auto *LP = dyn_cast<LandingPadInst>(First)) {
402       LPads.push_back(LP);
403     } else if (First->isEHPad()) {
404       if (!ForExplicitEH)
405         EntryBlocks.push_back(&Fn.getEntryBlock());
406       if (!isa<CatchEndPadInst>(First) && !isa<CleanupEndPadInst>(First))
407         EntryBlocks.push_back(&BB);
408       ForExplicitEH = true;
409     }
410     if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
411       Resumes.push_back(Resume);
412   }
413
414   if (ForExplicitEH)
415     return prepareExplicitEH(Fn, EntryBlocks);
416
417   // No need to prepare functions that lack landing pads.
418   if (LPads.empty())
419     return false;
420
421   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
422   LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
423
424   // If there were any landing pads, prepareExceptionHandlers will make changes.
425   prepareExceptionHandlers(Fn, LPads);
426   return true;
427 }
428
429 bool WinEHPrepare::doFinalization(Module &M) { return false; }
430
431 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
432   AU.addRequired<DominatorTreeWrapperPass>();
433   AU.addRequired<TargetLibraryInfoWrapperPass>();
434 }
435
436 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
437                                Constant *&Selector, BasicBlock *&NextBB);
438
439 // Finds blocks reachable from the starting set Worklist. Does not follow unwind
440 // edges or blocks listed in StopPoints.
441 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
442                                 SetVector<BasicBlock *> &Worklist,
443                                 const SetVector<BasicBlock *> *StopPoints) {
444   while (!Worklist.empty()) {
445     BasicBlock *BB = Worklist.pop_back_val();
446
447     // Don't cross blocks that we should stop at.
448     if (StopPoints && StopPoints->count(BB))
449       continue;
450
451     if (!ReachableBBs.insert(BB).second)
452       continue; // Already visited.
453
454     // Don't follow unwind edges of invokes.
455     if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
456       Worklist.insert(II->getNormalDest());
457       continue;
458     }
459
460     // Otherwise, follow all successors.
461     Worklist.insert(succ_begin(BB), succ_end(BB));
462   }
463 }
464
465 // Attempt to find an instruction where a block can be split before
466 // a call to llvm.eh.begincatch and its operands.  If the block
467 // begins with the begincatch call or one of its adjacent operands
468 // the block will not be split.
469 static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
470                                              IntrinsicInst *II) {
471   // If the begincatch call is already the first instruction in the block,
472   // don't split.
473   Instruction *FirstNonPHI = BB->getFirstNonPHI();
474   if (II == FirstNonPHI)
475     return nullptr;
476
477   // If either operand is in the same basic block as the instruction and
478   // isn't used by another instruction before the begincatch call, include it
479   // in the split block.
480   auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
481   auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
482
483   Instruction *I = II->getPrevNode();
484   Instruction *LastI = II;
485
486   while (I == Op0 || I == Op1) {
487     // If the block begins with one of the operands and there are no other
488     // instructions between the operand and the begincatch call, don't split.
489     if (I == FirstNonPHI)
490       return nullptr;
491
492     LastI = I;
493     I = I->getPrevNode();
494   }
495
496   // If there is at least one instruction in the block before the begincatch
497   // call and its operands, split the block at either the begincatch or
498   // its operand.
499   return LastI;
500 }
501
502 /// Find all points where exceptional control rejoins normal control flow via
503 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
504 void WinEHPrepare::findCXXEHReturnPoints(
505     Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
506   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
507     BasicBlock *BB = BBI;
508     for (Instruction &I : *BB) {
509       if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
510         Instruction *SplitPt =
511             findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
512         if (SplitPt) {
513           // Split the block before the llvm.eh.begincatch call to allow
514           // cleanup and catch code to be distinguished later.
515           // Do not update BBI because we still need to process the
516           // portion of the block that we are splitting off.
517           SplitBlock(BB, SplitPt, DT);
518           break;
519         }
520       }
521       if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
522         // Split the block after the call to llvm.eh.endcatch if there is
523         // anything other than an unconditional branch, or if the successor
524         // starts with a phi.
525         auto *Br = dyn_cast<BranchInst>(I.getNextNode());
526         if (!Br || !Br->isUnconditional() ||
527             isa<PHINode>(Br->getSuccessor(0)->begin())) {
528           DEBUG(dbgs() << "splitting block " << BB->getName()
529                        << " with llvm.eh.endcatch\n");
530           BBI = SplitBlock(BB, I.getNextNode(), DT);
531         }
532         // The next BB is normal control flow.
533         EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
534         break;
535       }
536     }
537   }
538 }
539
540 static bool isCatchAllLandingPad(const BasicBlock *BB) {
541   const LandingPadInst *LP = BB->getLandingPadInst();
542   if (!LP)
543     return false;
544   unsigned N = LP->getNumClauses();
545   return (N > 0 && LP->isCatch(N - 1) &&
546           isa<ConstantPointerNull>(LP->getClause(N - 1)));
547 }
548
549 /// Find all points where exceptions control rejoins normal control flow via
550 /// selector dispatch.
551 void WinEHPrepare::findSEHEHReturnPoints(
552     Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
553   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
554     BasicBlock *BB = BBI;
555     // If the landingpad is a catch-all, treat the whole lpad as if it is
556     // reachable from normal control flow.
557     // FIXME: This is imprecise. We need a better way of identifying where a
558     // catch-all starts and cleanups stop. As far as LLVM is concerned, there
559     // is no difference.
560     if (isCatchAllLandingPad(BB)) {
561       EHReturnBlocks.insert(BB);
562       continue;
563     }
564
565     BasicBlock *CatchHandler;
566     BasicBlock *NextBB;
567     Constant *Selector;
568     if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
569       // Split the edge if there are multiple predecessors. This creates a place
570       // where we can insert EH recovery code.
571       if (!CatchHandler->getSinglePredecessor()) {
572         DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
573                      << " to " << CatchHandler->getName() << '\n');
574         BBI = CatchHandler = SplitCriticalEdge(
575             BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
576       }
577       EHReturnBlocks.insert(CatchHandler);
578     }
579   }
580 }
581
582 void WinEHPrepare::identifyEHBlocks(Function &F, 
583                                     SmallVectorImpl<LandingPadInst *> &LPads) {
584   DEBUG(dbgs() << "Demoting values live across exception handlers in function "
585                << F.getName() << '\n');
586
587   // Build a set of all non-exceptional blocks and exceptional blocks.
588   // - Non-exceptional blocks are blocks reachable from the entry block while
589   //   not following invoke unwind edges.
590   // - Exceptional blocks are blocks reachable from landingpads. Analysis does
591   //   not follow llvm.eh.endcatch blocks, which mark a transition from
592   //   exceptional to normal control.
593
594   if (Personality == EHPersonality::MSVC_CXX)
595     findCXXEHReturnPoints(F, EHReturnBlocks);
596   else
597     findSEHEHReturnPoints(F, EHReturnBlocks);
598
599   DEBUG({
600     dbgs() << "identified the following blocks as EH return points:\n";
601     for (BasicBlock *BB : EHReturnBlocks)
602       dbgs() << "  " << BB->getName() << '\n';
603   });
604
605 // Join points should not have phis at this point, unless they are a
606 // landingpad, in which case we will demote their phis later.
607 #ifndef NDEBUG
608   for (BasicBlock *BB : EHReturnBlocks)
609     assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
610            "non-lpad EH return block has phi");
611 #endif
612
613   // Normal blocks are the blocks reachable from the entry block and all EH
614   // return points.
615   SetVector<BasicBlock *> Worklist;
616   Worklist = EHReturnBlocks;
617   Worklist.insert(&F.getEntryBlock());
618   findReachableBlocks(NormalBlocks, Worklist, nullptr);
619   DEBUG({
620     dbgs() << "marked the following blocks as normal:\n";
621     for (BasicBlock *BB : NormalBlocks)
622       dbgs() << "  " << BB->getName() << '\n';
623   });
624
625   // Exceptional blocks are the blocks reachable from landingpads that don't
626   // cross EH return points.
627   Worklist.clear();
628   for (auto *LPI : LPads)
629     Worklist.insert(LPI->getParent());
630   findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
631   DEBUG({
632     dbgs() << "marked the following blocks as exceptional:\n";
633     for (BasicBlock *BB : EHBlocks)
634       dbgs() << "  " << BB->getName() << '\n';
635   });
636
637 }
638
639 /// Ensure that all values live into and out of exception handlers are stored
640 /// in memory.
641 /// FIXME: This falls down when values are defined in one handler and live into
642 /// another handler. For example, a cleanup defines a value used only by a
643 /// catch handler.
644 void WinEHPrepare::demoteValuesLiveAcrossHandlers(
645     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
646   DEBUG(dbgs() << "Demoting values live across exception handlers in function "
647                << F.getName() << '\n');
648
649   // identifyEHBlocks() should have been called before this function.
650   assert(!NormalBlocks.empty());
651
652   // Try to avoid demoting EH pointer and selector values. They get in the way
653   // of our pattern matching.
654   SmallPtrSet<Instruction *, 10> EHVals;
655   for (BasicBlock &BB : F) {
656     LandingPadInst *LP = BB.getLandingPadInst();
657     if (!LP)
658       continue;
659     EHVals.insert(LP);
660     for (User *U : LP->users()) {
661       auto *EI = dyn_cast<ExtractValueInst>(U);
662       if (!EI)
663         continue;
664       EHVals.insert(EI);
665       for (User *U2 : EI->users()) {
666         if (auto *PN = dyn_cast<PHINode>(U2))
667           EHVals.insert(PN);
668       }
669     }
670   }
671
672   SetVector<Argument *> ArgsToDemote;
673   SetVector<Instruction *> InstrsToDemote;
674   for (BasicBlock &BB : F) {
675     bool IsNormalBB = NormalBlocks.count(&BB);
676     bool IsEHBB = EHBlocks.count(&BB);
677     if (!IsNormalBB && !IsEHBB)
678       continue; // Blocks that are neither normal nor EH are unreachable.
679     for (Instruction &I : BB) {
680       for (Value *Op : I.operands()) {
681         // Don't demote static allocas, constants, and labels.
682         if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
683           continue;
684         auto *AI = dyn_cast<AllocaInst>(Op);
685         if (AI && AI->isStaticAlloca())
686           continue;
687
688         if (auto *Arg = dyn_cast<Argument>(Op)) {
689           if (IsEHBB) {
690             DEBUG(dbgs() << "Demoting argument " << *Arg
691                          << " used by EH instr: " << I << "\n");
692             ArgsToDemote.insert(Arg);
693           }
694           continue;
695         }
696
697         // Don't demote EH values.
698         auto *OpI = cast<Instruction>(Op);
699         if (EHVals.count(OpI))
700           continue;
701
702         BasicBlock *OpBB = OpI->getParent();
703         // If a value is produced and consumed in the same BB, we don't need to
704         // demote it.
705         if (OpBB == &BB)
706           continue;
707         bool IsOpNormalBB = NormalBlocks.count(OpBB);
708         bool IsOpEHBB = EHBlocks.count(OpBB);
709         if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
710           DEBUG({
711             dbgs() << "Demoting instruction live in-out from EH:\n";
712             dbgs() << "Instr: " << *OpI << '\n';
713             dbgs() << "User: " << I << '\n';
714           });
715           InstrsToDemote.insert(OpI);
716         }
717       }
718     }
719   }
720
721   // Demote values live into and out of handlers.
722   // FIXME: This demotion is inefficient. We should insert spills at the point
723   // of definition, insert one reload in each handler that uses the value, and
724   // insert reloads in the BB used to rejoin normal control flow.
725   Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
726   for (Instruction *I : InstrsToDemote)
727     DemoteRegToStack(*I, false, AllocaInsertPt);
728
729   // Demote arguments separately, and only for uses in EH blocks.
730   for (Argument *Arg : ArgsToDemote) {
731     auto *Slot = new AllocaInst(Arg->getType(), nullptr,
732                                 Arg->getName() + ".reg2mem", AllocaInsertPt);
733     SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
734     for (User *U : Users) {
735       auto *I = dyn_cast<Instruction>(U);
736       if (I && EHBlocks.count(I->getParent())) {
737         auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
738         U->replaceUsesOfWith(Arg, Reload);
739       }
740     }
741     new StoreInst(Arg, Slot, AllocaInsertPt);
742   }
743
744   // Demote landingpad phis, as the landingpad will be removed from the machine
745   // CFG.
746   for (LandingPadInst *LPI : LPads) {
747     BasicBlock *BB = LPI->getParent();
748     while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
749       DemotePHIToStack(Phi, AllocaInsertPt);
750   }
751
752   DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
753                << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
754 }
755
756 bool WinEHPrepare::prepareExceptionHandlers(
757     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
758   // Don't run on functions that are already prepared.
759   for (LandingPadInst *LPad : LPads) {
760     BasicBlock *LPadBB = LPad->getParent();
761     for (Instruction &Inst : *LPadBB)
762       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
763         return false;
764   }
765
766   identifyEHBlocks(F, LPads);
767   demoteValuesLiveAcrossHandlers(F, LPads);
768
769   // These containers are used to re-map frame variables that are used in
770   // outlined catch and cleanup handlers.  They will be populated as the
771   // handlers are outlined.
772   FrameVarInfoMap FrameVarInfo;
773
774   bool HandlersOutlined = false;
775
776   Module *M = F.getParent();
777   LLVMContext &Context = M->getContext();
778
779   // Create a new function to receive the handler contents.
780   PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
781   Type *Int32Type = Type::getInt32Ty(Context);
782   Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
783
784   if (isAsynchronousEHPersonality(Personality)) {
785     // FIXME: Switch the ehptr type to i32 and then switch this.
786     SEHExceptionCodeSlot =
787         new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
788                        F.getEntryBlock().getFirstInsertionPt());
789   }
790
791   // In order to handle the case where one outlined catch handler returns
792   // to a block within another outlined catch handler that would otherwise
793   // be unreachable, we need to outline the nested landing pad before we
794   // outline the landing pad which encloses it.
795   if (!isAsynchronousEHPersonality(Personality))
796     std::sort(LPads.begin(), LPads.end(),
797               [this](LandingPadInst *const &L, LandingPadInst *const &R) {
798                 return DT->properlyDominates(R->getParent(), L->getParent());
799               });
800
801   // This container stores the llvm.eh.recover and IndirectBr instructions
802   // that make up the body of each landing pad after it has been outlined.
803   // We need to defer the population of the target list for the indirectbr
804   // until all landing pads have been outlined so that we can handle the
805   // case of blocks in the target that are reached only from nested
806   // landing pads.
807   SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
808
809   for (LandingPadInst *LPad : LPads) {
810     // Look for evidence that this landingpad has already been processed.
811     bool LPadHasActionList = false;
812     BasicBlock *LPadBB = LPad->getParent();
813     for (Instruction &Inst : *LPadBB) {
814       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
815         LPadHasActionList = true;
816         break;
817       }
818     }
819
820     // If we've already outlined the handlers for this landingpad,
821     // there's nothing more to do here.
822     if (LPadHasActionList)
823       continue;
824
825     // If either of the values in the aggregate returned by the landing pad is
826     // extracted and stored to memory, promote the stored value to a register.
827     promoteLandingPadValues(LPad);
828
829     LandingPadActions Actions;
830     mapLandingPadBlocks(LPad, Actions);
831
832     HandlersOutlined |= !Actions.actions().empty();
833     for (ActionHandler *Action : Actions) {
834       if (Action->hasBeenProcessed())
835         continue;
836       BasicBlock *StartBB = Action->getStartBlock();
837
838       // SEH doesn't do any outlining for catches. Instead, pass the handler
839       // basic block addr to llvm.eh.actions and list the block as a return
840       // target.
841       if (isAsynchronousEHPersonality(Personality)) {
842         if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
843           processSEHCatchHandler(CatchAction, StartBB);
844           continue;
845         }
846       }
847
848       outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
849     }
850
851     // Split the block after the landingpad instruction so that it is just a
852     // call to llvm.eh.actions followed by indirectbr.
853     assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
854     SplitBlock(LPadBB, LPad->getNextNode(), DT);
855     // Erase the branch inserted by the split so we can insert indirectbr.
856     LPadBB->getTerminator()->eraseFromParent();
857
858     // Replace all extracted values with undef and ultimately replace the
859     // landingpad with undef.
860     SmallVector<Instruction *, 4> SEHCodeUses;
861     SmallVector<Instruction *, 4> EHUndefs;
862     for (User *U : LPad->users()) {
863       auto *E = dyn_cast<ExtractValueInst>(U);
864       if (!E)
865         continue;
866       assert(E->getNumIndices() == 1 &&
867              "Unexpected operation: extracting both landing pad values");
868       unsigned Idx = *E->idx_begin();
869       assert((Idx == 0 || Idx == 1) && "unexpected index");
870       if (Idx == 0 && isAsynchronousEHPersonality(Personality))
871         SEHCodeUses.push_back(E);
872       else
873         EHUndefs.push_back(E);
874     }
875     for (Instruction *E : EHUndefs) {
876       E->replaceAllUsesWith(UndefValue::get(E->getType()));
877       E->eraseFromParent();
878     }
879     LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
880
881     // Rewrite uses of the exception pointer to loads of an alloca.
882     while (!SEHCodeUses.empty()) {
883       Instruction *E = SEHCodeUses.pop_back_val();
884       SmallVector<Use *, 4> Uses;
885       for (Use &U : E->uses())
886         Uses.push_back(&U);
887       for (Use *U : Uses) {
888         auto *I = cast<Instruction>(U->getUser());
889         if (isa<ResumeInst>(I))
890           continue;
891         if (auto *Phi = dyn_cast<PHINode>(I))
892           SEHCodeUses.push_back(Phi);
893         else
894           U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
895       }
896       E->replaceAllUsesWith(UndefValue::get(E->getType()));
897       E->eraseFromParent();
898     }
899
900     // Add a call to describe the actions for this landing pad.
901     std::vector<Value *> ActionArgs;
902     for (ActionHandler *Action : Actions) {
903       // Action codes from docs are: 0 cleanup, 1 catch.
904       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
905         ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
906         ActionArgs.push_back(CatchAction->getSelector());
907         // Find the frame escape index of the exception object alloca in the
908         // parent.
909         int FrameEscapeIdx = -1;
910         Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
911         if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
912           auto I = FrameVarInfo.find(EHObj);
913           assert(I != FrameVarInfo.end() &&
914                  "failed to map llvm.eh.begincatch var");
915           FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
916         }
917         ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
918       } else {
919         ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
920       }
921       ActionArgs.push_back(Action->getHandlerBlockOrFunc());
922     }
923     CallInst *Recover =
924         CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
925
926     SetVector<BasicBlock *> ReturnTargets;
927     for (ActionHandler *Action : Actions) {
928       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
929         const auto &CatchTargets = CatchAction->getReturnTargets();
930         ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
931       }
932     }
933     IndirectBrInst *Branch =
934         IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
935     for (BasicBlock *Target : ReturnTargets)
936       Branch->addDestination(Target);
937
938     if (!isAsynchronousEHPersonality(Personality)) {
939       // C++ EH must repopulate the targets later to handle the case of
940       // targets that are reached indirectly through nested landing pads.
941       LPadImpls.push_back(std::make_pair(Recover, Branch));
942     }
943
944   } // End for each landingpad
945
946   // If nothing got outlined, there is no more processing to be done.
947   if (!HandlersOutlined)
948     return false;
949
950   // Replace any nested landing pad stubs with the correct action handler.
951   // This must be done before we remove unreachable blocks because it
952   // cleans up references to outlined blocks that will be deleted.
953   for (auto &LPadPair : NestedLPtoOriginalLP)
954     completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
955   NestedLPtoOriginalLP.clear();
956
957   // Update the indirectbr instructions' target lists if necessary.
958   SetVector<BasicBlock*> CheckedTargets;
959   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
960   for (auto &LPadImplPair : LPadImpls) {
961     IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
962     IndirectBrInst *Branch = LPadImplPair.second;
963
964     // Get a list of handlers called by 
965     parseEHActions(Recover, ActionList);
966
967     // Add an indirect branch listing possible successors of the catch handlers.
968     SetVector<BasicBlock *> ReturnTargets;
969     for (const auto &Action : ActionList) {
970       if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
971         Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
972         getPossibleReturnTargets(&F, Handler, ReturnTargets);
973       }
974     }
975     ActionList.clear();
976     // Clear any targets we already knew about.
977     for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
978       BasicBlock *KnownTarget = Branch->getDestination(I);
979       if (ReturnTargets.count(KnownTarget))
980         ReturnTargets.remove(KnownTarget);
981     }
982     for (BasicBlock *Target : ReturnTargets) {
983       Branch->addDestination(Target);
984       // The target may be a block that we excepted to get pruned.
985       // If it is, it may contain a call to llvm.eh.endcatch.
986       if (CheckedTargets.insert(Target)) {
987         // Earlier preparations guarantee that all calls to llvm.eh.endcatch
988         // will be followed by an unconditional branch.
989         auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
990         if (Br && Br->isUnconditional() &&
991             Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
992           Instruction *Prev = Br->getPrevNode();
993           if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
994             Prev->eraseFromParent();
995         }
996       }
997     }
998   }
999   LPadImpls.clear();
1000
1001   F.addFnAttr("wineh-parent", F.getName());
1002
1003   // Delete any blocks that were only used by handlers that were outlined above.
1004   removeUnreachableBlocks(F);
1005
1006   BasicBlock *Entry = &F.getEntryBlock();
1007   IRBuilder<> Builder(F.getParent()->getContext());
1008   Builder.SetInsertPoint(Entry->getFirstInsertionPt());
1009
1010   Function *FrameEscapeFn =
1011       Intrinsic::getDeclaration(M, Intrinsic::localescape);
1012   Function *RecoverFrameFn =
1013       Intrinsic::getDeclaration(M, Intrinsic::localrecover);
1014   SmallVector<Value *, 8> AllocasToEscape;
1015
1016   // Scan the entry block for an existing call to llvm.localescape. We need to
1017   // keep escaping those objects.
1018   for (Instruction &I : F.front()) {
1019     auto *II = dyn_cast<IntrinsicInst>(&I);
1020     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1021       auto Args = II->arg_operands();
1022       AllocasToEscape.append(Args.begin(), Args.end());
1023       II->eraseFromParent();
1024       break;
1025     }
1026   }
1027
1028   // Finally, replace all of the temporary allocas for frame variables used in
1029   // the outlined handlers with calls to llvm.localrecover.
1030   for (auto &VarInfoEntry : FrameVarInfo) {
1031     Value *ParentVal = VarInfoEntry.first;
1032     TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
1033     AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
1034
1035     // FIXME: We should try to sink unescaped allocas from the parent frame into
1036     // the child frame. If the alloca is escaped, we have to use the lifetime
1037     // markers to ensure that the alloca is only live within the child frame.
1038
1039     // Add this alloca to the list of things to escape.
1040     AllocasToEscape.push_back(ParentAlloca);
1041
1042     // Next replace all outlined allocas that are mapped to it.
1043     for (AllocaInst *TempAlloca : Allocas) {
1044       if (TempAlloca == getCatchObjectSentinel())
1045         continue; // Skip catch parameter sentinels.
1046       Function *HandlerFn = TempAlloca->getParent()->getParent();
1047       llvm::Value *FP = HandlerToParentFP[HandlerFn];
1048       assert(FP);
1049
1050       // FIXME: Sink this localrecover into the blocks where it is used.
1051       Builder.SetInsertPoint(TempAlloca);
1052       Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1053       Value *RecoverArgs[] = {
1054           Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
1055           llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
1056       Instruction *RecoveredAlloca =
1057           Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1058
1059       // Add a pointer bitcast if the alloca wasn't an i8.
1060       if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1061         RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
1062         RecoveredAlloca = cast<Instruction>(
1063             Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
1064       }
1065       TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1066       TempAlloca->removeFromParent();
1067       RecoveredAlloca->takeName(TempAlloca);
1068       delete TempAlloca;
1069     }
1070   } // End for each FrameVarInfo entry.
1071
1072   // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
1073   // block.
1074   Builder.SetInsertPoint(&F.getEntryBlock().back());
1075   Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1076
1077   if (SEHExceptionCodeSlot) {
1078     if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1079       SmallPtrSet<BasicBlock *, 4> UserBlocks;
1080       for (User *U : SEHExceptionCodeSlot->users()) {
1081         if (auto *Inst = dyn_cast<Instruction>(U))
1082           UserBlocks.insert(Inst->getParent());
1083       }
1084       PromoteMemToReg(SEHExceptionCodeSlot, *DT);
1085       // After the promotion, kill off dead instructions.
1086       for (BasicBlock *BB : UserBlocks)
1087         SimplifyInstructionsInBlock(BB, LibInfo);
1088     }
1089   }
1090
1091   // Clean up the handler action maps we created for this function
1092   DeleteContainerSeconds(CatchHandlerMap);
1093   CatchHandlerMap.clear();
1094   DeleteContainerSeconds(CleanupHandlerMap);
1095   CleanupHandlerMap.clear();
1096   HandlerToParentFP.clear();
1097   DT = nullptr;
1098   LibInfo = nullptr;
1099   SEHExceptionCodeSlot = nullptr;
1100   EHBlocks.clear();
1101   NormalBlocks.clear();
1102   EHReturnBlocks.clear();
1103
1104   return HandlersOutlined;
1105 }
1106
1107 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1108   // If the return values of the landing pad instruction are extracted and
1109   // stored to memory, we want to promote the store locations to reg values.
1110   SmallVector<AllocaInst *, 2> EHAllocas;
1111
1112   // The landingpad instruction returns an aggregate value.  Typically, its
1113   // value will be passed to a pair of extract value instructions and the
1114   // results of those extracts are often passed to store instructions.
1115   // In unoptimized code the stored value will often be loaded and then stored
1116   // again.
1117   for (auto *U : LPad->users()) {
1118     ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1119     if (!Extract)
1120       continue;
1121
1122     for (auto *EU : Extract->users()) {
1123       if (auto *Store = dyn_cast<StoreInst>(EU)) {
1124         auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1125         EHAllocas.push_back(AV);
1126       }
1127     }
1128   }
1129
1130   // We can't do this without a dominator tree.
1131   assert(DT);
1132
1133   if (!EHAllocas.empty()) {
1134     PromoteMemToReg(EHAllocas, *DT);
1135     EHAllocas.clear();
1136   }
1137
1138   // After promotion, some extracts may be trivially dead. Remove them.
1139   SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1140   for (auto *U : Users)
1141     RecursivelyDeleteTriviallyDeadInstructions(U);
1142 }
1143
1144 void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1145                                             Function *HandlerF,
1146                                             SetVector<BasicBlock*> &Targets) {
1147   for (BasicBlock &BB : *HandlerF) {
1148     // If the handler contains landing pads, check for any
1149     // handlers that may return directly to a block in the
1150     // parent function.
1151     if (auto *LPI = BB.getLandingPadInst()) {
1152       IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
1153       SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
1154       parseEHActions(Recover, ActionList);
1155       for (const auto &Action : ActionList) {
1156         if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
1157           Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1158           getPossibleReturnTargets(ParentF, NestedF, Targets);
1159         }
1160       }
1161     }
1162
1163     auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1164     if (!Ret)
1165       continue;
1166
1167     // Handler functions must always return a block address.
1168     BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1169
1170     // If this is the handler for a nested landing pad, the
1171     // return address may have been remapped to a block in the
1172     // parent handler.  We're not interested in those.
1173     if (BA->getFunction() != ParentF)
1174       continue;
1175
1176     Targets.insert(BA->getBasicBlock());
1177   }
1178 }
1179
1180 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1181                                             LandingPadInst *OutlinedLPad,
1182                                             const LandingPadInst *OriginalLPad,
1183                                             FrameVarInfoMap &FrameVarInfo) {
1184   // Get the nested block and erase the unreachable instruction that was
1185   // temporarily inserted as its terminator.
1186   LLVMContext &Context = ParentFn->getContext();
1187   BasicBlock *OutlinedBB = OutlinedLPad->getParent();
1188   // If the nested landing pad was outlined before the landing pad that enclosed
1189   // it, it will already be in outlined form.  In that case, we just need to see
1190   // if the returns and the enclosing branch instruction need to be updated.
1191   IndirectBrInst *Branch =
1192       dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1193   if (!Branch) {
1194     // If the landing pad wasn't in outlined form, it should be a stub with
1195     // an unreachable terminator.
1196     assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1197     OutlinedBB->getTerminator()->eraseFromParent();
1198     // That should leave OutlinedLPad as the last instruction in its block.
1199     assert(&OutlinedBB->back() == OutlinedLPad);
1200   }
1201
1202   // The original landing pad will have already had its action intrinsic
1203   // built by the outlining loop.  We need to clone that into the outlined
1204   // location.  It may also be necessary to add references to the exception
1205   // variables to the outlined handler in which this landing pad is nested
1206   // and remap return instructions in the nested handlers that should return
1207   // to an address in the outlined handler.
1208   Function *OutlinedHandlerFn = OutlinedBB->getParent();
1209   BasicBlock::const_iterator II = OriginalLPad;
1210   ++II;
1211   // The instruction after the landing pad should now be a call to eh.actions.
1212   const Instruction *Recover = II;
1213   const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
1214
1215   // Remap the return target in the nested handler.
1216   SmallVector<BlockAddress *, 4> ActionTargets;
1217   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
1218   parseEHActions(EHActions, ActionList);
1219   for (const auto &Action : ActionList) {
1220     auto *Catch = dyn_cast<CatchHandler>(Action.get());
1221     if (!Catch)
1222       continue;
1223     // The dyn_cast to function here selects C++ catch handlers and skips
1224     // SEH catch handlers.
1225     auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1226     if (!Handler)
1227       continue;
1228     // Visit all the return instructions, looking for places that return
1229     // to a location within OutlinedHandlerFn.
1230     for (BasicBlock &NestedHandlerBB : *Handler) {
1231       auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1232       if (!Ret)
1233         continue;
1234
1235       // Handler functions must always return a block address.
1236       BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1237       // The original target will have been in the main parent function,
1238       // but if it is the address of a block that has been outlined, it
1239       // should be a block that was outlined into OutlinedHandlerFn.
1240       assert(BA->getFunction() == ParentFn);
1241
1242       // Ignore targets that aren't part of an outlined handler function.
1243       if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1244         continue;
1245
1246       // If the return value is the address ofF a block that we
1247       // previously outlined into the parent handler function, replace
1248       // the return instruction and add the mapped target to the list
1249       // of possible return addresses.
1250       BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1251       assert(MappedBB->getParent() == OutlinedHandlerFn);
1252       BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1253       Ret->eraseFromParent();
1254       ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1255       ActionTargets.push_back(NewBA);
1256     }
1257   }
1258   ActionList.clear();
1259
1260   if (Branch) {
1261     // If the landing pad was already in outlined form, just update its targets.
1262     for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1263       Branch->removeDestination(I);
1264     // Add the previously collected action targets.
1265     for (auto *Target : ActionTargets)
1266       Branch->addDestination(Target->getBasicBlock());
1267   } else {
1268     // If the landing pad was previously stubbed out, fill in its outlined form.
1269     IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1270     OutlinedBB->getInstList().push_back(NewEHActions);
1271
1272     // Insert an indirect branch into the outlined landing pad BB.
1273     IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1274     // Add the previously collected action targets.
1275     for (auto *Target : ActionTargets)
1276       IBr->addDestination(Target->getBasicBlock());
1277   }
1278 }
1279
1280 // This function examines a block to determine whether the block ends with a
1281 // conditional branch to a catch handler based on a selector comparison.
1282 // This function is used both by the WinEHPrepare::findSelectorComparison() and
1283 // WinEHCleanupDirector::handleTypeIdFor().
1284 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1285                                Constant *&Selector, BasicBlock *&NextBB) {
1286   ICmpInst::Predicate Pred;
1287   BasicBlock *TBB, *FBB;
1288   Value *LHS, *RHS;
1289
1290   if (!match(BB->getTerminator(),
1291              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1292     return false;
1293
1294   if (!match(LHS,
1295              m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1296       !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1297     return false;
1298
1299   if (Pred == CmpInst::ICMP_EQ) {
1300     CatchHandler = TBB;
1301     NextBB = FBB;
1302     return true;
1303   }
1304
1305   if (Pred == CmpInst::ICMP_NE) {
1306     CatchHandler = FBB;
1307     NextBB = TBB;
1308     return true;
1309   }
1310
1311   return false;
1312 }
1313
1314 static bool isCatchBlock(BasicBlock *BB) {
1315   for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1316        II != IE; ++II) {
1317     if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1318       return true;
1319   }
1320   return false;
1321 }
1322
1323 static BasicBlock *createStubLandingPad(Function *Handler) {
1324   // FIXME: Finish this!
1325   LLVMContext &Context = Handler->getContext();
1326   BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1327   Handler->getBasicBlockList().push_back(StubBB);
1328   IRBuilder<> Builder(StubBB);
1329   LandingPadInst *LPad = Builder.CreateLandingPad(
1330       llvm::StructType::get(Type::getInt8PtrTy(Context),
1331                             Type::getInt32Ty(Context), nullptr),
1332       0);
1333   // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1334   Function *ActionIntrin =
1335       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
1336   Builder.CreateCall(ActionIntrin, {}, "recover");
1337   LPad->setCleanup(true);
1338   Builder.CreateUnreachable();
1339   return StubBB;
1340 }
1341
1342 // Cycles through the blocks in an outlined handler function looking for an
1343 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1344 // landing pad if none is found.  The code that generates the .xdata tables for
1345 // the handler needs at least one landing pad to identify the parent function's
1346 // personality.
1347 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
1348   ReturnInst *Ret = nullptr;
1349   UnreachableInst *Unreached = nullptr;
1350   for (BasicBlock &BB : *Handler) {
1351     TerminatorInst *Terminator = BB.getTerminator();
1352     // If we find an invoke, there is nothing to be done.
1353     auto *II = dyn_cast<InvokeInst>(Terminator);
1354     if (II)
1355       return;
1356     // If we've already recorded a return instruction, keep looking for invokes.
1357     if (!Ret)
1358       Ret = dyn_cast<ReturnInst>(Terminator);
1359     // If we haven't recorded an unreachable instruction, try this terminator.
1360     if (!Unreached)
1361       Unreached = dyn_cast<UnreachableInst>(Terminator);
1362   }
1363
1364   // If we got this far, the handler contains no invokes.  We should have seen
1365   // at least one return or unreachable instruction.  We'll insert an invoke of
1366   // llvm.donothing ahead of that instruction.
1367   assert(Ret || Unreached);
1368   TerminatorInst *Term;
1369   if (Ret)
1370     Term = Ret;
1371   else
1372     Term = Unreached;
1373   BasicBlock *OldRetBB = Term->getParent();
1374   BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
1375   // SplitBlock adds an unconditional branch instruction at the end of the
1376   // parent block.  We want to replace that with an invoke call, so we can
1377   // erase it now.
1378   OldRetBB->getTerminator()->eraseFromParent();
1379   BasicBlock *StubLandingPad = createStubLandingPad(Handler);
1380   Function *F =
1381       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1382   InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1383 }
1384
1385 // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1386 // usually doesn't build LLVM IR, so that's probably the wrong place.
1387 Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1388                                           const Twine &Name, Module *M,
1389                                           Value *&ParentFP) {
1390   // x64 uses a two-argument prototype where the parent FP is the second
1391   // argument. x86 uses no arguments, just the incoming EBP value.
1392   LLVMContext &Context = M->getContext();
1393   Type *Int8PtrType = Type::getInt8PtrTy(Context);
1394   FunctionType *FnType;
1395   if (TheTriple.getArch() == Triple::x86_64) {
1396     Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1397     FnType = FunctionType::get(RetTy, ArgTys, false);
1398   } else {
1399     FnType = FunctionType::get(RetTy, None, false);
1400   }
1401
1402   Function *Handler =
1403       Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1404   BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1405   Handler->getBasicBlockList().push_front(Entry);
1406   if (TheTriple.getArch() == Triple::x86_64) {
1407     ParentFP = &(Handler->getArgumentList().back());
1408   } else {
1409     assert(M);
1410     Function *FrameAddressFn =
1411         Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
1412     Function *RecoverFPFn =
1413         Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1414     IRBuilder<> Builder(&Handler->getEntryBlock());
1415     Value *EBP =
1416         Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1417     Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1418     ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
1419   }
1420   return Handler;
1421 }
1422
1423 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1424                                   LandingPadInst *LPad, BasicBlock *StartBB,
1425                                   FrameVarInfoMap &VarInfo) {
1426   Module *M = SrcFn->getParent();
1427   LLVMContext &Context = M->getContext();
1428   Type *Int8PtrType = Type::getInt8PtrTy(Context);
1429
1430   // Create a new function to receive the handler contents.
1431   Value *ParentFP;
1432   Function *Handler;
1433   if (Action->getType() == Catch) {
1434     Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
1435                                 ParentFP);
1436   } else {
1437     Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
1438                                 SrcFn->getName() + ".cleanup", M, ParentFP);
1439   }
1440   Handler->setPersonalityFn(SrcFn->getPersonalityFn());
1441   HandlerToParentFP[Handler] = ParentFP;
1442   Handler->addFnAttr("wineh-parent", SrcFn->getName());
1443   BasicBlock *Entry = &Handler->getEntryBlock();
1444
1445   // Generate a standard prolog to setup the frame recovery structure.
1446   IRBuilder<> Builder(Context);
1447   Builder.SetInsertPoint(Entry);
1448   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1449
1450   std::unique_ptr<WinEHCloningDirectorBase> Director;
1451
1452   ValueToValueMapTy VMap;
1453
1454   LandingPadMap &LPadMap = LPadMaps[LPad];
1455   if (!LPadMap.isInitialized())
1456     LPadMap.mapLandingPad(LPad);
1457   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1458     Constant *Sel = CatchAction->getSelector();
1459     Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1460                                           LPadMap, NestedLPtoOriginalLP, DT,
1461                                           EHBlocks));
1462     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1463                           ConstantInt::get(Type::getInt32Ty(Context), 1));
1464   } else {
1465     Director.reset(
1466         new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
1467     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1468                           UndefValue::get(Type::getInt32Ty(Context)));
1469   }
1470
1471   SmallVector<ReturnInst *, 8> Returns;
1472   ClonedCodeInfo OutlinedFunctionInfo;
1473
1474   // If the start block contains PHI nodes, we need to map them.
1475   BasicBlock::iterator II = StartBB->begin();
1476   while (auto *PN = dyn_cast<PHINode>(II)) {
1477     bool Mapped = false;
1478     // Look for PHI values that we have already mapped (such as the selector).
1479     for (Value *Val : PN->incoming_values()) {
1480       if (VMap.count(Val)) {
1481         VMap[PN] = VMap[Val];
1482         Mapped = true;
1483       }
1484     }
1485     // If we didn't find a match for this value, map it as an undef.
1486     if (!Mapped) {
1487       VMap[PN] = UndefValue::get(PN->getType());
1488     }
1489     ++II;
1490   }
1491
1492   // The landing pad value may be used by PHI nodes.  It will ultimately be
1493   // eliminated, but we need it in the map for intermediate handling.
1494   VMap[LPad] = UndefValue::get(LPad->getType());
1495
1496   // Skip over PHIs and, if applicable, landingpad instructions.
1497   II = StartBB->getFirstInsertionPt();
1498
1499   CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1500                             /*ModuleLevelChanges=*/false, Returns, "",
1501                             &OutlinedFunctionInfo, Director.get());
1502
1503   // Move all the instructions in the cloned "entry" block into our entry block.
1504   // Depending on how the parent function was laid out, the block that will
1505   // correspond to the outlined entry block may not be the first block in the
1506   // list.  We can recognize it, however, as the cloned block which has no
1507   // predecessors.  Any other block wouldn't have been cloned if it didn't
1508   // have a predecessor which was also cloned.
1509   Function::iterator ClonedIt = std::next(Function::iterator(Entry));
1510   while (!pred_empty(ClonedIt))
1511     ++ClonedIt;
1512   BasicBlock *ClonedEntryBB = ClonedIt;
1513   assert(ClonedEntryBB);
1514   Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1515   ClonedEntryBB->eraseFromParent();
1516
1517   // Make sure we can identify the handler's personality later.
1518   addStubInvokeToHandlerIfNeeded(Handler);
1519
1520   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1521     WinEHCatchDirector *CatchDirector =
1522         reinterpret_cast<WinEHCatchDirector *>(Director.get());
1523     CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1524     CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1525
1526     // Look for blocks that are not part of the landing pad that we just
1527     // outlined but terminate with a call to llvm.eh.endcatch and a
1528     // branch to a block that is in the handler we just outlined.
1529     // These blocks will be part of a nested landing pad that intends to
1530     // return to an address in this handler.  This case is best handled
1531     // after both landing pads have been outlined, so for now we'll just
1532     // save the association of the blocks in LPadTargetBlocks.  The
1533     // return instructions which are created from these branches will be
1534     // replaced after all landing pads have been outlined.
1535     for (const auto MapEntry : VMap) {
1536       // VMap maps all values and blocks that were just cloned, but dead
1537       // blocks which were pruned will map to nullptr.
1538       if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1539         continue;
1540       const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1541       for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1542         auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1543         if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1544           continue;
1545         BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1546         --II;
1547         if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1548           // This would indicate that a nested landing pad wants to return
1549           // to a block that is outlined into two different handlers.
1550           assert(!LPadTargetBlocks.count(MappedBB));
1551           LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1552         }
1553       }
1554     }
1555   } // End if (CatchAction)
1556
1557   Action->setHandlerBlockOrFunc(Handler);
1558
1559   return true;
1560 }
1561
1562 /// This BB must end in a selector dispatch. All we need to do is pass the
1563 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1564 /// target.
1565 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1566                                           BasicBlock *StartBB) {
1567   BasicBlock *HandlerBB;
1568   BasicBlock *NextBB;
1569   Constant *Selector;
1570   bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1571   if (Res) {
1572     // If this was EH dispatch, this must be a conditional branch to the handler
1573     // block.
1574     // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1575     // leading to crashes if some optimization hoists stuff here.
1576     assert(CatchAction->getSelector() && HandlerBB &&
1577            "expected catch EH dispatch");
1578   } else {
1579     // This must be a catch-all. Split the block after the landingpad.
1580     assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1581     HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
1582   }
1583   IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1584   Function *EHCodeFn = Intrinsic::getDeclaration(
1585       StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
1586   Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
1587   Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1588   Builder.CreateStore(Code, SEHExceptionCodeSlot);
1589   CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1590   TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1591   CatchAction->setReturnTargets(Targets);
1592 }
1593
1594 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1595   // Each instance of this class should only ever be used to map a single
1596   // landing pad.
1597   assert(OriginLPad == nullptr || OriginLPad == LPad);
1598
1599   // If the landing pad has already been mapped, there's nothing more to do.
1600   if (OriginLPad == LPad)
1601     return;
1602
1603   OriginLPad = LPad;
1604
1605   // The landingpad instruction returns an aggregate value.  Typically, its
1606   // value will be passed to a pair of extract value instructions and the
1607   // results of those extracts will have been promoted to reg values before
1608   // this routine is called.
1609   for (auto *U : LPad->users()) {
1610     const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1611     if (!Extract)
1612       continue;
1613     assert(Extract->getNumIndices() == 1 &&
1614            "Unexpected operation: extracting both landing pad values");
1615     unsigned int Idx = *(Extract->idx_begin());
1616     assert((Idx == 0 || Idx == 1) &&
1617            "Unexpected operation: extracting an unknown landing pad element");
1618     if (Idx == 0) {
1619       ExtractedEHPtrs.push_back(Extract);
1620     } else if (Idx == 1) {
1621       ExtractedSelectors.push_back(Extract);
1622     }
1623   }
1624 }
1625
1626 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1627   return BB->getLandingPadInst() == OriginLPad;
1628 }
1629
1630 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1631   if (Inst == OriginLPad)
1632     return true;
1633   for (auto *Extract : ExtractedEHPtrs) {
1634     if (Inst == Extract)
1635       return true;
1636   }
1637   for (auto *Extract : ExtractedSelectors) {
1638     if (Inst == Extract)
1639       return true;
1640   }
1641   return false;
1642 }
1643
1644 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1645                                   Value *SelectorValue) const {
1646   // Remap all landing pad extract instructions to the specified values.
1647   for (auto *Extract : ExtractedEHPtrs)
1648     VMap[Extract] = EHPtrValue;
1649   for (auto *Extract : ExtractedSelectors)
1650     VMap[Extract] = SelectorValue;
1651 }
1652
1653 static bool isLocalAddressCall(const Value *V) {
1654   return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
1655 }
1656
1657 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1658     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1659   // If this is one of the boilerplate landing pad instructions, skip it.
1660   // The instruction will have already been remapped in VMap.
1661   if (LPadMap.isLandingPadSpecificInst(Inst))
1662     return CloningDirector::SkipInstruction;
1663
1664   // Nested landing pads that have not already been outlined will be cloned as
1665   // stubs, with just the landingpad instruction and an unreachable instruction.
1666   // When all landingpads have been outlined, we'll replace this with the
1667   // llvm.eh.actions call and indirect branch created when the landing pad was
1668   // outlined.
1669   if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1670     return handleLandingPad(VMap, LPad, NewBB);
1671   }
1672
1673   // Nested landing pads that have already been outlined will be cloned in their
1674   // outlined form, but we need to intercept the ibr instruction to filter out
1675   // targets that do not return to the handler we are outlining.
1676   if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1677     return handleIndirectBr(VMap, IBr, NewBB);
1678   }
1679
1680   if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1681     return handleInvoke(VMap, Invoke, NewBB);
1682
1683   if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1684     return handleResume(VMap, Resume, NewBB);
1685
1686   if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1687     return handleCompare(VMap, Cmp, NewBB);
1688
1689   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1690     return handleBeginCatch(VMap, Inst, NewBB);
1691   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1692     return handleEndCatch(VMap, Inst, NewBB);
1693   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1694     return handleTypeIdFor(VMap, Inst, NewBB);
1695
1696   // When outlining llvm.localaddress(), remap that to the second argument,
1697   // which is the FP of the parent.
1698   if (isLocalAddressCall(Inst)) {
1699     VMap[Inst] = ParentFP;
1700     return CloningDirector::SkipInstruction;
1701   }
1702
1703   // Continue with the default cloning behavior.
1704   return CloningDirector::CloneInstruction;
1705 }
1706
1707 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1708     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1709   // If the instruction after the landing pad is a call to llvm.eh.actions
1710   // the landing pad has already been outlined.  In this case, we should
1711   // clone it because it may return to a block in the handler we are
1712   // outlining now that would otherwise be unreachable.  The landing pads
1713   // are sorted before outlining begins to enable this case to work
1714   // properly.
1715   const Instruction *NextI = LPad->getNextNode();
1716   if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1717     return CloningDirector::CloneInstruction;
1718
1719   // If the landing pad hasn't been outlined yet, the landing pad we are
1720   // outlining now does not dominate it and so it cannot return to a block
1721   // in this handler.  In that case, we can just insert a stub landing
1722   // pad now and patch it up later.
1723   Instruction *NewInst = LPad->clone();
1724   if (LPad->hasName())
1725     NewInst->setName(LPad->getName());
1726   // Save this correlation for later processing.
1727   NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1728   VMap[LPad] = NewInst;
1729   BasicBlock::InstListType &InstList = NewBB->getInstList();
1730   InstList.push_back(NewInst);
1731   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1732   return CloningDirector::StopCloningBB;
1733 }
1734
1735 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1736     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1737   // The argument to the call is some form of the first element of the
1738   // landingpad aggregate value, but that doesn't matter.  It isn't used
1739   // here.
1740   // The second argument is an outparameter where the exception object will be
1741   // stored. Typically the exception object is a scalar, but it can be an
1742   // aggregate when catching by value.
1743   // FIXME: Leave something behind to indicate where the exception object lives
1744   // for this handler. Should it be part of llvm.eh.actions?
1745   assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1746                                           "llvm.eh.begincatch found while "
1747                                           "outlining catch handler.");
1748   ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1749   if (isa<ConstantPointerNull>(ExceptionObjectVar))
1750     return CloningDirector::SkipInstruction;
1751   assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1752          "catch parameter is not static alloca");
1753   Materializer.escapeCatchObject(ExceptionObjectVar);
1754   return CloningDirector::SkipInstruction;
1755 }
1756
1757 CloningDirector::CloningAction
1758 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1759                                    const Instruction *Inst, BasicBlock *NewBB) {
1760   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1761   // It might be interesting to track whether or not we are inside a catch
1762   // function, but that might make the algorithm more brittle than it needs
1763   // to be.
1764
1765   // The end catch call can occur in one of two places: either in a
1766   // landingpad block that is part of the catch handlers exception mechanism,
1767   // or at the end of the catch block.  However, a catch-all handler may call
1768   // end catch from the original landing pad.  If the call occurs in a nested
1769   // landing pad block, we must skip it and continue so that the landing pad
1770   // gets cloned.
1771   auto *ParentBB = IntrinCall->getParent();
1772   if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1773     return CloningDirector::SkipInstruction;
1774
1775   // If an end catch occurs anywhere else we want to terminate the handler
1776   // with a return to the code that follows the endcatch call.  If the
1777   // next instruction is not an unconditional branch, we need to split the
1778   // block to provide a clear target for the return instruction.
1779   BasicBlock *ContinueBB;
1780   auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1781   const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1782   if (!Branch || !Branch->isUnconditional()) {
1783     // We're interrupting the cloning process at this location, so the
1784     // const_cast we're doing here will not cause a problem.
1785     ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1786                             const_cast<Instruction *>(cast<Instruction>(Next)));
1787   } else {
1788     ContinueBB = Branch->getSuccessor(0);
1789   }
1790
1791   ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1792   ReturnTargets.push_back(ContinueBB);
1793
1794   // We just added a terminator to the cloned block.
1795   // Tell the caller to stop processing the current basic block so that
1796   // the branch instruction will be skipped.
1797   return CloningDirector::StopCloningBB;
1798 }
1799
1800 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1801     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1802   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1803   Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1804   // This causes a replacement that will collapse the landing pad CFG based
1805   // on the filter function we intend to match.
1806   if (Selector == CurrentSelector)
1807     VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1808   else
1809     VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1810   // Tell the caller not to clone this instruction.
1811   return CloningDirector::SkipInstruction;
1812 }
1813
1814 CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1815     ValueToValueMapTy &VMap,
1816     const IndirectBrInst *IBr,
1817     BasicBlock *NewBB) {
1818   // If this indirect branch is not part of a landing pad block, just clone it.
1819   const BasicBlock *ParentBB = IBr->getParent();
1820   if (!ParentBB->isLandingPad())
1821     return CloningDirector::CloneInstruction;
1822
1823   // If it is part of a landing pad, we want to filter out target blocks
1824   // that are not part of the handler we are outlining.
1825   const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1826
1827   // Save this correlation for later processing.
1828   NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1829
1830   // We should only get here for landing pads that have already been outlined.
1831   assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1832
1833   // Copy the indirectbr, but only include targets that were previously
1834   // identified as EH blocks and are dominated by the nested landing pad.
1835   SetVector<const BasicBlock *> ReturnTargets;
1836   for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1837     auto *TargetBB = IBr->getDestination(I);
1838     if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1839         DT->dominates(ParentBB, TargetBB)) {
1840       DEBUG(dbgs() << "  Adding destination " << TargetBB->getName() << "\n");
1841       ReturnTargets.insert(TargetBB);
1842     }
1843   }
1844   IndirectBrInst *NewBranch = 
1845         IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1846                                ReturnTargets.size(), NewBB);
1847   for (auto *Target : ReturnTargets)
1848     NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1849
1850   // The operands and targets of the branch instruction are remapped later
1851   // because it is a terminator.  Tell the cloning code to clone the
1852   // blocks we just added to the target list.
1853   return CloningDirector::CloneSuccessors;
1854 }
1855
1856 CloningDirector::CloningAction
1857 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1858                                  const InvokeInst *Invoke, BasicBlock *NewBB) {
1859   return CloningDirector::CloneInstruction;
1860 }
1861
1862 CloningDirector::CloningAction
1863 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1864                                  const ResumeInst *Resume, BasicBlock *NewBB) {
1865   // Resume instructions shouldn't be reachable from catch handlers.
1866   // We still need to handle it, but it will be pruned.
1867   BasicBlock::InstListType &InstList = NewBB->getInstList();
1868   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1869   return CloningDirector::StopCloningBB;
1870 }
1871
1872 CloningDirector::CloningAction
1873 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1874                                   const CmpInst *Compare, BasicBlock *NewBB) {
1875   const IntrinsicInst *IntrinCall = nullptr;
1876   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1877     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1878   } else if (match(Compare->getOperand(1),
1879                    m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1880     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1881   }
1882   if (IntrinCall) {
1883     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1884     // This causes a replacement that will collapse the landing pad CFG based
1885     // on the filter function we intend to match.
1886     if (Selector == CurrentSelector->stripPointerCasts()) {
1887       VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1888     } else {
1889       VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1890     }
1891     return CloningDirector::SkipInstruction;
1892   }
1893   return CloningDirector::CloneInstruction;
1894 }
1895
1896 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1897     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1898   // The MS runtime will terminate the process if an exception occurs in a
1899   // cleanup handler, so we shouldn't encounter landing pads in the actual
1900   // cleanup code, but they may appear in catch blocks.  Depending on where
1901   // we started cloning we may see one, but it will get dropped during dead
1902   // block pruning.
1903   Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1904   VMap[LPad] = NewInst;
1905   BasicBlock::InstListType &InstList = NewBB->getInstList();
1906   InstList.push_back(NewInst);
1907   return CloningDirector::StopCloningBB;
1908 }
1909
1910 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1911     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1912   // Cleanup code may flow into catch blocks or the catch block may be part
1913   // of a branch that will be optimized away.  We'll insert a return
1914   // instruction now, but it may be pruned before the cloning process is
1915   // complete.
1916   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1917   return CloningDirector::StopCloningBB;
1918 }
1919
1920 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1921     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1922   // Cleanup handlers nested within catch handlers may begin with a call to
1923   // eh.endcatch.  We can just ignore that instruction.
1924   return CloningDirector::SkipInstruction;
1925 }
1926
1927 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1928     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1929   // If we encounter a selector comparison while cloning a cleanup handler,
1930   // we want to stop cloning immediately.  Anything after the dispatch
1931   // will be outlined into a different handler.
1932   BasicBlock *CatchHandler;
1933   Constant *Selector;
1934   BasicBlock *NextBB;
1935   if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1936                          CatchHandler, Selector, NextBB)) {
1937     ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1938     return CloningDirector::StopCloningBB;
1939   }
1940   // If eg.typeid.for is called for any other reason, it can be ignored.
1941   VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1942   return CloningDirector::SkipInstruction;
1943 }
1944
1945 CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1946     ValueToValueMapTy &VMap,
1947     const IndirectBrInst *IBr,
1948     BasicBlock *NewBB) {
1949   // No special handling is required for cleanup cloning.
1950   return CloningDirector::CloneInstruction;
1951 }
1952
1953 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1954     ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1955   // All invokes in cleanup handlers can be replaced with calls.
1956   SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1957   // Insert a normal call instruction...
1958   CallInst *NewCall =
1959       CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1960                        Invoke->getName(), NewBB);
1961   NewCall->setCallingConv(Invoke->getCallingConv());
1962   NewCall->setAttributes(Invoke->getAttributes());
1963   NewCall->setDebugLoc(Invoke->getDebugLoc());
1964   VMap[Invoke] = NewCall;
1965
1966   // Remap the operands.
1967   llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1968
1969   // Insert an unconditional branch to the normal destination.
1970   BranchInst::Create(Invoke->getNormalDest(), NewBB);
1971
1972   // The unwind destination won't be cloned into the new function, so
1973   // we don't need to clean up its phi nodes.
1974
1975   // We just added a terminator to the cloned block.
1976   // Tell the caller to stop processing the current basic block.
1977   return CloningDirector::CloneSuccessors;
1978 }
1979
1980 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1981     ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1982   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1983
1984   // We just added a terminator to the cloned block.
1985   // Tell the caller to stop processing the current basic block so that
1986   // the branch instruction will be skipped.
1987   return CloningDirector::StopCloningBB;
1988 }
1989
1990 CloningDirector::CloningAction
1991 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1992                                     const CmpInst *Compare, BasicBlock *NewBB) {
1993   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1994       match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1995     VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1996     return CloningDirector::SkipInstruction;
1997   }
1998   return CloningDirector::CloneInstruction;
1999 }
2000
2001 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
2002     Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
2003     : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
2004   BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
2005
2006   // New allocas should be inserted in the entry block, but after the parent FP
2007   // is established if it is an instruction.
2008   Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
2009   if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
2010     InsertPoint = FPInst->getNextNode();
2011   Builder.SetInsertPoint(EntryBB, InsertPoint);
2012 }
2013
2014 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
2015   // If we're asked to materialize a static alloca, we temporarily create an
2016   // alloca in the outlined function and add this to the FrameVarInfo map.  When
2017   // all the outlining is complete, we'll replace these temporary allocas with
2018   // calls to llvm.localrecover.
2019   if (auto *AV = dyn_cast<AllocaInst>(V)) {
2020     assert(AV->isStaticAlloca() &&
2021            "cannot materialize un-demoted dynamic alloca");
2022     AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
2023     Builder.Insert(NewAlloca, AV->getName());
2024     FrameVarInfo[AV].push_back(NewAlloca);
2025     return NewAlloca;
2026   }
2027
2028   if (isa<Instruction>(V) || isa<Argument>(V)) {
2029     Function *Parent = isa<Instruction>(V)
2030                            ? cast<Instruction>(V)->getParent()->getParent()
2031                            : cast<Argument>(V)->getParent();
2032     errs()
2033         << "Failed to demote instruction used in exception handler of function "
2034         << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
2035     errs() << "  " << *V << '\n';
2036     report_fatal_error("WinEHPrepare failed to demote instruction");
2037   }
2038
2039   // Don't materialize other values.
2040   return nullptr;
2041 }
2042
2043 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2044   // Catch parameter objects have to live in the parent frame. When we see a use
2045   // of a catch parameter, add a sentinel to the multimap to indicate that it's
2046   // used from another handler. This will prevent us from trying to sink the
2047   // alloca into the handler and ensure that the catch parameter is present in
2048   // the call to llvm.localescape.
2049   FrameVarInfo[V].push_back(getCatchObjectSentinel());
2050 }
2051
2052 // This function maps the catch and cleanup handlers that are reachable from the
2053 // specified landing pad. The landing pad sequence will have this basic shape:
2054 //
2055 //  <cleanup handler>
2056 //  <selector comparison>
2057 //  <catch handler>
2058 //  <cleanup handler>
2059 //  <selector comparison>
2060 //  <catch handler>
2061 //  <cleanup handler>
2062 //  ...
2063 //
2064 // Any of the cleanup slots may be absent.  The cleanup slots may be occupied by
2065 // any arbitrary control flow, but all paths through the cleanup code must
2066 // eventually reach the next selector comparison and no path can skip to a
2067 // different selector comparisons, though some paths may terminate abnormally.
2068 // Therefore, we will use a depth first search from the start of any given
2069 // cleanup block and stop searching when we find the next selector comparison.
2070 //
2071 // If the landingpad instruction does not have a catch clause, we will assume
2072 // that any instructions other than selector comparisons and catch handlers can
2073 // be ignored.  In practice, these will only be the boilerplate instructions.
2074 //
2075 // The catch handlers may also have any control structure, but we are only
2076 // interested in the start of the catch handlers, so we don't need to actually
2077 // follow the flow of the catch handlers.  The start of the catch handlers can
2078 // be located from the compare instructions, but they can be skipped in the
2079 // flow by following the contrary branch.
2080 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2081                                        LandingPadActions &Actions) {
2082   unsigned int NumClauses = LPad->getNumClauses();
2083   unsigned int HandlersFound = 0;
2084   BasicBlock *BB = LPad->getParent();
2085
2086   DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2087
2088   if (NumClauses == 0) {
2089     findCleanupHandlers(Actions, BB, nullptr);
2090     return;
2091   }
2092
2093   VisitedBlockSet VisitedBlocks;
2094
2095   while (HandlersFound != NumClauses) {
2096     BasicBlock *NextBB = nullptr;
2097
2098     // Skip over filter clauses.
2099     if (LPad->isFilter(HandlersFound)) {
2100       ++HandlersFound;
2101       continue;
2102     }
2103
2104     // See if the clause we're looking for is a catch-all.
2105     // If so, the catch begins immediately.
2106     Constant *ExpectedSelector =
2107         LPad->getClause(HandlersFound)->stripPointerCasts();
2108     if (isa<ConstantPointerNull>(ExpectedSelector)) {
2109       // The catch all must occur last.
2110       assert(HandlersFound == NumClauses - 1);
2111
2112       // There can be additional selector dispatches in the call chain that we
2113       // need to ignore.
2114       BasicBlock *CatchBlock = nullptr;
2115       Constant *Selector;
2116       while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2117         DEBUG(dbgs() << "  Found extra catch dispatch in block "
2118                      << CatchBlock->getName() << "\n");
2119         BB = NextBB;
2120       }
2121
2122       // Add the catch handler to the action list.
2123       CatchHandler *Action = nullptr;
2124       if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2125         // If the CatchHandlerMap already has an entry for this BB, re-use it.
2126         Action = CatchHandlerMap[BB];
2127         assert(Action->getSelector() == ExpectedSelector);
2128       } else {
2129         // We don't expect a selector dispatch, but there may be a call to
2130         // llvm.eh.begincatch, which separates catch handling code from
2131         // cleanup code in the same control flow.  This call looks for the
2132         // begincatch intrinsic.
2133         Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2134         if (Action) {
2135           // For C++ EH, check if there is any interesting cleanup code before
2136           // we begin the catch. This is important because cleanups cannot
2137           // rethrow exceptions but code called from catches can. For SEH, it
2138           // isn't important if some finally code before a catch-all is executed
2139           // out of line or after recovering from the exception.
2140           if (Personality == EHPersonality::MSVC_CXX)
2141             findCleanupHandlers(Actions, BB, BB);
2142         } else {
2143           // If an action was not found, it means that the control flows
2144           // directly into the catch-all handler and there is no cleanup code.
2145           // That's an expected situation and we must create a catch action.
2146           // Since this is a catch-all handler, the selector won't actually
2147           // appear in the code anywhere.  ExpectedSelector here is the constant
2148           // null ptr that we got from the landing pad instruction.
2149           Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2150           CatchHandlerMap[BB] = Action;
2151         }
2152       }
2153       Actions.insertCatchHandler(Action);
2154       DEBUG(dbgs() << "  Catch all handler at block " << BB->getName() << "\n");
2155       ++HandlersFound;
2156
2157       // Once we reach a catch-all, don't expect to hit a resume instruction.
2158       BB = nullptr;
2159       break;
2160     }
2161
2162     CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
2163     assert(CatchAction);
2164
2165     // See if there is any interesting code executed before the dispatch.
2166     findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
2167
2168     // When the source program contains multiple nested try blocks the catch
2169     // handlers can get strung together in such a way that we can encounter
2170     // a dispatch for a selector that we've already had a handler for.
2171     if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2172       ++HandlersFound;
2173
2174       // Add the catch handler to the action list.
2175       DEBUG(dbgs() << "  Found catch dispatch in block "
2176                    << CatchAction->getStartBlock()->getName() << "\n");
2177       Actions.insertCatchHandler(CatchAction);
2178     } else {
2179       // Under some circumstances optimized IR will flow unconditionally into a
2180       // handler block without checking the selector.  This can only happen if
2181       // the landing pad has a catch-all handler and the handler for the
2182       // preceding catch clause is identical to the catch-call handler
2183       // (typically an empty catch).  In this case, the handler must be shared
2184       // by all remaining clauses.
2185       if (isa<ConstantPointerNull>(
2186               CatchAction->getSelector()->stripPointerCasts())) {
2187         DEBUG(dbgs() << "  Applying early catch-all handler in block "
2188                      << CatchAction->getStartBlock()->getName()
2189                      << "  to all remaining clauses.\n");
2190         Actions.insertCatchHandler(CatchAction);
2191         return;
2192       }
2193
2194       DEBUG(dbgs() << "  Found extra catch dispatch in block "
2195                    << CatchAction->getStartBlock()->getName() << "\n");
2196     }
2197
2198     // Move on to the block after the catch handler.
2199     BB = NextBB;
2200   }
2201
2202   // If we didn't wind up in a catch-all, see if there is any interesting code
2203   // executed before the resume.
2204   findCleanupHandlers(Actions, BB, BB);
2205
2206   // It's possible that some optimization moved code into a landingpad that
2207   // wasn't
2208   // previously being used for cleanup.  If that happens, we need to execute
2209   // that
2210   // extra code from a cleanup handler.
2211   if (Actions.includesCleanup() && !LPad->isCleanup())
2212     LPad->setCleanup(true);
2213 }
2214
2215 // This function searches starting with the input block for the next
2216 // block that terminates with a branch whose condition is based on a selector
2217 // comparison.  This may be the input block.  See the mapLandingPadBlocks
2218 // comments for a discussion of control flow assumptions.
2219 //
2220 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2221                                              BasicBlock *&NextBB,
2222                                              VisitedBlockSet &VisitedBlocks) {
2223   // See if we've already found a catch handler use it.
2224   // Call count() first to avoid creating a null entry for blocks
2225   // we haven't seen before.
2226   if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2227     CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2228     NextBB = Action->getNextBB();
2229     return Action;
2230   }
2231
2232   // VisitedBlocks applies only to the current search.  We still
2233   // need to consider blocks that we've visited while mapping other
2234   // landing pads.
2235   VisitedBlocks.insert(BB);
2236
2237   BasicBlock *CatchBlock = nullptr;
2238   Constant *Selector = nullptr;
2239
2240   // If this is the first time we've visited this block from any landing pad
2241   // look to see if it is a selector dispatch block.
2242   if (!CatchHandlerMap.count(BB)) {
2243     if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2244       CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2245       CatchHandlerMap[BB] = Action;
2246       return Action;
2247     }
2248     // If we encounter a block containing an llvm.eh.begincatch before we
2249     // find a selector dispatch block, the handler is assumed to be
2250     // reached unconditionally.  This happens for catch-all blocks, but
2251     // it can also happen for other catch handlers that have been combined
2252     // with the catch-all handler during optimization.
2253     if (isCatchBlock(BB)) {
2254       PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2255       Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2256       CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2257       CatchHandlerMap[BB] = Action;
2258       return Action;
2259     }
2260   }
2261
2262   // Visit each successor, looking for the dispatch.
2263   // FIXME: We expect to find the dispatch quickly, so this will probably
2264   //        work better as a breadth first search.
2265   for (BasicBlock *Succ : successors(BB)) {
2266     if (VisitedBlocks.count(Succ))
2267       continue;
2268
2269     CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2270     if (Action)
2271       return Action;
2272   }
2273   return nullptr;
2274 }
2275
2276 // These are helper functions to combine repeated code from findCleanupHandlers.
2277 static void createCleanupHandler(LandingPadActions &Actions,
2278                                  CleanupHandlerMapTy &CleanupHandlerMap,
2279                                  BasicBlock *BB) {
2280   CleanupHandler *Action = new CleanupHandler(BB);
2281   CleanupHandlerMap[BB] = Action;
2282   Actions.insertCleanupHandler(Action);
2283   DEBUG(dbgs() << "  Found cleanup code in block "
2284                << Action->getStartBlock()->getName() << "\n");
2285 }
2286
2287 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2288                                          Instruction *MaybeCall) {
2289   // Look for finally blocks that Clang has already outlined for us.
2290   //   %fp = call i8* @llvm.localaddress()
2291   //   call void @"fin$parent"(iN 1, i8* %fp)
2292   if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
2293     MaybeCall = MaybeCall->getNextNode();
2294   CallSite FinallyCall(MaybeCall);
2295   if (!FinallyCall || FinallyCall.arg_size() != 2)
2296     return CallSite();
2297   if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2298     return CallSite();
2299   if (!isLocalAddressCall(FinallyCall.getArgument(1)))
2300     return CallSite();
2301   return FinallyCall;
2302 }
2303
2304 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2305   // Skip single ubr blocks.
2306   while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2307     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2308     if (Br && Br->isUnconditional())
2309       BB = Br->getSuccessor(0);
2310     else
2311       return BB;
2312   }
2313   return BB;
2314 }
2315
2316 // This function searches starting with the input block for the next block that
2317 // contains code that is not part of a catch handler and would not be eliminated
2318 // during handler outlining.
2319 //
2320 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2321                                        BasicBlock *StartBB, BasicBlock *EndBB) {
2322   // Here we will skip over the following:
2323   //
2324   // landing pad prolog:
2325   //
2326   // Unconditional branches
2327   //
2328   // Selector dispatch
2329   //
2330   // Resume pattern
2331   //
2332   // Anything else marks the start of an interesting block
2333
2334   BasicBlock *BB = StartBB;
2335   // Anything other than an unconditional branch will kick us out of this loop
2336   // one way or another.
2337   while (BB) {
2338     BB = followSingleUnconditionalBranches(BB);
2339     // If we've already scanned this block, don't scan it again.  If it is
2340     // a cleanup block, there will be an action in the CleanupHandlerMap.
2341     // If we've scanned it and it is not a cleanup block, there will be a
2342     // nullptr in the CleanupHandlerMap.  If we have not scanned it, there will
2343     // be no entry in the CleanupHandlerMap.  We must call count() first to
2344     // avoid creating a null entry for blocks we haven't scanned.
2345     if (CleanupHandlerMap.count(BB)) {
2346       if (auto *Action = CleanupHandlerMap[BB]) {
2347         Actions.insertCleanupHandler(Action);
2348         DEBUG(dbgs() << "  Found cleanup code in block "
2349                      << Action->getStartBlock()->getName() << "\n");
2350         // FIXME: This cleanup might chain into another, and we need to discover
2351         // that.
2352         return;
2353       } else {
2354         // Here we handle the case where the cleanup handler map contains a
2355         // value for this block but the value is a nullptr.  This means that
2356         // we have previously analyzed the block and determined that it did
2357         // not contain any cleanup code.  Based on the earlier analysis, we
2358         // know the block must end in either an unconditional branch, a
2359         // resume or a conditional branch that is predicated on a comparison
2360         // with a selector.  Either the resume or the selector dispatch
2361         // would terminate the search for cleanup code, so the unconditional
2362         // branch is the only case for which we might need to continue
2363         // searching.
2364         BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2365         if (SuccBB == BB || SuccBB == EndBB)
2366           return;
2367         BB = SuccBB;
2368         continue;
2369       }
2370     }
2371
2372     // Create an entry in the cleanup handler map for this block.  Initially
2373     // we create an entry that says this isn't a cleanup block.  If we find
2374     // cleanup code, the caller will replace this entry.
2375     CleanupHandlerMap[BB] = nullptr;
2376
2377     TerminatorInst *Terminator = BB->getTerminator();
2378
2379     // Landing pad blocks have extra instructions we need to accept.
2380     LandingPadMap *LPadMap = nullptr;
2381     if (BB->isLandingPad()) {
2382       LandingPadInst *LPad = BB->getLandingPadInst();
2383       LPadMap = &LPadMaps[LPad];
2384       if (!LPadMap->isInitialized())
2385         LPadMap->mapLandingPad(LPad);
2386     }
2387
2388     // Look for the bare resume pattern:
2389     //   %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2390     //   %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
2391     //   resume { i8*, i32 } %lpad.val2
2392     if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2393       InsertValueInst *Insert1 = nullptr;
2394       InsertValueInst *Insert2 = nullptr;
2395       Value *ResumeVal = Resume->getOperand(0);
2396       // If the resume value isn't a phi or landingpad value, it should be a
2397       // series of insertions. Identify them so we can avoid them when scanning
2398       // for cleanups.
2399       if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
2400         Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
2401         if (!Insert2)
2402           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2403         Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2404         if (!Insert1)
2405           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2406       }
2407       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2408            II != IE; ++II) {
2409         Instruction *Inst = II;
2410         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2411           continue;
2412         if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2413           continue;
2414         if (!Inst->hasOneUse() ||
2415             (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
2416           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2417         }
2418       }
2419       return;
2420     }
2421
2422     BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
2423     if (Branch && Branch->isConditional()) {
2424       // Look for the selector dispatch.
2425       //   %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2426       //   %matches = icmp eq i32 %sel, %2
2427       //   br i1 %matches, label %catch14, label %eh.resume
2428       CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2429       if (!Compare || !Compare->isEquality())
2430         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2431       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2432            II != IE; ++II) {
2433         Instruction *Inst = II;
2434         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2435           continue;
2436         if (Inst == Compare || Inst == Branch)
2437           continue;
2438         if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2439           continue;
2440         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2441       }
2442       // The selector dispatch block should always terminate our search.
2443       assert(BB == EndBB);
2444       return;
2445     }
2446
2447     if (isAsynchronousEHPersonality(Personality)) {
2448       // If this is a landingpad block, split the block at the first non-landing
2449       // pad instruction.
2450       Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2451       if (LPadMap) {
2452         while (MaybeCall != BB->getTerminator() &&
2453                LPadMap->isLandingPadSpecificInst(MaybeCall))
2454           MaybeCall = MaybeCall->getNextNode();
2455       }
2456
2457       // Look for outlined finally calls on x64, since those happen to match the
2458       // prototype provided by the runtime.
2459       if (TheTriple.getArch() == Triple::x86_64) {
2460         if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2461           Function *Fin = FinallyCall.getCalledFunction();
2462           assert(Fin && "outlined finally call should be direct");
2463           auto *Action = new CleanupHandler(BB);
2464           Action->setHandlerBlockOrFunc(Fin);
2465           Actions.insertCleanupHandler(Action);
2466           CleanupHandlerMap[BB] = Action;
2467           DEBUG(dbgs() << "  Found frontend-outlined finally call to "
2468                        << Fin->getName() << " in block "
2469                        << Action->getStartBlock()->getName() << "\n");
2470
2471           // Split the block if there were more interesting instructions and
2472           // look for finally calls in the normal successor block.
2473           BasicBlock *SuccBB = BB;
2474           if (FinallyCall.getInstruction() != BB->getTerminator() &&
2475               FinallyCall.getInstruction()->getNextNode() !=
2476                   BB->getTerminator()) {
2477             SuccBB =
2478                 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
2479           } else {
2480             if (FinallyCall.isInvoke()) {
2481               SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2482                            ->getNormalDest();
2483             } else {
2484               SuccBB = BB->getUniqueSuccessor();
2485               assert(SuccBB &&
2486                      "splitOutlinedFinallyCalls didn't insert a branch");
2487             }
2488           }
2489           BB = SuccBB;
2490           if (BB == EndBB)
2491             return;
2492           continue;
2493         }
2494       }
2495     }
2496
2497     // Anything else is either a catch block or interesting cleanup code.
2498     for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2499          II != IE; ++II) {
2500       Instruction *Inst = II;
2501       if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2502         continue;
2503       // Unconditional branches fall through to this loop.
2504       if (Inst == Branch)
2505         continue;
2506       // If this is a catch block, there is no cleanup code to be found.
2507       if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2508         return;
2509       // If this a nested landing pad, it may contain an endcatch call.
2510       if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2511         return;
2512       // Anything else makes this interesting cleanup code.
2513       return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2514     }
2515
2516     // Only unconditional branches in empty blocks should get this far.
2517     assert(Branch && Branch->isUnconditional());
2518     if (BB == EndBB)
2519       return;
2520     BB = Branch->getSuccessor(0);
2521   }
2522 }
2523
2524 // This is a public function, declared in WinEHFuncInfo.h and is also
2525 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2526 void llvm::parseEHActions(
2527     const IntrinsicInst *II,
2528     SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
2529   assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2530          "attempted to parse non eh.actions intrinsic");
2531   for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2532     uint64_t ActionKind =
2533         cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2534     if (ActionKind == /*catch=*/1) {
2535       auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2536       ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2537       int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2538       Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2539       I += 4;
2540       auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2541                                           /*NextBB=*/nullptr);
2542       CH->setHandlerBlockOrFunc(Handler);
2543       CH->setExceptionVarIndex(EHObjIndexVal);
2544       Actions.push_back(std::move(CH));
2545     } else if (ActionKind == 0) {
2546       Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2547       I += 2;
2548       auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
2549       CH->setHandlerBlockOrFunc(Handler);
2550       Actions.push_back(std::move(CH));
2551     } else {
2552       llvm_unreachable("Expected either a catch or cleanup handler!");
2553     }
2554   }
2555   std::reverse(Actions.begin(), Actions.end());
2556 }
2557
2558 namespace {
2559 struct WinEHNumbering {
2560   WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
2561       CurrentBaseState(-1), NextState(0) {}
2562
2563   WinEHFuncInfo &FuncInfo;
2564   int CurrentBaseState;
2565   int NextState;
2566
2567   SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
2568   SmallPtrSet<const Function *, 4> VisitedHandlers;
2569
2570   int currentEHNumber() const {
2571     return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
2572   }
2573
2574   void createUnwindMapEntry(int ToState, ActionHandler *AH);
2575   void createTryBlockMapEntry(int TryLow, int TryHigh,
2576                               ArrayRef<CatchHandler *> Handlers);
2577   void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2578                        ImmutableCallSite CS);
2579   void popUnmatchedActions(int FirstMismatch);
2580   void calculateStateNumbers(const Function &F);
2581   void findActionRootLPads(const Function &F);
2582 };
2583 }
2584
2585 static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
2586                              const Value *V) {
2587   WinEHUnwindMapEntry UME;
2588   UME.ToState = ToState;
2589   UME.Cleanup = V;
2590   FuncInfo.UnwindMap.push_back(UME);
2591   return FuncInfo.getLastStateNumber();
2592 }
2593
2594 static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
2595                                 int TryHigh, int CatchHigh,
2596                                 ArrayRef<const CatchPadInst *> Handlers) {
2597   WinEHTryBlockMapEntry TBME;
2598   TBME.TryLow = TryLow;
2599   TBME.TryHigh = TryHigh;
2600   TBME.CatchHigh = CatchHigh;
2601   assert(TBME.TryLow <= TBME.TryHigh);
2602   for (const CatchPadInst *CPI : Handlers) {
2603     WinEHHandlerType HT;
2604     Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
2605     if (TypeInfo->isNullValue()) {
2606       HT.Adjectives = 0x40;
2607       HT.TypeDescriptor = nullptr;
2608     } else {
2609       auto *GV = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
2610       // Selectors are always pointers to GlobalVariables with 'struct' type.
2611       // The struct has two fields, adjectives and a type descriptor.
2612       auto *CS = cast<ConstantStruct>(GV->getInitializer());
2613       HT.Adjectives =
2614           cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2615       HT.TypeDescriptor =
2616           cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2617     }
2618     HT.Handler = CPI->getNormalDest();
2619     // FIXME: Pass CPI->getArgOperand(1).
2620     HT.CatchObjRecoverIdx = -1;
2621     TBME.HandlerArray.push_back(HT);
2622   }
2623   FuncInfo.TryBlockMap.push_back(TBME);
2624 }
2625
2626 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
2627   Value *V = nullptr;
2628   if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
2629     V = cast<Function>(CH->getHandlerBlockOrFunc());
2630   addUnwindMapEntry(FuncInfo, ToState, V);
2631 }
2632
2633 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
2634                                             ArrayRef<CatchHandler *> Handlers) {
2635   // See if we already have an entry for this set of handlers.
2636   // This is using iterators rather than a range-based for loop because
2637   // if we find the entry we're looking for we'll need the iterator to erase it.
2638   int NumHandlers = Handlers.size();
2639   auto I = FuncInfo.TryBlockMap.begin();
2640   auto E = FuncInfo.TryBlockMap.end();
2641   for ( ; I != E; ++I) {
2642     auto &Entry = *I;
2643     if (Entry.HandlerArray.size() != (size_t)NumHandlers)
2644       continue;
2645     int N;
2646     for (N = 0; N < NumHandlers; ++N) {
2647       if (Entry.HandlerArray[N].Handler.get<const Value *>() !=
2648           Handlers[N]->getHandlerBlockOrFunc())
2649         break; // breaks out of inner loop
2650     }
2651     // If all the handlers match, this is what we were looking for.
2652     if (N == NumHandlers) {
2653       break;
2654     }
2655   }
2656
2657   // If we found an existing entry for this set of handlers, extend the range
2658   // but move the entry to the end of the map vector.  The order of entries
2659   // in the map is critical to the way that the runtime finds handlers.
2660   // FIXME: Depending on what has happened with block ordering, this may
2661   //        incorrectly combine entries that should remain separate.
2662   if (I != E) {
2663     // Copy the existing entry.
2664     WinEHTryBlockMapEntry Entry = *I;
2665     Entry.TryLow = std::min(TryLow, Entry.TryLow);
2666     Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
2667     assert(Entry.TryLow <= Entry.TryHigh);
2668     // Erase the old entry and add this one to the back.
2669     FuncInfo.TryBlockMap.erase(I);
2670     FuncInfo.TryBlockMap.push_back(Entry);
2671     return;
2672   }
2673
2674   // If we didn't find an entry, create a new one.
2675   WinEHTryBlockMapEntry TBME;
2676   TBME.TryLow = TryLow;
2677   TBME.TryHigh = TryHigh;
2678   assert(TBME.TryLow <= TBME.TryHigh);
2679   for (CatchHandler *CH : Handlers) {
2680     WinEHHandlerType HT;
2681     if (CH->getSelector()->isNullValue()) {
2682       HT.Adjectives = 0x40;
2683       HT.TypeDescriptor = nullptr;
2684     } else {
2685       auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
2686       // Selectors are always pointers to GlobalVariables with 'struct' type.
2687       // The struct has two fields, adjectives and a type descriptor.
2688       auto *CS = cast<ConstantStruct>(GV->getInitializer());
2689       HT.Adjectives =
2690           cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2691       HT.TypeDescriptor =
2692           cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2693     }
2694     HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
2695     HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
2696     TBME.HandlerArray.push_back(HT);
2697   }
2698   FuncInfo.TryBlockMap.push_back(TBME);
2699 }
2700
2701 static void print_name(const Value *V) {
2702 #ifndef NDEBUG
2703   if (!V) {
2704     DEBUG(dbgs() << "null");
2705     return;
2706   }
2707
2708   if (const auto *F = dyn_cast<Function>(V))
2709     DEBUG(dbgs() << F->getName());
2710   else
2711     DEBUG(V->dump());
2712 #endif
2713 }
2714
2715 void WinEHNumbering::processCallSite(
2716     MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2717     ImmutableCallSite CS) {
2718   DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
2719                << ") for: ");
2720   print_name(CS ? CS.getCalledValue() : nullptr);
2721   DEBUG(dbgs() << '\n');
2722
2723   DEBUG(dbgs() << "HandlerStack: \n");
2724   for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2725     DEBUG(dbgs() << "  ");
2726     print_name(HandlerStack[I]->getHandlerBlockOrFunc());
2727     DEBUG(dbgs() << '\n');
2728   }
2729   DEBUG(dbgs() << "Actions: \n");
2730   for (int I = 0, E = Actions.size(); I < E; ++I) {
2731     DEBUG(dbgs() << "  ");
2732     print_name(Actions[I]->getHandlerBlockOrFunc());
2733     DEBUG(dbgs() << '\n');
2734   }
2735   int FirstMismatch = 0;
2736   for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
2737        ++FirstMismatch) {
2738     if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
2739         Actions[FirstMismatch]->getHandlerBlockOrFunc())
2740       break;
2741   }
2742
2743   // Remove unmatched actions from the stack and process their EH states.
2744   popUnmatchedActions(FirstMismatch);
2745
2746   DEBUG(dbgs() << "Pushing actions for CallSite: ");
2747   print_name(CS ? CS.getCalledValue() : nullptr);
2748   DEBUG(dbgs() << '\n');
2749
2750   bool LastActionWasCatch = false;
2751   const LandingPadInst *LastRootLPad = nullptr;
2752   for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
2753     // We can reuse eh states when pushing two catches for the same invoke.
2754     bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
2755     auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
2756     // Various conditions can lead to a handler being popped from the
2757     // stack and re-pushed later.  That shouldn't create a new state.
2758     // FIXME: Can code optimization lead to re-used handlers?
2759     if (FuncInfo.HandlerEnclosedState.count(Handler)) {
2760       // If we already assigned the state enclosed by this handler re-use it.
2761       Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
2762       continue;
2763     }
2764     const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
2765     if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
2766       DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
2767       Actions[I]->setEHState(currentEHNumber());
2768     } else {
2769       DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
2770       print_name(Actions[I]->getHandlerBlockOrFunc());
2771       DEBUG(dbgs() << ") with EH state " << NextState << "\n");
2772       createUnwindMapEntry(currentEHNumber(), Actions[I].get());
2773       DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
2774       Actions[I]->setEHState(NextState);
2775       NextState++;
2776     }
2777     HandlerStack.push_back(std::move(Actions[I]));
2778     LastActionWasCatch = CurrActionIsCatch;
2779     LastRootLPad = RootLPad;
2780   }
2781
2782   // This is used to defer numbering states for a handler until after the
2783   // last time it appears in an invoke action list.
2784   if (CS.isInvoke()) {
2785     for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2786       auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
2787       if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
2788         continue;
2789       FuncInfo.LastInvokeVisited[Handler] = true;
2790       DEBUG(dbgs() << "Last invoke of ");
2791       print_name(Handler);
2792       DEBUG(dbgs() << " has been visited.\n");
2793     }
2794   }
2795
2796   DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
2797   print_name(CS ? CS.getCalledValue() : nullptr);
2798   DEBUG(dbgs() << '\n');
2799 }
2800
2801 void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
2802   // Don't recurse while we are looping over the handler stack.  Instead, defer
2803   // the numbering of the catch handlers until we are done popping.
2804   SmallVector<CatchHandler *, 4> PoppedCatches;
2805   for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
2806     std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
2807     if (isa<CatchHandler>(Handler.get()))
2808       PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
2809   }
2810
2811   int TryHigh = NextState - 1;
2812   int LastTryLowIdx = 0;
2813   for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
2814     CatchHandler *CH = PoppedCatches[I];
2815     DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
2816     if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
2817       int TryLow = CH->getEHState();
2818       auto Handlers =
2819           makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
2820       DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
2821       for (size_t J = 0; J < Handlers.size(); ++J) {
2822         DEBUG(dbgs() << ", ");
2823         print_name(Handlers[J]->getHandlerBlockOrFunc());
2824       }
2825       DEBUG(dbgs() << ")\n");
2826       createTryBlockMapEntry(TryLow, TryHigh, Handlers);
2827       LastTryLowIdx = I + 1;
2828     }
2829   }
2830
2831   for (CatchHandler *CH : PoppedCatches) {
2832     if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
2833       if (FuncInfo.LastInvokeVisited[F]) {
2834         DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
2835         print_name(F);
2836         DEBUG(dbgs() << '\n');
2837         FuncInfo.HandlerBaseState[F] = NextState;
2838         DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
2839                      << ", null)\n");
2840         createUnwindMapEntry(currentEHNumber(), nullptr);
2841         ++NextState;
2842         calculateStateNumbers(*F);
2843       }
2844       else {
2845         DEBUG(dbgs() << "Deferring handling of ");
2846         print_name(F);
2847         DEBUG(dbgs() << " until last invoke visited.\n");
2848       }
2849     }
2850     delete CH;
2851   }
2852 }
2853
2854 void WinEHNumbering::calculateStateNumbers(const Function &F) {
2855   auto I = VisitedHandlers.insert(&F);
2856   if (!I.second)
2857     return; // We've already visited this handler, don't renumber it.
2858
2859   int OldBaseState = CurrentBaseState;
2860   if (FuncInfo.HandlerBaseState.count(&F)) {
2861     CurrentBaseState = FuncInfo.HandlerBaseState[&F];
2862   }
2863
2864   size_t SavedHandlerStackSize = HandlerStack.size();
2865
2866   DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
2867   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2868   for (const BasicBlock &BB : F) {
2869     for (const Instruction &I : BB) {
2870       const auto *CI = dyn_cast<CallInst>(&I);
2871       if (!CI || CI->doesNotThrow())
2872         continue;
2873       processCallSite(None, CI);
2874     }
2875     const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2876     if (!II)
2877       continue;
2878     const LandingPadInst *LPI = II->getLandingPadInst();
2879     auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2880     if (!ActionsCall)
2881       continue;
2882     parseEHActions(ActionsCall, ActionList);
2883     if (ActionList.empty())
2884       continue;
2885     processCallSite(ActionList, II);
2886     ActionList.clear();
2887     FuncInfo.EHPadStateMap[LPI] = currentEHNumber();
2888     DEBUG(dbgs() << "Assigning state " << currentEHNumber()
2889                   << " to landing pad at " << LPI->getParent()->getName()
2890                   << '\n');
2891   }
2892
2893   // Pop any actions that were pushed on the stack for this function.
2894   popUnmatchedActions(SavedHandlerStackSize);
2895
2896   DEBUG(dbgs() << "Assigning max state " << NextState - 1
2897                << " to " << F.getName() << '\n');
2898   FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
2899
2900   CurrentBaseState = OldBaseState;
2901 }
2902
2903 // This function follows the same basic traversal as calculateStateNumbers
2904 // but it is necessary to identify the root landing pad associated
2905 // with each action before we start assigning state numbers.
2906 void WinEHNumbering::findActionRootLPads(const Function &F) {
2907   auto I = VisitedHandlers.insert(&F);
2908   if (!I.second)
2909     return; // We've already visited this handler, don't revisit it.
2910
2911   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2912   for (const BasicBlock &BB : F) {
2913     const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2914     if (!II)
2915       continue;
2916     const LandingPadInst *LPI = II->getLandingPadInst();
2917     auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2918     if (!ActionsCall)
2919       continue;
2920
2921     assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
2922     parseEHActions(ActionsCall, ActionList);
2923     if (ActionList.empty())
2924       continue;
2925     for (int I = 0, E = ActionList.size(); I < E; ++I) {
2926       if (auto *Handler
2927               = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
2928         FuncInfo.LastInvoke[Handler] = II;
2929         // Don't replace the root landing pad if we previously saw this
2930         // handler in a different function.
2931         if (FuncInfo.RootLPad.count(Handler) &&
2932             FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
2933           continue;
2934         DEBUG(dbgs() << "Setting root lpad for ");
2935         print_name(Handler);
2936         DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
2937         FuncInfo.RootLPad[Handler] = LPI;
2938       }
2939     }
2940     // Walk the actions again and look for nested handlers.  This has to
2941     // happen after all of the actions have been processed in the current
2942     // function.
2943     for (int I = 0, E = ActionList.size(); I < E; ++I)
2944       if (auto *Handler
2945               = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
2946         findActionRootLPads(*Handler);
2947     ActionList.clear();
2948   }
2949 }
2950
2951 static const CatchPadInst *getSingleCatchPadPredecessor(const BasicBlock *BB) {
2952   for (const BasicBlock *PredBlock : predecessors(BB))
2953     if (auto *CPI = dyn_cast<CatchPadInst>(PredBlock->getFirstNonPHI()))
2954       return CPI;
2955   return nullptr;
2956 }
2957
2958 /// Find all the catchpads that feed directly into the catchendpad. Frontends
2959 /// using this personality should ensure that each catchendpad and catchpad has
2960 /// one or zero catchpad predecessors.
2961 ///
2962 /// The following C++ generates the IR after it:
2963 ///   try {
2964 ///   } catch (A) {
2965 ///   } catch (B) {
2966 ///   }
2967 ///
2968 /// IR:
2969 ///   %catchpad.A
2970 ///     catchpad [i8* A typeinfo]
2971 ///         to label %catch.A unwind label %catchpad.B
2972 ///   %catchpad.B
2973 ///     catchpad [i8* B typeinfo]
2974 ///         to label %catch.B unwind label %endcatches
2975 ///   %endcatches
2976 ///     catchendblock unwind to caller
2977 void findCatchPadsForCatchEndPad(
2978     const BasicBlock *CatchEndBB,
2979     SmallVectorImpl<const CatchPadInst *> &Handlers) {
2980   const CatchPadInst *CPI = getSingleCatchPadPredecessor(CatchEndBB);
2981   while (CPI) {
2982     Handlers.push_back(CPI);
2983     CPI = getSingleCatchPadPredecessor(CPI->getParent());
2984   }
2985   // We've pushed these back into reverse source order.  Reverse them to get
2986   // the list back into source order.
2987   std::reverse(Handlers.begin(), Handlers.end());
2988 }
2989
2990 // Given BB which ends in an unwind edge, return the EHPad that this BB belongs
2991 // to. If the unwind edge came from an invoke, return null.
2992 static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) {
2993   const TerminatorInst *TI = BB->getTerminator();
2994   if (isa<InvokeInst>(TI))
2995     return nullptr;
2996   if (isa<CatchPadInst>(TI) || isa<CatchEndPadInst>(TI) ||
2997       isa<TerminatePadInst>(TI))
2998     return BB;
2999   if (auto *CEPI = dyn_cast<CleanupEndPadInst>(TI))
3000     return CEPI->getCleanupPad()->getParent();
3001   return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent();
3002 }
3003
3004 static void calculateExplicitCXXStateNumbers(WinEHFuncInfo &FuncInfo,
3005                                              const BasicBlock &BB,
3006                                              int ParentState) {
3007   assert(BB.isEHPad());
3008   const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3009   // All catchpad instructions will be handled when we process their
3010   // respective catchendpad instruction.
3011   if (isa<CatchPadInst>(FirstNonPHI))
3012     return;
3013
3014   if (isa<CatchEndPadInst>(FirstNonPHI)) {
3015     SmallVector<const CatchPadInst *, 2> Handlers;
3016     findCatchPadsForCatchEndPad(&BB, Handlers);
3017     const BasicBlock *FirstTryPad = Handlers.front()->getParent();
3018     int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
3019     FuncInfo.EHPadStateMap[Handlers.front()] = TryLow;
3020     for (const BasicBlock *PredBlock : predecessors(FirstTryPad))
3021       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3022         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, TryLow);
3023     int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
3024
3025     // catchpads are separate funclets in C++ EH due to the way rethrow works.
3026     // In SEH, they aren't, so no invokes will unwind to the catchendpad.
3027     FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow;
3028     int TryHigh = CatchLow - 1;
3029     for (const BasicBlock *PredBlock : predecessors(&BB))
3030       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3031         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CatchLow);
3032     int CatchHigh = FuncInfo.getLastStateNumber();
3033     addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
3034     DEBUG(dbgs() << "TryLow[" << FirstTryPad->getName() << "]: " << TryLow
3035                  << '\n');
3036     DEBUG(dbgs() << "TryHigh[" << FirstTryPad->getName() << "]: " << TryHigh
3037                  << '\n');
3038     DEBUG(dbgs() << "CatchHigh[" << FirstTryPad->getName() << "]: " << CatchHigh
3039                  << '\n');
3040   } else if (isa<CleanupPadInst>(FirstNonPHI)) {
3041     int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB);
3042     FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
3043     DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
3044                  << BB.getName() << '\n');
3045     for (const BasicBlock *PredBlock : predecessors(&BB))
3046       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3047         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CleanupState);
3048   } else if (isa<TerminatePadInst>(FirstNonPHI)) {
3049     report_fatal_error("Not yet implemented!");
3050   } else {
3051     llvm_unreachable("unexpected EH Pad!");
3052   }
3053 }
3054
3055 static int addSEHHandler(WinEHFuncInfo &FuncInfo, int ParentState,
3056                           const Function *Filter, const BasicBlock *Handler) {
3057   SEHUnwindMapEntry Entry;
3058   Entry.ToState = ParentState;
3059   Entry.Filter = Filter;
3060   Entry.Handler = Handler;
3061   FuncInfo.SEHUnwindMap.push_back(Entry);
3062   return FuncInfo.SEHUnwindMap.size() - 1;
3063 }
3064
3065 static void calculateExplicitSEHStateNumbers(WinEHFuncInfo &FuncInfo,
3066                                              const BasicBlock &BB,
3067                                              int ParentState) {
3068   assert(BB.isEHPad());
3069   const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3070   // All catchpad instructions will be handled when we process their
3071   // respective catchendpad instruction.
3072   if (isa<CatchPadInst>(FirstNonPHI))
3073     return;
3074
3075   if (isa<CatchEndPadInst>(FirstNonPHI)) {
3076     // Extract the filter function and the __except basic block and create a
3077     // state for them.
3078     SmallVector<const CatchPadInst *, 1> Handlers;
3079     findCatchPadsForCatchEndPad(&BB, Handlers);
3080     assert(Handlers.size() == 1 &&
3081            "SEH doesn't have multiple handlers per __try");
3082     const CatchPadInst *CPI = Handlers.front();
3083     const BasicBlock *CatchPadBB = CPI->getParent();
3084     const Function *Filter =
3085         cast<Function>(CPI->getArgOperand(0)->stripPointerCasts());
3086     int TryState =
3087         addSEHHandler(FuncInfo, ParentState, Filter, CPI->getNormalDest());
3088
3089     // Everything in the __try block uses TryState as its parent state.
3090     FuncInfo.EHPadStateMap[CPI] = TryState;
3091     DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
3092                  << CatchPadBB->getName() << '\n');
3093     for (const BasicBlock *PredBlock : predecessors(CatchPadBB))
3094       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3095         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, TryState);
3096
3097     // Everything in the __except block unwinds to ParentState, just like code
3098     // outside the __try.
3099     FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
3100     DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
3101                  << BB.getName() << '\n');
3102     for (const BasicBlock *PredBlock : predecessors(&BB))
3103       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3104         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
3105   } else if (isa<CleanupPadInst>(FirstNonPHI)) {
3106     int CleanupState =
3107         addSEHHandler(FuncInfo, ParentState, /*Filter=*/nullptr, &BB);
3108     FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
3109     DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
3110                  << BB.getName() << '\n');
3111     for (const BasicBlock *PredBlock : predecessors(&BB))
3112       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3113         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, CleanupState);
3114   } else if (isa<TerminatePadInst>(FirstNonPHI)) {
3115     report_fatal_error("Not yet implemented!");
3116   } else {
3117     llvm_unreachable("unexpected EH Pad!");
3118   }
3119 }
3120
3121 /// Check if the EH Pad unwinds to caller.  Cleanups are a little bit of a
3122 /// special case because we have to look at the cleanupret instruction that uses
3123 /// the cleanuppad.
3124 static bool doesEHPadUnwindToCaller(const Instruction *EHPad) {
3125   auto *CPI = dyn_cast<CleanupPadInst>(EHPad);
3126   if (!CPI)
3127     return EHPad->mayThrow();
3128
3129   // This cleanup does not return or unwind, so we say it unwinds to caller.
3130   if (CPI->use_empty())
3131     return true;
3132
3133   const Instruction *User = CPI->user_back();
3134   if (auto *CRI = dyn_cast<CleanupReturnInst>(User))
3135     return CRI->unwindsToCaller();
3136   return cast<CleanupEndPadInst>(User)->unwindsToCaller();
3137 }
3138
3139 void llvm::calculateSEHStateNumbers(const Function *ParentFn,
3140                                     WinEHFuncInfo &FuncInfo) {
3141   // Don't compute state numbers twice.
3142   if (!FuncInfo.SEHUnwindMap.empty())
3143     return;
3144
3145   for (const BasicBlock &BB : *ParentFn) {
3146     if (!BB.isEHPad() || !doesEHPadUnwindToCaller(BB.getFirstNonPHI()))
3147       continue;
3148     calculateExplicitSEHStateNumbers(FuncInfo, BB, -1);
3149   }
3150 }
3151
3152 void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
3153                                          WinEHFuncInfo &FuncInfo) {
3154   // Return if it's already been done.
3155   if (!FuncInfo.EHPadStateMap.empty())
3156     return;
3157
3158   bool IsExplicit = false;
3159   for (const BasicBlock &BB : *ParentFn) {
3160     if (!BB.isEHPad())
3161       continue;
3162     const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3163     // Skip cleanupendpads; they are exits, not entries.
3164     if (isa<CleanupEndPadInst>(FirstNonPHI))
3165       continue;
3166     if (!doesEHPadUnwindToCaller(FirstNonPHI))
3167       continue;
3168     calculateExplicitCXXStateNumbers(FuncInfo, BB, -1);
3169     IsExplicit = true;
3170   }
3171
3172   if (IsExplicit)
3173     return;
3174
3175   WinEHNumbering Num(FuncInfo);
3176   Num.findActionRootLPads(*ParentFn);
3177   // The VisitedHandlers list is used by both findActionRootLPads and
3178   // calculateStateNumbers, but both functions need to visit all handlers.
3179   Num.VisitedHandlers.clear();
3180   Num.calculateStateNumbers(*ParentFn);
3181   // Pop everything on the handler stack.
3182   // It may be necessary to call this more than once because a handler can
3183   // be pushed on the stack as a result of clearing the stack.
3184   while (!Num.HandlerStack.empty())
3185     Num.processCallSite(None, ImmutableCallSite());
3186 }
3187
3188 void WinEHPrepare::colorFunclets(Function &F,
3189                                  SmallVectorImpl<BasicBlock *> &EntryBlocks) {
3190   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist;
3191   BasicBlock *EntryBlock = &F.getEntryBlock();
3192
3193   // Build up the color map, which maps each block to its set of 'colors'.
3194   // For any block B, the "colors" of B are the set of funclets F (possibly
3195   // including a root "funclet" representing the main function), such that
3196   // F will need to directly contain B or a copy of B (where the term "directly
3197   // contain" is used to distinguish from being "transitively contained" in
3198   // a nested funclet).
3199   // Use a CFG walk driven by a worklist of (block, color) pairs.  The "color"
3200   // sets attached during this processing to a block which is the entry of some
3201   // funclet F is actually the set of F's parents -- i.e. the union of colors
3202   // of all predecessors of F's entry.  For all other blocks, the color sets
3203   // are as defined above.  A post-pass fixes up the block color map to reflect
3204   // the same sense of "color" for funclet entries as for other blocks.
3205
3206   Worklist.push_back({EntryBlock, EntryBlock});
3207
3208   while (!Worklist.empty()) {
3209     BasicBlock *Visiting;
3210     BasicBlock *Color;
3211     std::tie(Visiting, Color) = Worklist.pop_back_val();
3212     Instruction *VisitingHead = Visiting->getFirstNonPHI();
3213     if (VisitingHead->isEHPad() && !isa<CatchEndPadInst>(VisitingHead) &&
3214         !isa<CleanupEndPadInst>(VisitingHead)) {
3215       // Mark this as a funclet head as a member of itself.
3216       FuncletBlocks[Visiting].insert(Visiting);
3217       // Queue exits with the parent color.
3218       for (User *Exit : VisitingHead->users()) {
3219         for (BasicBlock *Succ :
3220              successors(cast<Instruction>(Exit)->getParent())) {
3221           if (BlockColors[Succ].insert(Color).second) {
3222             Worklist.push_back({Succ, Color});
3223           }
3224         }
3225       }
3226       // Handle CatchPad specially since its successors need different colors.
3227       if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(VisitingHead)) {
3228         // Visit the normal successor with the color of the new EH pad, and
3229         // visit the unwind successor with the color of the parent.
3230         BasicBlock *NormalSucc = CatchPad->getNormalDest();
3231         if (BlockColors[NormalSucc].insert(Visiting).second) {
3232           Worklist.push_back({NormalSucc, Visiting});
3233         }
3234         BasicBlock *UnwindSucc = CatchPad->getUnwindDest();
3235         if (BlockColors[UnwindSucc].insert(Color).second) {
3236           Worklist.push_back({UnwindSucc, Color});
3237         }
3238         continue;
3239       }
3240       // Switch color to the current node, except for terminate pads which
3241       // have no bodies and only unwind successors and so need their successors
3242       // visited with the color of the parent.
3243       if (!isa<TerminatePadInst>(VisitingHead))
3244         Color = Visiting;
3245     } else {
3246       // Note that this is a member of the given color.
3247       FuncletBlocks[Color].insert(Visiting);
3248       TerminatorInst *Terminator = Visiting->getTerminator();
3249       if (isa<CleanupReturnInst>(Terminator) ||
3250           isa<CatchReturnInst>(Terminator) ||
3251           isa<CleanupEndPadInst>(Terminator)) {
3252         // These block's successors have already been queued with the parent
3253         // color.
3254         continue;
3255       }
3256     }
3257     for (BasicBlock *Succ : successors(Visiting)) {
3258       if (isa<CatchEndPadInst>(Succ->getFirstNonPHI())) {
3259         // The catchendpad needs to be visited with the parent's color, not
3260         // the current color.  This will happen in the code above that visits
3261         // any catchpad unwind successor with the parent color, so we can
3262         // safely skip this successor here.
3263         continue;
3264       }
3265       if (BlockColors[Succ].insert(Color).second) {
3266         Worklist.push_back({Succ, Color});
3267       }
3268     }
3269   }
3270
3271   // The processing above actually accumulated the parent set for this
3272   // funclet into the color set for its entry; use the parent set to
3273   // populate the children map, and reset the color set to include just
3274   // the funclet itself (no instruction can target a funclet entry except on
3275   // that transitions to the child funclet).
3276   for (BasicBlock *FuncletEntry : EntryBlocks) {
3277     std::set<BasicBlock *> &ColorMapItem = BlockColors[FuncletEntry];
3278     for (BasicBlock *Parent : ColorMapItem)
3279       FuncletChildren[Parent].insert(FuncletEntry);
3280     ColorMapItem.clear();
3281     ColorMapItem.insert(FuncletEntry);
3282   }
3283 }
3284
3285 bool WinEHPrepare::prepareExplicitEH(
3286     Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
3287   // Remove unreachable blocks.  It is not valuable to assign them a color and
3288   // their existence can trick us into thinking values are alive when they are
3289   // not.
3290   removeUnreachableBlocks(F);
3291
3292   // Determine which blocks are reachable from which funclet entries.
3293   colorFunclets(F, EntryBlocks);
3294
3295   // Strip PHI nodes off of EH pads.
3296   SmallVector<PHINode *, 16> PHINodes;
3297   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3298     BasicBlock *BB = FI++;
3299     if (!BB->isEHPad())
3300       continue;
3301     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3302       Instruction *I = BI++;
3303       auto *PN = dyn_cast<PHINode>(I);
3304       // Stop at the first non-PHI.
3305       if (!PN)
3306         break;
3307
3308       AllocaInst *SpillSlot = insertPHILoads(PN, F);
3309       if (SpillSlot)
3310         insertPHIStores(PN, SpillSlot);
3311
3312       PHINodes.push_back(PN);
3313     }
3314   }
3315
3316   for (auto *PN : PHINodes) {
3317     // There may be lingering uses on other EH PHIs being removed
3318     PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
3319     PN->eraseFromParent();
3320   }
3321
3322   // Turn all inter-funclet uses of a Value into loads and stores.
3323   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3324     BasicBlock *BB = FI++;
3325     std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3326     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3327       Instruction *I = BI++;
3328       // Funclets are permitted to use static allocas.
3329       if (auto *AI = dyn_cast<AllocaInst>(I))
3330         if (AI->isStaticAlloca())
3331           continue;
3332
3333       demoteNonlocalUses(I, ColorsForBB, F);
3334     }
3335   }
3336   // Also demote function parameters used in funclets.
3337   std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()];
3338   for (Argument &Arg : F.args())
3339     demoteNonlocalUses(&Arg, ColorsForEntry, F);
3340
3341   // We need to clone all blocks which belong to multiple funclets.  Values are
3342   // remapped throughout the funclet to propogate both the new instructions
3343   // *and* the new basic blocks themselves.
3344   for (BasicBlock *FuncletPadBB : EntryBlocks) {
3345     std::set<BasicBlock *> &BlocksInFunclet = FuncletBlocks[FuncletPadBB];
3346
3347     std::map<BasicBlock *, BasicBlock *> Orig2Clone;
3348     ValueToValueMapTy VMap;
3349     for (BasicBlock *BB : BlocksInFunclet) {
3350       std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3351       // We don't need to do anything if the block is monochromatic.
3352       size_t NumColorsForBB = ColorsForBB.size();
3353       if (NumColorsForBB == 1)
3354         continue;
3355
3356       // Create a new basic block and copy instructions into it!
3357       BasicBlock *CBB =
3358           CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
3359       // Insert the clone immediately after the original to ensure determinism
3360       // and to keep the same relative ordering of any funclet's blocks.
3361       CBB->insertInto(&F, BB->getNextNode());
3362
3363       // Add basic block mapping.
3364       VMap[BB] = CBB;
3365
3366       // Record delta operations that we need to perform to our color mappings.
3367       Orig2Clone[BB] = CBB;
3368     }
3369
3370     // Update our color mappings to reflect that one block has lost a color and
3371     // another has gained a color.
3372     for (auto &BBMapping : Orig2Clone) {
3373       BasicBlock *OldBlock = BBMapping.first;
3374       BasicBlock *NewBlock = BBMapping.second;
3375
3376       BlocksInFunclet.insert(NewBlock);
3377       BlockColors[NewBlock].insert(FuncletPadBB);
3378
3379       BlocksInFunclet.erase(OldBlock);
3380       BlockColors[OldBlock].erase(FuncletPadBB);
3381     }
3382
3383     // Loop over all of the instructions in the function, fixing up operand
3384     // references as we go.  This uses VMap to do all the hard work.
3385     for (BasicBlock *BB : BlocksInFunclet)
3386       // Loop over all instructions, fixing each one as we find it...
3387       for (Instruction &I : *BB)
3388         RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
3389   }
3390
3391   // Remove implausible terminators and replace them with UnreachableInst.
3392   for (auto &Funclet : FuncletBlocks) {
3393     BasicBlock *FuncletPadBB = Funclet.first;
3394     std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3395     Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
3396     auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
3397     auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI);
3398
3399     for (BasicBlock *BB : BlocksInFunclet) {
3400       TerminatorInst *TI = BB->getTerminator();
3401       // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
3402       bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad);
3403       // The token consumed by a CatchReturnInst must match the funclet token.
3404       bool IsUnreachableCatchret = false;
3405       if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
3406         IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
3407       // The token consumed by a CleanupReturnInst must match the funclet token.
3408       bool IsUnreachableCleanupret = false;
3409       if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
3410         IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
3411       // The token consumed by a CleanupEndPadInst must match the funclet token.
3412       bool IsUnreachableCleanupendpad = false;
3413       if (auto *CEPI = dyn_cast<CleanupEndPadInst>(TI))
3414         IsUnreachableCleanupendpad = CEPI->getCleanupPad() != CleanupPad;
3415       if (IsUnreachableRet || IsUnreachableCatchret ||
3416           IsUnreachableCleanupret || IsUnreachableCleanupendpad) {
3417         new UnreachableInst(BB->getContext(), TI);
3418         TI->eraseFromParent();
3419       }
3420     }
3421   }
3422
3423   // Clean-up some of the mess we made by removing useles PHI nodes, trivial
3424   // branches, etc.
3425   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3426     BasicBlock *BB = FI++;
3427     SimplifyInstructionsInBlock(BB);
3428     ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
3429     MergeBlockIntoPredecessor(BB);
3430   }
3431
3432   // We might have some unreachable blocks after cleaning up some impossible
3433   // control flow.
3434   removeUnreachableBlocks(F);
3435
3436   // Recolor the CFG to verify that all is well.
3437   for (BasicBlock &BB : F) {
3438     size_t NumColors = BlockColors[&BB].size();
3439     assert(NumColors == 1 && "Expected monochromatic BB!");
3440     if (NumColors == 0)
3441       report_fatal_error("Uncolored BB!");
3442     if (NumColors > 1)
3443       report_fatal_error("Multicolor BB!");
3444     bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
3445     assert(!EHPadHasPHI && "EH Pad still has a PHI!");
3446     if (EHPadHasPHI)
3447       report_fatal_error("EH Pad still has a PHI!");
3448   }
3449
3450   BlockColors.clear();
3451   FuncletBlocks.clear();
3452   FuncletChildren.clear();
3453
3454   return true;
3455 }
3456
3457 // TODO: Share loads when one use dominates another, or when a catchpad exit
3458 // dominates uses (needs dominators).
3459 AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
3460   BasicBlock *PHIBlock = PN->getParent();
3461   AllocaInst *SpillSlot = nullptr;
3462
3463   if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) {
3464     // Insert a load in place of the PHI and replace all uses.
3465     SpillSlot = new AllocaInst(PN->getType(), nullptr,
3466                                Twine(PN->getName(), ".wineh.spillslot"),
3467                                F.getEntryBlock().begin());
3468     Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
3469                             PHIBlock->getFirstInsertionPt());
3470     PN->replaceAllUsesWith(V);
3471     return SpillSlot;
3472   }
3473
3474   DenseMap<BasicBlock *, Value *> Loads;
3475   for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
3476        UI != UE;) {
3477     Use &U = *UI++;
3478     auto *UsingInst = cast<Instruction>(U.getUser());
3479     BasicBlock *UsingBB = UsingInst->getParent();
3480     if (UsingBB->isEHPad()) {
3481       // Use is on an EH pad phi.  Leave it alone; we'll insert loads and
3482       // stores for it separately.
3483       assert(isa<PHINode>(UsingInst));
3484       continue;
3485     }
3486     replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
3487   }
3488   return SpillSlot;
3489 }
3490
3491 // TODO: improve store placement.  Inserting at def is probably good, but need
3492 // to be careful not to introduce interfering stores (needs liveness analysis).
3493 // TODO: identify related phi nodes that can share spill slots, and share them
3494 // (also needs liveness).
3495 void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
3496                                    AllocaInst *SpillSlot) {
3497   // Use a worklist of (Block, Value) pairs -- the given Value needs to be
3498   // stored to the spill slot by the end of the given Block.
3499   SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
3500
3501   Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
3502
3503   while (!Worklist.empty()) {
3504     BasicBlock *EHBlock;
3505     Value *InVal;
3506     std::tie(EHBlock, InVal) = Worklist.pop_back_val();
3507
3508     PHINode *PN = dyn_cast<PHINode>(InVal);
3509     if (PN && PN->getParent() == EHBlock) {
3510       // The value is defined by another PHI we need to remove, with no room to
3511       // insert a store after the PHI, so each predecessor needs to store its
3512       // incoming value.
3513       for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
3514         Value *PredVal = PN->getIncomingValue(i);
3515
3516         // Undef can safely be skipped.
3517         if (isa<UndefValue>(PredVal))
3518           continue;
3519
3520         insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
3521       }
3522     } else {
3523       // We need to store InVal, which dominates EHBlock, but can't put a store
3524       // in EHBlock, so need to put stores in each predecessor.
3525       for (BasicBlock *PredBlock : predecessors(EHBlock)) {
3526         insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
3527       }
3528     }
3529   }
3530 }
3531
3532 void WinEHPrepare::insertPHIStore(
3533     BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
3534     SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
3535
3536   if (PredBlock->isEHPad() &&
3537       !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) {
3538     // Pred is unsplittable, so we need to queue it on the worklist.
3539     Worklist.push_back({PredBlock, PredVal});
3540     return;
3541   }
3542
3543   // Otherwise, insert the store at the end of the basic block.
3544   new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
3545 }
3546
3547 // TODO: Share loads for same-funclet uses (requires dominators if funclets
3548 // aren't properly nested).
3549 void WinEHPrepare::demoteNonlocalUses(Value *V,
3550                                       std::set<BasicBlock *> &ColorsForBB,
3551                                       Function &F) {
3552   // Tokens can only be used non-locally due to control flow involving
3553   // unreachable edges.  Don't try to demote the token usage, we'll simply
3554   // delete the cloned user later.
3555   if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V))
3556     return;
3557
3558   DenseMap<BasicBlock *, Value *> Loads;
3559   AllocaInst *SpillSlot = nullptr;
3560   for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) {
3561     Use &U = *UI++;
3562     auto *UsingInst = cast<Instruction>(U.getUser());
3563     BasicBlock *UsingBB = UsingInst->getParent();
3564
3565     // Is the Use inside a block which is colored the same as the Def?
3566     // If so, we don't need to escape the Def because we will clone
3567     // ourselves our own private copy.
3568     std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
3569     if (ColorsForUsingBB == ColorsForBB)
3570       continue;
3571
3572     replaceUseWithLoad(V, U, SpillSlot, Loads, F);
3573   }
3574   if (SpillSlot) {
3575     // Insert stores of the computed value into the stack slot.
3576     // We have to be careful if I is an invoke instruction,
3577     // because we can't insert the store AFTER the terminator instruction.
3578     BasicBlock::iterator InsertPt;
3579     if (isa<Argument>(V)) {
3580       InsertPt = F.getEntryBlock().getTerminator();
3581     } else if (isa<TerminatorInst>(V)) {
3582       auto *II = cast<InvokeInst>(V);
3583       // We cannot demote invoke instructions to the stack if their normal
3584       // edge is critical. Therefore, split the critical edge and create a
3585       // basic block into which the store can be inserted.
3586       if (!II->getNormalDest()->getSinglePredecessor()) {
3587         unsigned SuccNum =
3588             GetSuccessorNumber(II->getParent(), II->getNormalDest());
3589         assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
3590         BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
3591         assert(NewBlock && "Unable to split critical edge.");
3592         // Update the color mapping for the newly split edge.
3593         std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()];
3594         BlockColors[NewBlock] = ColorsForUsingBB;
3595         for (BasicBlock *FuncletPad : ColorsForUsingBB)
3596           FuncletBlocks[FuncletPad].insert(NewBlock);
3597       }
3598       InsertPt = II->getNormalDest()->getFirstInsertionPt();
3599     } else {
3600       InsertPt = cast<Instruction>(V);
3601       ++InsertPt;
3602       // Don't insert before PHI nodes or EH pad instrs.
3603       for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
3604         ;
3605     }
3606     new StoreInst(V, SpillSlot, InsertPt);
3607   }
3608 }
3609
3610 void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
3611                                       DenseMap<BasicBlock *, Value *> &Loads,
3612                                       Function &F) {
3613   // Lazilly create the spill slot.
3614   if (!SpillSlot)
3615     SpillSlot = new AllocaInst(V->getType(), nullptr,
3616                                Twine(V->getName(), ".wineh.spillslot"),
3617                                F.getEntryBlock().begin());
3618
3619   auto *UsingInst = cast<Instruction>(U.getUser());
3620   if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
3621     // If this is a PHI node, we can't insert a load of the value before
3622     // the use.  Instead insert the load in the predecessor block
3623     // corresponding to the incoming value.
3624     //
3625     // Note that if there are multiple edges from a basic block to this
3626     // PHI node that we cannot have multiple loads.  The problem is that
3627     // the resulting PHI node will have multiple values (from each load)
3628     // coming in from the same block, which is illegal SSA form.
3629     // For this reason, we keep track of and reuse loads we insert.
3630     BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
3631     if (auto *CatchRet =
3632             dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
3633       // Putting a load above a catchret and use on the phi would still leave
3634       // a cross-funclet def/use.  We need to split the edge, change the
3635       // catchret to target the new block, and put the load there.
3636       BasicBlock *PHIBlock = UsingInst->getParent();
3637       BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
3638       // SplitEdge gives us:
3639       //   IncomingBlock:
3640       //     ...
3641       //     br label %NewBlock
3642       //   NewBlock:
3643       //     catchret label %PHIBlock
3644       // But we need:
3645       //   IncomingBlock:
3646       //     ...
3647       //     catchret label %NewBlock
3648       //   NewBlock:
3649       //     br label %PHIBlock
3650       // So move the terminators to each others' blocks and swap their
3651       // successors.
3652       BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
3653       Goto->removeFromParent();
3654       CatchRet->removeFromParent();
3655       IncomingBlock->getInstList().push_back(CatchRet);
3656       NewBlock->getInstList().push_back(Goto);
3657       Goto->setSuccessor(0, PHIBlock);
3658       CatchRet->setSuccessor(NewBlock);
3659       // Update the color mapping for the newly split edge.
3660       std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock];
3661       BlockColors[NewBlock] = ColorsForPHIBlock;
3662       for (BasicBlock *FuncletPad : ColorsForPHIBlock)
3663         FuncletBlocks[FuncletPad].insert(NewBlock);
3664       // Treat the new block as incoming for load insertion.
3665       IncomingBlock = NewBlock;
3666     }
3667     Value *&Load = Loads[IncomingBlock];
3668     // Insert the load into the predecessor block
3669     if (!Load)
3670       Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3671                           /*Volatile=*/false, IncomingBlock->getTerminator());
3672
3673     U.set(Load);
3674   } else {
3675     // Reload right before the old use.
3676     auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3677                               /*Volatile=*/false, UsingInst);
3678     U.set(Load);
3679   }
3680 }