8a0fb7fd1bccbedc491b281d3ae79ea41ec9f181
[oota-llvm.git] / lib / CodeGen / WinEHPrepare.cpp
1 //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass lowers LLVM IR exception handling into something closer to what the
11 // backend wants. It snifs the personality function to see which kind of
12 // preparation is necessary. If the personality function uses the Itanium LSDA,
13 // this pass delegates to the DWARF EH preparation pass.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/TinyPtrVector.h"
23 #include "llvm/Analysis/LibCallSemantics.h"
24 #include "llvm/CodeGen/WinEHFuncInfo.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
40 #include <memory>
41
42 using namespace llvm;
43 using namespace llvm::PatternMatch;
44
45 #define DEBUG_TYPE "winehprepare"
46
47 namespace {
48
49 // This map is used to model frame variable usage during outlining, to
50 // construct a structure type to hold the frame variables in a frame
51 // allocation block, and to remap the frame variable allocas (including
52 // spill locations as needed) to GEPs that get the variable from the
53 // frame allocation structure.
54 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
55
56 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
57 // quite null.
58 AllocaInst *getCatchObjectSentinel() {
59   return static_cast<AllocaInst *>(nullptr) + 1;
60 }
61
62 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
63
64 class LandingPadActions;
65 class LandingPadMap;
66
67 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
68 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
69
70 class WinEHPrepare : public FunctionPass {
71 public:
72   static char ID; // Pass identification, replacement for typeid.
73   WinEHPrepare(const TargetMachine *TM = nullptr)
74       : FunctionPass(ID), DT(nullptr) {}
75
76   bool runOnFunction(Function &Fn) override;
77
78   bool doFinalization(Module &M) override;
79
80   void getAnalysisUsage(AnalysisUsage &AU) const override;
81
82   const char *getPassName() const override {
83     return "Windows exception handling preparation";
84   }
85
86 private:
87   bool prepareExceptionHandlers(Function &F,
88                                 SmallVectorImpl<LandingPadInst *> &LPads);
89   void promoteLandingPadValues(LandingPadInst *LPad);
90   void demoteValuesLiveAcrossHandlers(Function &F,
91                                       SmallVectorImpl<LandingPadInst *> &LPads);
92   void completeNestedLandingPad(Function *ParentFn,
93                                 LandingPadInst *OutlinedLPad,
94                                 const LandingPadInst *OriginalLPad,
95                                 FrameVarInfoMap &VarInfo);
96   bool outlineHandler(ActionHandler *Action, Function *SrcFn,
97                       LandingPadInst *LPad, BasicBlock *StartBB,
98                       FrameVarInfoMap &VarInfo);
99   void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn);
100
101   void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
102   CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
103                                  VisitedBlockSet &VisitedBlocks);
104   void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
105                            BasicBlock *EndBB);
106
107   void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
108
109   // All fields are reset by runOnFunction.
110   DominatorTree *DT;
111   EHPersonality Personality;
112   CatchHandlerMapTy CatchHandlerMap;
113   CleanupHandlerMapTy CleanupHandlerMap;
114   DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
115
116   // This maps landing pad instructions found in outlined handlers to
117   // the landing pad instruction in the parent function from which they
118   // were cloned.  The cloned/nested landing pad is used as the key
119   // because the landing pad may be cloned into multiple handlers.
120   // This map will be used to add the llvm.eh.actions call to the nested
121   // landing pads after all handlers have been outlined.
122   DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
123
124   // This maps blocks in the parent function which are destinations of
125   // catch handlers to cloned blocks in (other) outlined handlers. This
126   // handles the case where a nested landing pads has a catch handler that
127   // returns to a handler function rather than the parent function.
128   // The original block is used as the key here because there should only
129   // ever be one handler function from which the cloned block is not pruned.
130   // The original block will be pruned from the parent function after all
131   // handlers have been outlined.  This map will be used to adjust the
132   // return instructions of handlers which return to the block that was
133   // outlined into a handler.  This is done after all handlers have been
134   // outlined but before the outlined code is pruned from the parent function.
135   DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
136 };
137
138 class WinEHFrameVariableMaterializer : public ValueMaterializer {
139 public:
140   WinEHFrameVariableMaterializer(Function *OutlinedFn,
141                                  FrameVarInfoMap &FrameVarInfo);
142   ~WinEHFrameVariableMaterializer() override {}
143
144   Value *materializeValueFor(Value *V) override;
145
146   void escapeCatchObject(Value *V);
147
148 private:
149   FrameVarInfoMap &FrameVarInfo;
150   IRBuilder<> Builder;
151 };
152
153 class LandingPadMap {
154 public:
155   LandingPadMap() : OriginLPad(nullptr) {}
156   void mapLandingPad(const LandingPadInst *LPad);
157
158   bool isInitialized() { return OriginLPad != nullptr; }
159
160   bool isOriginLandingPadBlock(const BasicBlock *BB) const;
161   bool isLandingPadSpecificInst(const Instruction *Inst) const;
162
163   void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
164                      Value *SelectorValue) const;
165
166 private:
167   const LandingPadInst *OriginLPad;
168   // We will normally only see one of each of these instructions, but
169   // if more than one occurs for some reason we can handle that.
170   TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
171   TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
172 };
173
174 class WinEHCloningDirectorBase : public CloningDirector {
175 public:
176   WinEHCloningDirectorBase(Function *HandlerFn, FrameVarInfoMap &VarInfo,
177                            LandingPadMap &LPadMap)
178       : Materializer(HandlerFn, VarInfo),
179         SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
180         Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
181         LPadMap(LPadMap) {
182     auto AI = HandlerFn->getArgumentList().begin();
183     ++AI;
184     EstablisherFrame = AI;
185   }
186
187   CloningAction handleInstruction(ValueToValueMapTy &VMap,
188                                   const Instruction *Inst,
189                                   BasicBlock *NewBB) override;
190
191   virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
192                                          const Instruction *Inst,
193                                          BasicBlock *NewBB) = 0;
194   virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
195                                        const Instruction *Inst,
196                                        BasicBlock *NewBB) = 0;
197   virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
198                                         const Instruction *Inst,
199                                         BasicBlock *NewBB) = 0;
200   virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
201                                      const InvokeInst *Invoke,
202                                      BasicBlock *NewBB) = 0;
203   virtual CloningAction handleResume(ValueToValueMapTy &VMap,
204                                      const ResumeInst *Resume,
205                                      BasicBlock *NewBB) = 0;
206   virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
207                                       const CmpInst *Compare,
208                                       BasicBlock *NewBB) = 0;
209   virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
210                                          const LandingPadInst *LPad,
211                                          BasicBlock *NewBB) = 0;
212
213   ValueMaterializer *getValueMaterializer() override { return &Materializer; }
214
215 protected:
216   WinEHFrameVariableMaterializer Materializer;
217   Type *SelectorIDType;
218   Type *Int8PtrType;
219   LandingPadMap &LPadMap;
220
221   /// The value representing the parent frame pointer.
222   Value *EstablisherFrame;
223 };
224
225 class WinEHCatchDirector : public WinEHCloningDirectorBase {
226 public:
227   WinEHCatchDirector(
228       Function *CatchFn, Value *Selector, FrameVarInfoMap &VarInfo,
229       LandingPadMap &LPadMap,
230       DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
231       : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
232         CurrentSelector(Selector->stripPointerCasts()),
233         ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
234
235   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
236                                  const Instruction *Inst,
237                                  BasicBlock *NewBB) override;
238   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
239                                BasicBlock *NewBB) override;
240   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
241                                 const Instruction *Inst,
242                                 BasicBlock *NewBB) override;
243   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
244                              BasicBlock *NewBB) override;
245   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
246                              BasicBlock *NewBB) override;
247   CloningAction handleCompare(ValueToValueMapTy &VMap,
248                               const CmpInst *Compare, BasicBlock *NewBB) override;
249   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
250                                  const LandingPadInst *LPad,
251                                  BasicBlock *NewBB) override;
252
253   Value *getExceptionVar() { return ExceptionObjectVar; }
254   TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
255
256 private:
257   Value *CurrentSelector;
258
259   Value *ExceptionObjectVar;
260   TinyPtrVector<BasicBlock *> ReturnTargets;
261
262   // This will be a reference to the field of the same name in the WinEHPrepare
263   // object which instantiates this WinEHCatchDirector object.
264   DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
265 };
266
267 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
268 public:
269   WinEHCleanupDirector(Function *CleanupFn, FrameVarInfoMap &VarInfo,
270                        LandingPadMap &LPadMap)
271       : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
272
273   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
274                                  const Instruction *Inst,
275                                  BasicBlock *NewBB) override;
276   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
277                                BasicBlock *NewBB) override;
278   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
279                                 const Instruction *Inst,
280                                 BasicBlock *NewBB) override;
281   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
282                              BasicBlock *NewBB) override;
283   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
284                              BasicBlock *NewBB) override;
285   CloningAction handleCompare(ValueToValueMapTy &VMap,
286                               const CmpInst *Compare, BasicBlock *NewBB) override;
287   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
288                                  const LandingPadInst *LPad,
289                                  BasicBlock *NewBB) override;
290 };
291
292 class LandingPadActions {
293 public:
294   LandingPadActions() : HasCleanupHandlers(false) {}
295
296   void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
297   void insertCleanupHandler(CleanupHandler *Action) {
298     Actions.push_back(Action);
299     HasCleanupHandlers = true;
300   }
301
302   bool includesCleanup() const { return HasCleanupHandlers; }
303
304   SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
305   SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
306   SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
307
308 private:
309   // Note that this class does not own the ActionHandler objects in this vector.
310   // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
311   // in the WinEHPrepare class.
312   SmallVector<ActionHandler *, 4> Actions;
313   bool HasCleanupHandlers;
314 };
315
316 } // end anonymous namespace
317
318 char WinEHPrepare::ID = 0;
319 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
320                    false, false)
321
322 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
323   return new WinEHPrepare(TM);
324 }
325
326 bool WinEHPrepare::runOnFunction(Function &Fn) {
327   // No need to prepare outlined handlers.
328   if (Fn.hasFnAttribute("wineh-parent"))
329     return false;
330
331   SmallVector<LandingPadInst *, 4> LPads;
332   SmallVector<ResumeInst *, 4> Resumes;
333   for (BasicBlock &BB : Fn) {
334     if (auto *LP = BB.getLandingPadInst())
335       LPads.push_back(LP);
336     if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
337       Resumes.push_back(Resume);
338   }
339
340   // No need to prepare functions that lack landing pads.
341   if (LPads.empty())
342     return false;
343
344   // Classify the personality to see what kind of preparation we need.
345   Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
346
347   // Do nothing if this is not an MSVC personality.
348   if (!isMSVCEHPersonality(Personality))
349     return false;
350
351   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
352
353   // If there were any landing pads, prepareExceptionHandlers will make changes.
354   prepareExceptionHandlers(Fn, LPads);
355   return true;
356 }
357
358 bool WinEHPrepare::doFinalization(Module &M) { return false; }
359
360 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
361   AU.addRequired<DominatorTreeWrapperPass>();
362 }
363
364 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
365                                Constant *&Selector, BasicBlock *&NextBB);
366
367 // Finds blocks reachable from the starting set Worklist. Does not follow unwind
368 // edges or blocks listed in StopPoints.
369 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
370                                 SetVector<BasicBlock *> &Worklist,
371                                 const SetVector<BasicBlock *> *StopPoints) {
372   while (!Worklist.empty()) {
373     BasicBlock *BB = Worklist.pop_back_val();
374
375     // Don't cross blocks that we should stop at.
376     if (StopPoints && StopPoints->count(BB))
377       continue;
378
379     if (!ReachableBBs.insert(BB).second)
380       continue; // Already visited.
381
382     // Don't follow unwind edges of invokes.
383     if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
384       Worklist.insert(II->getNormalDest());
385       continue;
386     }
387
388     // Otherwise, follow all successors.
389     Worklist.insert(succ_begin(BB), succ_end(BB));
390   }
391 }
392
393 /// Find all points where exceptional control rejoins normal control flow via
394 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
395 static void findCXXEHReturnPoints(Function &F,
396                                   SetVector<BasicBlock *> &EHReturnBlocks) {
397   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
398     BasicBlock *BB = BBI;
399     for (Instruction &I : *BB) {
400       if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
401         // Split the block after the call to llvm.eh.endcatch if there is
402         // anything other than an unconditional branch, or if the successor
403         // starts with a phi.
404         auto *Br = dyn_cast<BranchInst>(I.getNextNode());
405         if (!Br || !Br->isUnconditional() ||
406             isa<PHINode>(Br->getSuccessor(0)->begin())) {
407           DEBUG(dbgs() << "splitting block " << BB->getName()
408                        << " with llvm.eh.endcatch\n");
409           BBI = BB->splitBasicBlock(I.getNextNode(), "ehreturn");
410         }
411         // The next BB is normal control flow.
412         EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
413         break;
414       }
415     }
416   }
417 }
418
419 static bool isCatchAllLandingPad(const BasicBlock *BB) {
420   const LandingPadInst *LP = BB->getLandingPadInst();
421   if (!LP)
422     return false;
423   unsigned N = LP->getNumClauses();
424   return (N > 0 && LP->isCatch(N - 1) &&
425           isa<ConstantPointerNull>(LP->getClause(N - 1)));
426 }
427
428 /// Find all points where exceptions control rejoins normal control flow via
429 /// selector dispatch.
430 static void findSEHEHReturnPoints(Function &F,
431                                   SetVector<BasicBlock *> &EHReturnBlocks) {
432   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
433     BasicBlock *BB = BBI;
434     // If the landingpad is a catch-all, treat the whole lpad as if it is
435     // reachable from normal control flow.
436     // FIXME: This is imprecise. We need a better way of identifying where a
437     // catch-all starts and cleanups stop. As far as LLVM is concerned, there
438     // is no difference.
439     if (isCatchAllLandingPad(BB)) {
440       EHReturnBlocks.insert(BB);
441       continue;
442     }
443
444     BasicBlock *CatchHandler;
445     BasicBlock *NextBB;
446     Constant *Selector;
447     if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
448       // Split the edge if there is a phi node. Returning from EH to a phi node
449       // is just as impossible as having a phi after an indirectbr.
450       if (isa<PHINode>(CatchHandler->begin())) {
451         DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
452                      << " to " << CatchHandler->getName() << '\n');
453         BBI = CatchHandler = SplitCriticalEdge(
454             BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
455       }
456       EHReturnBlocks.insert(CatchHandler);
457     }
458   }
459 }
460
461 /// Ensure that all values live into and out of exception handlers are stored
462 /// in memory.
463 /// FIXME: This falls down when values are defined in one handler and live into
464 /// another handler. For example, a cleanup defines a value used only by a
465 /// catch handler.
466 void WinEHPrepare::demoteValuesLiveAcrossHandlers(
467     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
468   DEBUG(dbgs() << "Demoting values live across exception handlers in function "
469                << F.getName() << '\n');
470
471   // Build a set of all non-exceptional blocks and exceptional blocks.
472   // - Non-exceptional blocks are blocks reachable from the entry block while
473   //   not following invoke unwind edges.
474   // - Exceptional blocks are blocks reachable from landingpads. Analysis does
475   //   not follow llvm.eh.endcatch blocks, which mark a transition from
476   //   exceptional to normal control.
477   SmallPtrSet<BasicBlock *, 4> NormalBlocks;
478   SmallPtrSet<BasicBlock *, 4> EHBlocks;
479   SetVector<BasicBlock *> EHReturnBlocks;
480   SetVector<BasicBlock *> Worklist;
481
482   if (Personality == EHPersonality::MSVC_CXX)
483     findCXXEHReturnPoints(F, EHReturnBlocks);
484   else
485     findSEHEHReturnPoints(F, EHReturnBlocks);
486
487   DEBUG({
488     dbgs() << "identified the following blocks as EH return points:\n";
489     for (BasicBlock *BB : EHReturnBlocks)
490       dbgs() << "  " << BB->getName() << '\n';
491   });
492
493   // Join points should not have phis at this point, unless they are a
494   // landingpad, in which case we will demote their phis later.
495 #ifndef NDEBUG
496   for (BasicBlock *BB : EHReturnBlocks)
497     assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
498            "non-lpad EH return block has phi");
499 #endif
500
501   // Normal blocks are the blocks reachable from the entry block and all EH
502   // return points.
503   Worklist = EHReturnBlocks;
504   Worklist.insert(&F.getEntryBlock());
505   findReachableBlocks(NormalBlocks, Worklist, nullptr);
506   DEBUG({
507     dbgs() << "marked the following blocks as normal:\n";
508     for (BasicBlock *BB : NormalBlocks)
509       dbgs() << "  " << BB->getName() << '\n';
510   });
511
512   // Exceptional blocks are the blocks reachable from landingpads that don't
513   // cross EH return points.
514   Worklist.clear();
515   for (auto *LPI : LPads)
516     Worklist.insert(LPI->getParent());
517   findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
518   DEBUG({
519     dbgs() << "marked the following blocks as exceptional:\n";
520     for (BasicBlock *BB : EHBlocks)
521       dbgs() << "  " << BB->getName() << '\n';
522   });
523
524   SetVector<Argument *> ArgsToDemote;
525   SetVector<Instruction *> InstrsToDemote;
526   for (BasicBlock &BB : F) {
527     bool IsNormalBB = NormalBlocks.count(&BB);
528     bool IsEHBB = EHBlocks.count(&BB);
529     if (!IsNormalBB && !IsEHBB)
530       continue; // Blocks that are neither normal nor EH are unreachable.
531     for (Instruction &I : BB) {
532       for (Value *Op : I.operands()) {
533         // Don't demote static allocas, constants, and labels.
534         if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
535           continue;
536         auto *AI = dyn_cast<AllocaInst>(Op);
537         if (AI && AI->isStaticAlloca())
538           continue;
539
540         if (auto *Arg = dyn_cast<Argument>(Op)) {
541           if (IsEHBB) {
542             DEBUG(dbgs() << "Demoting argument " << *Arg
543                          << " used by EH instr: " << I << "\n");
544             ArgsToDemote.insert(Arg);
545           }
546           continue;
547         }
548
549         auto *OpI = cast<Instruction>(Op);
550         BasicBlock *OpBB = OpI->getParent();
551         // If a value is produced and consumed in the same BB, we don't need to
552         // demote it.
553         if (OpBB == &BB)
554           continue;
555         bool IsOpNormalBB = NormalBlocks.count(OpBB);
556         bool IsOpEHBB = EHBlocks.count(OpBB);
557         if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
558           DEBUG({
559             dbgs() << "Demoting instruction live in-out from EH:\n";
560             dbgs() << "Instr: " << *OpI << '\n';
561             dbgs() << "User: " << I << '\n';
562           });
563           InstrsToDemote.insert(OpI);
564         }
565       }
566     }
567   }
568
569   // Demote values live into and out of handlers.
570   // FIXME: This demotion is inefficient. We should insert spills at the point
571   // of definition, insert one reload in each handler that uses the value, and
572   // insert reloads in the BB used to rejoin normal control flow.
573   Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
574   for (Instruction *I : InstrsToDemote)
575     DemoteRegToStack(*I, false, AllocaInsertPt);
576
577   // Demote arguments separately, and only for uses in EH blocks.
578   for (Argument *Arg : ArgsToDemote) {
579     auto *Slot = new AllocaInst(Arg->getType(), nullptr,
580                                 Arg->getName() + ".reg2mem", AllocaInsertPt);
581     SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
582     for (User *U : Users) {
583       auto *I = dyn_cast<Instruction>(U);
584       if (I && EHBlocks.count(I->getParent())) {
585         auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
586         U->replaceUsesOfWith(Arg, Reload);
587       }
588     }
589     new StoreInst(Arg, Slot, AllocaInsertPt);
590   }
591
592   // Demote landingpad phis, as the landingpad will be removed from the machine
593   // CFG.
594   for (LandingPadInst *LPI : LPads) {
595     BasicBlock *BB = LPI->getParent();
596     while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
597       DemotePHIToStack(Phi, AllocaInsertPt);
598   }
599
600   DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
601                << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
602 }
603
604 bool WinEHPrepare::prepareExceptionHandlers(
605     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
606   // Don't run on functions that are already prepared.
607   for (LandingPadInst *LPad : LPads) {
608     BasicBlock *LPadBB = LPad->getParent();
609     for (Instruction &Inst : *LPadBB)
610       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
611         return false;
612   }
613
614   demoteValuesLiveAcrossHandlers(F, LPads);
615
616   // These containers are used to re-map frame variables that are used in
617   // outlined catch and cleanup handlers.  They will be populated as the
618   // handlers are outlined.
619   FrameVarInfoMap FrameVarInfo;
620
621   bool HandlersOutlined = false;
622
623   Module *M = F.getParent();
624   LLVMContext &Context = M->getContext();
625
626   // Create a new function to receive the handler contents.
627   PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
628   Type *Int32Type = Type::getInt32Ty(Context);
629   Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
630
631   for (LandingPadInst *LPad : LPads) {
632     // Look for evidence that this landingpad has already been processed.
633     bool LPadHasActionList = false;
634     BasicBlock *LPadBB = LPad->getParent();
635     for (Instruction &Inst : *LPadBB) {
636       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
637         LPadHasActionList = true;
638         break;
639       }
640     }
641
642     // If we've already outlined the handlers for this landingpad,
643     // there's nothing more to do here.
644     if (LPadHasActionList)
645       continue;
646
647     // If either of the values in the aggregate returned by the landing pad is
648     // extracted and stored to memory, promote the stored value to a register.
649     promoteLandingPadValues(LPad);
650
651     LandingPadActions Actions;
652     mapLandingPadBlocks(LPad, Actions);
653
654     HandlersOutlined |= !Actions.actions().empty();
655     for (ActionHandler *Action : Actions) {
656       if (Action->hasBeenProcessed())
657         continue;
658       BasicBlock *StartBB = Action->getStartBlock();
659
660       // SEH doesn't do any outlining for catches. Instead, pass the handler
661       // basic block addr to llvm.eh.actions and list the block as a return
662       // target.
663       if (isAsynchronousEHPersonality(Personality)) {
664         if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
665           processSEHCatchHandler(CatchAction, StartBB);
666           continue;
667         }
668       }
669
670       outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
671     }
672
673     // Split the block after the landingpad instruction so that it is just a
674     // call to llvm.eh.actions followed by indirectbr.
675     assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
676     LPadBB->splitBasicBlock(LPad->getNextNode(),
677                             LPadBB->getName() + ".prepsplit");
678     // Erase the branch inserted by the split so we can insert indirectbr.
679     LPadBB->getTerminator()->eraseFromParent();
680
681     // Replace all extracted values with undef and ultimately replace the
682     // landingpad with undef.
683     // FIXME: This doesn't handle SEH GetExceptionCode(). For now, we just give
684     // out undef until we figure out the codegen support.
685     SmallVector<Instruction *, 4> Extracts;
686     for (User *U : LPad->users()) {
687       auto *E = dyn_cast<ExtractValueInst>(U);
688       if (!E)
689         continue;
690       assert(E->getNumIndices() == 1 &&
691              "Unexpected operation: extracting both landing pad values");
692       Extracts.push_back(E);
693     }
694     for (Instruction *E : Extracts) {
695       E->replaceAllUsesWith(UndefValue::get(E->getType()));
696       E->eraseFromParent();
697     }
698     LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
699
700     // Add a call to describe the actions for this landing pad.
701     std::vector<Value *> ActionArgs;
702     for (ActionHandler *Action : Actions) {
703       // Action codes from docs are: 0 cleanup, 1 catch.
704       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
705         ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
706         ActionArgs.push_back(CatchAction->getSelector());
707         // Find the frame escape index of the exception object alloca in the
708         // parent.
709         int FrameEscapeIdx = -1;
710         Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
711         if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
712           auto I = FrameVarInfo.find(EHObj);
713           assert(I != FrameVarInfo.end() &&
714                  "failed to map llvm.eh.begincatch var");
715           FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
716         }
717         ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
718       } else {
719         ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
720       }
721       ActionArgs.push_back(Action->getHandlerBlockOrFunc());
722     }
723     CallInst *Recover =
724         CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
725
726     // Add an indirect branch listing possible successors of the catch handlers.
727     SetVector<BasicBlock *> ReturnTargets;
728     for (ActionHandler *Action : Actions) {
729       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
730         const auto &CatchTargets = CatchAction->getReturnTargets();
731         ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
732       }
733     }
734     IndirectBrInst *Branch =
735         IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
736     for (BasicBlock *Target : ReturnTargets)
737       Branch->addDestination(Target);
738   } // End for each landingpad
739
740   // If nothing got outlined, there is no more processing to be done.
741   if (!HandlersOutlined)
742     return false;
743
744   // Replace any nested landing pad stubs with the correct action handler.
745   // This must be done before we remove unreachable blocks because it
746   // cleans up references to outlined blocks that will be deleted.
747   for (auto &LPadPair : NestedLPtoOriginalLP)
748     completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
749   NestedLPtoOriginalLP.clear();
750
751   F.addFnAttr("wineh-parent", F.getName());
752
753   // Delete any blocks that were only used by handlers that were outlined above.
754   removeUnreachableBlocks(F);
755
756   BasicBlock *Entry = &F.getEntryBlock();
757   IRBuilder<> Builder(F.getParent()->getContext());
758   Builder.SetInsertPoint(Entry->getFirstInsertionPt());
759
760   Function *FrameEscapeFn =
761       Intrinsic::getDeclaration(M, Intrinsic::frameescape);
762   Function *RecoverFrameFn =
763       Intrinsic::getDeclaration(M, Intrinsic::framerecover);
764   SmallVector<Value *, 8> AllocasToEscape;
765
766   // Scan the entry block for an existing call to llvm.frameescape. We need to
767   // keep escaping those objects.
768   for (Instruction &I : F.front()) {
769     auto *II = dyn_cast<IntrinsicInst>(&I);
770     if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
771       auto Args = II->arg_operands();
772       AllocasToEscape.append(Args.begin(), Args.end());
773       II->eraseFromParent();
774       break;
775     }
776   }
777
778   // Finally, replace all of the temporary allocas for frame variables used in
779   // the outlined handlers with calls to llvm.framerecover.
780   for (auto &VarInfoEntry : FrameVarInfo) {
781     Value *ParentVal = VarInfoEntry.first;
782     TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
783     AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
784
785     // FIXME: We should try to sink unescaped allocas from the parent frame into
786     // the child frame. If the alloca is escaped, we have to use the lifetime
787     // markers to ensure that the alloca is only live within the child frame.
788
789     // Add this alloca to the list of things to escape.
790     AllocasToEscape.push_back(ParentAlloca);
791
792     // Next replace all outlined allocas that are mapped to it.
793     for (AllocaInst *TempAlloca : Allocas) {
794       if (TempAlloca == getCatchObjectSentinel())
795         continue; // Skip catch parameter sentinels.
796       Function *HandlerFn = TempAlloca->getParent()->getParent();
797       // FIXME: Sink this GEP into the blocks where it is used.
798       Builder.SetInsertPoint(TempAlloca);
799       Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
800       Value *RecoverArgs[] = {
801           Builder.CreateBitCast(&F, Int8PtrType, ""),
802           &(HandlerFn->getArgumentList().back()),
803           llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
804       Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
805       // Add a pointer bitcast if the alloca wasn't an i8.
806       if (RecoveredAlloca->getType() != TempAlloca->getType()) {
807         RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
808         RecoveredAlloca =
809             Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
810       }
811       TempAlloca->replaceAllUsesWith(RecoveredAlloca);
812       TempAlloca->removeFromParent();
813       RecoveredAlloca->takeName(TempAlloca);
814       delete TempAlloca;
815     }
816   } // End for each FrameVarInfo entry.
817
818   // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
819   // block.
820   Builder.SetInsertPoint(&F.getEntryBlock().back());
821   Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
822
823   // Clean up the handler action maps we created for this function
824   DeleteContainerSeconds(CatchHandlerMap);
825   CatchHandlerMap.clear();
826   DeleteContainerSeconds(CleanupHandlerMap);
827   CleanupHandlerMap.clear();
828
829   return HandlersOutlined;
830 }
831
832 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
833   // If the return values of the landing pad instruction are extracted and
834   // stored to memory, we want to promote the store locations to reg values.
835   SmallVector<AllocaInst *, 2> EHAllocas;
836
837   // The landingpad instruction returns an aggregate value.  Typically, its
838   // value will be passed to a pair of extract value instructions and the
839   // results of those extracts are often passed to store instructions.
840   // In unoptimized code the stored value will often be loaded and then stored
841   // again.
842   for (auto *U : LPad->users()) {
843     ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
844     if (!Extract)
845       continue;
846
847     for (auto *EU : Extract->users()) {
848       if (auto *Store = dyn_cast<StoreInst>(EU)) {
849         auto *AV = cast<AllocaInst>(Store->getPointerOperand());
850         EHAllocas.push_back(AV);
851       }
852     }
853   }
854
855   // We can't do this without a dominator tree.
856   assert(DT);
857
858   if (!EHAllocas.empty()) {
859     PromoteMemToReg(EHAllocas, *DT);
860     EHAllocas.clear();
861   }
862
863   // After promotion, some extracts may be trivially dead. Remove them.
864   SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
865   for (auto *U : Users)
866     RecursivelyDeleteTriviallyDeadInstructions(U);
867 }
868
869 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
870                                             LandingPadInst *OutlinedLPad,
871                                             const LandingPadInst *OriginalLPad,
872                                             FrameVarInfoMap &FrameVarInfo) {
873   // Get the nested block and erase the unreachable instruction that was
874   // temporarily inserted as its terminator.
875   LLVMContext &Context = ParentFn->getContext();
876   BasicBlock *OutlinedBB = OutlinedLPad->getParent();
877   assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
878   OutlinedBB->getTerminator()->eraseFromParent();
879   // That should leave OutlinedLPad as the last instruction in its block.
880   assert(&OutlinedBB->back() == OutlinedLPad);
881
882   // The original landing pad will have already had its action intrinsic
883   // built by the outlining loop.  We need to clone that into the outlined
884   // location.  It may also be necessary to add references to the exception
885   // variables to the outlined handler in which this landing pad is nested
886   // and remap return instructions in the nested handlers that should return
887   // to an address in the outlined handler.
888   Function *OutlinedHandlerFn = OutlinedBB->getParent();
889   BasicBlock::const_iterator II = OriginalLPad;
890   ++II;
891   // The instruction after the landing pad should now be a call to eh.actions.
892   const Instruction *Recover = II;
893   assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
894   IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
895
896   // Remap the exception variables into the outlined function.
897   WinEHFrameVariableMaterializer Materializer(OutlinedHandlerFn, FrameVarInfo);
898   SmallVector<BlockAddress *, 4> ActionTargets;
899   SmallVector<ActionHandler *, 4> ActionList;
900   parseEHActions(EHActions, ActionList);
901   for (auto *Action : ActionList) {
902     auto *Catch = dyn_cast<CatchHandler>(Action);
903     if (!Catch)
904       continue;
905     // The dyn_cast to function here selects C++ catch handlers and skips
906     // SEH catch handlers.
907     auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
908     if (!Handler)
909       continue;
910     // Visit all the return instructions, looking for places that return
911     // to a location within OutlinedHandlerFn.
912     for (BasicBlock &NestedHandlerBB : *Handler) {
913       auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
914       if (!Ret)
915         continue;
916
917       // Handler functions must always return a block address.
918       BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
919       // The original target will have been in the main parent function,
920       // but if it is the address of a block that has been outlined, it
921       // should be a block that was outlined into OutlinedHandlerFn.
922       assert(BA->getFunction() == ParentFn);
923
924       // Ignore targets that aren't part of OutlinedHandlerFn.
925       if (!LPadTargetBlocks.count(BA->getBasicBlock()))
926         continue;
927
928       // If the return value is the address ofF a block that we
929       // previously outlined into the parent handler function, replace
930       // the return instruction and add the mapped target to the list
931       // of possible return addresses.
932       BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
933       assert(MappedBB->getParent() == OutlinedHandlerFn);
934       BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
935       Ret->eraseFromParent();
936       ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
937       ActionTargets.push_back(NewBA);
938     }
939   }
940   DeleteContainerPointers(ActionList);
941   ActionList.clear();
942   OutlinedBB->getInstList().push_back(EHActions);
943
944   // Insert an indirect branch into the outlined landing pad BB.
945   IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
946   // Add the previously collected action targets.
947   for (auto *Target : ActionTargets)
948     IBr->addDestination(Target->getBasicBlock());
949 }
950
951 // This function examines a block to determine whether the block ends with a
952 // conditional branch to a catch handler based on a selector comparison.
953 // This function is used both by the WinEHPrepare::findSelectorComparison() and
954 // WinEHCleanupDirector::handleTypeIdFor().
955 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
956                                Constant *&Selector, BasicBlock *&NextBB) {
957   ICmpInst::Predicate Pred;
958   BasicBlock *TBB, *FBB;
959   Value *LHS, *RHS;
960
961   if (!match(BB->getTerminator(),
962              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
963     return false;
964
965   if (!match(LHS,
966              m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
967       !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
968     return false;
969
970   if (Pred == CmpInst::ICMP_EQ) {
971     CatchHandler = TBB;
972     NextBB = FBB;
973     return true;
974   }
975
976   if (Pred == CmpInst::ICMP_NE) {
977     CatchHandler = FBB;
978     NextBB = TBB;
979     return true;
980   }
981
982   return false;
983 }
984
985 static bool isCatchBlock(BasicBlock *BB) {
986   for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
987        II != IE; ++II) {
988     if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
989       return true;
990   }
991   return false;
992 }
993
994 static BasicBlock *createStubLandingPad(Function *Handler,
995                                         Value *PersonalityFn) {
996   // FIXME: Finish this!
997   LLVMContext &Context = Handler->getContext();
998   BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
999   Handler->getBasicBlockList().push_back(StubBB);
1000   IRBuilder<> Builder(StubBB);
1001   LandingPadInst *LPad = Builder.CreateLandingPad(
1002       llvm::StructType::get(Type::getInt8PtrTy(Context),
1003                             Type::getInt32Ty(Context), nullptr),
1004       PersonalityFn, 0);
1005   // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1006   Function *ActionIntrin = Intrinsic::getDeclaration(Handler->getParent(),
1007                                                      Intrinsic::eh_actions);
1008   Builder.CreateCall(ActionIntrin, "recover");
1009   LPad->setCleanup(true);
1010   Builder.CreateUnreachable();
1011   return StubBB;
1012 }
1013
1014 // Cycles through the blocks in an outlined handler function looking for an
1015 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1016 // landing pad if none is found.  The code that generates the .xdata tables for
1017 // the handler needs at least one landing pad to identify the parent function's
1018 // personality.
1019 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
1020                                                   Value *PersonalityFn) {
1021   ReturnInst *Ret = nullptr;
1022   UnreachableInst *Unreached = nullptr;
1023   for (BasicBlock &BB : *Handler) {
1024     TerminatorInst *Terminator = BB.getTerminator();
1025     // If we find an invoke, there is nothing to be done.
1026     auto *II = dyn_cast<InvokeInst>(Terminator);
1027     if (II)
1028       return;
1029     // If we've already recorded a return instruction, keep looking for invokes.
1030     if (!Ret)
1031       Ret = dyn_cast<ReturnInst>(Terminator);
1032     // If we haven't recorded an unreachable instruction, try this terminator.
1033     if (!Unreached)
1034       Unreached = dyn_cast<UnreachableInst>(Terminator);
1035   }
1036
1037   // If we got this far, the handler contains no invokes.  We should have seen
1038   // at least one return or unreachable instruction.  We'll insert an invoke of
1039   // llvm.donothing ahead of that instruction.
1040   assert(Ret || Unreached);
1041   TerminatorInst *Term;
1042   if (Ret)
1043     Term = Ret;
1044   else
1045     Term = Unreached;
1046   BasicBlock *OldRetBB = Term->getParent();
1047   BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term);
1048   // SplitBlock adds an unconditional branch instruction at the end of the
1049   // parent block.  We want to replace that with an invoke call, so we can
1050   // erase it now.
1051   OldRetBB->getTerminator()->eraseFromParent();
1052   BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
1053   Function *F =
1054       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1055   InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1056 }
1057
1058 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1059                                   LandingPadInst *LPad, BasicBlock *StartBB,
1060                                   FrameVarInfoMap &VarInfo) {
1061   Module *M = SrcFn->getParent();
1062   LLVMContext &Context = M->getContext();
1063
1064   // Create a new function to receive the handler contents.
1065   Type *Int8PtrType = Type::getInt8PtrTy(Context);
1066   std::vector<Type *> ArgTys;
1067   ArgTys.push_back(Int8PtrType);
1068   ArgTys.push_back(Int8PtrType);
1069   Function *Handler;
1070   if (Action->getType() == Catch) {
1071     FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
1072     Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
1073                                SrcFn->getName() + ".catch", M);
1074   } else {
1075     FunctionType *FnType =
1076         FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
1077     Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
1078                                SrcFn->getName() + ".cleanup", M);
1079   }
1080
1081   Handler->addFnAttr("wineh-parent", SrcFn->getName());
1082
1083   // Generate a standard prolog to setup the frame recovery structure.
1084   IRBuilder<> Builder(Context);
1085   BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1086   Handler->getBasicBlockList().push_front(Entry);
1087   Builder.SetInsertPoint(Entry);
1088   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1089
1090   std::unique_ptr<WinEHCloningDirectorBase> Director;
1091
1092   ValueToValueMapTy VMap;
1093
1094   LandingPadMap &LPadMap = LPadMaps[LPad];
1095   if (!LPadMap.isInitialized())
1096     LPadMap.mapLandingPad(LPad);
1097   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1098     Constant *Sel = CatchAction->getSelector();
1099     Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
1100                                           NestedLPtoOriginalLP));
1101     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1102                           ConstantInt::get(Type::getInt32Ty(Context), 1));
1103   } else {
1104     Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
1105     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1106                           UndefValue::get(Type::getInt32Ty(Context)));
1107   }
1108
1109   SmallVector<ReturnInst *, 8> Returns;
1110   ClonedCodeInfo OutlinedFunctionInfo;
1111
1112   // If the start block contains PHI nodes, we need to map them.
1113   BasicBlock::iterator II = StartBB->begin();
1114   while (auto *PN = dyn_cast<PHINode>(II)) {
1115     bool Mapped = false;
1116     // Look for PHI values that we have already mapped (such as the selector).
1117     for (Value *Val : PN->incoming_values()) {
1118       if (VMap.count(Val)) {
1119         VMap[PN] = VMap[Val];
1120         Mapped = true;
1121       }
1122     }
1123     // If we didn't find a match for this value, map it as an undef.
1124     if (!Mapped) {
1125       VMap[PN] = UndefValue::get(PN->getType());
1126     }
1127     ++II;
1128   }
1129
1130   // The landing pad value may be used by PHI nodes.  It will ultimately be
1131   // eliminated, but we need it in the map for intermediate handling.
1132   VMap[LPad] = UndefValue::get(LPad->getType());
1133
1134   // Skip over PHIs and, if applicable, landingpad instructions.
1135   II = StartBB->getFirstInsertionPt();
1136
1137   CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1138                             /*ModuleLevelChanges=*/false, Returns, "",
1139                             &OutlinedFunctionInfo, Director.get());
1140
1141   // Move all the instructions in the first cloned block into our entry block.
1142   BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
1143   Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
1144   FirstClonedBB->eraseFromParent();
1145
1146   // Make sure we can identify the handler's personality later.
1147   addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
1148
1149   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1150     WinEHCatchDirector *CatchDirector =
1151         reinterpret_cast<WinEHCatchDirector *>(Director.get());
1152     CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1153     CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1154
1155     // Look for blocks that are not part of the landing pad that we just
1156     // outlined but terminate with a call to llvm.eh.endcatch and a
1157     // branch to a block that is in the handler we just outlined.
1158     // These blocks will be part of a nested landing pad that intends to
1159     // return to an address in this handler.  This case is best handled
1160     // after both landing pads have been outlined, so for now we'll just
1161     // save the association of the blocks in LPadTargetBlocks.  The
1162     // return instructions which are created from these branches will be
1163     // replaced after all landing pads have been outlined.
1164     for (const auto MapEntry : VMap) {
1165       // VMap maps all values and blocks that were just cloned, but dead
1166       // blocks which were pruned will map to nullptr.
1167       if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1168         continue;
1169       const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1170       for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1171         auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1172         if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1173           continue;
1174         BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1175         --II;
1176         if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1177           // This would indicate that a nested landing pad wants to return
1178           // to a block that is outlined into two different handlers.
1179           assert(!LPadTargetBlocks.count(MappedBB));
1180           LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1181         }
1182       }
1183     }
1184   } // End if (CatchAction)
1185
1186   Action->setHandlerBlockOrFunc(Handler);
1187
1188   return true;
1189 }
1190
1191 /// This BB must end in a selector dispatch. All we need to do is pass the
1192 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1193 /// target.
1194 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1195                                           BasicBlock *StartBB) {
1196   BasicBlock *HandlerBB;
1197   BasicBlock *NextBB;
1198   Constant *Selector;
1199   bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1200   if (Res) {
1201     // If this was EH dispatch, this must be a conditional branch to the handler
1202     // block.
1203     // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1204     // leading to crashes if some optimization hoists stuff here.
1205     assert(CatchAction->getSelector() && HandlerBB &&
1206            "expected catch EH dispatch");
1207   } else {
1208     // This must be a catch-all. Split the block after the landingpad.
1209     assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1210     HandlerBB =
1211         StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
1212   }
1213   CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1214   TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1215   CatchAction->setReturnTargets(Targets);
1216 }
1217
1218 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1219   // Each instance of this class should only ever be used to map a single
1220   // landing pad.
1221   assert(OriginLPad == nullptr || OriginLPad == LPad);
1222
1223   // If the landing pad has already been mapped, there's nothing more to do.
1224   if (OriginLPad == LPad)
1225     return;
1226
1227   OriginLPad = LPad;
1228
1229   // The landingpad instruction returns an aggregate value.  Typically, its
1230   // value will be passed to a pair of extract value instructions and the
1231   // results of those extracts will have been promoted to reg values before
1232   // this routine is called.
1233   for (auto *U : LPad->users()) {
1234     const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1235     if (!Extract)
1236       continue;
1237     assert(Extract->getNumIndices() == 1 &&
1238            "Unexpected operation: extracting both landing pad values");
1239     unsigned int Idx = *(Extract->idx_begin());
1240     assert((Idx == 0 || Idx == 1) &&
1241            "Unexpected operation: extracting an unknown landing pad element");
1242     if (Idx == 0) {
1243       ExtractedEHPtrs.push_back(Extract);
1244     } else if (Idx == 1) {
1245       ExtractedSelectors.push_back(Extract);
1246     }
1247   }
1248 }
1249
1250 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1251   return BB->getLandingPadInst() == OriginLPad;
1252 }
1253
1254 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1255   if (Inst == OriginLPad)
1256     return true;
1257   for (auto *Extract : ExtractedEHPtrs) {
1258     if (Inst == Extract)
1259       return true;
1260   }
1261   for (auto *Extract : ExtractedSelectors) {
1262     if (Inst == Extract)
1263       return true;
1264   }
1265   return false;
1266 }
1267
1268 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1269                                   Value *SelectorValue) const {
1270   // Remap all landing pad extract instructions to the specified values.
1271   for (auto *Extract : ExtractedEHPtrs)
1272     VMap[Extract] = EHPtrValue;
1273   for (auto *Extract : ExtractedSelectors)
1274     VMap[Extract] = SelectorValue;
1275 }
1276
1277 static bool isFrameAddressCall(const Value *V) {
1278   return match(const_cast<Value *>(V),
1279                m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1280 }
1281
1282 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1283     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1284   // If this is one of the boilerplate landing pad instructions, skip it.
1285   // The instruction will have already been remapped in VMap.
1286   if (LPadMap.isLandingPadSpecificInst(Inst))
1287     return CloningDirector::SkipInstruction;
1288
1289   // Nested landing pads will be cloned as stubs, with just the
1290   // landingpad instruction and an unreachable instruction. When
1291   // all landingpads have been outlined, we'll replace this with the
1292   // llvm.eh.actions call and indirect branch created when the
1293   // landing pad was outlined.
1294   if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1295     return handleLandingPad(VMap, LPad, NewBB);
1296   }
1297
1298   if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1299     return handleInvoke(VMap, Invoke, NewBB);
1300
1301   if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1302     return handleResume(VMap, Resume, NewBB);
1303
1304   if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1305     return handleCompare(VMap, Cmp, NewBB);
1306
1307   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1308     return handleBeginCatch(VMap, Inst, NewBB);
1309   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1310     return handleEndCatch(VMap, Inst, NewBB);
1311   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1312     return handleTypeIdFor(VMap, Inst, NewBB);
1313
1314   // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1315   // which is the FP of the parent.
1316   if (isFrameAddressCall(Inst)) {
1317     VMap[Inst] = EstablisherFrame;
1318     return CloningDirector::SkipInstruction;
1319   }
1320
1321   // Continue with the default cloning behavior.
1322   return CloningDirector::CloneInstruction;
1323 }
1324
1325 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1326     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1327   Instruction *NewInst = LPad->clone();
1328   if (LPad->hasName())
1329     NewInst->setName(LPad->getName());
1330   // Save this correlation for later processing.
1331   NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1332   VMap[LPad] = NewInst;
1333   BasicBlock::InstListType &InstList = NewBB->getInstList();
1334   InstList.push_back(NewInst);
1335   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1336   return CloningDirector::StopCloningBB;
1337 }
1338
1339 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1340     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1341   // The argument to the call is some form of the first element of the
1342   // landingpad aggregate value, but that doesn't matter.  It isn't used
1343   // here.
1344   // The second argument is an outparameter where the exception object will be
1345   // stored. Typically the exception object is a scalar, but it can be an
1346   // aggregate when catching by value.
1347   // FIXME: Leave something behind to indicate where the exception object lives
1348   // for this handler. Should it be part of llvm.eh.actions?
1349   assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1350                                           "llvm.eh.begincatch found while "
1351                                           "outlining catch handler.");
1352   ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1353   if (isa<ConstantPointerNull>(ExceptionObjectVar))
1354     return CloningDirector::SkipInstruction;
1355   assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1356          "catch parameter is not static alloca");
1357   Materializer.escapeCatchObject(ExceptionObjectVar);
1358   return CloningDirector::SkipInstruction;
1359 }
1360
1361 CloningDirector::CloningAction
1362 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1363                                    const Instruction *Inst, BasicBlock *NewBB) {
1364   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1365   // It might be interesting to track whether or not we are inside a catch
1366   // function, but that might make the algorithm more brittle than it needs
1367   // to be.
1368
1369   // The end catch call can occur in one of two places: either in a
1370   // landingpad block that is part of the catch handlers exception mechanism,
1371   // or at the end of the catch block.  However, a catch-all handler may call
1372   // end catch from the original landing pad.  If the call occurs in a nested
1373   // landing pad block, we must skip it and continue so that the landing pad
1374   // gets cloned.
1375   auto *ParentBB = IntrinCall->getParent();
1376   if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1377     return CloningDirector::SkipInstruction;
1378
1379   // If an end catch occurs anywhere else we want to terminate the handler
1380   // with a return to the code that follows the endcatch call.  If the
1381   // next instruction is not an unconditional branch, we need to split the
1382   // block to provide a clear target for the return instruction.
1383   BasicBlock *ContinueBB;
1384   auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1385   const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1386   if (!Branch || !Branch->isUnconditional()) {
1387     // We're interrupting the cloning process at this location, so the
1388     // const_cast we're doing here will not cause a problem.
1389     ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1390                             const_cast<Instruction *>(cast<Instruction>(Next)));
1391   } else {
1392     ContinueBB = Branch->getSuccessor(0);
1393   }
1394
1395   ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1396   ReturnTargets.push_back(ContinueBB);
1397
1398   // We just added a terminator to the cloned block.
1399   // Tell the caller to stop processing the current basic block so that
1400   // the branch instruction will be skipped.
1401   return CloningDirector::StopCloningBB;
1402 }
1403
1404 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1405     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1406   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1407   Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1408   // This causes a replacement that will collapse the landing pad CFG based
1409   // on the filter function we intend to match.
1410   if (Selector == CurrentSelector)
1411     VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1412   else
1413     VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1414   // Tell the caller not to clone this instruction.
1415   return CloningDirector::SkipInstruction;
1416 }
1417
1418 CloningDirector::CloningAction
1419 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1420                                  const InvokeInst *Invoke, BasicBlock *NewBB) {
1421   return CloningDirector::CloneInstruction;
1422 }
1423
1424 CloningDirector::CloningAction
1425 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1426                                  const ResumeInst *Resume, BasicBlock *NewBB) {
1427   // Resume instructions shouldn't be reachable from catch handlers.
1428   // We still need to handle it, but it will be pruned.
1429   BasicBlock::InstListType &InstList = NewBB->getInstList();
1430   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1431   return CloningDirector::StopCloningBB;
1432 }
1433
1434 CloningDirector::CloningAction
1435 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1436                                   const CmpInst *Compare, BasicBlock *NewBB) {
1437   const IntrinsicInst *IntrinCall = nullptr;
1438   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1439     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1440   } else if (match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1441     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1442   }
1443   if (IntrinCall) {
1444     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1445     // This causes a replacement that will collapse the landing pad CFG based
1446     // on the filter function we intend to match.
1447     if (Selector == CurrentSelector->stripPointerCasts()) {
1448       VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1449     }
1450     else {
1451       VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1452     }
1453     return CloningDirector::SkipInstruction;
1454   }
1455   return CloningDirector::CloneInstruction;
1456 }
1457
1458 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1459     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1460   // The MS runtime will terminate the process if an exception occurs in a
1461   // cleanup handler, so we shouldn't encounter landing pads in the actual
1462   // cleanup code, but they may appear in catch blocks.  Depending on where
1463   // we started cloning we may see one, but it will get dropped during dead
1464   // block pruning.
1465   Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1466   VMap[LPad] = NewInst;
1467   BasicBlock::InstListType &InstList = NewBB->getInstList();
1468   InstList.push_back(NewInst);
1469   return CloningDirector::StopCloningBB;
1470 }
1471
1472 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1473     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1474   // Cleanup code may flow into catch blocks or the catch block may be part
1475   // of a branch that will be optimized away.  We'll insert a return
1476   // instruction now, but it may be pruned before the cloning process is
1477   // complete.
1478   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1479   return CloningDirector::StopCloningBB;
1480 }
1481
1482 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1483     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1484   // Cleanup handlers nested within catch handlers may begin with a call to
1485   // eh.endcatch.  We can just ignore that instruction.
1486   return CloningDirector::SkipInstruction;
1487 }
1488
1489 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1490     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1491   // If we encounter a selector comparison while cloning a cleanup handler,
1492   // we want to stop cloning immediately.  Anything after the dispatch
1493   // will be outlined into a different handler.
1494   BasicBlock *CatchHandler;
1495   Constant *Selector;
1496   BasicBlock *NextBB;
1497   if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1498                          CatchHandler, Selector, NextBB)) {
1499     ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1500     return CloningDirector::StopCloningBB;
1501   }
1502   // If eg.typeid.for is called for any other reason, it can be ignored.
1503   VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1504   return CloningDirector::SkipInstruction;
1505 }
1506
1507 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1508     ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1509   // All invokes in cleanup handlers can be replaced with calls.
1510   SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1511   // Insert a normal call instruction...
1512   CallInst *NewCall =
1513       CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1514                        Invoke->getName(), NewBB);
1515   NewCall->setCallingConv(Invoke->getCallingConv());
1516   NewCall->setAttributes(Invoke->getAttributes());
1517   NewCall->setDebugLoc(Invoke->getDebugLoc());
1518   VMap[Invoke] = NewCall;
1519
1520   // Remap the operands.
1521   llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1522
1523   // Insert an unconditional branch to the normal destination.
1524   BranchInst::Create(Invoke->getNormalDest(), NewBB);
1525
1526   // The unwind destination won't be cloned into the new function, so
1527   // we don't need to clean up its phi nodes.
1528
1529   // We just added a terminator to the cloned block.
1530   // Tell the caller to stop processing the current basic block.
1531   return CloningDirector::CloneSuccessors;
1532 }
1533
1534 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1535     ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1536   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1537
1538   // We just added a terminator to the cloned block.
1539   // Tell the caller to stop processing the current basic block so that
1540   // the branch instruction will be skipped.
1541   return CloningDirector::StopCloningBB;
1542 }
1543
1544 CloningDirector::CloningAction
1545 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1546                                     const CmpInst *Compare, BasicBlock *NewBB) {
1547   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1548       match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1549     VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1550     return CloningDirector::SkipInstruction;
1551   }
1552   return CloningDirector::CloneInstruction;
1553
1554 }
1555
1556 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1557     Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1558     : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1559   BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1560   Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
1561 }
1562
1563 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1564   // If we're asked to materialize a static alloca, we temporarily create an
1565   // alloca in the outlined function and add this to the FrameVarInfo map.  When
1566   // all the outlining is complete, we'll replace these temporary allocas with
1567   // calls to llvm.framerecover.
1568   if (auto *AV = dyn_cast<AllocaInst>(V)) {
1569     assert(AV->isStaticAlloca() &&
1570            "cannot materialize un-demoted dynamic alloca");
1571     AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1572     Builder.Insert(NewAlloca, AV->getName());
1573     FrameVarInfo[AV].push_back(NewAlloca);
1574     return NewAlloca;
1575   }
1576
1577   if (isa<Instruction>(V) || isa<Argument>(V)) {
1578     errs() << "Failed to demote instruction used in exception handler:\n";
1579     errs() << "  " << *V << '\n';
1580     report_fatal_error("WinEHPrepare failed to demote instruction");
1581   }
1582
1583   // Don't materialize other values.
1584   return nullptr;
1585 }
1586
1587 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1588   // Catch parameter objects have to live in the parent frame. When we see a use
1589   // of a catch parameter, add a sentinel to the multimap to indicate that it's
1590   // used from another handler. This will prevent us from trying to sink the
1591   // alloca into the handler and ensure that the catch parameter is present in
1592   // the call to llvm.frameescape.
1593   FrameVarInfo[V].push_back(getCatchObjectSentinel());
1594 }
1595
1596 // This function maps the catch and cleanup handlers that are reachable from the
1597 // specified landing pad. The landing pad sequence will have this basic shape:
1598 //
1599 //  <cleanup handler>
1600 //  <selector comparison>
1601 //  <catch handler>
1602 //  <cleanup handler>
1603 //  <selector comparison>
1604 //  <catch handler>
1605 //  <cleanup handler>
1606 //  ...
1607 //
1608 // Any of the cleanup slots may be absent.  The cleanup slots may be occupied by
1609 // any arbitrary control flow, but all paths through the cleanup code must
1610 // eventually reach the next selector comparison and no path can skip to a
1611 // different selector comparisons, though some paths may terminate abnormally.
1612 // Therefore, we will use a depth first search from the start of any given
1613 // cleanup block and stop searching when we find the next selector comparison.
1614 //
1615 // If the landingpad instruction does not have a catch clause, we will assume
1616 // that any instructions other than selector comparisons and catch handlers can
1617 // be ignored.  In practice, these will only be the boilerplate instructions.
1618 //
1619 // The catch handlers may also have any control structure, but we are only
1620 // interested in the start of the catch handlers, so we don't need to actually
1621 // follow the flow of the catch handlers.  The start of the catch handlers can
1622 // be located from the compare instructions, but they can be skipped in the
1623 // flow by following the contrary branch.
1624 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1625                                        LandingPadActions &Actions) {
1626   unsigned int NumClauses = LPad->getNumClauses();
1627   unsigned int HandlersFound = 0;
1628   BasicBlock *BB = LPad->getParent();
1629
1630   DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1631
1632   if (NumClauses == 0) {
1633     findCleanupHandlers(Actions, BB, nullptr);
1634     return;
1635   }
1636
1637   VisitedBlockSet VisitedBlocks;
1638
1639   while (HandlersFound != NumClauses) {
1640     BasicBlock *NextBB = nullptr;
1641
1642     // Skip over filter clauses.
1643     if (LPad->isFilter(HandlersFound)) {
1644       ++HandlersFound;
1645       continue;
1646     }
1647
1648     // See if the clause we're looking for is a catch-all.
1649     // If so, the catch begins immediately.
1650     Constant *ExpectedSelector = LPad->getClause(HandlersFound)->stripPointerCasts();
1651     if (isa<ConstantPointerNull>(ExpectedSelector)) {
1652       // The catch all must occur last.
1653       assert(HandlersFound == NumClauses - 1);
1654
1655       // There can be additional selector dispatches in the call chain that we
1656       // need to ignore.
1657       BasicBlock *CatchBlock = nullptr;
1658       Constant *Selector;
1659       while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1660         DEBUG(dbgs() << "  Found extra catch dispatch in block "
1661           << CatchBlock->getName() << "\n");
1662         BB = NextBB;
1663       }
1664
1665       // For C++ EH, check if there is any interesting cleanup code before we
1666       // begin the catch. This is important because cleanups cannot rethrow
1667       // exceptions but code called from catches can. For SEH, it isn't
1668       // important if some finally code before a catch-all is executed out of
1669       // line or after recovering from the exception.
1670       if (Personality == EHPersonality::MSVC_CXX)
1671         findCleanupHandlers(Actions, BB, BB);
1672
1673       // Add the catch handler to the action list.
1674       CatchHandler *Action = nullptr;
1675       if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1676         // If the CatchHandlerMap already has an entry for this BB, re-use it.
1677         Action = CatchHandlerMap[BB];
1678         assert(Action->getSelector() == ExpectedSelector);
1679       } else {
1680         // Since this is a catch-all handler, the selector won't actually appear
1681         // in the code anywhere.  ExpectedSelector here is the constant null ptr
1682         // that we got from the landing pad instruction.
1683         Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1684         CatchHandlerMap[BB] = Action;
1685       }
1686       Actions.insertCatchHandler(Action);
1687       DEBUG(dbgs() << "  Catch all handler at block " << BB->getName() << "\n");
1688       ++HandlersFound;
1689
1690       // Once we reach a catch-all, don't expect to hit a resume instruction.
1691       BB = nullptr;
1692       break;
1693     }
1694
1695     CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1696     assert(CatchAction);
1697
1698     // See if there is any interesting code executed before the dispatch.
1699     findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
1700
1701     // When the source program contains multiple nested try blocks the catch
1702     // handlers can get strung together in such a way that we can encounter
1703     // a dispatch for a selector that we've already had a handler for.
1704     if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1705       ++HandlersFound;
1706
1707       // Add the catch handler to the action list.
1708       DEBUG(dbgs() << "  Found catch dispatch in block "
1709                    << CatchAction->getStartBlock()->getName() << "\n");
1710       Actions.insertCatchHandler(CatchAction);
1711     } else {
1712       // Under some circumstances optimized IR will flow unconditionally into a
1713       // handler block without checking the selector.  This can only happen if
1714       // the landing pad has a catch-all handler and the handler for the
1715       // preceeding catch clause is identical to the catch-call handler
1716       // (typically an empty catch).  In this case, the handler must be shared
1717       // by all remaining clauses.
1718       if (isa<ConstantPointerNull>(
1719               CatchAction->getSelector()->stripPointerCasts())) {
1720         DEBUG(dbgs() << "  Applying early catch-all handler in block "
1721                      << CatchAction->getStartBlock()->getName()
1722                      << "  to all remaining clauses.\n");
1723         Actions.insertCatchHandler(CatchAction);
1724         return;
1725       }
1726
1727       DEBUG(dbgs() << "  Found extra catch dispatch in block "
1728                    << CatchAction->getStartBlock()->getName() << "\n");
1729     }
1730
1731     // Move on to the block after the catch handler.
1732     BB = NextBB;
1733   }
1734
1735   // If we didn't wind up in a catch-all, see if there is any interesting code
1736   // executed before the resume.
1737   findCleanupHandlers(Actions, BB, BB);
1738
1739   // It's possible that some optimization moved code into a landingpad that
1740   // wasn't
1741   // previously being used for cleanup.  If that happens, we need to execute
1742   // that
1743   // extra code from a cleanup handler.
1744   if (Actions.includesCleanup() && !LPad->isCleanup())
1745     LPad->setCleanup(true);
1746 }
1747
1748 // This function searches starting with the input block for the next
1749 // block that terminates with a branch whose condition is based on a selector
1750 // comparison.  This may be the input block.  See the mapLandingPadBlocks
1751 // comments for a discussion of control flow assumptions.
1752 //
1753 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1754                                              BasicBlock *&NextBB,
1755                                              VisitedBlockSet &VisitedBlocks) {
1756   // See if we've already found a catch handler use it.
1757   // Call count() first to avoid creating a null entry for blocks
1758   // we haven't seen before.
1759   if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1760     CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1761     NextBB = Action->getNextBB();
1762     return Action;
1763   }
1764
1765   // VisitedBlocks applies only to the current search.  We still
1766   // need to consider blocks that we've visited while mapping other
1767   // landing pads.
1768   VisitedBlocks.insert(BB);
1769
1770   BasicBlock *CatchBlock = nullptr;
1771   Constant *Selector = nullptr;
1772
1773   // If this is the first time we've visited this block from any landing pad
1774   // look to see if it is a selector dispatch block.
1775   if (!CatchHandlerMap.count(BB)) {
1776     if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1777       CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1778       CatchHandlerMap[BB] = Action;
1779       return Action;
1780     }
1781     // If we encounter a block containing an llvm.eh.begincatch before we
1782     // find a selector dispatch block, the handler is assumed to be
1783     // reached unconditionally.  This happens for catch-all blocks, but
1784     // it can also happen for other catch handlers that have been combined
1785     // with the catch-all handler during optimization.
1786     if (isCatchBlock(BB)) {
1787       PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
1788       Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
1789       CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
1790       CatchHandlerMap[BB] = Action;
1791       return Action;
1792     }
1793   }
1794
1795   // Visit each successor, looking for the dispatch.
1796   // FIXME: We expect to find the dispatch quickly, so this will probably
1797   //        work better as a breadth first search.
1798   for (BasicBlock *Succ : successors(BB)) {
1799     if (VisitedBlocks.count(Succ))
1800       continue;
1801
1802     CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1803     if (Action)
1804       return Action;
1805   }
1806   return nullptr;
1807 }
1808
1809 // These are helper functions to combine repeated code from findCleanupHandlers.
1810 static void createCleanupHandler(LandingPadActions &Actions,
1811                                  CleanupHandlerMapTy &CleanupHandlerMap,
1812                                  BasicBlock *BB) {
1813   CleanupHandler *Action = new CleanupHandler(BB);
1814   CleanupHandlerMap[BB] = Action;
1815   Actions.insertCleanupHandler(Action);
1816   DEBUG(dbgs() << "  Found cleanup code in block "
1817                << Action->getStartBlock()->getName() << "\n");
1818 }
1819
1820 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1821                                          Instruction *MaybeCall) {
1822   // Look for finally blocks that Clang has already outlined for us.
1823   //   %fp = call i8* @llvm.frameaddress(i32 0)
1824   //   call void @"fin$parent"(iN 1, i8* %fp)
1825   if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1826     MaybeCall = MaybeCall->getNextNode();
1827   CallSite FinallyCall(MaybeCall);
1828   if (!FinallyCall || FinallyCall.arg_size() != 2)
1829     return CallSite();
1830   if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
1831     return CallSite();
1832   if (!isFrameAddressCall(FinallyCall.getArgument(1)))
1833     return CallSite();
1834   return FinallyCall;
1835 }
1836
1837 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
1838   // Skip single ubr blocks.
1839   while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
1840     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
1841     if (Br && Br->isUnconditional())
1842       BB = Br->getSuccessor(0);
1843     else
1844       return BB;
1845   }
1846   return BB;
1847 }
1848
1849 // This function searches starting with the input block for the next block that
1850 // contains code that is not part of a catch handler and would not be eliminated
1851 // during handler outlining.
1852 //
1853 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
1854                                        BasicBlock *StartBB, BasicBlock *EndBB) {
1855   // Here we will skip over the following:
1856   //
1857   // landing pad prolog:
1858   //
1859   // Unconditional branches
1860   //
1861   // Selector dispatch
1862   //
1863   // Resume pattern
1864   //
1865   // Anything else marks the start of an interesting block
1866
1867   BasicBlock *BB = StartBB;
1868   // Anything other than an unconditional branch will kick us out of this loop
1869   // one way or another.
1870   while (BB) {
1871     BB = followSingleUnconditionalBranches(BB);
1872     // If we've already scanned this block, don't scan it again.  If it is
1873     // a cleanup block, there will be an action in the CleanupHandlerMap.
1874     // If we've scanned it and it is not a cleanup block, there will be a
1875     // nullptr in the CleanupHandlerMap.  If we have not scanned it, there will
1876     // be no entry in the CleanupHandlerMap.  We must call count() first to
1877     // avoid creating a null entry for blocks we haven't scanned.
1878     if (CleanupHandlerMap.count(BB)) {
1879       if (auto *Action = CleanupHandlerMap[BB]) {
1880         Actions.insertCleanupHandler(Action);
1881         DEBUG(dbgs() << "  Found cleanup code in block "
1882               << Action->getStartBlock()->getName() << "\n");
1883         // FIXME: This cleanup might chain into another, and we need to discover
1884         // that.
1885         return;
1886       } else {
1887         // Here we handle the case where the cleanup handler map contains a
1888         // value for this block but the value is a nullptr.  This means that
1889         // we have previously analyzed the block and determined that it did
1890         // not contain any cleanup code.  Based on the earlier analysis, we
1891         // know the the block must end in either an unconditional branch, a
1892         // resume or a conditional branch that is predicated on a comparison
1893         // with a selector.  Either the resume or the selector dispatch
1894         // would terminate the search for cleanup code, so the unconditional
1895         // branch is the only case for which we might need to continue
1896         // searching.
1897         BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
1898         if (SuccBB == BB || SuccBB == EndBB)
1899           return;
1900         BB = SuccBB;
1901         continue;
1902       }
1903     }
1904
1905     // Create an entry in the cleanup handler map for this block.  Initially
1906     // we create an entry that says this isn't a cleanup block.  If we find
1907     // cleanup code, the caller will replace this entry.
1908     CleanupHandlerMap[BB] = nullptr;
1909
1910     TerminatorInst *Terminator = BB->getTerminator();
1911
1912     // Landing pad blocks have extra instructions we need to accept.
1913     LandingPadMap *LPadMap = nullptr;
1914     if (BB->isLandingPad()) {
1915       LandingPadInst *LPad = BB->getLandingPadInst();
1916       LPadMap = &LPadMaps[LPad];
1917       if (!LPadMap->isInitialized())
1918         LPadMap->mapLandingPad(LPad);
1919     }
1920
1921     // Look for the bare resume pattern:
1922     //   %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1923     //   %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
1924     //   resume { i8*, i32 } %lpad.val2
1925     if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1926       InsertValueInst *Insert1 = nullptr;
1927       InsertValueInst *Insert2 = nullptr;
1928       Value *ResumeVal = Resume->getOperand(0);
1929       // If the resume value isn't a phi or landingpad value, it should be a
1930       // series of insertions. Identify them so we can avoid them when scanning
1931       // for cleanups.
1932       if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
1933         Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1934         if (!Insert2)
1935           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1936         Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1937         if (!Insert1)
1938           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1939       }
1940       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1941            II != IE; ++II) {
1942         Instruction *Inst = II;
1943         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1944           continue;
1945         if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1946           continue;
1947         if (!Inst->hasOneUse() ||
1948             (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1949           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1950         }
1951       }
1952       return;
1953     }
1954
1955     BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1956     if (Branch && Branch->isConditional()) {
1957       // Look for the selector dispatch.
1958       //   %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1959       //   %matches = icmp eq i32 %sel, %2
1960       //   br i1 %matches, label %catch14, label %eh.resume
1961       CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1962       if (!Compare || !Compare->isEquality())
1963         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1964       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1965            II != IE; ++II) {
1966         Instruction *Inst = II;
1967         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1968           continue;
1969         if (Inst == Compare || Inst == Branch)
1970           continue;
1971         if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1972           continue;
1973         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1974       }
1975       // The selector dispatch block should always terminate our search.
1976       assert(BB == EndBB);
1977       return;
1978     }
1979
1980     if (isAsynchronousEHPersonality(Personality)) {
1981       // If this is a landingpad block, split the block at the first non-landing
1982       // pad instruction.
1983       Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
1984       if (LPadMap) {
1985         while (MaybeCall != BB->getTerminator() &&
1986                LPadMap->isLandingPadSpecificInst(MaybeCall))
1987           MaybeCall = MaybeCall->getNextNode();
1988       }
1989
1990       // Look for outlined finally calls.
1991       if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
1992         Function *Fin = FinallyCall.getCalledFunction();
1993         assert(Fin && "outlined finally call should be direct");
1994         auto *Action = new CleanupHandler(BB);
1995         Action->setHandlerBlockOrFunc(Fin);
1996         Actions.insertCleanupHandler(Action);
1997         CleanupHandlerMap[BB] = Action;
1998         DEBUG(dbgs() << "  Found frontend-outlined finally call to "
1999                      << Fin->getName() << " in block "
2000                      << Action->getStartBlock()->getName() << "\n");
2001
2002         // Split the block if there were more interesting instructions and look
2003         // for finally calls in the normal successor block.
2004         BasicBlock *SuccBB = BB;
2005         if (FinallyCall.getInstruction() != BB->getTerminator() &&
2006             FinallyCall.getInstruction()->getNextNode() != BB->getTerminator()) {
2007           SuccBB = BB->splitBasicBlock(FinallyCall.getInstruction()->getNextNode());
2008         } else {
2009           if (FinallyCall.isInvoke()) {
2010             SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
2011           } else {
2012             SuccBB = BB->getUniqueSuccessor();
2013             assert(SuccBB && "splitOutlinedFinallyCalls didn't insert a branch");
2014           }
2015         }
2016         BB = SuccBB;
2017         if (BB == EndBB)
2018           return;
2019         continue;
2020       }
2021     }
2022
2023     // Anything else is either a catch block or interesting cleanup code.
2024     for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2025          II != IE; ++II) {
2026       Instruction *Inst = II;
2027       if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2028         continue;
2029       // Unconditional branches fall through to this loop.
2030       if (Inst == Branch)
2031         continue;
2032       // If this is a catch block, there is no cleanup code to be found.
2033       if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2034         return;
2035       // If this a nested landing pad, it may contain an endcatch call.
2036       if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2037         return;
2038       // Anything else makes this interesting cleanup code.
2039       return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2040     }
2041
2042     // Only unconditional branches in empty blocks should get this far.
2043     assert(Branch && Branch->isUnconditional());
2044     if (BB == EndBB)
2045       return;
2046     BB = Branch->getSuccessor(0);
2047   }
2048 }
2049
2050 // This is a public function, declared in WinEHFuncInfo.h and is also
2051 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2052 void llvm::parseEHActions(const IntrinsicInst *II,
2053                           SmallVectorImpl<ActionHandler *> &Actions) {
2054   for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2055     uint64_t ActionKind =
2056         cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2057     if (ActionKind == /*catch=*/1) {
2058       auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2059       ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2060       int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2061       Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2062       I += 4;
2063       auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
2064       CH->setHandlerBlockOrFunc(Handler);
2065       CH->setExceptionVarIndex(EHObjIndexVal);
2066       Actions.push_back(CH);
2067     } else if (ActionKind == 0) {
2068       Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2069       I += 2;
2070       auto *CH = new CleanupHandler(/*BB=*/nullptr);
2071       CH->setHandlerBlockOrFunc(Handler);
2072       Actions.push_back(CH);
2073     } else {
2074       llvm_unreachable("Expected either a catch or cleanup handler!");
2075     }
2076   }
2077   std::reverse(Actions.begin(), Actions.end());
2078 }