1 //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/TinyPtrVector.h"
26 #include "llvm/Analysis/CFG.h"
27 #include "llvm/Analysis/LibCallSemantics.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/CodeGen/WinEHFuncInfo.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PatternMatch.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Transforms/Utils/Cloning.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
45 #include "llvm/Transforms/Utils/SSAUpdater.h"
49 using namespace llvm::PatternMatch;
51 #define DEBUG_TYPE "winehprepare"
53 static cl::opt<bool> DisableDemotion(
54 "disable-demotion", cl::Hidden,
56 "Clone multicolor basic blocks but do not demote cross funclet values"),
59 static cl::opt<bool> DisableCleanups(
60 "disable-cleanups", cl::Hidden,
61 cl::desc("Do not remove implausible terminators or other similar cleanups"),
66 class WinEHPrepare : public FunctionPass {
68 static char ID; // Pass identification, replacement for typeid.
69 WinEHPrepare(const TargetMachine *TM = nullptr)
72 TheTriple = TM->getTargetTriple();
75 bool runOnFunction(Function &Fn) override;
77 bool doFinalization(Module &M) override;
79 void getAnalysisUsage(AnalysisUsage &AU) const override;
81 const char *getPassName() const override {
82 return "Windows exception handling preparation";
86 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
88 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
89 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
90 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
91 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
92 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
93 void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB,
95 bool prepareExplicitEH(Function &F,
96 SmallVectorImpl<BasicBlock *> &EntryBlocks);
97 void replaceTerminatePadWithCleanup(Function &F);
98 void colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks);
99 void demotePHIsOnFunclets(Function &F);
100 void demoteUsesBetweenFunclets(Function &F);
101 void demoteArgumentUses(Function &F);
102 void cloneCommonBlocks(Function &F,
103 SmallVectorImpl<BasicBlock *> &EntryBlocks);
104 void removeImplausibleTerminators(Function &F);
105 void cleanupPreparedFunclets(Function &F);
106 void verifyPreparedFunclets(Function &F);
110 // All fields are reset by runOnFunction.
111 EHPersonality Personality = EHPersonality::Unknown;
113 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
114 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
115 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletChildren;
118 } // end anonymous namespace
120 char WinEHPrepare::ID = 0;
121 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
124 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
125 return new WinEHPrepare(TM);
128 static void findFuncletEntryPoints(Function &Fn,
129 SmallVectorImpl<BasicBlock *> &EntryBlocks) {
130 EntryBlocks.push_back(&Fn.getEntryBlock());
131 for (BasicBlock &BB : Fn) {
132 Instruction *First = BB.getFirstNonPHI();
133 if (!First->isEHPad())
135 assert(!isa<LandingPadInst>(First) &&
136 "landingpad cannot be used with funclet EH personality");
137 // Find EH pad blocks that represent funclet start points.
138 if (!isa<CatchEndPadInst>(First) && !isa<CleanupEndPadInst>(First))
139 EntryBlocks.push_back(&BB);
143 bool WinEHPrepare::runOnFunction(Function &Fn) {
144 if (!Fn.hasPersonalityFn())
147 // No need to prepare outlined handlers.
148 if (Fn.hasFnAttribute("wineh-parent"))
151 // Classify the personality to see what kind of preparation we need.
152 Personality = classifyEHPersonality(Fn.getPersonalityFn());
154 // Do nothing if this is not a funclet-based personality.
155 if (!isFuncletEHPersonality(Personality))
158 // Remove unreachable blocks. It is not valuable to assign them a color and
159 // their existence can trick us into thinking values are alive when they are
161 removeUnreachableBlocks(Fn);
163 SmallVector<BasicBlock *, 4> EntryBlocks;
164 findFuncletEntryPoints(Fn, EntryBlocks);
165 return prepareExplicitEH(Fn, EntryBlocks);
168 bool WinEHPrepare::doFinalization(Module &M) { return false; }
170 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
171 AU.addRequired<DominatorTreeWrapperPass>();
172 AU.addRequired<TargetLibraryInfoWrapperPass>();
175 static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
177 CxxUnwindMapEntry UME;
178 UME.ToState = ToState;
180 FuncInfo.CxxUnwindMap.push_back(UME);
181 return FuncInfo.getLastStateNumber();
184 static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
185 int TryHigh, int CatchHigh,
186 ArrayRef<const CatchPadInst *> Handlers) {
187 WinEHTryBlockMapEntry TBME;
188 TBME.TryLow = TryLow;
189 TBME.TryHigh = TryHigh;
190 TBME.CatchHigh = CatchHigh;
191 assert(TBME.TryLow <= TBME.TryHigh);
192 for (const CatchPadInst *CPI : Handlers) {
194 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
195 if (TypeInfo->isNullValue())
196 HT.TypeDescriptor = nullptr;
198 HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
199 HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
200 HT.Handler = CPI->getParent();
201 HT.CatchObjRecoverIdx = -2;
202 if (isa<ConstantPointerNull>(CPI->getArgOperand(2)))
203 HT.CatchObj.Alloca = nullptr;
205 HT.CatchObj.Alloca = cast<AllocaInst>(CPI->getArgOperand(2));
206 TBME.HandlerArray.push_back(HT);
208 FuncInfo.TryBlockMap.push_back(TBME);
211 static const CatchPadInst *getSingleCatchPadPredecessor(const BasicBlock *BB) {
212 for (const BasicBlock *PredBlock : predecessors(BB))
213 if (auto *CPI = dyn_cast<CatchPadInst>(PredBlock->getFirstNonPHI()))
218 /// Find all the catchpads that feed directly into the catchendpad. Frontends
219 /// using this personality should ensure that each catchendpad and catchpad has
220 /// one or zero catchpad predecessors.
222 /// The following C++ generates the IR after it:
230 /// catchpad [i8* A typeinfo]
231 /// to label %catch.A unwind label %catchpad.B
233 /// catchpad [i8* B typeinfo]
234 /// to label %catch.B unwind label %endcatches
236 /// catchendblock unwind to caller
238 findCatchPadsForCatchEndPad(const BasicBlock *CatchEndBB,
239 SmallVectorImpl<const CatchPadInst *> &Handlers) {
240 const CatchPadInst *CPI = getSingleCatchPadPredecessor(CatchEndBB);
242 Handlers.push_back(CPI);
243 CPI = getSingleCatchPadPredecessor(CPI->getParent());
245 // We've pushed these back into reverse source order. Reverse them to get
246 // the list back into source order.
247 std::reverse(Handlers.begin(), Handlers.end());
250 // Given BB which ends in an unwind edge, return the EHPad that this BB belongs
251 // to. If the unwind edge came from an invoke, return null.
252 static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) {
253 const TerminatorInst *TI = BB->getTerminator();
254 if (isa<InvokeInst>(TI))
258 return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent();
261 static void calculateExplicitCXXStateNumbers(WinEHFuncInfo &FuncInfo,
262 const BasicBlock &BB,
264 assert(BB.isEHPad());
265 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
266 // All catchpad instructions will be handled when we process their
267 // respective catchendpad instruction.
268 if (isa<CatchPadInst>(FirstNonPHI))
271 if (isa<CatchEndPadInst>(FirstNonPHI)) {
272 SmallVector<const CatchPadInst *, 2> Handlers;
273 findCatchPadsForCatchEndPad(&BB, Handlers);
274 const BasicBlock *FirstTryPad = Handlers.front()->getParent();
275 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
276 FuncInfo.EHPadStateMap[Handlers.front()] = TryLow;
277 for (const BasicBlock *PredBlock : predecessors(FirstTryPad))
278 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
279 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, TryLow);
280 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
282 // catchpads are separate funclets in C++ EH due to the way rethrow works.
283 // In SEH, they aren't, so no invokes will unwind to the catchendpad.
284 FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow;
285 int TryHigh = CatchLow - 1;
286 for (const BasicBlock *PredBlock : predecessors(&BB))
287 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
288 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CatchLow);
289 int CatchHigh = FuncInfo.getLastStateNumber();
290 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
291 DEBUG(dbgs() << "TryLow[" << FirstTryPad->getName() << "]: " << TryLow
293 DEBUG(dbgs() << "TryHigh[" << FirstTryPad->getName() << "]: " << TryHigh
295 DEBUG(dbgs() << "CatchHigh[" << FirstTryPad->getName() << "]: " << CatchHigh
297 } else if (isa<CleanupPadInst>(FirstNonPHI)) {
298 // A cleanup can have multiple exits; don't re-process after the first.
299 if (FuncInfo.EHPadStateMap.count(FirstNonPHI))
301 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB);
302 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
303 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
304 << BB.getName() << '\n');
305 for (const BasicBlock *PredBlock : predecessors(&BB))
306 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
307 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CleanupState);
308 } else if (auto *CEPI = dyn_cast<CleanupEndPadInst>(FirstNonPHI)) {
309 // Propagate ParentState to the cleanuppad in case it doesn't have
311 BasicBlock *CleanupBlock = CEPI->getCleanupPad()->getParent();
312 calculateExplicitCXXStateNumbers(FuncInfo, *CleanupBlock, ParentState);
313 // Anything unwinding through CleanupEndPadInst is in ParentState.
314 for (const BasicBlock *PredBlock : predecessors(&BB))
315 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
316 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, ParentState);
317 } else if (isa<TerminatePadInst>(FirstNonPHI)) {
318 report_fatal_error("Not yet implemented!");
320 llvm_unreachable("unexpected EH Pad!");
324 static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
325 const Function *Filter, const BasicBlock *Handler) {
326 SEHUnwindMapEntry Entry;
327 Entry.ToState = ParentState;
328 Entry.IsFinally = false;
329 Entry.Filter = Filter;
330 Entry.Handler = Handler;
331 FuncInfo.SEHUnwindMap.push_back(Entry);
332 return FuncInfo.SEHUnwindMap.size() - 1;
335 static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
336 const BasicBlock *Handler) {
337 SEHUnwindMapEntry Entry;
338 Entry.ToState = ParentState;
339 Entry.IsFinally = true;
340 Entry.Filter = nullptr;
341 Entry.Handler = Handler;
342 FuncInfo.SEHUnwindMap.push_back(Entry);
343 return FuncInfo.SEHUnwindMap.size() - 1;
346 static void calculateExplicitSEHStateNumbers(WinEHFuncInfo &FuncInfo,
347 const BasicBlock &BB,
349 assert(BB.isEHPad());
350 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
351 // All catchpad instructions will be handled when we process their
352 // respective catchendpad instruction.
353 if (isa<CatchPadInst>(FirstNonPHI))
356 if (isa<CatchEndPadInst>(FirstNonPHI)) {
357 // Extract the filter function and the __except basic block and create a
359 SmallVector<const CatchPadInst *, 1> Handlers;
360 findCatchPadsForCatchEndPad(&BB, Handlers);
361 assert(Handlers.size() == 1 &&
362 "SEH doesn't have multiple handlers per __try");
363 const CatchPadInst *CPI = Handlers.front();
364 const BasicBlock *CatchPadBB = CPI->getParent();
365 const Constant *FilterOrNull =
366 cast<Constant>(CPI->getArgOperand(0)->stripPointerCasts());
367 const Function *Filter = dyn_cast<Function>(FilterOrNull);
368 assert((Filter || FilterOrNull->isNullValue()) &&
369 "unexpected filter value");
370 int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
372 // Everything in the __try block uses TryState as its parent state.
373 FuncInfo.EHPadStateMap[CPI] = TryState;
374 DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
375 << CatchPadBB->getName() << '\n');
376 for (const BasicBlock *PredBlock : predecessors(CatchPadBB))
377 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
378 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, TryState);
380 // Everything in the __except block unwinds to ParentState, just like code
381 // outside the __try.
382 FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
383 DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
384 << BB.getName() << '\n');
385 for (const BasicBlock *PredBlock : predecessors(&BB))
386 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
387 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
388 } else if (isa<CleanupPadInst>(FirstNonPHI)) {
389 // A cleanup can have multiple exits; don't re-process after the first.
390 if (FuncInfo.EHPadStateMap.count(FirstNonPHI))
392 int CleanupState = addSEHFinally(FuncInfo, ParentState, &BB);
393 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
394 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
395 << BB.getName() << '\n');
396 for (const BasicBlock *PredBlock : predecessors(&BB))
397 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
398 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, CleanupState);
399 } else if (auto *CEPI = dyn_cast<CleanupEndPadInst>(FirstNonPHI)) {
400 // Propagate ParentState to the cleanuppad in case it doesn't have
402 BasicBlock *CleanupBlock = CEPI->getCleanupPad()->getParent();
403 calculateExplicitSEHStateNumbers(FuncInfo, *CleanupBlock, ParentState);
404 // Anything unwinding through CleanupEndPadInst is in ParentState.
405 FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
406 DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
407 << BB.getName() << '\n');
408 for (const BasicBlock *PredBlock : predecessors(&BB))
409 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
410 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
411 } else if (isa<TerminatePadInst>(FirstNonPHI)) {
412 report_fatal_error("Not yet implemented!");
414 llvm_unreachable("unexpected EH Pad!");
418 /// Check if the EH Pad unwinds to caller. Cleanups are a little bit of a
419 /// special case because we have to look at the cleanupret instruction that uses
421 static bool doesEHPadUnwindToCaller(const Instruction *EHPad) {
422 auto *CPI = dyn_cast<CleanupPadInst>(EHPad);
424 return EHPad->mayThrow();
426 // This cleanup does not return or unwind, so we say it unwinds to caller.
427 if (CPI->use_empty())
430 const Instruction *User = CPI->user_back();
431 if (auto *CRI = dyn_cast<CleanupReturnInst>(User))
432 return CRI->unwindsToCaller();
433 return cast<CleanupEndPadInst>(User)->unwindsToCaller();
436 void llvm::calculateSEHStateNumbers(const Function *Fn,
437 WinEHFuncInfo &FuncInfo) {
438 // Don't compute state numbers twice.
439 if (!FuncInfo.SEHUnwindMap.empty())
442 for (const BasicBlock &BB : *Fn) {
443 if (!BB.isEHPad() || !doesEHPadUnwindToCaller(BB.getFirstNonPHI()))
445 calculateExplicitSEHStateNumbers(FuncInfo, BB, -1);
449 void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
450 WinEHFuncInfo &FuncInfo) {
451 // Return if it's already been done.
452 if (!FuncInfo.EHPadStateMap.empty())
455 for (const BasicBlock &BB : *Fn) {
458 if (BB.isLandingPad())
459 report_fatal_error("MSVC C++ EH cannot use landingpads");
460 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
461 if (!doesEHPadUnwindToCaller(FirstNonPHI))
463 calculateExplicitCXXStateNumbers(FuncInfo, BB, -1);
467 static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int ParentState,
468 ClrHandlerType HandlerType, uint32_t TypeToken,
469 const BasicBlock *Handler) {
470 ClrEHUnwindMapEntry Entry;
471 Entry.Parent = ParentState;
472 Entry.Handler = Handler;
473 Entry.HandlerType = HandlerType;
474 Entry.TypeToken = TypeToken;
475 FuncInfo.ClrEHUnwindMap.push_back(Entry);
476 return FuncInfo.ClrEHUnwindMap.size() - 1;
479 void llvm::calculateClrEHStateNumbers(const Function *Fn,
480 WinEHFuncInfo &FuncInfo) {
481 // Return if it's already been done.
482 if (!FuncInfo.EHPadStateMap.empty())
485 SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
487 // Each pad needs to be able to refer to its parent, so scan the function
488 // looking for top-level handlers and seed the worklist with them.
489 for (const BasicBlock &BB : *Fn) {
492 if (BB.isLandingPad())
493 report_fatal_error("CoreCLR EH cannot use landingpads");
494 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
495 if (!doesEHPadUnwindToCaller(FirstNonPHI))
497 // queue this with sentinel parent state -1 to mean unwind to caller.
498 Worklist.emplace_back(FirstNonPHI, -1);
501 while (!Worklist.empty()) {
502 const Instruction *Pad;
504 std::tie(Pad, ParentState) = Worklist.pop_back_val();
507 if (const CleanupEndPadInst *EndPad = dyn_cast<CleanupEndPadInst>(Pad)) {
508 FuncInfo.EHPadStateMap[EndPad] = ParentState;
509 // Queue the cleanuppad, in case it doesn't have a cleanupret.
510 Worklist.emplace_back(EndPad->getCleanupPad(), ParentState);
511 // Preds of the endpad should get the parent state.
512 PredState = ParentState;
513 } else if (const CleanupPadInst *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
514 // A cleanup can have multiple exits; don't re-process after the first.
515 if (FuncInfo.EHPadStateMap.count(Pad))
517 // CoreCLR personality uses arity to distinguish faults from finallies.
518 const BasicBlock *PadBlock = Cleanup->getParent();
519 ClrHandlerType HandlerType =
520 (Cleanup->getNumOperands() ? ClrHandlerType::Fault
521 : ClrHandlerType::Finally);
523 addClrEHHandler(FuncInfo, ParentState, HandlerType, 0, PadBlock);
524 FuncInfo.EHPadStateMap[Cleanup] = NewState;
525 // Propagate the new state to all preds of the cleanup
526 PredState = NewState;
527 } else if (const CatchEndPadInst *EndPad = dyn_cast<CatchEndPadInst>(Pad)) {
528 FuncInfo.EHPadStateMap[EndPad] = ParentState;
529 // Preds of the endpad should get the parent state.
530 PredState = ParentState;
531 } else if (const CatchPadInst *Catch = dyn_cast<CatchPadInst>(Pad)) {
532 const BasicBlock *PadBlock = Catch->getParent();
533 uint32_t TypeToken = static_cast<uint32_t>(
534 cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
535 int NewState = addClrEHHandler(FuncInfo, ParentState,
536 ClrHandlerType::Catch, TypeToken, PadBlock);
537 FuncInfo.EHPadStateMap[Catch] = NewState;
538 // Preds of the catch get its state
539 PredState = NewState;
541 llvm_unreachable("Unexpected EH pad");
544 // Queue all predecessors with the given state
545 for (const BasicBlock *Pred : predecessors(Pad->getParent())) {
546 if ((Pred = getEHPadFromPredecessor(Pred)))
547 Worklist.emplace_back(Pred->getFirstNonPHI(), PredState);
552 void WinEHPrepare::replaceTerminatePadWithCleanup(Function &F) {
553 if (Personality != EHPersonality::MSVC_CXX)
555 for (BasicBlock &BB : F) {
556 Instruction *First = BB.getFirstNonPHI();
557 auto *TPI = dyn_cast<TerminatePadInst>(First);
561 if (TPI->getNumArgOperands() != 1)
563 "Expected a unary terminatepad for MSVC C++ personalities!");
565 auto *TerminateFn = dyn_cast<Function>(TPI->getArgOperand(0));
567 report_fatal_error("Function operand expected in terminatepad for MSVC "
568 "C++ personalities!");
570 // Insert the cleanuppad instruction.
571 auto *CPI = CleanupPadInst::Create(
572 BB.getContext(), {}, Twine("terminatepad.for.", BB.getName()), &BB);
574 // Insert the call to the terminate instruction.
575 auto *CallTerminate = CallInst::Create(TerminateFn, {}, &BB);
576 CallTerminate->setDoesNotThrow();
577 CallTerminate->setDoesNotReturn();
578 CallTerminate->setCallingConv(TerminateFn->getCallingConv());
580 // Insert a new terminator for the cleanuppad using the same successor as
582 CleanupReturnInst::Create(CPI, TPI->getUnwindDest(), &BB);
584 // Let's remove the terminatepad now that we've inserted the new
586 TPI->eraseFromParent();
591 colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks,
592 std::map<BasicBlock *, std::set<BasicBlock *>> &BlockColors,
593 std::map<BasicBlock *, std::set<BasicBlock *>> &FuncletBlocks,
594 std::map<BasicBlock *, std::set<BasicBlock *>> &FuncletChildren) {
595 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist;
596 BasicBlock *EntryBlock = &F.getEntryBlock();
598 // Build up the color map, which maps each block to its set of 'colors'.
599 // For any block B, the "colors" of B are the set of funclets F (possibly
600 // including a root "funclet" representing the main function), such that
601 // F will need to directly contain B or a copy of B (where the term "directly
602 // contain" is used to distinguish from being "transitively contained" in
603 // a nested funclet).
604 // Use a CFG walk driven by a worklist of (block, color) pairs. The "color"
605 // sets attached during this processing to a block which is the entry of some
606 // funclet F is actually the set of F's parents -- i.e. the union of colors
607 // of all predecessors of F's entry. For all other blocks, the color sets
608 // are as defined above. A post-pass fixes up the block color map to reflect
609 // the same sense of "color" for funclet entries as for other blocks.
611 Worklist.push_back({EntryBlock, EntryBlock});
613 while (!Worklist.empty()) {
614 BasicBlock *Visiting;
616 std::tie(Visiting, Color) = Worklist.pop_back_val();
617 Instruction *VisitingHead = Visiting->getFirstNonPHI();
618 if (VisitingHead->isEHPad() && !isa<CatchEndPadInst>(VisitingHead) &&
619 !isa<CleanupEndPadInst>(VisitingHead)) {
620 // Mark this as a funclet head as a member of itself.
621 FuncletBlocks[Visiting].insert(Visiting);
622 // Queue exits with the parent color.
623 for (User *U : VisitingHead->users()) {
624 if (auto *Exit = dyn_cast<TerminatorInst>(U)) {
625 for (BasicBlock *Succ : successors(Exit->getParent()))
626 if (BlockColors[Succ].insert(Color).second)
627 Worklist.push_back({Succ, Color});
630 // Handle CatchPad specially since its successors need different colors.
631 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(VisitingHead)) {
632 // Visit the normal successor with the color of the new EH pad, and
633 // visit the unwind successor with the color of the parent.
634 BasicBlock *NormalSucc = CatchPad->getNormalDest();
635 if (BlockColors[NormalSucc].insert(Visiting).second) {
636 Worklist.push_back({NormalSucc, Visiting});
638 BasicBlock *UnwindSucc = CatchPad->getUnwindDest();
639 if (BlockColors[UnwindSucc].insert(Color).second) {
640 Worklist.push_back({UnwindSucc, Color});
644 // Switch color to the current node, except for terminate pads which
645 // have no bodies and only unwind successors and so need their successors
646 // visited with the color of the parent.
647 if (!isa<TerminatePadInst>(VisitingHead))
650 // Note that this is a member of the given color.
651 FuncletBlocks[Color].insert(Visiting);
654 TerminatorInst *Terminator = Visiting->getTerminator();
655 if (isa<CleanupReturnInst>(Terminator) ||
656 isa<CatchReturnInst>(Terminator) ||
657 isa<CleanupEndPadInst>(Terminator)) {
658 // These blocks' successors have already been queued with the parent
662 for (BasicBlock *Succ : successors(Visiting)) {
663 if (isa<CatchEndPadInst>(Succ->getFirstNonPHI())) {
664 // The catchendpad needs to be visited with the parent's color, not
665 // the current color. This will happen in the code above that visits
666 // any catchpad unwind successor with the parent color, so we can
667 // safely skip this successor here.
670 if (BlockColors[Succ].insert(Color).second) {
671 Worklist.push_back({Succ, Color});
676 // The processing above actually accumulated the parent set for this
677 // funclet into the color set for its entry; use the parent set to
678 // populate the children map, and reset the color set to include just
679 // the funclet itself (no instruction can target a funclet entry except on
680 // that transitions to the child funclet).
681 for (BasicBlock *FuncletEntry : EntryBlocks) {
682 std::set<BasicBlock *> &ColorMapItem = BlockColors[FuncletEntry];
683 for (BasicBlock *Parent : ColorMapItem)
684 FuncletChildren[Parent].insert(FuncletEntry);
685 ColorMapItem.clear();
686 ColorMapItem.insert(FuncletEntry);
690 void WinEHPrepare::colorFunclets(Function &F,
691 SmallVectorImpl<BasicBlock *> &EntryBlocks) {
692 ::colorFunclets(F, EntryBlocks, BlockColors, FuncletBlocks, FuncletChildren);
695 void llvm::calculateCatchReturnSuccessorColors(const Function *Fn,
696 WinEHFuncInfo &FuncInfo) {
697 SmallVector<BasicBlock *, 4> EntryBlocks;
698 // colorFunclets needs the set of EntryBlocks, get them using
699 // findFuncletEntryPoints.
700 findFuncletEntryPoints(const_cast<Function &>(*Fn), EntryBlocks);
702 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
703 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
704 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletChildren;
705 // Figure out which basic blocks belong to which funclets.
706 colorFunclets(const_cast<Function &>(*Fn), EntryBlocks, BlockColors,
707 FuncletBlocks, FuncletChildren);
709 // We need to find the catchret successors. To do this, we must first find
710 // all the catchpad funclets.
711 for (auto &Funclet : FuncletBlocks) {
712 // Figure out what kind of funclet we are looking at; We only care about
714 BasicBlock *FuncletPadBB = Funclet.first;
715 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
716 auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
720 // The users of a catchpad are always catchrets.
721 for (User *Exit : CatchPad->users()) {
722 auto *CatchReturn = dyn_cast<CatchReturnInst>(Exit);
725 BasicBlock *CatchRetSuccessor = CatchReturn->getSuccessor();
726 std::set<BasicBlock *> &SuccessorColors = BlockColors[CatchRetSuccessor];
727 assert(SuccessorColors.size() == 1 && "Expected BB to be monochrome!");
728 BasicBlock *Color = *SuccessorColors.begin();
729 if (auto *CPI = dyn_cast<CatchPadInst>(Color->getFirstNonPHI()))
730 Color = CPI->getNormalDest();
731 // Record the catchret successor's funclet membership.
732 FuncInfo.CatchRetSuccessorColorMap[CatchReturn] = Color;
737 void WinEHPrepare::demotePHIsOnFunclets(Function &F) {
738 // Strip PHI nodes off of EH pads.
739 SmallVector<PHINode *, 16> PHINodes;
740 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
741 BasicBlock *BB = &*FI++;
744 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
745 Instruction *I = &*BI++;
746 auto *PN = dyn_cast<PHINode>(I);
747 // Stop at the first non-PHI.
751 AllocaInst *SpillSlot = insertPHILoads(PN, F);
753 insertPHIStores(PN, SpillSlot);
755 PHINodes.push_back(PN);
759 for (auto *PN : PHINodes) {
760 // There may be lingering uses on other EH PHIs being removed
761 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
762 PN->eraseFromParent();
766 void WinEHPrepare::demoteUsesBetweenFunclets(Function &F) {
767 // Turn all inter-funclet uses of a Value into loads and stores.
768 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
769 BasicBlock *BB = &*FI++;
770 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
771 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
772 Instruction *I = &*BI++;
773 // Funclets are permitted to use static allocas.
774 if (auto *AI = dyn_cast<AllocaInst>(I))
775 if (AI->isStaticAlloca())
778 demoteNonlocalUses(I, ColorsForBB, F);
783 void WinEHPrepare::demoteArgumentUses(Function &F) {
784 // Also demote function parameters used in funclets.
785 std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()];
786 for (Argument &Arg : F.args())
787 demoteNonlocalUses(&Arg, ColorsForEntry, F);
790 void WinEHPrepare::cloneCommonBlocks(
791 Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
792 // We need to clone all blocks which belong to multiple funclets. Values are
793 // remapped throughout the funclet to propogate both the new instructions
794 // *and* the new basic blocks themselves.
795 for (BasicBlock *FuncletPadBB : EntryBlocks) {
796 std::set<BasicBlock *> &BlocksInFunclet = FuncletBlocks[FuncletPadBB];
798 std::map<BasicBlock *, BasicBlock *> Orig2Clone;
799 ValueToValueMapTy VMap;
800 for (BasicBlock *BB : BlocksInFunclet) {
801 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
802 // We don't need to do anything if the block is monochromatic.
803 size_t NumColorsForBB = ColorsForBB.size();
804 if (NumColorsForBB == 1)
807 // Create a new basic block and copy instructions into it!
809 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
810 // Insert the clone immediately after the original to ensure determinism
811 // and to keep the same relative ordering of any funclet's blocks.
812 CBB->insertInto(&F, BB->getNextNode());
814 // Add basic block mapping.
817 // Record delta operations that we need to perform to our color mappings.
818 Orig2Clone[BB] = CBB;
821 // If nothing was cloned, we're done cloning in this funclet.
822 if (Orig2Clone.empty())
825 // Update our color mappings to reflect that one block has lost a color and
826 // another has gained a color.
827 for (auto &BBMapping : Orig2Clone) {
828 BasicBlock *OldBlock = BBMapping.first;
829 BasicBlock *NewBlock = BBMapping.second;
831 BlocksInFunclet.insert(NewBlock);
832 BlockColors[NewBlock].insert(FuncletPadBB);
834 BlocksInFunclet.erase(OldBlock);
835 BlockColors[OldBlock].erase(FuncletPadBB);
838 // Loop over all of the instructions in this funclet, fixing up operand
839 // references as we go. This uses VMap to do all the hard work.
840 for (BasicBlock *BB : BlocksInFunclet)
841 // Loop over all instructions, fixing each one as we find it...
842 for (Instruction &I : *BB)
843 RemapInstruction(&I, VMap,
844 RF_IgnoreMissingEntries | RF_NoModuleLevelChanges);
846 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
847 // the PHI nodes for NewBB now.
848 for (auto &BBMapping : Orig2Clone) {
849 BasicBlock *OldBlock = BBMapping.first;
850 BasicBlock *NewBlock = BBMapping.second;
851 for (BasicBlock *SuccBB : successors(NewBlock)) {
852 for (Instruction &SuccI : *SuccBB) {
853 auto *SuccPN = dyn_cast<PHINode>(&SuccI);
857 // Ok, we have a PHI node. Figure out what the incoming value was for
859 int OldBlockIdx = SuccPN->getBasicBlockIndex(OldBlock);
860 if (OldBlockIdx == -1)
862 Value *IV = SuccPN->getIncomingValue(OldBlockIdx);
864 // Remap the value if necessary.
865 if (auto *Inst = dyn_cast<Instruction>(IV)) {
866 ValueToValueMapTy::iterator I = VMap.find(Inst);
871 SuccPN->addIncoming(IV, NewBlock);
876 for (ValueToValueMapTy::value_type VT : VMap) {
877 // If there were values defined in BB that are used outside the funclet,
878 // then we now have to update all uses of the value to use either the
879 // original value, the cloned value, or some PHI derived value. This can
880 // require arbitrary PHI insertion, of which we are prepared to do, clean
882 SmallVector<Use *, 16> UsesToRename;
884 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
887 auto *NewI = cast<Instruction>(VT.second);
888 // Scan all uses of this instruction to see if it is used outside of its
889 // funclet, and if so, record them in UsesToRename.
890 for (Use &U : OldI->uses()) {
891 Instruction *UserI = cast<Instruction>(U.getUser());
892 BasicBlock *UserBB = UserI->getParent();
893 std::set<BasicBlock *> &ColorsForUserBB = BlockColors[UserBB];
894 assert(!ColorsForUserBB.empty());
895 if (ColorsForUserBB.size() > 1 ||
896 *ColorsForUserBB.begin() != FuncletPadBB)
897 UsesToRename.push_back(&U);
900 // If there are no uses outside the block, we're done with this
902 if (UsesToRename.empty())
905 // We found a use of OldI outside of the funclet. Rename all uses of OldI
906 // that are outside its funclet to be uses of the appropriate PHI node
908 SSAUpdater SSAUpdate;
909 SSAUpdate.Initialize(OldI->getType(), OldI->getName());
910 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
911 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
913 while (!UsesToRename.empty())
914 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
919 void WinEHPrepare::removeImplausibleTerminators(Function &F) {
920 // Remove implausible terminators and replace them with UnreachableInst.
921 for (auto &Funclet : FuncletBlocks) {
922 BasicBlock *FuncletPadBB = Funclet.first;
923 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
924 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
925 auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
926 auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI);
928 for (BasicBlock *BB : BlocksInFunclet) {
929 TerminatorInst *TI = BB->getTerminator();
930 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
931 bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad);
932 // The token consumed by a CatchReturnInst must match the funclet token.
933 bool IsUnreachableCatchret = false;
934 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
935 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
936 // The token consumed by a CleanupReturnInst must match the funclet token.
937 bool IsUnreachableCleanupret = false;
938 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
939 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
940 // The token consumed by a CleanupEndPadInst must match the funclet token.
941 bool IsUnreachableCleanupendpad = false;
942 if (auto *CEPI = dyn_cast<CleanupEndPadInst>(TI))
943 IsUnreachableCleanupendpad = CEPI->getCleanupPad() != CleanupPad;
944 if (IsUnreachableRet || IsUnreachableCatchret ||
945 IsUnreachableCleanupret || IsUnreachableCleanupendpad) {
946 // Loop through all of our successors and make sure they know that one
947 // of their predecessors is going away.
948 for (BasicBlock *SuccBB : TI->successors())
949 SuccBB->removePredecessor(BB);
951 if (IsUnreachableCleanupendpad) {
952 // We can't simply replace a cleanupendpad with unreachable, because
953 // its predecessor edges are EH edges and unreachable is not an EH
954 // pad. Change all predecessors to the "unwind to caller" form.
955 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
957 BasicBlock *Pred = *PI++;
958 removeUnwindEdge(Pred);
962 new UnreachableInst(BB->getContext(), TI);
963 TI->eraseFromParent();
965 // FIXME: Check for invokes/cleanuprets/cleanupendpads which unwind to
966 // implausible catchendpads (i.e. catchendpad not in immediate parent
972 void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
973 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
975 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
976 BasicBlock *BB = &*FI++;
977 SimplifyInstructionsInBlock(BB);
978 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
979 MergeBlockIntoPredecessor(BB);
982 // We might have some unreachable blocks after cleaning up some impossible
984 removeUnreachableBlocks(F);
987 void WinEHPrepare::verifyPreparedFunclets(Function &F) {
988 // Recolor the CFG to verify that all is well.
989 for (BasicBlock &BB : F) {
990 size_t NumColors = BlockColors[&BB].size();
991 assert(NumColors == 1 && "Expected monochromatic BB!");
993 report_fatal_error("Uncolored BB!");
995 report_fatal_error("Multicolor BB!");
996 if (!DisableDemotion) {
997 bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
998 assert(!EHPadHasPHI && "EH Pad still has a PHI!");
1000 report_fatal_error("EH Pad still has a PHI!");
1005 bool WinEHPrepare::prepareExplicitEH(
1006 Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
1007 replaceTerminatePadWithCleanup(F);
1009 // Determine which blocks are reachable from which funclet entries.
1010 colorFunclets(F, EntryBlocks);
1012 if (!DisableDemotion) {
1013 demotePHIsOnFunclets(F);
1015 demoteUsesBetweenFunclets(F);
1017 demoteArgumentUses(F);
1020 cloneCommonBlocks(F, EntryBlocks);
1022 if (!DisableCleanups) {
1023 removeImplausibleTerminators(F);
1025 cleanupPreparedFunclets(F);
1028 verifyPreparedFunclets(F);
1030 BlockColors.clear();
1031 FuncletBlocks.clear();
1032 FuncletChildren.clear();
1037 // TODO: Share loads when one use dominates another, or when a catchpad exit
1038 // dominates uses (needs dominators).
1039 AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
1040 BasicBlock *PHIBlock = PN->getParent();
1041 AllocaInst *SpillSlot = nullptr;
1043 if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) {
1044 // Insert a load in place of the PHI and replace all uses.
1045 SpillSlot = new AllocaInst(PN->getType(), nullptr,
1046 Twine(PN->getName(), ".wineh.spillslot"),
1047 &F.getEntryBlock().front());
1048 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
1049 &*PHIBlock->getFirstInsertionPt());
1050 PN->replaceAllUsesWith(V);
1054 DenseMap<BasicBlock *, Value *> Loads;
1055 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1058 auto *UsingInst = cast<Instruction>(U.getUser());
1059 BasicBlock *UsingBB = UsingInst->getParent();
1060 if (UsingBB->isEHPad()) {
1061 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
1062 // stores for it separately.
1063 assert(isa<PHINode>(UsingInst));
1066 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
1071 // TODO: improve store placement. Inserting at def is probably good, but need
1072 // to be careful not to introduce interfering stores (needs liveness analysis).
1073 // TODO: identify related phi nodes that can share spill slots, and share them
1074 // (also needs liveness).
1075 void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
1076 AllocaInst *SpillSlot) {
1077 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
1078 // stored to the spill slot by the end of the given Block.
1079 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
1081 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
1083 while (!Worklist.empty()) {
1084 BasicBlock *EHBlock;
1086 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
1088 PHINode *PN = dyn_cast<PHINode>(InVal);
1089 if (PN && PN->getParent() == EHBlock) {
1090 // The value is defined by another PHI we need to remove, with no room to
1091 // insert a store after the PHI, so each predecessor needs to store its
1093 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1094 Value *PredVal = PN->getIncomingValue(i);
1096 // Undef can safely be skipped.
1097 if (isa<UndefValue>(PredVal))
1100 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
1103 // We need to store InVal, which dominates EHBlock, but can't put a store
1104 // in EHBlock, so need to put stores in each predecessor.
1105 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
1106 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
1112 void WinEHPrepare::insertPHIStore(
1113 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
1114 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
1116 if (PredBlock->isEHPad() &&
1117 !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) {
1118 // Pred is unsplittable, so we need to queue it on the worklist.
1119 Worklist.push_back({PredBlock, PredVal});
1123 // Otherwise, insert the store at the end of the basic block.
1124 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
1127 // TODO: Share loads for same-funclet uses (requires dominators if funclets
1128 // aren't properly nested).
1129 void WinEHPrepare::demoteNonlocalUses(Value *V,
1130 std::set<BasicBlock *> &ColorsForBB,
1132 // Tokens can only be used non-locally due to control flow involving
1133 // unreachable edges. Don't try to demote the token usage, we'll simply
1134 // delete the cloned user later.
1135 if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V))
1138 DenseMap<BasicBlock *, Value *> Loads;
1139 AllocaInst *SpillSlot = nullptr;
1140 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) {
1142 auto *UsingInst = cast<Instruction>(U.getUser());
1143 BasicBlock *UsingBB = UsingInst->getParent();
1145 // Is the Use inside a block which is colored the same as the Def?
1146 // If so, we don't need to escape the Def because we will clone
1147 // ourselves our own private copy.
1148 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
1149 if (ColorsForUsingBB == ColorsForBB)
1152 replaceUseWithLoad(V, U, SpillSlot, Loads, F);
1155 // Insert stores of the computed value into the stack slot.
1156 // We have to be careful if I is an invoke instruction,
1157 // because we can't insert the store AFTER the terminator instruction.
1158 BasicBlock::iterator InsertPt;
1159 if (isa<Argument>(V)) {
1160 InsertPt = F.getEntryBlock().getTerminator()->getIterator();
1161 } else if (isa<TerminatorInst>(V)) {
1162 auto *II = cast<InvokeInst>(V);
1163 // We cannot demote invoke instructions to the stack if their normal
1164 // edge is critical. Therefore, split the critical edge and create a
1165 // basic block into which the store can be inserted.
1166 if (!II->getNormalDest()->getSinglePredecessor()) {
1168 GetSuccessorNumber(II->getParent(), II->getNormalDest());
1169 assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
1170 BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
1171 assert(NewBlock && "Unable to split critical edge.");
1172 // Update the color mapping for the newly split edge.
1173 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()];
1174 BlockColors[NewBlock] = ColorsForUsingBB;
1175 for (BasicBlock *FuncletPad : ColorsForUsingBB)
1176 FuncletBlocks[FuncletPad].insert(NewBlock);
1178 InsertPt = II->getNormalDest()->getFirstInsertionPt();
1180 InsertPt = cast<Instruction>(V)->getIterator();
1182 // Don't insert before PHI nodes or EH pad instrs.
1183 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
1186 new StoreInst(V, SpillSlot, &*InsertPt);
1190 void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
1191 DenseMap<BasicBlock *, Value *> &Loads,
1193 // Lazilly create the spill slot.
1195 SpillSlot = new AllocaInst(V->getType(), nullptr,
1196 Twine(V->getName(), ".wineh.spillslot"),
1197 &F.getEntryBlock().front());
1199 auto *UsingInst = cast<Instruction>(U.getUser());
1200 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
1201 // If this is a PHI node, we can't insert a load of the value before
1202 // the use. Instead insert the load in the predecessor block
1203 // corresponding to the incoming value.
1205 // Note that if there are multiple edges from a basic block to this
1206 // PHI node that we cannot have multiple loads. The problem is that
1207 // the resulting PHI node will have multiple values (from each load)
1208 // coming in from the same block, which is illegal SSA form.
1209 // For this reason, we keep track of and reuse loads we insert.
1210 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
1211 if (auto *CatchRet =
1212 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1213 // Putting a load above a catchret and use on the phi would still leave
1214 // a cross-funclet def/use. We need to split the edge, change the
1215 // catchret to target the new block, and put the load there.
1216 BasicBlock *PHIBlock = UsingInst->getParent();
1217 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
1218 // SplitEdge gives us:
1221 // br label %NewBlock
1223 // catchret label %PHIBlock
1227 // catchret label %NewBlock
1229 // br label %PHIBlock
1230 // So move the terminators to each others' blocks and swap their
1232 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
1233 Goto->removeFromParent();
1234 CatchRet->removeFromParent();
1235 IncomingBlock->getInstList().push_back(CatchRet);
1236 NewBlock->getInstList().push_back(Goto);
1237 Goto->setSuccessor(0, PHIBlock);
1238 CatchRet->setSuccessor(NewBlock);
1239 // Update the color mapping for the newly split edge.
1240 std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock];
1241 BlockColors[NewBlock] = ColorsForPHIBlock;
1242 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
1243 FuncletBlocks[FuncletPad].insert(NewBlock);
1244 // Treat the new block as incoming for load insertion.
1245 IncomingBlock = NewBlock;
1247 Value *&Load = Loads[IncomingBlock];
1248 // Insert the load into the predecessor block
1250 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1251 /*Volatile=*/false, IncomingBlock->getTerminator());
1255 // Reload right before the old use.
1256 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1257 /*Volatile=*/false, UsingInst);
1262 void WinEHFuncInfo::addIPToStateRange(const BasicBlock *PadBB,
1263 MCSymbol *InvokeBegin,
1264 MCSymbol *InvokeEnd) {
1265 assert(PadBB->isEHPad() && EHPadStateMap.count(PadBB->getFirstNonPHI()) &&
1266 "should get EH pad BB with precomputed state");
1267 InvokeToStateMap[InvokeBegin] =
1268 std::make_pair(EHPadStateMap[PadBB->getFirstNonPHI()], InvokeEnd);