blob: df2d5db8c67e22df20ca902008870a1f456e2f76 [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 Kleckner0738a9c2015-05-05 17:44:16 +000011// backend wants for functions using a personality function from a runtime
12// provided by MSVC. Functions with other personality functions are left alone
13// and may be prepared by other passes. In particular, all supported MSVC
14// personality functions require cleanup code to be outlined, and the C++
15// personality requires catch handler code to be outlined.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/CodeGen/Passes.h"
20#include "llvm/ADT/MapVector.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000021#include "llvm/ADT/STLExtras.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000022#include "llvm/ADT/SmallSet.h"
Reid Klecknerfd7df282015-04-22 21:05:21 +000023#include "llvm/ADT/SetVector.h"
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000024#include "llvm/ADT/Triple.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000025#include "llvm/ADT/TinyPtrVector.h"
David Majnemerfd9f4772015-08-11 01:15:26 +000026#include "llvm/Analysis/CFG.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000027#include "llvm/Analysis/LibCallSemantics.h"
Reid Klecknerf12c0302015-06-09 21:42:19 +000028#include "llvm/Analysis/TargetLibraryInfo.h"
David Majnemercde33032015-03-30 22:58:10 +000029#include "llvm/CodeGen/WinEHFuncInfo.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000030#include "llvm/IR/Dominators.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/PatternMatch.h"
37#include "llvm/Pass.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000038#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000039#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000041#include "llvm/Transforms/Utils/Cloning.h"
42#include "llvm/Transforms/Utils/Local.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000043#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000044#include <memory>
45
46using namespace llvm;
47using namespace llvm::PatternMatch;
48
49#define DEBUG_TYPE "winehprepare"
50
51namespace {
52
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000053// This map is used to model frame variable usage during outlining, to
54// construct a structure type to hold the frame variables in a frame
55// allocation block, and to remap the frame variable allocas (including
56// spill locations as needed) to GEPs that get the variable from the
57// frame allocation structure.
Reid Klecknercfb9ce52015-03-05 18:26:34 +000058typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000059
Reid Kleckner3567d272015-04-02 21:13:31 +000060// TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
61// quite null.
62AllocaInst *getCatchObjectSentinel() {
63 return static_cast<AllocaInst *>(nullptr) + 1;
64}
65
Andrew Kaylor6b67d422015-03-11 23:22:06 +000066typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
67
Andrew Kaylor6b67d422015-03-11 23:22:06 +000068class LandingPadActions;
Andrew Kaylor6b67d422015-03-11 23:22:06 +000069class LandingPadMap;
70
71typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
72typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
73
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000074class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000075public:
76 static char ID; // Pass identification, replacement for typeid.
77 WinEHPrepare(const TargetMachine *TM = nullptr)
Reid Kleckner582786b2015-04-30 18:17:12 +000078 : FunctionPass(ID) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000079 if (TM)
Daniel Sanders110bf6d2015-06-24 13:25:57 +000080 TheTriple = TM->getTargetTriple();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000081 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000082
83 bool runOnFunction(Function &Fn) override;
84
85 bool doFinalization(Module &M) override;
86
87 void getAnalysisUsage(AnalysisUsage &AU) const override;
88
89 const char *getPassName() const override {
90 return "Windows exception handling preparation";
91 }
92
93private:
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000094 bool prepareExceptionHandlers(Function &F,
95 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylora6c5b962015-05-20 23:22:24 +000096 void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor64622aa2015-04-01 17:21:25 +000097 void promoteLandingPadValues(LandingPadInst *LPad);
Reid Klecknerfd7df282015-04-22 21:05:21 +000098 void demoteValuesLiveAcrossHandlers(Function &F,
99 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000100 void findSEHEHReturnPoints(Function &F,
101 SetVector<BasicBlock *> &EHReturnBlocks);
102 void findCXXEHReturnPoints(Function &F,
103 SetVector<BasicBlock *> &EHReturnBlocks);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000104 void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
105 SetVector<BasicBlock*> &Targets);
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000106 void completeNestedLandingPad(Function *ParentFn,
107 LandingPadInst *OutlinedLPad,
108 const LandingPadInst *OriginalLPad,
109 FrameVarInfoMap &VarInfo);
Reid Kleckner6511c8b2015-07-01 20:59:25 +0000110 Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
111 const Twine &Name, Module *M, Value *&ParentFP);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000112 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
113 LandingPadInst *LPad, BasicBlock *StartBB,
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000114 FrameVarInfoMap &VarInfo);
David Majnemer7fddecc2015-06-17 20:52:32 +0000115 void addStubInvokeToHandlerIfNeeded(Function *Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000116
117 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
118 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
119 VisitedBlockSet &VisitedBlocks);
Reid Kleckner9405ef02015-04-10 23:12:29 +0000120 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
121 BasicBlock *EndBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000122
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000123 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000124 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
125 void
126 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
127 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
128 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
129 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
130 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
131 void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB,
132 Function &F);
David Majnemerfd9f4772015-08-11 01:15:26 +0000133 bool prepareExplicitEH(Function &F);
134 void numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB);
135
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000136 Triple TheTriple;
137
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000138 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +0000139 DominatorTree *DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000140 const TargetLibraryInfo *LibInfo = nullptr;
Reid Kleckner582786b2015-04-30 18:17:12 +0000141 EHPersonality Personality = EHPersonality::Unknown;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000142 CatchHandlerMapTy CatchHandlerMap;
143 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000144 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000145 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
146 SmallPtrSet<BasicBlock *, 4> EHBlocks;
147 SetVector<BasicBlock *> EHReturnBlocks;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000148
149 // This maps landing pad instructions found in outlined handlers to
150 // the landing pad instruction in the parent function from which they
151 // were cloned. The cloned/nested landing pad is used as the key
152 // because the landing pad may be cloned into multiple handlers.
153 // This map will be used to add the llvm.eh.actions call to the nested
154 // landing pads after all handlers have been outlined.
155 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
156
157 // This maps blocks in the parent function which are destinations of
158 // catch handlers to cloned blocks in (other) outlined handlers. This
159 // handles the case where a nested landing pads has a catch handler that
160 // returns to a handler function rather than the parent function.
161 // The original block is used as the key here because there should only
162 // ever be one handler function from which the cloned block is not pruned.
163 // The original block will be pruned from the parent function after all
164 // handlers have been outlined. This map will be used to adjust the
165 // return instructions of handlers which return to the block that was
166 // outlined into a handler. This is done after all handlers have been
167 // outlined but before the outlined code is pruned from the parent function.
168 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000169
Reid Klecknerd5afc62f2015-07-07 23:23:03 +0000170 // Map from outlined handler to call to parent local address. Only used for
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000171 // 32-bit EH.
172 DenseMap<Function *, Value *> HandlerToParentFP;
173
Reid Kleckner582786b2015-04-30 18:17:12 +0000174 AllocaInst *SEHExceptionCodeSlot = nullptr;
David Majnemerfd9f4772015-08-11 01:15:26 +0000175
176 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
177 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000178};
179
180class WinEHFrameVariableMaterializer : public ValueMaterializer {
181public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000182 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000183 FrameVarInfoMap &FrameVarInfo);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000184 ~WinEHFrameVariableMaterializer() override {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000185
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000186 Value *materializeValueFor(Value *V) override;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000187
Reid Kleckner3567d272015-04-02 21:13:31 +0000188 void escapeCatchObject(Value *V);
189
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000190private:
191 FrameVarInfoMap &FrameVarInfo;
192 IRBuilder<> Builder;
193};
194
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000195class LandingPadMap {
196public:
197 LandingPadMap() : OriginLPad(nullptr) {}
198 void mapLandingPad(const LandingPadInst *LPad);
199
200 bool isInitialized() { return OriginLPad != nullptr; }
201
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000202 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000203 bool isLandingPadSpecificInst(const Instruction *Inst) const;
204
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000205 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
206 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000207
208private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000209 const LandingPadInst *OriginLPad;
210 // We will normally only see one of each of these instructions, but
211 // if more than one occurs for some reason we can handle that.
212 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
213 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000214};
215
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000216class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000217public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000218 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
219 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
220 : Materializer(HandlerFn, ParentFP, VarInfo),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000221 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
222 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000223 LPadMap(LPadMap), ParentFP(ParentFP) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000224
225 CloningAction handleInstruction(ValueToValueMapTy &VMap,
226 const Instruction *Inst,
227 BasicBlock *NewBB) override;
228
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000229 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
230 const Instruction *Inst,
231 BasicBlock *NewBB) = 0;
232 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
233 const Instruction *Inst,
234 BasicBlock *NewBB) = 0;
235 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
236 const Instruction *Inst,
237 BasicBlock *NewBB) = 0;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000238 virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
239 const IndirectBrInst *IBr,
240 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000241 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
242 const InvokeInst *Invoke,
243 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000244 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
245 const ResumeInst *Resume,
246 BasicBlock *NewBB) = 0;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000247 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
248 const CmpInst *Compare,
249 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000250 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
251 const LandingPadInst *LPad,
252 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000253
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000254 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
255
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000256protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000257 WinEHFrameVariableMaterializer Materializer;
258 Type *SelectorIDType;
259 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000260 LandingPadMap &LPadMap;
Reid Klecknerf14787d2015-04-22 00:07:52 +0000261
262 /// The value representing the parent frame pointer.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000263 Value *ParentFP;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000264};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000265
266class WinEHCatchDirector : public WinEHCloningDirectorBase {
267public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000268 WinEHCatchDirector(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000269 Function *CatchFn, Value *ParentFP, Value *Selector,
270 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000271 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
272 DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000273 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000274 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000275 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
276 DT(DT), EHBlocks(EHBlocks) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000277
278 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
279 const Instruction *Inst,
280 BasicBlock *NewBB) override;
281 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
282 BasicBlock *NewBB) override;
283 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
284 const Instruction *Inst,
285 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000286 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
287 const IndirectBrInst *IBr,
288 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000289 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
290 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000291 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
292 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000293 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
294 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000295 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
296 const LandingPadInst *LPad,
297 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000298
Reid Kleckner3567d272015-04-02 21:13:31 +0000299 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000300 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
301
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000302private:
303 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000304
Reid Kleckner3567d272015-04-02 21:13:31 +0000305 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000306 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000307
308 // This will be a reference to the field of the same name in the WinEHPrepare
309 // object which instantiates this WinEHCatchDirector object.
310 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000311 DominatorTree *DT;
312 SmallPtrSetImpl<BasicBlock *> &EHBlocks;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000313};
314
315class WinEHCleanupDirector : public WinEHCloningDirectorBase {
316public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000317 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
318 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
319 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
320 LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000321
322 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
323 const Instruction *Inst,
324 BasicBlock *NewBB) override;
325 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
326 BasicBlock *NewBB) override;
327 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
328 const Instruction *Inst,
329 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000330 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
331 const IndirectBrInst *IBr,
332 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000333 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
334 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000335 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
336 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000337 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
338 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000339 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
340 const LandingPadInst *LPad,
341 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000342};
343
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000344class LandingPadActions {
345public:
346 LandingPadActions() : HasCleanupHandlers(false) {}
347
348 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
349 void insertCleanupHandler(CleanupHandler *Action) {
350 Actions.push_back(Action);
351 HasCleanupHandlers = true;
352 }
353
354 bool includesCleanup() const { return HasCleanupHandlers; }
355
David Majnemercde33032015-03-30 22:58:10 +0000356 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000357 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
358 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
359
360private:
361 // Note that this class does not own the ActionHandler objects in this vector.
362 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
363 // in the WinEHPrepare class.
364 SmallVector<ActionHandler *, 4> Actions;
365 bool HasCleanupHandlers;
366};
367
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000368} // end anonymous namespace
369
370char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000371INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
372 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000373
374FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
375 return new WinEHPrepare(TM);
376}
377
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000378bool WinEHPrepare::runOnFunction(Function &Fn) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000379 if (!Fn.hasPersonalityFn())
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000380 return false;
381
David Majnemerfd9f4772015-08-11 01:15:26 +0000382 // No need to prepare outlined handlers.
383 if (Fn.hasFnAttribute("wineh-parent"))
David Majnemer09e1fdb2015-08-06 21:13:51 +0000384 return false;
385
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000386 // Classify the personality to see what kind of preparation we need.
David Majnemer7fddecc2015-06-17 20:52:32 +0000387 Personality = classifyEHPersonality(Fn.getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000388
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000389 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000390 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000391 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000392
David Majnemerfd9f4772015-08-11 01:15:26 +0000393 SmallVector<LandingPadInst *, 4> LPads;
394 SmallVector<ResumeInst *, 4> Resumes;
395 bool ForExplicitEH = false;
396 for (BasicBlock &BB : Fn) {
397 if (auto *LP = BB.getLandingPadInst()) {
398 LPads.push_back(LP);
399 } else if (BB.getFirstNonPHI()->isEHPad()) {
400 ForExplicitEH = true;
401 break;
402 }
403 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
404 Resumes.push_back(Resume);
405 }
406
407 if (ForExplicitEH)
408 return prepareExplicitEH(Fn);
409
410 // No need to prepare functions that lack landing pads.
411 if (LPads.empty())
412 return false;
413
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000414 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000415 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000416
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000417 // If there were any landing pads, prepareExceptionHandlers will make changes.
418 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000419 return true;
420}
421
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000422bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000423
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000424void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
425 AU.addRequired<DominatorTreeWrapperPass>();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000426 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000427}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000428
Reid Klecknerfd7df282015-04-22 21:05:21 +0000429static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
430 Constant *&Selector, BasicBlock *&NextBB);
431
432// Finds blocks reachable from the starting set Worklist. Does not follow unwind
433// edges or blocks listed in StopPoints.
434static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
435 SetVector<BasicBlock *> &Worklist,
436 const SetVector<BasicBlock *> *StopPoints) {
437 while (!Worklist.empty()) {
438 BasicBlock *BB = Worklist.pop_back_val();
439
440 // Don't cross blocks that we should stop at.
441 if (StopPoints && StopPoints->count(BB))
442 continue;
443
444 if (!ReachableBBs.insert(BB).second)
445 continue; // Already visited.
446
447 // Don't follow unwind edges of invokes.
448 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
449 Worklist.insert(II->getNormalDest());
450 continue;
451 }
452
453 // Otherwise, follow all successors.
454 Worklist.insert(succ_begin(BB), succ_end(BB));
455 }
456}
457
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000458// Attempt to find an instruction where a block can be split before
459// a call to llvm.eh.begincatch and its operands. If the block
460// begins with the begincatch call or one of its adjacent operands
461// the block will not be split.
462static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
463 IntrinsicInst *II) {
464 // If the begincatch call is already the first instruction in the block,
465 // don't split.
466 Instruction *FirstNonPHI = BB->getFirstNonPHI();
467 if (II == FirstNonPHI)
468 return nullptr;
469
470 // If either operand is in the same basic block as the instruction and
471 // isn't used by another instruction before the begincatch call, include it
472 // in the split block.
473 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
474 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
475
476 Instruction *I = II->getPrevNode();
477 Instruction *LastI = II;
478
479 while (I == Op0 || I == Op1) {
480 // If the block begins with one of the operands and there are no other
481 // instructions between the operand and the begincatch call, don't split.
482 if (I == FirstNonPHI)
483 return nullptr;
484
485 LastI = I;
486 I = I->getPrevNode();
487 }
488
489 // If there is at least one instruction in the block before the begincatch
490 // call and its operands, split the block at either the begincatch or
491 // its operand.
492 return LastI;
493}
494
Reid Klecknerfd7df282015-04-22 21:05:21 +0000495/// Find all points where exceptional control rejoins normal control flow via
496/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000497void WinEHPrepare::findCXXEHReturnPoints(
498 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000499 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
500 BasicBlock *BB = BBI;
501 for (Instruction &I : *BB) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000502 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
Andrew Kaylor91307432015-04-28 22:01:51 +0000503 Instruction *SplitPt =
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000504 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
505 if (SplitPt) {
506 // Split the block before the llvm.eh.begincatch call to allow
507 // cleanup and catch code to be distinguished later.
508 // Do not update BBI because we still need to process the
509 // portion of the block that we are splitting off.
Andrew Kaylora33f1592015-04-29 17:21:26 +0000510 SplitBlock(BB, SplitPt, DT);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000511 break;
512 }
513 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000514 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
515 // Split the block after the call to llvm.eh.endcatch if there is
516 // anything other than an unconditional branch, or if the successor
517 // starts with a phi.
518 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
519 if (!Br || !Br->isUnconditional() ||
520 isa<PHINode>(Br->getSuccessor(0)->begin())) {
521 DEBUG(dbgs() << "splitting block " << BB->getName()
522 << " with llvm.eh.endcatch\n");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000523 BBI = SplitBlock(BB, I.getNextNode(), DT);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000524 }
525 // The next BB is normal control flow.
526 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
527 break;
528 }
529 }
530 }
531}
532
533static bool isCatchAllLandingPad(const BasicBlock *BB) {
534 const LandingPadInst *LP = BB->getLandingPadInst();
535 if (!LP)
536 return false;
537 unsigned N = LP->getNumClauses();
538 return (N > 0 && LP->isCatch(N - 1) &&
539 isa<ConstantPointerNull>(LP->getClause(N - 1)));
540}
541
542/// Find all points where exceptions control rejoins normal control flow via
543/// selector dispatch.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000544void WinEHPrepare::findSEHEHReturnPoints(
545 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000546 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
547 BasicBlock *BB = BBI;
548 // If the landingpad is a catch-all, treat the whole lpad as if it is
549 // reachable from normal control flow.
550 // FIXME: This is imprecise. We need a better way of identifying where a
551 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
552 // is no difference.
553 if (isCatchAllLandingPad(BB)) {
554 EHReturnBlocks.insert(BB);
555 continue;
556 }
557
558 BasicBlock *CatchHandler;
559 BasicBlock *NextBB;
560 Constant *Selector;
561 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
Reid Klecknered012db2015-07-08 18:08:52 +0000562 // Split the edge if there are multiple predecessors. This creates a place
563 // where we can insert EH recovery code.
564 if (!CatchHandler->getSinglePredecessor()) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000565 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
566 << " to " << CatchHandler->getName() << '\n');
567 BBI = CatchHandler = SplitCriticalEdge(
568 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
569 }
570 EHReturnBlocks.insert(CatchHandler);
571 }
572 }
573}
574
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000575void WinEHPrepare::identifyEHBlocks(Function &F,
576 SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000577 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
578 << F.getName() << '\n');
579
580 // Build a set of all non-exceptional blocks and exceptional blocks.
581 // - Non-exceptional blocks are blocks reachable from the entry block while
582 // not following invoke unwind edges.
583 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
584 // not follow llvm.eh.endcatch blocks, which mark a transition from
585 // exceptional to normal control.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000586
587 if (Personality == EHPersonality::MSVC_CXX)
588 findCXXEHReturnPoints(F, EHReturnBlocks);
589 else
590 findSEHEHReturnPoints(F, EHReturnBlocks);
591
592 DEBUG({
593 dbgs() << "identified the following blocks as EH return points:\n";
594 for (BasicBlock *BB : EHReturnBlocks)
595 dbgs() << " " << BB->getName() << '\n';
596 });
597
Andrew Kaylor91307432015-04-28 22:01:51 +0000598// Join points should not have phis at this point, unless they are a
599// landingpad, in which case we will demote their phis later.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000600#ifndef NDEBUG
601 for (BasicBlock *BB : EHReturnBlocks)
602 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
603 "non-lpad EH return block has phi");
604#endif
605
606 // Normal blocks are the blocks reachable from the entry block and all EH
607 // return points.
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000608 SetVector<BasicBlock *> Worklist;
Reid Klecknerfd7df282015-04-22 21:05:21 +0000609 Worklist = EHReturnBlocks;
610 Worklist.insert(&F.getEntryBlock());
611 findReachableBlocks(NormalBlocks, Worklist, nullptr);
612 DEBUG({
613 dbgs() << "marked the following blocks as normal:\n";
614 for (BasicBlock *BB : NormalBlocks)
615 dbgs() << " " << BB->getName() << '\n';
616 });
617
618 // Exceptional blocks are the blocks reachable from landingpads that don't
619 // cross EH return points.
620 Worklist.clear();
621 for (auto *LPI : LPads)
622 Worklist.insert(LPI->getParent());
623 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
624 DEBUG({
625 dbgs() << "marked the following blocks as exceptional:\n";
626 for (BasicBlock *BB : EHBlocks)
627 dbgs() << " " << BB->getName() << '\n';
628 });
629
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000630}
631
632/// Ensure that all values live into and out of exception handlers are stored
633/// in memory.
634/// FIXME: This falls down when values are defined in one handler and live into
635/// another handler. For example, a cleanup defines a value used only by a
636/// catch handler.
637void WinEHPrepare::demoteValuesLiveAcrossHandlers(
638 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
639 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
640 << F.getName() << '\n');
641
642 // identifyEHBlocks() should have been called before this function.
643 assert(!NormalBlocks.empty());
644
Reid Kleckner7ea77082015-07-10 22:21:54 +0000645 // Try to avoid demoting EH pointer and selector values. They get in the way
646 // of our pattern matching.
647 SmallPtrSet<Instruction *, 10> EHVals;
648 for (BasicBlock &BB : F) {
649 LandingPadInst *LP = BB.getLandingPadInst();
650 if (!LP)
651 continue;
652 EHVals.insert(LP);
653 for (User *U : LP->users()) {
654 auto *EI = dyn_cast<ExtractValueInst>(U);
655 if (!EI)
656 continue;
657 EHVals.insert(EI);
658 for (User *U2 : EI->users()) {
659 if (auto *PN = dyn_cast<PHINode>(U2))
660 EHVals.insert(PN);
661 }
662 }
663 }
664
Reid Klecknerfd7df282015-04-22 21:05:21 +0000665 SetVector<Argument *> ArgsToDemote;
666 SetVector<Instruction *> InstrsToDemote;
667 for (BasicBlock &BB : F) {
668 bool IsNormalBB = NormalBlocks.count(&BB);
669 bool IsEHBB = EHBlocks.count(&BB);
670 if (!IsNormalBB && !IsEHBB)
671 continue; // Blocks that are neither normal nor EH are unreachable.
672 for (Instruction &I : BB) {
673 for (Value *Op : I.operands()) {
674 // Don't demote static allocas, constants, and labels.
675 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
676 continue;
677 auto *AI = dyn_cast<AllocaInst>(Op);
678 if (AI && AI->isStaticAlloca())
679 continue;
680
681 if (auto *Arg = dyn_cast<Argument>(Op)) {
682 if (IsEHBB) {
683 DEBUG(dbgs() << "Demoting argument " << *Arg
684 << " used by EH instr: " << I << "\n");
685 ArgsToDemote.insert(Arg);
686 }
687 continue;
688 }
689
Reid Kleckner7ea77082015-07-10 22:21:54 +0000690 // Don't demote EH values.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000691 auto *OpI = cast<Instruction>(Op);
Reid Kleckner7ea77082015-07-10 22:21:54 +0000692 if (EHVals.count(OpI))
693 continue;
694
Reid Klecknerfd7df282015-04-22 21:05:21 +0000695 BasicBlock *OpBB = OpI->getParent();
696 // If a value is produced and consumed in the same BB, we don't need to
697 // demote it.
698 if (OpBB == &BB)
699 continue;
700 bool IsOpNormalBB = NormalBlocks.count(OpBB);
701 bool IsOpEHBB = EHBlocks.count(OpBB);
702 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
703 DEBUG({
704 dbgs() << "Demoting instruction live in-out from EH:\n";
705 dbgs() << "Instr: " << *OpI << '\n';
706 dbgs() << "User: " << I << '\n';
707 });
708 InstrsToDemote.insert(OpI);
709 }
710 }
711 }
712 }
713
714 // Demote values live into and out of handlers.
715 // FIXME: This demotion is inefficient. We should insert spills at the point
716 // of definition, insert one reload in each handler that uses the value, and
717 // insert reloads in the BB used to rejoin normal control flow.
718 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
719 for (Instruction *I : InstrsToDemote)
720 DemoteRegToStack(*I, false, AllocaInsertPt);
721
722 // Demote arguments separately, and only for uses in EH blocks.
723 for (Argument *Arg : ArgsToDemote) {
724 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
725 Arg->getName() + ".reg2mem", AllocaInsertPt);
726 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
727 for (User *U : Users) {
728 auto *I = dyn_cast<Instruction>(U);
729 if (I && EHBlocks.count(I->getParent())) {
730 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
731 U->replaceUsesOfWith(Arg, Reload);
732 }
733 }
734 new StoreInst(Arg, Slot, AllocaInsertPt);
735 }
736
737 // Demote landingpad phis, as the landingpad will be removed from the machine
738 // CFG.
739 for (LandingPadInst *LPI : LPads) {
740 BasicBlock *BB = LPI->getParent();
741 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
742 DemotePHIToStack(Phi, AllocaInsertPt);
743 }
744
745 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
746 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
747}
748
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000749bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000750 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000751 // Don't run on functions that are already prepared.
752 for (LandingPadInst *LPad : LPads) {
753 BasicBlock *LPadBB = LPad->getParent();
754 for (Instruction &Inst : *LPadBB)
755 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
756 return false;
757 }
758
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000759 identifyEHBlocks(F, LPads);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000760 demoteValuesLiveAcrossHandlers(F, LPads);
761
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000762 // These containers are used to re-map frame variables that are used in
763 // outlined catch and cleanup handlers. They will be populated as the
764 // handlers are outlined.
765 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000766
767 bool HandlersOutlined = false;
768
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000769 Module *M = F.getParent();
770 LLVMContext &Context = M->getContext();
771
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000772 // Create a new function to receive the handler contents.
773 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
774 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000775 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000776
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000777 if (isAsynchronousEHPersonality(Personality)) {
778 // FIXME: Switch the ehptr type to i32 and then switch this.
779 SEHExceptionCodeSlot =
780 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
781 F.getEntryBlock().getFirstInsertionPt());
782 }
783
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000784 // In order to handle the case where one outlined catch handler returns
785 // to a block within another outlined catch handler that would otherwise
786 // be unreachable, we need to outline the nested landing pad before we
787 // outline the landing pad which encloses it.
Manuel Klimekb00d42c2015-05-21 15:38:25 +0000788 if (!isAsynchronousEHPersonality(Personality))
789 std::sort(LPads.begin(), LPads.end(),
790 [this](LandingPadInst *const &L, LandingPadInst *const &R) {
791 return DT->properlyDominates(R->getParent(), L->getParent());
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000792 });
793
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000794 // This container stores the llvm.eh.recover and IndirectBr instructions
795 // that make up the body of each landing pad after it has been outlined.
796 // We need to defer the population of the target list for the indirectbr
797 // until all landing pads have been outlined so that we can handle the
798 // case of blocks in the target that are reached only from nested
799 // landing pads.
800 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
801
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000802 for (LandingPadInst *LPad : LPads) {
803 // Look for evidence that this landingpad has already been processed.
804 bool LPadHasActionList = false;
805 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000806 for (Instruction &Inst : *LPadBB) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000807 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
808 LPadHasActionList = true;
809 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000810 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000811 }
812
813 // If we've already outlined the handlers for this landingpad,
814 // there's nothing more to do here.
815 if (LPadHasActionList)
816 continue;
817
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000818 // If either of the values in the aggregate returned by the landing pad is
819 // extracted and stored to memory, promote the stored value to a register.
820 promoteLandingPadValues(LPad);
821
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000822 LandingPadActions Actions;
823 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000824
Reid Kleckner9405ef02015-04-10 23:12:29 +0000825 HandlersOutlined |= !Actions.actions().empty();
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000826 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000827 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000828 continue;
829 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000830
831 // SEH doesn't do any outlining for catches. Instead, pass the handler
832 // basic block addr to llvm.eh.actions and list the block as a return
833 // target.
834 if (isAsynchronousEHPersonality(Personality)) {
835 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
836 processSEHCatchHandler(CatchAction, StartBB);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000837 continue;
838 }
839 }
840
Reid Kleckner9405ef02015-04-10 23:12:29 +0000841 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
842 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000843
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000844 // Split the block after the landingpad instruction so that it is just a
845 // call to llvm.eh.actions followed by indirectbr.
846 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000847 SplitBlock(LPadBB, LPad->getNextNode(), DT);
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000848 // Erase the branch inserted by the split so we can insert indirectbr.
849 LPadBB->getTerminator()->eraseFromParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000850
Reid Klecknere3af86e2015-04-23 21:22:30 +0000851 // Replace all extracted values with undef and ultimately replace the
852 // landingpad with undef.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000853 SmallVector<Instruction *, 4> SEHCodeUses;
854 SmallVector<Instruction *, 4> EHUndefs;
Reid Klecknere3af86e2015-04-23 21:22:30 +0000855 for (User *U : LPad->users()) {
856 auto *E = dyn_cast<ExtractValueInst>(U);
857 if (!E)
858 continue;
859 assert(E->getNumIndices() == 1 &&
860 "Unexpected operation: extracting both landing pad values");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000861 unsigned Idx = *E->idx_begin();
862 assert((Idx == 0 || Idx == 1) && "unexpected index");
863 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
864 SEHCodeUses.push_back(E);
865 else
866 EHUndefs.push_back(E);
Reid Klecknere3af86e2015-04-23 21:22:30 +0000867 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000868 for (Instruction *E : EHUndefs) {
Reid Klecknere3af86e2015-04-23 21:22:30 +0000869 E->replaceAllUsesWith(UndefValue::get(E->getType()));
870 E->eraseFromParent();
871 }
872 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000873
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000874 // Rewrite uses of the exception pointer to loads of an alloca.
Reid Kleckner7ea77082015-07-10 22:21:54 +0000875 while (!SEHCodeUses.empty()) {
876 Instruction *E = SEHCodeUses.pop_back_val();
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000877 SmallVector<Use *, 4> Uses;
878 for (Use &U : E->uses())
879 Uses.push_back(&U);
880 for (Use *U : Uses) {
881 auto *I = cast<Instruction>(U->getUser());
882 if (isa<ResumeInst>(I))
883 continue;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000884 if (auto *Phi = dyn_cast<PHINode>(I))
Reid Kleckner7ea77082015-07-10 22:21:54 +0000885 SEHCodeUses.push_back(Phi);
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000886 else
Reid Kleckner7ea77082015-07-10 22:21:54 +0000887 U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000888 }
889 E->replaceAllUsesWith(UndefValue::get(E->getType()));
890 E->eraseFromParent();
891 }
892
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000893 // Add a call to describe the actions for this landing pad.
894 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000895 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000896 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000897 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000898 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000899 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000900 // Find the frame escape index of the exception object alloca in the
901 // parent.
902 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000903 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000904 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
905 auto I = FrameVarInfo.find(EHObj);
906 assert(I != FrameVarInfo.end() &&
907 "failed to map llvm.eh.begincatch var");
908 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
909 }
910 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000911 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000912 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000913 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000914 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000915 }
916 CallInst *Recover =
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000917 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000918
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000919 SetVector<BasicBlock *> ReturnTargets;
920 for (ActionHandler *Action : Actions) {
921 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
922 const auto &CatchTargets = CatchAction->getReturnTargets();
923 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000924 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000925 }
926 IndirectBrInst *Branch =
927 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
928 for (BasicBlock *Target : ReturnTargets)
929 Branch->addDestination(Target);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000930
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000931 if (!isAsynchronousEHPersonality(Personality)) {
932 // C++ EH must repopulate the targets later to handle the case of
933 // targets that are reached indirectly through nested landing pads.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000934 LPadImpls.push_back(std::make_pair(Recover, Branch));
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000935 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000936
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000937 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000938
939 // If nothing got outlined, there is no more processing to be done.
940 if (!HandlersOutlined)
941 return false;
942
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000943 // Replace any nested landing pad stubs with the correct action handler.
944 // This must be done before we remove unreachable blocks because it
945 // cleans up references to outlined blocks that will be deleted.
946 for (auto &LPadPair : NestedLPtoOriginalLP)
947 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
Andrew Kaylor67d3c032015-04-08 20:57:22 +0000948 NestedLPtoOriginalLP.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000949
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000950 // Update the indirectbr instructions' target lists if necessary.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000951 SetVector<BasicBlock*> CheckedTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000952 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000953 for (auto &LPadImplPair : LPadImpls) {
954 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
955 IndirectBrInst *Branch = LPadImplPair.second;
956
957 // Get a list of handlers called by
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000958 parseEHActions(Recover, ActionList);
959
960 // Add an indirect branch listing possible successors of the catch handlers.
961 SetVector<BasicBlock *> ReturnTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000962 for (const auto &Action : ActionList) {
963 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000964 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
965 getPossibleReturnTargets(&F, Handler, ReturnTargets);
966 }
967 }
Andrew Kaylor0ddaf2b2015-05-12 00:13:51 +0000968 ActionList.clear();
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000969 // Clear any targets we already knew about.
970 for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
971 BasicBlock *KnownTarget = Branch->getDestination(I);
972 if (ReturnTargets.count(KnownTarget))
973 ReturnTargets.remove(KnownTarget);
974 }
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000975 for (BasicBlock *Target : ReturnTargets) {
976 Branch->addDestination(Target);
977 // The target may be a block that we excepted to get pruned.
978 // If it is, it may contain a call to llvm.eh.endcatch.
979 if (CheckedTargets.insert(Target)) {
980 // Earlier preparations guarantee that all calls to llvm.eh.endcatch
981 // will be followed by an unconditional branch.
982 auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
983 if (Br && Br->isUnconditional() &&
984 Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
985 Instruction *Prev = Br->getPrevNode();
986 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
987 Prev->eraseFromParent();
988 }
989 }
990 }
991 }
992 LPadImpls.clear();
993
David Majnemercde33032015-03-30 22:58:10 +0000994 F.addFnAttr("wineh-parent", F.getName());
995
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000996 // Delete any blocks that were only used by handlers that were outlined above.
997 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000998
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000999 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001000 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001001 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001002
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001003 Function *FrameEscapeFn =
Reid Kleckner60381792015-07-07 22:25:32 +00001004 Intrinsic::getDeclaration(M, Intrinsic::localescape);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001005 Function *RecoverFrameFn =
Reid Kleckner60381792015-07-07 22:25:32 +00001006 Intrinsic::getDeclaration(M, Intrinsic::localrecover);
Reid Klecknerf14787d2015-04-22 00:07:52 +00001007 SmallVector<Value *, 8> AllocasToEscape;
1008
Reid Kleckner60381792015-07-07 22:25:32 +00001009 // Scan the entry block for an existing call to llvm.localescape. We need to
Reid Klecknerf14787d2015-04-22 00:07:52 +00001010 // keep escaping those objects.
1011 for (Instruction &I : F.front()) {
1012 auto *II = dyn_cast<IntrinsicInst>(&I);
Reid Kleckner60381792015-07-07 22:25:32 +00001013 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
Reid Klecknerf14787d2015-04-22 00:07:52 +00001014 auto Args = II->arg_operands();
1015 AllocasToEscape.append(Args.begin(), Args.end());
1016 II->eraseFromParent();
1017 break;
1018 }
1019 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001020
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001021 // Finally, replace all of the temporary allocas for frame variables used in
Reid Kleckner60381792015-07-07 22:25:32 +00001022 // the outlined handlers with calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001023 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +00001024 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001025 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Reid Klecknerfd7df282015-04-22 21:05:21 +00001026 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
Andrew Kaylor72029c62015-03-03 00:41:03 +00001027
Reid Klecknerb4019412015-04-06 18:50:38 +00001028 // FIXME: We should try to sink unescaped allocas from the parent frame into
1029 // the child frame. If the alloca is escaped, we have to use the lifetime
1030 // markers to ensure that the alloca is only live within the child frame.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001031
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001032 // Add this alloca to the list of things to escape.
1033 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001034
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001035 // Next replace all outlined allocas that are mapped to it.
1036 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +00001037 if (TempAlloca == getCatchObjectSentinel())
1038 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001039 Function *HandlerFn = TempAlloca->getParent()->getParent();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001040 llvm::Value *FP = HandlerToParentFP[HandlerFn];
1041 assert(FP);
1042
Reid Kleckner60381792015-07-07 22:25:32 +00001043 // FIXME: Sink this localrecover into the blocks where it is used.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001044 Builder.SetInsertPoint(TempAlloca);
1045 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1046 Value *RecoverArgs[] = {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001047 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001048 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001049 Instruction *RecoveredAlloca =
1050 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1051
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001052 // Add a pointer bitcast if the alloca wasn't an i8.
1053 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1054 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001055 RecoveredAlloca = cast<Instruction>(
1056 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001057 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001058 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1059 TempAlloca->removeFromParent();
1060 RecoveredAlloca->takeName(TempAlloca);
1061 delete TempAlloca;
1062 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001063 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001064
Reid Kleckner60381792015-07-07 22:25:32 +00001065 // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001066 // block.
1067 Builder.SetInsertPoint(&F.getEntryBlock().back());
1068 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1069
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001070 if (SEHExceptionCodeSlot) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00001071 if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1072 SmallPtrSet<BasicBlock *, 4> UserBlocks;
1073 for (User *U : SEHExceptionCodeSlot->users()) {
1074 if (auto *Inst = dyn_cast<Instruction>(U))
1075 UserBlocks.insert(Inst->getParent());
1076 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001077 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001078 // After the promotion, kill off dead instructions.
1079 for (BasicBlock *BB : UserBlocks)
1080 SimplifyInstructionsInBlock(BB, LibInfo);
1081 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001082 }
1083
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001084 // Clean up the handler action maps we created for this function
1085 DeleteContainerSeconds(CatchHandlerMap);
1086 CatchHandlerMap.clear();
1087 DeleteContainerSeconds(CleanupHandlerMap);
1088 CleanupHandlerMap.clear();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001089 HandlerToParentFP.clear();
1090 DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +00001091 LibInfo = nullptr;
Ahmed Bougachaed363c52015-05-06 01:28:58 +00001092 SEHExceptionCodeSlot = nullptr;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001093 EHBlocks.clear();
1094 NormalBlocks.clear();
1095 EHReturnBlocks.clear();
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001096
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001097 return HandlersOutlined;
1098}
1099
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001100void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1101 // If the return values of the landing pad instruction are extracted and
1102 // stored to memory, we want to promote the store locations to reg values.
1103 SmallVector<AllocaInst *, 2> EHAllocas;
1104
1105 // The landingpad instruction returns an aggregate value. Typically, its
1106 // value will be passed to a pair of extract value instructions and the
1107 // results of those extracts are often passed to store instructions.
1108 // In unoptimized code the stored value will often be loaded and then stored
1109 // again.
1110 for (auto *U : LPad->users()) {
1111 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1112 if (!Extract)
1113 continue;
1114
1115 for (auto *EU : Extract->users()) {
1116 if (auto *Store = dyn_cast<StoreInst>(EU)) {
1117 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1118 EHAllocas.push_back(AV);
1119 }
1120 }
1121 }
1122
1123 // We can't do this without a dominator tree.
1124 assert(DT);
1125
1126 if (!EHAllocas.empty()) {
1127 PromoteMemToReg(EHAllocas, *DT);
1128 EHAllocas.clear();
1129 }
Reid Kleckner86762142015-04-16 00:02:04 +00001130
1131 // After promotion, some extracts may be trivially dead. Remove them.
1132 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1133 for (auto *U : Users)
1134 RecursivelyDeleteTriviallyDeadInstructions(U);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001135}
1136
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001137void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1138 Function *HandlerF,
1139 SetVector<BasicBlock*> &Targets) {
1140 for (BasicBlock &BB : *HandlerF) {
1141 // If the handler contains landing pads, check for any
1142 // handlers that may return directly to a block in the
1143 // parent function.
1144 if (auto *LPI = BB.getLandingPadInst()) {
1145 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
Benjamin Kramera48e0652015-05-16 15:40:03 +00001146 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001147 parseEHActions(Recover, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001148 for (const auto &Action : ActionList) {
1149 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001150 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1151 getPossibleReturnTargets(ParentF, NestedF, Targets);
1152 }
1153 }
1154 }
1155
1156 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1157 if (!Ret)
1158 continue;
1159
1160 // Handler functions must always return a block address.
1161 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1162
1163 // If this is the handler for a nested landing pad, the
1164 // return address may have been remapped to a block in the
1165 // parent handler. We're not interested in those.
1166 if (BA->getFunction() != ParentF)
1167 continue;
1168
1169 Targets.insert(BA->getBasicBlock());
1170 }
1171}
1172
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001173void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1174 LandingPadInst *OutlinedLPad,
1175 const LandingPadInst *OriginalLPad,
1176 FrameVarInfoMap &FrameVarInfo) {
1177 // Get the nested block and erase the unreachable instruction that was
1178 // temporarily inserted as its terminator.
1179 LLVMContext &Context = ParentFn->getContext();
1180 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001181 // If the nested landing pad was outlined before the landing pad that enclosed
1182 // it, it will already be in outlined form. In that case, we just need to see
1183 // if the returns and the enclosing branch instruction need to be updated.
1184 IndirectBrInst *Branch =
1185 dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1186 if (!Branch) {
1187 // If the landing pad wasn't in outlined form, it should be a stub with
1188 // an unreachable terminator.
1189 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1190 OutlinedBB->getTerminator()->eraseFromParent();
1191 // That should leave OutlinedLPad as the last instruction in its block.
1192 assert(&OutlinedBB->back() == OutlinedLPad);
1193 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001194
1195 // The original landing pad will have already had its action intrinsic
1196 // built by the outlining loop. We need to clone that into the outlined
1197 // location. It may also be necessary to add references to the exception
1198 // variables to the outlined handler in which this landing pad is nested
1199 // and remap return instructions in the nested handlers that should return
1200 // to an address in the outlined handler.
1201 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001202 BasicBlock::const_iterator II = OriginalLPad;
1203 ++II;
1204 // The instruction after the landing pad should now be a call to eh.actions.
1205 const Instruction *Recover = II;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001206 const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001207
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001208 // Remap the return target in the nested handler.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001209 SmallVector<BlockAddress *, 4> ActionTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +00001210 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001211 parseEHActions(EHActions, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001212 for (const auto &Action : ActionList) {
1213 auto *Catch = dyn_cast<CatchHandler>(Action.get());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001214 if (!Catch)
1215 continue;
1216 // The dyn_cast to function here selects C++ catch handlers and skips
1217 // SEH catch handlers.
1218 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1219 if (!Handler)
1220 continue;
1221 // Visit all the return instructions, looking for places that return
1222 // to a location within OutlinedHandlerFn.
1223 for (BasicBlock &NestedHandlerBB : *Handler) {
1224 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1225 if (!Ret)
1226 continue;
1227
1228 // Handler functions must always return a block address.
1229 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1230 // The original target will have been in the main parent function,
1231 // but if it is the address of a block that has been outlined, it
1232 // should be a block that was outlined into OutlinedHandlerFn.
1233 assert(BA->getFunction() == ParentFn);
1234
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001235 // Ignore targets that aren't part of an outlined handler function.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001236 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1237 continue;
1238
1239 // If the return value is the address ofF a block that we
1240 // previously outlined into the parent handler function, replace
1241 // the return instruction and add the mapped target to the list
1242 // of possible return addresses.
1243 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1244 assert(MappedBB->getParent() == OutlinedHandlerFn);
1245 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1246 Ret->eraseFromParent();
1247 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1248 ActionTargets.push_back(NewBA);
1249 }
1250 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +00001251 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001252
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001253 if (Branch) {
1254 // If the landing pad was already in outlined form, just update its targets.
1255 for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1256 Branch->removeDestination(I);
1257 // Add the previously collected action targets.
1258 for (auto *Target : ActionTargets)
1259 Branch->addDestination(Target->getBasicBlock());
1260 } else {
1261 // If the landing pad was previously stubbed out, fill in its outlined form.
1262 IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1263 OutlinedBB->getInstList().push_back(NewEHActions);
1264
1265 // Insert an indirect branch into the outlined landing pad BB.
1266 IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1267 // Add the previously collected action targets.
1268 for (auto *Target : ActionTargets)
1269 IBr->addDestination(Target->getBasicBlock());
1270 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001271}
1272
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001273// This function examines a block to determine whether the block ends with a
1274// conditional branch to a catch handler based on a selector comparison.
1275// This function is used both by the WinEHPrepare::findSelectorComparison() and
1276// WinEHCleanupDirector::handleTypeIdFor().
1277static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1278 Constant *&Selector, BasicBlock *&NextBB) {
1279 ICmpInst::Predicate Pred;
1280 BasicBlock *TBB, *FBB;
1281 Value *LHS, *RHS;
1282
1283 if (!match(BB->getTerminator(),
1284 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1285 return false;
1286
1287 if (!match(LHS,
1288 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1289 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1290 return false;
1291
1292 if (Pred == CmpInst::ICMP_EQ) {
1293 CatchHandler = TBB;
1294 NextBB = FBB;
1295 return true;
1296 }
1297
1298 if (Pred == CmpInst::ICMP_NE) {
1299 CatchHandler = FBB;
1300 NextBB = TBB;
1301 return true;
1302 }
1303
1304 return false;
1305}
1306
Andrew Kaylor41758512015-04-20 22:04:09 +00001307static bool isCatchBlock(BasicBlock *BB) {
1308 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1309 II != IE; ++II) {
1310 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1311 return true;
1312 }
1313 return false;
1314}
1315
David Majnemer7fddecc2015-06-17 20:52:32 +00001316static BasicBlock *createStubLandingPad(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001317 // FIXME: Finish this!
1318 LLVMContext &Context = Handler->getContext();
1319 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1320 Handler->getBasicBlockList().push_back(StubBB);
1321 IRBuilder<> Builder(StubBB);
1322 LandingPadInst *LPad = Builder.CreateLandingPad(
1323 llvm::StructType::get(Type::getInt8PtrTy(Context),
1324 Type::getInt32Ty(Context), nullptr),
David Majnemer7fddecc2015-06-17 20:52:32 +00001325 0);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001326 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
Andrew Kaylor91307432015-04-28 22:01:51 +00001327 Function *ActionIntrin =
1328 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
David Blaikieff6409d2015-05-18 22:13:54 +00001329 Builder.CreateCall(ActionIntrin, {}, "recover");
Andrew Kaylorbb111322015-04-07 21:30:23 +00001330 LPad->setCleanup(true);
1331 Builder.CreateUnreachable();
1332 return StubBB;
1333}
1334
1335// Cycles through the blocks in an outlined handler function looking for an
1336// invoke instruction and inserts an invoke of llvm.donothing with an empty
1337// landing pad if none is found. The code that generates the .xdata tables for
1338// the handler needs at least one landing pad to identify the parent function's
1339// personality.
David Majnemer7fddecc2015-06-17 20:52:32 +00001340void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001341 ReturnInst *Ret = nullptr;
Andrew Kaylor5f715522015-04-23 18:37:39 +00001342 UnreachableInst *Unreached = nullptr;
Andrew Kaylorbb111322015-04-07 21:30:23 +00001343 for (BasicBlock &BB : *Handler) {
1344 TerminatorInst *Terminator = BB.getTerminator();
1345 // If we find an invoke, there is nothing to be done.
1346 auto *II = dyn_cast<InvokeInst>(Terminator);
1347 if (II)
1348 return;
1349 // If we've already recorded a return instruction, keep looking for invokes.
Andrew Kaylor5f715522015-04-23 18:37:39 +00001350 if (!Ret)
1351 Ret = dyn_cast<ReturnInst>(Terminator);
1352 // If we haven't recorded an unreachable instruction, try this terminator.
1353 if (!Unreached)
1354 Unreached = dyn_cast<UnreachableInst>(Terminator);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001355 }
1356
1357 // If we got this far, the handler contains no invokes. We should have seen
Andrew Kaylor5f715522015-04-23 18:37:39 +00001358 // at least one return or unreachable instruction. We'll insert an invoke of
1359 // llvm.donothing ahead of that instruction.
1360 assert(Ret || Unreached);
1361 TerminatorInst *Term;
1362 if (Ret)
1363 Term = Ret;
1364 else
1365 Term = Unreached;
1366 BasicBlock *OldRetBB = Term->getParent();
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001367 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001368 // SplitBlock adds an unconditional branch instruction at the end of the
1369 // parent block. We want to replace that with an invoke call, so we can
1370 // erase it now.
1371 OldRetBB->getTerminator()->eraseFromParent();
David Majnemer7fddecc2015-06-17 20:52:32 +00001372 BasicBlock *StubLandingPad = createStubLandingPad(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001373 Function *F =
1374 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1375 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1376}
1377
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001378// FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1379// usually doesn't build LLVM IR, so that's probably the wrong place.
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001380Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1381 const Twine &Name, Module *M,
1382 Value *&ParentFP) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001383 // x64 uses a two-argument prototype where the parent FP is the second
1384 // argument. x86 uses no arguments, just the incoming EBP value.
1385 LLVMContext &Context = M->getContext();
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001386 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001387 FunctionType *FnType;
1388 if (TheTriple.getArch() == Triple::x86_64) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001389 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1390 FnType = FunctionType::get(RetTy, ArgTys, false);
1391 } else {
1392 FnType = FunctionType::get(RetTy, None, false);
1393 }
1394
1395 Function *Handler =
1396 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1397 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1398 Handler->getBasicBlockList().push_front(Entry);
1399 if (TheTriple.getArch() == Triple::x86_64) {
1400 ParentFP = &(Handler->getArgumentList().back());
1401 } else {
1402 assert(M);
1403 Function *FrameAddressFn =
1404 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001405 Function *RecoverFPFn =
1406 Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1407 IRBuilder<> Builder(&Handler->getEntryBlock());
1408 Value *EBP =
1409 Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1410 Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1411 ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001412 }
1413 return Handler;
1414}
1415
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001416bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1417 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001418 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001419 Module *M = SrcFn->getParent();
1420 LLVMContext &Context = M->getContext();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001421 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001422
1423 // Create a new function to receive the handler contents.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001424 Value *ParentFP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001425 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001426 if (Action->getType() == Catch) {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001427 Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001428 ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001429 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001430 Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001431 SrcFn->getName() + ".cleanup", M, ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001432 }
David Majnemer7fddecc2015-06-17 20:52:32 +00001433 Handler->setPersonalityFn(SrcFn->getPersonalityFn());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001434 HandlerToParentFP[Handler] = ParentFP;
David Majnemercde33032015-03-30 22:58:10 +00001435 Handler->addFnAttr("wineh-parent", SrcFn->getName());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001436 BasicBlock *Entry = &Handler->getEntryBlock();
David Majnemercde33032015-03-30 22:58:10 +00001437
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001438 // Generate a standard prolog to setup the frame recovery structure.
1439 IRBuilder<> Builder(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001440 Builder.SetInsertPoint(Entry);
1441 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1442
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001443 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001444
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001445 ValueToValueMapTy VMap;
1446
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001447 LandingPadMap &LPadMap = LPadMaps[LPad];
1448 if (!LPadMap.isInitialized())
1449 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001450 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1451 Constant *Sel = CatchAction->getSelector();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001452 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1453 LPadMap, NestedLPtoOriginalLP, DT,
1454 EHBlocks));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001455 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1456 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001457 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001458 Director.reset(
1459 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001460 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1461 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001462 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001463
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001464 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001465 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001466
Andrew Kaylor3170e562015-03-20 21:42:54 +00001467 // If the start block contains PHI nodes, we need to map them.
1468 BasicBlock::iterator II = StartBB->begin();
1469 while (auto *PN = dyn_cast<PHINode>(II)) {
1470 bool Mapped = false;
1471 // Look for PHI values that we have already mapped (such as the selector).
1472 for (Value *Val : PN->incoming_values()) {
1473 if (VMap.count(Val)) {
1474 VMap[PN] = VMap[Val];
1475 Mapped = true;
1476 }
1477 }
1478 // If we didn't find a match for this value, map it as an undef.
1479 if (!Mapped) {
1480 VMap[PN] = UndefValue::get(PN->getType());
1481 }
1482 ++II;
1483 }
1484
Andrew Kaylor00e5d9e2015-04-20 22:53:42 +00001485 // The landing pad value may be used by PHI nodes. It will ultimately be
1486 // eliminated, but we need it in the map for intermediate handling.
1487 VMap[LPad] = UndefValue::get(LPad->getType());
1488
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001489 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +00001490 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001491
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001492 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001493 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001494 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001495
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001496 // Move all the instructions in the cloned "entry" block into our entry block.
1497 // Depending on how the parent function was laid out, the block that will
1498 // correspond to the outlined entry block may not be the first block in the
1499 // list. We can recognize it, however, as the cloned block which has no
1500 // predecessors. Any other block wouldn't have been cloned if it didn't
1501 // have a predecessor which was also cloned.
Andrew Kaylor91307432015-04-28 22:01:51 +00001502 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001503 while (!pred_empty(ClonedIt))
1504 ++ClonedIt;
1505 BasicBlock *ClonedEntryBB = ClonedIt;
1506 assert(ClonedEntryBB);
1507 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1508 ClonedEntryBB->eraseFromParent();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001509
Andrew Kaylorbb111322015-04-07 21:30:23 +00001510 // Make sure we can identify the handler's personality later.
David Majnemer7fddecc2015-06-17 20:52:32 +00001511 addStubInvokeToHandlerIfNeeded(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001512
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001513 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1514 WinEHCatchDirector *CatchDirector =
1515 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1516 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1517 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001518
1519 // Look for blocks that are not part of the landing pad that we just
1520 // outlined but terminate with a call to llvm.eh.endcatch and a
1521 // branch to a block that is in the handler we just outlined.
1522 // These blocks will be part of a nested landing pad that intends to
1523 // return to an address in this handler. This case is best handled
1524 // after both landing pads have been outlined, so for now we'll just
1525 // save the association of the blocks in LPadTargetBlocks. The
1526 // return instructions which are created from these branches will be
1527 // replaced after all landing pads have been outlined.
Richard Trieu6b1aa5f2015-04-15 01:21:15 +00001528 for (const auto MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001529 // VMap maps all values and blocks that were just cloned, but dead
1530 // blocks which were pruned will map to nullptr.
1531 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1532 continue;
1533 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1534 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1535 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1536 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1537 continue;
1538 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1539 --II;
1540 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1541 // This would indicate that a nested landing pad wants to return
1542 // to a block that is outlined into two different handlers.
1543 assert(!LPadTargetBlocks.count(MappedBB));
1544 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1545 }
1546 }
1547 }
1548 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001549
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001550 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001551
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001552 return true;
1553}
1554
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001555/// This BB must end in a selector dispatch. All we need to do is pass the
1556/// handler block to llvm.eh.actions and list it as a possible indirectbr
1557/// target.
1558void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1559 BasicBlock *StartBB) {
1560 BasicBlock *HandlerBB;
1561 BasicBlock *NextBB;
1562 Constant *Selector;
1563 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1564 if (Res) {
1565 // If this was EH dispatch, this must be a conditional branch to the handler
1566 // block.
1567 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1568 // leading to crashes if some optimization hoists stuff here.
1569 assert(CatchAction->getSelector() && HandlerBB &&
1570 "expected catch EH dispatch");
1571 } else {
1572 // This must be a catch-all. Split the block after the landingpad.
1573 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001574 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001575 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001576 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1577 Function *EHCodeFn = Intrinsic::getDeclaration(
1578 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
David Blaikieff6409d2015-05-18 22:13:54 +00001579 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001580 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1581 Builder.CreateStore(Code, SEHExceptionCodeSlot);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001582 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1583 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1584 CatchAction->setReturnTargets(Targets);
1585}
1586
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001587void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1588 // Each instance of this class should only ever be used to map a single
1589 // landing pad.
1590 assert(OriginLPad == nullptr || OriginLPad == LPad);
1591
1592 // If the landing pad has already been mapped, there's nothing more to do.
1593 if (OriginLPad == LPad)
1594 return;
1595
1596 OriginLPad = LPad;
1597
1598 // The landingpad instruction returns an aggregate value. Typically, its
1599 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001600 // results of those extracts will have been promoted to reg values before
1601 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001602 for (auto *U : LPad->users()) {
1603 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1604 if (!Extract)
1605 continue;
1606 assert(Extract->getNumIndices() == 1 &&
1607 "Unexpected operation: extracting both landing pad values");
1608 unsigned int Idx = *(Extract->idx_begin());
1609 assert((Idx == 0 || Idx == 1) &&
1610 "Unexpected operation: extracting an unknown landing pad element");
1611 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001612 ExtractedEHPtrs.push_back(Extract);
1613 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001614 ExtractedSelectors.push_back(Extract);
1615 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001616 }
1617}
1618
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001619bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1620 return BB->getLandingPadInst() == OriginLPad;
1621}
1622
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001623bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1624 if (Inst == OriginLPad)
1625 return true;
1626 for (auto *Extract : ExtractedEHPtrs) {
1627 if (Inst == Extract)
1628 return true;
1629 }
1630 for (auto *Extract : ExtractedSelectors) {
1631 if (Inst == Extract)
1632 return true;
1633 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001634 return false;
1635}
1636
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001637void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1638 Value *SelectorValue) const {
1639 // Remap all landing pad extract instructions to the specified values.
1640 for (auto *Extract : ExtractedEHPtrs)
1641 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001642 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001643 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001644}
1645
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001646static bool isLocalAddressCall(const Value *V) {
1647 return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
Reid Klecknerf14787d2015-04-22 00:07:52 +00001648}
1649
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001650CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001651 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001652 // If this is one of the boilerplate landing pad instructions, skip it.
1653 // The instruction will have already been remapped in VMap.
1654 if (LPadMap.isLandingPadSpecificInst(Inst))
1655 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001656
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001657 // Nested landing pads that have not already been outlined will be cloned as
1658 // stubs, with just the landingpad instruction and an unreachable instruction.
1659 // When all landingpads have been outlined, we'll replace this with the
1660 // llvm.eh.actions call and indirect branch created when the landing pad was
1661 // outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001662 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1663 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001664 }
1665
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001666 // Nested landing pads that have already been outlined will be cloned in their
1667 // outlined form, but we need to intercept the ibr instruction to filter out
1668 // targets that do not return to the handler we are outlining.
1669 if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1670 return handleIndirectBr(VMap, IBr, NewBB);
1671 }
1672
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001673 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1674 return handleInvoke(VMap, Invoke, NewBB);
1675
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001676 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1677 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001678
Andrew Kaylorea8df612015-04-17 23:05:43 +00001679 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1680 return handleCompare(VMap, Cmp, NewBB);
1681
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001682 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1683 return handleBeginCatch(VMap, Inst, NewBB);
1684 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1685 return handleEndCatch(VMap, Inst, NewBB);
1686 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1687 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001688
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001689 // When outlining llvm.localaddress(), remap that to the second argument,
Reid Klecknerf14787d2015-04-22 00:07:52 +00001690 // which is the FP of the parent.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001691 if (isLocalAddressCall(Inst)) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001692 VMap[Inst] = ParentFP;
Reid Klecknerf14787d2015-04-22 00:07:52 +00001693 return CloningDirector::SkipInstruction;
1694 }
1695
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001696 // Continue with the default cloning behavior.
1697 return CloningDirector::CloneInstruction;
1698}
1699
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001700CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1701 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001702 // If the instruction after the landing pad is a call to llvm.eh.actions
1703 // the landing pad has already been outlined. In this case, we should
1704 // clone it because it may return to a block in the handler we are
1705 // outlining now that would otherwise be unreachable. The landing pads
1706 // are sorted before outlining begins to enable this case to work
1707 // properly.
1708 const Instruction *NextI = LPad->getNextNode();
1709 if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1710 return CloningDirector::CloneInstruction;
1711
1712 // If the landing pad hasn't been outlined yet, the landing pad we are
1713 // outlining now does not dominate it and so it cannot return to a block
1714 // in this handler. In that case, we can just insert a stub landing
1715 // pad now and patch it up later.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001716 Instruction *NewInst = LPad->clone();
1717 if (LPad->hasName())
1718 NewInst->setName(LPad->getName());
1719 // Save this correlation for later processing.
1720 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1721 VMap[LPad] = NewInst;
1722 BasicBlock::InstListType &InstList = NewBB->getInstList();
1723 InstList.push_back(NewInst);
1724 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1725 return CloningDirector::StopCloningBB;
1726}
1727
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001728CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1729 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1730 // The argument to the call is some form of the first element of the
1731 // landingpad aggregate value, but that doesn't matter. It isn't used
1732 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001733 // The second argument is an outparameter where the exception object will be
1734 // stored. Typically the exception object is a scalar, but it can be an
1735 // aggregate when catching by value.
1736 // FIXME: Leave something behind to indicate where the exception object lives
1737 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001738 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1739 "llvm.eh.begincatch found while "
1740 "outlining catch handler.");
1741 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001742 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1743 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001744 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1745 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001746 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001747 return CloningDirector::SkipInstruction;
1748}
1749
1750CloningDirector::CloningAction
1751WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1752 const Instruction *Inst, BasicBlock *NewBB) {
1753 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1754 // It might be interesting to track whether or not we are inside a catch
1755 // function, but that might make the algorithm more brittle than it needs
1756 // to be.
1757
1758 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001759 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001760 // or at the end of the catch block. However, a catch-all handler may call
1761 // end catch from the original landing pad. If the call occurs in a nested
1762 // landing pad block, we must skip it and continue so that the landing pad
1763 // gets cloned.
1764 auto *ParentBB = IntrinCall->getParent();
1765 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001766 return CloningDirector::SkipInstruction;
1767
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001768 // If an end catch occurs anywhere else we want to terminate the handler
1769 // with a return to the code that follows the endcatch call. If the
1770 // next instruction is not an unconditional branch, we need to split the
1771 // block to provide a clear target for the return instruction.
1772 BasicBlock *ContinueBB;
1773 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1774 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1775 if (!Branch || !Branch->isUnconditional()) {
1776 // We're interrupting the cloning process at this location, so the
1777 // const_cast we're doing here will not cause a problem.
1778 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1779 const_cast<Instruction *>(cast<Instruction>(Next)));
1780 } else {
1781 ContinueBB = Branch->getSuccessor(0);
1782 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001783
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001784 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1785 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001786
1787 // We just added a terminator to the cloned block.
1788 // Tell the caller to stop processing the current basic block so that
1789 // the branch instruction will be skipped.
1790 return CloningDirector::StopCloningBB;
1791}
1792
1793CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1794 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1795 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1796 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1797 // This causes a replacement that will collapse the landing pad CFG based
1798 // on the filter function we intend to match.
1799 if (Selector == CurrentSelector)
1800 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1801 else
1802 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1803 // Tell the caller not to clone this instruction.
1804 return CloningDirector::SkipInstruction;
1805}
1806
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001807CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1808 ValueToValueMapTy &VMap,
1809 const IndirectBrInst *IBr,
1810 BasicBlock *NewBB) {
1811 // If this indirect branch is not part of a landing pad block, just clone it.
1812 const BasicBlock *ParentBB = IBr->getParent();
1813 if (!ParentBB->isLandingPad())
1814 return CloningDirector::CloneInstruction;
1815
1816 // If it is part of a landing pad, we want to filter out target blocks
1817 // that are not part of the handler we are outlining.
1818 const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1819
1820 // Save this correlation for later processing.
1821 NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1822
1823 // We should only get here for landing pads that have already been outlined.
1824 assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1825
1826 // Copy the indirectbr, but only include targets that were previously
1827 // identified as EH blocks and are dominated by the nested landing pad.
1828 SetVector<const BasicBlock *> ReturnTargets;
1829 for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1830 auto *TargetBB = IBr->getDestination(I);
1831 if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1832 DT->dominates(ParentBB, TargetBB)) {
1833 DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n");
1834 ReturnTargets.insert(TargetBB);
1835 }
1836 }
1837 IndirectBrInst *NewBranch =
1838 IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1839 ReturnTargets.size(), NewBB);
1840 for (auto *Target : ReturnTargets)
1841 NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1842
1843 // The operands and targets of the branch instruction are remapped later
1844 // because it is a terminator. Tell the cloning code to clone the
1845 // blocks we just added to the target list.
1846 return CloningDirector::CloneSuccessors;
1847}
1848
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001849CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001850WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1851 const InvokeInst *Invoke, BasicBlock *NewBB) {
1852 return CloningDirector::CloneInstruction;
1853}
1854
1855CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001856WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1857 const ResumeInst *Resume, BasicBlock *NewBB) {
1858 // Resume instructions shouldn't be reachable from catch handlers.
1859 // We still need to handle it, but it will be pruned.
1860 BasicBlock::InstListType &InstList = NewBB->getInstList();
1861 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1862 return CloningDirector::StopCloningBB;
1863}
1864
Andrew Kaylorea8df612015-04-17 23:05:43 +00001865CloningDirector::CloningAction
1866WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1867 const CmpInst *Compare, BasicBlock *NewBB) {
1868 const IntrinsicInst *IntrinCall = nullptr;
1869 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1870 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
Andrew Kaylor91307432015-04-28 22:01:51 +00001871 } else if (match(Compare->getOperand(1),
1872 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001873 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1874 }
1875 if (IntrinCall) {
1876 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1877 // This causes a replacement that will collapse the landing pad CFG based
1878 // on the filter function we intend to match.
1879 if (Selector == CurrentSelector->stripPointerCasts()) {
1880 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
Andrew Kaylor91307432015-04-28 22:01:51 +00001881 } else {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001882 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1883 }
1884 return CloningDirector::SkipInstruction;
1885 }
1886 return CloningDirector::CloneInstruction;
1887}
1888
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001889CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1890 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1891 // The MS runtime will terminate the process if an exception occurs in a
1892 // cleanup handler, so we shouldn't encounter landing pads in the actual
1893 // cleanup code, but they may appear in catch blocks. Depending on where
1894 // we started cloning we may see one, but it will get dropped during dead
1895 // block pruning.
1896 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1897 VMap[LPad] = NewInst;
1898 BasicBlock::InstListType &InstList = NewBB->getInstList();
1899 InstList.push_back(NewInst);
1900 return CloningDirector::StopCloningBB;
1901}
1902
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001903CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1904 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001905 // Cleanup code may flow into catch blocks or the catch block may be part
1906 // of a branch that will be optimized away. We'll insert a return
1907 // instruction now, but it may be pruned before the cloning process is
1908 // complete.
1909 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001910 return CloningDirector::StopCloningBB;
1911}
1912
1913CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1914 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001915 // Cleanup handlers nested within catch handlers may begin with a call to
1916 // eh.endcatch. We can just ignore that instruction.
1917 return CloningDirector::SkipInstruction;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001918}
1919
1920CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1921 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001922 // If we encounter a selector comparison while cloning a cleanup handler,
1923 // we want to stop cloning immediately. Anything after the dispatch
1924 // will be outlined into a different handler.
1925 BasicBlock *CatchHandler;
1926 Constant *Selector;
1927 BasicBlock *NextBB;
1928 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1929 CatchHandler, Selector, NextBB)) {
1930 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1931 return CloningDirector::StopCloningBB;
1932 }
1933 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001934 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001935 return CloningDirector::SkipInstruction;
1936}
1937
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001938CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1939 ValueToValueMapTy &VMap,
1940 const IndirectBrInst *IBr,
1941 BasicBlock *NewBB) {
1942 // No special handling is required for cleanup cloning.
1943 return CloningDirector::CloneInstruction;
1944}
1945
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001946CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1947 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1948 // All invokes in cleanup handlers can be replaced with calls.
1949 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1950 // Insert a normal call instruction...
1951 CallInst *NewCall =
1952 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1953 Invoke->getName(), NewBB);
1954 NewCall->setCallingConv(Invoke->getCallingConv());
1955 NewCall->setAttributes(Invoke->getAttributes());
1956 NewCall->setDebugLoc(Invoke->getDebugLoc());
1957 VMap[Invoke] = NewCall;
1958
Reid Kleckner6e48a822015-04-10 16:26:42 +00001959 // Remap the operands.
1960 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1961
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001962 // Insert an unconditional branch to the normal destination.
1963 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1964
1965 // The unwind destination won't be cloned into the new function, so
1966 // we don't need to clean up its phi nodes.
1967
1968 // We just added a terminator to the cloned block.
1969 // Tell the caller to stop processing the current basic block.
Reid Kleckner6e48a822015-04-10 16:26:42 +00001970 return CloningDirector::CloneSuccessors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001971}
1972
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001973CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1974 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1975 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1976
1977 // We just added a terminator to the cloned block.
1978 // Tell the caller to stop processing the current basic block so that
1979 // the branch instruction will be skipped.
1980 return CloningDirector::StopCloningBB;
1981}
1982
Andrew Kaylorea8df612015-04-17 23:05:43 +00001983CloningDirector::CloningAction
1984WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1985 const CmpInst *Compare, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001986 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1987 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1988 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1989 return CloningDirector::SkipInstruction;
1990 }
1991 return CloningDirector::CloneInstruction;
Andrew Kaylorea8df612015-04-17 23:05:43 +00001992}
1993
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001994WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001995 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001996 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001997 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001998
1999 // New allocas should be inserted in the entry block, but after the parent FP
2000 // is established if it is an instruction.
2001 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
2002 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
2003 InsertPoint = FPInst->getNextNode();
2004 Builder.SetInsertPoint(EntryBB, InsertPoint);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002005}
2006
2007Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002008 // If we're asked to materialize a static alloca, we temporarily create an
2009 // alloca in the outlined function and add this to the FrameVarInfo map. When
2010 // all the outlining is complete, we'll replace these temporary allocas with
Reid Kleckner60381792015-07-07 22:25:32 +00002011 // calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002012 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002013 assert(AV->isStaticAlloca() &&
2014 "cannot materialize un-demoted dynamic alloca");
Andrew Kaylor72029c62015-03-03 00:41:03 +00002015 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
2016 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00002017 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002018 return NewAlloca;
2019 }
2020
Andrew Kaylor72029c62015-03-03 00:41:03 +00002021 if (isa<Instruction>(V) || isa<Argument>(V)) {
Reid Klecknerd1b38c42015-05-06 18:45:24 +00002022 Function *Parent = isa<Instruction>(V)
2023 ? cast<Instruction>(V)->getParent()->getParent()
2024 : cast<Argument>(V)->getParent();
2025 errs()
2026 << "Failed to demote instruction used in exception handler of function "
2027 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
Reid Klecknerfd7df282015-04-22 21:05:21 +00002028 errs() << " " << *V << '\n';
2029 report_fatal_error("WinEHPrepare failed to demote instruction");
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002030 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002031
Andrew Kaylor72029c62015-03-03 00:41:03 +00002032 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002033 return nullptr;
2034}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002035
Reid Kleckner3567d272015-04-02 21:13:31 +00002036void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2037 // Catch parameter objects have to live in the parent frame. When we see a use
2038 // of a catch parameter, add a sentinel to the multimap to indicate that it's
2039 // used from another handler. This will prevent us from trying to sink the
2040 // alloca into the handler and ensure that the catch parameter is present in
Reid Kleckner60381792015-07-07 22:25:32 +00002041 // the call to llvm.localescape.
Reid Kleckner3567d272015-04-02 21:13:31 +00002042 FrameVarInfo[V].push_back(getCatchObjectSentinel());
2043}
2044
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002045// This function maps the catch and cleanup handlers that are reachable from the
2046// specified landing pad. The landing pad sequence will have this basic shape:
2047//
2048// <cleanup handler>
2049// <selector comparison>
2050// <catch handler>
2051// <cleanup handler>
2052// <selector comparison>
2053// <catch handler>
2054// <cleanup handler>
2055// ...
2056//
2057// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
2058// any arbitrary control flow, but all paths through the cleanup code must
2059// eventually reach the next selector comparison and no path can skip to a
2060// different selector comparisons, though some paths may terminate abnormally.
2061// Therefore, we will use a depth first search from the start of any given
2062// cleanup block and stop searching when we find the next selector comparison.
2063//
2064// If the landingpad instruction does not have a catch clause, we will assume
2065// that any instructions other than selector comparisons and catch handlers can
2066// be ignored. In practice, these will only be the boilerplate instructions.
2067//
2068// The catch handlers may also have any control structure, but we are only
2069// interested in the start of the catch handlers, so we don't need to actually
2070// follow the flow of the catch handlers. The start of the catch handlers can
2071// be located from the compare instructions, but they can be skipped in the
2072// flow by following the contrary branch.
2073void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2074 LandingPadActions &Actions) {
2075 unsigned int NumClauses = LPad->getNumClauses();
2076 unsigned int HandlersFound = 0;
2077 BasicBlock *BB = LPad->getParent();
2078
2079 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2080
2081 if (NumClauses == 0) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002082 findCleanupHandlers(Actions, BB, nullptr);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002083 return;
2084 }
2085
2086 VisitedBlockSet VisitedBlocks;
2087
2088 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002089 BasicBlock *NextBB = nullptr;
2090
Andrew Kaylor20ae2a32015-04-23 22:38:36 +00002091 // Skip over filter clauses.
2092 if (LPad->isFilter(HandlersFound)) {
2093 ++HandlersFound;
2094 continue;
2095 }
2096
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002097 // See if the clause we're looking for is a catch-all.
2098 // If so, the catch begins immediately.
Andrew Kaylor91307432015-04-28 22:01:51 +00002099 Constant *ExpectedSelector =
2100 LPad->getClause(HandlersFound)->stripPointerCasts();
Andrew Kaylorea8df612015-04-17 23:05:43 +00002101 if (isa<ConstantPointerNull>(ExpectedSelector)) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002102 // The catch all must occur last.
2103 assert(HandlersFound == NumClauses - 1);
2104
Andrew Kaylorea8df612015-04-17 23:05:43 +00002105 // There can be additional selector dispatches in the call chain that we
2106 // need to ignore.
2107 BasicBlock *CatchBlock = nullptr;
2108 Constant *Selector;
2109 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2110 DEBUG(dbgs() << " Found extra catch dispatch in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002111 << CatchBlock->getName() << "\n");
Andrew Kaylorea8df612015-04-17 23:05:43 +00002112 BB = NextBB;
2113 }
2114
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002115 // Add the catch handler to the action list.
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002116 CatchHandler *Action = nullptr;
2117 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2118 // If the CatchHandlerMap already has an entry for this BB, re-use it.
2119 Action = CatchHandlerMap[BB];
2120 assert(Action->getSelector() == ExpectedSelector);
2121 } else {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002122 // We don't expect a selector dispatch, but there may be a call to
2123 // llvm.eh.begincatch, which separates catch handling code from
2124 // cleanup code in the same control flow. This call looks for the
2125 // begincatch intrinsic.
2126 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2127 if (Action) {
2128 // For C++ EH, check if there is any interesting cleanup code before
2129 // we begin the catch. This is important because cleanups cannot
2130 // rethrow exceptions but code called from catches can. For SEH, it
2131 // isn't important if some finally code before a catch-all is executed
2132 // out of line or after recovering from the exception.
2133 if (Personality == EHPersonality::MSVC_CXX)
2134 findCleanupHandlers(Actions, BB, BB);
2135 } else {
2136 // If an action was not found, it means that the control flows
2137 // directly into the catch-all handler and there is no cleanup code.
2138 // That's an expected situation and we must create a catch action.
2139 // Since this is a catch-all handler, the selector won't actually
2140 // appear in the code anywhere. ExpectedSelector here is the constant
2141 // null ptr that we got from the landing pad instruction.
2142 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2143 CatchHandlerMap[BB] = Action;
2144 }
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002145 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002146 Actions.insertCatchHandler(Action);
2147 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
2148 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002149
2150 // Once we reach a catch-all, don't expect to hit a resume instruction.
2151 BB = nullptr;
2152 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002153 }
2154
2155 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
Andrew Kaylor41758512015-04-20 22:04:09 +00002156 assert(CatchAction);
2157
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002158 // See if there is any interesting code executed before the dispatch.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002159 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002160
Andrew Kaylorea8df612015-04-17 23:05:43 +00002161 // When the source program contains multiple nested try blocks the catch
2162 // handlers can get strung together in such a way that we can encounter
2163 // a dispatch for a selector that we've already had a handler for.
2164 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2165 ++HandlersFound;
2166
2167 // Add the catch handler to the action list.
2168 DEBUG(dbgs() << " Found catch dispatch in block "
2169 << CatchAction->getStartBlock()->getName() << "\n");
2170 Actions.insertCatchHandler(CatchAction);
2171 } else {
Andrew Kaylor41758512015-04-20 22:04:09 +00002172 // Under some circumstances optimized IR will flow unconditionally into a
2173 // handler block without checking the selector. This can only happen if
2174 // the landing pad has a catch-all handler and the handler for the
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002175 // preceding catch clause is identical to the catch-call handler
Andrew Kaylor41758512015-04-20 22:04:09 +00002176 // (typically an empty catch). In this case, the handler must be shared
2177 // by all remaining clauses.
2178 if (isa<ConstantPointerNull>(
2179 CatchAction->getSelector()->stripPointerCasts())) {
2180 DEBUG(dbgs() << " Applying early catch-all handler in block "
2181 << CatchAction->getStartBlock()->getName()
2182 << " to all remaining clauses.\n");
2183 Actions.insertCatchHandler(CatchAction);
2184 return;
2185 }
2186
Andrew Kaylorea8df612015-04-17 23:05:43 +00002187 DEBUG(dbgs() << " Found extra catch dispatch in block "
2188 << CatchAction->getStartBlock()->getName() << "\n");
2189 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002190
2191 // Move on to the block after the catch handler.
2192 BB = NextBB;
2193 }
2194
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002195 // If we didn't wind up in a catch-all, see if there is any interesting code
2196 // executed before the resume.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002197 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002198
2199 // It's possible that some optimization moved code into a landingpad that
2200 // wasn't
2201 // previously being used for cleanup. If that happens, we need to execute
2202 // that
2203 // extra code from a cleanup handler.
2204 if (Actions.includesCleanup() && !LPad->isCleanup())
2205 LPad->setCleanup(true);
2206}
2207
2208// This function searches starting with the input block for the next
2209// block that terminates with a branch whose condition is based on a selector
2210// comparison. This may be the input block. See the mapLandingPadBlocks
2211// comments for a discussion of control flow assumptions.
2212//
2213CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2214 BasicBlock *&NextBB,
2215 VisitedBlockSet &VisitedBlocks) {
2216 // See if we've already found a catch handler use it.
2217 // Call count() first to avoid creating a null entry for blocks
2218 // we haven't seen before.
2219 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2220 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2221 NextBB = Action->getNextBB();
2222 return Action;
2223 }
2224
2225 // VisitedBlocks applies only to the current search. We still
2226 // need to consider blocks that we've visited while mapping other
2227 // landing pads.
2228 VisitedBlocks.insert(BB);
2229
2230 BasicBlock *CatchBlock = nullptr;
2231 Constant *Selector = nullptr;
2232
2233 // If this is the first time we've visited this block from any landing pad
2234 // look to see if it is a selector dispatch block.
2235 if (!CatchHandlerMap.count(BB)) {
2236 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2237 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2238 CatchHandlerMap[BB] = Action;
2239 return Action;
2240 }
Andrew Kaylor41758512015-04-20 22:04:09 +00002241 // If we encounter a block containing an llvm.eh.begincatch before we
2242 // find a selector dispatch block, the handler is assumed to be
2243 // reached unconditionally. This happens for catch-all blocks, but
2244 // it can also happen for other catch handlers that have been combined
2245 // with the catch-all handler during optimization.
2246 if (isCatchBlock(BB)) {
2247 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2248 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2249 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2250 CatchHandlerMap[BB] = Action;
2251 return Action;
2252 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002253 }
2254
2255 // Visit each successor, looking for the dispatch.
2256 // FIXME: We expect to find the dispatch quickly, so this will probably
2257 // work better as a breadth first search.
2258 for (BasicBlock *Succ : successors(BB)) {
2259 if (VisitedBlocks.count(Succ))
2260 continue;
2261
2262 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2263 if (Action)
2264 return Action;
2265 }
2266 return nullptr;
2267}
2268
Reid Kleckner9405ef02015-04-10 23:12:29 +00002269// These are helper functions to combine repeated code from findCleanupHandlers.
2270static void createCleanupHandler(LandingPadActions &Actions,
2271 CleanupHandlerMapTy &CleanupHandlerMap,
2272 BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002273 CleanupHandler *Action = new CleanupHandler(BB);
2274 CleanupHandlerMap[BB] = Action;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002275 Actions.insertCleanupHandler(Action);
2276 DEBUG(dbgs() << " Found cleanup code in block "
2277 << Action->getStartBlock()->getName() << "\n");
2278}
2279
Reid Kleckner9405ef02015-04-10 23:12:29 +00002280static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2281 Instruction *MaybeCall) {
2282 // Look for finally blocks that Clang has already outlined for us.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002283 // %fp = call i8* @llvm.localaddress()
Reid Kleckner9405ef02015-04-10 23:12:29 +00002284 // call void @"fin$parent"(iN 1, i8* %fp)
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002285 if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002286 MaybeCall = MaybeCall->getNextNode();
2287 CallSite FinallyCall(MaybeCall);
2288 if (!FinallyCall || FinallyCall.arg_size() != 2)
2289 return CallSite();
2290 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2291 return CallSite();
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002292 if (!isLocalAddressCall(FinallyCall.getArgument(1)))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002293 return CallSite();
2294 return FinallyCall;
2295}
2296
2297static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2298 // Skip single ubr blocks.
2299 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2300 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2301 if (Br && Br->isUnconditional())
2302 BB = Br->getSuccessor(0);
2303 else
2304 return BB;
2305 }
2306 return BB;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002307}
2308
2309// This function searches starting with the input block for the next block that
2310// contains code that is not part of a catch handler and would not be eliminated
2311// during handler outlining.
2312//
Reid Kleckner9405ef02015-04-10 23:12:29 +00002313void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2314 BasicBlock *StartBB, BasicBlock *EndBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002315 // Here we will skip over the following:
2316 //
2317 // landing pad prolog:
2318 //
2319 // Unconditional branches
2320 //
2321 // Selector dispatch
2322 //
2323 // Resume pattern
2324 //
2325 // Anything else marks the start of an interesting block
2326
2327 BasicBlock *BB = StartBB;
2328 // Anything other than an unconditional branch will kick us out of this loop
2329 // one way or another.
2330 while (BB) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002331 BB = followSingleUnconditionalBranches(BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002332 // If we've already scanned this block, don't scan it again. If it is
2333 // a cleanup block, there will be an action in the CleanupHandlerMap.
2334 // If we've scanned it and it is not a cleanup block, there will be a
2335 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2336 // be no entry in the CleanupHandlerMap. We must call count() first to
2337 // avoid creating a null entry for blocks we haven't scanned.
2338 if (CleanupHandlerMap.count(BB)) {
2339 if (auto *Action = CleanupHandlerMap[BB]) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002340 Actions.insertCleanupHandler(Action);
2341 DEBUG(dbgs() << " Found cleanup code in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002342 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002343 // FIXME: This cleanup might chain into another, and we need to discover
2344 // that.
2345 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002346 } else {
2347 // Here we handle the case where the cleanup handler map contains a
2348 // value for this block but the value is a nullptr. This means that
2349 // we have previously analyzed the block and determined that it did
2350 // not contain any cleanup code. Based on the earlier analysis, we
Eric Christopher572e03a2015-06-19 01:53:21 +00002351 // know the block must end in either an unconditional branch, a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002352 // resume or a conditional branch that is predicated on a comparison
2353 // with a selector. Either the resume or the selector dispatch
2354 // would terminate the search for cleanup code, so the unconditional
2355 // branch is the only case for which we might need to continue
2356 // searching.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002357 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2358 if (SuccBB == BB || SuccBB == EndBB)
2359 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002360 BB = SuccBB;
2361 continue;
2362 }
2363 }
2364
2365 // Create an entry in the cleanup handler map for this block. Initially
2366 // we create an entry that says this isn't a cleanup block. If we find
2367 // cleanup code, the caller will replace this entry.
2368 CleanupHandlerMap[BB] = nullptr;
2369
2370 TerminatorInst *Terminator = BB->getTerminator();
2371
2372 // Landing pad blocks have extra instructions we need to accept.
2373 LandingPadMap *LPadMap = nullptr;
2374 if (BB->isLandingPad()) {
2375 LandingPadInst *LPad = BB->getLandingPadInst();
2376 LPadMap = &LPadMaps[LPad];
2377 if (!LPadMap->isInitialized())
2378 LPadMap->mapLandingPad(LPad);
2379 }
2380
2381 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002382 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2383 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002384 // resume { i8*, i32 } %lpad.val2
2385 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2386 InsertValueInst *Insert1 = nullptr;
2387 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002388 Value *ResumeVal = Resume->getOperand(0);
Reid Kleckner1c130bb2015-04-16 17:02:23 +00002389 // If the resume value isn't a phi or landingpad value, it should be a
2390 // series of insertions. Identify them so we can avoid them when scanning
2391 // for cleanups.
2392 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002393 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002394 if (!Insert2)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002395 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002396 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2397 if (!Insert1)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002398 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002399 }
2400 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2401 II != IE; ++II) {
2402 Instruction *Inst = II;
2403 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2404 continue;
2405 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2406 continue;
2407 if (!Inst->hasOneUse() ||
2408 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002409 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002410 }
2411 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002412 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002413 }
2414
2415 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002416 if (Branch && Branch->isConditional()) {
2417 // Look for the selector dispatch.
2418 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2419 // %matches = icmp eq i32 %sel, %2
2420 // br i1 %matches, label %catch14, label %eh.resume
2421 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2422 if (!Compare || !Compare->isEquality())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002423 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylorbb111322015-04-07 21:30:23 +00002424 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2425 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002426 Instruction *Inst = II;
2427 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2428 continue;
2429 if (Inst == Compare || Inst == Branch)
2430 continue;
2431 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2432 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002433 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002434 }
2435 // The selector dispatch block should always terminate our search.
2436 assert(BB == EndBB);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002437 return;
2438 }
2439
2440 if (isAsynchronousEHPersonality(Personality)) {
2441 // If this is a landingpad block, split the block at the first non-landing
2442 // pad instruction.
2443 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2444 if (LPadMap) {
2445 while (MaybeCall != BB->getTerminator() &&
2446 LPadMap->isLandingPadSpecificInst(MaybeCall))
2447 MaybeCall = MaybeCall->getNextNode();
2448 }
2449
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002450 // Look for outlined finally calls on x64, since those happen to match the
2451 // prototype provided by the runtime.
2452 if (TheTriple.getArch() == Triple::x86_64) {
2453 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2454 Function *Fin = FinallyCall.getCalledFunction();
2455 assert(Fin && "outlined finally call should be direct");
2456 auto *Action = new CleanupHandler(BB);
2457 Action->setHandlerBlockOrFunc(Fin);
2458 Actions.insertCleanupHandler(Action);
2459 CleanupHandlerMap[BB] = Action;
2460 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2461 << Fin->getName() << " in block "
2462 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002463
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002464 // Split the block if there were more interesting instructions and
2465 // look for finally calls in the normal successor block.
2466 BasicBlock *SuccBB = BB;
2467 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2468 FinallyCall.getInstruction()->getNextNode() !=
2469 BB->getTerminator()) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002470 SuccBB =
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002471 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002472 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002473 if (FinallyCall.isInvoke()) {
2474 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2475 ->getNormalDest();
2476 } else {
2477 SuccBB = BB->getUniqueSuccessor();
2478 assert(SuccBB &&
2479 "splitOutlinedFinallyCalls didn't insert a branch");
2480 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002481 }
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002482 BB = SuccBB;
2483 if (BB == EndBB)
2484 return;
2485 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002486 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002487 }
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002488 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002489
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002490 // Anything else is either a catch block or interesting cleanup code.
Andrew Kaylorbb111322015-04-07 21:30:23 +00002491 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2492 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002493 Instruction *Inst = II;
2494 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2495 continue;
2496 // Unconditional branches fall through to this loop.
2497 if (Inst == Branch)
2498 continue;
2499 // If this is a catch block, there is no cleanup code to be found.
2500 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002501 return;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002502 // If this a nested landing pad, it may contain an endcatch call.
2503 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002504 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002505 // Anything else makes this interesting cleanup code.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002506 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002507 }
2508
2509 // Only unconditional branches in empty blocks should get this far.
2510 assert(Branch && Branch->isUnconditional());
2511 if (BB == EndBB)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002512 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002513 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002514 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002515}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002516
2517// This is a public function, declared in WinEHFuncInfo.h and is also
2518// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
Benjamin Kramera48e0652015-05-16 15:40:03 +00002519void llvm::parseEHActions(
2520 const IntrinsicInst *II,
2521 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00002522 assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2523 "attempted to parse non eh.actions intrinsic");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002524 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2525 uint64_t ActionKind =
Andrew Kaylorbb111322015-04-07 21:30:23 +00002526 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002527 if (ActionKind == /*catch=*/1) {
2528 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2529 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2530 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2531 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2532 I += 4;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002533 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2534 /*NextBB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002535 CH->setHandlerBlockOrFunc(Handler);
2536 CH->setExceptionVarIndex(EHObjIndexVal);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002537 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002538 } else if (ActionKind == 0) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002539 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2540 I += 2;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002541 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002542 CH->setHandlerBlockOrFunc(Handler);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002543 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002544 } else {
2545 llvm_unreachable("Expected either a catch or cleanup handler!");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002546 }
2547 }
2548 std::reverse(Actions.begin(), Actions.end());
2549}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002550
2551namespace {
2552struct WinEHNumbering {
2553 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
2554 CurrentBaseState(-1), NextState(0) {}
2555
2556 WinEHFuncInfo &FuncInfo;
2557 int CurrentBaseState;
2558 int NextState;
2559
2560 SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
2561 SmallPtrSet<const Function *, 4> VisitedHandlers;
2562
2563 int currentEHNumber() const {
2564 return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
2565 }
2566
2567 void createUnwindMapEntry(int ToState, ActionHandler *AH);
2568 void createTryBlockMapEntry(int TryLow, int TryHigh,
2569 ArrayRef<CatchHandler *> Handlers);
2570 void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2571 ImmutableCallSite CS);
2572 void popUnmatchedActions(int FirstMismatch);
2573 void calculateStateNumbers(const Function &F);
2574 void findActionRootLPads(const Function &F);
2575};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002576}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002577
David Majnemer0ad363e2015-08-18 19:07:12 +00002578static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
2579 const Value *V) {
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002580 WinEHUnwindMapEntry UME;
2581 UME.ToState = ToState;
David Majnemer0ad363e2015-08-18 19:07:12 +00002582 UME.Cleanup = V;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002583 FuncInfo.UnwindMap.push_back(UME);
David Majnemer0ad363e2015-08-18 19:07:12 +00002584 return FuncInfo.getLastStateNumber();
2585}
2586
2587static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
2588 int TryHigh, int CatchHigh,
2589 ArrayRef<const CatchPadInst *> Handlers) {
2590 WinEHTryBlockMapEntry TBME;
2591 TBME.TryLow = TryLow;
2592 TBME.TryHigh = TryHigh;
2593 TBME.CatchHigh = CatchHigh;
2594 assert(TBME.TryLow <= TBME.TryHigh);
2595 for (const CatchPadInst *CPI : Handlers) {
2596 WinEHHandlerType HT;
2597 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
2598 if (TypeInfo->isNullValue()) {
2599 HT.Adjectives = 0x40;
2600 HT.TypeDescriptor = nullptr;
2601 } else {
2602 auto *GV = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
2603 // Selectors are always pointers to GlobalVariables with 'struct' type.
2604 // The struct has two fields, adjectives and a type descriptor.
2605 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2606 HT.Adjectives =
2607 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2608 HT.TypeDescriptor =
2609 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2610 }
Reid Kleckner0e288232015-08-27 23:27:47 +00002611 HT.Handler = CPI->getNormalDest();
2612 HT.HandlerMBB = nullptr;
David Majnemer0ad363e2015-08-18 19:07:12 +00002613 // FIXME: Pass CPI->getArgOperand(1).
2614 HT.CatchObjRecoverIdx = -1;
2615 TBME.HandlerArray.push_back(HT);
2616 }
2617 FuncInfo.TryBlockMap.push_back(TBME);
2618}
2619
2620void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
2621 Value *V = nullptr;
2622 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
2623 V = cast<Function>(CH->getHandlerBlockOrFunc());
2624 addUnwindMapEntry(FuncInfo, ToState, V);
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002625}
2626
2627void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
2628 ArrayRef<CatchHandler *> Handlers) {
2629 // See if we already have an entry for this set of handlers.
2630 // This is using iterators rather than a range-based for loop because
2631 // if we find the entry we're looking for we'll need the iterator to erase it.
2632 int NumHandlers = Handlers.size();
2633 auto I = FuncInfo.TryBlockMap.begin();
2634 auto E = FuncInfo.TryBlockMap.end();
2635 for ( ; I != E; ++I) {
2636 auto &Entry = *I;
2637 if (Entry.HandlerArray.size() != (size_t)NumHandlers)
2638 continue;
2639 int N;
2640 for (N = 0; N < NumHandlers; ++N) {
2641 if (Entry.HandlerArray[N].Handler != Handlers[N]->getHandlerBlockOrFunc())
2642 break; // breaks out of inner loop
2643 }
2644 // If all the handlers match, this is what we were looking for.
2645 if (N == NumHandlers) {
2646 break;
2647 }
2648 }
2649
2650 // If we found an existing entry for this set of handlers, extend the range
2651 // but move the entry to the end of the map vector. The order of entries
2652 // in the map is critical to the way that the runtime finds handlers.
2653 // FIXME: Depending on what has happened with block ordering, this may
2654 // incorrectly combine entries that should remain separate.
2655 if (I != E) {
2656 // Copy the existing entry.
2657 WinEHTryBlockMapEntry Entry = *I;
2658 Entry.TryLow = std::min(TryLow, Entry.TryLow);
2659 Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
2660 assert(Entry.TryLow <= Entry.TryHigh);
2661 // Erase the old entry and add this one to the back.
2662 FuncInfo.TryBlockMap.erase(I);
2663 FuncInfo.TryBlockMap.push_back(Entry);
2664 return;
2665 }
2666
2667 // If we didn't find an entry, create a new one.
2668 WinEHTryBlockMapEntry TBME;
2669 TBME.TryLow = TryLow;
2670 TBME.TryHigh = TryHigh;
2671 assert(TBME.TryLow <= TBME.TryHigh);
2672 for (CatchHandler *CH : Handlers) {
2673 WinEHHandlerType HT;
2674 if (CH->getSelector()->isNullValue()) {
2675 HT.Adjectives = 0x40;
2676 HT.TypeDescriptor = nullptr;
2677 } else {
2678 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
2679 // Selectors are always pointers to GlobalVariables with 'struct' type.
2680 // The struct has two fields, adjectives and a type descriptor.
2681 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2682 HT.Adjectives =
2683 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2684 HT.TypeDescriptor =
2685 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2686 }
2687 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
Reid Kleckner0e288232015-08-27 23:27:47 +00002688 HT.HandlerMBB = nullptr;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002689 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
2690 TBME.HandlerArray.push_back(HT);
2691 }
2692 FuncInfo.TryBlockMap.push_back(TBME);
2693}
2694
2695static void print_name(const Value *V) {
2696#ifndef NDEBUG
2697 if (!V) {
2698 DEBUG(dbgs() << "null");
2699 return;
2700 }
2701
2702 if (const auto *F = dyn_cast<Function>(V))
2703 DEBUG(dbgs() << F->getName());
2704 else
2705 DEBUG(V->dump());
2706#endif
2707}
2708
2709void WinEHNumbering::processCallSite(
2710 MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2711 ImmutableCallSite CS) {
2712 DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
2713 << ") for: ");
2714 print_name(CS ? CS.getCalledValue() : nullptr);
2715 DEBUG(dbgs() << '\n');
2716
2717 DEBUG(dbgs() << "HandlerStack: \n");
2718 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2719 DEBUG(dbgs() << " ");
2720 print_name(HandlerStack[I]->getHandlerBlockOrFunc());
2721 DEBUG(dbgs() << '\n');
2722 }
2723 DEBUG(dbgs() << "Actions: \n");
2724 for (int I = 0, E = Actions.size(); I < E; ++I) {
2725 DEBUG(dbgs() << " ");
2726 print_name(Actions[I]->getHandlerBlockOrFunc());
2727 DEBUG(dbgs() << '\n');
2728 }
2729 int FirstMismatch = 0;
2730 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
2731 ++FirstMismatch) {
2732 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
2733 Actions[FirstMismatch]->getHandlerBlockOrFunc())
2734 break;
2735 }
2736
2737 // Remove unmatched actions from the stack and process their EH states.
2738 popUnmatchedActions(FirstMismatch);
2739
2740 DEBUG(dbgs() << "Pushing actions for CallSite: ");
2741 print_name(CS ? CS.getCalledValue() : nullptr);
2742 DEBUG(dbgs() << '\n');
2743
2744 bool LastActionWasCatch = false;
2745 const LandingPadInst *LastRootLPad = nullptr;
2746 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
2747 // We can reuse eh states when pushing two catches for the same invoke.
2748 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
2749 auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
2750 // Various conditions can lead to a handler being popped from the
2751 // stack and re-pushed later. That shouldn't create a new state.
2752 // FIXME: Can code optimization lead to re-used handlers?
2753 if (FuncInfo.HandlerEnclosedState.count(Handler)) {
2754 // If we already assigned the state enclosed by this handler re-use it.
2755 Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
2756 continue;
2757 }
2758 const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
2759 if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
2760 DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
2761 Actions[I]->setEHState(currentEHNumber());
2762 } else {
2763 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
2764 print_name(Actions[I]->getHandlerBlockOrFunc());
2765 DEBUG(dbgs() << ") with EH state " << NextState << "\n");
2766 createUnwindMapEntry(currentEHNumber(), Actions[I].get());
2767 DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
2768 Actions[I]->setEHState(NextState);
2769 NextState++;
2770 }
2771 HandlerStack.push_back(std::move(Actions[I]));
2772 LastActionWasCatch = CurrActionIsCatch;
2773 LastRootLPad = RootLPad;
2774 }
2775
2776 // This is used to defer numbering states for a handler until after the
2777 // last time it appears in an invoke action list.
2778 if (CS.isInvoke()) {
2779 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2780 auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
2781 if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
2782 continue;
2783 FuncInfo.LastInvokeVisited[Handler] = true;
2784 DEBUG(dbgs() << "Last invoke of ");
2785 print_name(Handler);
2786 DEBUG(dbgs() << " has been visited.\n");
2787 }
2788 }
2789
2790 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
2791 print_name(CS ? CS.getCalledValue() : nullptr);
2792 DEBUG(dbgs() << '\n');
2793}
2794
2795void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
2796 // Don't recurse while we are looping over the handler stack. Instead, defer
2797 // the numbering of the catch handlers until we are done popping.
2798 SmallVector<CatchHandler *, 4> PoppedCatches;
2799 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
2800 std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
2801 if (isa<CatchHandler>(Handler.get()))
2802 PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
2803 }
2804
2805 int TryHigh = NextState - 1;
2806 int LastTryLowIdx = 0;
2807 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
2808 CatchHandler *CH = PoppedCatches[I];
2809 DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
2810 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
2811 int TryLow = CH->getEHState();
2812 auto Handlers =
2813 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
2814 DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
2815 for (size_t J = 0; J < Handlers.size(); ++J) {
2816 DEBUG(dbgs() << ", ");
2817 print_name(Handlers[J]->getHandlerBlockOrFunc());
2818 }
2819 DEBUG(dbgs() << ")\n");
2820 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
2821 LastTryLowIdx = I + 1;
2822 }
2823 }
2824
2825 for (CatchHandler *CH : PoppedCatches) {
2826 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
2827 if (FuncInfo.LastInvokeVisited[F]) {
2828 DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
2829 print_name(F);
2830 DEBUG(dbgs() << '\n');
2831 FuncInfo.HandlerBaseState[F] = NextState;
2832 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
2833 << ", null)\n");
2834 createUnwindMapEntry(currentEHNumber(), nullptr);
2835 ++NextState;
2836 calculateStateNumbers(*F);
2837 }
2838 else {
2839 DEBUG(dbgs() << "Deferring handling of ");
2840 print_name(F);
2841 DEBUG(dbgs() << " until last invoke visited.\n");
2842 }
2843 }
2844 delete CH;
2845 }
2846}
2847
2848void WinEHNumbering::calculateStateNumbers(const Function &F) {
2849 auto I = VisitedHandlers.insert(&F);
2850 if (!I.second)
2851 return; // We've already visited this handler, don't renumber it.
2852
2853 int OldBaseState = CurrentBaseState;
2854 if (FuncInfo.HandlerBaseState.count(&F)) {
2855 CurrentBaseState = FuncInfo.HandlerBaseState[&F];
2856 }
2857
2858 size_t SavedHandlerStackSize = HandlerStack.size();
2859
2860 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
2861 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2862 for (const BasicBlock &BB : F) {
2863 for (const Instruction &I : BB) {
2864 const auto *CI = dyn_cast<CallInst>(&I);
2865 if (!CI || CI->doesNotThrow())
2866 continue;
2867 processCallSite(None, CI);
2868 }
2869 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2870 if (!II)
2871 continue;
2872 const LandingPadInst *LPI = II->getLandingPadInst();
2873 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2874 if (!ActionsCall)
2875 continue;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002876 parseEHActions(ActionsCall, ActionList);
2877 if (ActionList.empty())
2878 continue;
2879 processCallSite(ActionList, II);
2880 ActionList.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00002881 FuncInfo.EHPadStateMap[LPI] = currentEHNumber();
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002882 DEBUG(dbgs() << "Assigning state " << currentEHNumber()
2883 << " to landing pad at " << LPI->getParent()->getName()
2884 << '\n');
2885 }
2886
2887 // Pop any actions that were pushed on the stack for this function.
2888 popUnmatchedActions(SavedHandlerStackSize);
2889
2890 DEBUG(dbgs() << "Assigning max state " << NextState - 1
2891 << " to " << F.getName() << '\n');
2892 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
2893
2894 CurrentBaseState = OldBaseState;
2895}
2896
2897// This function follows the same basic traversal as calculateStateNumbers
2898// but it is necessary to identify the root landing pad associated
2899// with each action before we start assigning state numbers.
2900void WinEHNumbering::findActionRootLPads(const Function &F) {
2901 auto I = VisitedHandlers.insert(&F);
2902 if (!I.second)
2903 return; // We've already visited this handler, don't revisit it.
2904
2905 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2906 for (const BasicBlock &BB : F) {
2907 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2908 if (!II)
2909 continue;
2910 const LandingPadInst *LPI = II->getLandingPadInst();
2911 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2912 if (!ActionsCall)
2913 continue;
2914
2915 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
2916 parseEHActions(ActionsCall, ActionList);
2917 if (ActionList.empty())
2918 continue;
2919 for (int I = 0, E = ActionList.size(); I < E; ++I) {
2920 if (auto *Handler
2921 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
2922 FuncInfo.LastInvoke[Handler] = II;
2923 // Don't replace the root landing pad if we previously saw this
2924 // handler in a different function.
2925 if (FuncInfo.RootLPad.count(Handler) &&
2926 FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
2927 continue;
2928 DEBUG(dbgs() << "Setting root lpad for ");
2929 print_name(Handler);
2930 DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
2931 FuncInfo.RootLPad[Handler] = LPI;
2932 }
2933 }
2934 // Walk the actions again and look for nested handlers. This has to
2935 // happen after all of the actions have been processed in the current
2936 // function.
2937 for (int I = 0, E = ActionList.size(); I < E; ++I)
2938 if (auto *Handler
2939 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
2940 findActionRootLPads(*Handler);
2941 ActionList.clear();
2942 }
2943}
2944
David Majnemer0ad363e2015-08-18 19:07:12 +00002945static const BasicBlock *getSingleCatchPadPredecessor(const BasicBlock &BB) {
2946 for (const BasicBlock *PredBlock : predecessors(&BB))
2947 if (isa<CatchPadInst>(PredBlock->getFirstNonPHI()))
2948 return PredBlock;
2949 return nullptr;
2950}
2951
2952// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
2953// to. If the unwind edge came from an invoke, return null.
2954static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) {
2955 const TerminatorInst *TI = BB->getTerminator();
2956 if (isa<InvokeInst>(TI))
2957 return nullptr;
2958 if (isa<CatchPadInst>(TI) || isa<CatchEndPadInst>(TI) ||
2959 isa<TerminatePadInst>(TI))
2960 return BB;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002961 return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent();
David Majnemer0ad363e2015-08-18 19:07:12 +00002962}
2963
2964static void calculateExplicitStateNumbers(WinEHFuncInfo &FuncInfo,
2965 const BasicBlock &BB,
2966 int ParentState) {
2967 assert(BB.isEHPad());
2968 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
2969 // All catchpad instructions will be handled when we process their
2970 // respective catchendpad instruction.
2971 if (isa<CatchPadInst>(FirstNonPHI))
2972 return;
2973
2974 if (isa<CatchEndPadInst>(FirstNonPHI)) {
2975 const BasicBlock *TryPad = &BB;
2976 const BasicBlock *LastTryPad = nullptr;
2977 SmallVector<const CatchPadInst *, 2> Handlers;
2978 do {
2979 LastTryPad = TryPad;
2980 TryPad = getSingleCatchPadPredecessor(*TryPad);
2981 if (TryPad)
2982 Handlers.push_back(cast<CatchPadInst>(TryPad->getFirstNonPHI()));
2983 } while (TryPad);
2984 // We've pushed these back into reverse source order. Reverse them to get
2985 // the list back into source order.
2986 std::reverse(Handlers.begin(), Handlers.end());
2987 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
2988 FuncInfo.EHPadStateMap[Handlers.front()] = TryLow;
2989 for (const BasicBlock *PredBlock : predecessors(LastTryPad))
2990 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
2991 calculateExplicitStateNumbers(FuncInfo, *PredBlock, TryLow);
2992 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
2993 FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow;
2994 int TryHigh = CatchLow - 1;
2995 for (const BasicBlock *PredBlock : predecessors(&BB))
2996 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
2997 calculateExplicitStateNumbers(FuncInfo, *PredBlock, CatchLow);
2998 int CatchHigh = FuncInfo.getLastStateNumber();
2999 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
3000 DEBUG(dbgs() << "TryLow[" << LastTryPad->getName() << "]: " << TryLow
3001 << '\n');
3002 DEBUG(dbgs() << "TryHigh[" << LastTryPad->getName() << "]: " << TryHigh
3003 << '\n');
3004 DEBUG(dbgs() << "CatchHigh[" << LastTryPad->getName() << "]: " << CatchHigh
3005 << '\n');
3006 } else if (isa<CleanupPadInst>(FirstNonPHI)) {
3007 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB);
3008 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
3009 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
3010 << BB.getName() << '\n');
3011 for (const BasicBlock *PredBlock : predecessors(&BB))
3012 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3013 calculateExplicitStateNumbers(FuncInfo, *PredBlock, CleanupState);
3014 } else if (isa<TerminatePadInst>(FirstNonPHI)) {
3015 report_fatal_error("Not yet implemented!");
3016 } else {
3017 llvm_unreachable("unexpected EH Pad!");
3018 }
3019}
3020
Reid Klecknerfe4d4912015-05-28 22:00:24 +00003021void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
3022 WinEHFuncInfo &FuncInfo) {
3023 // Return if it's already been done.
David Majnemer0ad363e2015-08-18 19:07:12 +00003024 if (!FuncInfo.EHPadStateMap.empty())
3025 return;
3026
3027 bool IsExplicit = false;
3028 for (const BasicBlock &BB : *ParentFn) {
3029 if (!BB.isEHPad())
3030 continue;
3031 // Check if the EH Pad has no exceptional successors (i.e. it unwinds to
3032 // caller). Cleanups are a little bit of a special case because their
3033 // control flow cannot be determined by looking at the pad but instead by
3034 // the pad's users.
3035 bool HasNoSuccessors = false;
3036 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3037 if (FirstNonPHI->mayThrow()) {
3038 HasNoSuccessors = true;
3039 } else if (auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI)) {
3040 HasNoSuccessors =
3041 CPI->use_empty() ||
3042 cast<CleanupReturnInst>(CPI->user_back())->unwindsToCaller();
3043 }
3044
3045 if (!HasNoSuccessors)
3046 continue;
3047 calculateExplicitStateNumbers(FuncInfo, BB, -1);
3048 IsExplicit = true;
3049 }
3050
3051 if (IsExplicit)
Reid Klecknerfe4d4912015-05-28 22:00:24 +00003052 return;
3053
3054 WinEHNumbering Num(FuncInfo);
3055 Num.findActionRootLPads(*ParentFn);
3056 // The VisitedHandlers list is used by both findActionRootLPads and
3057 // calculateStateNumbers, but both functions need to visit all handlers.
3058 Num.VisitedHandlers.clear();
3059 Num.calculateStateNumbers(*ParentFn);
3060 // Pop everything on the handler stack.
3061 // It may be necessary to call this more than once because a handler can
3062 // be pushed on the stack as a result of clearing the stack.
3063 while (!Num.HandlerStack.empty())
3064 Num.processCallSite(None, ImmutableCallSite());
3065}
David Majnemerfd9f4772015-08-11 01:15:26 +00003066
3067void WinEHPrepare::numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB) {
3068 Instruction *FirstNonPHI = FuncletBB->getFirstNonPHI();
3069 bool IsCatch = isa<CatchPadInst>(FirstNonPHI);
3070 bool IsCleanup = isa<CleanupPadInst>(FirstNonPHI);
3071
3072 // Initialize the worklist with the funclet's entry point.
3073 std::vector<BasicBlock *> Worklist;
3074 Worklist.push_back(InitialBB);
3075
3076 while (!Worklist.empty()) {
3077 BasicBlock *BB = Worklist.back();
3078 Worklist.pop_back();
3079
3080 // There can be only one "pad" basic block in the funclet: the initial one.
3081 if (BB != FuncletBB && BB->isEHPad())
3082 continue;
3083
3084 // Add 'FuncletBB' as a possible color for 'BB'.
3085 if (BlockColors[BB].insert(FuncletBB).second == false) {
3086 // Skip basic blocks which we have already visited.
3087 continue;
3088 }
3089
3090 FuncletBlocks[FuncletBB].insert(BB);
3091
3092 Instruction *Terminator = BB->getTerminator();
3093 // The catchret's successors cannot be part of the funclet.
3094 if (IsCatch && isa<CatchReturnInst>(Terminator))
3095 continue;
3096 // The cleanupret's successors cannot be part of the funclet.
3097 if (IsCleanup && isa<CleanupReturnInst>(Terminator))
3098 continue;
3099
3100 Worklist.insert(Worklist.end(), succ_begin(BB), succ_end(BB));
3101 }
3102}
3103
3104bool WinEHPrepare::prepareExplicitEH(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +00003105 // Remove unreachable blocks. It is not valuable to assign them a color and
3106 // their existence can trick us into thinking values are alive when they are
3107 // not.
3108 removeUnreachableBlocks(F);
3109
3110 BasicBlock *EntryBlock = &F.getEntryBlock();
3111
3112 // Number everything starting from the entry block.
3113 numberFunclet(EntryBlock, EntryBlock);
3114
3115 for (BasicBlock &BB : F) {
3116 // Remove single entry PHIs to simplify preparation.
3117 if (auto *PN = dyn_cast<PHINode>(BB.begin()))
3118 if (PN->getNumIncomingValues() == 1)
3119 FoldSingleEntryPHINodes(&BB);
3120
3121 // EH pad instructions are always the first non-PHI nodes in a block if they
3122 // are at all present.
3123 Instruction *I = BB.getFirstNonPHI();
3124 if (I->isEHPad())
3125 numberFunclet(&BB, &BB);
3126
3127 // It is possible for a normal basic block to only be reachable via an
3128 // exceptional basic block. The successor of a catchret is the only case
3129 // where this is possible.
3130 if (auto *CRI = dyn_cast<CatchReturnInst>(BB.getTerminator()))
3131 numberFunclet(CRI->getSuccessor(), EntryBlock);
3132 }
3133
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003134 // Strip PHI nodes off of EH pads.
3135 SmallVector<PHINode *, 16> PHINodes;
David Majnemerfd9f4772015-08-11 01:15:26 +00003136 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3137 BasicBlock *BB = FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +00003138 if (!BB->isEHPad())
3139 continue;
David Majnemerfd9f4772015-08-11 01:15:26 +00003140 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3141 Instruction *I = BI++;
3142 auto *PN = dyn_cast<PHINode>(I);
3143 // Stop at the first non-PHI.
3144 if (!PN)
3145 break;
David Majnemerfd9f4772015-08-11 01:15:26 +00003146
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003147 AllocaInst *SpillSlot = insertPHILoads(PN, F);
3148 if (SpillSlot)
3149 insertPHIStores(PN, SpillSlot);
3150
3151 PHINodes.push_back(PN);
David Majnemerfd9f4772015-08-11 01:15:26 +00003152 }
3153 }
3154
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003155 for (auto *PN : PHINodes) {
3156 // There may be lingering uses on other EH PHIs being removed
3157 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
3158 PN->eraseFromParent();
David Majnemerfd9f4772015-08-11 01:15:26 +00003159 }
3160
3161 // Turn all inter-funclet uses of a Value into loads and stores.
3162 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3163 BasicBlock *BB = FI++;
3164 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3165 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3166 Instruction *I = BI++;
3167 // Funclets are permitted to use static allocas.
3168 if (auto *AI = dyn_cast<AllocaInst>(I))
3169 if (AI->isStaticAlloca())
3170 continue;
3171
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003172 demoteNonlocalUses(I, ColorsForBB, F);
David Majnemerfd9f4772015-08-11 01:15:26 +00003173 }
3174 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003175 // Also demote function parameters used in funclets.
3176 std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()];
3177 for (Argument &Arg : F.args())
3178 demoteNonlocalUses(&Arg, ColorsForEntry, F);
David Majnemerfd9f4772015-08-11 01:15:26 +00003179
3180 // We need to clone all blocks which belong to multiple funclets. Values are
3181 // remapped throughout the funclet to propogate both the new instructions
3182 // *and* the new basic blocks themselves.
3183 for (auto &Funclet : FuncletBlocks) {
3184 BasicBlock *FuncletPadBB = Funclet.first;
3185 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3186
3187 std::map<BasicBlock *, BasicBlock *> Orig2Clone;
3188 ValueToValueMapTy VMap;
3189 for (BasicBlock *BB : BlocksInFunclet) {
3190 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3191 // We don't need to do anything if the block is monochromatic.
3192 size_t NumColorsForBB = ColorsForBB.size();
3193 if (NumColorsForBB == 1)
3194 continue;
3195
3196 assert(!isa<PHINode>(BB->front()) &&
3197 "Polychromatic PHI nodes should have been demoted!");
3198
3199 // Create a new basic block and copy instructions into it!
3200 BasicBlock *CBB = CloneBasicBlock(
3201 BB, VMap, Twine(".for.", FuncletPadBB->getName()), &F);
3202
3203 // Add basic block mapping.
3204 VMap[BB] = CBB;
3205
3206 // Record delta operations that we need to perform to our color mappings.
3207 Orig2Clone[BB] = CBB;
3208 }
3209
3210 // Update our color mappings to reflect that one block has lost a color and
3211 // another has gained a color.
3212 for (auto &BBMapping : Orig2Clone) {
3213 BasicBlock *OldBlock = BBMapping.first;
3214 BasicBlock *NewBlock = BBMapping.second;
3215
3216 BlocksInFunclet.insert(NewBlock);
3217 BlockColors[NewBlock].insert(FuncletPadBB);
3218
3219 BlocksInFunclet.erase(OldBlock);
3220 BlockColors[OldBlock].erase(FuncletPadBB);
3221 }
3222
3223 // Loop over all of the instructions in the function, fixing up operand
3224 // references as we go. This uses VMap to do all the hard work.
3225 for (BasicBlock *BB : BlocksInFunclet)
3226 // Loop over all instructions, fixing each one as we find it...
3227 for (Instruction &I : *BB)
3228 RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
3229 }
3230
David Majnemer83f4bb22015-08-17 20:56:39 +00003231 // Remove implausible terminators and replace them with UnreachableInst.
3232 for (auto &Funclet : FuncletBlocks) {
3233 BasicBlock *FuncletPadBB = Funclet.first;
3234 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3235 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
3236 auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
3237 auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI);
3238
3239 for (BasicBlock *BB : BlocksInFunclet) {
3240 TerminatorInst *TI = BB->getTerminator();
3241 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
3242 bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad);
3243 // The token consumed by a CatchReturnInst must match the funclet token.
3244 bool IsUnreachableCatchret = false;
3245 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003246 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
David Majnemer83f4bb22015-08-17 20:56:39 +00003247 // The token consumed by a CleanupPadInst must match the funclet token.
3248 bool IsUnreachableCleanupret = false;
3249 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003250 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
David Majnemer83f4bb22015-08-17 20:56:39 +00003251 if (IsUnreachableRet || IsUnreachableCatchret || IsUnreachableCleanupret) {
3252 new UnreachableInst(BB->getContext(), TI);
3253 TI->eraseFromParent();
3254 }
3255 }
3256 }
3257
David Majnemerfd9f4772015-08-11 01:15:26 +00003258 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
3259 // branches, etc.
3260 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3261 BasicBlock *BB = FI++;
3262 SimplifyInstructionsInBlock(BB);
3263 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
3264 MergeBlockIntoPredecessor(BB);
3265 }
3266
David Majnemerfd9f4772015-08-11 01:15:26 +00003267 // We might have some unreachable blocks after cleaning up some impossible
3268 // control flow.
3269 removeUnreachableBlocks(F);
3270
3271 // Recolor the CFG to verify that all is well.
3272 for (BasicBlock &BB : F) {
3273 size_t NumColors = BlockColors[&BB].size();
3274 assert(NumColors == 1 && "Expected monochromatic BB!");
3275 if (NumColors == 0)
3276 report_fatal_error("Uncolored BB!");
3277 if (NumColors > 1)
3278 report_fatal_error("Multicolor BB!");
3279 bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
3280 assert(!EHPadHasPHI && "EH Pad still has a PHI!");
3281 if (EHPadHasPHI)
3282 report_fatal_error("EH Pad still has a PHI!");
3283 }
3284
3285 BlockColors.clear();
3286 FuncletBlocks.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00003287
David Majnemerfd9f4772015-08-11 01:15:26 +00003288 return true;
3289}
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003290
3291// TODO: Share loads when one use dominates another, or when a catchpad exit
3292// dominates uses (needs dominators).
3293AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
3294 BasicBlock *PHIBlock = PN->getParent();
3295 AllocaInst *SpillSlot = nullptr;
3296
3297 if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) {
3298 // Insert a load in place of the PHI and replace all uses.
3299 SpillSlot = new AllocaInst(PN->getType(), nullptr,
3300 Twine(PN->getName(), ".wineh.spillslot"),
3301 F.getEntryBlock().begin());
3302 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
3303 PHIBlock->getFirstInsertionPt());
3304 PN->replaceAllUsesWith(V);
3305 return SpillSlot;
3306 }
3307
3308 DenseMap<BasicBlock *, Value *> Loads;
3309 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
3310 UI != UE;) {
3311 Use &U = *UI++;
3312 auto *UsingInst = cast<Instruction>(U.getUser());
3313 BasicBlock *UsingBB = UsingInst->getParent();
3314 if (UsingBB->isEHPad()) {
3315 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
3316 // stores for it separately.
3317 assert(isa<PHINode>(UsingInst));
3318 continue;
3319 }
3320 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
3321 }
3322 return SpillSlot;
3323}
3324
3325// TODO: improve store placement. Inserting at def is probably good, but need
3326// to be careful not to introduce interfering stores (needs liveness analysis).
3327// TODO: identify related phi nodes that can share spill slots, and share them
3328// (also needs liveness).
3329void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
3330 AllocaInst *SpillSlot) {
3331 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
3332 // stored to the spill slot by the end of the given Block.
3333 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
3334
3335 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
3336
3337 while (!Worklist.empty()) {
3338 BasicBlock *EHBlock;
3339 Value *InVal;
3340 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
3341
3342 PHINode *PN = dyn_cast<PHINode>(InVal);
3343 if (PN && PN->getParent() == EHBlock) {
3344 // The value is defined by another PHI we need to remove, with no room to
3345 // insert a store after the PHI, so each predecessor needs to store its
3346 // incoming value.
3347 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
3348 Value *PredVal = PN->getIncomingValue(i);
3349
3350 // Undef can safely be skipped.
3351 if (isa<UndefValue>(PredVal))
3352 continue;
3353
3354 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
3355 }
3356 } else {
3357 // We need to store InVal, which dominates EHBlock, but can't put a store
3358 // in EHBlock, so need to put stores in each predecessor.
3359 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
3360 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
3361 }
3362 }
3363 }
3364}
3365
3366void WinEHPrepare::insertPHIStore(
3367 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
3368 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
3369
3370 if (PredBlock->isEHPad() &&
3371 !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) {
3372 // Pred is unsplittable, so we need to queue it on the worklist.
3373 Worklist.push_back({PredBlock, PredVal});
3374 return;
3375 }
3376
3377 // Otherwise, insert the store at the end of the basic block.
3378 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
3379}
3380
3381// TODO: Share loads for same-funclet uses (requires dominators if funclets
3382// aren't properly nested).
3383void WinEHPrepare::demoteNonlocalUses(Value *V,
3384 std::set<BasicBlock *> &ColorsForBB,
3385 Function &F) {
David Majnemer83f4bb22015-08-17 20:56:39 +00003386 // Tokens can only be used non-locally due to control flow involving
3387 // unreachable edges. Don't try to demote the token usage, we'll simply
3388 // delete the cloned user later.
3389 if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V))
3390 return;
3391
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003392 DenseMap<BasicBlock *, Value *> Loads;
3393 AllocaInst *SpillSlot = nullptr;
3394 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) {
3395 Use &U = *UI++;
3396 auto *UsingInst = cast<Instruction>(U.getUser());
3397 BasicBlock *UsingBB = UsingInst->getParent();
3398
3399 // Is the Use inside a block which is colored with a subset of the Def?
3400 // If so, we don't need to escape the Def because we will clone
3401 // ourselves our own private copy.
3402 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
3403 if (std::includes(ColorsForBB.begin(), ColorsForBB.end(),
3404 ColorsForUsingBB.begin(), ColorsForUsingBB.end()))
3405 continue;
3406
3407 replaceUseWithLoad(V, U, SpillSlot, Loads, F);
3408 }
3409 if (SpillSlot) {
3410 // Insert stores of the computed value into the stack slot.
3411 // We have to be careful if I is an invoke instruction,
3412 // because we can't insert the store AFTER the terminator instruction.
3413 BasicBlock::iterator InsertPt;
3414 if (isa<Argument>(V)) {
3415 InsertPt = F.getEntryBlock().getTerminator();
3416 } else if (isa<TerminatorInst>(V)) {
3417 auto *II = cast<InvokeInst>(V);
3418 // We cannot demote invoke instructions to the stack if their normal
3419 // edge is critical. Therefore, split the critical edge and create a
3420 // basic block into which the store can be inserted.
3421 if (!II->getNormalDest()->getSinglePredecessor()) {
3422 unsigned SuccNum =
3423 GetSuccessorNumber(II->getParent(), II->getNormalDest());
3424 assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
3425 BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
3426 assert(NewBlock && "Unable to split critical edge.");
3427 // Update the color mapping for the newly split edge.
3428 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()];
3429 BlockColors[NewBlock] = ColorsForUsingBB;
3430 for (BasicBlock *FuncletPad : ColorsForUsingBB)
3431 FuncletBlocks[FuncletPad].insert(NewBlock);
3432 }
3433 InsertPt = II->getNormalDest()->getFirstInsertionPt();
3434 } else {
3435 InsertPt = cast<Instruction>(V);
3436 ++InsertPt;
3437 // Don't insert before PHI nodes or EH pad instrs.
3438 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
3439 ;
3440 }
3441 new StoreInst(V, SpillSlot, InsertPt);
3442 }
3443}
3444
3445void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
3446 DenseMap<BasicBlock *, Value *> &Loads,
3447 Function &F) {
3448 // Lazilly create the spill slot.
3449 if (!SpillSlot)
3450 SpillSlot = new AllocaInst(V->getType(), nullptr,
3451 Twine(V->getName(), ".wineh.spillslot"),
3452 F.getEntryBlock().begin());
3453
3454 auto *UsingInst = cast<Instruction>(U.getUser());
3455 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
3456 // If this is a PHI node, we can't insert a load of the value before
3457 // the use. Instead insert the load in the predecessor block
3458 // corresponding to the incoming value.
3459 //
3460 // Note that if there are multiple edges from a basic block to this
3461 // PHI node that we cannot have multiple loads. The problem is that
3462 // the resulting PHI node will have multiple values (from each load)
3463 // coming in from the same block, which is illegal SSA form.
3464 // For this reason, we keep track of and reuse loads we insert.
3465 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00003466 if (auto *CatchRet =
3467 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
3468 // Putting a load above a catchret and use on the phi would still leave
3469 // a cross-funclet def/use. We need to split the edge, change the
3470 // catchret to target the new block, and put the load there.
3471 BasicBlock *PHIBlock = UsingInst->getParent();
3472 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
3473 // SplitEdge gives us:
3474 // IncomingBlock:
3475 // ...
3476 // br label %NewBlock
3477 // NewBlock:
3478 // catchret label %PHIBlock
3479 // But we need:
3480 // IncomingBlock:
3481 // ...
3482 // catchret label %NewBlock
3483 // NewBlock:
3484 // br label %PHIBlock
3485 // So move the terminators to each others' blocks and swap their
3486 // successors.
3487 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
3488 Goto->removeFromParent();
3489 CatchRet->removeFromParent();
3490 IncomingBlock->getInstList().push_back(CatchRet);
3491 NewBlock->getInstList().push_back(Goto);
3492 Goto->setSuccessor(0, PHIBlock);
3493 CatchRet->setSuccessor(NewBlock);
3494 // Update the color mapping for the newly split edge.
3495 std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock];
3496 BlockColors[NewBlock] = ColorsForPHIBlock;
3497 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
3498 FuncletBlocks[FuncletPad].insert(NewBlock);
3499 // Treat the new block as incoming for load insertion.
3500 IncomingBlock = NewBlock;
3501 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003502 Value *&Load = Loads[IncomingBlock];
3503 // Insert the load into the predecessor block
3504 if (!Load)
3505 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3506 /*Volatile=*/false, IncomingBlock->getTerminator());
3507
3508 U.set(Load);
3509 } else {
3510 // Reload right before the old use.
3511 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3512 /*Volatile=*/false, UsingInst);
3513 U.set(Load);
3514 }
3515}