blob: ed3cd5d400b82f373944c5ffe9180e5c844bb900 [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);
Joseph Tremouletec182852015-08-28 01:12:35 +0000133 bool prepareExplicitEH(Function &F,
134 SmallVectorImpl<BasicBlock *> &EntryBlocks);
135 void colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks);
David Majnemerfd9f4772015-08-11 01:15:26 +0000136
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000137 Triple TheTriple;
138
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000139 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +0000140 DominatorTree *DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000141 const TargetLibraryInfo *LibInfo = nullptr;
Reid Kleckner582786b2015-04-30 18:17:12 +0000142 EHPersonality Personality = EHPersonality::Unknown;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000143 CatchHandlerMapTy CatchHandlerMap;
144 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000145 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000146 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
147 SmallPtrSet<BasicBlock *, 4> EHBlocks;
148 SetVector<BasicBlock *> EHReturnBlocks;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000149
150 // This maps landing pad instructions found in outlined handlers to
151 // the landing pad instruction in the parent function from which they
152 // were cloned. The cloned/nested landing pad is used as the key
153 // because the landing pad may be cloned into multiple handlers.
154 // This map will be used to add the llvm.eh.actions call to the nested
155 // landing pads after all handlers have been outlined.
156 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
157
158 // This maps blocks in the parent function which are destinations of
159 // catch handlers to cloned blocks in (other) outlined handlers. This
160 // handles the case where a nested landing pads has a catch handler that
161 // returns to a handler function rather than the parent function.
162 // The original block is used as the key here because there should only
163 // ever be one handler function from which the cloned block is not pruned.
164 // The original block will be pruned from the parent function after all
165 // handlers have been outlined. This map will be used to adjust the
166 // return instructions of handlers which return to the block that was
167 // outlined into a handler. This is done after all handlers have been
168 // outlined but before the outlined code is pruned from the parent function.
169 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000170
Reid Klecknerd5afc62f2015-07-07 23:23:03 +0000171 // Map from outlined handler to call to parent local address. Only used for
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000172 // 32-bit EH.
173 DenseMap<Function *, Value *> HandlerToParentFP;
174
Reid Kleckner582786b2015-04-30 18:17:12 +0000175 AllocaInst *SEHExceptionCodeSlot = nullptr;
David Majnemerfd9f4772015-08-11 01:15:26 +0000176
177 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
178 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
Joseph Tremouletec182852015-08-28 01:12:35 +0000179 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletChildren;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000180};
181
182class WinEHFrameVariableMaterializer : public ValueMaterializer {
183public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000184 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000185 FrameVarInfoMap &FrameVarInfo);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000186 ~WinEHFrameVariableMaterializer() override {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000187
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000188 Value *materializeValueFor(Value *V) override;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000189
Reid Kleckner3567d272015-04-02 21:13:31 +0000190 void escapeCatchObject(Value *V);
191
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000192private:
193 FrameVarInfoMap &FrameVarInfo;
194 IRBuilder<> Builder;
195};
196
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000197class LandingPadMap {
198public:
199 LandingPadMap() : OriginLPad(nullptr) {}
200 void mapLandingPad(const LandingPadInst *LPad);
201
202 bool isInitialized() { return OriginLPad != nullptr; }
203
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000204 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000205 bool isLandingPadSpecificInst(const Instruction *Inst) const;
206
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000207 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
208 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000209
210private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000211 const LandingPadInst *OriginLPad;
212 // We will normally only see one of each of these instructions, but
213 // if more than one occurs for some reason we can handle that.
214 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
215 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000216};
217
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000218class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000219public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000220 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
221 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
222 : Materializer(HandlerFn, ParentFP, VarInfo),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000223 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
224 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000225 LPadMap(LPadMap), ParentFP(ParentFP) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000226
227 CloningAction handleInstruction(ValueToValueMapTy &VMap,
228 const Instruction *Inst,
229 BasicBlock *NewBB) override;
230
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000231 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
232 const Instruction *Inst,
233 BasicBlock *NewBB) = 0;
234 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
235 const Instruction *Inst,
236 BasicBlock *NewBB) = 0;
237 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
238 const Instruction *Inst,
239 BasicBlock *NewBB) = 0;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000240 virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
241 const IndirectBrInst *IBr,
242 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000243 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
244 const InvokeInst *Invoke,
245 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000246 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
247 const ResumeInst *Resume,
248 BasicBlock *NewBB) = 0;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000249 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
250 const CmpInst *Compare,
251 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000252 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
253 const LandingPadInst *LPad,
254 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000255
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000256 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
257
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000258protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000259 WinEHFrameVariableMaterializer Materializer;
260 Type *SelectorIDType;
261 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000262 LandingPadMap &LPadMap;
Reid Klecknerf14787d2015-04-22 00:07:52 +0000263
264 /// The value representing the parent frame pointer.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000265 Value *ParentFP;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000266};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000267
268class WinEHCatchDirector : public WinEHCloningDirectorBase {
269public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000270 WinEHCatchDirector(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000271 Function *CatchFn, Value *ParentFP, Value *Selector,
272 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000273 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
274 DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000275 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000276 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000277 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
278 DT(DT), EHBlocks(EHBlocks) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000279
280 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
281 const Instruction *Inst,
282 BasicBlock *NewBB) override;
283 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
284 BasicBlock *NewBB) override;
285 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
286 const Instruction *Inst,
287 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000288 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
289 const IndirectBrInst *IBr,
290 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000291 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
292 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000293 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
294 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000295 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
296 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000297 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
298 const LandingPadInst *LPad,
299 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000300
Reid Kleckner3567d272015-04-02 21:13:31 +0000301 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000302 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
303
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000304private:
305 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000306
Reid Kleckner3567d272015-04-02 21:13:31 +0000307 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000308 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000309
310 // This will be a reference to the field of the same name in the WinEHPrepare
311 // object which instantiates this WinEHCatchDirector object.
312 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000313 DominatorTree *DT;
314 SmallPtrSetImpl<BasicBlock *> &EHBlocks;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000315};
316
317class WinEHCleanupDirector : public WinEHCloningDirectorBase {
318public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000319 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
320 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
321 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
322 LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000323
324 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
325 const Instruction *Inst,
326 BasicBlock *NewBB) override;
327 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
328 BasicBlock *NewBB) override;
329 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
330 const Instruction *Inst,
331 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000332 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
333 const IndirectBrInst *IBr,
334 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000335 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
336 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000337 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
338 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000339 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
340 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000341 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
342 const LandingPadInst *LPad,
343 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000344};
345
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000346class LandingPadActions {
347public:
348 LandingPadActions() : HasCleanupHandlers(false) {}
349
350 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
351 void insertCleanupHandler(CleanupHandler *Action) {
352 Actions.push_back(Action);
353 HasCleanupHandlers = true;
354 }
355
356 bool includesCleanup() const { return HasCleanupHandlers; }
357
David Majnemercde33032015-03-30 22:58:10 +0000358 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000359 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
360 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
361
362private:
363 // Note that this class does not own the ActionHandler objects in this vector.
364 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
365 // in the WinEHPrepare class.
366 SmallVector<ActionHandler *, 4> Actions;
367 bool HasCleanupHandlers;
368};
369
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000370} // end anonymous namespace
371
372char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000373INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
374 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000375
376FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
377 return new WinEHPrepare(TM);
378}
379
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000380bool WinEHPrepare::runOnFunction(Function &Fn) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000381 if (!Fn.hasPersonalityFn())
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000382 return false;
383
David Majnemerfd9f4772015-08-11 01:15:26 +0000384 // No need to prepare outlined handlers.
385 if (Fn.hasFnAttribute("wineh-parent"))
David Majnemer09e1fdb2015-08-06 21:13:51 +0000386 return false;
387
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000388 // Classify the personality to see what kind of preparation we need.
David Majnemer7fddecc2015-06-17 20:52:32 +0000389 Personality = classifyEHPersonality(Fn.getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000390
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000391 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000392 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000393 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000394
David Majnemerfd9f4772015-08-11 01:15:26 +0000395 SmallVector<LandingPadInst *, 4> LPads;
396 SmallVector<ResumeInst *, 4> Resumes;
Joseph Tremouletec182852015-08-28 01:12:35 +0000397 SmallVector<BasicBlock *, 4> EntryBlocks;
David Majnemerfd9f4772015-08-11 01:15:26 +0000398 bool ForExplicitEH = false;
399 for (BasicBlock &BB : Fn) {
Joseph Tremouletec182852015-08-28 01:12:35 +0000400 Instruction *First = BB.getFirstNonPHI();
401 if (auto *LP = dyn_cast<LandingPadInst>(First)) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000402 LPads.push_back(LP);
Joseph Tremouletec182852015-08-28 01:12:35 +0000403 } else if (First->isEHPad()) {
404 if (!ForExplicitEH)
405 EntryBlocks.push_back(&Fn.getEntryBlock());
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000406 if (!isa<CatchEndPadInst>(First) && !isa<CleanupEndPadInst>(First))
Joseph Tremouletec182852015-08-28 01:12:35 +0000407 EntryBlocks.push_back(&BB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000408 ForExplicitEH = true;
David Majnemerfd9f4772015-08-11 01:15:26 +0000409 }
410 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
411 Resumes.push_back(Resume);
412 }
413
414 if (ForExplicitEH)
Joseph Tremouletec182852015-08-28 01:12:35 +0000415 return prepareExplicitEH(Fn, EntryBlocks);
David Majnemerfd9f4772015-08-11 01:15:26 +0000416
417 // No need to prepare functions that lack landing pads.
418 if (LPads.empty())
419 return false;
420
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000421 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000422 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000423
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000424 // If there were any landing pads, prepareExceptionHandlers will make changes.
425 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000426 return true;
427}
428
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000429bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000430
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000431void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
432 AU.addRequired<DominatorTreeWrapperPass>();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000433 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000434}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000435
Reid Klecknerfd7df282015-04-22 21:05:21 +0000436static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
437 Constant *&Selector, BasicBlock *&NextBB);
438
439// Finds blocks reachable from the starting set Worklist. Does not follow unwind
440// edges or blocks listed in StopPoints.
441static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
442 SetVector<BasicBlock *> &Worklist,
443 const SetVector<BasicBlock *> *StopPoints) {
444 while (!Worklist.empty()) {
445 BasicBlock *BB = Worklist.pop_back_val();
446
447 // Don't cross blocks that we should stop at.
448 if (StopPoints && StopPoints->count(BB))
449 continue;
450
451 if (!ReachableBBs.insert(BB).second)
452 continue; // Already visited.
453
454 // Don't follow unwind edges of invokes.
455 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
456 Worklist.insert(II->getNormalDest());
457 continue;
458 }
459
460 // Otherwise, follow all successors.
461 Worklist.insert(succ_begin(BB), succ_end(BB));
462 }
463}
464
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000465// Attempt to find an instruction where a block can be split before
466// a call to llvm.eh.begincatch and its operands. If the block
467// begins with the begincatch call or one of its adjacent operands
468// the block will not be split.
469static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
470 IntrinsicInst *II) {
471 // If the begincatch call is already the first instruction in the block,
472 // don't split.
473 Instruction *FirstNonPHI = BB->getFirstNonPHI();
474 if (II == FirstNonPHI)
475 return nullptr;
476
477 // If either operand is in the same basic block as the instruction and
478 // isn't used by another instruction before the begincatch call, include it
479 // in the split block.
480 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
481 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
482
483 Instruction *I = II->getPrevNode();
484 Instruction *LastI = II;
485
486 while (I == Op0 || I == Op1) {
487 // If the block begins with one of the operands and there are no other
488 // instructions between the operand and the begincatch call, don't split.
489 if (I == FirstNonPHI)
490 return nullptr;
491
492 LastI = I;
493 I = I->getPrevNode();
494 }
495
496 // If there is at least one instruction in the block before the begincatch
497 // call and its operands, split the block at either the begincatch or
498 // its operand.
499 return LastI;
500}
501
Reid Klecknerfd7df282015-04-22 21:05:21 +0000502/// Find all points where exceptional control rejoins normal control flow via
503/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000504void WinEHPrepare::findCXXEHReturnPoints(
505 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000506 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
507 BasicBlock *BB = BBI;
508 for (Instruction &I : *BB) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000509 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
Andrew Kaylor91307432015-04-28 22:01:51 +0000510 Instruction *SplitPt =
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000511 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
512 if (SplitPt) {
513 // Split the block before the llvm.eh.begincatch call to allow
514 // cleanup and catch code to be distinguished later.
515 // Do not update BBI because we still need to process the
516 // portion of the block that we are splitting off.
Andrew Kaylora33f1592015-04-29 17:21:26 +0000517 SplitBlock(BB, SplitPt, DT);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000518 break;
519 }
520 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000521 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
522 // Split the block after the call to llvm.eh.endcatch if there is
523 // anything other than an unconditional branch, or if the successor
524 // starts with a phi.
525 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
526 if (!Br || !Br->isUnconditional() ||
527 isa<PHINode>(Br->getSuccessor(0)->begin())) {
528 DEBUG(dbgs() << "splitting block " << BB->getName()
529 << " with llvm.eh.endcatch\n");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000530 BBI = SplitBlock(BB, I.getNextNode(), DT);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000531 }
532 // The next BB is normal control flow.
533 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
534 break;
535 }
536 }
537 }
538}
539
540static bool isCatchAllLandingPad(const BasicBlock *BB) {
541 const LandingPadInst *LP = BB->getLandingPadInst();
542 if (!LP)
543 return false;
544 unsigned N = LP->getNumClauses();
545 return (N > 0 && LP->isCatch(N - 1) &&
546 isa<ConstantPointerNull>(LP->getClause(N - 1)));
547}
548
549/// Find all points where exceptions control rejoins normal control flow via
550/// selector dispatch.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000551void WinEHPrepare::findSEHEHReturnPoints(
552 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000553 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
554 BasicBlock *BB = BBI;
555 // If the landingpad is a catch-all, treat the whole lpad as if it is
556 // reachable from normal control flow.
557 // FIXME: This is imprecise. We need a better way of identifying where a
558 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
559 // is no difference.
560 if (isCatchAllLandingPad(BB)) {
561 EHReturnBlocks.insert(BB);
562 continue;
563 }
564
565 BasicBlock *CatchHandler;
566 BasicBlock *NextBB;
567 Constant *Selector;
568 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
Reid Klecknered012db2015-07-08 18:08:52 +0000569 // Split the edge if there are multiple predecessors. This creates a place
570 // where we can insert EH recovery code.
571 if (!CatchHandler->getSinglePredecessor()) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000572 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
573 << " to " << CatchHandler->getName() << '\n');
574 BBI = CatchHandler = SplitCriticalEdge(
575 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
576 }
577 EHReturnBlocks.insert(CatchHandler);
578 }
579 }
580}
581
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000582void WinEHPrepare::identifyEHBlocks(Function &F,
583 SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000584 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
585 << F.getName() << '\n');
586
587 // Build a set of all non-exceptional blocks and exceptional blocks.
588 // - Non-exceptional blocks are blocks reachable from the entry block while
589 // not following invoke unwind edges.
590 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
591 // not follow llvm.eh.endcatch blocks, which mark a transition from
592 // exceptional to normal control.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000593
594 if (Personality == EHPersonality::MSVC_CXX)
595 findCXXEHReturnPoints(F, EHReturnBlocks);
596 else
597 findSEHEHReturnPoints(F, EHReturnBlocks);
598
599 DEBUG({
600 dbgs() << "identified the following blocks as EH return points:\n";
601 for (BasicBlock *BB : EHReturnBlocks)
602 dbgs() << " " << BB->getName() << '\n';
603 });
604
Andrew Kaylor91307432015-04-28 22:01:51 +0000605// Join points should not have phis at this point, unless they are a
606// landingpad, in which case we will demote their phis later.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000607#ifndef NDEBUG
608 for (BasicBlock *BB : EHReturnBlocks)
609 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
610 "non-lpad EH return block has phi");
611#endif
612
613 // Normal blocks are the blocks reachable from the entry block and all EH
614 // return points.
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000615 SetVector<BasicBlock *> Worklist;
Reid Klecknerfd7df282015-04-22 21:05:21 +0000616 Worklist = EHReturnBlocks;
617 Worklist.insert(&F.getEntryBlock());
618 findReachableBlocks(NormalBlocks, Worklist, nullptr);
619 DEBUG({
620 dbgs() << "marked the following blocks as normal:\n";
621 for (BasicBlock *BB : NormalBlocks)
622 dbgs() << " " << BB->getName() << '\n';
623 });
624
625 // Exceptional blocks are the blocks reachable from landingpads that don't
626 // cross EH return points.
627 Worklist.clear();
628 for (auto *LPI : LPads)
629 Worklist.insert(LPI->getParent());
630 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
631 DEBUG({
632 dbgs() << "marked the following blocks as exceptional:\n";
633 for (BasicBlock *BB : EHBlocks)
634 dbgs() << " " << BB->getName() << '\n';
635 });
636
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000637}
638
639/// Ensure that all values live into and out of exception handlers are stored
640/// in memory.
641/// FIXME: This falls down when values are defined in one handler and live into
642/// another handler. For example, a cleanup defines a value used only by a
643/// catch handler.
644void WinEHPrepare::demoteValuesLiveAcrossHandlers(
645 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
646 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
647 << F.getName() << '\n');
648
649 // identifyEHBlocks() should have been called before this function.
650 assert(!NormalBlocks.empty());
651
Reid Kleckner7ea77082015-07-10 22:21:54 +0000652 // Try to avoid demoting EH pointer and selector values. They get in the way
653 // of our pattern matching.
654 SmallPtrSet<Instruction *, 10> EHVals;
655 for (BasicBlock &BB : F) {
656 LandingPadInst *LP = BB.getLandingPadInst();
657 if (!LP)
658 continue;
659 EHVals.insert(LP);
660 for (User *U : LP->users()) {
661 auto *EI = dyn_cast<ExtractValueInst>(U);
662 if (!EI)
663 continue;
664 EHVals.insert(EI);
665 for (User *U2 : EI->users()) {
666 if (auto *PN = dyn_cast<PHINode>(U2))
667 EHVals.insert(PN);
668 }
669 }
670 }
671
Reid Klecknerfd7df282015-04-22 21:05:21 +0000672 SetVector<Argument *> ArgsToDemote;
673 SetVector<Instruction *> InstrsToDemote;
674 for (BasicBlock &BB : F) {
675 bool IsNormalBB = NormalBlocks.count(&BB);
676 bool IsEHBB = EHBlocks.count(&BB);
677 if (!IsNormalBB && !IsEHBB)
678 continue; // Blocks that are neither normal nor EH are unreachable.
679 for (Instruction &I : BB) {
680 for (Value *Op : I.operands()) {
681 // Don't demote static allocas, constants, and labels.
682 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
683 continue;
684 auto *AI = dyn_cast<AllocaInst>(Op);
685 if (AI && AI->isStaticAlloca())
686 continue;
687
688 if (auto *Arg = dyn_cast<Argument>(Op)) {
689 if (IsEHBB) {
690 DEBUG(dbgs() << "Demoting argument " << *Arg
691 << " used by EH instr: " << I << "\n");
692 ArgsToDemote.insert(Arg);
693 }
694 continue;
695 }
696
Reid Kleckner7ea77082015-07-10 22:21:54 +0000697 // Don't demote EH values.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000698 auto *OpI = cast<Instruction>(Op);
Reid Kleckner7ea77082015-07-10 22:21:54 +0000699 if (EHVals.count(OpI))
700 continue;
701
Reid Klecknerfd7df282015-04-22 21:05:21 +0000702 BasicBlock *OpBB = OpI->getParent();
703 // If a value is produced and consumed in the same BB, we don't need to
704 // demote it.
705 if (OpBB == &BB)
706 continue;
707 bool IsOpNormalBB = NormalBlocks.count(OpBB);
708 bool IsOpEHBB = EHBlocks.count(OpBB);
709 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
710 DEBUG({
711 dbgs() << "Demoting instruction live in-out from EH:\n";
712 dbgs() << "Instr: " << *OpI << '\n';
713 dbgs() << "User: " << I << '\n';
714 });
715 InstrsToDemote.insert(OpI);
716 }
717 }
718 }
719 }
720
721 // Demote values live into and out of handlers.
722 // FIXME: This demotion is inefficient. We should insert spills at the point
723 // of definition, insert one reload in each handler that uses the value, and
724 // insert reloads in the BB used to rejoin normal control flow.
725 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
726 for (Instruction *I : InstrsToDemote)
727 DemoteRegToStack(*I, false, AllocaInsertPt);
728
729 // Demote arguments separately, and only for uses in EH blocks.
730 for (Argument *Arg : ArgsToDemote) {
731 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
732 Arg->getName() + ".reg2mem", AllocaInsertPt);
733 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
734 for (User *U : Users) {
735 auto *I = dyn_cast<Instruction>(U);
736 if (I && EHBlocks.count(I->getParent())) {
737 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
738 U->replaceUsesOfWith(Arg, Reload);
739 }
740 }
741 new StoreInst(Arg, Slot, AllocaInsertPt);
742 }
743
744 // Demote landingpad phis, as the landingpad will be removed from the machine
745 // CFG.
746 for (LandingPadInst *LPI : LPads) {
747 BasicBlock *BB = LPI->getParent();
748 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
749 DemotePHIToStack(Phi, AllocaInsertPt);
750 }
751
752 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
753 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
754}
755
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000756bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000757 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000758 // Don't run on functions that are already prepared.
759 for (LandingPadInst *LPad : LPads) {
760 BasicBlock *LPadBB = LPad->getParent();
761 for (Instruction &Inst : *LPadBB)
762 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
763 return false;
764 }
765
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000766 identifyEHBlocks(F, LPads);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000767 demoteValuesLiveAcrossHandlers(F, LPads);
768
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000769 // These containers are used to re-map frame variables that are used in
770 // outlined catch and cleanup handlers. They will be populated as the
771 // handlers are outlined.
772 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000773
774 bool HandlersOutlined = false;
775
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000776 Module *M = F.getParent();
777 LLVMContext &Context = M->getContext();
778
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000779 // Create a new function to receive the handler contents.
780 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
781 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000782 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000783
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000784 if (isAsynchronousEHPersonality(Personality)) {
785 // FIXME: Switch the ehptr type to i32 and then switch this.
786 SEHExceptionCodeSlot =
787 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
788 F.getEntryBlock().getFirstInsertionPt());
789 }
790
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000791 // In order to handle the case where one outlined catch handler returns
792 // to a block within another outlined catch handler that would otherwise
793 // be unreachable, we need to outline the nested landing pad before we
794 // outline the landing pad which encloses it.
Manuel Klimekb00d42c2015-05-21 15:38:25 +0000795 if (!isAsynchronousEHPersonality(Personality))
796 std::sort(LPads.begin(), LPads.end(),
797 [this](LandingPadInst *const &L, LandingPadInst *const &R) {
798 return DT->properlyDominates(R->getParent(), L->getParent());
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000799 });
800
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000801 // This container stores the llvm.eh.recover and IndirectBr instructions
802 // that make up the body of each landing pad after it has been outlined.
803 // We need to defer the population of the target list for the indirectbr
804 // until all landing pads have been outlined so that we can handle the
805 // case of blocks in the target that are reached only from nested
806 // landing pads.
807 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
808
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000809 for (LandingPadInst *LPad : LPads) {
810 // Look for evidence that this landingpad has already been processed.
811 bool LPadHasActionList = false;
812 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000813 for (Instruction &Inst : *LPadBB) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000814 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
815 LPadHasActionList = true;
816 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000817 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000818 }
819
820 // If we've already outlined the handlers for this landingpad,
821 // there's nothing more to do here.
822 if (LPadHasActionList)
823 continue;
824
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000825 // If either of the values in the aggregate returned by the landing pad is
826 // extracted and stored to memory, promote the stored value to a register.
827 promoteLandingPadValues(LPad);
828
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000829 LandingPadActions Actions;
830 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000831
Reid Kleckner9405ef02015-04-10 23:12:29 +0000832 HandlersOutlined |= !Actions.actions().empty();
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000833 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000834 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000835 continue;
836 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000837
838 // SEH doesn't do any outlining for catches. Instead, pass the handler
839 // basic block addr to llvm.eh.actions and list the block as a return
840 // target.
841 if (isAsynchronousEHPersonality(Personality)) {
842 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
843 processSEHCatchHandler(CatchAction, StartBB);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000844 continue;
845 }
846 }
847
Reid Kleckner9405ef02015-04-10 23:12:29 +0000848 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
849 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000850
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000851 // Split the block after the landingpad instruction so that it is just a
852 // call to llvm.eh.actions followed by indirectbr.
853 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000854 SplitBlock(LPadBB, LPad->getNextNode(), DT);
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000855 // Erase the branch inserted by the split so we can insert indirectbr.
856 LPadBB->getTerminator()->eraseFromParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000857
Reid Klecknere3af86e2015-04-23 21:22:30 +0000858 // Replace all extracted values with undef and ultimately replace the
859 // landingpad with undef.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000860 SmallVector<Instruction *, 4> SEHCodeUses;
861 SmallVector<Instruction *, 4> EHUndefs;
Reid Klecknere3af86e2015-04-23 21:22:30 +0000862 for (User *U : LPad->users()) {
863 auto *E = dyn_cast<ExtractValueInst>(U);
864 if (!E)
865 continue;
866 assert(E->getNumIndices() == 1 &&
867 "Unexpected operation: extracting both landing pad values");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000868 unsigned Idx = *E->idx_begin();
869 assert((Idx == 0 || Idx == 1) && "unexpected index");
870 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
871 SEHCodeUses.push_back(E);
872 else
873 EHUndefs.push_back(E);
Reid Klecknere3af86e2015-04-23 21:22:30 +0000874 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000875 for (Instruction *E : EHUndefs) {
Reid Klecknere3af86e2015-04-23 21:22:30 +0000876 E->replaceAllUsesWith(UndefValue::get(E->getType()));
877 E->eraseFromParent();
878 }
879 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000880
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000881 // Rewrite uses of the exception pointer to loads of an alloca.
Reid Kleckner7ea77082015-07-10 22:21:54 +0000882 while (!SEHCodeUses.empty()) {
883 Instruction *E = SEHCodeUses.pop_back_val();
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000884 SmallVector<Use *, 4> Uses;
885 for (Use &U : E->uses())
886 Uses.push_back(&U);
887 for (Use *U : Uses) {
888 auto *I = cast<Instruction>(U->getUser());
889 if (isa<ResumeInst>(I))
890 continue;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000891 if (auto *Phi = dyn_cast<PHINode>(I))
Reid Kleckner7ea77082015-07-10 22:21:54 +0000892 SEHCodeUses.push_back(Phi);
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000893 else
Reid Kleckner7ea77082015-07-10 22:21:54 +0000894 U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000895 }
896 E->replaceAllUsesWith(UndefValue::get(E->getType()));
897 E->eraseFromParent();
898 }
899
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000900 // Add a call to describe the actions for this landing pad.
901 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000902 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000903 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000904 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000905 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000906 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000907 // Find the frame escape index of the exception object alloca in the
908 // parent.
909 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000910 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000911 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
912 auto I = FrameVarInfo.find(EHObj);
913 assert(I != FrameVarInfo.end() &&
914 "failed to map llvm.eh.begincatch var");
915 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
916 }
917 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000918 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000919 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000920 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000921 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000922 }
923 CallInst *Recover =
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000924 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000925
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000926 SetVector<BasicBlock *> ReturnTargets;
927 for (ActionHandler *Action : Actions) {
928 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
929 const auto &CatchTargets = CatchAction->getReturnTargets();
930 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000931 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000932 }
933 IndirectBrInst *Branch =
934 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
935 for (BasicBlock *Target : ReturnTargets)
936 Branch->addDestination(Target);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000937
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000938 if (!isAsynchronousEHPersonality(Personality)) {
939 // C++ EH must repopulate the targets later to handle the case of
940 // targets that are reached indirectly through nested landing pads.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000941 LPadImpls.push_back(std::make_pair(Recover, Branch));
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000942 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000943
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000944 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000945
946 // If nothing got outlined, there is no more processing to be done.
947 if (!HandlersOutlined)
948 return false;
949
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000950 // Replace any nested landing pad stubs with the correct action handler.
951 // This must be done before we remove unreachable blocks because it
952 // cleans up references to outlined blocks that will be deleted.
953 for (auto &LPadPair : NestedLPtoOriginalLP)
954 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
Andrew Kaylor67d3c032015-04-08 20:57:22 +0000955 NestedLPtoOriginalLP.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000956
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000957 // Update the indirectbr instructions' target lists if necessary.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000958 SetVector<BasicBlock*> CheckedTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000959 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000960 for (auto &LPadImplPair : LPadImpls) {
961 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
962 IndirectBrInst *Branch = LPadImplPair.second;
963
964 // Get a list of handlers called by
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000965 parseEHActions(Recover, ActionList);
966
967 // Add an indirect branch listing possible successors of the catch handlers.
968 SetVector<BasicBlock *> ReturnTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000969 for (const auto &Action : ActionList) {
970 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000971 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
972 getPossibleReturnTargets(&F, Handler, ReturnTargets);
973 }
974 }
Andrew Kaylor0ddaf2b2015-05-12 00:13:51 +0000975 ActionList.clear();
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000976 // Clear any targets we already knew about.
977 for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
978 BasicBlock *KnownTarget = Branch->getDestination(I);
979 if (ReturnTargets.count(KnownTarget))
980 ReturnTargets.remove(KnownTarget);
981 }
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000982 for (BasicBlock *Target : ReturnTargets) {
983 Branch->addDestination(Target);
984 // The target may be a block that we excepted to get pruned.
985 // If it is, it may contain a call to llvm.eh.endcatch.
986 if (CheckedTargets.insert(Target)) {
987 // Earlier preparations guarantee that all calls to llvm.eh.endcatch
988 // will be followed by an unconditional branch.
989 auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
990 if (Br && Br->isUnconditional() &&
991 Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
992 Instruction *Prev = Br->getPrevNode();
993 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
994 Prev->eraseFromParent();
995 }
996 }
997 }
998 }
999 LPadImpls.clear();
1000
David Majnemercde33032015-03-30 22:58:10 +00001001 F.addFnAttr("wineh-parent", F.getName());
1002
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001003 // Delete any blocks that were only used by handlers that were outlined above.
1004 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001005
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001006 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001007 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001008 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001009
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001010 Function *FrameEscapeFn =
Reid Kleckner60381792015-07-07 22:25:32 +00001011 Intrinsic::getDeclaration(M, Intrinsic::localescape);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001012 Function *RecoverFrameFn =
Reid Kleckner60381792015-07-07 22:25:32 +00001013 Intrinsic::getDeclaration(M, Intrinsic::localrecover);
Reid Klecknerf14787d2015-04-22 00:07:52 +00001014 SmallVector<Value *, 8> AllocasToEscape;
1015
Reid Kleckner60381792015-07-07 22:25:32 +00001016 // Scan the entry block for an existing call to llvm.localescape. We need to
Reid Klecknerf14787d2015-04-22 00:07:52 +00001017 // keep escaping those objects.
1018 for (Instruction &I : F.front()) {
1019 auto *II = dyn_cast<IntrinsicInst>(&I);
Reid Kleckner60381792015-07-07 22:25:32 +00001020 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
Reid Klecknerf14787d2015-04-22 00:07:52 +00001021 auto Args = II->arg_operands();
1022 AllocasToEscape.append(Args.begin(), Args.end());
1023 II->eraseFromParent();
1024 break;
1025 }
1026 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001027
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001028 // Finally, replace all of the temporary allocas for frame variables used in
Reid Kleckner60381792015-07-07 22:25:32 +00001029 // the outlined handlers with calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001030 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +00001031 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001032 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Reid Klecknerfd7df282015-04-22 21:05:21 +00001033 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
Andrew Kaylor72029c62015-03-03 00:41:03 +00001034
Reid Klecknerb4019412015-04-06 18:50:38 +00001035 // FIXME: We should try to sink unescaped allocas from the parent frame into
1036 // the child frame. If the alloca is escaped, we have to use the lifetime
1037 // markers to ensure that the alloca is only live within the child frame.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001038
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001039 // Add this alloca to the list of things to escape.
1040 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001041
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001042 // Next replace all outlined allocas that are mapped to it.
1043 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +00001044 if (TempAlloca == getCatchObjectSentinel())
1045 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001046 Function *HandlerFn = TempAlloca->getParent()->getParent();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001047 llvm::Value *FP = HandlerToParentFP[HandlerFn];
1048 assert(FP);
1049
Reid Kleckner60381792015-07-07 22:25:32 +00001050 // FIXME: Sink this localrecover into the blocks where it is used.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001051 Builder.SetInsertPoint(TempAlloca);
1052 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1053 Value *RecoverArgs[] = {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001054 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001055 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001056 Instruction *RecoveredAlloca =
1057 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1058
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001059 // Add a pointer bitcast if the alloca wasn't an i8.
1060 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1061 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001062 RecoveredAlloca = cast<Instruction>(
1063 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001064 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001065 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1066 TempAlloca->removeFromParent();
1067 RecoveredAlloca->takeName(TempAlloca);
1068 delete TempAlloca;
1069 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001070 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001071
Reid Kleckner60381792015-07-07 22:25:32 +00001072 // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001073 // block.
1074 Builder.SetInsertPoint(&F.getEntryBlock().back());
1075 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1076
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001077 if (SEHExceptionCodeSlot) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00001078 if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1079 SmallPtrSet<BasicBlock *, 4> UserBlocks;
1080 for (User *U : SEHExceptionCodeSlot->users()) {
1081 if (auto *Inst = dyn_cast<Instruction>(U))
1082 UserBlocks.insert(Inst->getParent());
1083 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001084 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001085 // After the promotion, kill off dead instructions.
1086 for (BasicBlock *BB : UserBlocks)
1087 SimplifyInstructionsInBlock(BB, LibInfo);
1088 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001089 }
1090
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001091 // Clean up the handler action maps we created for this function
1092 DeleteContainerSeconds(CatchHandlerMap);
1093 CatchHandlerMap.clear();
1094 DeleteContainerSeconds(CleanupHandlerMap);
1095 CleanupHandlerMap.clear();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001096 HandlerToParentFP.clear();
1097 DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +00001098 LibInfo = nullptr;
Ahmed Bougachaed363c52015-05-06 01:28:58 +00001099 SEHExceptionCodeSlot = nullptr;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001100 EHBlocks.clear();
1101 NormalBlocks.clear();
1102 EHReturnBlocks.clear();
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001103
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001104 return HandlersOutlined;
1105}
1106
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001107void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1108 // If the return values of the landing pad instruction are extracted and
1109 // stored to memory, we want to promote the store locations to reg values.
1110 SmallVector<AllocaInst *, 2> EHAllocas;
1111
1112 // The landingpad instruction returns an aggregate value. Typically, its
1113 // value will be passed to a pair of extract value instructions and the
1114 // results of those extracts are often passed to store instructions.
1115 // In unoptimized code the stored value will often be loaded and then stored
1116 // again.
1117 for (auto *U : LPad->users()) {
1118 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1119 if (!Extract)
1120 continue;
1121
1122 for (auto *EU : Extract->users()) {
1123 if (auto *Store = dyn_cast<StoreInst>(EU)) {
1124 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1125 EHAllocas.push_back(AV);
1126 }
1127 }
1128 }
1129
1130 // We can't do this without a dominator tree.
1131 assert(DT);
1132
1133 if (!EHAllocas.empty()) {
1134 PromoteMemToReg(EHAllocas, *DT);
1135 EHAllocas.clear();
1136 }
Reid Kleckner86762142015-04-16 00:02:04 +00001137
1138 // After promotion, some extracts may be trivially dead. Remove them.
1139 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1140 for (auto *U : Users)
1141 RecursivelyDeleteTriviallyDeadInstructions(U);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001142}
1143
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001144void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1145 Function *HandlerF,
1146 SetVector<BasicBlock*> &Targets) {
1147 for (BasicBlock &BB : *HandlerF) {
1148 // If the handler contains landing pads, check for any
1149 // handlers that may return directly to a block in the
1150 // parent function.
1151 if (auto *LPI = BB.getLandingPadInst()) {
1152 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
Benjamin Kramera48e0652015-05-16 15:40:03 +00001153 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001154 parseEHActions(Recover, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001155 for (const auto &Action : ActionList) {
1156 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001157 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1158 getPossibleReturnTargets(ParentF, NestedF, Targets);
1159 }
1160 }
1161 }
1162
1163 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1164 if (!Ret)
1165 continue;
1166
1167 // Handler functions must always return a block address.
1168 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1169
1170 // If this is the handler for a nested landing pad, the
1171 // return address may have been remapped to a block in the
1172 // parent handler. We're not interested in those.
1173 if (BA->getFunction() != ParentF)
1174 continue;
1175
1176 Targets.insert(BA->getBasicBlock());
1177 }
1178}
1179
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001180void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1181 LandingPadInst *OutlinedLPad,
1182 const LandingPadInst *OriginalLPad,
1183 FrameVarInfoMap &FrameVarInfo) {
1184 // Get the nested block and erase the unreachable instruction that was
1185 // temporarily inserted as its terminator.
1186 LLVMContext &Context = ParentFn->getContext();
1187 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001188 // If the nested landing pad was outlined before the landing pad that enclosed
1189 // it, it will already be in outlined form. In that case, we just need to see
1190 // if the returns and the enclosing branch instruction need to be updated.
1191 IndirectBrInst *Branch =
1192 dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1193 if (!Branch) {
1194 // If the landing pad wasn't in outlined form, it should be a stub with
1195 // an unreachable terminator.
1196 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1197 OutlinedBB->getTerminator()->eraseFromParent();
1198 // That should leave OutlinedLPad as the last instruction in its block.
1199 assert(&OutlinedBB->back() == OutlinedLPad);
1200 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001201
1202 // The original landing pad will have already had its action intrinsic
1203 // built by the outlining loop. We need to clone that into the outlined
1204 // location. It may also be necessary to add references to the exception
1205 // variables to the outlined handler in which this landing pad is nested
1206 // and remap return instructions in the nested handlers that should return
1207 // to an address in the outlined handler.
1208 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001209 BasicBlock::const_iterator II = OriginalLPad;
1210 ++II;
1211 // The instruction after the landing pad should now be a call to eh.actions.
1212 const Instruction *Recover = II;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001213 const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001214
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001215 // Remap the return target in the nested handler.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001216 SmallVector<BlockAddress *, 4> ActionTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +00001217 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001218 parseEHActions(EHActions, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001219 for (const auto &Action : ActionList) {
1220 auto *Catch = dyn_cast<CatchHandler>(Action.get());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001221 if (!Catch)
1222 continue;
1223 // The dyn_cast to function here selects C++ catch handlers and skips
1224 // SEH catch handlers.
1225 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1226 if (!Handler)
1227 continue;
1228 // Visit all the return instructions, looking for places that return
1229 // to a location within OutlinedHandlerFn.
1230 for (BasicBlock &NestedHandlerBB : *Handler) {
1231 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1232 if (!Ret)
1233 continue;
1234
1235 // Handler functions must always return a block address.
1236 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1237 // The original target will have been in the main parent function,
1238 // but if it is the address of a block that has been outlined, it
1239 // should be a block that was outlined into OutlinedHandlerFn.
1240 assert(BA->getFunction() == ParentFn);
1241
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001242 // Ignore targets that aren't part of an outlined handler function.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001243 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1244 continue;
1245
1246 // If the return value is the address ofF a block that we
1247 // previously outlined into the parent handler function, replace
1248 // the return instruction and add the mapped target to the list
1249 // of possible return addresses.
1250 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1251 assert(MappedBB->getParent() == OutlinedHandlerFn);
1252 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1253 Ret->eraseFromParent();
1254 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1255 ActionTargets.push_back(NewBA);
1256 }
1257 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +00001258 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001259
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001260 if (Branch) {
1261 // If the landing pad was already in outlined form, just update its targets.
1262 for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1263 Branch->removeDestination(I);
1264 // Add the previously collected action targets.
1265 for (auto *Target : ActionTargets)
1266 Branch->addDestination(Target->getBasicBlock());
1267 } else {
1268 // If the landing pad was previously stubbed out, fill in its outlined form.
1269 IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1270 OutlinedBB->getInstList().push_back(NewEHActions);
1271
1272 // Insert an indirect branch into the outlined landing pad BB.
1273 IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1274 // Add the previously collected action targets.
1275 for (auto *Target : ActionTargets)
1276 IBr->addDestination(Target->getBasicBlock());
1277 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001278}
1279
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001280// This function examines a block to determine whether the block ends with a
1281// conditional branch to a catch handler based on a selector comparison.
1282// This function is used both by the WinEHPrepare::findSelectorComparison() and
1283// WinEHCleanupDirector::handleTypeIdFor().
1284static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1285 Constant *&Selector, BasicBlock *&NextBB) {
1286 ICmpInst::Predicate Pred;
1287 BasicBlock *TBB, *FBB;
1288 Value *LHS, *RHS;
1289
1290 if (!match(BB->getTerminator(),
1291 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1292 return false;
1293
1294 if (!match(LHS,
1295 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1296 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1297 return false;
1298
1299 if (Pred == CmpInst::ICMP_EQ) {
1300 CatchHandler = TBB;
1301 NextBB = FBB;
1302 return true;
1303 }
1304
1305 if (Pred == CmpInst::ICMP_NE) {
1306 CatchHandler = FBB;
1307 NextBB = TBB;
1308 return true;
1309 }
1310
1311 return false;
1312}
1313
Andrew Kaylor41758512015-04-20 22:04:09 +00001314static bool isCatchBlock(BasicBlock *BB) {
1315 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1316 II != IE; ++II) {
1317 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1318 return true;
1319 }
1320 return false;
1321}
1322
David Majnemer7fddecc2015-06-17 20:52:32 +00001323static BasicBlock *createStubLandingPad(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001324 // FIXME: Finish this!
1325 LLVMContext &Context = Handler->getContext();
1326 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1327 Handler->getBasicBlockList().push_back(StubBB);
1328 IRBuilder<> Builder(StubBB);
1329 LandingPadInst *LPad = Builder.CreateLandingPad(
1330 llvm::StructType::get(Type::getInt8PtrTy(Context),
1331 Type::getInt32Ty(Context), nullptr),
David Majnemer7fddecc2015-06-17 20:52:32 +00001332 0);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001333 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
Andrew Kaylor91307432015-04-28 22:01:51 +00001334 Function *ActionIntrin =
1335 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
David Blaikieff6409d2015-05-18 22:13:54 +00001336 Builder.CreateCall(ActionIntrin, {}, "recover");
Andrew Kaylorbb111322015-04-07 21:30:23 +00001337 LPad->setCleanup(true);
1338 Builder.CreateUnreachable();
1339 return StubBB;
1340}
1341
1342// Cycles through the blocks in an outlined handler function looking for an
1343// invoke instruction and inserts an invoke of llvm.donothing with an empty
1344// landing pad if none is found. The code that generates the .xdata tables for
1345// the handler needs at least one landing pad to identify the parent function's
1346// personality.
David Majnemer7fddecc2015-06-17 20:52:32 +00001347void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001348 ReturnInst *Ret = nullptr;
Andrew Kaylor5f715522015-04-23 18:37:39 +00001349 UnreachableInst *Unreached = nullptr;
Andrew Kaylorbb111322015-04-07 21:30:23 +00001350 for (BasicBlock &BB : *Handler) {
1351 TerminatorInst *Terminator = BB.getTerminator();
1352 // If we find an invoke, there is nothing to be done.
1353 auto *II = dyn_cast<InvokeInst>(Terminator);
1354 if (II)
1355 return;
1356 // If we've already recorded a return instruction, keep looking for invokes.
Andrew Kaylor5f715522015-04-23 18:37:39 +00001357 if (!Ret)
1358 Ret = dyn_cast<ReturnInst>(Terminator);
1359 // If we haven't recorded an unreachable instruction, try this terminator.
1360 if (!Unreached)
1361 Unreached = dyn_cast<UnreachableInst>(Terminator);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001362 }
1363
1364 // If we got this far, the handler contains no invokes. We should have seen
Andrew Kaylor5f715522015-04-23 18:37:39 +00001365 // at least one return or unreachable instruction. We'll insert an invoke of
1366 // llvm.donothing ahead of that instruction.
1367 assert(Ret || Unreached);
1368 TerminatorInst *Term;
1369 if (Ret)
1370 Term = Ret;
1371 else
1372 Term = Unreached;
1373 BasicBlock *OldRetBB = Term->getParent();
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001374 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001375 // SplitBlock adds an unconditional branch instruction at the end of the
1376 // parent block. We want to replace that with an invoke call, so we can
1377 // erase it now.
1378 OldRetBB->getTerminator()->eraseFromParent();
David Majnemer7fddecc2015-06-17 20:52:32 +00001379 BasicBlock *StubLandingPad = createStubLandingPad(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001380 Function *F =
1381 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1382 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1383}
1384
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001385// FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1386// usually doesn't build LLVM IR, so that's probably the wrong place.
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001387Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1388 const Twine &Name, Module *M,
1389 Value *&ParentFP) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001390 // x64 uses a two-argument prototype where the parent FP is the second
1391 // argument. x86 uses no arguments, just the incoming EBP value.
1392 LLVMContext &Context = M->getContext();
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001393 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001394 FunctionType *FnType;
1395 if (TheTriple.getArch() == Triple::x86_64) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001396 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1397 FnType = FunctionType::get(RetTy, ArgTys, false);
1398 } else {
1399 FnType = FunctionType::get(RetTy, None, false);
1400 }
1401
1402 Function *Handler =
1403 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1404 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1405 Handler->getBasicBlockList().push_front(Entry);
1406 if (TheTriple.getArch() == Triple::x86_64) {
1407 ParentFP = &(Handler->getArgumentList().back());
1408 } else {
1409 assert(M);
1410 Function *FrameAddressFn =
1411 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001412 Function *RecoverFPFn =
1413 Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1414 IRBuilder<> Builder(&Handler->getEntryBlock());
1415 Value *EBP =
1416 Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1417 Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1418 ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001419 }
1420 return Handler;
1421}
1422
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001423bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1424 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001425 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001426 Module *M = SrcFn->getParent();
1427 LLVMContext &Context = M->getContext();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001428 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001429
1430 // Create a new function to receive the handler contents.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001431 Value *ParentFP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001432 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001433 if (Action->getType() == Catch) {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001434 Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001435 ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001436 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001437 Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001438 SrcFn->getName() + ".cleanup", M, ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001439 }
David Majnemer7fddecc2015-06-17 20:52:32 +00001440 Handler->setPersonalityFn(SrcFn->getPersonalityFn());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001441 HandlerToParentFP[Handler] = ParentFP;
David Majnemercde33032015-03-30 22:58:10 +00001442 Handler->addFnAttr("wineh-parent", SrcFn->getName());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001443 BasicBlock *Entry = &Handler->getEntryBlock();
David Majnemercde33032015-03-30 22:58:10 +00001444
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001445 // Generate a standard prolog to setup the frame recovery structure.
1446 IRBuilder<> Builder(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001447 Builder.SetInsertPoint(Entry);
1448 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1449
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001450 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001451
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001452 ValueToValueMapTy VMap;
1453
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001454 LandingPadMap &LPadMap = LPadMaps[LPad];
1455 if (!LPadMap.isInitialized())
1456 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001457 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1458 Constant *Sel = CatchAction->getSelector();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001459 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1460 LPadMap, NestedLPtoOriginalLP, DT,
1461 EHBlocks));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001462 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1463 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001464 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001465 Director.reset(
1466 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001467 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1468 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001469 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001470
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001471 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001472 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001473
Andrew Kaylor3170e562015-03-20 21:42:54 +00001474 // If the start block contains PHI nodes, we need to map them.
1475 BasicBlock::iterator II = StartBB->begin();
1476 while (auto *PN = dyn_cast<PHINode>(II)) {
1477 bool Mapped = false;
1478 // Look for PHI values that we have already mapped (such as the selector).
1479 for (Value *Val : PN->incoming_values()) {
1480 if (VMap.count(Val)) {
1481 VMap[PN] = VMap[Val];
1482 Mapped = true;
1483 }
1484 }
1485 // If we didn't find a match for this value, map it as an undef.
1486 if (!Mapped) {
1487 VMap[PN] = UndefValue::get(PN->getType());
1488 }
1489 ++II;
1490 }
1491
Andrew Kaylor00e5d9e2015-04-20 22:53:42 +00001492 // The landing pad value may be used by PHI nodes. It will ultimately be
1493 // eliminated, but we need it in the map for intermediate handling.
1494 VMap[LPad] = UndefValue::get(LPad->getType());
1495
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001496 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +00001497 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001498
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001499 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001500 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001501 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001502
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001503 // Move all the instructions in the cloned "entry" block into our entry block.
1504 // Depending on how the parent function was laid out, the block that will
1505 // correspond to the outlined entry block may not be the first block in the
1506 // list. We can recognize it, however, as the cloned block which has no
1507 // predecessors. Any other block wouldn't have been cloned if it didn't
1508 // have a predecessor which was also cloned.
Andrew Kaylor91307432015-04-28 22:01:51 +00001509 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001510 while (!pred_empty(ClonedIt))
1511 ++ClonedIt;
1512 BasicBlock *ClonedEntryBB = ClonedIt;
1513 assert(ClonedEntryBB);
1514 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1515 ClonedEntryBB->eraseFromParent();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001516
Andrew Kaylorbb111322015-04-07 21:30:23 +00001517 // Make sure we can identify the handler's personality later.
David Majnemer7fddecc2015-06-17 20:52:32 +00001518 addStubInvokeToHandlerIfNeeded(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001519
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001520 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1521 WinEHCatchDirector *CatchDirector =
1522 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1523 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1524 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001525
1526 // Look for blocks that are not part of the landing pad that we just
1527 // outlined but terminate with a call to llvm.eh.endcatch and a
1528 // branch to a block that is in the handler we just outlined.
1529 // These blocks will be part of a nested landing pad that intends to
1530 // return to an address in this handler. This case is best handled
1531 // after both landing pads have been outlined, so for now we'll just
1532 // save the association of the blocks in LPadTargetBlocks. The
1533 // return instructions which are created from these branches will be
1534 // replaced after all landing pads have been outlined.
Richard Trieu6b1aa5f2015-04-15 01:21:15 +00001535 for (const auto MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001536 // VMap maps all values and blocks that were just cloned, but dead
1537 // blocks which were pruned will map to nullptr.
1538 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1539 continue;
1540 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1541 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1542 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1543 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1544 continue;
1545 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1546 --II;
1547 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1548 // This would indicate that a nested landing pad wants to return
1549 // to a block that is outlined into two different handlers.
1550 assert(!LPadTargetBlocks.count(MappedBB));
1551 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1552 }
1553 }
1554 }
1555 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001556
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001557 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001558
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001559 return true;
1560}
1561
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001562/// This BB must end in a selector dispatch. All we need to do is pass the
1563/// handler block to llvm.eh.actions and list it as a possible indirectbr
1564/// target.
1565void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1566 BasicBlock *StartBB) {
1567 BasicBlock *HandlerBB;
1568 BasicBlock *NextBB;
1569 Constant *Selector;
1570 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1571 if (Res) {
1572 // If this was EH dispatch, this must be a conditional branch to the handler
1573 // block.
1574 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1575 // leading to crashes if some optimization hoists stuff here.
1576 assert(CatchAction->getSelector() && HandlerBB &&
1577 "expected catch EH dispatch");
1578 } else {
1579 // This must be a catch-all. Split the block after the landingpad.
1580 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001581 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001582 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001583 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1584 Function *EHCodeFn = Intrinsic::getDeclaration(
1585 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
David Blaikieff6409d2015-05-18 22:13:54 +00001586 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001587 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1588 Builder.CreateStore(Code, SEHExceptionCodeSlot);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001589 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1590 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1591 CatchAction->setReturnTargets(Targets);
1592}
1593
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001594void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1595 // Each instance of this class should only ever be used to map a single
1596 // landing pad.
1597 assert(OriginLPad == nullptr || OriginLPad == LPad);
1598
1599 // If the landing pad has already been mapped, there's nothing more to do.
1600 if (OriginLPad == LPad)
1601 return;
1602
1603 OriginLPad = LPad;
1604
1605 // The landingpad instruction returns an aggregate value. Typically, its
1606 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001607 // results of those extracts will have been promoted to reg values before
1608 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001609 for (auto *U : LPad->users()) {
1610 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1611 if (!Extract)
1612 continue;
1613 assert(Extract->getNumIndices() == 1 &&
1614 "Unexpected operation: extracting both landing pad values");
1615 unsigned int Idx = *(Extract->idx_begin());
1616 assert((Idx == 0 || Idx == 1) &&
1617 "Unexpected operation: extracting an unknown landing pad element");
1618 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001619 ExtractedEHPtrs.push_back(Extract);
1620 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001621 ExtractedSelectors.push_back(Extract);
1622 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001623 }
1624}
1625
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001626bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1627 return BB->getLandingPadInst() == OriginLPad;
1628}
1629
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001630bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1631 if (Inst == OriginLPad)
1632 return true;
1633 for (auto *Extract : ExtractedEHPtrs) {
1634 if (Inst == Extract)
1635 return true;
1636 }
1637 for (auto *Extract : ExtractedSelectors) {
1638 if (Inst == Extract)
1639 return true;
1640 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001641 return false;
1642}
1643
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001644void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1645 Value *SelectorValue) const {
1646 // Remap all landing pad extract instructions to the specified values.
1647 for (auto *Extract : ExtractedEHPtrs)
1648 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001649 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001650 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001651}
1652
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001653static bool isLocalAddressCall(const Value *V) {
1654 return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
Reid Klecknerf14787d2015-04-22 00:07:52 +00001655}
1656
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001657CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001658 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001659 // If this is one of the boilerplate landing pad instructions, skip it.
1660 // The instruction will have already been remapped in VMap.
1661 if (LPadMap.isLandingPadSpecificInst(Inst))
1662 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001663
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001664 // Nested landing pads that have not already been outlined will be cloned as
1665 // stubs, with just the landingpad instruction and an unreachable instruction.
1666 // When all landingpads have been outlined, we'll replace this with the
1667 // llvm.eh.actions call and indirect branch created when the landing pad was
1668 // outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001669 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1670 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001671 }
1672
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001673 // Nested landing pads that have already been outlined will be cloned in their
1674 // outlined form, but we need to intercept the ibr instruction to filter out
1675 // targets that do not return to the handler we are outlining.
1676 if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1677 return handleIndirectBr(VMap, IBr, NewBB);
1678 }
1679
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001680 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1681 return handleInvoke(VMap, Invoke, NewBB);
1682
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001683 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1684 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001685
Andrew Kaylorea8df612015-04-17 23:05:43 +00001686 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1687 return handleCompare(VMap, Cmp, NewBB);
1688
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001689 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1690 return handleBeginCatch(VMap, Inst, NewBB);
1691 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1692 return handleEndCatch(VMap, Inst, NewBB);
1693 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1694 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001695
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001696 // When outlining llvm.localaddress(), remap that to the second argument,
Reid Klecknerf14787d2015-04-22 00:07:52 +00001697 // which is the FP of the parent.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001698 if (isLocalAddressCall(Inst)) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001699 VMap[Inst] = ParentFP;
Reid Klecknerf14787d2015-04-22 00:07:52 +00001700 return CloningDirector::SkipInstruction;
1701 }
1702
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001703 // Continue with the default cloning behavior.
1704 return CloningDirector::CloneInstruction;
1705}
1706
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001707CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1708 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001709 // If the instruction after the landing pad is a call to llvm.eh.actions
1710 // the landing pad has already been outlined. In this case, we should
1711 // clone it because it may return to a block in the handler we are
1712 // outlining now that would otherwise be unreachable. The landing pads
1713 // are sorted before outlining begins to enable this case to work
1714 // properly.
1715 const Instruction *NextI = LPad->getNextNode();
1716 if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1717 return CloningDirector::CloneInstruction;
1718
1719 // If the landing pad hasn't been outlined yet, the landing pad we are
1720 // outlining now does not dominate it and so it cannot return to a block
1721 // in this handler. In that case, we can just insert a stub landing
1722 // pad now and patch it up later.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001723 Instruction *NewInst = LPad->clone();
1724 if (LPad->hasName())
1725 NewInst->setName(LPad->getName());
1726 // Save this correlation for later processing.
1727 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1728 VMap[LPad] = NewInst;
1729 BasicBlock::InstListType &InstList = NewBB->getInstList();
1730 InstList.push_back(NewInst);
1731 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1732 return CloningDirector::StopCloningBB;
1733}
1734
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001735CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1736 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1737 // The argument to the call is some form of the first element of the
1738 // landingpad aggregate value, but that doesn't matter. It isn't used
1739 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001740 // The second argument is an outparameter where the exception object will be
1741 // stored. Typically the exception object is a scalar, but it can be an
1742 // aggregate when catching by value.
1743 // FIXME: Leave something behind to indicate where the exception object lives
1744 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001745 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1746 "llvm.eh.begincatch found while "
1747 "outlining catch handler.");
1748 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001749 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1750 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001751 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1752 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001753 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001754 return CloningDirector::SkipInstruction;
1755}
1756
1757CloningDirector::CloningAction
1758WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1759 const Instruction *Inst, BasicBlock *NewBB) {
1760 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1761 // It might be interesting to track whether or not we are inside a catch
1762 // function, but that might make the algorithm more brittle than it needs
1763 // to be.
1764
1765 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001766 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001767 // or at the end of the catch block. However, a catch-all handler may call
1768 // end catch from the original landing pad. If the call occurs in a nested
1769 // landing pad block, we must skip it and continue so that the landing pad
1770 // gets cloned.
1771 auto *ParentBB = IntrinCall->getParent();
1772 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001773 return CloningDirector::SkipInstruction;
1774
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001775 // If an end catch occurs anywhere else we want to terminate the handler
1776 // with a return to the code that follows the endcatch call. If the
1777 // next instruction is not an unconditional branch, we need to split the
1778 // block to provide a clear target for the return instruction.
1779 BasicBlock *ContinueBB;
1780 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1781 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1782 if (!Branch || !Branch->isUnconditional()) {
1783 // We're interrupting the cloning process at this location, so the
1784 // const_cast we're doing here will not cause a problem.
1785 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1786 const_cast<Instruction *>(cast<Instruction>(Next)));
1787 } else {
1788 ContinueBB = Branch->getSuccessor(0);
1789 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001790
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001791 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1792 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001793
1794 // We just added a terminator to the cloned block.
1795 // Tell the caller to stop processing the current basic block so that
1796 // the branch instruction will be skipped.
1797 return CloningDirector::StopCloningBB;
1798}
1799
1800CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1801 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1802 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1803 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1804 // This causes a replacement that will collapse the landing pad CFG based
1805 // on the filter function we intend to match.
1806 if (Selector == CurrentSelector)
1807 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1808 else
1809 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1810 // Tell the caller not to clone this instruction.
1811 return CloningDirector::SkipInstruction;
1812}
1813
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001814CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1815 ValueToValueMapTy &VMap,
1816 const IndirectBrInst *IBr,
1817 BasicBlock *NewBB) {
1818 // If this indirect branch is not part of a landing pad block, just clone it.
1819 const BasicBlock *ParentBB = IBr->getParent();
1820 if (!ParentBB->isLandingPad())
1821 return CloningDirector::CloneInstruction;
1822
1823 // If it is part of a landing pad, we want to filter out target blocks
1824 // that are not part of the handler we are outlining.
1825 const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1826
1827 // Save this correlation for later processing.
1828 NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1829
1830 // We should only get here for landing pads that have already been outlined.
1831 assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1832
1833 // Copy the indirectbr, but only include targets that were previously
1834 // identified as EH blocks and are dominated by the nested landing pad.
1835 SetVector<const BasicBlock *> ReturnTargets;
1836 for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1837 auto *TargetBB = IBr->getDestination(I);
1838 if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1839 DT->dominates(ParentBB, TargetBB)) {
1840 DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n");
1841 ReturnTargets.insert(TargetBB);
1842 }
1843 }
1844 IndirectBrInst *NewBranch =
1845 IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1846 ReturnTargets.size(), NewBB);
1847 for (auto *Target : ReturnTargets)
1848 NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1849
1850 // The operands and targets of the branch instruction are remapped later
1851 // because it is a terminator. Tell the cloning code to clone the
1852 // blocks we just added to the target list.
1853 return CloningDirector::CloneSuccessors;
1854}
1855
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001856CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001857WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1858 const InvokeInst *Invoke, BasicBlock *NewBB) {
1859 return CloningDirector::CloneInstruction;
1860}
1861
1862CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001863WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1864 const ResumeInst *Resume, BasicBlock *NewBB) {
1865 // Resume instructions shouldn't be reachable from catch handlers.
1866 // We still need to handle it, but it will be pruned.
1867 BasicBlock::InstListType &InstList = NewBB->getInstList();
1868 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1869 return CloningDirector::StopCloningBB;
1870}
1871
Andrew Kaylorea8df612015-04-17 23:05:43 +00001872CloningDirector::CloningAction
1873WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1874 const CmpInst *Compare, BasicBlock *NewBB) {
1875 const IntrinsicInst *IntrinCall = nullptr;
1876 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1877 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
Andrew Kaylor91307432015-04-28 22:01:51 +00001878 } else if (match(Compare->getOperand(1),
1879 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001880 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1881 }
1882 if (IntrinCall) {
1883 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1884 // This causes a replacement that will collapse the landing pad CFG based
1885 // on the filter function we intend to match.
1886 if (Selector == CurrentSelector->stripPointerCasts()) {
1887 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
Andrew Kaylor91307432015-04-28 22:01:51 +00001888 } else {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001889 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1890 }
1891 return CloningDirector::SkipInstruction;
1892 }
1893 return CloningDirector::CloneInstruction;
1894}
1895
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001896CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1897 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1898 // The MS runtime will terminate the process if an exception occurs in a
1899 // cleanup handler, so we shouldn't encounter landing pads in the actual
1900 // cleanup code, but they may appear in catch blocks. Depending on where
1901 // we started cloning we may see one, but it will get dropped during dead
1902 // block pruning.
1903 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1904 VMap[LPad] = NewInst;
1905 BasicBlock::InstListType &InstList = NewBB->getInstList();
1906 InstList.push_back(NewInst);
1907 return CloningDirector::StopCloningBB;
1908}
1909
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001910CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1911 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001912 // Cleanup code may flow into catch blocks or the catch block may be part
1913 // of a branch that will be optimized away. We'll insert a return
1914 // instruction now, but it may be pruned before the cloning process is
1915 // complete.
1916 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001917 return CloningDirector::StopCloningBB;
1918}
1919
1920CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1921 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001922 // Cleanup handlers nested within catch handlers may begin with a call to
1923 // eh.endcatch. We can just ignore that instruction.
1924 return CloningDirector::SkipInstruction;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001925}
1926
1927CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1928 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001929 // If we encounter a selector comparison while cloning a cleanup handler,
1930 // we want to stop cloning immediately. Anything after the dispatch
1931 // will be outlined into a different handler.
1932 BasicBlock *CatchHandler;
1933 Constant *Selector;
1934 BasicBlock *NextBB;
1935 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1936 CatchHandler, Selector, NextBB)) {
1937 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1938 return CloningDirector::StopCloningBB;
1939 }
1940 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001941 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001942 return CloningDirector::SkipInstruction;
1943}
1944
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001945CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1946 ValueToValueMapTy &VMap,
1947 const IndirectBrInst *IBr,
1948 BasicBlock *NewBB) {
1949 // No special handling is required for cleanup cloning.
1950 return CloningDirector::CloneInstruction;
1951}
1952
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001953CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1954 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1955 // All invokes in cleanup handlers can be replaced with calls.
1956 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1957 // Insert a normal call instruction...
1958 CallInst *NewCall =
1959 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1960 Invoke->getName(), NewBB);
1961 NewCall->setCallingConv(Invoke->getCallingConv());
1962 NewCall->setAttributes(Invoke->getAttributes());
1963 NewCall->setDebugLoc(Invoke->getDebugLoc());
1964 VMap[Invoke] = NewCall;
1965
Reid Kleckner6e48a822015-04-10 16:26:42 +00001966 // Remap the operands.
1967 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1968
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001969 // Insert an unconditional branch to the normal destination.
1970 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1971
1972 // The unwind destination won't be cloned into the new function, so
1973 // we don't need to clean up its phi nodes.
1974
1975 // We just added a terminator to the cloned block.
1976 // Tell the caller to stop processing the current basic block.
Reid Kleckner6e48a822015-04-10 16:26:42 +00001977 return CloningDirector::CloneSuccessors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001978}
1979
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001980CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1981 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1982 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1983
1984 // We just added a terminator to the cloned block.
1985 // Tell the caller to stop processing the current basic block so that
1986 // the branch instruction will be skipped.
1987 return CloningDirector::StopCloningBB;
1988}
1989
Andrew Kaylorea8df612015-04-17 23:05:43 +00001990CloningDirector::CloningAction
1991WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1992 const CmpInst *Compare, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001993 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1994 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1995 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1996 return CloningDirector::SkipInstruction;
1997 }
1998 return CloningDirector::CloneInstruction;
Andrew Kaylorea8df612015-04-17 23:05:43 +00001999}
2000
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002001WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00002002 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002003 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002004 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00002005
2006 // New allocas should be inserted in the entry block, but after the parent FP
2007 // is established if it is an instruction.
2008 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
2009 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
2010 InsertPoint = FPInst->getNextNode();
2011 Builder.SetInsertPoint(EntryBB, InsertPoint);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002012}
2013
2014Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002015 // If we're asked to materialize a static alloca, we temporarily create an
2016 // alloca in the outlined function and add this to the FrameVarInfo map. When
2017 // all the outlining is complete, we'll replace these temporary allocas with
Reid Kleckner60381792015-07-07 22:25:32 +00002018 // calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002019 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002020 assert(AV->isStaticAlloca() &&
2021 "cannot materialize un-demoted dynamic alloca");
Andrew Kaylor72029c62015-03-03 00:41:03 +00002022 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
2023 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00002024 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002025 return NewAlloca;
2026 }
2027
Andrew Kaylor72029c62015-03-03 00:41:03 +00002028 if (isa<Instruction>(V) || isa<Argument>(V)) {
Reid Klecknerd1b38c42015-05-06 18:45:24 +00002029 Function *Parent = isa<Instruction>(V)
2030 ? cast<Instruction>(V)->getParent()->getParent()
2031 : cast<Argument>(V)->getParent();
2032 errs()
2033 << "Failed to demote instruction used in exception handler of function "
2034 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
Reid Klecknerfd7df282015-04-22 21:05:21 +00002035 errs() << " " << *V << '\n';
2036 report_fatal_error("WinEHPrepare failed to demote instruction");
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002037 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002038
Andrew Kaylor72029c62015-03-03 00:41:03 +00002039 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002040 return nullptr;
2041}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002042
Reid Kleckner3567d272015-04-02 21:13:31 +00002043void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2044 // Catch parameter objects have to live in the parent frame. When we see a use
2045 // of a catch parameter, add a sentinel to the multimap to indicate that it's
2046 // used from another handler. This will prevent us from trying to sink the
2047 // alloca into the handler and ensure that the catch parameter is present in
Reid Kleckner60381792015-07-07 22:25:32 +00002048 // the call to llvm.localescape.
Reid Kleckner3567d272015-04-02 21:13:31 +00002049 FrameVarInfo[V].push_back(getCatchObjectSentinel());
2050}
2051
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002052// This function maps the catch and cleanup handlers that are reachable from the
2053// specified landing pad. The landing pad sequence will have this basic shape:
2054//
2055// <cleanup handler>
2056// <selector comparison>
2057// <catch handler>
2058// <cleanup handler>
2059// <selector comparison>
2060// <catch handler>
2061// <cleanup handler>
2062// ...
2063//
2064// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
2065// any arbitrary control flow, but all paths through the cleanup code must
2066// eventually reach the next selector comparison and no path can skip to a
2067// different selector comparisons, though some paths may terminate abnormally.
2068// Therefore, we will use a depth first search from the start of any given
2069// cleanup block and stop searching when we find the next selector comparison.
2070//
2071// If the landingpad instruction does not have a catch clause, we will assume
2072// that any instructions other than selector comparisons and catch handlers can
2073// be ignored. In practice, these will only be the boilerplate instructions.
2074//
2075// The catch handlers may also have any control structure, but we are only
2076// interested in the start of the catch handlers, so we don't need to actually
2077// follow the flow of the catch handlers. The start of the catch handlers can
2078// be located from the compare instructions, but they can be skipped in the
2079// flow by following the contrary branch.
2080void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2081 LandingPadActions &Actions) {
2082 unsigned int NumClauses = LPad->getNumClauses();
2083 unsigned int HandlersFound = 0;
2084 BasicBlock *BB = LPad->getParent();
2085
2086 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2087
2088 if (NumClauses == 0) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002089 findCleanupHandlers(Actions, BB, nullptr);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002090 return;
2091 }
2092
2093 VisitedBlockSet VisitedBlocks;
2094
2095 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002096 BasicBlock *NextBB = nullptr;
2097
Andrew Kaylor20ae2a32015-04-23 22:38:36 +00002098 // Skip over filter clauses.
2099 if (LPad->isFilter(HandlersFound)) {
2100 ++HandlersFound;
2101 continue;
2102 }
2103
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002104 // See if the clause we're looking for is a catch-all.
2105 // If so, the catch begins immediately.
Andrew Kaylor91307432015-04-28 22:01:51 +00002106 Constant *ExpectedSelector =
2107 LPad->getClause(HandlersFound)->stripPointerCasts();
Andrew Kaylorea8df612015-04-17 23:05:43 +00002108 if (isa<ConstantPointerNull>(ExpectedSelector)) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002109 // The catch all must occur last.
2110 assert(HandlersFound == NumClauses - 1);
2111
Andrew Kaylorea8df612015-04-17 23:05:43 +00002112 // There can be additional selector dispatches in the call chain that we
2113 // need to ignore.
2114 BasicBlock *CatchBlock = nullptr;
2115 Constant *Selector;
2116 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2117 DEBUG(dbgs() << " Found extra catch dispatch in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002118 << CatchBlock->getName() << "\n");
Andrew Kaylorea8df612015-04-17 23:05:43 +00002119 BB = NextBB;
2120 }
2121
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002122 // Add the catch handler to the action list.
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002123 CatchHandler *Action = nullptr;
2124 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2125 // If the CatchHandlerMap already has an entry for this BB, re-use it.
2126 Action = CatchHandlerMap[BB];
2127 assert(Action->getSelector() == ExpectedSelector);
2128 } else {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002129 // We don't expect a selector dispatch, but there may be a call to
2130 // llvm.eh.begincatch, which separates catch handling code from
2131 // cleanup code in the same control flow. This call looks for the
2132 // begincatch intrinsic.
2133 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2134 if (Action) {
2135 // For C++ EH, check if there is any interesting cleanup code before
2136 // we begin the catch. This is important because cleanups cannot
2137 // rethrow exceptions but code called from catches can. For SEH, it
2138 // isn't important if some finally code before a catch-all is executed
2139 // out of line or after recovering from the exception.
2140 if (Personality == EHPersonality::MSVC_CXX)
2141 findCleanupHandlers(Actions, BB, BB);
2142 } else {
2143 // If an action was not found, it means that the control flows
2144 // directly into the catch-all handler and there is no cleanup code.
2145 // That's an expected situation and we must create a catch action.
2146 // Since this is a catch-all handler, the selector won't actually
2147 // appear in the code anywhere. ExpectedSelector here is the constant
2148 // null ptr that we got from the landing pad instruction.
2149 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2150 CatchHandlerMap[BB] = Action;
2151 }
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002152 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002153 Actions.insertCatchHandler(Action);
2154 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
2155 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002156
2157 // Once we reach a catch-all, don't expect to hit a resume instruction.
2158 BB = nullptr;
2159 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002160 }
2161
2162 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
Andrew Kaylor41758512015-04-20 22:04:09 +00002163 assert(CatchAction);
2164
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002165 // See if there is any interesting code executed before the dispatch.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002166 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002167
Andrew Kaylorea8df612015-04-17 23:05:43 +00002168 // When the source program contains multiple nested try blocks the catch
2169 // handlers can get strung together in such a way that we can encounter
2170 // a dispatch for a selector that we've already had a handler for.
2171 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2172 ++HandlersFound;
2173
2174 // Add the catch handler to the action list.
2175 DEBUG(dbgs() << " Found catch dispatch in block "
2176 << CatchAction->getStartBlock()->getName() << "\n");
2177 Actions.insertCatchHandler(CatchAction);
2178 } else {
Andrew Kaylor41758512015-04-20 22:04:09 +00002179 // Under some circumstances optimized IR will flow unconditionally into a
2180 // handler block without checking the selector. This can only happen if
2181 // the landing pad has a catch-all handler and the handler for the
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002182 // preceding catch clause is identical to the catch-call handler
Andrew Kaylor41758512015-04-20 22:04:09 +00002183 // (typically an empty catch). In this case, the handler must be shared
2184 // by all remaining clauses.
2185 if (isa<ConstantPointerNull>(
2186 CatchAction->getSelector()->stripPointerCasts())) {
2187 DEBUG(dbgs() << " Applying early catch-all handler in block "
2188 << CatchAction->getStartBlock()->getName()
2189 << " to all remaining clauses.\n");
2190 Actions.insertCatchHandler(CatchAction);
2191 return;
2192 }
2193
Andrew Kaylorea8df612015-04-17 23:05:43 +00002194 DEBUG(dbgs() << " Found extra catch dispatch in block "
2195 << CatchAction->getStartBlock()->getName() << "\n");
2196 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002197
2198 // Move on to the block after the catch handler.
2199 BB = NextBB;
2200 }
2201
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002202 // If we didn't wind up in a catch-all, see if there is any interesting code
2203 // executed before the resume.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002204 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002205
2206 // It's possible that some optimization moved code into a landingpad that
2207 // wasn't
2208 // previously being used for cleanup. If that happens, we need to execute
2209 // that
2210 // extra code from a cleanup handler.
2211 if (Actions.includesCleanup() && !LPad->isCleanup())
2212 LPad->setCleanup(true);
2213}
2214
2215// This function searches starting with the input block for the next
2216// block that terminates with a branch whose condition is based on a selector
2217// comparison. This may be the input block. See the mapLandingPadBlocks
2218// comments for a discussion of control flow assumptions.
2219//
2220CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2221 BasicBlock *&NextBB,
2222 VisitedBlockSet &VisitedBlocks) {
2223 // See if we've already found a catch handler use it.
2224 // Call count() first to avoid creating a null entry for blocks
2225 // we haven't seen before.
2226 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2227 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2228 NextBB = Action->getNextBB();
2229 return Action;
2230 }
2231
2232 // VisitedBlocks applies only to the current search. We still
2233 // need to consider blocks that we've visited while mapping other
2234 // landing pads.
2235 VisitedBlocks.insert(BB);
2236
2237 BasicBlock *CatchBlock = nullptr;
2238 Constant *Selector = nullptr;
2239
2240 // If this is the first time we've visited this block from any landing pad
2241 // look to see if it is a selector dispatch block.
2242 if (!CatchHandlerMap.count(BB)) {
2243 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2244 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2245 CatchHandlerMap[BB] = Action;
2246 return Action;
2247 }
Andrew Kaylor41758512015-04-20 22:04:09 +00002248 // If we encounter a block containing an llvm.eh.begincatch before we
2249 // find a selector dispatch block, the handler is assumed to be
2250 // reached unconditionally. This happens for catch-all blocks, but
2251 // it can also happen for other catch handlers that have been combined
2252 // with the catch-all handler during optimization.
2253 if (isCatchBlock(BB)) {
2254 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2255 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2256 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2257 CatchHandlerMap[BB] = Action;
2258 return Action;
2259 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002260 }
2261
2262 // Visit each successor, looking for the dispatch.
2263 // FIXME: We expect to find the dispatch quickly, so this will probably
2264 // work better as a breadth first search.
2265 for (BasicBlock *Succ : successors(BB)) {
2266 if (VisitedBlocks.count(Succ))
2267 continue;
2268
2269 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2270 if (Action)
2271 return Action;
2272 }
2273 return nullptr;
2274}
2275
Reid Kleckner9405ef02015-04-10 23:12:29 +00002276// These are helper functions to combine repeated code from findCleanupHandlers.
2277static void createCleanupHandler(LandingPadActions &Actions,
2278 CleanupHandlerMapTy &CleanupHandlerMap,
2279 BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002280 CleanupHandler *Action = new CleanupHandler(BB);
2281 CleanupHandlerMap[BB] = Action;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002282 Actions.insertCleanupHandler(Action);
2283 DEBUG(dbgs() << " Found cleanup code in block "
2284 << Action->getStartBlock()->getName() << "\n");
2285}
2286
Reid Kleckner9405ef02015-04-10 23:12:29 +00002287static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2288 Instruction *MaybeCall) {
2289 // Look for finally blocks that Clang has already outlined for us.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002290 // %fp = call i8* @llvm.localaddress()
Reid Kleckner9405ef02015-04-10 23:12:29 +00002291 // call void @"fin$parent"(iN 1, i8* %fp)
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002292 if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002293 MaybeCall = MaybeCall->getNextNode();
2294 CallSite FinallyCall(MaybeCall);
2295 if (!FinallyCall || FinallyCall.arg_size() != 2)
2296 return CallSite();
2297 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2298 return CallSite();
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002299 if (!isLocalAddressCall(FinallyCall.getArgument(1)))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002300 return CallSite();
2301 return FinallyCall;
2302}
2303
2304static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2305 // Skip single ubr blocks.
2306 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2307 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2308 if (Br && Br->isUnconditional())
2309 BB = Br->getSuccessor(0);
2310 else
2311 return BB;
2312 }
2313 return BB;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002314}
2315
2316// This function searches starting with the input block for the next block that
2317// contains code that is not part of a catch handler and would not be eliminated
2318// during handler outlining.
2319//
Reid Kleckner9405ef02015-04-10 23:12:29 +00002320void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2321 BasicBlock *StartBB, BasicBlock *EndBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002322 // Here we will skip over the following:
2323 //
2324 // landing pad prolog:
2325 //
2326 // Unconditional branches
2327 //
2328 // Selector dispatch
2329 //
2330 // Resume pattern
2331 //
2332 // Anything else marks the start of an interesting block
2333
2334 BasicBlock *BB = StartBB;
2335 // Anything other than an unconditional branch will kick us out of this loop
2336 // one way or another.
2337 while (BB) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002338 BB = followSingleUnconditionalBranches(BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002339 // If we've already scanned this block, don't scan it again. If it is
2340 // a cleanup block, there will be an action in the CleanupHandlerMap.
2341 // If we've scanned it and it is not a cleanup block, there will be a
2342 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2343 // be no entry in the CleanupHandlerMap. We must call count() first to
2344 // avoid creating a null entry for blocks we haven't scanned.
2345 if (CleanupHandlerMap.count(BB)) {
2346 if (auto *Action = CleanupHandlerMap[BB]) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002347 Actions.insertCleanupHandler(Action);
2348 DEBUG(dbgs() << " Found cleanup code in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002349 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002350 // FIXME: This cleanup might chain into another, and we need to discover
2351 // that.
2352 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002353 } else {
2354 // Here we handle the case where the cleanup handler map contains a
2355 // value for this block but the value is a nullptr. This means that
2356 // we have previously analyzed the block and determined that it did
2357 // not contain any cleanup code. Based on the earlier analysis, we
Eric Christopher572e03a2015-06-19 01:53:21 +00002358 // know the block must end in either an unconditional branch, a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002359 // resume or a conditional branch that is predicated on a comparison
2360 // with a selector. Either the resume or the selector dispatch
2361 // would terminate the search for cleanup code, so the unconditional
2362 // branch is the only case for which we might need to continue
2363 // searching.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002364 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2365 if (SuccBB == BB || SuccBB == EndBB)
2366 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002367 BB = SuccBB;
2368 continue;
2369 }
2370 }
2371
2372 // Create an entry in the cleanup handler map for this block. Initially
2373 // we create an entry that says this isn't a cleanup block. If we find
2374 // cleanup code, the caller will replace this entry.
2375 CleanupHandlerMap[BB] = nullptr;
2376
2377 TerminatorInst *Terminator = BB->getTerminator();
2378
2379 // Landing pad blocks have extra instructions we need to accept.
2380 LandingPadMap *LPadMap = nullptr;
2381 if (BB->isLandingPad()) {
2382 LandingPadInst *LPad = BB->getLandingPadInst();
2383 LPadMap = &LPadMaps[LPad];
2384 if (!LPadMap->isInitialized())
2385 LPadMap->mapLandingPad(LPad);
2386 }
2387
2388 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002389 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2390 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002391 // resume { i8*, i32 } %lpad.val2
2392 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2393 InsertValueInst *Insert1 = nullptr;
2394 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002395 Value *ResumeVal = Resume->getOperand(0);
Reid Kleckner1c130bb2015-04-16 17:02:23 +00002396 // If the resume value isn't a phi or landingpad value, it should be a
2397 // series of insertions. Identify them so we can avoid them when scanning
2398 // for cleanups.
2399 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002400 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002401 if (!Insert2)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002402 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002403 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2404 if (!Insert1)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002405 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002406 }
2407 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2408 II != IE; ++II) {
2409 Instruction *Inst = II;
2410 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2411 continue;
2412 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2413 continue;
2414 if (!Inst->hasOneUse() ||
2415 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002416 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002417 }
2418 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002419 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002420 }
2421
2422 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002423 if (Branch && Branch->isConditional()) {
2424 // Look for the selector dispatch.
2425 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2426 // %matches = icmp eq i32 %sel, %2
2427 // br i1 %matches, label %catch14, label %eh.resume
2428 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2429 if (!Compare || !Compare->isEquality())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002430 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylorbb111322015-04-07 21:30:23 +00002431 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2432 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002433 Instruction *Inst = II;
2434 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2435 continue;
2436 if (Inst == Compare || Inst == Branch)
2437 continue;
2438 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2439 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002440 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002441 }
2442 // The selector dispatch block should always terminate our search.
2443 assert(BB == EndBB);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002444 return;
2445 }
2446
2447 if (isAsynchronousEHPersonality(Personality)) {
2448 // If this is a landingpad block, split the block at the first non-landing
2449 // pad instruction.
2450 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2451 if (LPadMap) {
2452 while (MaybeCall != BB->getTerminator() &&
2453 LPadMap->isLandingPadSpecificInst(MaybeCall))
2454 MaybeCall = MaybeCall->getNextNode();
2455 }
2456
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002457 // Look for outlined finally calls on x64, since those happen to match the
2458 // prototype provided by the runtime.
2459 if (TheTriple.getArch() == Triple::x86_64) {
2460 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2461 Function *Fin = FinallyCall.getCalledFunction();
2462 assert(Fin && "outlined finally call should be direct");
2463 auto *Action = new CleanupHandler(BB);
2464 Action->setHandlerBlockOrFunc(Fin);
2465 Actions.insertCleanupHandler(Action);
2466 CleanupHandlerMap[BB] = Action;
2467 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2468 << Fin->getName() << " in block "
2469 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002470
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002471 // Split the block if there were more interesting instructions and
2472 // look for finally calls in the normal successor block.
2473 BasicBlock *SuccBB = BB;
2474 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2475 FinallyCall.getInstruction()->getNextNode() !=
2476 BB->getTerminator()) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002477 SuccBB =
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002478 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002479 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002480 if (FinallyCall.isInvoke()) {
2481 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2482 ->getNormalDest();
2483 } else {
2484 SuccBB = BB->getUniqueSuccessor();
2485 assert(SuccBB &&
2486 "splitOutlinedFinallyCalls didn't insert a branch");
2487 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002488 }
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002489 BB = SuccBB;
2490 if (BB == EndBB)
2491 return;
2492 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002493 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002494 }
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002495 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002496
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002497 // Anything else is either a catch block or interesting cleanup code.
Andrew Kaylorbb111322015-04-07 21:30:23 +00002498 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2499 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002500 Instruction *Inst = II;
2501 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2502 continue;
2503 // Unconditional branches fall through to this loop.
2504 if (Inst == Branch)
2505 continue;
2506 // If this is a catch block, there is no cleanup code to be found.
2507 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002508 return;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002509 // If this a nested landing pad, it may contain an endcatch call.
2510 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002511 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002512 // Anything else makes this interesting cleanup code.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002513 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002514 }
2515
2516 // Only unconditional branches in empty blocks should get this far.
2517 assert(Branch && Branch->isUnconditional());
2518 if (BB == EndBB)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002519 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002520 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002521 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002522}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002523
2524// This is a public function, declared in WinEHFuncInfo.h and is also
2525// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
Benjamin Kramera48e0652015-05-16 15:40:03 +00002526void llvm::parseEHActions(
2527 const IntrinsicInst *II,
2528 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00002529 assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2530 "attempted to parse non eh.actions intrinsic");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002531 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2532 uint64_t ActionKind =
Andrew Kaylorbb111322015-04-07 21:30:23 +00002533 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002534 if (ActionKind == /*catch=*/1) {
2535 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2536 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2537 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2538 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2539 I += 4;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002540 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2541 /*NextBB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002542 CH->setHandlerBlockOrFunc(Handler);
2543 CH->setExceptionVarIndex(EHObjIndexVal);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002544 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002545 } else if (ActionKind == 0) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002546 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2547 I += 2;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002548 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002549 CH->setHandlerBlockOrFunc(Handler);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002550 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002551 } else {
2552 llvm_unreachable("Expected either a catch or cleanup handler!");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002553 }
2554 }
2555 std::reverse(Actions.begin(), Actions.end());
2556}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002557
2558namespace {
2559struct WinEHNumbering {
2560 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
2561 CurrentBaseState(-1), NextState(0) {}
2562
2563 WinEHFuncInfo &FuncInfo;
2564 int CurrentBaseState;
2565 int NextState;
2566
2567 SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
2568 SmallPtrSet<const Function *, 4> VisitedHandlers;
2569
2570 int currentEHNumber() const {
2571 return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
2572 }
2573
2574 void createUnwindMapEntry(int ToState, ActionHandler *AH);
2575 void createTryBlockMapEntry(int TryLow, int TryHigh,
2576 ArrayRef<CatchHandler *> Handlers);
2577 void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2578 ImmutableCallSite CS);
2579 void popUnmatchedActions(int FirstMismatch);
2580 void calculateStateNumbers(const Function &F);
2581 void findActionRootLPads(const Function &F);
2582};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002583}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002584
David Majnemer0ad363e2015-08-18 19:07:12 +00002585static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
2586 const Value *V) {
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002587 WinEHUnwindMapEntry UME;
2588 UME.ToState = ToState;
David Majnemer0ad363e2015-08-18 19:07:12 +00002589 UME.Cleanup = V;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002590 FuncInfo.UnwindMap.push_back(UME);
David Majnemer0ad363e2015-08-18 19:07:12 +00002591 return FuncInfo.getLastStateNumber();
2592}
2593
2594static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
2595 int TryHigh, int CatchHigh,
2596 ArrayRef<const CatchPadInst *> Handlers) {
2597 WinEHTryBlockMapEntry TBME;
2598 TBME.TryLow = TryLow;
2599 TBME.TryHigh = TryHigh;
2600 TBME.CatchHigh = CatchHigh;
2601 assert(TBME.TryLow <= TBME.TryHigh);
2602 for (const CatchPadInst *CPI : Handlers) {
2603 WinEHHandlerType HT;
2604 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
2605 if (TypeInfo->isNullValue()) {
2606 HT.Adjectives = 0x40;
2607 HT.TypeDescriptor = nullptr;
2608 } else {
2609 auto *GV = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
2610 // Selectors are always pointers to GlobalVariables with 'struct' type.
2611 // The struct has two fields, adjectives and a type descriptor.
2612 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2613 HT.Adjectives =
2614 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2615 HT.TypeDescriptor =
2616 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2617 }
Reid Kleckner0e288232015-08-27 23:27:47 +00002618 HT.Handler = CPI->getNormalDest();
David Majnemer0ad363e2015-08-18 19:07:12 +00002619 // FIXME: Pass CPI->getArgOperand(1).
2620 HT.CatchObjRecoverIdx = -1;
2621 TBME.HandlerArray.push_back(HT);
2622 }
2623 FuncInfo.TryBlockMap.push_back(TBME);
2624}
2625
2626void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
2627 Value *V = nullptr;
2628 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
2629 V = cast<Function>(CH->getHandlerBlockOrFunc());
2630 addUnwindMapEntry(FuncInfo, ToState, V);
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002631}
2632
2633void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
2634 ArrayRef<CatchHandler *> Handlers) {
2635 // See if we already have an entry for this set of handlers.
2636 // This is using iterators rather than a range-based for loop because
2637 // if we find the entry we're looking for we'll need the iterator to erase it.
2638 int NumHandlers = Handlers.size();
2639 auto I = FuncInfo.TryBlockMap.begin();
2640 auto E = FuncInfo.TryBlockMap.end();
2641 for ( ; I != E; ++I) {
2642 auto &Entry = *I;
2643 if (Entry.HandlerArray.size() != (size_t)NumHandlers)
2644 continue;
2645 int N;
2646 for (N = 0; N < NumHandlers; ++N) {
Reid Kleckner94b704c2015-09-09 21:10:03 +00002647 if (Entry.HandlerArray[N].Handler.get<const Value *>() !=
2648 Handlers[N]->getHandlerBlockOrFunc())
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002649 break; // breaks out of inner loop
2650 }
2651 // If all the handlers match, this is what we were looking for.
2652 if (N == NumHandlers) {
2653 break;
2654 }
2655 }
2656
2657 // If we found an existing entry for this set of handlers, extend the range
2658 // but move the entry to the end of the map vector. The order of entries
2659 // in the map is critical to the way that the runtime finds handlers.
2660 // FIXME: Depending on what has happened with block ordering, this may
2661 // incorrectly combine entries that should remain separate.
2662 if (I != E) {
2663 // Copy the existing entry.
2664 WinEHTryBlockMapEntry Entry = *I;
2665 Entry.TryLow = std::min(TryLow, Entry.TryLow);
2666 Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
2667 assert(Entry.TryLow <= Entry.TryHigh);
2668 // Erase the old entry and add this one to the back.
2669 FuncInfo.TryBlockMap.erase(I);
2670 FuncInfo.TryBlockMap.push_back(Entry);
2671 return;
2672 }
2673
2674 // If we didn't find an entry, create a new one.
2675 WinEHTryBlockMapEntry TBME;
2676 TBME.TryLow = TryLow;
2677 TBME.TryHigh = TryHigh;
2678 assert(TBME.TryLow <= TBME.TryHigh);
2679 for (CatchHandler *CH : Handlers) {
2680 WinEHHandlerType HT;
2681 if (CH->getSelector()->isNullValue()) {
2682 HT.Adjectives = 0x40;
2683 HT.TypeDescriptor = nullptr;
2684 } else {
2685 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
2686 // Selectors are always pointers to GlobalVariables with 'struct' type.
2687 // The struct has two fields, adjectives and a type descriptor.
2688 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2689 HT.Adjectives =
2690 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2691 HT.TypeDescriptor =
2692 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2693 }
2694 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
2695 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
2696 TBME.HandlerArray.push_back(HT);
2697 }
2698 FuncInfo.TryBlockMap.push_back(TBME);
2699}
2700
2701static void print_name(const Value *V) {
2702#ifndef NDEBUG
2703 if (!V) {
2704 DEBUG(dbgs() << "null");
2705 return;
2706 }
2707
2708 if (const auto *F = dyn_cast<Function>(V))
2709 DEBUG(dbgs() << F->getName());
2710 else
2711 DEBUG(V->dump());
2712#endif
2713}
2714
2715void WinEHNumbering::processCallSite(
2716 MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2717 ImmutableCallSite CS) {
2718 DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
2719 << ") for: ");
2720 print_name(CS ? CS.getCalledValue() : nullptr);
2721 DEBUG(dbgs() << '\n');
2722
2723 DEBUG(dbgs() << "HandlerStack: \n");
2724 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2725 DEBUG(dbgs() << " ");
2726 print_name(HandlerStack[I]->getHandlerBlockOrFunc());
2727 DEBUG(dbgs() << '\n');
2728 }
2729 DEBUG(dbgs() << "Actions: \n");
2730 for (int I = 0, E = Actions.size(); I < E; ++I) {
2731 DEBUG(dbgs() << " ");
2732 print_name(Actions[I]->getHandlerBlockOrFunc());
2733 DEBUG(dbgs() << '\n');
2734 }
2735 int FirstMismatch = 0;
2736 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
2737 ++FirstMismatch) {
2738 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
2739 Actions[FirstMismatch]->getHandlerBlockOrFunc())
2740 break;
2741 }
2742
2743 // Remove unmatched actions from the stack and process their EH states.
2744 popUnmatchedActions(FirstMismatch);
2745
2746 DEBUG(dbgs() << "Pushing actions for CallSite: ");
2747 print_name(CS ? CS.getCalledValue() : nullptr);
2748 DEBUG(dbgs() << '\n');
2749
2750 bool LastActionWasCatch = false;
2751 const LandingPadInst *LastRootLPad = nullptr;
2752 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
2753 // We can reuse eh states when pushing two catches for the same invoke.
2754 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
2755 auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
2756 // Various conditions can lead to a handler being popped from the
2757 // stack and re-pushed later. That shouldn't create a new state.
2758 // FIXME: Can code optimization lead to re-used handlers?
2759 if (FuncInfo.HandlerEnclosedState.count(Handler)) {
2760 // If we already assigned the state enclosed by this handler re-use it.
2761 Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
2762 continue;
2763 }
2764 const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
2765 if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
2766 DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
2767 Actions[I]->setEHState(currentEHNumber());
2768 } else {
2769 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
2770 print_name(Actions[I]->getHandlerBlockOrFunc());
2771 DEBUG(dbgs() << ") with EH state " << NextState << "\n");
2772 createUnwindMapEntry(currentEHNumber(), Actions[I].get());
2773 DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
2774 Actions[I]->setEHState(NextState);
2775 NextState++;
2776 }
2777 HandlerStack.push_back(std::move(Actions[I]));
2778 LastActionWasCatch = CurrActionIsCatch;
2779 LastRootLPad = RootLPad;
2780 }
2781
2782 // This is used to defer numbering states for a handler until after the
2783 // last time it appears in an invoke action list.
2784 if (CS.isInvoke()) {
2785 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2786 auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
2787 if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
2788 continue;
2789 FuncInfo.LastInvokeVisited[Handler] = true;
2790 DEBUG(dbgs() << "Last invoke of ");
2791 print_name(Handler);
2792 DEBUG(dbgs() << " has been visited.\n");
2793 }
2794 }
2795
2796 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
2797 print_name(CS ? CS.getCalledValue() : nullptr);
2798 DEBUG(dbgs() << '\n');
2799}
2800
2801void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
2802 // Don't recurse while we are looping over the handler stack. Instead, defer
2803 // the numbering of the catch handlers until we are done popping.
2804 SmallVector<CatchHandler *, 4> PoppedCatches;
2805 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
2806 std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
2807 if (isa<CatchHandler>(Handler.get()))
2808 PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
2809 }
2810
2811 int TryHigh = NextState - 1;
2812 int LastTryLowIdx = 0;
2813 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
2814 CatchHandler *CH = PoppedCatches[I];
2815 DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
2816 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
2817 int TryLow = CH->getEHState();
2818 auto Handlers =
2819 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
2820 DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
2821 for (size_t J = 0; J < Handlers.size(); ++J) {
2822 DEBUG(dbgs() << ", ");
2823 print_name(Handlers[J]->getHandlerBlockOrFunc());
2824 }
2825 DEBUG(dbgs() << ")\n");
2826 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
2827 LastTryLowIdx = I + 1;
2828 }
2829 }
2830
2831 for (CatchHandler *CH : PoppedCatches) {
2832 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
2833 if (FuncInfo.LastInvokeVisited[F]) {
2834 DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
2835 print_name(F);
2836 DEBUG(dbgs() << '\n');
2837 FuncInfo.HandlerBaseState[F] = NextState;
2838 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
2839 << ", null)\n");
2840 createUnwindMapEntry(currentEHNumber(), nullptr);
2841 ++NextState;
2842 calculateStateNumbers(*F);
2843 }
2844 else {
2845 DEBUG(dbgs() << "Deferring handling of ");
2846 print_name(F);
2847 DEBUG(dbgs() << " until last invoke visited.\n");
2848 }
2849 }
2850 delete CH;
2851 }
2852}
2853
2854void WinEHNumbering::calculateStateNumbers(const Function &F) {
2855 auto I = VisitedHandlers.insert(&F);
2856 if (!I.second)
2857 return; // We've already visited this handler, don't renumber it.
2858
2859 int OldBaseState = CurrentBaseState;
2860 if (FuncInfo.HandlerBaseState.count(&F)) {
2861 CurrentBaseState = FuncInfo.HandlerBaseState[&F];
2862 }
2863
2864 size_t SavedHandlerStackSize = HandlerStack.size();
2865
2866 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
2867 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2868 for (const BasicBlock &BB : F) {
2869 for (const Instruction &I : BB) {
2870 const auto *CI = dyn_cast<CallInst>(&I);
2871 if (!CI || CI->doesNotThrow())
2872 continue;
2873 processCallSite(None, CI);
2874 }
2875 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2876 if (!II)
2877 continue;
2878 const LandingPadInst *LPI = II->getLandingPadInst();
2879 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2880 if (!ActionsCall)
2881 continue;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002882 parseEHActions(ActionsCall, ActionList);
2883 if (ActionList.empty())
2884 continue;
2885 processCallSite(ActionList, II);
2886 ActionList.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00002887 FuncInfo.EHPadStateMap[LPI] = currentEHNumber();
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002888 DEBUG(dbgs() << "Assigning state " << currentEHNumber()
2889 << " to landing pad at " << LPI->getParent()->getName()
2890 << '\n');
2891 }
2892
2893 // Pop any actions that were pushed on the stack for this function.
2894 popUnmatchedActions(SavedHandlerStackSize);
2895
2896 DEBUG(dbgs() << "Assigning max state " << NextState - 1
2897 << " to " << F.getName() << '\n');
2898 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
2899
2900 CurrentBaseState = OldBaseState;
2901}
2902
2903// This function follows the same basic traversal as calculateStateNumbers
2904// but it is necessary to identify the root landing pad associated
2905// with each action before we start assigning state numbers.
2906void WinEHNumbering::findActionRootLPads(const Function &F) {
2907 auto I = VisitedHandlers.insert(&F);
2908 if (!I.second)
2909 return; // We've already visited this handler, don't revisit it.
2910
2911 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2912 for (const BasicBlock &BB : F) {
2913 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2914 if (!II)
2915 continue;
2916 const LandingPadInst *LPI = II->getLandingPadInst();
2917 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2918 if (!ActionsCall)
2919 continue;
2920
2921 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
2922 parseEHActions(ActionsCall, ActionList);
2923 if (ActionList.empty())
2924 continue;
2925 for (int I = 0, E = ActionList.size(); I < E; ++I) {
2926 if (auto *Handler
2927 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
2928 FuncInfo.LastInvoke[Handler] = II;
2929 // Don't replace the root landing pad if we previously saw this
2930 // handler in a different function.
2931 if (FuncInfo.RootLPad.count(Handler) &&
2932 FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
2933 continue;
2934 DEBUG(dbgs() << "Setting root lpad for ");
2935 print_name(Handler);
2936 DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
2937 FuncInfo.RootLPad[Handler] = LPI;
2938 }
2939 }
2940 // Walk the actions again and look for nested handlers. This has to
2941 // happen after all of the actions have been processed in the current
2942 // function.
2943 for (int I = 0, E = ActionList.size(); I < E; ++I)
2944 if (auto *Handler
2945 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
2946 findActionRootLPads(*Handler);
2947 ActionList.clear();
2948 }
2949}
2950
Reid Kleckner94b704c2015-09-09 21:10:03 +00002951static const CatchPadInst *getSingleCatchPadPredecessor(const BasicBlock *BB) {
2952 for (const BasicBlock *PredBlock : predecessors(BB))
2953 if (auto *CPI = dyn_cast<CatchPadInst>(PredBlock->getFirstNonPHI()))
2954 return CPI;
David Majnemer0ad363e2015-08-18 19:07:12 +00002955 return nullptr;
2956}
2957
Reid Kleckner94b704c2015-09-09 21:10:03 +00002958/// Find all the catchpads that feed directly into the catchendpad. Frontends
2959/// using this personality should ensure that each catchendpad and catchpad has
2960/// one or zero catchpad predecessors.
2961///
2962/// The following C++ generates the IR after it:
2963/// try {
2964/// } catch (A) {
2965/// } catch (B) {
2966/// }
2967///
2968/// IR:
2969/// %catchpad.A
2970/// catchpad [i8* A typeinfo]
2971/// to label %catch.A unwind label %catchpad.B
2972/// %catchpad.B
2973/// catchpad [i8* B typeinfo]
2974/// to label %catch.B unwind label %endcatches
2975/// %endcatches
2976/// catchendblock unwind to caller
2977void findCatchPadsForCatchEndPad(
2978 const BasicBlock *CatchEndBB,
2979 SmallVectorImpl<const CatchPadInst *> &Handlers) {
2980 const CatchPadInst *CPI = getSingleCatchPadPredecessor(CatchEndBB);
2981 while (CPI) {
2982 Handlers.push_back(CPI);
2983 CPI = getSingleCatchPadPredecessor(CPI->getParent());
2984 }
2985 // We've pushed these back into reverse source order. Reverse them to get
2986 // the list back into source order.
2987 std::reverse(Handlers.begin(), Handlers.end());
2988}
2989
David Majnemer0ad363e2015-08-18 19:07:12 +00002990// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
2991// to. If the unwind edge came from an invoke, return null.
2992static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) {
2993 const TerminatorInst *TI = BB->getTerminator();
2994 if (isa<InvokeInst>(TI))
2995 return nullptr;
2996 if (isa<CatchPadInst>(TI) || isa<CatchEndPadInst>(TI) ||
2997 isa<TerminatePadInst>(TI))
2998 return BB;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00002999 if (auto *CEPI = dyn_cast<CleanupEndPadInst>(TI))
3000 return CEPI->getCleanupPad()->getParent();
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003001 return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent();
David Majnemer0ad363e2015-08-18 19:07:12 +00003002}
3003
Reid Kleckner94b704c2015-09-09 21:10:03 +00003004static void calculateExplicitCXXStateNumbers(WinEHFuncInfo &FuncInfo,
3005 const BasicBlock &BB,
3006 int ParentState) {
David Majnemer0ad363e2015-08-18 19:07:12 +00003007 assert(BB.isEHPad());
3008 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3009 // All catchpad instructions will be handled when we process their
3010 // respective catchendpad instruction.
3011 if (isa<CatchPadInst>(FirstNonPHI))
3012 return;
3013
3014 if (isa<CatchEndPadInst>(FirstNonPHI)) {
David Majnemer0ad363e2015-08-18 19:07:12 +00003015 SmallVector<const CatchPadInst *, 2> Handlers;
Reid Kleckner94b704c2015-09-09 21:10:03 +00003016 findCatchPadsForCatchEndPad(&BB, Handlers);
3017 const BasicBlock *FirstTryPad = Handlers.front()->getParent();
David Majnemer0ad363e2015-08-18 19:07:12 +00003018 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
3019 FuncInfo.EHPadStateMap[Handlers.front()] = TryLow;
Reid Kleckner94b704c2015-09-09 21:10:03 +00003020 for (const BasicBlock *PredBlock : predecessors(FirstTryPad))
David Majnemer0ad363e2015-08-18 19:07:12 +00003021 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
Reid Kleckner94b704c2015-09-09 21:10:03 +00003022 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, TryLow);
David Majnemer0ad363e2015-08-18 19:07:12 +00003023 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
Reid Kleckner94b704c2015-09-09 21:10:03 +00003024
3025 // catchpads are separate funclets in C++ EH due to the way rethrow works.
3026 // In SEH, they aren't, so no invokes will unwind to the catchendpad.
David Majnemer0ad363e2015-08-18 19:07:12 +00003027 FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow;
3028 int TryHigh = CatchLow - 1;
3029 for (const BasicBlock *PredBlock : predecessors(&BB))
3030 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
Reid Kleckner94b704c2015-09-09 21:10:03 +00003031 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CatchLow);
David Majnemer0ad363e2015-08-18 19:07:12 +00003032 int CatchHigh = FuncInfo.getLastStateNumber();
3033 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
Reid Kleckner94b704c2015-09-09 21:10:03 +00003034 DEBUG(dbgs() << "TryLow[" << FirstTryPad->getName() << "]: " << TryLow
David Majnemer0ad363e2015-08-18 19:07:12 +00003035 << '\n');
Reid Kleckner94b704c2015-09-09 21:10:03 +00003036 DEBUG(dbgs() << "TryHigh[" << FirstTryPad->getName() << "]: " << TryHigh
David Majnemer0ad363e2015-08-18 19:07:12 +00003037 << '\n');
Reid Kleckner94b704c2015-09-09 21:10:03 +00003038 DEBUG(dbgs() << "CatchHigh[" << FirstTryPad->getName() << "]: " << CatchHigh
David Majnemer0ad363e2015-08-18 19:07:12 +00003039 << '\n');
3040 } else if (isa<CleanupPadInst>(FirstNonPHI)) {
3041 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB);
3042 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
3043 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
3044 << BB.getName() << '\n');
3045 for (const BasicBlock *PredBlock : predecessors(&BB))
3046 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
Reid Kleckner94b704c2015-09-09 21:10:03 +00003047 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CleanupState);
David Majnemer0ad363e2015-08-18 19:07:12 +00003048 } else if (isa<TerminatePadInst>(FirstNonPHI)) {
3049 report_fatal_error("Not yet implemented!");
3050 } else {
3051 llvm_unreachable("unexpected EH Pad!");
3052 }
3053}
3054
Reid Kleckner94b704c2015-09-09 21:10:03 +00003055static int addSEHHandler(WinEHFuncInfo &FuncInfo, int ParentState,
3056 const Function *Filter, const BasicBlock *Handler) {
3057 SEHUnwindMapEntry Entry;
3058 Entry.ToState = ParentState;
3059 Entry.Filter = Filter;
3060 Entry.Handler = Handler;
3061 FuncInfo.SEHUnwindMap.push_back(Entry);
3062 return FuncInfo.SEHUnwindMap.size() - 1;
3063}
3064
3065static void calculateExplicitSEHStateNumbers(WinEHFuncInfo &FuncInfo,
3066 const BasicBlock &BB,
3067 int ParentState) {
3068 assert(BB.isEHPad());
3069 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3070 // All catchpad instructions will be handled when we process their
3071 // respective catchendpad instruction.
3072 if (isa<CatchPadInst>(FirstNonPHI))
3073 return;
3074
3075 if (isa<CatchEndPadInst>(FirstNonPHI)) {
3076 // Extract the filter function and the __except basic block and create a
3077 // state for them.
3078 SmallVector<const CatchPadInst *, 1> Handlers;
3079 findCatchPadsForCatchEndPad(&BB, Handlers);
3080 assert(Handlers.size() == 1 &&
3081 "SEH doesn't have multiple handlers per __try");
3082 const CatchPadInst *CPI = Handlers.front();
3083 const BasicBlock *CatchPadBB = CPI->getParent();
3084 const Function *Filter =
3085 cast<Function>(CPI->getArgOperand(0)->stripPointerCasts());
3086 int TryState =
3087 addSEHHandler(FuncInfo, ParentState, Filter, CPI->getNormalDest());
3088
3089 // Everything in the __try block uses TryState as its parent state.
3090 FuncInfo.EHPadStateMap[CPI] = TryState;
3091 DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
3092 << CatchPadBB->getName() << '\n');
3093 for (const BasicBlock *PredBlock : predecessors(CatchPadBB))
3094 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3095 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, TryState);
3096
3097 // Everything in the __except block unwinds to ParentState, just like code
3098 // outside the __try.
3099 FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
3100 DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
3101 << BB.getName() << '\n');
3102 for (const BasicBlock *PredBlock : predecessors(&BB))
3103 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3104 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
3105 } else if (isa<CleanupPadInst>(FirstNonPHI)) {
3106 int CleanupState =
3107 addSEHHandler(FuncInfo, ParentState, /*Filter=*/nullptr, &BB);
3108 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
3109 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
3110 << BB.getName() << '\n');
3111 for (const BasicBlock *PredBlock : predecessors(&BB))
3112 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3113 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, CleanupState);
3114 } else if (isa<TerminatePadInst>(FirstNonPHI)) {
3115 report_fatal_error("Not yet implemented!");
3116 } else {
3117 llvm_unreachable("unexpected EH Pad!");
3118 }
3119}
3120
3121/// Check if the EH Pad unwinds to caller. Cleanups are a little bit of a
3122/// special case because we have to look at the cleanupret instruction that uses
3123/// the cleanuppad.
3124static bool doesEHPadUnwindToCaller(const Instruction *EHPad) {
3125 auto *CPI = dyn_cast<CleanupPadInst>(EHPad);
3126 if (!CPI)
3127 return EHPad->mayThrow();
3128
3129 // This cleanup does not return or unwind, so we say it unwinds to caller.
3130 if (CPI->use_empty())
3131 return true;
3132
3133 const Instruction *User = CPI->user_back();
3134 if (auto *CRI = dyn_cast<CleanupReturnInst>(User))
3135 return CRI->unwindsToCaller();
3136 return cast<CleanupEndPadInst>(User)->unwindsToCaller();
3137}
3138
3139void llvm::calculateSEHStateNumbers(const Function *ParentFn,
3140 WinEHFuncInfo &FuncInfo) {
3141 // Don't compute state numbers twice.
3142 if (!FuncInfo.SEHUnwindMap.empty())
3143 return;
3144
3145 for (const BasicBlock &BB : *ParentFn) {
3146 if (!BB.isEHPad() || !doesEHPadUnwindToCaller(BB.getFirstNonPHI()))
3147 continue;
3148 calculateExplicitSEHStateNumbers(FuncInfo, BB, -1);
3149 }
3150}
3151
Reid Klecknerfe4d4912015-05-28 22:00:24 +00003152void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
3153 WinEHFuncInfo &FuncInfo) {
3154 // Return if it's already been done.
David Majnemer0ad363e2015-08-18 19:07:12 +00003155 if (!FuncInfo.EHPadStateMap.empty())
3156 return;
3157
3158 bool IsExplicit = false;
3159 for (const BasicBlock &BB : *ParentFn) {
3160 if (!BB.isEHPad())
3161 continue;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003162 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3163 // Skip cleanupendpads; they are exits, not entries.
3164 if (isa<CleanupEndPadInst>(FirstNonPHI))
3165 continue;
Reid Kleckner94b704c2015-09-09 21:10:03 +00003166 if (!doesEHPadUnwindToCaller(FirstNonPHI))
David Majnemer0ad363e2015-08-18 19:07:12 +00003167 continue;
Reid Kleckner94b704c2015-09-09 21:10:03 +00003168 calculateExplicitCXXStateNumbers(FuncInfo, BB, -1);
David Majnemer0ad363e2015-08-18 19:07:12 +00003169 IsExplicit = true;
3170 }
3171
3172 if (IsExplicit)
Reid Klecknerfe4d4912015-05-28 22:00:24 +00003173 return;
3174
3175 WinEHNumbering Num(FuncInfo);
3176 Num.findActionRootLPads(*ParentFn);
3177 // The VisitedHandlers list is used by both findActionRootLPads and
3178 // calculateStateNumbers, but both functions need to visit all handlers.
3179 Num.VisitedHandlers.clear();
3180 Num.calculateStateNumbers(*ParentFn);
3181 // Pop everything on the handler stack.
3182 // It may be necessary to call this more than once because a handler can
3183 // be pushed on the stack as a result of clearing the stack.
3184 while (!Num.HandlerStack.empty())
3185 Num.processCallSite(None, ImmutableCallSite());
3186}
David Majnemerfd9f4772015-08-11 01:15:26 +00003187
Joseph Tremouletec182852015-08-28 01:12:35 +00003188void WinEHPrepare::colorFunclets(Function &F,
3189 SmallVectorImpl<BasicBlock *> &EntryBlocks) {
3190 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist;
3191 BasicBlock *EntryBlock = &F.getEntryBlock();
David Majnemerfd9f4772015-08-11 01:15:26 +00003192
Joseph Tremouletec182852015-08-28 01:12:35 +00003193 // Build up the color map, which maps each block to its set of 'colors'.
3194 // For any block B, the "colors" of B are the set of funclets F (possibly
3195 // including a root "funclet" representing the main function), such that
3196 // F will need to directly contain B or a copy of B (where the term "directly
3197 // contain" is used to distinguish from being "transitively contained" in
3198 // a nested funclet).
3199 // Use a CFG walk driven by a worklist of (block, color) pairs. The "color"
3200 // sets attached during this processing to a block which is the entry of some
3201 // funclet F is actually the set of F's parents -- i.e. the union of colors
3202 // of all predecessors of F's entry. For all other blocks, the color sets
3203 // are as defined above. A post-pass fixes up the block color map to reflect
3204 // the same sense of "color" for funclet entries as for other blocks.
3205
3206 Worklist.push_back({EntryBlock, EntryBlock});
David Majnemerfd9f4772015-08-11 01:15:26 +00003207
3208 while (!Worklist.empty()) {
Joseph Tremouletec182852015-08-28 01:12:35 +00003209 BasicBlock *Visiting;
3210 BasicBlock *Color;
3211 std::tie(Visiting, Color) = Worklist.pop_back_val();
3212 Instruction *VisitingHead = Visiting->getFirstNonPHI();
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003213 if (VisitingHead->isEHPad() && !isa<CatchEndPadInst>(VisitingHead) &&
3214 !isa<CleanupEndPadInst>(VisitingHead)) {
Joseph Tremouletec182852015-08-28 01:12:35 +00003215 // Mark this as a funclet head as a member of itself.
3216 FuncletBlocks[Visiting].insert(Visiting);
3217 // Queue exits with the parent color.
3218 for (User *Exit : VisitingHead->users()) {
3219 for (BasicBlock *Succ :
3220 successors(cast<Instruction>(Exit)->getParent())) {
3221 if (BlockColors[Succ].insert(Color).second) {
3222 Worklist.push_back({Succ, Color});
3223 }
3224 }
3225 }
3226 // Handle CatchPad specially since its successors need different colors.
3227 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(VisitingHead)) {
3228 // Visit the normal successor with the color of the new EH pad, and
3229 // visit the unwind successor with the color of the parent.
3230 BasicBlock *NormalSucc = CatchPad->getNormalDest();
3231 if (BlockColors[NormalSucc].insert(Visiting).second) {
3232 Worklist.push_back({NormalSucc, Visiting});
3233 }
3234 BasicBlock *UnwindSucc = CatchPad->getUnwindDest();
3235 if (BlockColors[UnwindSucc].insert(Color).second) {
3236 Worklist.push_back({UnwindSucc, Color});
3237 }
3238 continue;
3239 }
3240 // Switch color to the current node, except for terminate pads which
3241 // have no bodies and only unwind successors and so need their successors
3242 // visited with the color of the parent.
3243 if (!isa<TerminatePadInst>(VisitingHead))
3244 Color = Visiting;
3245 } else {
3246 // Note that this is a member of the given color.
3247 FuncletBlocks[Color].insert(Visiting);
3248 TerminatorInst *Terminator = Visiting->getTerminator();
3249 if (isa<CleanupReturnInst>(Terminator) ||
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003250 isa<CatchReturnInst>(Terminator) ||
3251 isa<CleanupEndPadInst>(Terminator)) {
Joseph Tremouletec182852015-08-28 01:12:35 +00003252 // These block's successors have already been queued with the parent
3253 // color.
3254 continue;
3255 }
David Majnemerfd9f4772015-08-11 01:15:26 +00003256 }
Joseph Tremouletec182852015-08-28 01:12:35 +00003257 for (BasicBlock *Succ : successors(Visiting)) {
3258 if (isa<CatchEndPadInst>(Succ->getFirstNonPHI())) {
3259 // The catchendpad needs to be visited with the parent's color, not
3260 // the current color. This will happen in the code above that visits
3261 // any catchpad unwind successor with the parent color, so we can
3262 // safely skip this successor here.
3263 continue;
3264 }
3265 if (BlockColors[Succ].insert(Color).second) {
3266 Worklist.push_back({Succ, Color});
3267 }
3268 }
3269 }
David Majnemerfd9f4772015-08-11 01:15:26 +00003270
Joseph Tremouletec182852015-08-28 01:12:35 +00003271 // The processing above actually accumulated the parent set for this
3272 // funclet into the color set for its entry; use the parent set to
3273 // populate the children map, and reset the color set to include just
3274 // the funclet itself (no instruction can target a funclet entry except on
3275 // that transitions to the child funclet).
3276 for (BasicBlock *FuncletEntry : EntryBlocks) {
3277 std::set<BasicBlock *> &ColorMapItem = BlockColors[FuncletEntry];
3278 for (BasicBlock *Parent : ColorMapItem)
3279 FuncletChildren[Parent].insert(FuncletEntry);
3280 ColorMapItem.clear();
3281 ColorMapItem.insert(FuncletEntry);
David Majnemerfd9f4772015-08-11 01:15:26 +00003282 }
3283}
3284
Joseph Tremouletec182852015-08-28 01:12:35 +00003285bool WinEHPrepare::prepareExplicitEH(
3286 Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
David Majnemerfd9f4772015-08-11 01:15:26 +00003287 // Remove unreachable blocks. It is not valuable to assign them a color and
3288 // their existence can trick us into thinking values are alive when they are
3289 // not.
3290 removeUnreachableBlocks(F);
3291
Joseph Tremouletec182852015-08-28 01:12:35 +00003292 // Determine which blocks are reachable from which funclet entries.
3293 colorFunclets(F, EntryBlocks);
David Majnemerfd9f4772015-08-11 01:15:26 +00003294
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003295 // Strip PHI nodes off of EH pads.
3296 SmallVector<PHINode *, 16> PHINodes;
David Majnemerfd9f4772015-08-11 01:15:26 +00003297 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3298 BasicBlock *BB = FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +00003299 if (!BB->isEHPad())
3300 continue;
David Majnemerfd9f4772015-08-11 01:15:26 +00003301 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3302 Instruction *I = BI++;
3303 auto *PN = dyn_cast<PHINode>(I);
3304 // Stop at the first non-PHI.
3305 if (!PN)
3306 break;
David Majnemerfd9f4772015-08-11 01:15:26 +00003307
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003308 AllocaInst *SpillSlot = insertPHILoads(PN, F);
3309 if (SpillSlot)
3310 insertPHIStores(PN, SpillSlot);
3311
3312 PHINodes.push_back(PN);
David Majnemerfd9f4772015-08-11 01:15:26 +00003313 }
3314 }
3315
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003316 for (auto *PN : PHINodes) {
3317 // There may be lingering uses on other EH PHIs being removed
3318 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
3319 PN->eraseFromParent();
David Majnemerfd9f4772015-08-11 01:15:26 +00003320 }
3321
3322 // Turn all inter-funclet uses of a Value into loads and stores.
3323 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3324 BasicBlock *BB = FI++;
3325 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3326 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3327 Instruction *I = BI++;
3328 // Funclets are permitted to use static allocas.
3329 if (auto *AI = dyn_cast<AllocaInst>(I))
3330 if (AI->isStaticAlloca())
3331 continue;
3332
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003333 demoteNonlocalUses(I, ColorsForBB, F);
David Majnemerfd9f4772015-08-11 01:15:26 +00003334 }
3335 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003336 // Also demote function parameters used in funclets.
3337 std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()];
3338 for (Argument &Arg : F.args())
3339 demoteNonlocalUses(&Arg, ColorsForEntry, F);
David Majnemerfd9f4772015-08-11 01:15:26 +00003340
3341 // We need to clone all blocks which belong to multiple funclets. Values are
3342 // remapped throughout the funclet to propogate both the new instructions
3343 // *and* the new basic blocks themselves.
Joseph Tremouletec182852015-08-28 01:12:35 +00003344 for (BasicBlock *FuncletPadBB : EntryBlocks) {
3345 std::set<BasicBlock *> &BlocksInFunclet = FuncletBlocks[FuncletPadBB];
David Majnemerfd9f4772015-08-11 01:15:26 +00003346
3347 std::map<BasicBlock *, BasicBlock *> Orig2Clone;
3348 ValueToValueMapTy VMap;
3349 for (BasicBlock *BB : BlocksInFunclet) {
3350 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3351 // We don't need to do anything if the block is monochromatic.
3352 size_t NumColorsForBB = ColorsForBB.size();
3353 if (NumColorsForBB == 1)
3354 continue;
3355
David Majnemerfd9f4772015-08-11 01:15:26 +00003356 // Create a new basic block and copy instructions into it!
Joseph Tremouletec182852015-08-28 01:12:35 +00003357 BasicBlock *CBB =
3358 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
3359 // Insert the clone immediately after the original to ensure determinism
3360 // and to keep the same relative ordering of any funclet's blocks.
3361 CBB->insertInto(&F, BB->getNextNode());
David Majnemerfd9f4772015-08-11 01:15:26 +00003362
3363 // Add basic block mapping.
3364 VMap[BB] = CBB;
3365
3366 // Record delta operations that we need to perform to our color mappings.
3367 Orig2Clone[BB] = CBB;
3368 }
3369
3370 // Update our color mappings to reflect that one block has lost a color and
3371 // another has gained a color.
3372 for (auto &BBMapping : Orig2Clone) {
3373 BasicBlock *OldBlock = BBMapping.first;
3374 BasicBlock *NewBlock = BBMapping.second;
3375
3376 BlocksInFunclet.insert(NewBlock);
3377 BlockColors[NewBlock].insert(FuncletPadBB);
3378
3379 BlocksInFunclet.erase(OldBlock);
3380 BlockColors[OldBlock].erase(FuncletPadBB);
3381 }
3382
3383 // Loop over all of the instructions in the function, fixing up operand
3384 // references as we go. This uses VMap to do all the hard work.
3385 for (BasicBlock *BB : BlocksInFunclet)
3386 // Loop over all instructions, fixing each one as we find it...
3387 for (Instruction &I : *BB)
3388 RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
3389 }
3390
David Majnemer83f4bb22015-08-17 20:56:39 +00003391 // Remove implausible terminators and replace them with UnreachableInst.
3392 for (auto &Funclet : FuncletBlocks) {
3393 BasicBlock *FuncletPadBB = Funclet.first;
3394 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3395 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
3396 auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
3397 auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI);
3398
3399 for (BasicBlock *BB : BlocksInFunclet) {
3400 TerminatorInst *TI = BB->getTerminator();
3401 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
3402 bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad);
3403 // The token consumed by a CatchReturnInst must match the funclet token.
3404 bool IsUnreachableCatchret = false;
3405 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003406 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003407 // The token consumed by a CleanupReturnInst must match the funclet token.
David Majnemer83f4bb22015-08-17 20:56:39 +00003408 bool IsUnreachableCleanupret = false;
3409 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003410 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003411 // The token consumed by a CleanupEndPadInst must match the funclet token.
3412 bool IsUnreachableCleanupendpad = false;
3413 if (auto *CEPI = dyn_cast<CleanupEndPadInst>(TI))
3414 IsUnreachableCleanupendpad = CEPI->getCleanupPad() != CleanupPad;
3415 if (IsUnreachableRet || IsUnreachableCatchret ||
3416 IsUnreachableCleanupret || IsUnreachableCleanupendpad) {
David Majnemer83f4bb22015-08-17 20:56:39 +00003417 new UnreachableInst(BB->getContext(), TI);
3418 TI->eraseFromParent();
3419 }
3420 }
3421 }
3422
David Majnemerfd9f4772015-08-11 01:15:26 +00003423 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
3424 // branches, etc.
3425 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3426 BasicBlock *BB = FI++;
3427 SimplifyInstructionsInBlock(BB);
3428 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
3429 MergeBlockIntoPredecessor(BB);
3430 }
3431
David Majnemerfd9f4772015-08-11 01:15:26 +00003432 // We might have some unreachable blocks after cleaning up some impossible
3433 // control flow.
3434 removeUnreachableBlocks(F);
3435
3436 // Recolor the CFG to verify that all is well.
3437 for (BasicBlock &BB : F) {
3438 size_t NumColors = BlockColors[&BB].size();
3439 assert(NumColors == 1 && "Expected monochromatic BB!");
3440 if (NumColors == 0)
3441 report_fatal_error("Uncolored BB!");
3442 if (NumColors > 1)
3443 report_fatal_error("Multicolor BB!");
3444 bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
3445 assert(!EHPadHasPHI && "EH Pad still has a PHI!");
3446 if (EHPadHasPHI)
3447 report_fatal_error("EH Pad still has a PHI!");
3448 }
3449
3450 BlockColors.clear();
3451 FuncletBlocks.clear();
Joseph Tremouletec182852015-08-28 01:12:35 +00003452 FuncletChildren.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00003453
David Majnemerfd9f4772015-08-11 01:15:26 +00003454 return true;
3455}
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003456
3457// TODO: Share loads when one use dominates another, or when a catchpad exit
3458// dominates uses (needs dominators).
3459AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
3460 BasicBlock *PHIBlock = PN->getParent();
3461 AllocaInst *SpillSlot = nullptr;
3462
3463 if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) {
3464 // Insert a load in place of the PHI and replace all uses.
3465 SpillSlot = new AllocaInst(PN->getType(), nullptr,
3466 Twine(PN->getName(), ".wineh.spillslot"),
3467 F.getEntryBlock().begin());
3468 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
3469 PHIBlock->getFirstInsertionPt());
3470 PN->replaceAllUsesWith(V);
3471 return SpillSlot;
3472 }
3473
3474 DenseMap<BasicBlock *, Value *> Loads;
3475 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
3476 UI != UE;) {
3477 Use &U = *UI++;
3478 auto *UsingInst = cast<Instruction>(U.getUser());
3479 BasicBlock *UsingBB = UsingInst->getParent();
3480 if (UsingBB->isEHPad()) {
3481 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
3482 // stores for it separately.
3483 assert(isa<PHINode>(UsingInst));
3484 continue;
3485 }
3486 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
3487 }
3488 return SpillSlot;
3489}
3490
3491// TODO: improve store placement. Inserting at def is probably good, but need
3492// to be careful not to introduce interfering stores (needs liveness analysis).
3493// TODO: identify related phi nodes that can share spill slots, and share them
3494// (also needs liveness).
3495void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
3496 AllocaInst *SpillSlot) {
3497 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
3498 // stored to the spill slot by the end of the given Block.
3499 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
3500
3501 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
3502
3503 while (!Worklist.empty()) {
3504 BasicBlock *EHBlock;
3505 Value *InVal;
3506 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
3507
3508 PHINode *PN = dyn_cast<PHINode>(InVal);
3509 if (PN && PN->getParent() == EHBlock) {
3510 // The value is defined by another PHI we need to remove, with no room to
3511 // insert a store after the PHI, so each predecessor needs to store its
3512 // incoming value.
3513 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
3514 Value *PredVal = PN->getIncomingValue(i);
3515
3516 // Undef can safely be skipped.
3517 if (isa<UndefValue>(PredVal))
3518 continue;
3519
3520 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
3521 }
3522 } else {
3523 // We need to store InVal, which dominates EHBlock, but can't put a store
3524 // in EHBlock, so need to put stores in each predecessor.
3525 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
3526 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
3527 }
3528 }
3529 }
3530}
3531
3532void WinEHPrepare::insertPHIStore(
3533 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
3534 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
3535
3536 if (PredBlock->isEHPad() &&
3537 !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) {
3538 // Pred is unsplittable, so we need to queue it on the worklist.
3539 Worklist.push_back({PredBlock, PredVal});
3540 return;
3541 }
3542
3543 // Otherwise, insert the store at the end of the basic block.
3544 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
3545}
3546
3547// TODO: Share loads for same-funclet uses (requires dominators if funclets
3548// aren't properly nested).
3549void WinEHPrepare::demoteNonlocalUses(Value *V,
3550 std::set<BasicBlock *> &ColorsForBB,
3551 Function &F) {
David Majnemer83f4bb22015-08-17 20:56:39 +00003552 // Tokens can only be used non-locally due to control flow involving
3553 // unreachable edges. Don't try to demote the token usage, we'll simply
3554 // delete the cloned user later.
3555 if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V))
3556 return;
3557
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003558 DenseMap<BasicBlock *, Value *> Loads;
3559 AllocaInst *SpillSlot = nullptr;
3560 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) {
3561 Use &U = *UI++;
3562 auto *UsingInst = cast<Instruction>(U.getUser());
3563 BasicBlock *UsingBB = UsingInst->getParent();
3564
Joseph Tremouletec182852015-08-28 01:12:35 +00003565 // Is the Use inside a block which is colored the same as the Def?
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003566 // If so, we don't need to escape the Def because we will clone
3567 // ourselves our own private copy.
3568 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
Joseph Tremouletec182852015-08-28 01:12:35 +00003569 if (ColorsForUsingBB == ColorsForBB)
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003570 continue;
3571
3572 replaceUseWithLoad(V, U, SpillSlot, Loads, F);
3573 }
3574 if (SpillSlot) {
3575 // Insert stores of the computed value into the stack slot.
3576 // We have to be careful if I is an invoke instruction,
3577 // because we can't insert the store AFTER the terminator instruction.
3578 BasicBlock::iterator InsertPt;
3579 if (isa<Argument>(V)) {
3580 InsertPt = F.getEntryBlock().getTerminator();
3581 } else if (isa<TerminatorInst>(V)) {
3582 auto *II = cast<InvokeInst>(V);
3583 // We cannot demote invoke instructions to the stack if their normal
3584 // edge is critical. Therefore, split the critical edge and create a
3585 // basic block into which the store can be inserted.
3586 if (!II->getNormalDest()->getSinglePredecessor()) {
3587 unsigned SuccNum =
3588 GetSuccessorNumber(II->getParent(), II->getNormalDest());
3589 assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
3590 BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
3591 assert(NewBlock && "Unable to split critical edge.");
3592 // Update the color mapping for the newly split edge.
3593 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()];
3594 BlockColors[NewBlock] = ColorsForUsingBB;
3595 for (BasicBlock *FuncletPad : ColorsForUsingBB)
3596 FuncletBlocks[FuncletPad].insert(NewBlock);
3597 }
3598 InsertPt = II->getNormalDest()->getFirstInsertionPt();
3599 } else {
3600 InsertPt = cast<Instruction>(V);
3601 ++InsertPt;
3602 // Don't insert before PHI nodes or EH pad instrs.
3603 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
3604 ;
3605 }
3606 new StoreInst(V, SpillSlot, InsertPt);
3607 }
3608}
3609
3610void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
3611 DenseMap<BasicBlock *, Value *> &Loads,
3612 Function &F) {
3613 // Lazilly create the spill slot.
3614 if (!SpillSlot)
3615 SpillSlot = new AllocaInst(V->getType(), nullptr,
3616 Twine(V->getName(), ".wineh.spillslot"),
3617 F.getEntryBlock().begin());
3618
3619 auto *UsingInst = cast<Instruction>(U.getUser());
3620 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
3621 // If this is a PHI node, we can't insert a load of the value before
3622 // the use. Instead insert the load in the predecessor block
3623 // corresponding to the incoming value.
3624 //
3625 // Note that if there are multiple edges from a basic block to this
3626 // PHI node that we cannot have multiple loads. The problem is that
3627 // the resulting PHI node will have multiple values (from each load)
3628 // coming in from the same block, which is illegal SSA form.
3629 // For this reason, we keep track of and reuse loads we insert.
3630 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00003631 if (auto *CatchRet =
3632 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
3633 // Putting a load above a catchret and use on the phi would still leave
3634 // a cross-funclet def/use. We need to split the edge, change the
3635 // catchret to target the new block, and put the load there.
3636 BasicBlock *PHIBlock = UsingInst->getParent();
3637 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
3638 // SplitEdge gives us:
3639 // IncomingBlock:
3640 // ...
3641 // br label %NewBlock
3642 // NewBlock:
3643 // catchret label %PHIBlock
3644 // But we need:
3645 // IncomingBlock:
3646 // ...
3647 // catchret label %NewBlock
3648 // NewBlock:
3649 // br label %PHIBlock
3650 // So move the terminators to each others' blocks and swap their
3651 // successors.
3652 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
3653 Goto->removeFromParent();
3654 CatchRet->removeFromParent();
3655 IncomingBlock->getInstList().push_back(CatchRet);
3656 NewBlock->getInstList().push_back(Goto);
3657 Goto->setSuccessor(0, PHIBlock);
3658 CatchRet->setSuccessor(NewBlock);
3659 // Update the color mapping for the newly split edge.
3660 std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock];
3661 BlockColors[NewBlock] = ColorsForPHIBlock;
3662 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
3663 FuncletBlocks[FuncletPad].insert(NewBlock);
3664 // Treat the new block as incoming for load insertion.
3665 IncomingBlock = NewBlock;
3666 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003667 Value *&Load = Loads[IncomingBlock];
3668 // Insert the load into the predecessor block
3669 if (!Load)
3670 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3671 /*Volatile=*/false, IncomingBlock->getTerminator());
3672
3673 U.set(Load);
3674 } else {
3675 // Reload right before the old use.
3676 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3677 /*Volatile=*/false, UsingInst);
3678 U.set(Load);
3679 }
3680}