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. It snifs the personality function to see which kind of
12 // preparation is necessary. If the personality function uses the Itanium LSDA,
13 // this pass delegates to the DWARF EH preparation pass.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/TinyPtrVector.h"
22 #include "llvm/Analysis/LibCallSemantics.h"
23 #include "llvm/CodeGen/WinEHFuncInfo.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Cloning.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
42 using namespace llvm::PatternMatch;
44 #define DEBUG_TYPE "winehprepare"
48 // This map is used to model frame variable usage during outlining, to
49 // construct a structure type to hold the frame variables in a frame
50 // allocation block, and to remap the frame variable allocas (including
51 // spill locations as needed) to GEPs that get the variable from the
52 // frame allocation structure.
53 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
55 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
57 AllocaInst *getCatchObjectSentinel() {
58 return static_cast<AllocaInst *>(nullptr) + 1;
61 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
63 class LandingPadActions;
66 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
67 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
69 class WinEHPrepare : public FunctionPass {
71 static char ID; // Pass identification, replacement for typeid.
72 WinEHPrepare(const TargetMachine *TM = nullptr)
73 : FunctionPass(ID), DT(nullptr) {}
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 bool prepareExceptionHandlers(Function &F,
87 SmallVectorImpl<LandingPadInst *> &LPads);
88 void promoteLandingPadValues(LandingPadInst *LPad);
89 void completeNestedLandingPad(Function *ParentFn,
90 LandingPadInst *OutlinedLPad,
91 const LandingPadInst *OriginalLPad,
92 FrameVarInfoMap &VarInfo);
93 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
94 LandingPadInst *LPad, BasicBlock *StartBB,
95 FrameVarInfoMap &VarInfo);
97 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
98 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
99 VisitedBlockSet &VisitedBlocks);
100 CleanupHandler *findCleanupHandler(BasicBlock *StartBB, BasicBlock *EndBB);
102 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
104 // All fields are reset by runOnFunction.
106 EHPersonality Personality;
107 CatchHandlerMapTy CatchHandlerMap;
108 CleanupHandlerMapTy CleanupHandlerMap;
109 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
111 // This maps landing pad instructions found in outlined handlers to
112 // the landing pad instruction in the parent function from which they
113 // were cloned. The cloned/nested landing pad is used as the key
114 // because the landing pad may be cloned into multiple handlers.
115 // This map will be used to add the llvm.eh.actions call to the nested
116 // landing pads after all handlers have been outlined.
117 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
119 // This maps blocks in the parent function which are destinations of
120 // catch handlers to cloned blocks in (other) outlined handlers. This
121 // handles the case where a nested landing pads has a catch handler that
122 // returns to a handler function rather than the parent function.
123 // The original block is used as the key here because there should only
124 // ever be one handler function from which the cloned block is not pruned.
125 // The original block will be pruned from the parent function after all
126 // handlers have been outlined. This map will be used to adjust the
127 // return instructions of handlers which return to the block that was
128 // outlined into a handler. This is done after all handlers have been
129 // outlined but before the outlined code is pruned from the parent function.
130 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
133 class WinEHFrameVariableMaterializer : public ValueMaterializer {
135 WinEHFrameVariableMaterializer(Function *OutlinedFn,
136 FrameVarInfoMap &FrameVarInfo);
137 ~WinEHFrameVariableMaterializer() {}
139 virtual Value *materializeValueFor(Value *V) override;
141 void escapeCatchObject(Value *V);
144 FrameVarInfoMap &FrameVarInfo;
148 class LandingPadMap {
150 LandingPadMap() : OriginLPad(nullptr) {}
151 void mapLandingPad(const LandingPadInst *LPad);
153 bool isInitialized() { return OriginLPad != nullptr; }
155 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
156 bool isLandingPadSpecificInst(const Instruction *Inst) const;
158 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
159 Value *SelectorValue) const;
162 const LandingPadInst *OriginLPad;
163 // We will normally only see one of each of these instructions, but
164 // if more than one occurs for some reason we can handle that.
165 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
166 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
169 class WinEHCloningDirectorBase : public CloningDirector {
171 WinEHCloningDirectorBase(Function *HandlerFn, FrameVarInfoMap &VarInfo,
172 LandingPadMap &LPadMap)
173 : Materializer(HandlerFn, VarInfo),
174 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
175 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
178 CloningAction handleInstruction(ValueToValueMapTy &VMap,
179 const Instruction *Inst,
180 BasicBlock *NewBB) override;
182 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
183 const Instruction *Inst,
184 BasicBlock *NewBB) = 0;
185 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
186 const Instruction *Inst,
187 BasicBlock *NewBB) = 0;
188 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
189 const Instruction *Inst,
190 BasicBlock *NewBB) = 0;
191 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
192 const InvokeInst *Invoke,
193 BasicBlock *NewBB) = 0;
194 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
195 const ResumeInst *Resume,
196 BasicBlock *NewBB) = 0;
197 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
198 const LandingPadInst *LPad,
199 BasicBlock *NewBB) = 0;
201 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
204 WinEHFrameVariableMaterializer Materializer;
205 Type *SelectorIDType;
207 LandingPadMap &LPadMap;
210 class WinEHCatchDirector : public WinEHCloningDirectorBase {
213 Function *CatchFn, Value *Selector, FrameVarInfoMap &VarInfo,
214 LandingPadMap &LPadMap,
215 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
216 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
217 CurrentSelector(Selector->stripPointerCasts()),
218 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
220 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
221 const Instruction *Inst,
222 BasicBlock *NewBB) override;
223 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
224 BasicBlock *NewBB) override;
225 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
226 const Instruction *Inst,
227 BasicBlock *NewBB) override;
228 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
229 BasicBlock *NewBB) override;
230 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
231 BasicBlock *NewBB) override;
232 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
233 const LandingPadInst *LPad,
234 BasicBlock *NewBB) override;
236 Value *getExceptionVar() { return ExceptionObjectVar; }
237 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
240 Value *CurrentSelector;
242 Value *ExceptionObjectVar;
243 TinyPtrVector<BasicBlock *> ReturnTargets;
245 // This will be a reference to the field of the same name in the WinEHPrepare
246 // object which instantiates this WinEHCatchDirector object.
247 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
250 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
252 WinEHCleanupDirector(Function *CleanupFn, FrameVarInfoMap &VarInfo,
253 LandingPadMap &LPadMap)
254 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
256 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
257 const Instruction *Inst,
258 BasicBlock *NewBB) override;
259 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
260 BasicBlock *NewBB) override;
261 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
262 const Instruction *Inst,
263 BasicBlock *NewBB) override;
264 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
265 BasicBlock *NewBB) override;
266 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
267 BasicBlock *NewBB) override;
268 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
269 const LandingPadInst *LPad,
270 BasicBlock *NewBB) override;
273 class LandingPadActions {
275 LandingPadActions() : HasCleanupHandlers(false) {}
277 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
278 void insertCleanupHandler(CleanupHandler *Action) {
279 Actions.push_back(Action);
280 HasCleanupHandlers = true;
283 bool includesCleanup() const { return HasCleanupHandlers; }
285 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
286 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
287 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
290 // Note that this class does not own the ActionHandler objects in this vector.
291 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
292 // in the WinEHPrepare class.
293 SmallVector<ActionHandler *, 4> Actions;
294 bool HasCleanupHandlers;
297 } // end anonymous namespace
299 char WinEHPrepare::ID = 0;
300 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
303 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
304 return new WinEHPrepare(TM);
307 // FIXME: Remove this once the backend can handle the prepared IR.
309 SEHPrepare("sehprepare", cl::Hidden,
310 cl::desc("Prepare functions with SEH personalities"));
312 bool WinEHPrepare::runOnFunction(Function &Fn) {
313 SmallVector<LandingPadInst *, 4> LPads;
314 SmallVector<ResumeInst *, 4> Resumes;
315 for (BasicBlock &BB : Fn) {
316 if (auto *LP = BB.getLandingPadInst())
318 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
319 Resumes.push_back(Resume);
322 // No need to prepare functions that lack landing pads.
326 // Classify the personality to see what kind of preparation we need.
327 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
329 // Do nothing if this is not an MSVC personality.
330 if (!isMSVCEHPersonality(Personality))
333 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
335 if (isAsynchronousEHPersonality(Personality) && !SEHPrepare) {
336 // Replace all resume instructions with unreachable.
337 // FIXME: Remove this once the backend can handle the prepared IR.
338 for (ResumeInst *Resume : Resumes) {
339 IRBuilder<>(Resume).CreateUnreachable();
340 Resume->eraseFromParent();
345 // If there were any landing pads, prepareExceptionHandlers will make changes.
346 prepareExceptionHandlers(Fn, LPads);
350 bool WinEHPrepare::doFinalization(Module &M) { return false; }
352 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
353 AU.addRequired<DominatorTreeWrapperPass>();
356 bool WinEHPrepare::prepareExceptionHandlers(
357 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
358 // These containers are used to re-map frame variables that are used in
359 // outlined catch and cleanup handlers. They will be populated as the
360 // handlers are outlined.
361 FrameVarInfoMap FrameVarInfo;
363 bool HandlersOutlined = false;
365 Module *M = F.getParent();
366 LLVMContext &Context = M->getContext();
368 // Create a new function to receive the handler contents.
369 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
370 Type *Int32Type = Type::getInt32Ty(Context);
371 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
373 for (LandingPadInst *LPad : LPads) {
374 // Look for evidence that this landingpad has already been processed.
375 bool LPadHasActionList = false;
376 BasicBlock *LPadBB = LPad->getParent();
377 for (Instruction &Inst : *LPadBB) {
378 if (auto *IntrinCall = dyn_cast<IntrinsicInst>(&Inst)) {
379 if (IntrinCall->getIntrinsicID() == Intrinsic::eh_actions) {
380 LPadHasActionList = true;
384 // FIXME: This is here to help with the development of nested landing pad
385 // outlining. It should be removed when that is finished.
386 if (isa<UnreachableInst>(Inst)) {
387 LPadHasActionList = true;
392 // If we've already outlined the handlers for this landingpad,
393 // there's nothing more to do here.
394 if (LPadHasActionList)
397 // If either of the values in the aggregate returned by the landing pad is
398 // extracted and stored to memory, promote the stored value to a register.
399 promoteLandingPadValues(LPad);
401 LandingPadActions Actions;
402 mapLandingPadBlocks(LPad, Actions);
404 for (ActionHandler *Action : Actions) {
405 if (Action->hasBeenProcessed())
407 BasicBlock *StartBB = Action->getStartBlock();
409 // SEH doesn't do any outlining for catches. Instead, pass the handler
410 // basic block addr to llvm.eh.actions and list the block as a return
412 if (isAsynchronousEHPersonality(Personality)) {
413 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
414 processSEHCatchHandler(CatchAction, StartBB);
415 HandlersOutlined = true;
420 if (outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo)) {
421 HandlersOutlined = true;
423 } // End for each Action
425 // FIXME: We need a guard against partially outlined functions.
426 if (!HandlersOutlined)
429 // Replace the landing pad with a new llvm.eh.action based landing pad.
430 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
431 assert(!isa<PHINode>(LPadBB->begin()));
432 auto *NewLPad = cast<LandingPadInst>(LPad->clone());
433 NewLPadBB->getInstList().push_back(NewLPad);
434 while (!pred_empty(LPadBB)) {
435 auto *pred = *pred_begin(LPadBB);
436 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
437 Invoke->setUnwindDest(NewLPadBB);
440 // Replace the mapping of any nested landing pad that previously mapped
441 // to this landing pad with a referenced to the cloned version.
442 for (auto &LPadPair : NestedLPtoOriginalLP) {
443 const LandingPadInst *OriginalLPad = LPadPair.second;
444 if (OriginalLPad == LPad) {
445 LPadPair.second = NewLPad;
449 // Replace uses of the old lpad in phis with this block and delete the old
451 LPadBB->replaceSuccessorsPhiUsesWith(NewLPadBB);
452 LPadBB->getTerminator()->eraseFromParent();
453 new UnreachableInst(LPadBB->getContext(), LPadBB);
455 // Add a call to describe the actions for this landing pad.
456 std::vector<Value *> ActionArgs;
457 for (ActionHandler *Action : Actions) {
458 // Action codes from docs are: 0 cleanup, 1 catch.
459 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
460 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
461 ActionArgs.push_back(CatchAction->getSelector());
462 // Find the frame escape index of the exception object alloca in the
464 int FrameEscapeIdx = -1;
465 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
466 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
467 auto I = FrameVarInfo.find(EHObj);
468 assert(I != FrameVarInfo.end() &&
469 "failed to map llvm.eh.begincatch var");
470 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
472 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
474 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
476 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
479 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
481 // Add an indirect branch listing possible successors of the catch handlers.
482 IndirectBrInst *Branch = IndirectBrInst::Create(Recover, 0, NewLPadBB);
483 for (ActionHandler *Action : Actions) {
484 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
485 for (auto *Target : CatchAction->getReturnTargets()) {
486 Branch->addDestination(Target);
490 } // End for each landingpad
492 // If nothing got outlined, there is no more processing to be done.
493 if (!HandlersOutlined)
496 // Replace any nested landing pad stubs with the correct action handler.
497 // This must be done before we remove unreachable blocks because it
498 // cleans up references to outlined blocks that will be deleted.
499 for (auto &LPadPair : NestedLPtoOriginalLP)
500 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
502 F.addFnAttr("wineh-parent", F.getName());
504 // Delete any blocks that were only used by handlers that were outlined above.
505 removeUnreachableBlocks(F);
507 BasicBlock *Entry = &F.getEntryBlock();
508 IRBuilder<> Builder(F.getParent()->getContext());
509 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
511 Function *FrameEscapeFn =
512 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
513 Function *RecoverFrameFn =
514 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
516 // Finally, replace all of the temporary allocas for frame variables used in
517 // the outlined handlers with calls to llvm.framerecover.
518 BasicBlock::iterator II = Entry->getFirstInsertionPt();
519 Instruction *AllocaInsertPt = II;
520 SmallVector<Value *, 8> AllocasToEscape;
521 for (auto &VarInfoEntry : FrameVarInfo) {
522 Value *ParentVal = VarInfoEntry.first;
523 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
525 // If the mapped value isn't already an alloca, we need to spill it if it
526 // is a computed value or copy it if it is an argument.
527 AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
529 if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
530 // Lower this argument to a copy and then demote that to the stack.
531 // We can't just use the argument location because the handler needs
532 // it to be in the frame allocation block.
533 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
534 Value *TrueValue = ConstantInt::getTrue(Context);
535 Value *UndefValue = UndefValue::get(Arg->getType());
537 SelectInst::Create(TrueValue, Arg, UndefValue,
538 Arg->getName() + ".tmp", AllocaInsertPt);
539 Arg->replaceAllUsesWith(SI);
540 // Reset the select operand, because it was clobbered by the RAUW above.
541 SI->setOperand(1, Arg);
542 ParentAlloca = DemoteRegToStack(*SI, true, SI);
543 } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
544 ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
546 Instruction *ParentInst = cast<Instruction>(ParentVal);
547 // FIXME: This is a work-around to temporarily handle the case where an
548 // instruction that is only used in handlers is not sunk.
549 // Without uses, DemoteRegToStack would just eliminate the value.
550 // This will fail if ParentInst is an invoke.
551 if (ParentInst->getNumUses() == 0) {
552 BasicBlock::iterator InsertPt = ParentInst;
555 new AllocaInst(ParentInst->getType(), nullptr,
556 ParentInst->getName() + ".reg2mem", InsertPt);
557 new StoreInst(ParentInst, ParentAlloca, InsertPt);
559 ParentAlloca = DemoteRegToStack(*ParentInst, true, ParentInst);
564 // FIXME: We should try to sink unescaped allocas from the parent frame into
565 // the child frame. If the alloca is escaped, we have to use the lifetime
566 // markers to ensure that the alloca is only live within the child frame.
568 // Add this alloca to the list of things to escape.
569 AllocasToEscape.push_back(ParentAlloca);
571 // Next replace all outlined allocas that are mapped to it.
572 for (AllocaInst *TempAlloca : Allocas) {
573 if (TempAlloca == getCatchObjectSentinel())
574 continue; // Skip catch parameter sentinels.
575 Function *HandlerFn = TempAlloca->getParent()->getParent();
576 // FIXME: Sink this GEP into the blocks where it is used.
577 Builder.SetInsertPoint(TempAlloca);
578 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
579 Value *RecoverArgs[] = {
580 Builder.CreateBitCast(&F, Int8PtrType, ""),
581 &(HandlerFn->getArgumentList().back()),
582 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
583 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
584 // Add a pointer bitcast if the alloca wasn't an i8.
585 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
586 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
588 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
590 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
591 TempAlloca->removeFromParent();
592 RecoveredAlloca->takeName(TempAlloca);
595 } // End for each FrameVarInfo entry.
597 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
599 Builder.SetInsertPoint(&F.getEntryBlock().back());
600 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
602 // Clean up the handler action maps we created for this function
603 DeleteContainerSeconds(CatchHandlerMap);
604 CatchHandlerMap.clear();
605 DeleteContainerSeconds(CleanupHandlerMap);
606 CleanupHandlerMap.clear();
608 return HandlersOutlined;
611 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
612 // If the return values of the landing pad instruction are extracted and
613 // stored to memory, we want to promote the store locations to reg values.
614 SmallVector<AllocaInst *, 2> EHAllocas;
616 // The landingpad instruction returns an aggregate value. Typically, its
617 // value will be passed to a pair of extract value instructions and the
618 // results of those extracts are often passed to store instructions.
619 // In unoptimized code the stored value will often be loaded and then stored
621 for (auto *U : LPad->users()) {
622 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
626 for (auto *EU : Extract->users()) {
627 if (auto *Store = dyn_cast<StoreInst>(EU)) {
628 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
629 EHAllocas.push_back(AV);
634 // We can't do this without a dominator tree.
637 if (!EHAllocas.empty()) {
638 PromoteMemToReg(EHAllocas, *DT);
643 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
644 LandingPadInst *OutlinedLPad,
645 const LandingPadInst *OriginalLPad,
646 FrameVarInfoMap &FrameVarInfo) {
647 // Get the nested block and erase the unreachable instruction that was
648 // temporarily inserted as its terminator.
649 LLVMContext &Context = ParentFn->getContext();
650 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
651 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
652 OutlinedBB->getTerminator()->eraseFromParent();
653 // That should leave OutlinedLPad as the last instruction in its block.
654 assert(&OutlinedBB->back() == OutlinedLPad);
656 // The original landing pad will have already had its action intrinsic
657 // built by the outlining loop. We need to clone that into the outlined
658 // location. It may also be necessary to add references to the exception
659 // variables to the outlined handler in which this landing pad is nested
660 // and remap return instructions in the nested handlers that should return
661 // to an address in the outlined handler.
662 Function *OutlinedHandlerFn = OutlinedBB->getParent();
663 BasicBlock::const_iterator II = OriginalLPad;
665 // The instruction after the landing pad should now be a call to eh.actions.
666 const Instruction *Recover = II;
667 assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
668 IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
670 // Remap the exception variables into the outlined function.
671 WinEHFrameVariableMaterializer Materializer(OutlinedHandlerFn, FrameVarInfo);
672 SmallVector<BlockAddress *, 4> ActionTargets;
673 SmallVector<ActionHandler *, 4> ActionList;
674 parseEHActions(EHActions, ActionList);
675 for (auto *Action : ActionList) {
676 auto *Catch = dyn_cast<CatchHandler>(Action);
679 // The dyn_cast to function here selects C++ catch handlers and skips
680 // SEH catch handlers.
681 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
684 // Visit all the return instructions, looking for places that return
685 // to a location within OutlinedHandlerFn.
686 for (BasicBlock &NestedHandlerBB : *Handler) {
687 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
691 // Handler functions must always return a block address.
692 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
693 // The original target will have been in the main parent function,
694 // but if it is the address of a block that has been outlined, it
695 // should be a block that was outlined into OutlinedHandlerFn.
696 assert(BA->getFunction() == ParentFn);
698 // Ignore targets that aren't part of OutlinedHandlerFn.
699 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
702 // If the return value is the address ofF a block that we
703 // previously outlined into the parent handler function, replace
704 // the return instruction and add the mapped target to the list
705 // of possible return addresses.
706 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
707 assert(MappedBB->getParent() == OutlinedHandlerFn);
708 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
709 Ret->eraseFromParent();
710 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
711 ActionTargets.push_back(NewBA);
714 DeleteContainerPointers(ActionList);
716 OutlinedBB->getInstList().push_back(EHActions);
718 // Insert an indirect branch into the outlined landing pad BB.
719 IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
720 // Add the previously collected action targets.
721 for (auto *Target : ActionTargets)
722 IBr->addDestination(Target->getBasicBlock());
725 // This function examines a block to determine whether the block ends with a
726 // conditional branch to a catch handler based on a selector comparison.
727 // This function is used both by the WinEHPrepare::findSelectorComparison() and
728 // WinEHCleanupDirector::handleTypeIdFor().
729 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
730 Constant *&Selector, BasicBlock *&NextBB) {
731 ICmpInst::Predicate Pred;
732 BasicBlock *TBB, *FBB;
735 if (!match(BB->getTerminator(),
736 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
740 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
741 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
744 if (Pred == CmpInst::ICMP_EQ) {
750 if (Pred == CmpInst::ICMP_NE) {
759 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
760 LandingPadInst *LPad, BasicBlock *StartBB,
761 FrameVarInfoMap &VarInfo) {
762 Module *M = SrcFn->getParent();
763 LLVMContext &Context = M->getContext();
765 // Create a new function to receive the handler contents.
766 Type *Int8PtrType = Type::getInt8PtrTy(Context);
767 std::vector<Type *> ArgTys;
768 ArgTys.push_back(Int8PtrType);
769 ArgTys.push_back(Int8PtrType);
771 if (Action->getType() == Catch) {
772 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
773 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
774 SrcFn->getName() + ".catch", M);
776 FunctionType *FnType =
777 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
778 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
779 SrcFn->getName() + ".cleanup", M);
782 Handler->addFnAttr("wineh-parent", SrcFn->getName());
784 // Generate a standard prolog to setup the frame recovery structure.
785 IRBuilder<> Builder(Context);
786 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
787 Handler->getBasicBlockList().push_front(Entry);
788 Builder.SetInsertPoint(Entry);
789 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
791 std::unique_ptr<WinEHCloningDirectorBase> Director;
793 ValueToValueMapTy VMap;
795 LandingPadMap &LPadMap = LPadMaps[LPad];
796 if (!LPadMap.isInitialized())
797 LPadMap.mapLandingPad(LPad);
798 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
799 Constant *Sel = CatchAction->getSelector();
800 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
801 NestedLPtoOriginalLP));
802 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
803 ConstantInt::get(Type::getInt32Ty(Context), 1));
805 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
806 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
807 UndefValue::get(Type::getInt32Ty(Context)));
810 SmallVector<ReturnInst *, 8> Returns;
811 ClonedCodeInfo OutlinedFunctionInfo;
813 // If the start block contains PHI nodes, we need to map them.
814 BasicBlock::iterator II = StartBB->begin();
815 while (auto *PN = dyn_cast<PHINode>(II)) {
817 // Look for PHI values that we have already mapped (such as the selector).
818 for (Value *Val : PN->incoming_values()) {
819 if (VMap.count(Val)) {
820 VMap[PN] = VMap[Val];
824 // If we didn't find a match for this value, map it as an undef.
826 VMap[PN] = UndefValue::get(PN->getType());
831 // Skip over PHIs and, if applicable, landingpad instructions.
832 II = StartBB->getFirstInsertionPt();
834 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
835 /*ModuleLevelChanges=*/false, Returns, "",
836 &OutlinedFunctionInfo, Director.get());
838 // Move all the instructions in the first cloned block into our entry block.
839 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
840 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
841 FirstClonedBB->eraseFromParent();
843 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
844 WinEHCatchDirector *CatchDirector =
845 reinterpret_cast<WinEHCatchDirector *>(Director.get());
846 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
847 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
849 // Look for blocks that are not part of the landing pad that we just
850 // outlined but terminate with a call to llvm.eh.endcatch and a
851 // branch to a block that is in the handler we just outlined.
852 // These blocks will be part of a nested landing pad that intends to
853 // return to an address in this handler. This case is best handled
854 // after both landing pads have been outlined, so for now we'll just
855 // save the association of the blocks in LPadTargetBlocks. The
856 // return instructions which are created from these branches will be
857 // replaced after all landing pads have been outlined.
858 for (const auto &MapEntry : VMap) {
859 // VMap maps all values and blocks that were just cloned, but dead
860 // blocks which were pruned will map to nullptr.
861 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
863 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
864 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
865 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
866 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
868 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
870 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
871 // This would indicate that a nested landing pad wants to return
872 // to a block that is outlined into two different handlers.
873 assert(!LPadTargetBlocks.count(MappedBB));
874 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
878 } // End if (CatchAction)
880 Action->setHandlerBlockOrFunc(Handler);
885 /// This BB must end in a selector dispatch. All we need to do is pass the
886 /// handler block to llvm.eh.actions and list it as a possible indirectbr
888 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
889 BasicBlock *StartBB) {
890 BasicBlock *HandlerBB;
893 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
895 // If this was EH dispatch, this must be a conditional branch to the handler
897 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
898 // leading to crashes if some optimization hoists stuff here.
899 assert(CatchAction->getSelector() && HandlerBB &&
900 "expected catch EH dispatch");
902 // This must be a catch-all. Split the block after the landingpad.
903 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
905 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
907 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
908 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
909 CatchAction->setReturnTargets(Targets);
912 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
913 // Each instance of this class should only ever be used to map a single
915 assert(OriginLPad == nullptr || OriginLPad == LPad);
917 // If the landing pad has already been mapped, there's nothing more to do.
918 if (OriginLPad == LPad)
923 // The landingpad instruction returns an aggregate value. Typically, its
924 // value will be passed to a pair of extract value instructions and the
925 // results of those extracts will have been promoted to reg values before
926 // this routine is called.
927 for (auto *U : LPad->users()) {
928 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
931 assert(Extract->getNumIndices() == 1 &&
932 "Unexpected operation: extracting both landing pad values");
933 unsigned int Idx = *(Extract->idx_begin());
934 assert((Idx == 0 || Idx == 1) &&
935 "Unexpected operation: extracting an unknown landing pad element");
937 ExtractedEHPtrs.push_back(Extract);
938 } else if (Idx == 1) {
939 ExtractedSelectors.push_back(Extract);
944 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
945 return BB->getLandingPadInst() == OriginLPad;
948 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
949 if (Inst == OriginLPad)
951 for (auto *Extract : ExtractedEHPtrs) {
955 for (auto *Extract : ExtractedSelectors) {
962 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
963 Value *SelectorValue) const {
964 // Remap all landing pad extract instructions to the specified values.
965 for (auto *Extract : ExtractedEHPtrs)
966 VMap[Extract] = EHPtrValue;
967 for (auto *Extract : ExtractedSelectors)
968 VMap[Extract] = SelectorValue;
971 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
972 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
973 // If this is one of the boilerplate landing pad instructions, skip it.
974 // The instruction will have already been remapped in VMap.
975 if (LPadMap.isLandingPadSpecificInst(Inst))
976 return CloningDirector::SkipInstruction;
978 // Nested landing pads will be cloned as stubs, with just the
979 // landingpad instruction and an unreachable instruction. When
980 // all landingpads have been outlined, we'll replace this with the
981 // llvm.eh.actions call and indirect branch created when the
982 // landing pad was outlined.
983 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
984 return handleLandingPad(VMap, LPad, NewBB);
987 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
988 return handleInvoke(VMap, Invoke, NewBB);
990 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
991 return handleResume(VMap, Resume, NewBB);
993 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
994 return handleBeginCatch(VMap, Inst, NewBB);
995 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
996 return handleEndCatch(VMap, Inst, NewBB);
997 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
998 return handleTypeIdFor(VMap, Inst, NewBB);
1000 // Continue with the default cloning behavior.
1001 return CloningDirector::CloneInstruction;
1004 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1005 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1006 Instruction *NewInst = LPad->clone();
1007 if (LPad->hasName())
1008 NewInst->setName(LPad->getName());
1009 // Save this correlation for later processing.
1010 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1011 VMap[LPad] = NewInst;
1012 BasicBlock::InstListType &InstList = NewBB->getInstList();
1013 InstList.push_back(NewInst);
1014 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1015 return CloningDirector::StopCloningBB;
1018 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1019 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1020 // The argument to the call is some form of the first element of the
1021 // landingpad aggregate value, but that doesn't matter. It isn't used
1023 // The second argument is an outparameter where the exception object will be
1024 // stored. Typically the exception object is a scalar, but it can be an
1025 // aggregate when catching by value.
1026 // FIXME: Leave something behind to indicate where the exception object lives
1027 // for this handler. Should it be part of llvm.eh.actions?
1028 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1029 "llvm.eh.begincatch found while "
1030 "outlining catch handler.");
1031 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1032 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1033 return CloningDirector::SkipInstruction;
1034 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1035 "catch parameter is not static alloca");
1036 Materializer.escapeCatchObject(ExceptionObjectVar);
1037 return CloningDirector::SkipInstruction;
1040 CloningDirector::CloningAction
1041 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1042 const Instruction *Inst, BasicBlock *NewBB) {
1043 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1044 // It might be interesting to track whether or not we are inside a catch
1045 // function, but that might make the algorithm more brittle than it needs
1048 // The end catch call can occur in one of two places: either in a
1049 // landingpad block that is part of the catch handlers exception mechanism,
1050 // or at the end of the catch block. However, a catch-all handler may call
1051 // end catch from the original landing pad. If the call occurs in a nested
1052 // landing pad block, we must skip it and continue so that the landing pad
1054 auto *ParentBB = IntrinCall->getParent();
1055 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1056 return CloningDirector::SkipInstruction;
1058 // If an end catch occurs anywhere else we want to terminate the handler
1059 // with a return to the code that follows the endcatch call. If the
1060 // next instruction is not an unconditional branch, we need to split the
1061 // block to provide a clear target for the return instruction.
1062 BasicBlock *ContinueBB;
1063 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1064 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1065 if (!Branch || !Branch->isUnconditional()) {
1066 // We're interrupting the cloning process at this location, so the
1067 // const_cast we're doing here will not cause a problem.
1068 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1069 const_cast<Instruction *>(cast<Instruction>(Next)));
1071 ContinueBB = Branch->getSuccessor(0);
1074 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1075 ReturnTargets.push_back(ContinueBB);
1077 // We just added a terminator to the cloned block.
1078 // Tell the caller to stop processing the current basic block so that
1079 // the branch instruction will be skipped.
1080 return CloningDirector::StopCloningBB;
1083 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1084 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1085 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1086 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1087 // This causes a replacement that will collapse the landing pad CFG based
1088 // on the filter function we intend to match.
1089 if (Selector == CurrentSelector)
1090 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1092 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1093 // Tell the caller not to clone this instruction.
1094 return CloningDirector::SkipInstruction;
1097 CloningDirector::CloningAction
1098 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1099 const InvokeInst *Invoke, BasicBlock *NewBB) {
1100 return CloningDirector::CloneInstruction;
1103 CloningDirector::CloningAction
1104 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1105 const ResumeInst *Resume, BasicBlock *NewBB) {
1106 // Resume instructions shouldn't be reachable from catch handlers.
1107 // We still need to handle it, but it will be pruned.
1108 BasicBlock::InstListType &InstList = NewBB->getInstList();
1109 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1110 return CloningDirector::StopCloningBB;
1113 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1114 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1115 // The MS runtime will terminate the process if an exception occurs in a
1116 // cleanup handler, so we shouldn't encounter landing pads in the actual
1117 // cleanup code, but they may appear in catch blocks. Depending on where
1118 // we started cloning we may see one, but it will get dropped during dead
1120 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1121 VMap[LPad] = NewInst;
1122 BasicBlock::InstListType &InstList = NewBB->getInstList();
1123 InstList.push_back(NewInst);
1124 return CloningDirector::StopCloningBB;
1127 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1128 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1129 // Catch blocks within cleanup handlers will always be unreachable.
1130 // We'll insert an unreachable instruction now, but it will be pruned
1131 // before the cloning process is complete.
1132 BasicBlock::InstListType &InstList = NewBB->getInstList();
1133 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1134 return CloningDirector::StopCloningBB;
1137 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1138 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1139 // Catch blocks within cleanup handlers will always be unreachable.
1140 // We'll insert an unreachable instruction now, but it will be pruned
1141 // before the cloning process is complete.
1142 BasicBlock::InstListType &InstList = NewBB->getInstList();
1143 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1144 return CloningDirector::StopCloningBB;
1147 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1148 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1149 // If we encounter a selector comparison while cloning a cleanup handler,
1150 // we want to stop cloning immediately. Anything after the dispatch
1151 // will be outlined into a different handler.
1152 BasicBlock *CatchHandler;
1155 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1156 CatchHandler, Selector, NextBB)) {
1157 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1158 return CloningDirector::StopCloningBB;
1160 // If eg.typeid.for is called for any other reason, it can be ignored.
1161 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1162 return CloningDirector::SkipInstruction;
1165 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1166 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1167 // All invokes in cleanup handlers can be replaced with calls.
1168 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1169 // Insert a normal call instruction...
1171 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1172 Invoke->getName(), NewBB);
1173 NewCall->setCallingConv(Invoke->getCallingConv());
1174 NewCall->setAttributes(Invoke->getAttributes());
1175 NewCall->setDebugLoc(Invoke->getDebugLoc());
1176 VMap[Invoke] = NewCall;
1178 // Insert an unconditional branch to the normal destination.
1179 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1181 // The unwind destination won't be cloned into the new function, so
1182 // we don't need to clean up its phi nodes.
1184 // We just added a terminator to the cloned block.
1185 // Tell the caller to stop processing the current basic block.
1186 return CloningDirector::StopCloningBB;
1189 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1190 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1191 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1193 // We just added a terminator to the cloned block.
1194 // Tell the caller to stop processing the current basic block so that
1195 // the branch instruction will be skipped.
1196 return CloningDirector::StopCloningBB;
1199 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1200 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1201 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1202 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1203 Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
1206 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1207 // If we're asked to materialize a value that is an instruction, we
1208 // temporarily create an alloca in the outlined function and add this
1209 // to the FrameVarInfo map. When all the outlining is complete, we'll
1210 // collect these into a structure, spilling non-alloca values in the
1211 // parent frame as necessary, and replace these temporary allocas with
1212 // GEPs referencing the frame allocation block.
1214 // If the value is an alloca, the mapping is direct.
1215 if (auto *AV = dyn_cast<AllocaInst>(V)) {
1216 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1217 Builder.Insert(NewAlloca, AV->getName());
1218 FrameVarInfo[AV].push_back(NewAlloca);
1222 // For other types of instructions or arguments, we need an alloca based on
1223 // the value's type and a load of the alloca. The alloca will be replaced
1224 // by a GEP, but the load will stay. In the parent function, the value will
1225 // be spilled to a location in the frame allocation block.
1226 if (isa<Instruction>(V) || isa<Argument>(V)) {
1227 AllocaInst *NewAlloca =
1228 Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
1229 FrameVarInfo[V].push_back(NewAlloca);
1230 LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1234 // Don't materialize other values.
1238 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1239 // Catch parameter objects have to live in the parent frame. When we see a use
1240 // of a catch parameter, add a sentinel to the multimap to indicate that it's
1241 // used from another handler. This will prevent us from trying to sink the
1242 // alloca into the handler and ensure that the catch parameter is present in
1243 // the call to llvm.frameescape.
1244 FrameVarInfo[V].push_back(getCatchObjectSentinel());
1247 // This function maps the catch and cleanup handlers that are reachable from the
1248 // specified landing pad. The landing pad sequence will have this basic shape:
1250 // <cleanup handler>
1251 // <selector comparison>
1253 // <cleanup handler>
1254 // <selector comparison>
1256 // <cleanup handler>
1259 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1260 // any arbitrary control flow, but all paths through the cleanup code must
1261 // eventually reach the next selector comparison and no path can skip to a
1262 // different selector comparisons, though some paths may terminate abnormally.
1263 // Therefore, we will use a depth first search from the start of any given
1264 // cleanup block and stop searching when we find the next selector comparison.
1266 // If the landingpad instruction does not have a catch clause, we will assume
1267 // that any instructions other than selector comparisons and catch handlers can
1268 // be ignored. In practice, these will only be the boilerplate instructions.
1270 // The catch handlers may also have any control structure, but we are only
1271 // interested in the start of the catch handlers, so we don't need to actually
1272 // follow the flow of the catch handlers. The start of the catch handlers can
1273 // be located from the compare instructions, but they can be skipped in the
1274 // flow by following the contrary branch.
1275 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1276 LandingPadActions &Actions) {
1277 unsigned int NumClauses = LPad->getNumClauses();
1278 unsigned int HandlersFound = 0;
1279 BasicBlock *BB = LPad->getParent();
1281 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1283 if (NumClauses == 0) {
1284 // This landing pad contains only cleanup code.
1285 CleanupHandler *Action = new CleanupHandler(BB);
1286 CleanupHandlerMap[BB] = Action;
1287 Actions.insertCleanupHandler(Action);
1288 DEBUG(dbgs() << " Assuming cleanup code in block " << BB->getName()
1290 assert(LPad->isCleanup());
1294 VisitedBlockSet VisitedBlocks;
1296 while (HandlersFound != NumClauses) {
1297 BasicBlock *NextBB = nullptr;
1299 // See if the clause we're looking for is a catch-all.
1300 // If so, the catch begins immediately.
1301 if (isa<ConstantPointerNull>(LPad->getClause(HandlersFound))) {
1302 // The catch all must occur last.
1303 assert(HandlersFound == NumClauses - 1);
1305 // For C++ EH, check if there is any interesting cleanup code before we
1306 // begin the catch. This is important because cleanups cannot rethrow
1307 // exceptions but code called from catches can. For SEH, it isn't
1308 // important if some finally code before a catch-all is executed out of
1309 // line or after recovering from the exception.
1310 if (Personality == EHPersonality::MSVC_CXX) {
1311 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1312 // Add a cleanup entry to the list
1313 Actions.insertCleanupHandler(CleanupAction);
1314 DEBUG(dbgs() << " Found cleanup code in block "
1315 << CleanupAction->getStartBlock()->getName() << "\n");
1319 // Add the catch handler to the action list.
1320 CatchHandler *Action =
1321 new CatchHandler(BB, LPad->getClause(HandlersFound), nullptr);
1322 CatchHandlerMap[BB] = Action;
1323 Actions.insertCatchHandler(Action);
1324 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1327 // Once we reach a catch-all, don't expect to hit a resume instruction.
1332 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1333 // See if there is any interesting code executed before the dispatch.
1334 if (auto *CleanupAction =
1335 findCleanupHandler(BB, CatchAction->getStartBlock())) {
1336 // Add a cleanup entry to the list
1337 Actions.insertCleanupHandler(CleanupAction);
1338 DEBUG(dbgs() << " Found cleanup code in block "
1339 << CleanupAction->getStartBlock()->getName() << "\n");
1342 assert(CatchAction);
1345 // Add the catch handler to the action list.
1346 Actions.insertCatchHandler(CatchAction);
1347 DEBUG(dbgs() << " Found catch dispatch in block "
1348 << CatchAction->getStartBlock()->getName() << "\n");
1350 // Move on to the block after the catch handler.
1354 // If we didn't wind up in a catch-all, see if there is any interesting code
1355 // executed before the resume.
1356 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1357 // Add a cleanup entry to the list
1358 Actions.insertCleanupHandler(CleanupAction);
1359 DEBUG(dbgs() << " Found cleanup code in block "
1360 << CleanupAction->getStartBlock()->getName() << "\n");
1363 // It's possible that some optimization moved code into a landingpad that
1365 // previously being used for cleanup. If that happens, we need to execute
1367 // extra code from a cleanup handler.
1368 if (Actions.includesCleanup() && !LPad->isCleanup())
1369 LPad->setCleanup(true);
1372 // This function searches starting with the input block for the next
1373 // block that terminates with a branch whose condition is based on a selector
1374 // comparison. This may be the input block. See the mapLandingPadBlocks
1375 // comments for a discussion of control flow assumptions.
1377 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1378 BasicBlock *&NextBB,
1379 VisitedBlockSet &VisitedBlocks) {
1380 // See if we've already found a catch handler use it.
1381 // Call count() first to avoid creating a null entry for blocks
1382 // we haven't seen before.
1383 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1384 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1385 NextBB = Action->getNextBB();
1389 // VisitedBlocks applies only to the current search. We still
1390 // need to consider blocks that we've visited while mapping other
1392 VisitedBlocks.insert(BB);
1394 BasicBlock *CatchBlock = nullptr;
1395 Constant *Selector = nullptr;
1397 // If this is the first time we've visited this block from any landing pad
1398 // look to see if it is a selector dispatch block.
1399 if (!CatchHandlerMap.count(BB)) {
1400 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1401 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1402 CatchHandlerMap[BB] = Action;
1407 // Visit each successor, looking for the dispatch.
1408 // FIXME: We expect to find the dispatch quickly, so this will probably
1409 // work better as a breadth first search.
1410 for (BasicBlock *Succ : successors(BB)) {
1411 if (VisitedBlocks.count(Succ))
1414 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1421 // These are helper functions to combine repeated code from findCleanupHandler.
1422 static CleanupHandler *
1423 createCleanupHandler(CleanupHandlerMapTy &CleanupHandlerMap, BasicBlock *BB) {
1424 CleanupHandler *Action = new CleanupHandler(BB);
1425 CleanupHandlerMap[BB] = Action;
1429 // This function searches starting with the input block for the next block that
1430 // contains code that is not part of a catch handler and would not be eliminated
1431 // during handler outlining.
1433 CleanupHandler *WinEHPrepare::findCleanupHandler(BasicBlock *StartBB,
1434 BasicBlock *EndBB) {
1435 // Here we will skip over the following:
1437 // landing pad prolog:
1439 // Unconditional branches
1441 // Selector dispatch
1445 // Anything else marks the start of an interesting block
1447 BasicBlock *BB = StartBB;
1448 // Anything other than an unconditional branch will kick us out of this loop
1449 // one way or another.
1451 // If we've already scanned this block, don't scan it again. If it is
1452 // a cleanup block, there will be an action in the CleanupHandlerMap.
1453 // If we've scanned it and it is not a cleanup block, there will be a
1454 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1455 // be no entry in the CleanupHandlerMap. We must call count() first to
1456 // avoid creating a null entry for blocks we haven't scanned.
1457 if (CleanupHandlerMap.count(BB)) {
1458 if (auto *Action = CleanupHandlerMap[BB]) {
1459 return cast<CleanupHandler>(Action);
1461 // Here we handle the case where the cleanup handler map contains a
1462 // value for this block but the value is a nullptr. This means that
1463 // we have previously analyzed the block and determined that it did
1464 // not contain any cleanup code. Based on the earlier analysis, we
1465 // know the the block must end in either an unconditional branch, a
1466 // resume or a conditional branch that is predicated on a comparison
1467 // with a selector. Either the resume or the selector dispatch
1468 // would terminate the search for cleanup code, so the unconditional
1469 // branch is the only case for which we might need to continue
1474 if (!match(BB->getTerminator(), m_UnconditionalBr(SuccBB)))
1481 // Create an entry in the cleanup handler map for this block. Initially
1482 // we create an entry that says this isn't a cleanup block. If we find
1483 // cleanup code, the caller will replace this entry.
1484 CleanupHandlerMap[BB] = nullptr;
1486 TerminatorInst *Terminator = BB->getTerminator();
1488 // Landing pad blocks have extra instructions we need to accept.
1489 LandingPadMap *LPadMap = nullptr;
1490 if (BB->isLandingPad()) {
1491 LandingPadInst *LPad = BB->getLandingPadInst();
1492 LPadMap = &LPadMaps[LPad];
1493 if (!LPadMap->isInitialized())
1494 LPadMap->mapLandingPad(LPad);
1497 // Look for the bare resume pattern:
1498 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1499 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
1500 // resume { i8*, i32 } %lpad.val2
1501 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1502 InsertValueInst *Insert1 = nullptr;
1503 InsertValueInst *Insert2 = nullptr;
1504 Value *ResumeVal = Resume->getOperand(0);
1505 // If there is only one landingpad, we may use the lpad directly with no
1507 if (isa<LandingPadInst>(ResumeVal))
1509 if (!isa<PHINode>(ResumeVal)) {
1510 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1512 return createCleanupHandler(CleanupHandlerMap, BB);
1513 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1515 return createCleanupHandler(CleanupHandlerMap, BB);
1517 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1519 Instruction *Inst = II;
1520 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1522 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1524 if (!Inst->hasOneUse() ||
1525 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1526 return createCleanupHandler(CleanupHandlerMap, BB);
1532 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1533 if (Branch && Branch->isConditional()) {
1534 // Look for the selector dispatch.
1535 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1536 // %matches = icmp eq i32 %sel, %2
1537 // br i1 %matches, label %catch14, label %eh.resume
1538 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1539 if (!Compare || !Compare->isEquality())
1540 return createCleanupHandler(CleanupHandlerMap, BB);
1541 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1544 Instruction *Inst = II;
1545 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1547 if (Inst == Compare || Inst == Branch)
1549 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1551 return createCleanupHandler(CleanupHandlerMap, BB);
1553 // The selector dispatch block should always terminate our search.
1554 assert(BB == EndBB);
1558 // Anything else is either a catch block or interesting cleanup code.
1559 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1562 Instruction *Inst = II;
1563 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1565 // Unconditional branches fall through to this loop.
1568 // If this is a catch block, there is no cleanup code to be found.
1569 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1571 // If this a nested landing pad, it may contain an endcatch call.
1572 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1574 // Anything else makes this interesting cleanup code.
1575 return createCleanupHandler(CleanupHandlerMap, BB);
1578 // Only unconditional branches in empty blocks should get this far.
1579 assert(Branch && Branch->isUnconditional());
1582 BB = Branch->getSuccessor(0);
1587 // This is a public function, declared in WinEHFuncInfo.h and is also
1588 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
1589 void llvm::parseEHActions(const IntrinsicInst *II,
1590 SmallVectorImpl<ActionHandler *> &Actions) {
1591 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
1592 uint64_t ActionKind =
1593 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
1594 if (ActionKind == /*catch=*/1) {
1595 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
1596 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
1597 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
1598 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
1600 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
1601 CH->setHandlerBlockOrFunc(Handler);
1602 CH->setExceptionVarIndex(EHObjIndexVal);
1603 Actions.push_back(CH);
1604 } else if (ActionKind == 0) {
1605 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
1607 auto *CH = new CleanupHandler(/*BB=*/nullptr);
1608 CH->setHandlerBlockOrFunc(Handler);
1609 Actions.push_back(CH);
1611 llvm_unreachable("Expected either a catch or cleanup handler!");
1614 std::reverse(Actions.begin(), Actions.end());