blob: c1067c5d56000f8f7e26ead28ab9838b314ce2f6 [file] [log] [blame]
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass lowers LLVM IR exception handling into something closer to what the
Reid Kleckner83d89fa2015-05-01 22:50:14 +000011// 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.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/ADT/MapVector.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000019#include "llvm/ADT/STLExtras.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000020#include "llvm/ADT/SmallSet.h"
Reid Klecknerfd7df282015-04-22 21:05:21 +000021#include "llvm/ADT/SetVector.h"
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000022#include "llvm/ADT/Triple.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000023#include "llvm/ADT/TinyPtrVector.h"
24#include "llvm/Analysis/LibCallSemantics.h"
David Majnemercde33032015-03-30 22:58:10 +000025#include "llvm/CodeGen/WinEHFuncInfo.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000026#include "llvm/IR/Dominators.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000027#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/PatternMatch.h"
33#include "llvm/Pass.h"
Reid Kleckner83d89fa2015-05-01 22:50:14 +000034#include "llvm/Support/CommandLine.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000035#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000036#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000038#include "llvm/Transforms/Utils/Cloning.h"
39#include "llvm/Transforms/Utils/Local.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000040#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000041#include <memory>
42
43using namespace llvm;
44using namespace llvm::PatternMatch;
45
46#define DEBUG_TYPE "winehprepare"
47
48namespace {
49
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000050// This map is used to model frame variable usage during outlining, to
51// construct a structure type to hold the frame variables in a frame
52// allocation block, and to remap the frame variable allocas (including
53// spill locations as needed) to GEPs that get the variable from the
54// frame allocation structure.
Reid Klecknercfb9ce52015-03-05 18:26:34 +000055typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000056
Reid Kleckner3567d272015-04-02 21:13:31 +000057// TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
58// quite null.
59AllocaInst *getCatchObjectSentinel() {
60 return static_cast<AllocaInst *>(nullptr) + 1;
61}
62
Andrew Kaylor6b67d422015-03-11 23:22:06 +000063typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
64
Andrew Kaylor6b67d422015-03-11 23:22:06 +000065class LandingPadActions;
Andrew Kaylor6b67d422015-03-11 23:22:06 +000066class LandingPadMap;
67
68typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
69typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
70
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000071class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000072public:
73 static char ID; // Pass identification, replacement for typeid.
74 WinEHPrepare(const TargetMachine *TM = nullptr)
Reid Kleckner582786b2015-04-30 18:17:12 +000075 : FunctionPass(ID) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000076 if (TM)
77 TheTriple = Triple(TM->getTargetTriple());
78 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000079
80 bool runOnFunction(Function &Fn) override;
81
82 bool doFinalization(Module &M) override;
83
84 void getAnalysisUsage(AnalysisUsage &AU) const override;
85
86 const char *getPassName() const override {
87 return "Windows exception handling preparation";
88 }
89
90private:
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000091 bool prepareExceptionHandlers(Function &F,
92 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor64622aa2015-04-01 17:21:25 +000093 void promoteLandingPadValues(LandingPadInst *LPad);
Reid Klecknerfd7df282015-04-22 21:05:21 +000094 void demoteValuesLiveAcrossHandlers(Function &F,
95 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor046f7b42015-04-28 21:54:14 +000096 void findSEHEHReturnPoints(Function &F,
97 SetVector<BasicBlock *> &EHReturnBlocks);
98 void findCXXEHReturnPoints(Function &F,
99 SetVector<BasicBlock *> &EHReturnBlocks);
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000100 void completeNestedLandingPad(Function *ParentFn,
101 LandingPadInst *OutlinedLPad,
102 const LandingPadInst *OriginalLPad,
103 FrameVarInfoMap &VarInfo);
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000104 Function *createHandlerFunc(Type *RetTy, const Twine &Name, Module *M,
105 Value *&ParentFP);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000106 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
107 LandingPadInst *LPad, BasicBlock *StartBB,
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000108 FrameVarInfoMap &VarInfo);
Andrew Kaylorbb111322015-04-07 21:30:23 +0000109 void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000110
111 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
112 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
113 VisitedBlockSet &VisitedBlocks);
Reid Kleckner9405ef02015-04-10 23:12:29 +0000114 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
115 BasicBlock *EndBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000116
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000117 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
118
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000119 Triple TheTriple;
120
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000121 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +0000122 DominatorTree *DT = nullptr;
123 EHPersonality Personality = EHPersonality::Unknown;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000124 CatchHandlerMapTy CatchHandlerMap;
125 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000126 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000127
128 // This maps landing pad instructions found in outlined handlers to
129 // the landing pad instruction in the parent function from which they
130 // were cloned. The cloned/nested landing pad is used as the key
131 // because the landing pad may be cloned into multiple handlers.
132 // This map will be used to add the llvm.eh.actions call to the nested
133 // landing pads after all handlers have been outlined.
134 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
135
136 // This maps blocks in the parent function which are destinations of
137 // catch handlers to cloned blocks in (other) outlined handlers. This
138 // handles the case where a nested landing pads has a catch handler that
139 // returns to a handler function rather than the parent function.
140 // The original block is used as the key here because there should only
141 // ever be one handler function from which the cloned block is not pruned.
142 // The original block will be pruned from the parent function after all
143 // handlers have been outlined. This map will be used to adjust the
144 // return instructions of handlers which return to the block that was
145 // outlined into a handler. This is done after all handlers have been
146 // outlined but before the outlined code is pruned from the parent function.
147 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000148
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000149 // Map from outlined handler to call to llvm.frameaddress(1). Only used for
150 // 32-bit EH.
151 DenseMap<Function *, Value *> HandlerToParentFP;
152
Reid Kleckner582786b2015-04-30 18:17:12 +0000153 AllocaInst *SEHExceptionCodeSlot = nullptr;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000154};
155
156class WinEHFrameVariableMaterializer : public ValueMaterializer {
157public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000158 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000159 FrameVarInfoMap &FrameVarInfo);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000160 ~WinEHFrameVariableMaterializer() override {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000161
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000162 Value *materializeValueFor(Value *V) override;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000163
Reid Kleckner3567d272015-04-02 21:13:31 +0000164 void escapeCatchObject(Value *V);
165
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000166private:
167 FrameVarInfoMap &FrameVarInfo;
168 IRBuilder<> Builder;
169};
170
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000171class LandingPadMap {
172public:
173 LandingPadMap() : OriginLPad(nullptr) {}
174 void mapLandingPad(const LandingPadInst *LPad);
175
176 bool isInitialized() { return OriginLPad != nullptr; }
177
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000178 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000179 bool isLandingPadSpecificInst(const Instruction *Inst) const;
180
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000181 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
182 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000183
184private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000185 const LandingPadInst *OriginLPad;
186 // We will normally only see one of each of these instructions, but
187 // if more than one occurs for some reason we can handle that.
188 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
189 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000190};
191
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000192class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000193public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000194 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
195 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
196 : Materializer(HandlerFn, ParentFP, VarInfo),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000197 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
198 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000199 LPadMap(LPadMap), ParentFP(ParentFP) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000200
201 CloningAction handleInstruction(ValueToValueMapTy &VMap,
202 const Instruction *Inst,
203 BasicBlock *NewBB) override;
204
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000205 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
206 const Instruction *Inst,
207 BasicBlock *NewBB) = 0;
208 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
209 const Instruction *Inst,
210 BasicBlock *NewBB) = 0;
211 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
212 const Instruction *Inst,
213 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000214 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
215 const InvokeInst *Invoke,
216 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000217 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
218 const ResumeInst *Resume,
219 BasicBlock *NewBB) = 0;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000220 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
221 const CmpInst *Compare,
222 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000223 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
224 const LandingPadInst *LPad,
225 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000226
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000227 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
228
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000229protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000230 WinEHFrameVariableMaterializer Materializer;
231 Type *SelectorIDType;
232 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000233 LandingPadMap &LPadMap;
Reid Klecknerf14787d2015-04-22 00:07:52 +0000234
235 /// The value representing the parent frame pointer.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000236 Value *ParentFP;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000237};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000238
239class WinEHCatchDirector : public WinEHCloningDirectorBase {
240public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000241 WinEHCatchDirector(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000242 Function *CatchFn, Value *ParentFP, Value *Selector,
243 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000244 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000245 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000246 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000247 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000248
249 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
250 const Instruction *Inst,
251 BasicBlock *NewBB) override;
252 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
253 BasicBlock *NewBB) override;
254 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
255 const Instruction *Inst,
256 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000257 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
258 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000259 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
260 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000261 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
262 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000263 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
264 const LandingPadInst *LPad,
265 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000266
Reid Kleckner3567d272015-04-02 21:13:31 +0000267 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000268 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
269
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000270private:
271 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000272
Reid Kleckner3567d272015-04-02 21:13:31 +0000273 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000274 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000275
276 // This will be a reference to the field of the same name in the WinEHPrepare
277 // object which instantiates this WinEHCatchDirector object.
278 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000279};
280
281class WinEHCleanupDirector : public WinEHCloningDirectorBase {
282public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000283 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
284 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
285 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
286 LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000287
288 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
289 const Instruction *Inst,
290 BasicBlock *NewBB) override;
291 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
292 BasicBlock *NewBB) override;
293 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
294 const Instruction *Inst,
295 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000296 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
297 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000298 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
299 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000300 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
301 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000302 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
303 const LandingPadInst *LPad,
304 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000305};
306
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000307class LandingPadActions {
308public:
309 LandingPadActions() : HasCleanupHandlers(false) {}
310
311 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
312 void insertCleanupHandler(CleanupHandler *Action) {
313 Actions.push_back(Action);
314 HasCleanupHandlers = true;
315 }
316
317 bool includesCleanup() const { return HasCleanupHandlers; }
318
David Majnemercde33032015-03-30 22:58:10 +0000319 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000320 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
321 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
322
323private:
324 // Note that this class does not own the ActionHandler objects in this vector.
325 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
326 // in the WinEHPrepare class.
327 SmallVector<ActionHandler *, 4> Actions;
328 bool HasCleanupHandlers;
329};
330
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000331} // end anonymous namespace
332
333char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000334INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
335 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000336
337FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
338 return new WinEHPrepare(TM);
339}
340
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000341bool WinEHPrepare::runOnFunction(Function &Fn) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000342 // No need to prepare outlined handlers.
343 if (Fn.hasFnAttribute("wineh-parent"))
344 return false;
345
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000346 SmallVector<LandingPadInst *, 4> LPads;
347 SmallVector<ResumeInst *, 4> Resumes;
348 for (BasicBlock &BB : Fn) {
349 if (auto *LP = BB.getLandingPadInst())
350 LPads.push_back(LP);
351 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
352 Resumes.push_back(Resume);
353 }
354
355 // No need to prepare functions that lack landing pads.
356 if (LPads.empty())
357 return false;
358
359 // Classify the personality to see what kind of preparation we need.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000360 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000361
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000362 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000363 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000364 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000365
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000366 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
367
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000368 // If there were any landing pads, prepareExceptionHandlers will make changes.
369 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000370 return true;
371}
372
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000373bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000374
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000375void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
376 AU.addRequired<DominatorTreeWrapperPass>();
377}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000378
Reid Klecknerfd7df282015-04-22 21:05:21 +0000379static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
380 Constant *&Selector, BasicBlock *&NextBB);
381
382// Finds blocks reachable from the starting set Worklist. Does not follow unwind
383// edges or blocks listed in StopPoints.
384static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
385 SetVector<BasicBlock *> &Worklist,
386 const SetVector<BasicBlock *> *StopPoints) {
387 while (!Worklist.empty()) {
388 BasicBlock *BB = Worklist.pop_back_val();
389
390 // Don't cross blocks that we should stop at.
391 if (StopPoints && StopPoints->count(BB))
392 continue;
393
394 if (!ReachableBBs.insert(BB).second)
395 continue; // Already visited.
396
397 // Don't follow unwind edges of invokes.
398 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
399 Worklist.insert(II->getNormalDest());
400 continue;
401 }
402
403 // Otherwise, follow all successors.
404 Worklist.insert(succ_begin(BB), succ_end(BB));
405 }
406}
407
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000408// Attempt to find an instruction where a block can be split before
409// a call to llvm.eh.begincatch and its operands. If the block
410// begins with the begincatch call or one of its adjacent operands
411// the block will not be split.
412static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
413 IntrinsicInst *II) {
414 // If the begincatch call is already the first instruction in the block,
415 // don't split.
416 Instruction *FirstNonPHI = BB->getFirstNonPHI();
417 if (II == FirstNonPHI)
418 return nullptr;
419
420 // If either operand is in the same basic block as the instruction and
421 // isn't used by another instruction before the begincatch call, include it
422 // in the split block.
423 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
424 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
425
426 Instruction *I = II->getPrevNode();
427 Instruction *LastI = II;
428
429 while (I == Op0 || I == Op1) {
430 // If the block begins with one of the operands and there are no other
431 // instructions between the operand and the begincatch call, don't split.
432 if (I == FirstNonPHI)
433 return nullptr;
434
435 LastI = I;
436 I = I->getPrevNode();
437 }
438
439 // If there is at least one instruction in the block before the begincatch
440 // call and its operands, split the block at either the begincatch or
441 // its operand.
442 return LastI;
443}
444
Reid Klecknerfd7df282015-04-22 21:05:21 +0000445/// Find all points where exceptional control rejoins normal control flow via
446/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000447void WinEHPrepare::findCXXEHReturnPoints(
448 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000449 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
450 BasicBlock *BB = BBI;
451 for (Instruction &I : *BB) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000452 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
Andrew Kaylor91307432015-04-28 22:01:51 +0000453 Instruction *SplitPt =
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000454 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
455 if (SplitPt) {
456 // Split the block before the llvm.eh.begincatch call to allow
457 // cleanup and catch code to be distinguished later.
458 // Do not update BBI because we still need to process the
459 // portion of the block that we are splitting off.
Andrew Kaylora33f1592015-04-29 17:21:26 +0000460 SplitBlock(BB, SplitPt, DT);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000461 break;
462 }
463 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000464 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
465 // Split the block after the call to llvm.eh.endcatch if there is
466 // anything other than an unconditional branch, or if the successor
467 // starts with a phi.
468 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
469 if (!Br || !Br->isUnconditional() ||
470 isa<PHINode>(Br->getSuccessor(0)->begin())) {
471 DEBUG(dbgs() << "splitting block " << BB->getName()
472 << " with llvm.eh.endcatch\n");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000473 BBI = SplitBlock(BB, I.getNextNode(), DT);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000474 }
475 // The next BB is normal control flow.
476 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
477 break;
478 }
479 }
480 }
481}
482
483static bool isCatchAllLandingPad(const BasicBlock *BB) {
484 const LandingPadInst *LP = BB->getLandingPadInst();
485 if (!LP)
486 return false;
487 unsigned N = LP->getNumClauses();
488 return (N > 0 && LP->isCatch(N - 1) &&
489 isa<ConstantPointerNull>(LP->getClause(N - 1)));
490}
491
492/// Find all points where exceptions control rejoins normal control flow via
493/// selector dispatch.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000494void WinEHPrepare::findSEHEHReturnPoints(
495 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000496 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
497 BasicBlock *BB = BBI;
498 // If the landingpad is a catch-all, treat the whole lpad as if it is
499 // reachable from normal control flow.
500 // FIXME: This is imprecise. We need a better way of identifying where a
501 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
502 // is no difference.
503 if (isCatchAllLandingPad(BB)) {
504 EHReturnBlocks.insert(BB);
505 continue;
506 }
507
508 BasicBlock *CatchHandler;
509 BasicBlock *NextBB;
510 Constant *Selector;
511 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
512 // Split the edge if there is a phi node. Returning from EH to a phi node
513 // is just as impossible as having a phi after an indirectbr.
514 if (isa<PHINode>(CatchHandler->begin())) {
515 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
516 << " to " << CatchHandler->getName() << '\n');
517 BBI = CatchHandler = SplitCriticalEdge(
518 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
519 }
520 EHReturnBlocks.insert(CatchHandler);
521 }
522 }
523}
524
525/// Ensure that all values live into and out of exception handlers are stored
526/// in memory.
527/// FIXME: This falls down when values are defined in one handler and live into
528/// another handler. For example, a cleanup defines a value used only by a
529/// catch handler.
530void WinEHPrepare::demoteValuesLiveAcrossHandlers(
531 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
532 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
533 << F.getName() << '\n');
534
535 // Build a set of all non-exceptional blocks and exceptional blocks.
536 // - Non-exceptional blocks are blocks reachable from the entry block while
537 // not following invoke unwind edges.
538 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
539 // not follow llvm.eh.endcatch blocks, which mark a transition from
540 // exceptional to normal control.
541 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
542 SmallPtrSet<BasicBlock *, 4> EHBlocks;
543 SetVector<BasicBlock *> EHReturnBlocks;
544 SetVector<BasicBlock *> Worklist;
545
546 if (Personality == EHPersonality::MSVC_CXX)
547 findCXXEHReturnPoints(F, EHReturnBlocks);
548 else
549 findSEHEHReturnPoints(F, EHReturnBlocks);
550
551 DEBUG({
552 dbgs() << "identified the following blocks as EH return points:\n";
553 for (BasicBlock *BB : EHReturnBlocks)
554 dbgs() << " " << BB->getName() << '\n';
555 });
556
Andrew Kaylor91307432015-04-28 22:01:51 +0000557// Join points should not have phis at this point, unless they are a
558// landingpad, in which case we will demote their phis later.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000559#ifndef NDEBUG
560 for (BasicBlock *BB : EHReturnBlocks)
561 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
562 "non-lpad EH return block has phi");
563#endif
564
565 // Normal blocks are the blocks reachable from the entry block and all EH
566 // return points.
567 Worklist = EHReturnBlocks;
568 Worklist.insert(&F.getEntryBlock());
569 findReachableBlocks(NormalBlocks, Worklist, nullptr);
570 DEBUG({
571 dbgs() << "marked the following blocks as normal:\n";
572 for (BasicBlock *BB : NormalBlocks)
573 dbgs() << " " << BB->getName() << '\n';
574 });
575
576 // Exceptional blocks are the blocks reachable from landingpads that don't
577 // cross EH return points.
578 Worklist.clear();
579 for (auto *LPI : LPads)
580 Worklist.insert(LPI->getParent());
581 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
582 DEBUG({
583 dbgs() << "marked the following blocks as exceptional:\n";
584 for (BasicBlock *BB : EHBlocks)
585 dbgs() << " " << BB->getName() << '\n';
586 });
587
588 SetVector<Argument *> ArgsToDemote;
589 SetVector<Instruction *> InstrsToDemote;
590 for (BasicBlock &BB : F) {
591 bool IsNormalBB = NormalBlocks.count(&BB);
592 bool IsEHBB = EHBlocks.count(&BB);
593 if (!IsNormalBB && !IsEHBB)
594 continue; // Blocks that are neither normal nor EH are unreachable.
595 for (Instruction &I : BB) {
596 for (Value *Op : I.operands()) {
597 // Don't demote static allocas, constants, and labels.
598 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
599 continue;
600 auto *AI = dyn_cast<AllocaInst>(Op);
601 if (AI && AI->isStaticAlloca())
602 continue;
603
604 if (auto *Arg = dyn_cast<Argument>(Op)) {
605 if (IsEHBB) {
606 DEBUG(dbgs() << "Demoting argument " << *Arg
607 << " used by EH instr: " << I << "\n");
608 ArgsToDemote.insert(Arg);
609 }
610 continue;
611 }
612
613 auto *OpI = cast<Instruction>(Op);
614 BasicBlock *OpBB = OpI->getParent();
615 // If a value is produced and consumed in the same BB, we don't need to
616 // demote it.
617 if (OpBB == &BB)
618 continue;
619 bool IsOpNormalBB = NormalBlocks.count(OpBB);
620 bool IsOpEHBB = EHBlocks.count(OpBB);
621 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
622 DEBUG({
623 dbgs() << "Demoting instruction live in-out from EH:\n";
624 dbgs() << "Instr: " << *OpI << '\n';
625 dbgs() << "User: " << I << '\n';
626 });
627 InstrsToDemote.insert(OpI);
628 }
629 }
630 }
631 }
632
633 // Demote values live into and out of handlers.
634 // FIXME: This demotion is inefficient. We should insert spills at the point
635 // of definition, insert one reload in each handler that uses the value, and
636 // insert reloads in the BB used to rejoin normal control flow.
637 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
638 for (Instruction *I : InstrsToDemote)
639 DemoteRegToStack(*I, false, AllocaInsertPt);
640
641 // Demote arguments separately, and only for uses in EH blocks.
642 for (Argument *Arg : ArgsToDemote) {
643 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
644 Arg->getName() + ".reg2mem", AllocaInsertPt);
645 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
646 for (User *U : Users) {
647 auto *I = dyn_cast<Instruction>(U);
648 if (I && EHBlocks.count(I->getParent())) {
649 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
650 U->replaceUsesOfWith(Arg, Reload);
651 }
652 }
653 new StoreInst(Arg, Slot, AllocaInsertPt);
654 }
655
656 // Demote landingpad phis, as the landingpad will be removed from the machine
657 // CFG.
658 for (LandingPadInst *LPI : LPads) {
659 BasicBlock *BB = LPI->getParent();
660 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
661 DemotePHIToStack(Phi, AllocaInsertPt);
662 }
663
664 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
665 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
666}
667
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000668bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000669 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000670 // Don't run on functions that are already prepared.
671 for (LandingPadInst *LPad : LPads) {
672 BasicBlock *LPadBB = LPad->getParent();
673 for (Instruction &Inst : *LPadBB)
674 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
675 return false;
676 }
677
678 demoteValuesLiveAcrossHandlers(F, LPads);
679
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000680 // These containers are used to re-map frame variables that are used in
681 // outlined catch and cleanup handlers. They will be populated as the
682 // handlers are outlined.
683 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000684
685 bool HandlersOutlined = false;
686
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000687 Module *M = F.getParent();
688 LLVMContext &Context = M->getContext();
689
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000690 // Create a new function to receive the handler contents.
691 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
692 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000693 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000694
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000695 if (isAsynchronousEHPersonality(Personality)) {
696 // FIXME: Switch the ehptr type to i32 and then switch this.
697 SEHExceptionCodeSlot =
698 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
699 F.getEntryBlock().getFirstInsertionPt());
700 }
701
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000702 for (LandingPadInst *LPad : LPads) {
703 // Look for evidence that this landingpad has already been processed.
704 bool LPadHasActionList = false;
705 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000706 for (Instruction &Inst : *LPadBB) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000707 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
708 LPadHasActionList = true;
709 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000710 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000711 }
712
713 // If we've already outlined the handlers for this landingpad,
714 // there's nothing more to do here.
715 if (LPadHasActionList)
716 continue;
717
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000718 // If either of the values in the aggregate returned by the landing pad is
719 // extracted and stored to memory, promote the stored value to a register.
720 promoteLandingPadValues(LPad);
721
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000722 LandingPadActions Actions;
723 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000724
Reid Kleckner9405ef02015-04-10 23:12:29 +0000725 HandlersOutlined |= !Actions.actions().empty();
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000726 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000727 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000728 continue;
729 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000730
731 // SEH doesn't do any outlining for catches. Instead, pass the handler
732 // basic block addr to llvm.eh.actions and list the block as a return
733 // target.
734 if (isAsynchronousEHPersonality(Personality)) {
735 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
736 processSEHCatchHandler(CatchAction, StartBB);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000737 continue;
738 }
739 }
740
Reid Kleckner9405ef02015-04-10 23:12:29 +0000741 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
742 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000743
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000744 // Split the block after the landingpad instruction so that it is just a
745 // call to llvm.eh.actions followed by indirectbr.
746 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000747 SplitBlock(LPadBB, LPad->getNextNode(), DT);
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000748 // Erase the branch inserted by the split so we can insert indirectbr.
749 LPadBB->getTerminator()->eraseFromParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000750
Reid Klecknere3af86e2015-04-23 21:22:30 +0000751 // Replace all extracted values with undef and ultimately replace the
752 // landingpad with undef.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000753 SmallVector<Instruction *, 4> SEHCodeUses;
754 SmallVector<Instruction *, 4> EHUndefs;
Reid Klecknere3af86e2015-04-23 21:22:30 +0000755 for (User *U : LPad->users()) {
756 auto *E = dyn_cast<ExtractValueInst>(U);
757 if (!E)
758 continue;
759 assert(E->getNumIndices() == 1 &&
760 "Unexpected operation: extracting both landing pad values");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000761 unsigned Idx = *E->idx_begin();
762 assert((Idx == 0 || Idx == 1) && "unexpected index");
763 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
764 SEHCodeUses.push_back(E);
765 else
766 EHUndefs.push_back(E);
Reid Klecknere3af86e2015-04-23 21:22:30 +0000767 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000768 for (Instruction *E : EHUndefs) {
Reid Klecknere3af86e2015-04-23 21:22:30 +0000769 E->replaceAllUsesWith(UndefValue::get(E->getType()));
770 E->eraseFromParent();
771 }
772 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000773
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000774 // Rewrite uses of the exception pointer to loads of an alloca.
775 for (Instruction *E : SEHCodeUses) {
776 SmallVector<Use *, 4> Uses;
777 for (Use &U : E->uses())
778 Uses.push_back(&U);
779 for (Use *U : Uses) {
780 auto *I = cast<Instruction>(U->getUser());
781 if (isa<ResumeInst>(I))
782 continue;
783 LoadInst *LI;
784 if (auto *Phi = dyn_cast<PHINode>(I))
785 LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false,
786 Phi->getIncomingBlock(*U));
787 else
788 LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I);
789 U->set(LI);
790 }
791 E->replaceAllUsesWith(UndefValue::get(E->getType()));
792 E->eraseFromParent();
793 }
794
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000795 // Add a call to describe the actions for this landing pad.
796 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000797 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000798 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000799 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000800 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000801 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000802 // Find the frame escape index of the exception object alloca in the
803 // parent.
804 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000805 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000806 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
807 auto I = FrameVarInfo.find(EHObj);
808 assert(I != FrameVarInfo.end() &&
809 "failed to map llvm.eh.begincatch var");
810 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
811 }
812 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000813 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000814 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000815 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000816 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000817 }
818 CallInst *Recover =
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000819 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000820
821 // Add an indirect branch listing possible successors of the catch handlers.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000822 SetVector<BasicBlock *> ReturnTargets;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000823 for (ActionHandler *Action : Actions) {
824 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000825 const auto &CatchTargets = CatchAction->getReturnTargets();
826 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000827 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000828 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000829 IndirectBrInst *Branch =
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000830 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000831 for (BasicBlock *Target : ReturnTargets)
832 Branch->addDestination(Target);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000833 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000834
835 // If nothing got outlined, there is no more processing to be done.
836 if (!HandlersOutlined)
837 return false;
838
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000839 // Replace any nested landing pad stubs with the correct action handler.
840 // This must be done before we remove unreachable blocks because it
841 // cleans up references to outlined blocks that will be deleted.
842 for (auto &LPadPair : NestedLPtoOriginalLP)
843 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
Andrew Kaylor67d3c032015-04-08 20:57:22 +0000844 NestedLPtoOriginalLP.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000845
David Majnemercde33032015-03-30 22:58:10 +0000846 F.addFnAttr("wineh-parent", F.getName());
847
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000848 // Delete any blocks that were only used by handlers that were outlined above.
849 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000850
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000851 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000852 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000853 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000854
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000855 Function *FrameEscapeFn =
856 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
857 Function *RecoverFrameFn =
858 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
Reid Klecknerf14787d2015-04-22 00:07:52 +0000859 SmallVector<Value *, 8> AllocasToEscape;
860
861 // Scan the entry block for an existing call to llvm.frameescape. We need to
862 // keep escaping those objects.
863 for (Instruction &I : F.front()) {
864 auto *II = dyn_cast<IntrinsicInst>(&I);
865 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
866 auto Args = II->arg_operands();
867 AllocasToEscape.append(Args.begin(), Args.end());
868 II->eraseFromParent();
869 break;
870 }
871 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000872
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000873 // Finally, replace all of the temporary allocas for frame variables used in
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000874 // the outlined handlers with calls to llvm.framerecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000875 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +0000876 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000877 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Reid Klecknerfd7df282015-04-22 21:05:21 +0000878 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
Andrew Kaylor72029c62015-03-03 00:41:03 +0000879
Reid Klecknerb4019412015-04-06 18:50:38 +0000880 // FIXME: We should try to sink unescaped allocas from the parent frame into
881 // the child frame. If the alloca is escaped, we have to use the lifetime
882 // markers to ensure that the alloca is only live within the child frame.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000883
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000884 // Add this alloca to the list of things to escape.
885 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000886
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000887 // Next replace all outlined allocas that are mapped to it.
888 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +0000889 if (TempAlloca == getCatchObjectSentinel())
890 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000891 Function *HandlerFn = TempAlloca->getParent()->getParent();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000892 llvm::Value *FP = HandlerToParentFP[HandlerFn];
893 assert(FP);
894
895 // FIXME: Sink this framerecover into the blocks where it is used.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000896 Builder.SetInsertPoint(TempAlloca);
897 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
898 Value *RecoverArgs[] = {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000899 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000900 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000901 Instruction *RecoveredAlloca =
902 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
903
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000904 // Add a pointer bitcast if the alloca wasn't an i8.
905 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
906 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000907 RecoveredAlloca = cast<Instruction>(
908 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000909 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000910 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
911 TempAlloca->removeFromParent();
912 RecoveredAlloca->takeName(TempAlloca);
913 delete TempAlloca;
914 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000915 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000916
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000917 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
918 // block.
919 Builder.SetInsertPoint(&F.getEntryBlock().back());
920 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
921
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000922 if (SEHExceptionCodeSlot) {
923 if (SEHExceptionCodeSlot->hasNUses(0))
924 SEHExceptionCodeSlot->eraseFromParent();
Reid Kleckner83d89fa2015-05-01 22:50:14 +0000925 else
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000926 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
927 }
928
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000929 // Clean up the handler action maps we created for this function
930 DeleteContainerSeconds(CatchHandlerMap);
931 CatchHandlerMap.clear();
932 DeleteContainerSeconds(CleanupHandlerMap);
933 CleanupHandlerMap.clear();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000934 HandlerToParentFP.clear();
935 DT = nullptr;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000936
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000937 return HandlersOutlined;
938}
939
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000940void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
941 // If the return values of the landing pad instruction are extracted and
942 // stored to memory, we want to promote the store locations to reg values.
943 SmallVector<AllocaInst *, 2> EHAllocas;
944
945 // The landingpad instruction returns an aggregate value. Typically, its
946 // value will be passed to a pair of extract value instructions and the
947 // results of those extracts are often passed to store instructions.
948 // In unoptimized code the stored value will often be loaded and then stored
949 // again.
950 for (auto *U : LPad->users()) {
951 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
952 if (!Extract)
953 continue;
954
955 for (auto *EU : Extract->users()) {
956 if (auto *Store = dyn_cast<StoreInst>(EU)) {
957 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
958 EHAllocas.push_back(AV);
959 }
960 }
961 }
962
963 // We can't do this without a dominator tree.
964 assert(DT);
965
966 if (!EHAllocas.empty()) {
967 PromoteMemToReg(EHAllocas, *DT);
968 EHAllocas.clear();
969 }
Reid Kleckner86762142015-04-16 00:02:04 +0000970
971 // After promotion, some extracts may be trivially dead. Remove them.
972 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
973 for (auto *U : Users)
974 RecursivelyDeleteTriviallyDeadInstructions(U);
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000975}
976
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000977void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
978 LandingPadInst *OutlinedLPad,
979 const LandingPadInst *OriginalLPad,
980 FrameVarInfoMap &FrameVarInfo) {
981 // Get the nested block and erase the unreachable instruction that was
982 // temporarily inserted as its terminator.
983 LLVMContext &Context = ParentFn->getContext();
984 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
985 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
986 OutlinedBB->getTerminator()->eraseFromParent();
987 // That should leave OutlinedLPad as the last instruction in its block.
988 assert(&OutlinedBB->back() == OutlinedLPad);
989
990 // The original landing pad will have already had its action intrinsic
991 // built by the outlining loop. We need to clone that into the outlined
992 // location. It may also be necessary to add references to the exception
993 // variables to the outlined handler in which this landing pad is nested
994 // and remap return instructions in the nested handlers that should return
995 // to an address in the outlined handler.
996 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000997 BasicBlock::const_iterator II = OriginalLPad;
998 ++II;
999 // The instruction after the landing pad should now be a call to eh.actions.
1000 const Instruction *Recover = II;
1001 assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
1002 IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
1003
1004 // Remap the exception variables into the outlined function.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001005 SmallVector<BlockAddress *, 4> ActionTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001006 SmallVector<ActionHandler *, 4> ActionList;
1007 parseEHActions(EHActions, ActionList);
1008 for (auto *Action : ActionList) {
1009 auto *Catch = dyn_cast<CatchHandler>(Action);
1010 if (!Catch)
1011 continue;
1012 // The dyn_cast to function here selects C++ catch handlers and skips
1013 // SEH catch handlers.
1014 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1015 if (!Handler)
1016 continue;
1017 // Visit all the return instructions, looking for places that return
1018 // to a location within OutlinedHandlerFn.
1019 for (BasicBlock &NestedHandlerBB : *Handler) {
1020 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1021 if (!Ret)
1022 continue;
1023
1024 // Handler functions must always return a block address.
1025 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1026 // The original target will have been in the main parent function,
1027 // but if it is the address of a block that has been outlined, it
1028 // should be a block that was outlined into OutlinedHandlerFn.
1029 assert(BA->getFunction() == ParentFn);
1030
1031 // Ignore targets that aren't part of OutlinedHandlerFn.
1032 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1033 continue;
1034
1035 // If the return value is the address ofF a block that we
1036 // previously outlined into the parent handler function, replace
1037 // the return instruction and add the mapped target to the list
1038 // of possible return addresses.
1039 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1040 assert(MappedBB->getParent() == OutlinedHandlerFn);
1041 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1042 Ret->eraseFromParent();
1043 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1044 ActionTargets.push_back(NewBA);
1045 }
1046 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +00001047 DeleteContainerPointers(ActionList);
1048 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001049 OutlinedBB->getInstList().push_back(EHActions);
1050
1051 // Insert an indirect branch into the outlined landing pad BB.
1052 IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
1053 // Add the previously collected action targets.
1054 for (auto *Target : ActionTargets)
1055 IBr->addDestination(Target->getBasicBlock());
1056}
1057
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001058// This function examines a block to determine whether the block ends with a
1059// conditional branch to a catch handler based on a selector comparison.
1060// This function is used both by the WinEHPrepare::findSelectorComparison() and
1061// WinEHCleanupDirector::handleTypeIdFor().
1062static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1063 Constant *&Selector, BasicBlock *&NextBB) {
1064 ICmpInst::Predicate Pred;
1065 BasicBlock *TBB, *FBB;
1066 Value *LHS, *RHS;
1067
1068 if (!match(BB->getTerminator(),
1069 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1070 return false;
1071
1072 if (!match(LHS,
1073 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1074 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1075 return false;
1076
1077 if (Pred == CmpInst::ICMP_EQ) {
1078 CatchHandler = TBB;
1079 NextBB = FBB;
1080 return true;
1081 }
1082
1083 if (Pred == CmpInst::ICMP_NE) {
1084 CatchHandler = FBB;
1085 NextBB = TBB;
1086 return true;
1087 }
1088
1089 return false;
1090}
1091
Andrew Kaylor41758512015-04-20 22:04:09 +00001092static bool isCatchBlock(BasicBlock *BB) {
1093 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1094 II != IE; ++II) {
1095 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1096 return true;
1097 }
1098 return false;
1099}
1100
Andrew Kaylorbb111322015-04-07 21:30:23 +00001101static BasicBlock *createStubLandingPad(Function *Handler,
1102 Value *PersonalityFn) {
1103 // FIXME: Finish this!
1104 LLVMContext &Context = Handler->getContext();
1105 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1106 Handler->getBasicBlockList().push_back(StubBB);
1107 IRBuilder<> Builder(StubBB);
1108 LandingPadInst *LPad = Builder.CreateLandingPad(
1109 llvm::StructType::get(Type::getInt8PtrTy(Context),
1110 Type::getInt32Ty(Context), nullptr),
1111 PersonalityFn, 0);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001112 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
Andrew Kaylor91307432015-04-28 22:01:51 +00001113 Function *ActionIntrin =
1114 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001115 Builder.CreateCall(ActionIntrin, "recover");
Andrew Kaylorbb111322015-04-07 21:30:23 +00001116 LPad->setCleanup(true);
1117 Builder.CreateUnreachable();
1118 return StubBB;
1119}
1120
1121// Cycles through the blocks in an outlined handler function looking for an
1122// invoke instruction and inserts an invoke of llvm.donothing with an empty
1123// landing pad if none is found. The code that generates the .xdata tables for
1124// the handler needs at least one landing pad to identify the parent function's
1125// personality.
1126void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
1127 Value *PersonalityFn) {
1128 ReturnInst *Ret = nullptr;
Andrew Kaylor5f715522015-04-23 18:37:39 +00001129 UnreachableInst *Unreached = nullptr;
Andrew Kaylorbb111322015-04-07 21:30:23 +00001130 for (BasicBlock &BB : *Handler) {
1131 TerminatorInst *Terminator = BB.getTerminator();
1132 // If we find an invoke, there is nothing to be done.
1133 auto *II = dyn_cast<InvokeInst>(Terminator);
1134 if (II)
1135 return;
1136 // If we've already recorded a return instruction, keep looking for invokes.
Andrew Kaylor5f715522015-04-23 18:37:39 +00001137 if (!Ret)
1138 Ret = dyn_cast<ReturnInst>(Terminator);
1139 // If we haven't recorded an unreachable instruction, try this terminator.
1140 if (!Unreached)
1141 Unreached = dyn_cast<UnreachableInst>(Terminator);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001142 }
1143
1144 // If we got this far, the handler contains no invokes. We should have seen
Andrew Kaylor5f715522015-04-23 18:37:39 +00001145 // at least one return or unreachable instruction. We'll insert an invoke of
1146 // llvm.donothing ahead of that instruction.
1147 assert(Ret || Unreached);
1148 TerminatorInst *Term;
1149 if (Ret)
1150 Term = Ret;
1151 else
1152 Term = Unreached;
1153 BasicBlock *OldRetBB = Term->getParent();
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001154 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001155 // SplitBlock adds an unconditional branch instruction at the end of the
1156 // parent block. We want to replace that with an invoke call, so we can
1157 // erase it now.
1158 OldRetBB->getTerminator()->eraseFromParent();
1159 BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
1160 Function *F =
1161 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1162 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1163}
1164
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001165// FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1166// usually doesn't build LLVM IR, so that's probably the wrong place.
1167Function *WinEHPrepare::createHandlerFunc(Type *RetTy, const Twine &Name,
1168 Module *M, Value *&ParentFP) {
1169 // x64 uses a two-argument prototype where the parent FP is the second
1170 // argument. x86 uses no arguments, just the incoming EBP value.
1171 LLVMContext &Context = M->getContext();
1172 FunctionType *FnType;
1173 if (TheTriple.getArch() == Triple::x86_64) {
1174 Type *Int8PtrType = Type::getInt8PtrTy(Context);
1175 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1176 FnType = FunctionType::get(RetTy, ArgTys, false);
1177 } else {
1178 FnType = FunctionType::get(RetTy, None, false);
1179 }
1180
1181 Function *Handler =
1182 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1183 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1184 Handler->getBasicBlockList().push_front(Entry);
1185 if (TheTriple.getArch() == Triple::x86_64) {
1186 ParentFP = &(Handler->getArgumentList().back());
1187 } else {
1188 assert(M);
1189 Function *FrameAddressFn =
1190 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
1191 Value *Args[1] = {ConstantInt::get(Type::getInt32Ty(Context), 1)};
1192 ParentFP = CallInst::Create(FrameAddressFn, Args, "parent_fp",
1193 &Handler->getEntryBlock());
1194 }
1195 return Handler;
1196}
1197
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001198bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1199 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001200 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001201 Module *M = SrcFn->getParent();
1202 LLVMContext &Context = M->getContext();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001203 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001204
1205 // Create a new function to receive the handler contents.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001206 Value *ParentFP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001207 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001208 if (Action->getType() == Catch) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001209 Handler = createHandlerFunc(Int8PtrType, SrcFn->getName() + ".catch", M,
1210 ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001211 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001212 Handler = createHandlerFunc(Type::getVoidTy(Context),
1213 SrcFn->getName() + ".cleanup", M, ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001214 }
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001215 HandlerToParentFP[Handler] = ParentFP;
David Majnemercde33032015-03-30 22:58:10 +00001216 Handler->addFnAttr("wineh-parent", SrcFn->getName());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001217 BasicBlock *Entry = &Handler->getEntryBlock();
David Majnemercde33032015-03-30 22:58:10 +00001218
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001219 // Generate a standard prolog to setup the frame recovery structure.
1220 IRBuilder<> Builder(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001221 Builder.SetInsertPoint(Entry);
1222 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1223
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001224 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001225
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001226 ValueToValueMapTy VMap;
1227
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001228 LandingPadMap &LPadMap = LPadMaps[LPad];
1229 if (!LPadMap.isInitialized())
1230 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001231 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1232 Constant *Sel = CatchAction->getSelector();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001233 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel,
1234 VarInfo, LPadMap,
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001235 NestedLPtoOriginalLP));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001236 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1237 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001238 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001239 Director.reset(
1240 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001241 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1242 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001243 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001244
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001245 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001246 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001247
Andrew Kaylor3170e562015-03-20 21:42:54 +00001248 // If the start block contains PHI nodes, we need to map them.
1249 BasicBlock::iterator II = StartBB->begin();
1250 while (auto *PN = dyn_cast<PHINode>(II)) {
1251 bool Mapped = false;
1252 // Look for PHI values that we have already mapped (such as the selector).
1253 for (Value *Val : PN->incoming_values()) {
1254 if (VMap.count(Val)) {
1255 VMap[PN] = VMap[Val];
1256 Mapped = true;
1257 }
1258 }
1259 // If we didn't find a match for this value, map it as an undef.
1260 if (!Mapped) {
1261 VMap[PN] = UndefValue::get(PN->getType());
1262 }
1263 ++II;
1264 }
1265
Andrew Kaylor00e5d9e2015-04-20 22:53:42 +00001266 // The landing pad value may be used by PHI nodes. It will ultimately be
1267 // eliminated, but we need it in the map for intermediate handling.
1268 VMap[LPad] = UndefValue::get(LPad->getType());
1269
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001270 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +00001271 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001272
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001273 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001274 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001275 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001276
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001277 // Move all the instructions in the cloned "entry" block into our entry block.
1278 // Depending on how the parent function was laid out, the block that will
1279 // correspond to the outlined entry block may not be the first block in the
1280 // list. We can recognize it, however, as the cloned block which has no
1281 // predecessors. Any other block wouldn't have been cloned if it didn't
1282 // have a predecessor which was also cloned.
Andrew Kaylor91307432015-04-28 22:01:51 +00001283 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001284 while (!pred_empty(ClonedIt))
1285 ++ClonedIt;
1286 BasicBlock *ClonedEntryBB = ClonedIt;
1287 assert(ClonedEntryBB);
1288 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1289 ClonedEntryBB->eraseFromParent();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001290
Andrew Kaylorbb111322015-04-07 21:30:23 +00001291 // Make sure we can identify the handler's personality later.
1292 addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
1293
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001294 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1295 WinEHCatchDirector *CatchDirector =
1296 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1297 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1298 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001299
1300 // Look for blocks that are not part of the landing pad that we just
1301 // outlined but terminate with a call to llvm.eh.endcatch and a
1302 // branch to a block that is in the handler we just outlined.
1303 // These blocks will be part of a nested landing pad that intends to
1304 // return to an address in this handler. This case is best handled
1305 // after both landing pads have been outlined, so for now we'll just
1306 // save the association of the blocks in LPadTargetBlocks. The
1307 // return instructions which are created from these branches will be
1308 // replaced after all landing pads have been outlined.
Richard Trieu6b1aa5f2015-04-15 01:21:15 +00001309 for (const auto MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001310 // VMap maps all values and blocks that were just cloned, but dead
1311 // blocks which were pruned will map to nullptr.
1312 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1313 continue;
1314 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1315 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1316 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1317 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1318 continue;
1319 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1320 --II;
1321 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1322 // This would indicate that a nested landing pad wants to return
1323 // to a block that is outlined into two different handlers.
1324 assert(!LPadTargetBlocks.count(MappedBB));
1325 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1326 }
1327 }
1328 }
1329 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001330
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001331 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001332
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001333 return true;
1334}
1335
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001336/// This BB must end in a selector dispatch. All we need to do is pass the
1337/// handler block to llvm.eh.actions and list it as a possible indirectbr
1338/// target.
1339void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1340 BasicBlock *StartBB) {
1341 BasicBlock *HandlerBB;
1342 BasicBlock *NextBB;
1343 Constant *Selector;
1344 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1345 if (Res) {
1346 // If this was EH dispatch, this must be a conditional branch to the handler
1347 // block.
1348 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1349 // leading to crashes if some optimization hoists stuff here.
1350 assert(CatchAction->getSelector() && HandlerBB &&
1351 "expected catch EH dispatch");
1352 } else {
1353 // This must be a catch-all. Split the block after the landingpad.
1354 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001355 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001356 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001357 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1358 Function *EHCodeFn = Intrinsic::getDeclaration(
1359 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
1360 Value *Code = Builder.CreateCall(EHCodeFn, "sehcode");
1361 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1362 Builder.CreateStore(Code, SEHExceptionCodeSlot);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001363 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1364 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1365 CatchAction->setReturnTargets(Targets);
1366}
1367
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001368void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1369 // Each instance of this class should only ever be used to map a single
1370 // landing pad.
1371 assert(OriginLPad == nullptr || OriginLPad == LPad);
1372
1373 // If the landing pad has already been mapped, there's nothing more to do.
1374 if (OriginLPad == LPad)
1375 return;
1376
1377 OriginLPad = LPad;
1378
1379 // The landingpad instruction returns an aggregate value. Typically, its
1380 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001381 // results of those extracts will have been promoted to reg values before
1382 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001383 for (auto *U : LPad->users()) {
1384 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1385 if (!Extract)
1386 continue;
1387 assert(Extract->getNumIndices() == 1 &&
1388 "Unexpected operation: extracting both landing pad values");
1389 unsigned int Idx = *(Extract->idx_begin());
1390 assert((Idx == 0 || Idx == 1) &&
1391 "Unexpected operation: extracting an unknown landing pad element");
1392 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001393 ExtractedEHPtrs.push_back(Extract);
1394 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001395 ExtractedSelectors.push_back(Extract);
1396 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001397 }
1398}
1399
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001400bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1401 return BB->getLandingPadInst() == OriginLPad;
1402}
1403
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001404bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1405 if (Inst == OriginLPad)
1406 return true;
1407 for (auto *Extract : ExtractedEHPtrs) {
1408 if (Inst == Extract)
1409 return true;
1410 }
1411 for (auto *Extract : ExtractedSelectors) {
1412 if (Inst == Extract)
1413 return true;
1414 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001415 return false;
1416}
1417
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001418void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1419 Value *SelectorValue) const {
1420 // Remap all landing pad extract instructions to the specified values.
1421 for (auto *Extract : ExtractedEHPtrs)
1422 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001423 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001424 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001425}
1426
Reid Klecknerf14787d2015-04-22 00:07:52 +00001427static bool isFrameAddressCall(const Value *V) {
1428 return match(const_cast<Value *>(V),
1429 m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1430}
1431
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001432CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001433 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001434 // If this is one of the boilerplate landing pad instructions, skip it.
1435 // The instruction will have already been remapped in VMap.
1436 if (LPadMap.isLandingPadSpecificInst(Inst))
1437 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001438
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001439 // Nested landing pads will be cloned as stubs, with just the
1440 // landingpad instruction and an unreachable instruction. When
1441 // all landingpads have been outlined, we'll replace this with the
1442 // llvm.eh.actions call and indirect branch created when the
1443 // landing pad was outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001444 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1445 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001446 }
1447
1448 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1449 return handleInvoke(VMap, Invoke, NewBB);
1450
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001451 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1452 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001453
Andrew Kaylorea8df612015-04-17 23:05:43 +00001454 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1455 return handleCompare(VMap, Cmp, NewBB);
1456
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001457 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1458 return handleBeginCatch(VMap, Inst, NewBB);
1459 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1460 return handleEndCatch(VMap, Inst, NewBB);
1461 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1462 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001463
Reid Klecknerf14787d2015-04-22 00:07:52 +00001464 // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1465 // which is the FP of the parent.
1466 if (isFrameAddressCall(Inst)) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001467 VMap[Inst] = ParentFP;
Reid Klecknerf14787d2015-04-22 00:07:52 +00001468 return CloningDirector::SkipInstruction;
1469 }
1470
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001471 // Continue with the default cloning behavior.
1472 return CloningDirector::CloneInstruction;
1473}
1474
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001475CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1476 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1477 Instruction *NewInst = LPad->clone();
1478 if (LPad->hasName())
1479 NewInst->setName(LPad->getName());
1480 // Save this correlation for later processing.
1481 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1482 VMap[LPad] = NewInst;
1483 BasicBlock::InstListType &InstList = NewBB->getInstList();
1484 InstList.push_back(NewInst);
1485 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1486 return CloningDirector::StopCloningBB;
1487}
1488
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001489CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1490 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1491 // The argument to the call is some form of the first element of the
1492 // landingpad aggregate value, but that doesn't matter. It isn't used
1493 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001494 // The second argument is an outparameter where the exception object will be
1495 // stored. Typically the exception object is a scalar, but it can be an
1496 // aggregate when catching by value.
1497 // FIXME: Leave something behind to indicate where the exception object lives
1498 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001499 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1500 "llvm.eh.begincatch found while "
1501 "outlining catch handler.");
1502 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001503 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1504 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001505 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1506 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001507 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001508 return CloningDirector::SkipInstruction;
1509}
1510
1511CloningDirector::CloningAction
1512WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1513 const Instruction *Inst, BasicBlock *NewBB) {
1514 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1515 // It might be interesting to track whether or not we are inside a catch
1516 // function, but that might make the algorithm more brittle than it needs
1517 // to be.
1518
1519 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001520 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001521 // or at the end of the catch block. However, a catch-all handler may call
1522 // end catch from the original landing pad. If the call occurs in a nested
1523 // landing pad block, we must skip it and continue so that the landing pad
1524 // gets cloned.
1525 auto *ParentBB = IntrinCall->getParent();
1526 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001527 return CloningDirector::SkipInstruction;
1528
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001529 // If an end catch occurs anywhere else we want to terminate the handler
1530 // with a return to the code that follows the endcatch call. If the
1531 // next instruction is not an unconditional branch, we need to split the
1532 // block to provide a clear target for the return instruction.
1533 BasicBlock *ContinueBB;
1534 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1535 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1536 if (!Branch || !Branch->isUnconditional()) {
1537 // We're interrupting the cloning process at this location, so the
1538 // const_cast we're doing here will not cause a problem.
1539 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1540 const_cast<Instruction *>(cast<Instruction>(Next)));
1541 } else {
1542 ContinueBB = Branch->getSuccessor(0);
1543 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001544
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001545 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1546 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001547
1548 // We just added a terminator to the cloned block.
1549 // Tell the caller to stop processing the current basic block so that
1550 // the branch instruction will be skipped.
1551 return CloningDirector::StopCloningBB;
1552}
1553
1554CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1555 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1556 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1557 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1558 // This causes a replacement that will collapse the landing pad CFG based
1559 // on the filter function we intend to match.
1560 if (Selector == CurrentSelector)
1561 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1562 else
1563 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1564 // Tell the caller not to clone this instruction.
1565 return CloningDirector::SkipInstruction;
1566}
1567
1568CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001569WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1570 const InvokeInst *Invoke, BasicBlock *NewBB) {
1571 return CloningDirector::CloneInstruction;
1572}
1573
1574CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001575WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1576 const ResumeInst *Resume, BasicBlock *NewBB) {
1577 // Resume instructions shouldn't be reachable from catch handlers.
1578 // We still need to handle it, but it will be pruned.
1579 BasicBlock::InstListType &InstList = NewBB->getInstList();
1580 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1581 return CloningDirector::StopCloningBB;
1582}
1583
Andrew Kaylorea8df612015-04-17 23:05:43 +00001584CloningDirector::CloningAction
1585WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1586 const CmpInst *Compare, BasicBlock *NewBB) {
1587 const IntrinsicInst *IntrinCall = nullptr;
1588 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1589 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
Andrew Kaylor91307432015-04-28 22:01:51 +00001590 } else if (match(Compare->getOperand(1),
1591 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001592 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1593 }
1594 if (IntrinCall) {
1595 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1596 // This causes a replacement that will collapse the landing pad CFG based
1597 // on the filter function we intend to match.
1598 if (Selector == CurrentSelector->stripPointerCasts()) {
1599 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
Andrew Kaylor91307432015-04-28 22:01:51 +00001600 } else {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001601 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1602 }
1603 return CloningDirector::SkipInstruction;
1604 }
1605 return CloningDirector::CloneInstruction;
1606}
1607
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001608CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1609 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1610 // The MS runtime will terminate the process if an exception occurs in a
1611 // cleanup handler, so we shouldn't encounter landing pads in the actual
1612 // cleanup code, but they may appear in catch blocks. Depending on where
1613 // we started cloning we may see one, but it will get dropped during dead
1614 // block pruning.
1615 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1616 VMap[LPad] = NewInst;
1617 BasicBlock::InstListType &InstList = NewBB->getInstList();
1618 InstList.push_back(NewInst);
1619 return CloningDirector::StopCloningBB;
1620}
1621
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001622CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1623 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001624 // Cleanup code may flow into catch blocks or the catch block may be part
1625 // of a branch that will be optimized away. We'll insert a return
1626 // instruction now, but it may be pruned before the cloning process is
1627 // complete.
1628 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001629 return CloningDirector::StopCloningBB;
1630}
1631
1632CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1633 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001634 // Cleanup handlers nested within catch handlers may begin with a call to
1635 // eh.endcatch. We can just ignore that instruction.
1636 return CloningDirector::SkipInstruction;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001637}
1638
1639CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1640 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001641 // If we encounter a selector comparison while cloning a cleanup handler,
1642 // we want to stop cloning immediately. Anything after the dispatch
1643 // will be outlined into a different handler.
1644 BasicBlock *CatchHandler;
1645 Constant *Selector;
1646 BasicBlock *NextBB;
1647 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1648 CatchHandler, Selector, NextBB)) {
1649 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1650 return CloningDirector::StopCloningBB;
1651 }
1652 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001653 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001654 return CloningDirector::SkipInstruction;
1655}
1656
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001657CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1658 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1659 // All invokes in cleanup handlers can be replaced with calls.
1660 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1661 // Insert a normal call instruction...
1662 CallInst *NewCall =
1663 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1664 Invoke->getName(), NewBB);
1665 NewCall->setCallingConv(Invoke->getCallingConv());
1666 NewCall->setAttributes(Invoke->getAttributes());
1667 NewCall->setDebugLoc(Invoke->getDebugLoc());
1668 VMap[Invoke] = NewCall;
1669
Reid Kleckner6e48a822015-04-10 16:26:42 +00001670 // Remap the operands.
1671 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1672
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001673 // Insert an unconditional branch to the normal destination.
1674 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1675
1676 // The unwind destination won't be cloned into the new function, so
1677 // we don't need to clean up its phi nodes.
1678
1679 // We just added a terminator to the cloned block.
1680 // Tell the caller to stop processing the current basic block.
Reid Kleckner6e48a822015-04-10 16:26:42 +00001681 return CloningDirector::CloneSuccessors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001682}
1683
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001684CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1685 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1686 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1687
1688 // We just added a terminator to the cloned block.
1689 // Tell the caller to stop processing the current basic block so that
1690 // the branch instruction will be skipped.
1691 return CloningDirector::StopCloningBB;
1692}
1693
Andrew Kaylorea8df612015-04-17 23:05:43 +00001694CloningDirector::CloningAction
1695WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1696 const CmpInst *Compare, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001697 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1698 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1699 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1700 return CloningDirector::SkipInstruction;
1701 }
1702 return CloningDirector::CloneInstruction;
Andrew Kaylorea8df612015-04-17 23:05:43 +00001703}
1704
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001705WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001706 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001707 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001708 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001709
1710 // New allocas should be inserted in the entry block, but after the parent FP
1711 // is established if it is an instruction.
1712 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
1713 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
1714 InsertPoint = FPInst->getNextNode();
1715 Builder.SetInsertPoint(EntryBB, InsertPoint);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001716}
1717
1718Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001719 // If we're asked to materialize a static alloca, we temporarily create an
1720 // alloca in the outlined function and add this to the FrameVarInfo map. When
1721 // all the outlining is complete, we'll replace these temporary allocas with
1722 // calls to llvm.framerecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001723 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001724 assert(AV->isStaticAlloca() &&
1725 "cannot materialize un-demoted dynamic alloca");
Andrew Kaylor72029c62015-03-03 00:41:03 +00001726 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1727 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001728 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001729 return NewAlloca;
1730 }
1731
Andrew Kaylor72029c62015-03-03 00:41:03 +00001732 if (isa<Instruction>(V) || isa<Argument>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001733 errs() << "Failed to demote instruction used in exception handler:\n";
1734 errs() << " " << *V << '\n';
1735 report_fatal_error("WinEHPrepare failed to demote instruction");
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001736 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001737
Andrew Kaylor72029c62015-03-03 00:41:03 +00001738 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001739 return nullptr;
1740}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001741
Reid Kleckner3567d272015-04-02 21:13:31 +00001742void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1743 // Catch parameter objects have to live in the parent frame. When we see a use
1744 // of a catch parameter, add a sentinel to the multimap to indicate that it's
1745 // used from another handler. This will prevent us from trying to sink the
1746 // alloca into the handler and ensure that the catch parameter is present in
1747 // the call to llvm.frameescape.
1748 FrameVarInfo[V].push_back(getCatchObjectSentinel());
1749}
1750
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001751// This function maps the catch and cleanup handlers that are reachable from the
1752// specified landing pad. The landing pad sequence will have this basic shape:
1753//
1754// <cleanup handler>
1755// <selector comparison>
1756// <catch handler>
1757// <cleanup handler>
1758// <selector comparison>
1759// <catch handler>
1760// <cleanup handler>
1761// ...
1762//
1763// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1764// any arbitrary control flow, but all paths through the cleanup code must
1765// eventually reach the next selector comparison and no path can skip to a
1766// different selector comparisons, though some paths may terminate abnormally.
1767// Therefore, we will use a depth first search from the start of any given
1768// cleanup block and stop searching when we find the next selector comparison.
1769//
1770// If the landingpad instruction does not have a catch clause, we will assume
1771// that any instructions other than selector comparisons and catch handlers can
1772// be ignored. In practice, these will only be the boilerplate instructions.
1773//
1774// The catch handlers may also have any control structure, but we are only
1775// interested in the start of the catch handlers, so we don't need to actually
1776// follow the flow of the catch handlers. The start of the catch handlers can
1777// be located from the compare instructions, but they can be skipped in the
1778// flow by following the contrary branch.
1779void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1780 LandingPadActions &Actions) {
1781 unsigned int NumClauses = LPad->getNumClauses();
1782 unsigned int HandlersFound = 0;
1783 BasicBlock *BB = LPad->getParent();
1784
1785 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1786
1787 if (NumClauses == 0) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00001788 findCleanupHandlers(Actions, BB, nullptr);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001789 return;
1790 }
1791
1792 VisitedBlockSet VisitedBlocks;
1793
1794 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001795 BasicBlock *NextBB = nullptr;
1796
Andrew Kaylor20ae2a32015-04-23 22:38:36 +00001797 // Skip over filter clauses.
1798 if (LPad->isFilter(HandlersFound)) {
1799 ++HandlersFound;
1800 continue;
1801 }
1802
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001803 // See if the clause we're looking for is a catch-all.
1804 // If so, the catch begins immediately.
Andrew Kaylor91307432015-04-28 22:01:51 +00001805 Constant *ExpectedSelector =
1806 LPad->getClause(HandlersFound)->stripPointerCasts();
Andrew Kaylorea8df612015-04-17 23:05:43 +00001807 if (isa<ConstantPointerNull>(ExpectedSelector)) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001808 // The catch all must occur last.
1809 assert(HandlersFound == NumClauses - 1);
1810
Andrew Kaylorea8df612015-04-17 23:05:43 +00001811 // There can be additional selector dispatches in the call chain that we
1812 // need to ignore.
1813 BasicBlock *CatchBlock = nullptr;
1814 Constant *Selector;
1815 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1816 DEBUG(dbgs() << " Found extra catch dispatch in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00001817 << CatchBlock->getName() << "\n");
Andrew Kaylorea8df612015-04-17 23:05:43 +00001818 BB = NextBB;
1819 }
1820
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001821 // Add the catch handler to the action list.
Andrew Kaylorf18771b2015-04-20 18:48:45 +00001822 CatchHandler *Action = nullptr;
1823 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1824 // If the CatchHandlerMap already has an entry for this BB, re-use it.
1825 Action = CatchHandlerMap[BB];
1826 assert(Action->getSelector() == ExpectedSelector);
1827 } else {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001828 // We don't expect a selector dispatch, but there may be a call to
1829 // llvm.eh.begincatch, which separates catch handling code from
1830 // cleanup code in the same control flow. This call looks for the
1831 // begincatch intrinsic.
1832 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
1833 if (Action) {
1834 // For C++ EH, check if there is any interesting cleanup code before
1835 // we begin the catch. This is important because cleanups cannot
1836 // rethrow exceptions but code called from catches can. For SEH, it
1837 // isn't important if some finally code before a catch-all is executed
1838 // out of line or after recovering from the exception.
1839 if (Personality == EHPersonality::MSVC_CXX)
1840 findCleanupHandlers(Actions, BB, BB);
1841 } else {
1842 // If an action was not found, it means that the control flows
1843 // directly into the catch-all handler and there is no cleanup code.
1844 // That's an expected situation and we must create a catch action.
1845 // Since this is a catch-all handler, the selector won't actually
1846 // appear in the code anywhere. ExpectedSelector here is the constant
1847 // null ptr that we got from the landing pad instruction.
1848 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1849 CatchHandlerMap[BB] = Action;
1850 }
Andrew Kaylorf18771b2015-04-20 18:48:45 +00001851 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001852 Actions.insertCatchHandler(Action);
1853 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1854 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001855
1856 // Once we reach a catch-all, don't expect to hit a resume instruction.
1857 BB = nullptr;
1858 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001859 }
1860
1861 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
Andrew Kaylor41758512015-04-20 22:04:09 +00001862 assert(CatchAction);
1863
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001864 // See if there is any interesting code executed before the dispatch.
Reid Kleckner9405ef02015-04-10 23:12:29 +00001865 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001866
Andrew Kaylorea8df612015-04-17 23:05:43 +00001867 // When the source program contains multiple nested try blocks the catch
1868 // handlers can get strung together in such a way that we can encounter
1869 // a dispatch for a selector that we've already had a handler for.
1870 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1871 ++HandlersFound;
1872
1873 // Add the catch handler to the action list.
1874 DEBUG(dbgs() << " Found catch dispatch in block "
1875 << CatchAction->getStartBlock()->getName() << "\n");
1876 Actions.insertCatchHandler(CatchAction);
1877 } else {
Andrew Kaylor41758512015-04-20 22:04:09 +00001878 // Under some circumstances optimized IR will flow unconditionally into a
1879 // handler block without checking the selector. This can only happen if
1880 // the landing pad has a catch-all handler and the handler for the
1881 // preceeding catch clause is identical to the catch-call handler
1882 // (typically an empty catch). In this case, the handler must be shared
1883 // by all remaining clauses.
1884 if (isa<ConstantPointerNull>(
1885 CatchAction->getSelector()->stripPointerCasts())) {
1886 DEBUG(dbgs() << " Applying early catch-all handler in block "
1887 << CatchAction->getStartBlock()->getName()
1888 << " to all remaining clauses.\n");
1889 Actions.insertCatchHandler(CatchAction);
1890 return;
1891 }
1892
Andrew Kaylorea8df612015-04-17 23:05:43 +00001893 DEBUG(dbgs() << " Found extra catch dispatch in block "
1894 << CatchAction->getStartBlock()->getName() << "\n");
1895 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001896
1897 // Move on to the block after the catch handler.
1898 BB = NextBB;
1899 }
1900
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001901 // If we didn't wind up in a catch-all, see if there is any interesting code
1902 // executed before the resume.
Reid Kleckner9405ef02015-04-10 23:12:29 +00001903 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001904
1905 // It's possible that some optimization moved code into a landingpad that
1906 // wasn't
1907 // previously being used for cleanup. If that happens, we need to execute
1908 // that
1909 // extra code from a cleanup handler.
1910 if (Actions.includesCleanup() && !LPad->isCleanup())
1911 LPad->setCleanup(true);
1912}
1913
1914// This function searches starting with the input block for the next
1915// block that terminates with a branch whose condition is based on a selector
1916// comparison. This may be the input block. See the mapLandingPadBlocks
1917// comments for a discussion of control flow assumptions.
1918//
1919CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1920 BasicBlock *&NextBB,
1921 VisitedBlockSet &VisitedBlocks) {
1922 // See if we've already found a catch handler use it.
1923 // Call count() first to avoid creating a null entry for blocks
1924 // we haven't seen before.
1925 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1926 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1927 NextBB = Action->getNextBB();
1928 return Action;
1929 }
1930
1931 // VisitedBlocks applies only to the current search. We still
1932 // need to consider blocks that we've visited while mapping other
1933 // landing pads.
1934 VisitedBlocks.insert(BB);
1935
1936 BasicBlock *CatchBlock = nullptr;
1937 Constant *Selector = nullptr;
1938
1939 // If this is the first time we've visited this block from any landing pad
1940 // look to see if it is a selector dispatch block.
1941 if (!CatchHandlerMap.count(BB)) {
1942 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1943 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1944 CatchHandlerMap[BB] = Action;
1945 return Action;
1946 }
Andrew Kaylor41758512015-04-20 22:04:09 +00001947 // If we encounter a block containing an llvm.eh.begincatch before we
1948 // find a selector dispatch block, the handler is assumed to be
1949 // reached unconditionally. This happens for catch-all blocks, but
1950 // it can also happen for other catch handlers that have been combined
1951 // with the catch-all handler during optimization.
1952 if (isCatchBlock(BB)) {
1953 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
1954 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
1955 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
1956 CatchHandlerMap[BB] = Action;
1957 return Action;
1958 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001959 }
1960
1961 // Visit each successor, looking for the dispatch.
1962 // FIXME: We expect to find the dispatch quickly, so this will probably
1963 // work better as a breadth first search.
1964 for (BasicBlock *Succ : successors(BB)) {
1965 if (VisitedBlocks.count(Succ))
1966 continue;
1967
1968 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1969 if (Action)
1970 return Action;
1971 }
1972 return nullptr;
1973}
1974
Reid Kleckner9405ef02015-04-10 23:12:29 +00001975// These are helper functions to combine repeated code from findCleanupHandlers.
1976static void createCleanupHandler(LandingPadActions &Actions,
1977 CleanupHandlerMapTy &CleanupHandlerMap,
1978 BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001979 CleanupHandler *Action = new CleanupHandler(BB);
1980 CleanupHandlerMap[BB] = Action;
Reid Kleckner9405ef02015-04-10 23:12:29 +00001981 Actions.insertCleanupHandler(Action);
1982 DEBUG(dbgs() << " Found cleanup code in block "
1983 << Action->getStartBlock()->getName() << "\n");
1984}
1985
Reid Kleckner9405ef02015-04-10 23:12:29 +00001986static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1987 Instruction *MaybeCall) {
1988 // Look for finally blocks that Clang has already outlined for us.
1989 // %fp = call i8* @llvm.frameaddress(i32 0)
1990 // call void @"fin$parent"(iN 1, i8* %fp)
1991 if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1992 MaybeCall = MaybeCall->getNextNode();
1993 CallSite FinallyCall(MaybeCall);
1994 if (!FinallyCall || FinallyCall.arg_size() != 2)
1995 return CallSite();
1996 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
1997 return CallSite();
1998 if (!isFrameAddressCall(FinallyCall.getArgument(1)))
1999 return CallSite();
2000 return FinallyCall;
2001}
2002
2003static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2004 // Skip single ubr blocks.
2005 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2006 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2007 if (Br && Br->isUnconditional())
2008 BB = Br->getSuccessor(0);
2009 else
2010 return BB;
2011 }
2012 return BB;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002013}
2014
2015// This function searches starting with the input block for the next block that
2016// contains code that is not part of a catch handler and would not be eliminated
2017// during handler outlining.
2018//
Reid Kleckner9405ef02015-04-10 23:12:29 +00002019void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2020 BasicBlock *StartBB, BasicBlock *EndBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002021 // Here we will skip over the following:
2022 //
2023 // landing pad prolog:
2024 //
2025 // Unconditional branches
2026 //
2027 // Selector dispatch
2028 //
2029 // Resume pattern
2030 //
2031 // Anything else marks the start of an interesting block
2032
2033 BasicBlock *BB = StartBB;
2034 // Anything other than an unconditional branch will kick us out of this loop
2035 // one way or another.
2036 while (BB) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002037 BB = followSingleUnconditionalBranches(BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002038 // If we've already scanned this block, don't scan it again. If it is
2039 // a cleanup block, there will be an action in the CleanupHandlerMap.
2040 // If we've scanned it and it is not a cleanup block, there will be a
2041 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2042 // be no entry in the CleanupHandlerMap. We must call count() first to
2043 // avoid creating a null entry for blocks we haven't scanned.
2044 if (CleanupHandlerMap.count(BB)) {
2045 if (auto *Action = CleanupHandlerMap[BB]) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002046 Actions.insertCleanupHandler(Action);
2047 DEBUG(dbgs() << " Found cleanup code in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002048 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002049 // FIXME: This cleanup might chain into another, and we need to discover
2050 // that.
2051 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002052 } else {
2053 // Here we handle the case where the cleanup handler map contains a
2054 // value for this block but the value is a nullptr. This means that
2055 // we have previously analyzed the block and determined that it did
2056 // not contain any cleanup code. Based on the earlier analysis, we
2057 // know the the block must end in either an unconditional branch, a
2058 // resume or a conditional branch that is predicated on a comparison
2059 // with a selector. Either the resume or the selector dispatch
2060 // would terminate the search for cleanup code, so the unconditional
2061 // branch is the only case for which we might need to continue
2062 // searching.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002063 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2064 if (SuccBB == BB || SuccBB == EndBB)
2065 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002066 BB = SuccBB;
2067 continue;
2068 }
2069 }
2070
2071 // Create an entry in the cleanup handler map for this block. Initially
2072 // we create an entry that says this isn't a cleanup block. If we find
2073 // cleanup code, the caller will replace this entry.
2074 CleanupHandlerMap[BB] = nullptr;
2075
2076 TerminatorInst *Terminator = BB->getTerminator();
2077
2078 // Landing pad blocks have extra instructions we need to accept.
2079 LandingPadMap *LPadMap = nullptr;
2080 if (BB->isLandingPad()) {
2081 LandingPadInst *LPad = BB->getLandingPadInst();
2082 LPadMap = &LPadMaps[LPad];
2083 if (!LPadMap->isInitialized())
2084 LPadMap->mapLandingPad(LPad);
2085 }
2086
2087 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002088 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2089 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002090 // resume { i8*, i32 } %lpad.val2
2091 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2092 InsertValueInst *Insert1 = nullptr;
2093 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002094 Value *ResumeVal = Resume->getOperand(0);
Reid Kleckner1c130bb2015-04-16 17:02:23 +00002095 // If the resume value isn't a phi or landingpad value, it should be a
2096 // series of insertions. Identify them so we can avoid them when scanning
2097 // for cleanups.
2098 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002099 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002100 if (!Insert2)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002101 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002102 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2103 if (!Insert1)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002104 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002105 }
2106 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2107 II != IE; ++II) {
2108 Instruction *Inst = II;
2109 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2110 continue;
2111 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2112 continue;
2113 if (!Inst->hasOneUse() ||
2114 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002115 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002116 }
2117 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002118 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002119 }
2120
2121 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002122 if (Branch && Branch->isConditional()) {
2123 // Look for the selector dispatch.
2124 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2125 // %matches = icmp eq i32 %sel, %2
2126 // br i1 %matches, label %catch14, label %eh.resume
2127 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2128 if (!Compare || !Compare->isEquality())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002129 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylorbb111322015-04-07 21:30:23 +00002130 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2131 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002132 Instruction *Inst = II;
2133 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2134 continue;
2135 if (Inst == Compare || Inst == Branch)
2136 continue;
2137 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2138 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002139 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002140 }
2141 // The selector dispatch block should always terminate our search.
2142 assert(BB == EndBB);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002143 return;
2144 }
2145
2146 if (isAsynchronousEHPersonality(Personality)) {
2147 // If this is a landingpad block, split the block at the first non-landing
2148 // pad instruction.
2149 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2150 if (LPadMap) {
2151 while (MaybeCall != BB->getTerminator() &&
2152 LPadMap->isLandingPadSpecificInst(MaybeCall))
2153 MaybeCall = MaybeCall->getNextNode();
2154 }
2155
2156 // Look for outlined finally calls.
2157 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2158 Function *Fin = FinallyCall.getCalledFunction();
2159 assert(Fin && "outlined finally call should be direct");
2160 auto *Action = new CleanupHandler(BB);
2161 Action->setHandlerBlockOrFunc(Fin);
2162 Actions.insertCleanupHandler(Action);
2163 CleanupHandlerMap[BB] = Action;
2164 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2165 << Fin->getName() << " in block "
2166 << Action->getStartBlock()->getName() << "\n");
2167
2168 // Split the block if there were more interesting instructions and look
2169 // for finally calls in the normal successor block.
2170 BasicBlock *SuccBB = BB;
2171 if (FinallyCall.getInstruction() != BB->getTerminator() &&
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002172 FinallyCall.getInstruction()->getNextNode() !=
2173 BB->getTerminator()) {
2174 SuccBB =
2175 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002176 } else {
2177 if (FinallyCall.isInvoke()) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002178 SuccBB =
2179 cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
Reid Kleckner9405ef02015-04-10 23:12:29 +00002180 } else {
2181 SuccBB = BB->getUniqueSuccessor();
Andrew Kaylor91307432015-04-28 22:01:51 +00002182 assert(SuccBB &&
2183 "splitOutlinedFinallyCalls didn't insert a branch");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002184 }
2185 }
2186 BB = SuccBB;
2187 if (BB == EndBB)
2188 return;
2189 continue;
2190 }
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002191 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002192
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002193 // Anything else is either a catch block or interesting cleanup code.
Andrew Kaylorbb111322015-04-07 21:30:23 +00002194 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2195 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002196 Instruction *Inst = II;
2197 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2198 continue;
2199 // Unconditional branches fall through to this loop.
2200 if (Inst == Branch)
2201 continue;
2202 // If this is a catch block, there is no cleanup code to be found.
2203 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002204 return;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002205 // If this a nested landing pad, it may contain an endcatch call.
2206 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002207 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002208 // Anything else makes this interesting cleanup code.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002209 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002210 }
2211
2212 // Only unconditional branches in empty blocks should get this far.
2213 assert(Branch && Branch->isUnconditional());
2214 if (BB == EndBB)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002215 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002216 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002217 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002218}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002219
2220// This is a public function, declared in WinEHFuncInfo.h and is also
2221// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2222void llvm::parseEHActions(const IntrinsicInst *II,
David Majnemer69132a72015-04-03 22:49:05 +00002223 SmallVectorImpl<ActionHandler *> &Actions) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002224 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2225 uint64_t ActionKind =
Andrew Kaylorbb111322015-04-07 21:30:23 +00002226 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002227 if (ActionKind == /*catch=*/1) {
2228 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2229 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2230 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2231 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2232 I += 4;
2233 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
2234 CH->setHandlerBlockOrFunc(Handler);
2235 CH->setExceptionVarIndex(EHObjIndexVal);
2236 Actions.push_back(CH);
David Majnemer69132a72015-04-03 22:49:05 +00002237 } else if (ActionKind == 0) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002238 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2239 I += 2;
2240 auto *CH = new CleanupHandler(/*BB=*/nullptr);
2241 CH->setHandlerBlockOrFunc(Handler);
2242 Actions.push_back(CH);
David Majnemer69132a72015-04-03 22:49:05 +00002243 } else {
2244 llvm_unreachable("Expected either a catch or cleanup handler!");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002245 }
2246 }
2247 std::reverse(Actions.begin(), Actions.end());
2248}