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