blob: ab0f96ef05fb17d63c45193da3b3f83c09711ef3 [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
11// backend wants. It snifs the personality function to see which kind of
12// preparation is necessary. If the personality function uses the Itanium LSDA,
13// this pass delegates to the DWARF EH preparation pass.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/ADT/MapVector.h"
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"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000021#include "llvm/ADT/TinyPtrVector.h"
22#include "llvm/Analysis/LibCallSemantics.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/PatternMatch.h"
29#include "llvm/Pass.h"
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000030#include "llvm/Support/CommandLine.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000031#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000032#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000034#include "llvm/Transforms/Utils/Cloning.h"
35#include "llvm/Transforms/Utils/Local.h"
36#include <memory>
37
38using namespace llvm;
39using namespace llvm::PatternMatch;
40
41#define DEBUG_TYPE "winehprepare"
42
43namespace {
44
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000045// This map is used to model frame variable usage during outlining, to
46// construct a structure type to hold the frame variables in a frame
47// allocation block, and to remap the frame variable allocas (including
48// spill locations as needed) to GEPs that get the variable from the
49// frame allocation structure.
Reid Klecknercfb9ce52015-03-05 18:26:34 +000050typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000051
Andrew Kaylor6b67d422015-03-11 23:22:06 +000052typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
53
54enum ActionType { Catch, Cleanup };
55
56class LandingPadActions;
57class ActionHandler;
58class CatchHandler;
59class CleanupHandler;
60class LandingPadMap;
61
62typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
63typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
64
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000065class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000066public:
67 static char ID; // Pass identification, replacement for typeid.
68 WinEHPrepare(const TargetMachine *TM = nullptr)
Reid Kleckner47c8e7a2015-03-12 00:36:20 +000069 : FunctionPass(ID) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000070
71 bool runOnFunction(Function &Fn) override;
72
73 bool doFinalization(Module &M) override;
74
75 void getAnalysisUsage(AnalysisUsage &AU) const override;
76
77 const char *getPassName() const override {
78 return "Windows exception handling preparation";
79 }
80
81private:
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000082 bool prepareExceptionHandlers(Function &F,
83 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor6b67d422015-03-11 23:22:06 +000084 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
85 LandingPadInst *LPad, BasicBlock *StartBB,
Reid Klecknercfb9ce52015-03-05 18:26:34 +000086 FrameVarInfoMap &VarInfo);
Andrew Kaylor6b67d422015-03-11 23:22:06 +000087
88 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
89 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
90 VisitedBlockSet &VisitedBlocks);
91 CleanupHandler *findCleanupHandler(BasicBlock *StartBB, BasicBlock *EndBB);
92
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000093 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
94
95 // All fields are reset by runOnFunction.
96 EHPersonality Personality;
Andrew Kaylor6b67d422015-03-11 23:22:06 +000097 CatchHandlerMapTy CatchHandlerMap;
98 CleanupHandlerMapTy CleanupHandlerMap;
99 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000100};
101
102class WinEHFrameVariableMaterializer : public ValueMaterializer {
103public:
104 WinEHFrameVariableMaterializer(Function *OutlinedFn,
105 FrameVarInfoMap &FrameVarInfo);
106 ~WinEHFrameVariableMaterializer() {}
107
108 virtual Value *materializeValueFor(Value *V) override;
109
110private:
111 FrameVarInfoMap &FrameVarInfo;
112 IRBuilder<> Builder;
113};
114
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000115class LandingPadMap {
116public:
117 LandingPadMap() : OriginLPad(nullptr) {}
118 void mapLandingPad(const LandingPadInst *LPad);
119
120 bool isInitialized() { return OriginLPad != nullptr; }
121
122 bool mapIfEHPtrLoad(const LoadInst *Load) {
123 return mapIfEHLoad(Load, EHPtrStores, EHPtrStoreAddrs);
124 }
125 bool mapIfSelectorLoad(const LoadInst *Load) {
126 return mapIfEHLoad(Load, SelectorStores, SelectorStoreAddrs);
127 }
128
129 bool isLandingPadSpecificInst(const Instruction *Inst) const;
130
131 void remapSelector(ValueToValueMapTy &VMap, Value *MappedValue) const;
132
133private:
134 bool mapIfEHLoad(const LoadInst *Load,
135 SmallVectorImpl<const StoreInst *> &Stores,
136 SmallVectorImpl<const Value *> &StoreAddrs);
137
138 const LandingPadInst *OriginLPad;
139 // We will normally only see one of each of these instructions, but
140 // if more than one occurs for some reason we can handle that.
141 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
142 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
143
144 // In optimized code, there will typically be at most one instance of
145 // each of the following, but in unoptimized IR it is not uncommon
146 // for the values to be stored, loaded and then stored again. In that
147 // case we will create a second entry for each store and store address.
148 SmallVector<const StoreInst *, 2> EHPtrStores;
149 SmallVector<const StoreInst *, 2> SelectorStores;
150 SmallVector<const Value *, 2> EHPtrStoreAddrs;
151 SmallVector<const Value *, 2> SelectorStoreAddrs;
152};
153
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000154class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000155public:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000156 WinEHCloningDirectorBase(Function *HandlerFn,
157 FrameVarInfoMap &VarInfo,
158 LandingPadMap &LPadMap)
159 : Materializer(HandlerFn, VarInfo),
160 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
161 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
162 LPadMap(LPadMap) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000163
164 CloningAction handleInstruction(ValueToValueMapTy &VMap,
165 const Instruction *Inst,
166 BasicBlock *NewBB) override;
167
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000168 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
169 const Instruction *Inst,
170 BasicBlock *NewBB) = 0;
171 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
172 const Instruction *Inst,
173 BasicBlock *NewBB) = 0;
174 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
175 const Instruction *Inst,
176 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000177 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
178 const InvokeInst *Invoke,
179 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000180 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
181 const ResumeInst *Resume,
182 BasicBlock *NewBB) = 0;
183
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000184 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
185
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000186protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000187 WinEHFrameVariableMaterializer Materializer;
188 Type *SelectorIDType;
189 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000190 LandingPadMap &LPadMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000191};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000192
193class WinEHCatchDirector : public WinEHCloningDirectorBase {
194public:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000195 WinEHCatchDirector(Function *CatchFn, Value *Selector,
196 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
197 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
198 CurrentSelector(Selector->stripPointerCasts()),
199 ExceptionObjectVar(nullptr) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000200
201 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
202 const Instruction *Inst,
203 BasicBlock *NewBB) override;
204 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
205 BasicBlock *NewBB) override;
206 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
207 const Instruction *Inst,
208 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000209 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
210 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000211 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
212 BasicBlock *NewBB) override;
213
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000214 const Value *getExceptionVar() { return ExceptionObjectVar; }
215 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
216
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000217private:
218 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000219
220 const Value *ExceptionObjectVar;
221 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000222};
223
224class WinEHCleanupDirector : public WinEHCloningDirectorBase {
225public:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000226 WinEHCleanupDirector(Function *CleanupFn,
227 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
228 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000229
230 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
231 const Instruction *Inst,
232 BasicBlock *NewBB) override;
233 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
234 BasicBlock *NewBB) override;
235 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
236 const Instruction *Inst,
237 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000238 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
239 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000240 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
241 BasicBlock *NewBB) override;
242};
243
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000244class ActionHandler {
245public:
246 ActionHandler(BasicBlock *BB, ActionType Type)
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000247 : StartBB(BB), Type(Type), HandlerBlockOrFunc(nullptr) {}
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000248
249 ActionType getType() const { return Type; }
250 BasicBlock *getStartBlock() const { return StartBB; }
251
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000252 bool hasBeenProcessed() { return HandlerBlockOrFunc != nullptr; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000253
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000254 void setHandlerBlockOrFunc(Constant *F) { HandlerBlockOrFunc = F; }
255 Constant *getHandlerBlockOrFunc() { return HandlerBlockOrFunc; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000256
257private:
258 BasicBlock *StartBB;
259 ActionType Type;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000260
261 // Can be either a BlockAddress or a Function depending on the EH personality.
262 Constant *HandlerBlockOrFunc;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000263};
264
265class CatchHandler : public ActionHandler {
266public:
267 CatchHandler(BasicBlock *BB, Constant *Selector, BasicBlock *NextBB)
Reid Kleckner3c2ea312015-03-11 23:39:36 +0000268 : ActionHandler(BB, ActionType::Catch), Selector(Selector),
269 NextBB(NextBB), ExceptionObjectVar(nullptr) {}
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000270
271 // Method for support type inquiry through isa, cast, and dyn_cast:
272 static inline bool classof(const ActionHandler *H) {
273 return H->getType() == ActionType::Catch;
274 }
275
276 Constant *getSelector() const { return Selector; }
277 BasicBlock *getNextBB() const { return NextBB; }
278
279 const Value *getExceptionVar() { return ExceptionObjectVar; }
280 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
281
282 void setExceptionVar(const Value *Val) { ExceptionObjectVar = Val; }
283 void setReturnTargets(TinyPtrVector<BasicBlock *> &Targets) {
284 ReturnTargets = Targets;
285 }
286
287private:
288 Constant *Selector;
289 BasicBlock *NextBB;
290 const Value *ExceptionObjectVar;
291 TinyPtrVector<BasicBlock *> ReturnTargets;
292};
293
294class CleanupHandler : public ActionHandler {
295public:
296 CleanupHandler(BasicBlock *BB) : ActionHandler(BB, ActionType::Cleanup) {}
297
298 // Method for support type inquiry through isa, cast, and dyn_cast:
299 static inline bool classof(const ActionHandler *H) {
300 return H->getType() == ActionType::Cleanup;
301 }
302};
303
304class LandingPadActions {
305public:
306 LandingPadActions() : HasCleanupHandlers(false) {}
307
308 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
309 void insertCleanupHandler(CleanupHandler *Action) {
310 Actions.push_back(Action);
311 HasCleanupHandlers = true;
312 }
313
314 bool includesCleanup() const { return HasCleanupHandlers; }
315
316 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
317 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
318
319private:
320 // Note that this class does not own the ActionHandler objects in this vector.
321 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
322 // in the WinEHPrepare class.
323 SmallVector<ActionHandler *, 4> Actions;
324 bool HasCleanupHandlers;
325};
326
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000327} // end anonymous namespace
328
329char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000330INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
331 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000332
333FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
334 return new WinEHPrepare(TM);
335}
336
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000337// FIXME: Remove this once the backend can handle the prepared IR.
338static cl::opt<bool>
339SEHPrepare("sehprepare", cl::Hidden,
340 cl::desc("Prepare functions with SEH personalities"));
341
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000342bool WinEHPrepare::runOnFunction(Function &Fn) {
343 SmallVector<LandingPadInst *, 4> LPads;
344 SmallVector<ResumeInst *, 4> Resumes;
345 for (BasicBlock &BB : Fn) {
346 if (auto *LP = BB.getLandingPadInst())
347 LPads.push_back(LP);
348 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
349 Resumes.push_back(Resume);
350 }
351
352 // No need to prepare functions that lack landing pads.
353 if (LPads.empty())
354 return false;
355
356 // Classify the personality to see what kind of preparation we need.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000357 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000358
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000359 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000360 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000361 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000362
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000363 if (isAsynchronousEHPersonality(Personality) && !SEHPrepare) {
364 // Replace all resume instructions with unreachable.
365 // FIXME: Remove this once the backend can handle the prepared IR.
366 for (ResumeInst *Resume : Resumes) {
367 IRBuilder<>(Resume).CreateUnreachable();
368 Resume->eraseFromParent();
369 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000370 return true;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000371 }
372
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000373 // If there were any landing pads, prepareExceptionHandlers will make changes.
374 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000375 return true;
376}
377
378bool WinEHPrepare::doFinalization(Module &M) {
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000379 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000380}
381
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000382void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000383
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000384bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000385 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
386 // These containers are used to re-map frame variables that are used in
387 // outlined catch and cleanup handlers. They will be populated as the
388 // handlers are outlined.
389 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000390
391 bool HandlersOutlined = false;
392
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000393 Module *M = F.getParent();
394 LLVMContext &Context = M->getContext();
395
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000396 // Create a new function to receive the handler contents.
397 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
398 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000399 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000400
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000401 for (LandingPadInst *LPad : LPads) {
402 // Look for evidence that this landingpad has already been processed.
403 bool LPadHasActionList = false;
404 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000405 for (Instruction &Inst : *LPadBB) {
Reid Kleckner52b07792015-03-12 01:45:37 +0000406 if (auto *IntrinCall = dyn_cast<IntrinsicInst>(&Inst)) {
407 if (IntrinCall->getIntrinsicID() == Intrinsic::eh_actions) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000408 LPadHasActionList = true;
409 break;
410 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000411 }
412 // FIXME: This is here to help with the development of nested landing pad
413 // outlining. It should be removed when that is finished.
414 if (isa<UnreachableInst>(Inst)) {
415 LPadHasActionList = true;
416 break;
417 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000418 }
419
420 // If we've already outlined the handlers for this landingpad,
421 // there's nothing more to do here.
422 if (LPadHasActionList)
423 continue;
424
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000425 LandingPadActions Actions;
426 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000427
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000428 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000429 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000430 continue;
431 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000432
433 // SEH doesn't do any outlining for catches. Instead, pass the handler
434 // basic block addr to llvm.eh.actions and list the block as a return
435 // target.
436 if (isAsynchronousEHPersonality(Personality)) {
437 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
438 processSEHCatchHandler(CatchAction, StartBB);
439 HandlersOutlined = true;
440 continue;
441 }
442 }
443
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000444 if (outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo)) {
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000445 HandlersOutlined = true;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000446 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000447 } // End for each Action
448
449 // FIXME: We need a guard against partially outlined functions.
450 if (!HandlersOutlined)
451 continue;
452
453 // Replace the landing pad with a new llvm.eh.action based landing pad.
454 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
455 assert(!isa<PHINode>(LPadBB->begin()));
456 Instruction *NewLPad = LPad->clone();
457 NewLPadBB->getInstList().push_back(NewLPad);
458 while (!pred_empty(LPadBB)) {
459 auto *pred = *pred_begin(LPadBB);
460 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
461 Invoke->setUnwindDest(NewLPadBB);
462 }
463
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000464 // Replace uses of the old lpad in phis with this block and delete the old
465 // block.
466 LPadBB->replaceSuccessorsPhiUsesWith(NewLPadBB);
467 LPadBB->getTerminator()->eraseFromParent();
468 new UnreachableInst(LPadBB->getContext(), LPadBB);
469
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000470 // Add a call to describe the actions for this landing pad.
471 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000472 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000473 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000474 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000475 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000476 ActionArgs.push_back(CatchAction->getSelector());
477 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
478 if (EHObj)
479 ActionArgs.push_back(EHObj);
480 else
481 ActionArgs.push_back(ConstantPointerNull::get(Int8PtrType));
482 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000483 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000484 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000485 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000486 }
487 CallInst *Recover =
488 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
489
490 // Add an indirect branch listing possible successors of the catch handlers.
491 IndirectBrInst *Branch = IndirectBrInst::Create(Recover, 0, NewLPadBB);
492 for (ActionHandler *Action : Actions) {
493 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
494 for (auto *Target : CatchAction->getReturnTargets()) {
495 Branch->addDestination(Target);
496 }
497 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000498 }
499 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000500
501 // If nothing got outlined, there is no more processing to be done.
502 if (!HandlersOutlined)
503 return false;
504
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000505 // Delete any blocks that were only used by handlers that were outlined above.
506 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000507
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000508 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000509 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000510 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000511
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000512 Function *FrameEscapeFn =
513 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
514 Function *RecoverFrameFn =
515 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000516
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000517 // Finally, replace all of the temporary allocas for frame variables used in
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000518 // the outlined handlers with calls to llvm.framerecover.
519 BasicBlock::iterator II = Entry->getFirstInsertionPt();
Andrew Kaylor72029c62015-03-03 00:41:03 +0000520 Instruction *AllocaInsertPt = II;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000521 SmallVector<Value *, 8> AllocasToEscape;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000522 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +0000523 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000524 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000525
Andrew Kaylor72029c62015-03-03 00:41:03 +0000526 // If the mapped value isn't already an alloca, we need to spill it if it
527 // is a computed value or copy it if it is an argument.
528 AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
529 if (!ParentAlloca) {
530 if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
531 // Lower this argument to a copy and then demote that to the stack.
532 // We can't just use the argument location because the handler needs
533 // it to be in the frame allocation block.
534 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
535 Value *TrueValue = ConstantInt::getTrue(Context);
536 Value *UndefValue = UndefValue::get(Arg->getType());
537 Instruction *SI =
538 SelectInst::Create(TrueValue, Arg, UndefValue,
539 Arg->getName() + ".tmp", AllocaInsertPt);
540 Arg->replaceAllUsesWith(SI);
541 // Reset the select operand, because it was clobbered by the RAUW above.
542 SI->setOperand(1, Arg);
543 ParentAlloca = DemoteRegToStack(*SI, true, SI);
544 } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
545 ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
546 } else {
547 Instruction *ParentInst = cast<Instruction>(ParentVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000548 // FIXME: This is a work-around to temporarily handle the case where an
549 // instruction that is only used in handlers is not sunk.
550 // Without uses, DemoteRegToStack would just eliminate the value.
551 // This will fail if ParentInst is an invoke.
552 if (ParentInst->getNumUses() == 0) {
553 BasicBlock::iterator InsertPt = ParentInst;
554 ++InsertPt;
555 ParentAlloca =
556 new AllocaInst(ParentInst->getType(), nullptr,
557 ParentInst->getName() + ".reg2mem", InsertPt);
558 new StoreInst(ParentInst, ParentAlloca, InsertPt);
559 } else {
560 ParentAlloca = DemoteRegToStack(*ParentInst, true, ParentInst);
561 }
Andrew Kaylor72029c62015-03-03 00:41:03 +0000562 }
563 }
564
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000565 // If the parent alloca is no longer used and only one of the handlers used
566 // it, erase the parent and leave the copy in the outlined handler.
567 if (ParentAlloca->getNumUses() == 0 && Allocas.size() == 1) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000568 ParentAlloca->eraseFromParent();
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000569 continue;
570 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000571
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000572 // Add this alloca to the list of things to escape.
573 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000574
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000575 // Next replace all outlined allocas that are mapped to it.
576 for (AllocaInst *TempAlloca : Allocas) {
577 Function *HandlerFn = TempAlloca->getParent()->getParent();
578 // FIXME: Sink this GEP into the blocks where it is used.
579 Builder.SetInsertPoint(TempAlloca);
580 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
581 Value *RecoverArgs[] = {
582 Builder.CreateBitCast(&F, Int8PtrType, ""),
583 &(HandlerFn->getArgumentList().back()),
584 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000585 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000586 // Add a pointer bitcast if the alloca wasn't an i8.
587 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
588 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
589 RecoveredAlloca =
590 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000591 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000592 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
593 TempAlloca->removeFromParent();
594 RecoveredAlloca->takeName(TempAlloca);
595 delete TempAlloca;
596 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000597 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000598
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000599 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
600 // block.
601 Builder.SetInsertPoint(&F.getEntryBlock().back());
602 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
603
Reid Kleckner7e9546b2015-03-25 20:10:36 +0000604 // Insert an alloca for the EH state in the entry block. On x86, we will also
605 // insert stores to update the EH state, but on other ISAs, the runtime does
606 // it for us.
607 // FIXME: This record is different on x86.
608 Type *UnwindHelpTy = Type::getInt64Ty(Context);
609 AllocaInst *UnwindHelp =
610 new AllocaInst(UnwindHelpTy, "unwindhelp", &F.getEntryBlock().front());
611 Builder.CreateStore(llvm::ConstantInt::get(UnwindHelpTy, -2), UnwindHelp);
612 Function *UnwindHelpFn =
613 Intrinsic::getDeclaration(M, Intrinsic::eh_unwindhelp);
614 Builder.CreateCall(UnwindHelpFn,
615 Builder.CreateBitCast(UnwindHelp, Int8PtrType));
616
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000617 // Clean up the handler action maps we created for this function
618 DeleteContainerSeconds(CatchHandlerMap);
619 CatchHandlerMap.clear();
620 DeleteContainerSeconds(CleanupHandlerMap);
621 CleanupHandlerMap.clear();
622
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000623 return HandlersOutlined;
624}
625
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000626// This function examines a block to determine whether the block ends with a
627// conditional branch to a catch handler based on a selector comparison.
628// This function is used both by the WinEHPrepare::findSelectorComparison() and
629// WinEHCleanupDirector::handleTypeIdFor().
630static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
631 Constant *&Selector, BasicBlock *&NextBB) {
632 ICmpInst::Predicate Pred;
633 BasicBlock *TBB, *FBB;
634 Value *LHS, *RHS;
635
636 if (!match(BB->getTerminator(),
637 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
638 return false;
639
640 if (!match(LHS,
641 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
642 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
643 return false;
644
645 if (Pred == CmpInst::ICMP_EQ) {
646 CatchHandler = TBB;
647 NextBB = FBB;
648 return true;
649 }
650
651 if (Pred == CmpInst::ICMP_NE) {
652 CatchHandler = FBB;
653 NextBB = TBB;
654 return true;
655 }
656
657 return false;
658}
659
660bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
661 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000662 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000663 Module *M = SrcFn->getParent();
664 LLVMContext &Context = M->getContext();
665
666 // Create a new function to receive the handler contents.
667 Type *Int8PtrType = Type::getInt8PtrTy(Context);
668 std::vector<Type *> ArgTys;
669 ArgTys.push_back(Int8PtrType);
670 ArgTys.push_back(Int8PtrType);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000671 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000672 if (Action->getType() == Catch) {
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000673 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
674 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
675 SrcFn->getName() + ".catch", M);
676 } else {
677 FunctionType *FnType =
678 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
679 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
680 SrcFn->getName() + ".cleanup", M);
681 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000682
683 // Generate a standard prolog to setup the frame recovery structure.
684 IRBuilder<> Builder(Context);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000685 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
686 Handler->getBasicBlockList().push_front(Entry);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000687 Builder.SetInsertPoint(Entry);
688 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
689
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000690 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000691
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000692 ValueToValueMapTy VMap;
693
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000694 LandingPadMap &LPadMap = LPadMaps[LPad];
695 if (!LPadMap.isInitialized())
696 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000697 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
698 Constant *Sel = CatchAction->getSelector();
699 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap));
700 LPadMap.remapSelector(VMap, ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000701 } else {
702 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
703 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000704
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000705 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000706 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000707
Andrew Kaylor3170e562015-03-20 21:42:54 +0000708 // If the start block contains PHI nodes, we need to map them.
709 BasicBlock::iterator II = StartBB->begin();
710 while (auto *PN = dyn_cast<PHINode>(II)) {
711 bool Mapped = false;
712 // Look for PHI values that we have already mapped (such as the selector).
713 for (Value *Val : PN->incoming_values()) {
714 if (VMap.count(Val)) {
715 VMap[PN] = VMap[Val];
716 Mapped = true;
717 }
718 }
719 // If we didn't find a match for this value, map it as an undef.
720 if (!Mapped) {
721 VMap[PN] = UndefValue::get(PN->getType());
722 }
723 ++II;
724 }
725
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000726 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +0000727 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000728
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000729 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000730 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000731 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000732
733 // Move all the instructions in the first cloned block into our entry block.
734 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
735 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
736 FirstClonedBB->eraseFromParent();
737
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000738 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
739 WinEHCatchDirector *CatchDirector =
740 reinterpret_cast<WinEHCatchDirector *>(Director.get());
741 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
742 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
743 }
744
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000745 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000746
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000747 return true;
748}
749
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000750/// This BB must end in a selector dispatch. All we need to do is pass the
751/// handler block to llvm.eh.actions and list it as a possible indirectbr
752/// target.
753void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
754 BasicBlock *StartBB) {
755 BasicBlock *HandlerBB;
756 BasicBlock *NextBB;
757 Constant *Selector;
758 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
759 if (Res) {
760 // If this was EH dispatch, this must be a conditional branch to the handler
761 // block.
762 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
763 // leading to crashes if some optimization hoists stuff here.
764 assert(CatchAction->getSelector() && HandlerBB &&
765 "expected catch EH dispatch");
766 } else {
767 // This must be a catch-all. Split the block after the landingpad.
768 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
769 HandlerBB =
770 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
771 }
772 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
773 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
774 CatchAction->setReturnTargets(Targets);
775}
776
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000777void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
778 // Each instance of this class should only ever be used to map a single
779 // landing pad.
780 assert(OriginLPad == nullptr || OriginLPad == LPad);
781
782 // If the landing pad has already been mapped, there's nothing more to do.
783 if (OriginLPad == LPad)
784 return;
785
786 OriginLPad = LPad;
787
788 // The landingpad instruction returns an aggregate value. Typically, its
789 // value will be passed to a pair of extract value instructions and the
790 // results of those extracts are often passed to store instructions.
791 // In unoptimized code the stored value will often be loaded and then stored
792 // again.
793 for (auto *U : LPad->users()) {
794 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
795 if (!Extract)
796 continue;
797 assert(Extract->getNumIndices() == 1 &&
798 "Unexpected operation: extracting both landing pad values");
799 unsigned int Idx = *(Extract->idx_begin());
800 assert((Idx == 0 || Idx == 1) &&
801 "Unexpected operation: extracting an unknown landing pad element");
802 if (Idx == 0) {
803 // Element 0 doesn't directly corresponds to anything in the WinEH
804 // scheme.
805 // It will be stored to a memory location, then later loaded and finally
806 // the loaded value will be used as the argument to an
807 // llvm.eh.begincatch
808 // call. We're tracking it here so that we can skip the store and load.
809 ExtractedEHPtrs.push_back(Extract);
810 } else if (Idx == 1) {
811 // Element 1 corresponds to the filter selector. We'll map it to 1 for
812 // matching purposes, but it will also probably be stored to memory and
813 // reloaded, so we need to track the instuction so that we can map the
814 // loaded value too.
815 ExtractedSelectors.push_back(Extract);
816 }
817
818 // Look for stores of the extracted values.
819 for (auto *EU : Extract->users()) {
820 if (auto *Store = dyn_cast<StoreInst>(EU)) {
821 if (Idx == 1) {
822 SelectorStores.push_back(Store);
823 SelectorStoreAddrs.push_back(Store->getPointerOperand());
824 } else {
825 EHPtrStores.push_back(Store);
826 EHPtrStoreAddrs.push_back(Store->getPointerOperand());
827 }
828 }
829 }
830 }
831}
832
833bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
834 if (Inst == OriginLPad)
835 return true;
836 for (auto *Extract : ExtractedEHPtrs) {
837 if (Inst == Extract)
838 return true;
839 }
840 for (auto *Extract : ExtractedSelectors) {
841 if (Inst == Extract)
842 return true;
843 }
844 for (auto *Store : EHPtrStores) {
845 if (Inst == Store)
846 return true;
847 }
848 for (auto *Store : SelectorStores) {
849 if (Inst == Store)
850 return true;
851 }
852
853 return false;
854}
855
856void LandingPadMap::remapSelector(ValueToValueMapTy &VMap,
857 Value *MappedValue) const {
858 // Remap all selector extract instructions to the specified value.
859 for (auto *Extract : ExtractedSelectors)
860 VMap[Extract] = MappedValue;
861}
862
863bool LandingPadMap::mapIfEHLoad(const LoadInst *Load,
864 SmallVectorImpl<const StoreInst *> &Stores,
865 SmallVectorImpl<const Value *> &StoreAddrs) {
866 // This makes the assumption that a store we've previously seen dominates
867 // this load instruction. That might seem like a rather huge assumption,
868 // but given the way that landingpads are constructed its fairly safe.
869 // FIXME: Add debug/assert code that verifies this.
870 const Value *LoadAddr = Load->getPointerOperand();
871 for (auto *StoreAddr : StoreAddrs) {
872 if (LoadAddr == StoreAddr) {
873 // Handle the common debug scenario where this loaded value is stored
874 // to a different location.
875 for (auto *U : Load->users()) {
876 if (auto *Store = dyn_cast<StoreInst>(U)) {
877 Stores.push_back(Store);
878 StoreAddrs.push_back(Store->getPointerOperand());
879 }
880 }
881 return true;
882 }
883 }
884 return false;
885}
886
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000887CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000888 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000889 // If this is one of the boilerplate landing pad instructions, skip it.
890 // The instruction will have already been remapped in VMap.
891 if (LPadMap.isLandingPadSpecificInst(Inst))
892 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000893
894 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
895 // Look for loads of (previously suppressed) landingpad values.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000896 // The EHPtr load can be mapped to an undef value as it should only be used
897 // as an argument to llvm.eh.begincatch, but the selector value needs to be
898 // mapped to a constant value of 1. This value will be used to simplify the
899 // branching to always flow to the current handler.
900 if (LPadMap.mapIfSelectorLoad(Load)) {
901 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000902 return CloningDirector::SkipInstruction;
903 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000904 if (LPadMap.mapIfEHPtrLoad(Load)) {
905 VMap[Inst] = UndefValue::get(Int8PtrType);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000906 return CloningDirector::SkipInstruction;
907 }
908
909 // Any other loads just get cloned.
910 return CloningDirector::CloneInstruction;
911 }
912
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000913 // Nested landing pads will be cloned as stubs, with just the
914 // landingpad instruction and an unreachable instruction. When
915 // all landingpads have been outlined, we'll replace this with the
916 // llvm.eh.actions call and indirect branch created when the
917 // landing pad was outlined.
918 if (auto *NestedLPad = dyn_cast<LandingPadInst>(Inst)) {
919 Instruction *NewInst = NestedLPad->clone();
920 if (NestedLPad->hasName())
921 NewInst->setName(NestedLPad->getName());
922 // FIXME: Store this mapping somewhere else also.
923 VMap[NestedLPad] = NewInst;
924 BasicBlock::InstListType &InstList = NewBB->getInstList();
925 InstList.push_back(NewInst);
926 InstList.push_back(new UnreachableInst(NewBB->getContext()));
927 return CloningDirector::StopCloningBB;
928 }
929
930 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
931 return handleInvoke(VMap, Invoke, NewBB);
932
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000933 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
934 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000935
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000936 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
937 return handleBeginCatch(VMap, Inst, NewBB);
938 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
939 return handleEndCatch(VMap, Inst, NewBB);
940 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
941 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000942
943 // Continue with the default cloning behavior.
944 return CloningDirector::CloneInstruction;
945}
946
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000947CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
948 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
949 // The argument to the call is some form of the first element of the
950 // landingpad aggregate value, but that doesn't matter. It isn't used
951 // here.
Reid Kleckner42366532015-03-03 23:20:30 +0000952 // The second argument is an outparameter where the exception object will be
953 // stored. Typically the exception object is a scalar, but it can be an
954 // aggregate when catching by value.
955 // FIXME: Leave something behind to indicate where the exception object lives
956 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000957 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
958 "llvm.eh.begincatch found while "
959 "outlining catch handler.");
960 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000961 return CloningDirector::SkipInstruction;
962}
963
964CloningDirector::CloningAction
965WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
966 const Instruction *Inst, BasicBlock *NewBB) {
967 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
968 // It might be interesting to track whether or not we are inside a catch
969 // function, but that might make the algorithm more brittle than it needs
970 // to be.
971
972 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000973 // landingpad block that is part of the catch handlers exception mechanism,
974 // or at the end of the catch block. If it occurs in a landing pad, we must
975 // skip it and continue so that the landing pad gets cloned.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000976 // FIXME: This case isn't fully supported yet and shouldn't turn up in any
977 // of the test cases until it is.
978 if (IntrinCall->getParent()->isLandingPad())
979 return CloningDirector::SkipInstruction;
980
981 // If an end catch occurs anywhere else the next instruction should be an
982 // unconditional branch instruction that we want to replace with a return
983 // to the the address of the branch target.
984 const BasicBlock *EndCatchBB = IntrinCall->getParent();
985 const TerminatorInst *Terminator = EndCatchBB->getTerminator();
986 const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
987 assert(Branch && Branch->isUnconditional());
988 assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
989 BasicBlock::const_iterator(Branch));
990
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000991 BasicBlock *ContinueLabel = Branch->getSuccessor(0);
992 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueLabel),
993 NewBB);
994 ReturnTargets.push_back(ContinueLabel);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000995
996 // We just added a terminator to the cloned block.
997 // Tell the caller to stop processing the current basic block so that
998 // the branch instruction will be skipped.
999 return CloningDirector::StopCloningBB;
1000}
1001
1002CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1003 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1004 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1005 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1006 // This causes a replacement that will collapse the landing pad CFG based
1007 // on the filter function we intend to match.
1008 if (Selector == CurrentSelector)
1009 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1010 else
1011 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1012 // Tell the caller not to clone this instruction.
1013 return CloningDirector::SkipInstruction;
1014}
1015
1016CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001017WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1018 const InvokeInst *Invoke, BasicBlock *NewBB) {
1019 return CloningDirector::CloneInstruction;
1020}
1021
1022CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001023WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1024 const ResumeInst *Resume, BasicBlock *NewBB) {
1025 // Resume instructions shouldn't be reachable from catch handlers.
1026 // We still need to handle it, but it will be pruned.
1027 BasicBlock::InstListType &InstList = NewBB->getInstList();
1028 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1029 return CloningDirector::StopCloningBB;
1030}
1031
1032CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1033 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1034 // Catch blocks within cleanup handlers will always be unreachable.
1035 // We'll insert an unreachable instruction now, but it will be pruned
1036 // before the cloning process is complete.
1037 BasicBlock::InstListType &InstList = NewBB->getInstList();
1038 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1039 return CloningDirector::StopCloningBB;
1040}
1041
1042CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1043 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1044 // Catch blocks within cleanup handlers will always be unreachable.
1045 // We'll insert an unreachable instruction now, but it will be pruned
1046 // before the cloning process is complete.
1047 BasicBlock::InstListType &InstList = NewBB->getInstList();
1048 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1049 return CloningDirector::StopCloningBB;
1050}
1051
1052CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1053 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001054 // If we encounter a selector comparison while cloning a cleanup handler,
1055 // we want to stop cloning immediately. Anything after the dispatch
1056 // will be outlined into a different handler.
1057 BasicBlock *CatchHandler;
1058 Constant *Selector;
1059 BasicBlock *NextBB;
1060 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1061 CatchHandler, Selector, NextBB)) {
1062 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1063 return CloningDirector::StopCloningBB;
1064 }
1065 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001066 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001067 return CloningDirector::SkipInstruction;
1068}
1069
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001070CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1071 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1072 // All invokes in cleanup handlers can be replaced with calls.
1073 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1074 // Insert a normal call instruction...
1075 CallInst *NewCall =
1076 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1077 Invoke->getName(), NewBB);
1078 NewCall->setCallingConv(Invoke->getCallingConv());
1079 NewCall->setAttributes(Invoke->getAttributes());
1080 NewCall->setDebugLoc(Invoke->getDebugLoc());
1081 VMap[Invoke] = NewCall;
1082
1083 // Insert an unconditional branch to the normal destination.
1084 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1085
1086 // The unwind destination won't be cloned into the new function, so
1087 // we don't need to clean up its phi nodes.
1088
1089 // We just added a terminator to the cloned block.
1090 // Tell the caller to stop processing the current basic block.
1091 return CloningDirector::StopCloningBB;
1092}
1093
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001094CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1095 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1096 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1097
1098 // We just added a terminator to the cloned block.
1099 // Tell the caller to stop processing the current basic block so that
1100 // the branch instruction will be skipped.
1101 return CloningDirector::StopCloningBB;
1102}
1103
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001104WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1105 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1106 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1107 Builder.SetInsertPoint(&OutlinedFn->getEntryBlock());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001108}
1109
1110Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Andrew Kaylor72029c62015-03-03 00:41:03 +00001111 // If we're asked to materialize a value that is an instruction, we
1112 // temporarily create an alloca in the outlined function and add this
1113 // to the FrameVarInfo map. When all the outlining is complete, we'll
1114 // collect these into a structure, spilling non-alloca values in the
1115 // parent frame as necessary, and replace these temporary allocas with
1116 // GEPs referencing the frame allocation block.
1117
1118 // If the value is an alloca, the mapping is direct.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001119 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Andrew Kaylor72029c62015-03-03 00:41:03 +00001120 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1121 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001122 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001123 return NewAlloca;
1124 }
1125
Andrew Kaylor72029c62015-03-03 00:41:03 +00001126 // For other types of instructions or arguments, we need an alloca based on
1127 // the value's type and a load of the alloca. The alloca will be replaced
1128 // by a GEP, but the load will stay. In the parent function, the value will
1129 // be spilled to a location in the frame allocation block.
1130 if (isa<Instruction>(V) || isa<Argument>(V)) {
1131 AllocaInst *NewAlloca =
1132 Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001133 FrameVarInfo[V].push_back(NewAlloca);
Andrew Kaylor72029c62015-03-03 00:41:03 +00001134 LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1135 return NewLoad;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001136 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001137
Andrew Kaylor72029c62015-03-03 00:41:03 +00001138 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001139 return nullptr;
1140}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001141
1142// This function maps the catch and cleanup handlers that are reachable from the
1143// specified landing pad. The landing pad sequence will have this basic shape:
1144//
1145// <cleanup handler>
1146// <selector comparison>
1147// <catch handler>
1148// <cleanup handler>
1149// <selector comparison>
1150// <catch handler>
1151// <cleanup handler>
1152// ...
1153//
1154// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1155// any arbitrary control flow, but all paths through the cleanup code must
1156// eventually reach the next selector comparison and no path can skip to a
1157// different selector comparisons, though some paths may terminate abnormally.
1158// Therefore, we will use a depth first search from the start of any given
1159// cleanup block and stop searching when we find the next selector comparison.
1160//
1161// If the landingpad instruction does not have a catch clause, we will assume
1162// that any instructions other than selector comparisons and catch handlers can
1163// be ignored. In practice, these will only be the boilerplate instructions.
1164//
1165// The catch handlers may also have any control structure, but we are only
1166// interested in the start of the catch handlers, so we don't need to actually
1167// follow the flow of the catch handlers. The start of the catch handlers can
1168// be located from the compare instructions, but they can be skipped in the
1169// flow by following the contrary branch.
1170void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1171 LandingPadActions &Actions) {
1172 unsigned int NumClauses = LPad->getNumClauses();
1173 unsigned int HandlersFound = 0;
1174 BasicBlock *BB = LPad->getParent();
1175
1176 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1177
1178 if (NumClauses == 0) {
1179 // This landing pad contains only cleanup code.
1180 CleanupHandler *Action = new CleanupHandler(BB);
1181 CleanupHandlerMap[BB] = Action;
1182 Actions.insertCleanupHandler(Action);
1183 DEBUG(dbgs() << " Assuming cleanup code in block " << BB->getName()
1184 << "\n");
1185 assert(LPad->isCleanup());
1186 return;
1187 }
1188
1189 VisitedBlockSet VisitedBlocks;
1190
1191 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001192 BasicBlock *NextBB = nullptr;
1193
1194 // See if the clause we're looking for is a catch-all.
1195 // If so, the catch begins immediately.
1196 if (isa<ConstantPointerNull>(LPad->getClause(HandlersFound))) {
1197 // The catch all must occur last.
1198 assert(HandlersFound == NumClauses - 1);
1199
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001200 // For C++ EH, check if there is any interesting cleanup code before we
1201 // begin the catch. This is important because cleanups cannot rethrow
1202 // exceptions but code called from catches can. For SEH, it isn't
1203 // important if some finally code before a catch-all is executed out of
1204 // line or after recovering from the exception.
1205 if (Personality == EHPersonality::MSVC_CXX) {
1206 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1207 // Add a cleanup entry to the list
1208 Actions.insertCleanupHandler(CleanupAction);
1209 DEBUG(dbgs() << " Found cleanup code in block "
1210 << CleanupAction->getStartBlock()->getName() << "\n");
1211 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001212 }
1213
1214 // Add the catch handler to the action list.
1215 CatchHandler *Action =
1216 new CatchHandler(BB, LPad->getClause(HandlersFound), nullptr);
1217 CatchHandlerMap[BB] = Action;
1218 Actions.insertCatchHandler(Action);
1219 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1220 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001221
1222 // Once we reach a catch-all, don't expect to hit a resume instruction.
1223 BB = nullptr;
1224 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001225 }
1226
1227 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1228 // See if there is any interesting code executed before the dispatch.
1229 if (auto *CleanupAction =
1230 findCleanupHandler(BB, CatchAction->getStartBlock())) {
1231 // Add a cleanup entry to the list
1232 Actions.insertCleanupHandler(CleanupAction);
1233 DEBUG(dbgs() << " Found cleanup code in block "
1234 << CleanupAction->getStartBlock()->getName() << "\n");
1235 }
1236
1237 assert(CatchAction);
1238 ++HandlersFound;
1239
1240 // Add the catch handler to the action list.
1241 Actions.insertCatchHandler(CatchAction);
1242 DEBUG(dbgs() << " Found catch dispatch in block "
1243 << CatchAction->getStartBlock()->getName() << "\n");
1244
1245 // Move on to the block after the catch handler.
1246 BB = NextBB;
1247 }
1248
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001249 // If we didn't wind up in a catch-all, see if there is any interesting code
1250 // executed before the resume.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001251 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1252 // Add a cleanup entry to the list
1253 Actions.insertCleanupHandler(CleanupAction);
1254 DEBUG(dbgs() << " Found cleanup code in block "
1255 << CleanupAction->getStartBlock()->getName() << "\n");
1256 }
1257
1258 // It's possible that some optimization moved code into a landingpad that
1259 // wasn't
1260 // previously being used for cleanup. If that happens, we need to execute
1261 // that
1262 // extra code from a cleanup handler.
1263 if (Actions.includesCleanup() && !LPad->isCleanup())
1264 LPad->setCleanup(true);
1265}
1266
1267// This function searches starting with the input block for the next
1268// block that terminates with a branch whose condition is based on a selector
1269// comparison. This may be the input block. See the mapLandingPadBlocks
1270// comments for a discussion of control flow assumptions.
1271//
1272CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1273 BasicBlock *&NextBB,
1274 VisitedBlockSet &VisitedBlocks) {
1275 // See if we've already found a catch handler use it.
1276 // Call count() first to avoid creating a null entry for blocks
1277 // we haven't seen before.
1278 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1279 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1280 NextBB = Action->getNextBB();
1281 return Action;
1282 }
1283
1284 // VisitedBlocks applies only to the current search. We still
1285 // need to consider blocks that we've visited while mapping other
1286 // landing pads.
1287 VisitedBlocks.insert(BB);
1288
1289 BasicBlock *CatchBlock = nullptr;
1290 Constant *Selector = nullptr;
1291
1292 // If this is the first time we've visited this block from any landing pad
1293 // look to see if it is a selector dispatch block.
1294 if (!CatchHandlerMap.count(BB)) {
1295 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1296 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1297 CatchHandlerMap[BB] = Action;
1298 return Action;
1299 }
1300 }
1301
1302 // Visit each successor, looking for the dispatch.
1303 // FIXME: We expect to find the dispatch quickly, so this will probably
1304 // work better as a breadth first search.
1305 for (BasicBlock *Succ : successors(BB)) {
1306 if (VisitedBlocks.count(Succ))
1307 continue;
1308
1309 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1310 if (Action)
1311 return Action;
1312 }
1313 return nullptr;
1314}
1315
1316// These are helper functions to combine repeated code from findCleanupHandler.
1317static CleanupHandler *createCleanupHandler(CleanupHandlerMapTy &CleanupHandlerMap,
1318 BasicBlock *BB) {
1319 CleanupHandler *Action = new CleanupHandler(BB);
1320 CleanupHandlerMap[BB] = Action;
1321 return Action;
1322}
1323
1324// This function searches starting with the input block for the next block that
1325// contains code that is not part of a catch handler and would not be eliminated
1326// during handler outlining.
1327//
1328CleanupHandler *WinEHPrepare::findCleanupHandler(BasicBlock *StartBB,
1329 BasicBlock *EndBB) {
1330 // Here we will skip over the following:
1331 //
1332 // landing pad prolog:
1333 //
1334 // Unconditional branches
1335 //
1336 // Selector dispatch
1337 //
1338 // Resume pattern
1339 //
1340 // Anything else marks the start of an interesting block
1341
1342 BasicBlock *BB = StartBB;
1343 // Anything other than an unconditional branch will kick us out of this loop
1344 // one way or another.
1345 while (BB) {
1346 // If we've already scanned this block, don't scan it again. If it is
1347 // a cleanup block, there will be an action in the CleanupHandlerMap.
1348 // If we've scanned it and it is not a cleanup block, there will be a
1349 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1350 // be no entry in the CleanupHandlerMap. We must call count() first to
1351 // avoid creating a null entry for blocks we haven't scanned.
1352 if (CleanupHandlerMap.count(BB)) {
1353 if (auto *Action = CleanupHandlerMap[BB]) {
1354 return cast<CleanupHandler>(Action);
1355 } else {
1356 // Here we handle the case where the cleanup handler map contains a
1357 // value for this block but the value is a nullptr. This means that
1358 // we have previously analyzed the block and determined that it did
1359 // not contain any cleanup code. Based on the earlier analysis, we
1360 // know the the block must end in either an unconditional branch, a
1361 // resume or a conditional branch that is predicated on a comparison
1362 // with a selector. Either the resume or the selector dispatch
1363 // would terminate the search for cleanup code, so the unconditional
1364 // branch is the only case for which we might need to continue
1365 // searching.
1366 if (BB == EndBB)
1367 return nullptr;
1368 BasicBlock *SuccBB;
1369 if (!match(BB->getTerminator(), m_UnconditionalBr(SuccBB)))
1370 return nullptr;
1371 BB = SuccBB;
1372 continue;
1373 }
1374 }
1375
1376 // Create an entry in the cleanup handler map for this block. Initially
1377 // we create an entry that says this isn't a cleanup block. If we find
1378 // cleanup code, the caller will replace this entry.
1379 CleanupHandlerMap[BB] = nullptr;
1380
1381 TerminatorInst *Terminator = BB->getTerminator();
1382
1383 // Landing pad blocks have extra instructions we need to accept.
1384 LandingPadMap *LPadMap = nullptr;
1385 if (BB->isLandingPad()) {
1386 LandingPadInst *LPad = BB->getLandingPadInst();
1387 LPadMap = &LPadMaps[LPad];
1388 if (!LPadMap->isInitialized())
1389 LPadMap->mapLandingPad(LPad);
1390 }
1391
1392 // Look for the bare resume pattern:
1393 // %exn2 = load i8** %exn.slot
1394 // %sel2 = load i32* %ehselector.slot
1395 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn2, 0
1396 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel2, 1
1397 // resume { i8*, i32 } %lpad.val2
1398 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1399 InsertValueInst *Insert1 = nullptr;
1400 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001401 Value *ResumeVal = Resume->getOperand(0);
1402 // If there is only one landingpad, we may use the lpad directly with no
1403 // insertions.
1404 if (isa<LandingPadInst>(ResumeVal))
1405 return nullptr;
1406 if (!isa<PHINode>(ResumeVal)) {
1407 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001408 if (!Insert2)
1409 return createCleanupHandler(CleanupHandlerMap, BB);
1410 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1411 if (!Insert1)
1412 return createCleanupHandler(CleanupHandlerMap, BB);
1413 }
1414 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1415 II != IE; ++II) {
1416 Instruction *Inst = II;
1417 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1418 continue;
1419 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1420 continue;
1421 if (!Inst->hasOneUse() ||
1422 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1423 return createCleanupHandler(CleanupHandlerMap, BB);
1424 }
1425 }
1426 return nullptr;
1427 }
1428
1429 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1430 if (Branch) {
1431 if (Branch->isConditional()) {
1432 // Look for the selector dispatch.
1433 // %sel = load i32* %ehselector.slot
1434 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1435 // %matches = icmp eq i32 %sel12, %2
1436 // br i1 %matches, label %catch14, label %eh.resume
1437 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1438 if (!Compare || !Compare->isEquality())
1439 return createCleanupHandler(CleanupHandlerMap, BB);
1440 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1441 IE = BB->end();
1442 II != IE; ++II) {
1443 Instruction *Inst = II;
1444 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1445 continue;
1446 if (Inst == Compare || Inst == Branch)
1447 continue;
1448 if (!Inst->hasOneUse() || (Inst->user_back() != Compare))
1449 return createCleanupHandler(CleanupHandlerMap, BB);
1450 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1451 continue;
1452 if (!isa<LoadInst>(Inst))
1453 return createCleanupHandler(CleanupHandlerMap, BB);
1454 }
1455 // The selector dispatch block should always terminate our search.
1456 assert(BB == EndBB);
1457 return nullptr;
1458 } else {
1459 // Look for empty blocks with unconditional branches.
1460 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1461 IE = BB->end();
1462 II != IE; ++II) {
1463 Instruction *Inst = II;
1464 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1465 continue;
1466 if (Inst == Branch)
1467 continue;
1468 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1469 continue;
1470 // Anything else makes this interesting cleanup code.
1471 return createCleanupHandler(CleanupHandlerMap, BB);
1472 }
1473 if (BB == EndBB)
1474 return nullptr;
1475 // The branch was unconditional.
1476 BB = Branch->getSuccessor(0);
1477 continue;
1478 } // End else of if branch was conditional
1479 } // End if Branch
1480
1481 // Anything else makes this interesting cleanup code.
1482 return createCleanupHandler(CleanupHandlerMap, BB);
1483 }
1484 return nullptr;
1485}