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