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