[WinEH] Clone funclets with multiple parents
[oota-llvm.git] / lib / CodeGen / WinEHPrepare.cpp
1 //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass lowers LLVM IR exception handling into something closer to what the
11 // backend wants for functions using a personality function from a runtime
12 // provided by MSVC. Functions with other personality functions are left alone
13 // and may be prepared by other passes. In particular, all supported MSVC
14 // personality functions require cleanup code to be outlined, and the C++
15 // personality requires catch handler code to be outlined.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/Analysis/CFG.h"
21 #include "llvm/Analysis/LibCallSemantics.h"
22 #include "llvm/CodeGen/WinEHFuncInfo.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/Transforms/Utils/Cloning.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Transforms/Utils/SSAUpdater.h"
30
31 using namespace llvm;
32
33 #define DEBUG_TYPE "winehprepare"
34
35 static cl::opt<bool> DisableDemotion(
36     "disable-demotion", cl::Hidden,
37     cl::desc(
38         "Clone multicolor basic blocks but do not demote cross funclet values"),
39     cl::init(false));
40
41 static cl::opt<bool> DisableCleanups(
42     "disable-cleanups", cl::Hidden,
43     cl::desc("Do not remove implausible terminators or other similar cleanups"),
44     cl::init(false));
45
46 namespace {
47
48 class WinEHPrepare : public FunctionPass {
49 public:
50   static char ID; // Pass identification, replacement for typeid.
51   WinEHPrepare(const TargetMachine *TM = nullptr) : FunctionPass(ID) {}
52
53   bool runOnFunction(Function &Fn) override;
54
55   bool doFinalization(Module &M) override;
56
57   void getAnalysisUsage(AnalysisUsage &AU) const override;
58
59   const char *getPassName() const override {
60     return "Windows exception handling preparation";
61   }
62
63 private:
64   void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
65   void
66   insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
67                  SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
68   AllocaInst *insertPHILoads(PHINode *PN, Function &F);
69   void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
70                           DenseMap<BasicBlock *, Value *> &Loads, Function &F);
71   void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB,
72                           Function &F);
73   bool prepareExplicitEH(Function &F,
74                          SmallVectorImpl<BasicBlock *> &EntryBlocks);
75   void replaceTerminatePadWithCleanup(Function &F);
76   void colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks);
77   void resolveFuncletAncestry(Function &F,
78                               SmallVectorImpl<BasicBlock *> &EntryBlocks);
79   void resolveFuncletAncestryForPath(
80       Function &F, SmallVectorImpl<BasicBlock *> &FuncletPath,
81       std::map<BasicBlock *, BasicBlock *> &IdentityMap);
82   void makeFuncletEdgeUnreachable(BasicBlock *Parent, BasicBlock *Child);
83   BasicBlock *cloneFuncletForParent(Function &F, BasicBlock *FuncletEntry,
84                                     BasicBlock *Parent);
85   void updateTerminatorsAfterFuncletClone(
86       Function &F, BasicBlock *OrigFunclet, BasicBlock *CloneFunclet,
87       BasicBlock *OrigBlock, BasicBlock *CloneBlock, BasicBlock *CloneParent,
88       ValueToValueMapTy &VMap,
89       std::map<BasicBlock *, BasicBlock *> &Orig2Clone);
90
91   void demotePHIsOnFunclets(Function &F);
92   void demoteUsesBetweenFunclets(Function &F);
93   void demoteArgumentUses(Function &F);
94   void cloneCommonBlocks(Function &F,
95                          SmallVectorImpl<BasicBlock *> &EntryBlocks);
96   void removeImplausibleTerminators(Function &F);
97   void cleanupPreparedFunclets(Function &F);
98   void verifyPreparedFunclets(Function &F);
99
100   // All fields are reset by runOnFunction.
101   EHPersonality Personality = EHPersonality::Unknown;
102
103   std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
104   std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
105   std::map<BasicBlock *, std::vector<BasicBlock *>> FuncletChildren;
106   std::map<BasicBlock *, std::vector<BasicBlock *>> FuncletParents;
107
108   // This is a flag that indicates an uncommon situation where we need to
109   // clone funclets has been detected.
110   bool FuncletCloningRequired = false;
111   // When a funclet with multiple parents contains a catchret, the block to
112   // which it returns will be cloned so that there is a copy in each parent
113   // but one of the copies will not be properly linked to the catchret and
114   // in most cases will have no predecessors.  This double map allows us
115   // to find these cloned blocks when we clone the child funclet.
116   std::map<BasicBlock *, std::map<BasicBlock *, BasicBlock*>> EstrangedBlocks;
117 };
118
119 } // end anonymous namespace
120
121 char WinEHPrepare::ID = 0;
122 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
123                    false, false)
124
125 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
126   return new WinEHPrepare(TM);
127 }
128
129 static void findFuncletEntryPoints(Function &Fn,
130                                    SmallVectorImpl<BasicBlock *> &EntryBlocks) {
131   EntryBlocks.push_back(&Fn.getEntryBlock());
132   for (BasicBlock &BB : Fn) {
133     Instruction *First = BB.getFirstNonPHI();
134     if (!First->isEHPad())
135       continue;
136     assert(!isa<LandingPadInst>(First) &&
137            "landingpad cannot be used with funclet EH personality");
138     // Find EH pad blocks that represent funclet start points.
139     if (!isa<CatchEndPadInst>(First) && !isa<CleanupEndPadInst>(First))
140       EntryBlocks.push_back(&BB);
141   }
142 }
143
144 bool WinEHPrepare::runOnFunction(Function &Fn) {
145   if (!Fn.hasPersonalityFn())
146     return false;
147
148   // Classify the personality to see what kind of preparation we need.
149   Personality = classifyEHPersonality(Fn.getPersonalityFn());
150
151   // Do nothing if this is not a funclet-based personality.
152   if (!isFuncletEHPersonality(Personality))
153     return false;
154
155   // Remove unreachable blocks.  It is not valuable to assign them a color and
156   // their existence can trick us into thinking values are alive when they are
157   // not.
158   removeUnreachableBlocks(Fn);
159
160   SmallVector<BasicBlock *, 4> EntryBlocks;
161   findFuncletEntryPoints(Fn, EntryBlocks);
162   return prepareExplicitEH(Fn, EntryBlocks);
163 }
164
165 bool WinEHPrepare::doFinalization(Module &M) { return false; }
166
167 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
168
169 static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
170                              const BasicBlock *BB) {
171   CxxUnwindMapEntry UME;
172   UME.ToState = ToState;
173   UME.Cleanup = BB;
174   FuncInfo.CxxUnwindMap.push_back(UME);
175   return FuncInfo.getLastStateNumber();
176 }
177
178 static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
179                                 int TryHigh, int CatchHigh,
180                                 ArrayRef<const CatchPadInst *> Handlers) {
181   WinEHTryBlockMapEntry TBME;
182   TBME.TryLow = TryLow;
183   TBME.TryHigh = TryHigh;
184   TBME.CatchHigh = CatchHigh;
185   assert(TBME.TryLow <= TBME.TryHigh);
186   for (const CatchPadInst *CPI : Handlers) {
187     WinEHHandlerType HT;
188     Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
189     if (TypeInfo->isNullValue())
190       HT.TypeDescriptor = nullptr;
191     else
192       HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
193     HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
194     HT.Handler = CPI->getParent();
195     if (isa<ConstantPointerNull>(CPI->getArgOperand(2)))
196       HT.CatchObj.Alloca = nullptr;
197     else
198       HT.CatchObj.Alloca = cast<AllocaInst>(CPI->getArgOperand(2));
199     TBME.HandlerArray.push_back(HT);
200   }
201   FuncInfo.TryBlockMap.push_back(TBME);
202 }
203
204 static const CatchPadInst *getSingleCatchPadPredecessor(const BasicBlock *BB) {
205   for (const BasicBlock *PredBlock : predecessors(BB))
206     if (auto *CPI = dyn_cast<CatchPadInst>(PredBlock->getFirstNonPHI()))
207       return CPI;
208   return nullptr;
209 }
210
211 /// Find all the catchpads that feed directly into the catchendpad. Frontends
212 /// using this personality should ensure that each catchendpad and catchpad has
213 /// one or zero catchpad predecessors.
214 ///
215 /// The following C++ generates the IR after it:
216 ///   try {
217 ///   } catch (A) {
218 ///   } catch (B) {
219 ///   }
220 ///
221 /// IR:
222 ///   %catchpad.A
223 ///     catchpad [i8* A typeinfo]
224 ///         to label %catch.A unwind label %catchpad.B
225 ///   %catchpad.B
226 ///     catchpad [i8* B typeinfo]
227 ///         to label %catch.B unwind label %endcatches
228 ///   %endcatches
229 ///     catchendblock unwind to caller
230 static void
231 findCatchPadsForCatchEndPad(const BasicBlock *CatchEndBB,
232                             SmallVectorImpl<const CatchPadInst *> &Handlers) {
233   const CatchPadInst *CPI = getSingleCatchPadPredecessor(CatchEndBB);
234   while (CPI) {
235     Handlers.push_back(CPI);
236     CPI = getSingleCatchPadPredecessor(CPI->getParent());
237   }
238   // We've pushed these back into reverse source order.  Reverse them to get
239   // the list back into source order.
240   std::reverse(Handlers.begin(), Handlers.end());
241 }
242
243 // Given BB which ends in an unwind edge, return the EHPad that this BB belongs
244 // to. If the unwind edge came from an invoke, return null.
245 static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) {
246   const TerminatorInst *TI = BB->getTerminator();
247   if (isa<InvokeInst>(TI))
248     return nullptr;
249   if (TI->isEHPad())
250     return BB;
251   return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent();
252 }
253
254 static void calculateExplicitCXXStateNumbers(WinEHFuncInfo &FuncInfo,
255                                              const BasicBlock &BB,
256                                              int ParentState) {
257   assert(BB.isEHPad());
258   const Instruction *FirstNonPHI = BB.getFirstNonPHI();
259   // All catchpad instructions will be handled when we process their
260   // respective catchendpad instruction.
261   if (isa<CatchPadInst>(FirstNonPHI))
262     return;
263
264   if (isa<CatchEndPadInst>(FirstNonPHI)) {
265     SmallVector<const CatchPadInst *, 2> Handlers;
266     findCatchPadsForCatchEndPad(&BB, Handlers);
267     const BasicBlock *FirstTryPad = Handlers.front()->getParent();
268     int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
269     FuncInfo.EHPadStateMap[Handlers.front()] = TryLow;
270     for (const BasicBlock *PredBlock : predecessors(FirstTryPad))
271       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
272         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, TryLow);
273     int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
274
275     // catchpads are separate funclets in C++ EH due to the way rethrow works.
276     // In SEH, they aren't, so no invokes will unwind to the catchendpad.
277     FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow;
278     int TryHigh = CatchLow - 1;
279     for (const BasicBlock *PredBlock : predecessors(&BB))
280       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
281         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CatchLow);
282     int CatchHigh = FuncInfo.getLastStateNumber();
283     addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
284     DEBUG(dbgs() << "TryLow[" << FirstTryPad->getName() << "]: " << TryLow
285                  << '\n');
286     DEBUG(dbgs() << "TryHigh[" << FirstTryPad->getName() << "]: " << TryHigh
287                  << '\n');
288     DEBUG(dbgs() << "CatchHigh[" << FirstTryPad->getName() << "]: " << CatchHigh
289                  << '\n');
290   } else if (isa<CleanupPadInst>(FirstNonPHI)) {
291     // A cleanup can have multiple exits; don't re-process after the first.
292     if (FuncInfo.EHPadStateMap.count(FirstNonPHI))
293       return;
294     int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB);
295     FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
296     DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
297                  << BB.getName() << '\n');
298     for (const BasicBlock *PredBlock : predecessors(&BB))
299       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
300         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CleanupState);
301   } else if (auto *CEPI = dyn_cast<CleanupEndPadInst>(FirstNonPHI)) {
302     // Propagate ParentState to the cleanuppad in case it doesn't have
303     // any cleanuprets.
304     BasicBlock *CleanupBlock = CEPI->getCleanupPad()->getParent();
305     calculateExplicitCXXStateNumbers(FuncInfo, *CleanupBlock, ParentState);
306     // Anything unwinding through CleanupEndPadInst is in ParentState.
307     FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
308     for (const BasicBlock *PredBlock : predecessors(&BB))
309       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
310         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, ParentState);
311   } else if (isa<TerminatePadInst>(FirstNonPHI)) {
312     report_fatal_error("Not yet implemented!");
313   } else {
314     llvm_unreachable("unexpected EH Pad!");
315   }
316 }
317
318 static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
319                         const Function *Filter, const BasicBlock *Handler) {
320   SEHUnwindMapEntry Entry;
321   Entry.ToState = ParentState;
322   Entry.IsFinally = false;
323   Entry.Filter = Filter;
324   Entry.Handler = Handler;
325   FuncInfo.SEHUnwindMap.push_back(Entry);
326   return FuncInfo.SEHUnwindMap.size() - 1;
327 }
328
329 static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
330                          const BasicBlock *Handler) {
331   SEHUnwindMapEntry Entry;
332   Entry.ToState = ParentState;
333   Entry.IsFinally = true;
334   Entry.Filter = nullptr;
335   Entry.Handler = Handler;
336   FuncInfo.SEHUnwindMap.push_back(Entry);
337   return FuncInfo.SEHUnwindMap.size() - 1;
338 }
339
340 static void calculateExplicitSEHStateNumbers(WinEHFuncInfo &FuncInfo,
341                                              const BasicBlock &BB,
342                                              int ParentState) {
343   assert(BB.isEHPad());
344   const Instruction *FirstNonPHI = BB.getFirstNonPHI();
345   // All catchpad instructions will be handled when we process their
346   // respective catchendpad instruction.
347   if (isa<CatchPadInst>(FirstNonPHI))
348     return;
349
350   if (isa<CatchEndPadInst>(FirstNonPHI)) {
351     // Extract the filter function and the __except basic block and create a
352     // state for them.
353     SmallVector<const CatchPadInst *, 1> Handlers;
354     findCatchPadsForCatchEndPad(&BB, Handlers);
355     assert(Handlers.size() == 1 &&
356            "SEH doesn't have multiple handlers per __try");
357     const CatchPadInst *CPI = Handlers.front();
358     const BasicBlock *CatchPadBB = CPI->getParent();
359     const Constant *FilterOrNull =
360         cast<Constant>(CPI->getArgOperand(0)->stripPointerCasts());
361     const Function *Filter = dyn_cast<Function>(FilterOrNull);
362     assert((Filter || FilterOrNull->isNullValue()) &&
363            "unexpected filter value");
364     int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
365
366     // Everything in the __try block uses TryState as its parent state.
367     FuncInfo.EHPadStateMap[CPI] = TryState;
368     DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
369                  << CatchPadBB->getName() << '\n');
370     for (const BasicBlock *PredBlock : predecessors(CatchPadBB))
371       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
372         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, TryState);
373
374     // Everything in the __except block unwinds to ParentState, just like code
375     // outside the __try.
376     FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
377     DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
378                  << BB.getName() << '\n');
379     for (const BasicBlock *PredBlock : predecessors(&BB))
380       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
381         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
382   } else if (isa<CleanupPadInst>(FirstNonPHI)) {
383     // A cleanup can have multiple exits; don't re-process after the first.
384     if (FuncInfo.EHPadStateMap.count(FirstNonPHI))
385       return;
386     int CleanupState = addSEHFinally(FuncInfo, ParentState, &BB);
387     FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
388     DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
389                  << BB.getName() << '\n');
390     for (const BasicBlock *PredBlock : predecessors(&BB))
391       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
392         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, CleanupState);
393   } else if (auto *CEPI = dyn_cast<CleanupEndPadInst>(FirstNonPHI)) {
394     // Propagate ParentState to the cleanuppad in case it doesn't have
395     // any cleanuprets.
396     BasicBlock *CleanupBlock = CEPI->getCleanupPad()->getParent();
397     calculateExplicitSEHStateNumbers(FuncInfo, *CleanupBlock, ParentState);
398     // Anything unwinding through CleanupEndPadInst is in ParentState.
399     FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
400     DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
401                  << BB.getName() << '\n');
402     for (const BasicBlock *PredBlock : predecessors(&BB))
403       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
404         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
405   } else if (isa<TerminatePadInst>(FirstNonPHI)) {
406     report_fatal_error("Not yet implemented!");
407   } else {
408     llvm_unreachable("unexpected EH Pad!");
409   }
410 }
411
412 /// Check if the EH Pad unwinds to caller.  Cleanups are a little bit of a
413 /// special case because we have to look at the cleanupret instruction that uses
414 /// the cleanuppad.
415 static bool doesEHPadUnwindToCaller(const Instruction *EHPad) {
416   auto *CPI = dyn_cast<CleanupPadInst>(EHPad);
417   if (!CPI)
418     return EHPad->mayThrow();
419
420   // This cleanup does not return or unwind, so we say it unwinds to caller.
421   if (CPI->use_empty())
422     return true;
423
424   const Instruction *User = CPI->user_back();
425   if (auto *CRI = dyn_cast<CleanupReturnInst>(User))
426     return CRI->unwindsToCaller();
427   return cast<CleanupEndPadInst>(User)->unwindsToCaller();
428 }
429
430 void llvm::calculateSEHStateNumbers(const Function *Fn,
431                                     WinEHFuncInfo &FuncInfo) {
432   // Don't compute state numbers twice.
433   if (!FuncInfo.SEHUnwindMap.empty())
434     return;
435
436   for (const BasicBlock &BB : *Fn) {
437     if (!BB.isEHPad() || !doesEHPadUnwindToCaller(BB.getFirstNonPHI()))
438       continue;
439     calculateExplicitSEHStateNumbers(FuncInfo, BB, -1);
440   }
441 }
442
443 void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
444                                          WinEHFuncInfo &FuncInfo) {
445   // Return if it's already been done.
446   if (!FuncInfo.EHPadStateMap.empty())
447     return;
448
449   for (const BasicBlock &BB : *Fn) {
450     if (!BB.isEHPad())
451       continue;
452     if (BB.isLandingPad())
453       report_fatal_error("MSVC C++ EH cannot use landingpads");
454     const Instruction *FirstNonPHI = BB.getFirstNonPHI();
455     if (!doesEHPadUnwindToCaller(FirstNonPHI))
456       continue;
457     calculateExplicitCXXStateNumbers(FuncInfo, BB, -1);
458   }
459 }
460
461 static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int ParentState,
462                            ClrHandlerType HandlerType, uint32_t TypeToken,
463                            const BasicBlock *Handler) {
464   ClrEHUnwindMapEntry Entry;
465   Entry.Parent = ParentState;
466   Entry.Handler = Handler;
467   Entry.HandlerType = HandlerType;
468   Entry.TypeToken = TypeToken;
469   FuncInfo.ClrEHUnwindMap.push_back(Entry);
470   return FuncInfo.ClrEHUnwindMap.size() - 1;
471 }
472
473 void llvm::calculateClrEHStateNumbers(const Function *Fn,
474                                       WinEHFuncInfo &FuncInfo) {
475   // Return if it's already been done.
476   if (!FuncInfo.EHPadStateMap.empty())
477     return;
478
479   SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
480
481   // Each pad needs to be able to refer to its parent, so scan the function
482   // looking for top-level handlers and seed the worklist with them.
483   for (const BasicBlock &BB : *Fn) {
484     if (!BB.isEHPad())
485       continue;
486     if (BB.isLandingPad())
487       report_fatal_error("CoreCLR EH cannot use landingpads");
488     const Instruction *FirstNonPHI = BB.getFirstNonPHI();
489     if (!doesEHPadUnwindToCaller(FirstNonPHI))
490       continue;
491     // queue this with sentinel parent state -1 to mean unwind to caller.
492     Worklist.emplace_back(FirstNonPHI, -1);
493   }
494
495   while (!Worklist.empty()) {
496     const Instruction *Pad;
497     int ParentState;
498     std::tie(Pad, ParentState) = Worklist.pop_back_val();
499
500     int PredState;
501     if (const CleanupEndPadInst *EndPad = dyn_cast<CleanupEndPadInst>(Pad)) {
502       FuncInfo.EHPadStateMap[EndPad] = ParentState;
503       // Queue the cleanuppad, in case it doesn't have a cleanupret.
504       Worklist.emplace_back(EndPad->getCleanupPad(), ParentState);
505       // Preds of the endpad should get the parent state.
506       PredState = ParentState;
507     } else if (const CleanupPadInst *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
508       // A cleanup can have multiple exits; don't re-process after the first.
509       if (FuncInfo.EHPadStateMap.count(Pad))
510         continue;
511       // CoreCLR personality uses arity to distinguish faults from finallies.
512       const BasicBlock *PadBlock = Cleanup->getParent();
513       ClrHandlerType HandlerType =
514           (Cleanup->getNumOperands() ? ClrHandlerType::Fault
515                                      : ClrHandlerType::Finally);
516       int NewState =
517           addClrEHHandler(FuncInfo, ParentState, HandlerType, 0, PadBlock);
518       FuncInfo.EHPadStateMap[Cleanup] = NewState;
519       // Propagate the new state to all preds of the cleanup
520       PredState = NewState;
521     } else if (const CatchEndPadInst *EndPad = dyn_cast<CatchEndPadInst>(Pad)) {
522       FuncInfo.EHPadStateMap[EndPad] = ParentState;
523       // Preds of the endpad should get the parent state.
524       PredState = ParentState;
525     } else if (const CatchPadInst *Catch = dyn_cast<CatchPadInst>(Pad)) {
526       const BasicBlock *PadBlock = Catch->getParent();
527       uint32_t TypeToken = static_cast<uint32_t>(
528           cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
529       int NewState = addClrEHHandler(FuncInfo, ParentState,
530                                      ClrHandlerType::Catch, TypeToken, PadBlock);
531       FuncInfo.EHPadStateMap[Catch] = NewState;
532       // Preds of the catch get its state
533       PredState = NewState;
534     } else {
535       llvm_unreachable("Unexpected EH pad");
536     }
537
538     // Queue all predecessors with the given state
539     for (const BasicBlock *Pred : predecessors(Pad->getParent())) {
540       if ((Pred = getEHPadFromPredecessor(Pred)))
541         Worklist.emplace_back(Pred->getFirstNonPHI(), PredState);
542     }
543   }
544 }
545
546 void WinEHPrepare::replaceTerminatePadWithCleanup(Function &F) {
547   if (Personality != EHPersonality::MSVC_CXX)
548     return;
549   for (BasicBlock &BB : F) {
550     Instruction *First = BB.getFirstNonPHI();
551     auto *TPI = dyn_cast<TerminatePadInst>(First);
552     if (!TPI)
553       continue;
554
555     if (TPI->getNumArgOperands() != 1)
556       report_fatal_error(
557           "Expected a unary terminatepad for MSVC C++ personalities!");
558
559     auto *TerminateFn = dyn_cast<Function>(TPI->getArgOperand(0));
560     if (!TerminateFn)
561       report_fatal_error("Function operand expected in terminatepad for MSVC "
562                          "C++ personalities!");
563
564     // Insert the cleanuppad instruction.
565     auto *CPI = CleanupPadInst::Create(
566         BB.getContext(), {}, Twine("terminatepad.for.", BB.getName()), &BB);
567
568     // Insert the call to the terminate instruction.
569     auto *CallTerminate = CallInst::Create(TerminateFn, {}, &BB);
570     CallTerminate->setDoesNotThrow();
571     CallTerminate->setDoesNotReturn();
572     CallTerminate->setCallingConv(TerminateFn->getCallingConv());
573
574     // Insert a new terminator for the cleanuppad using the same successor as
575     // the terminatepad.
576     CleanupReturnInst::Create(CPI, TPI->getUnwindDest(), &BB);
577
578     // Let's remove the terminatepad now that we've inserted the new
579     // instructions.
580     TPI->eraseFromParent();
581   }
582 }
583
584 static void
585 colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks,
586               std::map<BasicBlock *, std::set<BasicBlock *>> &BlockColors,
587               std::map<BasicBlock *, std::set<BasicBlock *>> &FuncletBlocks) {
588   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist;
589   BasicBlock *EntryBlock = &F.getEntryBlock();
590
591   // Build up the color map, which maps each block to its set of 'colors'.
592   // For any block B, the "colors" of B are the set of funclets F (possibly
593   // including a root "funclet" representing the main function), such that
594   // F will need to directly contain B or a copy of B (where the term "directly
595   // contain" is used to distinguish from being "transitively contained" in
596   // a nested funclet).
597   // Use a CFG walk driven by a worklist of (block, color) pairs.  The "color"
598   // sets attached during this processing to a block which is the entry of some
599   // funclet F is actually the set of F's parents -- i.e. the union of colors
600   // of all predecessors of F's entry.  For all other blocks, the color sets
601   // are as defined above.  A post-pass fixes up the block color map to reflect
602   // the same sense of "color" for funclet entries as for other blocks.
603
604   DEBUG_WITH_TYPE("winehprepare-coloring", dbgs() << "\nColoring funclets for "
605                                                   << F.getName() << "\n");
606
607   Worklist.push_back({EntryBlock, EntryBlock});
608
609   while (!Worklist.empty()) {
610     BasicBlock *Visiting;
611     BasicBlock *Color;
612     std::tie(Visiting, Color) = Worklist.pop_back_val();
613     DEBUG_WITH_TYPE("winehprepare-coloring",
614                     dbgs() << "Visiting " << Visiting->getName() << ", "
615                            << Color->getName() << "\n");
616     Instruction *VisitingHead = Visiting->getFirstNonPHI();
617     if (VisitingHead->isEHPad() && !isa<CatchEndPadInst>(VisitingHead) &&
618         !isa<CleanupEndPadInst>(VisitingHead)) {
619       // Mark this as a funclet head as a member of itself.
620       FuncletBlocks[Visiting].insert(Visiting);
621       // Queue exits (i.e. successors of rets/endpads) with the parent color.
622       // Skip any exits that are catchendpads, since the parent color must then
623       // represent one of the catches chained to that catchendpad, but the
624       // catchendpad should get the color of the common parent of all its
625       // chained catches (i.e. the grandparent color of the current pad).
626       // We don't need to worry abou catchendpads going unvisited, since the
627       // catches chained to them must have unwind edges to them by which we will
628       // visit them.
629       for (User *U : VisitingHead->users()) {
630         if (auto *Exit = dyn_cast<TerminatorInst>(U)) {
631           for (BasicBlock *Succ : successors(Exit->getParent()))
632             if (!isa<CatchEndPadInst>(*Succ->getFirstNonPHI()))
633               if (BlockColors[Succ].insert(Color).second) {
634                 DEBUG_WITH_TYPE("winehprepare-coloring",
635                                 dbgs() << "  Assigned color \'"
636                                        << Color->getName() << "\' to block \'"
637                                        << Succ->getName() << "\'.\n");
638                 Worklist.push_back({Succ, Color});
639               }
640         }
641       }
642       // Handle CatchPad specially since its successors need different colors.
643       if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(VisitingHead)) {
644         // Visit the normal successor with the color of the new EH pad, and
645         // visit the unwind successor with the color of the parent.
646         BasicBlock *NormalSucc = CatchPad->getNormalDest();
647         if (BlockColors[NormalSucc].insert(Visiting).second) {
648           DEBUG_WITH_TYPE("winehprepare-coloring",
649                           dbgs() << "  Assigned color \'" << Visiting->getName()
650                                  << "\' to block \'" << NormalSucc->getName()
651                                  << "\'.\n");
652           Worklist.push_back({NormalSucc, Visiting});
653         }
654         BasicBlock *UnwindSucc = CatchPad->getUnwindDest();
655         if (BlockColors[UnwindSucc].insert(Color).second) {
656           DEBUG_WITH_TYPE("winehprepare-coloring",
657                           dbgs() << "  Assigned color \'" << Color->getName()
658                                  << "\' to block \'" << UnwindSucc->getName()
659                                  << "\'.\n");
660           Worklist.push_back({UnwindSucc, Color});
661         }
662         continue;
663       }
664       // Switch color to the current node, except for terminate pads which
665       // have no bodies and only unwind successors and so need their successors
666       // visited with the color of the parent.
667       if (!isa<TerminatePadInst>(VisitingHead))
668         Color = Visiting;
669     } else {
670       // Note that this is a member of the given color.
671       FuncletBlocks[Color].insert(Visiting);
672     }
673
674     TerminatorInst *Terminator = Visiting->getTerminator();
675     if (isa<CleanupReturnInst>(Terminator) ||
676         isa<CatchReturnInst>(Terminator) ||
677         isa<CleanupEndPadInst>(Terminator)) {
678       // These blocks' successors have already been queued with the parent
679       // color.
680       continue;
681     }
682     for (BasicBlock *Succ : successors(Visiting)) {
683       if (isa<CatchEndPadInst>(Succ->getFirstNonPHI())) {
684         // The catchendpad needs to be visited with the parent's color, not
685         // the current color.  This will happen in the code above that visits
686         // any catchpad unwind successor with the parent color, so we can
687         // safely skip this successor here.
688         continue;
689       }
690       if (BlockColors[Succ].insert(Color).second) {
691         DEBUG_WITH_TYPE("winehprepare-coloring",
692                         dbgs() << "  Assigned color \'" << Color->getName()
693                                << "\' to block \'" << Succ->getName()
694                                << "\'.\n");
695         Worklist.push_back({Succ, Color});
696       }
697     }
698   }
699 }
700
701 static BasicBlock *getEndPadForCatch(CatchPadInst *Catch) {
702   // The catch may have sibling catches.  Follow the unwind chain until we get
703   // to the catchendpad.
704   BasicBlock *NextUnwindDest = Catch->getUnwindDest();
705   auto *UnwindTerminator = NextUnwindDest->getTerminator();
706   while (auto *NextCatch = dyn_cast<CatchPadInst>(UnwindTerminator)) {
707     NextUnwindDest = NextCatch->getUnwindDest();
708     UnwindTerminator = NextUnwindDest->getTerminator();
709   }
710   // The last catch in the chain must unwind to a catchendpad.
711   assert(isa<CatchEndPadInst>(UnwindTerminator));
712   return NextUnwindDest;
713 }
714
715 static void updateClonedEHPadUnwindToParent(
716     BasicBlock *UnwindDest, BasicBlock *OrigBlock, BasicBlock *CloneBlock,
717     std::vector<BasicBlock *> &OrigParents, BasicBlock *CloneParent) {
718   auto updateUnwindTerminator = [](BasicBlock *BB) {
719     auto *Terminator = BB->getTerminator();
720     if (isa<CatchEndPadInst>(Terminator) ||
721         isa<CleanupEndPadInst>(Terminator)) {
722       removeUnwindEdge(BB);
723     } else {
724       // If the block we're updating has a cleanupendpad or cleanupret
725       // terminator, we just want to replace that terminator with an
726       // unreachable instruction.
727       assert(isa<CleanupEndPadInst>(Terminator) ||
728              isa<CleanupReturnInst>(Terminator));
729       // Loop over all of the successors, removing the block's entry from any
730       // PHI nodes.
731       for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
732         (*SI)->removePredecessor(BB);
733       // Remove the terminator and replace it with an unreachable instruction.
734       BB->getTerminator()->eraseFromParent();
735       new UnreachableInst(BB->getContext(), BB);
736     }
737   };
738
739   assert(UnwindDest->isEHPad());
740   // There are many places to which this EH terminator can unwind and each has
741   // slightly different rules for whether or not it fits with the given
742   // location.
743   auto *EHPadInst = UnwindDest->getFirstNonPHI();
744   if (auto *CEP = dyn_cast<CatchEndPadInst>(EHPadInst)) {
745     auto *CloneParentCatch =
746         dyn_cast<CatchPadInst>(CloneParent->getFirstNonPHI());
747     if (!CloneParentCatch ||
748         getEndPadForCatch(CloneParentCatch) != UnwindDest) {
749       DEBUG_WITH_TYPE(
750           "winehprepare-coloring",
751           dbgs() << "      removing unwind destination of clone block \'"
752                  << CloneBlock->getName() << "\'.\n");
753       updateUnwindTerminator(CloneBlock);
754     }
755     // It's possible that the catch end pad is a legal match for both the clone
756     // and the original, so they must be checked separately.  If the original
757     // funclet will still have multiple parents after the current clone parent
758     // is removed, we'll leave its unwind terminator until later.
759     assert(OrigParents.size() >= 2);
760     if (OrigParents.size() != 2)
761       return;
762
763     // If the original funclet will have a single parent after the clone parent
764     // is removed, check that parent's unwind destination.
765     assert(OrigParents.front() == CloneParent ||
766            OrigParents.back() == CloneParent);
767     BasicBlock *OrigParent;
768     if (OrigParents.front() == CloneParent)
769       OrigParent = OrigParents.back();
770     else
771       OrigParent = OrigParents.front();
772
773     auto *OrigParentCatch =
774         dyn_cast<CatchPadInst>(OrigParent->getFirstNonPHI());
775     if (!OrigParentCatch || getEndPadForCatch(OrigParentCatch) != UnwindDest) {
776       DEBUG_WITH_TYPE(
777           "winehprepare-coloring",
778           dbgs() << "      removing unwind destination of original block \'"
779                  << OrigBlock << "\'.\n");
780       updateUnwindTerminator(OrigBlock);
781     }
782   } else if (auto *CleanupEnd = dyn_cast<CleanupEndPadInst>(EHPadInst)) {
783     // If the EH terminator unwinds to a cleanupendpad, that cleanupendpad
784     // must be ending a cleanuppad of either our clone parent or one
785     // one of the parents of the original funclet.
786     auto *CloneParentCP =
787         dyn_cast<CleanupPadInst>(CloneParent->getFirstNonPHI());
788     auto *EndedCP = CleanupEnd->getCleanupPad();
789     if (EndedCP == CloneParentCP) {
790       // If it is ending the cleanuppad of our cloned parent, then we
791       // want to remove the unwind destination of the EH terminator that
792       // we associated with the original funclet.
793       assert(isa<CatchEndPadInst>(OrigBlock->getFirstNonPHI()));
794       DEBUG_WITH_TYPE(
795           "winehprepare-coloring",
796           dbgs() << "      removing unwind destination of original block \'"
797                  << OrigBlock->getName() << "\'.\n");
798       updateUnwindTerminator(OrigBlock);
799     } else {
800       // If it isn't ending the cleanuppad of our clone parent, then we
801       // want to remove the unwind destination of the EH terminator that
802       // associated with our cloned funclet.
803       assert(isa<CatchEndPadInst>(CloneBlock->getFirstNonPHI()));
804       DEBUG_WITH_TYPE(
805           "winehprepare-coloring",
806           dbgs() << "      removing unwind destination of clone block \'"
807                  << CloneBlock->getName() << "\'.\n");
808       updateUnwindTerminator(CloneBlock);
809     }
810   } else {
811     // If the EH terminator unwinds to a catchpad, cleanuppad or
812     // terminatepad that EH pad must be a sibling of the funclet we're
813     // cloning.  We'll clone it later and update one of the catchendpad
814     // instrunctions that unwinds to it at that time.
815     assert(isa<CatchPadInst>(EHPadInst) || isa<CleanupPadInst>(EHPadInst) ||
816            isa<TerminatePadInst>(EHPadInst));
817   }
818 }
819
820 // If the terminator is a catchpad, we must also clone the catchendpad to which
821 // it unwinds and add this to the clone parent's block list.  The catchendpad
822 // unwinds to either its caller, a sibling EH pad, a cleanup end pad in its
823 // parent funclet or a catch end pad in its grandparent funclet (which must be
824 // coupled with the parent funclet).  If it has no unwind destination
825 // (i.e. unwind to caller), there is nothing to be done. If the unwind
826 // destination is a sibling EH pad, we will update the terminators later (in
827 // resolveFuncletAncestryForPath).  If it unwinds to a cleanup end pad or a
828 // catch end pad and this end pad corresponds to the clone parent, we will
829 // remove the unwind destination in the original catchendpad. If it unwinds to
830 // a cleanup end pad or a catch end pad that does not correspond to the clone
831 // parent, we will remove the unwind destination in the cloned catchendpad.
832 static void updateCatchTerminators(
833     Function &F, CatchPadInst *OrigCatch, CatchPadInst *CloneCatch,
834     std::vector<BasicBlock *> &OrigParents, BasicBlock *CloneParent,
835     ValueToValueMapTy &VMap,
836     std::map<BasicBlock *, std::set<BasicBlock *>> &BlockColors,
837     std::map<BasicBlock *, std::set<BasicBlock *>> &FuncletBlocks) {
838   // If we're cloning a catch pad that unwinds to a catchendpad, we also
839   // need to clone the catchendpad.  The coloring algorithm associates
840   // the catchendpad block with the funclet's parent, so we have some work
841   // to do here to figure out whether the original belongs to the clone
842   // parent or one of the original funclets other parents (it might have
843   // more than one at this point).  In either case, we might also need to
844   // remove the unwind edge if the catchendpad doesn't unwind to a block
845   // in the right grandparent funclet.
846   Instruction *I = CloneCatch->getUnwindDest()->getFirstNonPHI();
847   if (auto *CEP = dyn_cast<CatchEndPadInst>(I)) {
848     assert(BlockColors[CEP->getParent()].size() == 1);
849     BasicBlock *CEPFunclet = *(BlockColors[CEP->getParent()].begin());
850     BasicBlock *CEPCloneParent = nullptr;
851     CatchPadInst *PredCatch = nullptr;
852     if (CEPFunclet == CloneParent) {
853       // The catchendpad is in the clone parent, so we need to clone it
854       // and associate the clone with the original funclet's parent.  If
855       // the original funclet had multiple parents, we'll add it to the
856       // first parent that isn't the clone parent.  The logic in
857       // updateClonedEHPadUnwindToParent() will only remove the unwind edge
858       // if there is only one parent other than the clone parent, so we don't
859       // need to verify the ancestry.  The catchendpad will eventually be
860       // cloned into the correct parent and all invalid unwind edges will be
861       // removed.
862       for (auto *Parent : OrigParents) {
863         if (Parent != CloneParent) {
864           CEPCloneParent = Parent;
865           break;
866         }
867       }
868       PredCatch = OrigCatch;
869     } else {
870       CEPCloneParent = CloneParent;
871       PredCatch = CloneCatch;
872     }
873     assert(CEPCloneParent && PredCatch);
874     DEBUG_WITH_TYPE("winehprepare-coloring",
875                     dbgs() << "  Cloning catchendpad \'"
876                            << CEP->getParent()->getName() << "\' for funclet \'"
877                            << CEPCloneParent->getName() << "\'.\n");
878     BasicBlock *ClonedCEP = CloneBasicBlock(
879         CEP->getParent(), VMap, Twine(".from.", CEPCloneParent->getName()));
880     // Insert the clone immediately after the original to ensure determinism
881     // and to keep the same relative ordering of any funclet's blocks.
882     ClonedCEP->insertInto(&F, CEP->getParent()->getNextNode());
883     PredCatch->setUnwindDest(ClonedCEP);
884     FuncletBlocks[CEPCloneParent].insert(ClonedCEP);
885     BlockColors[ClonedCEP].insert(CEPCloneParent);
886     DEBUG_WITH_TYPE("winehprepare-coloring",
887                     dbgs() << "    Assigning color \'"
888                            << CEPCloneParent->getName() << "\' to block \'"
889                            << ClonedCEP->getName() << "\'.\n");
890     auto *ClonedCEPInst = cast<CatchEndPadInst>(ClonedCEP->getTerminator());
891     if (auto *Dest = ClonedCEPInst->getUnwindDest())
892       updateClonedEHPadUnwindToParent(Dest, OrigCatch->getUnwindDest(),
893                                       CloneCatch->getUnwindDest(), OrigParents,
894                                       CloneParent);
895   }
896 }
897
898 // While we are cloning a funclet because it has multiple parents, we will call
899 // this routine to update the terminators for the original and cloned copies
900 // of each basic block.  All blocks in the funclet have been clone by this time.
901 // OrigBlock and CloneBlock will be identical except for their block label.
902 //
903 // If the terminator is a catchpad, we must also clone the catchendpad to which
904 // it unwinds and in most cases update either the original catchendpad or the
905 // clone.  See the updateCatchTerminators() helper routine for details.
906 //
907 // If the terminator is a catchret its successor is a block in its parent
908 // funclet.  If the instruction returns to a block in the parent for which the
909 // cloned funclet was created, the terminator in the original block must be
910 // replaced by an unreachable instruction.  Otherwise the terminator in the
911 // clone block must be replaced by an unreachable instruction.
912 //
913 // If the terminator is a cleanupret or cleanupendpad it either unwinds to
914 // caller or unwinds to a sibling EH pad, a cleanup end pad in its parent
915 // funclet or a catch end pad in its grandparent funclet (which must be
916 // coupled with the parent funclet).  If it unwinds to caller there is
917 // nothing to be done. If the unwind destination is a sibling EH pad, we will
918 // update the terminators later (in resolveFuncletAncestryForPath).  If it
919 // unwinds to a cleanup end pad or a catch end pad and this end pad corresponds
920 // to the clone parent, we will replace the terminator in the original block
921 // with an unreachable instruction. If it unwinds to a cleanup end pad or a
922 // catch end pad that does not correspond to the clone parent, we will replace
923 // the terminator in the clone block with an unreachable instruction.
924 //
925 // If the terminator is an invoke instruction, it unwinds either to a child
926 // EH pad, a cleanup end pad in the current funclet, or a catch end pad in a
927 // parent funclet (which ends either the current catch pad or a sibling
928 // catch pad).  If it unwinds to a child EH pad, the child will have multiple
929 // parents after this funclet is cloned and this case will be handled later in
930 // the resolveFuncletAncestryForPath processing.  If it unwinds to a
931 // cleanup end pad in the current funclet, the instruction remapping during
932 // the cloning process should have already mapped the unwind destination to
933 // the cloned copy of the cleanup end pad.  If it unwinds to a catch end pad
934 // there are two possibilities: either the catch end pad is the unwind
935 // destination for the catch pad we are currently cloning or it is the unwind
936 // destination for a sibling catch pad.  If it it the unwind destination of the
937 // catch pad we are cloning, we need to update the cloned invoke instruction
938 // to unwind to the cloned catch end pad.  Otherwise, we will handle this
939 // later (in resolveFuncletAncestryForPath).
940 void WinEHPrepare::updateTerminatorsAfterFuncletClone(
941     Function &F, BasicBlock *OrigFunclet, BasicBlock *CloneFunclet,
942     BasicBlock *OrigBlock, BasicBlock *CloneBlock, BasicBlock *CloneParent,
943     ValueToValueMapTy &VMap, std::map<BasicBlock *, BasicBlock *> &Orig2Clone) {
944   // If the cloned block doesn't have an exceptional terminator, there is
945   // nothing to be done here.
946   TerminatorInst *CloneTerminator = CloneBlock->getTerminator();
947   if (!CloneTerminator->isExceptional())
948     return;
949
950   if (auto *CloneCatch = dyn_cast<CatchPadInst>(CloneTerminator)) {
951     // A cloned catch pad has a lot of wrinkles, so we'll call a helper function
952     // to update this case.
953     auto *OrigCatch = cast<CatchPadInst>(OrigBlock->getTerminator());
954     updateCatchTerminators(F, OrigCatch, CloneCatch,
955                            FuncletParents[OrigFunclet], CloneParent, VMap,
956                            BlockColors, FuncletBlocks);
957   } else if (auto *CRI = dyn_cast<CatchReturnInst>(CloneTerminator)) {
958     if (FuncletBlocks[CloneParent].count(CRI->getSuccessor())) {
959       BasicBlock *OrigParent;
960       // The original funclet may have more than two parents, but that's OK.
961       // We just need to remap the original catchret to any of the parents.
962       // All of the parents should have an entry in the EstrangedBlocks map
963       // if any of them do.
964       if (FuncletParents[OrigFunclet].front() == CloneParent)
965         OrigParent = FuncletParents[OrigFunclet].back();
966       else
967         OrigParent = FuncletParents[OrigFunclet].front();
968       for (succ_iterator SI = succ_begin(OrigBlock), SE = succ_end(OrigBlock);
969            SI != SE; ++SI)
970         (*SI)->removePredecessor(OrigBlock);
971       BasicBlock *LostBlock = EstrangedBlocks[OrigParent][CRI->getSuccessor()];
972       auto *OrigCatchRet = cast<CatchReturnInst>(OrigBlock->getTerminator());
973       if (LostBlock) {
974         OrigCatchRet->setSuccessor(LostBlock);
975       } else {
976         OrigCatchRet->eraseFromParent();
977         new UnreachableInst(OrigBlock->getContext(), OrigBlock);
978       }
979     } else {
980       for (succ_iterator SI = succ_begin(CloneBlock), SE = succ_end(CloneBlock);
981            SI != SE; ++SI)
982         (*SI)->removePredecessor(CloneBlock);
983       BasicBlock *LostBlock = EstrangedBlocks[CloneParent][CRI->getSuccessor()];
984       if (LostBlock) {
985         CRI->setSuccessor(LostBlock);
986       } else {
987         CRI->eraseFromParent();
988         new UnreachableInst(CloneBlock->getContext(), CloneBlock);
989       }
990     }
991   } else if (isa<CleanupReturnInst>(CloneTerminator) ||
992              isa<CleanupEndPadInst>(CloneTerminator)) {
993     BasicBlock *UnwindDest = nullptr;
994
995     // A cleanup pad can unwind through either a cleanupret or a cleanupendpad
996     // but both are handled the same way.
997     if (auto *CRI = dyn_cast<CleanupReturnInst>(CloneTerminator))
998       UnwindDest = CRI->getUnwindDest();
999     else if (auto *CEI = dyn_cast<CleanupEndPadInst>(CloneTerminator))
1000       UnwindDest = CEI->getUnwindDest();
1001
1002     // If the instruction has no local unwind destination, there is nothing
1003     // to be done.
1004     if (!UnwindDest)
1005       return;
1006
1007     // The unwind destination may be a sibling EH pad, a catchendpad in
1008     // a grandparent funclet (ending a catchpad in the parent) or a cleanup
1009     // cleanupendpad in the parent.  Call a helper routine to diagnose this
1010     // and remove either the clone or original terminator as needed.
1011     updateClonedEHPadUnwindToParent(UnwindDest, OrigBlock, CloneBlock,
1012                                     FuncletParents[OrigFunclet], CloneParent);
1013   } else if (auto *II = dyn_cast<InvokeInst>(CloneTerminator)) {
1014     BasicBlock *UnwindDest = II->getUnwindDest();
1015     assert(UnwindDest && "Invoke unwinds to a null destination.");
1016     assert(UnwindDest->isEHPad() && "Invoke does not unwind to an EH pad.");
1017     auto *EHPadInst = UnwindDest->getFirstNonPHI();
1018     if (isa<CleanupEndPadInst>(EHPadInst)) {
1019       // An invoke that unwinds to a cleanup end pad must be in a cleanup pad.
1020       assert(isa<CleanupPadInst>(CloneFunclet->getFirstNonPHI()) &&
1021              "Unwinding to cleanup end pad from a non cleanup pad funclet.");
1022       // The funclet cloning should have remapped the destination to the cloned
1023       // cleanup end pad.
1024       assert(FuncletBlocks[CloneFunclet].count(UnwindDest) &&
1025              "Unwind destination for invoke was not updated during cloning.");
1026     } else if (auto *CEP = dyn_cast<CatchEndPadInst>(EHPadInst)) {
1027       auto *OrigCatch = cast<CatchPadInst>(OrigFunclet->getFirstNonPHI());
1028       auto *CloneCatch = cast<CatchPadInst>(CloneFunclet->getFirstNonPHI());
1029       if (OrigCatch->getUnwindDest() == UnwindDest) {
1030         // If the invoke unwinds to a catch end pad that is the unwind
1031         // destination for the original catch pad, the cloned invoke should
1032         // unwind to the cloned catch end pad.
1033         II->setUnwindDest(CloneCatch->getUnwindDest());
1034       } else if (CloneCatch->getUnwindDest() == UnwindDest) {
1035         // If the invoke unwinds to a catch end pad that is the unwind
1036         // destination for the clone catch pad, the original invoke should
1037         // unwind to the unwind destination of the original catch pad.
1038         // This happens when the catch end pad is matched to the clone
1039         // parent when the catchpad instruction is cloned and the original
1040         // invoke instruction unwinds to the original catch end pad (which
1041         // is now the unwind destination of the cloned catch pad).
1042         auto *OrigInvoke = cast<InvokeInst>(OrigBlock->getTerminator());
1043         OrigInvoke->setUnwindDest(OrigCatch->getUnwindDest());
1044       } else {
1045         // If the invoke unwinds to a catch end pad that is not the unwind
1046         // destination for the original catch pad, it must be the unwind
1047         // destination for a sibling catch end pad.  We'll handle that case
1048         // later.
1049         assert((getEndPadForCatch(OrigCatch) == UnwindDest ||
1050                 getEndPadForCatch(CloneCatch) == UnwindDest) &&
1051                "Invoke within catch pad unwinds to an invalid catch end pad.");
1052       }
1053     }
1054   }
1055 }
1056
1057 // Clones all blocks used by the specified funclet to avoid the funclet having
1058 // multiple parent funclets.  All terminators in the parent that unwind to the
1059 // original funclet are remapped to unwind to the clone.  Any terminator in the
1060 // original funclet which returned to this parent is converted to an unreachable
1061 // instruction. Likewise, any terminator in the cloned funclet which returns to
1062 // a parent funclet other than the specified parent is converted to an
1063 // unreachable instruction.
1064 BasicBlock *WinEHPrepare::cloneFuncletForParent(Function &F,
1065                                                 BasicBlock *FuncletEntry,
1066                                                 BasicBlock *Parent) {
1067   std::set<BasicBlock *> &BlocksInFunclet = FuncletBlocks[FuncletEntry];
1068
1069   DEBUG_WITH_TYPE("winehprepare-coloring",
1070                   dbgs() << "Cloning funclet \'" << FuncletEntry->getName()
1071                          << "\' for parent \'" << Parent->getName() << "\'.\n");
1072
1073   std::map<BasicBlock *, BasicBlock *> Orig2Clone;
1074   ValueToValueMapTy VMap;
1075   for (BasicBlock *BB : BlocksInFunclet) {
1076     // Create a new basic block and copy instructions into it.
1077     BasicBlock *CBB =
1078         CloneBasicBlock(BB, VMap, Twine(".from.", Parent->getName()));
1079
1080     // Insert the clone immediately after the original to ensure determinism
1081     // and to keep the same relative ordering of any funclet's blocks.
1082     CBB->insertInto(&F, BB->getNextNode());
1083
1084     // Add basic block mapping.
1085     VMap[BB] = CBB;
1086
1087     // Record delta operations that we need to perform to our color mappings.
1088     Orig2Clone[BB] = CBB;
1089   } // end for (BasicBlock *BB : BlocksInFunclet)
1090
1091   BasicBlock *ClonedFunclet = Orig2Clone[FuncletEntry];
1092   assert(ClonedFunclet);
1093
1094   // Set the coloring for the blocks we just cloned.
1095   std::set<BasicBlock *> &ClonedBlocks = FuncletBlocks[ClonedFunclet];
1096   for (auto &BBMapping : Orig2Clone) {
1097     BasicBlock *NewBlock = BBMapping.second;
1098     ClonedBlocks.insert(NewBlock);
1099     BlockColors[NewBlock].insert(ClonedFunclet);
1100
1101     DEBUG_WITH_TYPE("winehprepare-coloring",
1102                     dbgs() << "  Assigning color \'" << ClonedFunclet->getName()
1103                            << "\' to block \'" << NewBlock->getName()
1104                            << "\'.\n");
1105
1106     // Use the VMap to remap the instructions in this cloned block.
1107     for (Instruction &I : *NewBlock)
1108       RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
1109   }
1110
1111   // All the cloned blocks have to be colored in the loop above before we can
1112   // update the terminators because doing so can require checking the color of
1113   // other blocks in the cloned funclet.
1114   for (auto &BBMapping : Orig2Clone) {
1115     BasicBlock *OldBlock = BBMapping.first;
1116     BasicBlock *NewBlock = BBMapping.second;
1117
1118     // Update the terminator, if necessary, in both the original block and the
1119     // cloned so that the original funclet never returns to a block in the
1120     // clone parent and the clone funclet never returns to a block in any other
1121     // of the original funclet's parents.
1122     updateTerminatorsAfterFuncletClone(F, FuncletEntry, ClonedFunclet, OldBlock,
1123                                        NewBlock, Parent, VMap, Orig2Clone);
1124
1125     // Check to see if the cloned block successor has PHI nodes. If so, we need
1126     // to add entries to the PHI nodes for the cloned block now.
1127     for (BasicBlock *SuccBB : successors(NewBlock)) {
1128       for (Instruction &SuccI : *SuccBB) {
1129         auto *SuccPN = dyn_cast<PHINode>(&SuccI);
1130         if (!SuccPN)
1131           break;
1132
1133         // Ok, we have a PHI node.  Figure out what the incoming value was for
1134         // the OldBlock.
1135         int OldBlockIdx = SuccPN->getBasicBlockIndex(OldBlock);
1136         if (OldBlockIdx == -1)
1137           break;
1138         Value *IV = SuccPN->getIncomingValue(OldBlockIdx);
1139
1140         // Remap the value if necessary.
1141         if (auto *Inst = dyn_cast<Instruction>(IV)) {
1142           ValueToValueMapTy::iterator I = VMap.find(Inst);
1143           if (I != VMap.end())
1144             IV = I->second;
1145         }
1146
1147         SuccPN->addIncoming(IV, NewBlock);
1148       }
1149     }
1150   }
1151
1152   // Erase the clone's parent from the original funclet's parent list.
1153   std::vector<BasicBlock *> &Parents = FuncletParents[FuncletEntry];
1154   Parents.erase(std::remove(Parents.begin(), Parents.end(), Parent),
1155                 Parents.end());
1156
1157   // Store the cloned funclet's parent.
1158   assert(std::find(FuncletParents[ClonedFunclet].begin(),
1159                    FuncletParents[ClonedFunclet].end(),
1160                    Parent) == std::end(FuncletParents[ClonedFunclet]));
1161   FuncletParents[ClonedFunclet].push_back(Parent);
1162
1163   // Copy any children of the original funclet to the clone.  We'll either
1164   // clone them too or make that path unreachable when we take the next step
1165   // in resolveFuncletAncestryForPath().
1166   for (auto *Child : FuncletChildren[FuncletEntry]) {
1167     assert(std::find(FuncletChildren[ClonedFunclet].begin(),
1168                      FuncletChildren[ClonedFunclet].end(),
1169                      Child) == std::end(FuncletChildren[ClonedFunclet]));
1170     FuncletChildren[ClonedFunclet].push_back(Child);
1171     assert(std::find(FuncletParents[Child].begin(), FuncletParents[Child].end(),
1172                      ClonedFunclet) == std::end(FuncletParents[Child]));
1173     FuncletParents[Child].push_back(ClonedFunclet);
1174   }
1175
1176   // Find any blocks that unwound to the original funclet entry from the
1177   // clone parent block and remap them to the clone.
1178   for (auto *U : FuncletEntry->users()) {
1179     auto *UT = dyn_cast<TerminatorInst>(U);
1180     if (!UT)
1181       continue;
1182     BasicBlock *UBB = UT->getParent();
1183     assert(BlockColors[UBB].size() == 1);
1184     BasicBlock *UFunclet = *(BlockColors[UBB].begin());
1185     // Funclets shouldn't be able to loop back on themselves.
1186     assert(UFunclet != FuncletEntry);
1187     // If this instruction unwinds to the original funclet from the clone
1188     // parent, remap the terminator so that it unwinds to the clone instead.
1189     // We will perform a similar transformation for siblings after all
1190     // the siblings have been cloned.
1191     if (UFunclet == Parent) {
1192       // We're about to break the path from this block to the uncloned funclet
1193       // entry, so remove it as a predeccessor to clean up the PHIs.
1194       FuncletEntry->removePredecessor(UBB);
1195       TerminatorInst *Terminator = UBB->getTerminator();
1196       RemapInstruction(Terminator, VMap, RF_IgnoreMissingEntries);
1197     }
1198   }
1199
1200   // This asserts a condition that is relied upon inside the loop below,
1201   // namely that no predecessors of the original funclet entry block
1202   // are also predecessors of the cloned funclet entry block.
1203   assert(std::all_of(pred_begin(FuncletEntry), pred_end(FuncletEntry),
1204                      [&ClonedFunclet](BasicBlock *Pred) {
1205                        return std::find(pred_begin(ClonedFunclet),
1206                                         pred_end(ClonedFunclet),
1207                                         Pred) == pred_end(ClonedFunclet);
1208                      }));
1209
1210   // Remove any invalid PHI node entries in the cloned funclet.cl
1211   std::vector<PHINode *> PHIsToErase;
1212   for (Instruction &I : *ClonedFunclet) {
1213     auto *PN = dyn_cast<PHINode>(&I);
1214     if (!PN)
1215       break;
1216
1217     // Predecessors of the original funclet do not reach the cloned funclet,
1218     // but the cloning process assumes they will.  Remove them now.
1219     for (auto *Pred : predecessors(FuncletEntry))
1220       PN->removeIncomingValue(Pred, false);
1221   }
1222   for (auto *PN : PHIsToErase)
1223     PN->eraseFromParent();
1224
1225   // Replace the original funclet in the parent's children vector with the
1226   // cloned funclet.
1227   for (auto &It : FuncletChildren[Parent]) {
1228     if (It == FuncletEntry) {
1229       It = ClonedFunclet;
1230       break;
1231     }
1232   }
1233
1234   return ClonedFunclet;
1235 }
1236
1237 // Removes the unwind edge for any exceptional terminators within the specified
1238 // parent funclet that previously unwound to the specified child funclet.
1239 void WinEHPrepare::makeFuncletEdgeUnreachable(BasicBlock *Parent,
1240                                               BasicBlock *Child) {
1241   for (BasicBlock *BB : FuncletBlocks[Parent]) {
1242     TerminatorInst *Terminator = BB->getTerminator();
1243     if (!Terminator->isExceptional())
1244       continue;
1245
1246     // Look for terninators that unwind to the child funclet.
1247     BasicBlock *UnwindDest = nullptr;
1248     if (auto *I = dyn_cast<InvokeInst>(Terminator))
1249       UnwindDest = I->getUnwindDest();
1250     else if (auto *I = dyn_cast<CatchEndPadInst>(Terminator))
1251       UnwindDest = I->getUnwindDest();
1252     else if (auto *I = dyn_cast<TerminatePadInst>(Terminator))
1253       UnwindDest = I->getUnwindDest();
1254     // cleanupendpad, catchret and cleanupret don't represent a parent-to-child
1255     // funclet transition, so we don't need to consider them here.
1256
1257     // If the child funclet is the unwind destination, replace the terminator
1258     // with an unreachable instruction.
1259     if (UnwindDest == Child)
1260       removeUnwindEdge(BB);
1261   }
1262   // The specified parent is no longer a parent of the specified child.
1263   std::vector<BasicBlock *> &Children = FuncletChildren[Parent];
1264   Children.erase(std::remove(Children.begin(), Children.end(), Child),
1265                  Children.end());
1266 }
1267
1268 // This routine is called after funclets with multiple parents are cloned for
1269 // a specific parent.  Here we look for children of the specified funclet that
1270 // unwind to other children of that funclet and update the unwind destinations
1271 // to ensure that each sibling is connected to the correct clone of the sibling
1272 // to which it unwinds.
1273 static void updateSiblingToSiblingUnwind(
1274     BasicBlock *CurFunclet,
1275     std::map<BasicBlock *, std::set<BasicBlock *>> &BlockColors,
1276     std::map<BasicBlock *, std::set<BasicBlock *>> &FuncletBlocks,
1277     std::map<BasicBlock *, std::vector<BasicBlock *>> &FuncletParents,
1278     std::map<BasicBlock *, std::vector<BasicBlock *>> &FuncletChildren,
1279     std::map<BasicBlock *, BasicBlock *> &Funclet2Orig) {
1280   // Remap any bad sibling-to-sibling transitions for funclets that
1281   // we just cloned.
1282   for (BasicBlock *ChildFunclet : FuncletChildren[CurFunclet]) {
1283     bool NeedOrigInvokeRemapping = false;
1284     for (auto *BB : FuncletBlocks[ChildFunclet]) {
1285       TerminatorInst *Terminator = BB->getTerminator();
1286       if (!Terminator->isExceptional())
1287         continue;
1288
1289       // See if this terminator has an unwind destination.
1290       // Note that catchendpads are handled when the associated catchpad
1291       // is cloned.  They don't fit the pattern we're looking for here.
1292       BasicBlock *UnwindDest = nullptr;
1293       if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
1294         UnwindDest = II->getUnwindDest();
1295         assert(UnwindDest && "Invoke unwinds to a null destination.");
1296         assert(UnwindDest->isEHPad() && "Invoke does not unwind to an EH pad.");
1297         auto *EHPadInst = UnwindDest->getFirstNonPHI();
1298         if (auto *CEP = dyn_cast<CatchEndPadInst>(EHPadInst)) {
1299           // If the invoke unwind destination is the unwind destination for
1300           // the current child catch pad funclet, there is nothing to be done.
1301           auto *CurCatch = cast<CatchPadInst>(ChildFunclet->getFirstNonPHI());
1302           if (CurCatch->getUnwindDest() == UnwindDest)
1303             continue;
1304
1305           // Otherwise, the invoke unwinds to a catch end pad that is the unwind
1306           // destination another catch pad in the unwind chain from either the
1307           // current catch pad or one of its clones.  If it is already the
1308           // catch end pad at the end unwind chain from the current catch pad,
1309           // we'll need to check the invoke instructions in the original funclet
1310           // later.  Otherwise, we need to remap this invoke now.
1311           BasicBlock *CurCatchEnd = getEndPadForCatch(CurCatch);
1312           if (CurCatchEnd == UnwindDest)
1313             NeedOrigInvokeRemapping = true;
1314           else
1315             II->setUnwindDest(CurCatchEnd);
1316           continue;
1317         }
1318         // All other unwind scenarios for the invoke are handled elsewhere.
1319         continue;
1320       } else if (auto *I = dyn_cast<CatchPadInst>(Terminator)) {
1321         UnwindDest = I->getUnwindDest();
1322         // The catchendpad is not a sibling destination.  This case should
1323         // have been handled in cloneFuncletForParent().
1324         if (isa<CatchEndPadInst>(Terminator)) {
1325           assert(BlockColors[UnwindDest].size() == 1 &&
1326                  "Cloned catchpad unwinds to an pad with multiple parents.");
1327           assert(FuncletParents[UnwindDest].front() == CurFunclet &&
1328                  "Cloned catchpad unwinds to the wrong parent.");
1329           continue;
1330         }
1331       } else {
1332         if (auto *I = dyn_cast<CleanupReturnInst>(Terminator))
1333           UnwindDest = I->getUnwindDest();
1334         else if (auto *I = dyn_cast<CleanupEndPadInst>(Terminator))
1335           UnwindDest = I->getUnwindDest();
1336
1337         // If the cleanup unwinds to caller, there is nothing to be done.
1338         if (!UnwindDest)
1339           continue;
1340       }
1341
1342       // If the destination is not a cleanup pad, catch pad or terminate pad
1343       // we don't need to handle it here.
1344       Instruction *EHPad = UnwindDest->getFirstNonPHI();
1345       if (!isa<CleanupPadInst>(EHPad) && !isa<CatchPadInst>(EHPad) &&
1346           !isa<TerminatePadInst>(EHPad))
1347         continue;
1348
1349       // If it is one of these, then it is either a sibling of the current
1350       // child funclet or a clone of one of those siblings.
1351       // If it is a sibling, no action is needed.
1352       if (FuncletParents[UnwindDest].size() == 1 &&
1353           FuncletParents[UnwindDest].front() == CurFunclet)
1354         continue;
1355
1356       // If the unwind destination is a clone of a sibling, we need to figure
1357       // out which sibling it is a clone of and use that sibling as the
1358       // unwind destination.
1359       BasicBlock *DestOrig = Funclet2Orig[UnwindDest];
1360       BasicBlock *TargetSibling = nullptr;
1361       for (auto &Mapping : Funclet2Orig) {
1362         if (Mapping.second != DestOrig)
1363           continue;
1364         BasicBlock *MappedFunclet = Mapping.first;
1365         if (FuncletParents[MappedFunclet].size() == 1 &&
1366             FuncletParents[MappedFunclet].front() == CurFunclet) {
1367           TargetSibling = MappedFunclet;
1368         }
1369       }
1370       // If we didn't find the sibling we were looking for then the
1371       // unwind destination is not a clone of one of child's siblings.
1372       // That's unexpected.
1373       assert(TargetSibling && "Funclet unwinds to unexpected destination.");
1374
1375       // Update the terminator instruction to unwind to the correct sibling.
1376       if (auto *I = dyn_cast<CatchPadInst>(Terminator))
1377         I->setUnwindDest(TargetSibling);
1378       else if (auto *I = dyn_cast<CleanupReturnInst>(Terminator))
1379         I->setUnwindDest(TargetSibling);
1380       else if (auto *I = dyn_cast<CleanupEndPadInst>(Terminator))
1381         I->setUnwindDest(TargetSibling);
1382     }
1383     if (NeedOrigInvokeRemapping) {
1384       // To properly remap invoke instructions that unwind to catch end pads
1385       // that are not the unwind destination of the catch pad funclet in which
1386       // the invoke appears, we must also look at the uncloned invoke in the
1387       // original funclet.  If we saw an invoke that was already properly
1388       // unwinding to a sibling's catch end pad, we need to check the invokes
1389       // in the original funclet.
1390       BasicBlock *OrigFunclet = Funclet2Orig[ChildFunclet];
1391       for (auto *BB : FuncletBlocks[OrigFunclet]) {
1392         auto *II = dyn_cast<InvokeInst>(BB->getTerminator());
1393         if (!II)
1394           continue;
1395
1396         BasicBlock *UnwindDest = II->getUnwindDest();
1397         assert(UnwindDest && "Invoke unwinds to a null destination.");
1398         assert(UnwindDest->isEHPad() && "Invoke does not unwind to an EH pad.");
1399         auto *CEP = dyn_cast<CatchEndPadInst>(UnwindDest->getFirstNonPHI());
1400         if (!CEP)
1401           continue;
1402         // If the invoke unwind destination is the unwind destination for
1403         // the original catch pad funclet, there is nothing to be done.
1404         auto *OrigCatch = cast<CatchPadInst>(OrigFunclet->getFirstNonPHI());
1405         if (OrigCatch->getUnwindDest() == UnwindDest)
1406           continue;
1407
1408         // Otherwise, the invoke unwinds to a catch end pad that is the unwind
1409         // destination another catch pad in the unwind chain from either the
1410         // current catch pad or one of its clones.  If it is not already the
1411         // catch end pad at the end unwind chain from the current catch pad,
1412         // we need to remap this invoke now.
1413         BasicBlock *OrigCatchEnd = getEndPadForCatch(OrigCatch);
1414         if (OrigCatchEnd != UnwindDest)
1415           II->setUnwindDest(OrigCatchEnd);
1416       }
1417     }
1418   }
1419 }
1420
1421 void WinEHPrepare::resolveFuncletAncestry(
1422     Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
1423   // Most of the time this will be unnecessary.  If the conditions arise that
1424   // require this work, this flag will be set.
1425   if (!FuncletCloningRequired)
1426     return;
1427
1428   // Funclet2Orig is used to map any cloned funclets back to the original
1429   // funclet from which they were cloned.  The map is seeded with the
1430   // original funclets mapping to themselves.
1431   std::map<BasicBlock *, BasicBlock *> Funclet2Orig;
1432   for (auto *Funclet : EntryBlocks)
1433     Funclet2Orig[Funclet] = Funclet;
1434
1435   // Start with the entry funclet and walk the funclet parent-child tree.
1436   SmallVector<BasicBlock *, 4> FuncletPath;
1437   FuncletPath.push_back(&(F.getEntryBlock()));
1438   resolveFuncletAncestryForPath(F, FuncletPath, Funclet2Orig);
1439 }
1440
1441 // Walks the funclet control flow, cloning any funclets that have more than one
1442 // parent funclet and breaking any cyclic unwind chains so that the path becomes
1443 // unreachable at the point where a funclet would have unwound to a funclet that
1444 // was already in the chain.
1445 void WinEHPrepare::resolveFuncletAncestryForPath(
1446     Function &F, SmallVectorImpl<BasicBlock *> &FuncletPath,
1447     std::map<BasicBlock *, BasicBlock *> &Funclet2Orig) {
1448   bool ClonedAnyChildren = false;
1449   BasicBlock *CurFunclet = FuncletPath.back();
1450   // Copy the children vector because we might changing it.
1451   std::vector<BasicBlock *> Children(FuncletChildren[CurFunclet]);
1452   for (BasicBlock *ChildFunclet : Children) {
1453     // Don't allow the funclet chain to unwind back on itself.
1454     // If this funclet is already in the current funclet chain, make the
1455     // path to it through the current funclet unreachable.
1456     bool IsCyclic = false;
1457     BasicBlock *ChildIdentity = Funclet2Orig[ChildFunclet];
1458     for (BasicBlock *Ancestor : FuncletPath) {
1459       BasicBlock *AncestorIdentity = Funclet2Orig[Ancestor];
1460       if (AncestorIdentity == ChildIdentity) {
1461         IsCyclic = true;
1462         break;
1463       }
1464     }
1465     // If the unwind chain wraps back on itself, break the chain.
1466     if (IsCyclic) {
1467       makeFuncletEdgeUnreachable(CurFunclet, ChildFunclet);
1468       continue;
1469     }
1470     // If this child funclet has other parents, clone the entire funclet.
1471     if (FuncletParents[ChildFunclet].size() > 1) {
1472       ChildFunclet = cloneFuncletForParent(F, ChildFunclet, CurFunclet);
1473       Funclet2Orig[ChildFunclet] = ChildIdentity;
1474       ClonedAnyChildren = true;
1475     }
1476     FuncletPath.push_back(ChildFunclet);
1477     resolveFuncletAncestryForPath(F, FuncletPath, Funclet2Orig);
1478     FuncletPath.pop_back();
1479   }
1480   // If we didn't clone any children, we can return now.
1481   if (!ClonedAnyChildren)
1482     return;
1483
1484   updateSiblingToSiblingUnwind(CurFunclet, BlockColors, FuncletBlocks,
1485                                FuncletParents, FuncletChildren, Funclet2Orig);
1486 }
1487
1488 void WinEHPrepare::colorFunclets(Function &F,
1489                                  SmallVectorImpl<BasicBlock *> &EntryBlocks) {
1490   ::colorFunclets(F, EntryBlocks, BlockColors, FuncletBlocks);
1491
1492   // The processing above actually accumulated the parent set for this
1493   // funclet into the color set for its entry; use the parent set to
1494   // populate the children map, and reset the color set to include just
1495   // the funclet itself (no instruction can target a funclet entry except on
1496   // that transitions to the child funclet).
1497   for (BasicBlock *FuncletEntry : EntryBlocks) {
1498     std::set<BasicBlock *> &ColorMapItem = BlockColors[FuncletEntry];
1499     // It will be rare for funclets to have multiple parents, but if any
1500     // do we need to clone the funclet later to address that.  Here we
1501     // set a flag indicating that this case has arisen so that we don't
1502     // have to do a lot of checking later to handle the more common case.
1503     if (ColorMapItem.size() > 1)
1504       FuncletCloningRequired = true;
1505     for (BasicBlock *Parent : ColorMapItem) {
1506       assert(std::find(FuncletChildren[Parent].begin(),
1507                        FuncletChildren[Parent].end(),
1508                        FuncletEntry) == std::end(FuncletChildren[Parent]));
1509       FuncletChildren[Parent].push_back(FuncletEntry);
1510       assert(std::find(FuncletParents[FuncletEntry].begin(),
1511                        FuncletParents[FuncletEntry].end(),
1512                        Parent) == std::end(FuncletParents[FuncletEntry]));
1513       FuncletParents[FuncletEntry].push_back(Parent);
1514     }
1515     ColorMapItem.clear();
1516     ColorMapItem.insert(FuncletEntry);
1517   }
1518 }
1519
1520 void llvm::calculateCatchReturnSuccessorColors(const Function *Fn,
1521                                                WinEHFuncInfo &FuncInfo) {
1522   SmallVector<BasicBlock *, 4> EntryBlocks;
1523   // colorFunclets needs the set of EntryBlocks, get them using
1524   // findFuncletEntryPoints.
1525   findFuncletEntryPoints(const_cast<Function &>(*Fn), EntryBlocks);
1526
1527   std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
1528   std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
1529   // Figure out which basic blocks belong to which funclets.
1530   colorFunclets(const_cast<Function &>(*Fn), EntryBlocks, BlockColors,
1531                 FuncletBlocks);
1532
1533   // The static colorFunclets routine assigns multiple colors to funclet entries
1534   // because that information is needed to calculate funclets' parent-child
1535   // relationship, but we don't need those relationship here and ultimately the
1536   // entry blocks should have the color of the funclet they begin.
1537   for (BasicBlock *FuncletEntry : EntryBlocks) {
1538     BlockColors[FuncletEntry].clear();
1539     BlockColors[FuncletEntry].insert(FuncletEntry);
1540   }
1541
1542   // We need to find the catchret successors.  To do this, we must first find
1543   // all the catchpad funclets.
1544   for (auto &Funclet : FuncletBlocks) {
1545     // Figure out what kind of funclet we are looking at; We only care about
1546     // catchpads.
1547     BasicBlock *FuncletPadBB = Funclet.first;
1548     Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
1549     auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
1550     if (!CatchPad)
1551       continue;
1552
1553     // The users of a catchpad are always catchrets.
1554     for (User *Exit : CatchPad->users()) {
1555       auto *CatchReturn = dyn_cast<CatchReturnInst>(Exit);
1556       if (!CatchReturn)
1557         continue;
1558       BasicBlock *CatchRetSuccessor = CatchReturn->getSuccessor();
1559       std::set<BasicBlock *> &SuccessorColors = BlockColors[CatchRetSuccessor];
1560       assert(SuccessorColors.size() == 1 && "Expected BB to be monochrome!");
1561       BasicBlock *Color = *SuccessorColors.begin();
1562       // Record the catchret successor's funclet membership.
1563       FuncInfo.CatchRetSuccessorColorMap[CatchReturn] = Color;
1564     }
1565   }
1566 }
1567
1568 void WinEHPrepare::demotePHIsOnFunclets(Function &F) {
1569   // Strip PHI nodes off of EH pads.
1570   SmallVector<PHINode *, 16> PHINodes;
1571   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
1572     BasicBlock *BB = &*FI++;
1573     if (!BB->isEHPad())
1574       continue;
1575     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
1576       Instruction *I = &*BI++;
1577       auto *PN = dyn_cast<PHINode>(I);
1578       // Stop at the first non-PHI.
1579       if (!PN)
1580         break;
1581
1582       AllocaInst *SpillSlot = insertPHILoads(PN, F);
1583       if (SpillSlot)
1584         insertPHIStores(PN, SpillSlot);
1585
1586       PHINodes.push_back(PN);
1587     }
1588   }
1589
1590   for (auto *PN : PHINodes) {
1591     // There may be lingering uses on other EH PHIs being removed
1592     PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1593     PN->eraseFromParent();
1594   }
1595 }
1596
1597 void WinEHPrepare::demoteUsesBetweenFunclets(Function &F) {
1598   // Turn all inter-funclet uses of a Value into loads and stores.
1599   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
1600     BasicBlock *BB = &*FI++;
1601     std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
1602     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
1603       Instruction *I = &*BI++;
1604       // Funclets are permitted to use static allocas.
1605       if (auto *AI = dyn_cast<AllocaInst>(I))
1606         if (AI->isStaticAlloca())
1607           continue;
1608
1609       demoteNonlocalUses(I, ColorsForBB, F);
1610     }
1611   }
1612 }
1613
1614 void WinEHPrepare::demoteArgumentUses(Function &F) {
1615   // Also demote function parameters used in funclets.
1616   std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()];
1617   for (Argument &Arg : F.args())
1618     demoteNonlocalUses(&Arg, ColorsForEntry, F);
1619 }
1620
1621 void WinEHPrepare::cloneCommonBlocks(
1622     Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
1623   // We need to clone all blocks which belong to multiple funclets.  Values are
1624   // remapped throughout the funclet to propogate both the new instructions
1625   // *and* the new basic blocks themselves.
1626   for (BasicBlock *FuncletPadBB : EntryBlocks) {
1627     std::set<BasicBlock *> &BlocksInFunclet = FuncletBlocks[FuncletPadBB];
1628
1629     std::map<BasicBlock *, BasicBlock *> Orig2Clone;
1630     ValueToValueMapTy VMap;
1631     for (auto BlockIt = BlocksInFunclet.begin(),
1632               BlockEnd = BlocksInFunclet.end();
1633          BlockIt != BlockEnd;) {
1634       // Increment the iterator inside the loop because we might be removing
1635       // blocks from the set.
1636       BasicBlock *BB = *BlockIt++;
1637       std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
1638       // We don't need to do anything if the block is monochromatic.
1639       size_t NumColorsForBB = ColorsForBB.size();
1640       if (NumColorsForBB == 1)
1641         continue;
1642
1643       // If this block is a catchendpad, it shouldn't be cloned.
1644       // We will only see a catchendpad with multiple colors in the case where
1645       // some funclet has multiple parents.  In that case, the color will be
1646       // resolved during the resolveFuncletAncestry processing.
1647       // For now, find the catchpad that unwinds to this block and assign
1648       // that catchpad's first parent to be the color for this block.
1649       if (auto *CEP = dyn_cast<CatchEndPadInst>(BB->getFirstNonPHI())) {
1650         assert(
1651             FuncletCloningRequired &&
1652             "Found multi-colored catchendpad with no multi-parent funclets.");
1653         BasicBlock *CatchParent = nullptr;
1654         // There can only be one catchpad predecessor for a catchendpad.
1655         for (BasicBlock *PredBB : predecessors(BB)) {
1656           if (isa<CatchPadInst>(PredBB->getTerminator())) {
1657             CatchParent = PredBB;
1658             break;
1659           }
1660         }
1661         // There must be one catchpad predecessor for a catchendpad.
1662         assert(CatchParent && "No catchpad found for catchendpad.");
1663
1664         // If the catchpad has multiple parents, we'll clone the catchendpad
1665         // when we clone the catchpad funclet and insert it into the correct
1666         // funclet.  For now, we just select the first parent of the catchpad
1667         // and give the catchendpad that color.
1668         BasicBlock *CorrectColor = FuncletParents[CatchParent].front();
1669         assert(FuncletBlocks[CorrectColor].count(BB));
1670         assert(BlockColors[BB].count(CorrectColor));
1671
1672         // Remove this block from the FuncletBlocks set of any funclet that
1673         // isn't the funclet whose color we just selected.
1674         for (auto It = BlockColors[BB].begin(), End = BlockColors[BB].end();
1675              It != End; ) {
1676           // The iterator must be incremented here because we are removing
1677           // elements from the set we're walking.
1678           auto Temp = It++;
1679           BasicBlock *ContainingFunclet = *Temp;
1680           if (ContainingFunclet != CorrectColor) {
1681             FuncletBlocks[ContainingFunclet].erase(BB);
1682             BlockColors[BB].erase(Temp);
1683           }
1684         }
1685
1686         // This should leave just one color for BB.
1687         assert(BlockColors[BB].size() == 1);
1688         continue;
1689       }
1690
1691       DEBUG_WITH_TYPE("winehprepare-coloring",
1692                       dbgs() << "  Cloning block \'" << BB->getName()
1693                               << "\' for funclet \'" << FuncletPadBB->getName()
1694                               << "\'.\n");
1695
1696       // Create a new basic block and copy instructions into it!
1697       BasicBlock *CBB =
1698           CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
1699       // Insert the clone immediately after the original to ensure determinism
1700       // and to keep the same relative ordering of any funclet's blocks.
1701       CBB->insertInto(&F, BB->getNextNode());
1702
1703       // Add basic block mapping.
1704       VMap[BB] = CBB;
1705
1706       // Record delta operations that we need to perform to our color mappings.
1707       Orig2Clone[BB] = CBB;
1708     }
1709
1710     // If nothing was cloned, we're done cloning in this funclet.
1711     if (Orig2Clone.empty())
1712       continue;
1713
1714     // Update our color mappings to reflect that one block has lost a color and
1715     // another has gained a color.
1716     for (auto &BBMapping : Orig2Clone) {
1717       BasicBlock *OldBlock = BBMapping.first;
1718       BasicBlock *NewBlock = BBMapping.second;
1719
1720       BlocksInFunclet.insert(NewBlock);
1721       BlockColors[NewBlock].insert(FuncletPadBB);
1722
1723       DEBUG_WITH_TYPE("winehprepare-coloring",
1724                       dbgs() << "  Assigned color \'" << FuncletPadBB->getName()
1725                               << "\' to block \'" << NewBlock->getName()
1726                               << "\'.\n");
1727
1728       BlocksInFunclet.erase(OldBlock);
1729       BlockColors[OldBlock].erase(FuncletPadBB);
1730
1731       DEBUG_WITH_TYPE("winehprepare-coloring",
1732                       dbgs() << "  Removed color \'" << FuncletPadBB->getName()
1733                               << "\' from block \'" << OldBlock->getName()
1734                               << "\'.\n");
1735
1736       // If we are cloning a funclet that might share a child funclet with
1737       // another funclet, look to see if the cloned block is reached from a
1738       // catchret instruction.  If so, save this association so we can retrieve
1739       // the possibly orphaned clone when we clone the child funclet.
1740       if (FuncletCloningRequired) {
1741         for (auto *Pred : predecessors(OldBlock)) {
1742           auto *Terminator = Pred->getTerminator();
1743           if (!isa<CatchReturnInst>(Terminator))
1744             continue;
1745           // If this block is reached from a catchret instruction in a funclet
1746           // that has multiple parents, it will have a color for each of those
1747           // parents.  We just removed the color of one of the parents, but
1748           // the cloned block will be unreachable until we clone the child
1749           // funclet that contains the catchret instruction.  In that case we
1750           // need to create a mapping that will let us find the cloned block
1751           // later and associate it with the cloned child funclet.
1752           bool BlockWillBeEstranged = false;
1753           for (auto *Color : BlockColors[Pred]) {
1754             if (FuncletParents[Color].size() > 1) {
1755               BlockWillBeEstranged = true;
1756               break; // Breaks out of the color loop
1757             }
1758           }
1759           if (BlockWillBeEstranged) {
1760             EstrangedBlocks[FuncletPadBB][OldBlock] = NewBlock;
1761             DEBUG_WITH_TYPE("winehprepare-coloring",
1762                             dbgs() << "  Saved mapping of estranged block \'"
1763                                   << NewBlock->getName() << "\' for \'"
1764                                   << FuncletPadBB->getName() << "\'.\n");
1765             break; // Breaks out of the predecessor loop
1766           }
1767         }
1768       }
1769     }
1770
1771     // Loop over all of the instructions in this funclet, fixing up operand
1772     // references as we go.  This uses VMap to do all the hard work.
1773     for (BasicBlock *BB : BlocksInFunclet)
1774       // Loop over all instructions, fixing each one as we find it...
1775       for (Instruction &I : *BB)
1776         RemapInstruction(&I, VMap,
1777                          RF_IgnoreMissingEntries | RF_NoModuleLevelChanges);
1778
1779     // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
1780     // the PHI nodes for NewBB now.
1781     for (auto &BBMapping : Orig2Clone) {
1782       BasicBlock *OldBlock = BBMapping.first;
1783       BasicBlock *NewBlock = BBMapping.second;
1784       for (BasicBlock *SuccBB : successors(NewBlock)) {
1785         for (Instruction &SuccI : *SuccBB) {
1786           auto *SuccPN = dyn_cast<PHINode>(&SuccI);
1787           if (!SuccPN)
1788             break;
1789
1790           // Ok, we have a PHI node.  Figure out what the incoming value was for
1791           // the OldBlock.
1792           int OldBlockIdx = SuccPN->getBasicBlockIndex(OldBlock);
1793           if (OldBlockIdx == -1)
1794             break;
1795           Value *IV = SuccPN->getIncomingValue(OldBlockIdx);
1796
1797           // Remap the value if necessary.
1798           if (auto *Inst = dyn_cast<Instruction>(IV)) {
1799             ValueToValueMapTy::iterator I = VMap.find(Inst);
1800             if (I != VMap.end())
1801               IV = I->second;
1802           }
1803
1804           SuccPN->addIncoming(IV, NewBlock);
1805         }
1806       }
1807     }
1808
1809     for (ValueToValueMapTy::value_type VT : VMap) {
1810       // If there were values defined in BB that are used outside the funclet,
1811       // then we now have to update all uses of the value to use either the
1812       // original value, the cloned value, or some PHI derived value.  This can
1813       // require arbitrary PHI insertion, of which we are prepared to do, clean
1814       // these up now.
1815       SmallVector<Use *, 16> UsesToRename;
1816
1817       auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
1818       if (!OldI)
1819         continue;
1820       auto *NewI = cast<Instruction>(VT.second);
1821       // Scan all uses of this instruction to see if it is used outside of its
1822       // funclet, and if so, record them in UsesToRename.
1823       for (Use &U : OldI->uses()) {
1824         Instruction *UserI = cast<Instruction>(U.getUser());
1825         BasicBlock *UserBB = UserI->getParent();
1826         std::set<BasicBlock *> &ColorsForUserBB = BlockColors[UserBB];
1827         assert(!ColorsForUserBB.empty());
1828         if (ColorsForUserBB.size() > 1 ||
1829             *ColorsForUserBB.begin() != FuncletPadBB)
1830           UsesToRename.push_back(&U);
1831       }
1832
1833       // If there are no uses outside the block, we're done with this
1834       // instruction.
1835       if (UsesToRename.empty())
1836         continue;
1837
1838       // We found a use of OldI outside of the funclet.  Rename all uses of OldI
1839       // that are outside its funclet to be uses of the appropriate PHI node
1840       // etc.
1841       SSAUpdater SSAUpdate;
1842       SSAUpdate.Initialize(OldI->getType(), OldI->getName());
1843       SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
1844       SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
1845
1846       while (!UsesToRename.empty())
1847         SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
1848     }
1849   }
1850 }
1851
1852 void WinEHPrepare::removeImplausibleTerminators(Function &F) {
1853   // Remove implausible terminators and replace them with UnreachableInst.
1854   for (auto &Funclet : FuncletBlocks) {
1855     BasicBlock *FuncletPadBB = Funclet.first;
1856     std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
1857     Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
1858     auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
1859     auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI);
1860
1861     for (BasicBlock *BB : BlocksInFunclet) {
1862       TerminatorInst *TI = BB->getTerminator();
1863       // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
1864       bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad);
1865       // The token consumed by a CatchReturnInst must match the funclet token.
1866       bool IsUnreachableCatchret = false;
1867       if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
1868         IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
1869       // The token consumed by a CleanupReturnInst must match the funclet token.
1870       bool IsUnreachableCleanupret = false;
1871       if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
1872         IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
1873       // The token consumed by a CleanupEndPadInst must match the funclet token.
1874       bool IsUnreachableCleanupendpad = false;
1875       if (auto *CEPI = dyn_cast<CleanupEndPadInst>(TI))
1876         IsUnreachableCleanupendpad = CEPI->getCleanupPad() != CleanupPad;
1877       if (IsUnreachableRet || IsUnreachableCatchret ||
1878           IsUnreachableCleanupret || IsUnreachableCleanupendpad) {
1879         // Loop through all of our successors and make sure they know that one
1880         // of their predecessors is going away.
1881         for (BasicBlock *SuccBB : TI->successors())
1882           SuccBB->removePredecessor(BB);
1883
1884         if (IsUnreachableCleanupendpad) {
1885           // We can't simply replace a cleanupendpad with unreachable, because
1886           // its predecessor edges are EH edges and unreachable is not an EH
1887           // pad.  Change all predecessors to the "unwind to caller" form.
1888           for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1889                PI != PE;) {
1890             BasicBlock *Pred = *PI++;
1891             removeUnwindEdge(Pred);
1892           }
1893         }
1894
1895         new UnreachableInst(BB->getContext(), TI);
1896         TI->eraseFromParent();
1897       }
1898       // FIXME: Check for invokes/cleanuprets/cleanupendpads which unwind to
1899       // implausible catchendpads (i.e. catchendpad not in immediate parent
1900       // funclet).
1901     }
1902   }
1903 }
1904
1905 void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
1906   // Clean-up some of the mess we made by removing useles PHI nodes, trivial
1907   // branches, etc.
1908   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
1909     BasicBlock *BB = &*FI++;
1910     SimplifyInstructionsInBlock(BB);
1911     ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
1912     MergeBlockIntoPredecessor(BB);
1913   }
1914
1915   // We might have some unreachable blocks after cleaning up some impossible
1916   // control flow.
1917   removeUnreachableBlocks(F);
1918 }
1919
1920 void WinEHPrepare::verifyPreparedFunclets(Function &F) {
1921   // Recolor the CFG to verify that all is well.
1922   for (BasicBlock &BB : F) {
1923     size_t NumColors = BlockColors[&BB].size();
1924     assert(NumColors == 1 && "Expected monochromatic BB!");
1925     if (NumColors == 0)
1926       report_fatal_error("Uncolored BB!");
1927     if (NumColors > 1)
1928       report_fatal_error("Multicolor BB!");
1929     if (!DisableDemotion) {
1930       bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
1931       assert(!EHPadHasPHI && "EH Pad still has a PHI!");
1932       if (EHPadHasPHI)
1933         report_fatal_error("EH Pad still has a PHI!");
1934     }
1935   }
1936 }
1937
1938 bool WinEHPrepare::prepareExplicitEH(
1939     Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
1940   replaceTerminatePadWithCleanup(F);
1941
1942   // Determine which blocks are reachable from which funclet entries.
1943   colorFunclets(F, EntryBlocks);
1944
1945   if (!DisableDemotion) {
1946     demotePHIsOnFunclets(F);
1947
1948     demoteUsesBetweenFunclets(F);
1949
1950     demoteArgumentUses(F);
1951   }
1952
1953   cloneCommonBlocks(F, EntryBlocks);
1954
1955   resolveFuncletAncestry(F, EntryBlocks);
1956
1957   if (!DisableCleanups) {
1958     removeImplausibleTerminators(F);
1959
1960     cleanupPreparedFunclets(F);
1961   }
1962
1963   verifyPreparedFunclets(F);
1964
1965   BlockColors.clear();
1966   FuncletBlocks.clear();
1967   FuncletChildren.clear();
1968   FuncletParents.clear();
1969   EstrangedBlocks.clear();
1970   FuncletCloningRequired = false;
1971
1972   return true;
1973 }
1974
1975 // TODO: Share loads when one use dominates another, or when a catchpad exit
1976 // dominates uses (needs dominators).
1977 AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
1978   BasicBlock *PHIBlock = PN->getParent();
1979   AllocaInst *SpillSlot = nullptr;
1980
1981   if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) {
1982     // Insert a load in place of the PHI and replace all uses.
1983     SpillSlot = new AllocaInst(PN->getType(), nullptr,
1984                                Twine(PN->getName(), ".wineh.spillslot"),
1985                                &F.getEntryBlock().front());
1986     Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
1987                             &*PHIBlock->getFirstInsertionPt());
1988     PN->replaceAllUsesWith(V);
1989     return SpillSlot;
1990   }
1991
1992   DenseMap<BasicBlock *, Value *> Loads;
1993   for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1994        UI != UE;) {
1995     Use &U = *UI++;
1996     auto *UsingInst = cast<Instruction>(U.getUser());
1997     BasicBlock *UsingBB = UsingInst->getParent();
1998     if (UsingBB->isEHPad()) {
1999       // Use is on an EH pad phi.  Leave it alone; we'll insert loads and
2000       // stores for it separately.
2001       assert(isa<PHINode>(UsingInst));
2002       continue;
2003     }
2004     replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
2005   }
2006   return SpillSlot;
2007 }
2008
2009 // TODO: improve store placement.  Inserting at def is probably good, but need
2010 // to be careful not to introduce interfering stores (needs liveness analysis).
2011 // TODO: identify related phi nodes that can share spill slots, and share them
2012 // (also needs liveness).
2013 void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
2014                                    AllocaInst *SpillSlot) {
2015   // Use a worklist of (Block, Value) pairs -- the given Value needs to be
2016   // stored to the spill slot by the end of the given Block.
2017   SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
2018
2019   Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
2020
2021   while (!Worklist.empty()) {
2022     BasicBlock *EHBlock;
2023     Value *InVal;
2024     std::tie(EHBlock, InVal) = Worklist.pop_back_val();
2025
2026     PHINode *PN = dyn_cast<PHINode>(InVal);
2027     if (PN && PN->getParent() == EHBlock) {
2028       // The value is defined by another PHI we need to remove, with no room to
2029       // insert a store after the PHI, so each predecessor needs to store its
2030       // incoming value.
2031       for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
2032         Value *PredVal = PN->getIncomingValue(i);
2033
2034         // Undef can safely be skipped.
2035         if (isa<UndefValue>(PredVal))
2036           continue;
2037
2038         insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
2039       }
2040     } else {
2041       // We need to store InVal, which dominates EHBlock, but can't put a store
2042       // in EHBlock, so need to put stores in each predecessor.
2043       for (BasicBlock *PredBlock : predecessors(EHBlock)) {
2044         insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
2045       }
2046     }
2047   }
2048 }
2049
2050 void WinEHPrepare::insertPHIStore(
2051     BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
2052     SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
2053
2054   if (PredBlock->isEHPad() &&
2055       !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) {
2056     // Pred is unsplittable, so we need to queue it on the worklist.
2057     Worklist.push_back({PredBlock, PredVal});
2058     return;
2059   }
2060
2061   // Otherwise, insert the store at the end of the basic block.
2062   new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
2063 }
2064
2065 // TODO: Share loads for same-funclet uses (requires dominators if funclets
2066 // aren't properly nested).
2067 void WinEHPrepare::demoteNonlocalUses(Value *V,
2068                                       std::set<BasicBlock *> &ColorsForBB,
2069                                       Function &F) {
2070   // Tokens can only be used non-locally due to control flow involving
2071   // unreachable edges.  Don't try to demote the token usage, we'll simply
2072   // delete the cloned user later.
2073   if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V))
2074     return;
2075
2076   DenseMap<BasicBlock *, Value *> Loads;
2077   AllocaInst *SpillSlot = nullptr;
2078   for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) {
2079     Use &U = *UI++;
2080     auto *UsingInst = cast<Instruction>(U.getUser());
2081     BasicBlock *UsingBB = UsingInst->getParent();
2082
2083     // Is the Use inside a block which is colored the same as the Def?
2084     // If so, we don't need to escape the Def because we will clone
2085     // ourselves our own private copy.
2086     std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
2087     if (ColorsForUsingBB == ColorsForBB)
2088       continue;
2089
2090     replaceUseWithLoad(V, U, SpillSlot, Loads, F);
2091   }
2092   if (SpillSlot) {
2093     // Insert stores of the computed value into the stack slot.
2094     // We have to be careful if I is an invoke instruction,
2095     // because we can't insert the store AFTER the terminator instruction.
2096     BasicBlock::iterator InsertPt;
2097     if (isa<Argument>(V)) {
2098       InsertPt = F.getEntryBlock().getTerminator()->getIterator();
2099     } else if (isa<TerminatorInst>(V)) {
2100       auto *II = cast<InvokeInst>(V);
2101       // We cannot demote invoke instructions to the stack if their normal
2102       // edge is critical. Therefore, split the critical edge and create a
2103       // basic block into which the store can be inserted.
2104       if (!II->getNormalDest()->getSinglePredecessor()) {
2105         unsigned SuccNum =
2106             GetSuccessorNumber(II->getParent(), II->getNormalDest());
2107         assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
2108         BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
2109         assert(NewBlock && "Unable to split critical edge.");
2110         // Update the color mapping for the newly split edge.
2111         std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()];
2112         BlockColors[NewBlock] = ColorsForUsingBB;
2113         for (BasicBlock *FuncletPad : ColorsForUsingBB)
2114           FuncletBlocks[FuncletPad].insert(NewBlock);
2115       }
2116       InsertPt = II->getNormalDest()->getFirstInsertionPt();
2117     } else {
2118       InsertPt = cast<Instruction>(V)->getIterator();
2119       ++InsertPt;
2120       // Don't insert before PHI nodes or EH pad instrs.
2121       for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
2122         ;
2123     }
2124     new StoreInst(V, SpillSlot, &*InsertPt);
2125   }
2126 }
2127
2128 void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
2129                                       DenseMap<BasicBlock *, Value *> &Loads,
2130                                       Function &F) {
2131   // Lazilly create the spill slot.
2132   if (!SpillSlot)
2133     SpillSlot = new AllocaInst(V->getType(), nullptr,
2134                                Twine(V->getName(), ".wineh.spillslot"),
2135                                &F.getEntryBlock().front());
2136
2137   auto *UsingInst = cast<Instruction>(U.getUser());
2138   if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
2139     // If this is a PHI node, we can't insert a load of the value before
2140     // the use.  Instead insert the load in the predecessor block
2141     // corresponding to the incoming value.
2142     //
2143     // Note that if there are multiple edges from a basic block to this
2144     // PHI node that we cannot have multiple loads.  The problem is that
2145     // the resulting PHI node will have multiple values (from each load)
2146     // coming in from the same block, which is illegal SSA form.
2147     // For this reason, we keep track of and reuse loads we insert.
2148     BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
2149     if (auto *CatchRet =
2150             dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
2151       // Putting a load above a catchret and use on the phi would still leave
2152       // a cross-funclet def/use.  We need to split the edge, change the
2153       // catchret to target the new block, and put the load there.
2154       BasicBlock *PHIBlock = UsingInst->getParent();
2155       BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
2156       // SplitEdge gives us:
2157       //   IncomingBlock:
2158       //     ...
2159       //     br label %NewBlock
2160       //   NewBlock:
2161       //     catchret label %PHIBlock
2162       // But we need:
2163       //   IncomingBlock:
2164       //     ...
2165       //     catchret label %NewBlock
2166       //   NewBlock:
2167       //     br label %PHIBlock
2168       // So move the terminators to each others' blocks and swap their
2169       // successors.
2170       BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
2171       Goto->removeFromParent();
2172       CatchRet->removeFromParent();
2173       IncomingBlock->getInstList().push_back(CatchRet);
2174       NewBlock->getInstList().push_back(Goto);
2175       Goto->setSuccessor(0, PHIBlock);
2176       CatchRet->setSuccessor(NewBlock);
2177       // Update the color mapping for the newly split edge.
2178       std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock];
2179       BlockColors[NewBlock] = ColorsForPHIBlock;
2180       for (BasicBlock *FuncletPad : ColorsForPHIBlock)
2181         FuncletBlocks[FuncletPad].insert(NewBlock);
2182       // Treat the new block as incoming for load insertion.
2183       IncomingBlock = NewBlock;
2184     }
2185     Value *&Load = Loads[IncomingBlock];
2186     // Insert the load into the predecessor block
2187     if (!Load)
2188       Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
2189                           /*Volatile=*/false, IncomingBlock->getTerminator());
2190
2191     U.set(Load);
2192   } else {
2193     // Reload right before the old use.
2194     auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
2195                               /*Volatile=*/false, UsingInst);
2196     U.set(Load);
2197   }
2198 }
2199
2200 void WinEHFuncInfo::addIPToStateRange(const BasicBlock *PadBB,
2201                                       MCSymbol *InvokeBegin,
2202                                       MCSymbol *InvokeEnd) {
2203   assert(PadBB->isEHPad() && EHPadStateMap.count(PadBB->getFirstNonPHI()) &&
2204          "should get EH pad BB with precomputed state");
2205   InvokeToStateMap[InvokeBegin] =
2206       std::make_pair(EHPadStateMap[PadBB->getFirstNonPHI()], InvokeEnd);
2207 }