blob: 6a15240fa6e0ad401338ea15bfa1071b4f3d5d19 [file] [log] [blame]
Andrew Kaylor8f475e92015-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 Kleckner4def1cb2015-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 Kaylor8f475e92015-02-24 20:49:35 +000016//
17//===----------------------------------------------------------------------===//
18
Joseph Tremoulet7f410b12016-01-04 16:16:01 +000019#include "llvm/ADT/DenseMap.h"
David Majnemer8cec2f22015-12-12 05:38:55 +000020#include "llvm/ADT/MapVector.h"
Joseph Tremoulet7f410b12016-01-04 16:16:01 +000021#include "llvm/ADT/STLExtras.h"
David Majnemer7c58a662015-08-11 01:15:26 +000022#include "llvm/Analysis/CFG.h"
David Majnemer1114aa22015-12-02 23:06:39 +000023#include "llvm/Analysis/EHPersonalities.h"
David Blaikie8325fb22018-06-04 21:23:21 +000024#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthf79435e2015-12-29 09:24:39 +000025#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000026#include "llvm/CodeGen/Passes.h"
David Majnemer0a8ff292015-03-30 22:58:10 +000027#include "llvm/CodeGen/WinEHFuncInfo.h"
David Majnemer71d29c12016-01-02 09:26:36 +000028#include "llvm/IR/Verifier.h"
Chandler Carruthf79435e2015-12-29 09:24:39 +000029#include "llvm/MC/MCSymbol.h"
Andrew Kaylor8f475e92015-02-24 20:49:35 +000030#include "llvm/Pass.h"
Andrew Kaylor1134ac42015-03-11 23:22:06 +000031#include "llvm/Support/Debug.h"
Benjamin Kramer16ee53b2015-03-23 18:57:17 +000032#include "llvm/Support/raw_ostream.h"
Andrew Kaylor1134ac42015-03-11 23:22:06 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor8f475e92015-02-24 20:49:35 +000034#include "llvm/Transforms/Utils/Cloning.h"
David Majnemerad53a652015-09-16 18:40:37 +000035#include "llvm/Transforms/Utils/SSAUpdater.h"
Andrew Kaylor8f475e92015-02-24 20:49:35 +000036
37using namespace llvm;
Andrew Kaylor8f475e92015-02-24 20:49:35 +000038
39#define DEBUG_TYPE "winehprepare"
40
David Majnemerad53a652015-09-16 18:40:37 +000041static cl::opt<bool> DisableDemotion(
42 "disable-demotion", cl::Hidden,
43 cl::desc(
Heejin Ahn5b752cf2018-05-17 20:52:03 +000044 "Clone multicolor basic blocks but do not demote cross scopes"),
David Majnemerad53a652015-09-16 18:40:37 +000045 cl::init(false));
46
47static cl::opt<bool> DisableCleanups(
48 "disable-cleanups", cl::Hidden,
49 cl::desc("Do not remove implausible terminators or other similar cleanups"),
50 cl::init(false));
51
Heejin Ahna6e37da2018-05-31 22:02:34 +000052static cl::opt<bool> DemoteCatchSwitchPHIOnlyOpt(
53 "demote-catchswitch-only", cl::Hidden,
54 cl::desc("Demote catchswitch BBs only (for wasm EH)"), cl::init(false));
55
Andrew Kaylor8f475e92015-02-24 20:49:35 +000056namespace {
Fangrui Songaf7b1832018-07-30 19:41:25 +000057
Andrew Kaylor8f475e92015-02-24 20:49:35 +000058class WinEHPrepare : public FunctionPass {
Andrew Kaylor8f475e92015-02-24 20:49:35 +000059public:
60 static char ID; // Pass identification, replacement for typeid.
Heejin Ahna6e37da2018-05-31 22:02:34 +000061 WinEHPrepare(bool DemoteCatchSwitchPHIOnly = false)
62 : FunctionPass(ID), DemoteCatchSwitchPHIOnly(DemoteCatchSwitchPHIOnly) {}
Andrew Kaylor8f475e92015-02-24 20:49:35 +000063
64 bool runOnFunction(Function &Fn) override;
65
66 bool doFinalization(Module &M) override;
67
68 void getAnalysisUsage(AnalysisUsage &AU) const override;
69
Mehdi Amini67f335d2016-10-01 02:56:57 +000070 StringRef getPassName() const override {
Andrew Kaylor8f475e92015-02-24 20:49:35 +000071 return "Windows exception handling preparation";
72 }
73
74private:
Joseph Tremouletccc0cf32015-08-13 14:30:10 +000075 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
76 void
77 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
78 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
79 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
80 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
81 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
David Majnemer8cec2f22015-12-12 05:38:55 +000082 bool prepareExplicitEH(Function &F);
David Majnemer8cec2f22015-12-12 05:38:55 +000083 void colorFunclets(Function &F);
Andrew Kaylor805b66a2015-11-09 19:59:02 +000084
Heejin Ahna6e37da2018-05-31 22:02:34 +000085 void demotePHIsOnFunclets(Function &F, bool DemoteCatchSwitchPHIOnly);
David Majnemer8cec2f22015-12-12 05:38:55 +000086 void cloneCommonBlocks(Function &F);
David Majnemerb46bb542015-12-15 21:27:27 +000087 void removeImplausibleInstructions(Function &F);
David Majnemer6badbab2015-09-16 18:40:24 +000088 void cleanupPreparedFunclets(Function &F);
89 void verifyPreparedFunclets(Function &F);
David Majnemer7c58a662015-08-11 01:15:26 +000090
Heejin Ahna6e37da2018-05-31 22:02:34 +000091 bool DemoteCatchSwitchPHIOnly;
92
Reid Kleckner01a1af42015-03-18 20:26:53 +000093 // All fields are reset by runOnFunction.
Reid Kleckner1ed169d2015-04-30 18:17:12 +000094 EHPersonality Personality = EHPersonality::Unknown;
David Majnemer7c58a662015-08-11 01:15:26 +000095
Matt Arsenaulte0b3c332017-04-10 22:27:50 +000096 const DataLayout *DL = nullptr;
David Majnemer8cec2f22015-12-12 05:38:55 +000097 DenseMap<BasicBlock *, ColorVector> BlockColors;
98 MapVector<BasicBlock *, std::vector<BasicBlock *>> FuncletBlocks;
Andrew Kaylor8f475e92015-02-24 20:49:35 +000099};
100
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000101} // end anonymous namespace
102
103char WinEHPrepare::ID = 0;
Matthias Braun94c49042017-05-25 21:26:32 +0000104INITIALIZE_PASS(WinEHPrepare, DEBUG_TYPE, "Prepare Windows exceptions",
Francis Visoiu Mistrihae1c8532017-05-18 17:21:13 +0000105 false, false)
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000106
Heejin Ahna6e37da2018-05-31 22:02:34 +0000107FunctionPass *llvm::createWinEHPass(bool DemoteCatchSwitchPHIOnly) {
108 return new WinEHPrepare(DemoteCatchSwitchPHIOnly);
109}
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000110
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000111bool WinEHPrepare::runOnFunction(Function &Fn) {
David Majnemer7c58a662015-08-11 01:15:26 +0000112 if (!Fn.hasPersonalityFn())
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000113 return false;
114
115 // Classify the personality to see what kind of preparation we need.
David Majnemercc714e22015-06-17 20:52:32 +0000116 Personality = classifyEHPersonality(Fn.getPersonalityFn());
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000117
Heejin Ahn5b752cf2018-05-17 20:52:03 +0000118 // Do nothing if this is not a scope-based personality.
119 if (!isScopedEHPersonality(Personality))
Reid Kleckner7dedaab2015-03-12 00:36:20 +0000120 return false;
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000121
Matt Arsenaulte0b3c332017-04-10 22:27:50 +0000122 DL = &Fn.getParent()->getDataLayout();
David Majnemer8cec2f22015-12-12 05:38:55 +0000123 return prepareExplicitEH(Fn);
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000124}
125
Andrew Kaylor675e22e2015-04-03 19:37:50 +0000126bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000127
David Majnemerdd1775b2015-10-16 19:59:52 +0000128void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
Andrew Kaylor8f475e92015-02-24 20:49:35 +0000129
David Majnemer42be08a2015-08-18 19:07:12 +0000130static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
David Majnemera03aa8f2015-10-10 00:04:29 +0000131 const BasicBlock *BB) {
Reid Klecknerc839e942015-10-09 23:34:53 +0000132 CxxUnwindMapEntry UME;
Reid Kleckner5f504422015-05-28 22:00:24 +0000133 UME.ToState = ToState;
David Majnemera03aa8f2015-10-10 00:04:29 +0000134 UME.Cleanup = BB;
Reid Klecknerc839e942015-10-09 23:34:53 +0000135 FuncInfo.CxxUnwindMap.push_back(UME);
David Majnemer42be08a2015-08-18 19:07:12 +0000136 return FuncInfo.getLastStateNumber();
137}
138
139static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
140 int TryHigh, int CatchHigh,
141 ArrayRef<const CatchPadInst *> Handlers) {
142 WinEHTryBlockMapEntry TBME;
143 TBME.TryLow = TryLow;
144 TBME.TryHigh = TryHigh;
145 TBME.CatchHigh = CatchHigh;
146 assert(TBME.TryLow <= TBME.TryHigh);
147 for (const CatchPadInst *CPI : Handlers) {
148 WinEHHandlerType HT;
149 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
Reid Kleckner66ef9312015-09-16 20:16:27 +0000150 if (TypeInfo->isNullValue())
David Majnemer42be08a2015-08-18 19:07:12 +0000151 HT.TypeDescriptor = nullptr;
Reid Kleckner66ef9312015-09-16 20:16:27 +0000152 else
153 HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
154 HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
David Majnemer4d2c1b62015-10-06 23:31:59 +0000155 HT.Handler = CPI->getParent();
David Majnemer204e31b2016-01-08 08:03:55 +0000156 if (auto *AI =
157 dyn_cast<AllocaInst>(CPI->getArgOperand(2)->stripPointerCasts()))
158 HT.CatchObj.Alloca = AI;
Reid Kleckner66ef9312015-09-16 20:16:27 +0000159 else
David Majnemer204e31b2016-01-08 08:03:55 +0000160 HT.CatchObj.Alloca = nullptr;
David Majnemer42be08a2015-08-18 19:07:12 +0000161 TBME.HandlerArray.push_back(HT);
162 }
163 FuncInfo.TryBlockMap.push_back(TBME);
164}
165
David Majnemer8cec2f22015-12-12 05:38:55 +0000166static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad) {
167 for (const User *U : CleanupPad->users())
168 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
169 return CRI->getUnwindDest();
David Majnemer42be08a2015-08-18 19:07:12 +0000170 return nullptr;
171}
172
David Majnemer8cec2f22015-12-12 05:38:55 +0000173static void calculateStateNumbersForInvokes(const Function *Fn,
174 WinEHFuncInfo &FuncInfo) {
175 auto *F = const_cast<Function *>(Fn);
176 DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(*F);
177 for (BasicBlock &BB : *F) {
178 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
179 if (!II)
180 continue;
181
182 auto &BBColors = BlockColors[&BB];
David Majnemer0f16f3c2015-12-23 03:59:04 +0000183 assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
David Majnemer8cec2f22015-12-12 05:38:55 +0000184 BasicBlock *FuncletEntryBB = BBColors.front();
185
186 BasicBlock *FuncletUnwindDest;
187 auto *FuncletPad =
188 dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI());
189 assert(FuncletPad || FuncletEntryBB == &Fn->getEntryBlock());
190 if (!FuncletPad)
191 FuncletUnwindDest = nullptr;
192 else if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
193 FuncletUnwindDest = CatchPad->getCatchSwitch()->getUnwindDest();
194 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(FuncletPad))
195 FuncletUnwindDest = getCleanupRetUnwindDest(CleanupPad);
196 else
197 llvm_unreachable("unexpected funclet pad!");
198
199 BasicBlock *InvokeUnwindDest = II->getUnwindDest();
200 int BaseState = -1;
201 if (FuncletUnwindDest == InvokeUnwindDest) {
202 auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
203 if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
204 BaseState = BaseStateI->second;
205 }
206
207 if (BaseState != -1) {
208 FuncInfo.InvokeStateMap[II] = BaseState;
209 } else {
210 Instruction *PadInst = InvokeUnwindDest->getFirstNonPHI();
211 assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
212 FuncInfo.InvokeStateMap[II] = FuncInfo.EHPadStateMap[PadInst];
213 }
Reid Kleckner69d051c2015-09-09 21:10:03 +0000214 }
Reid Kleckner69d051c2015-09-09 21:10:03 +0000215}
216
David Majnemer42be08a2015-08-18 19:07:12 +0000217// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
218// to. If the unwind edge came from an invoke, return null.
David Majnemer8cec2f22015-12-12 05:38:55 +0000219static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB,
220 Value *ParentPad) {
Chandler Carruth2aaf7222018-10-15 10:04:59 +0000221 const Instruction *TI = BB->getTerminator();
David Majnemer42be08a2015-08-18 19:07:12 +0000222 if (isa<InvokeInst>(TI))
223 return nullptr;
David Majnemer8cec2f22015-12-12 05:38:55 +0000224 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
225 if (CatchSwitch->getParentPad() != ParentPad)
226 return nullptr;
David Majnemer42be08a2015-08-18 19:07:12 +0000227 return BB;
David Majnemer8cec2f22015-12-12 05:38:55 +0000228 }
229 assert(!TI->isEHPad() && "unexpected EHPad!");
230 auto *CleanupPad = cast<CleanupReturnInst>(TI)->getCleanupPad();
231 if (CleanupPad->getParentPad() != ParentPad)
232 return nullptr;
233 return CleanupPad->getParent();
David Majnemer42be08a2015-08-18 19:07:12 +0000234}
235
David Majnemer8cec2f22015-12-12 05:38:55 +0000236static void calculateCXXStateNumbers(WinEHFuncInfo &FuncInfo,
237 const Instruction *FirstNonPHI,
238 int ParentState) {
239 const BasicBlock *BB = FirstNonPHI->getParent();
240 assert(BB->isEHPad() && "not a funclet!");
David Majnemer42be08a2015-08-18 19:07:12 +0000241
David Majnemer8cec2f22015-12-12 05:38:55 +0000242 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
243 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
244 "shouldn't revist catch funclets!");
245
David Majnemer42be08a2015-08-18 19:07:12 +0000246 SmallVector<const CatchPadInst *, 2> Handlers;
David Majnemer8cec2f22015-12-12 05:38:55 +0000247 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
248 auto *CatchPad = cast<CatchPadInst>(CatchPadBB->getFirstNonPHI());
249 Handlers.push_back(CatchPad);
250 }
David Majnemer42be08a2015-08-18 19:07:12 +0000251 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
David Majnemer8cec2f22015-12-12 05:38:55 +0000252 FuncInfo.EHPadStateMap[CatchSwitch] = TryLow;
253 for (const BasicBlock *PredBlock : predecessors(BB))
254 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
255 CatchSwitch->getParentPad())))
256 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
257 TryLow);
David Majnemer42be08a2015-08-18 19:07:12 +0000258 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
Reid Kleckner69d051c2015-09-09 21:10:03 +0000259
260 // catchpads are separate funclets in C++ EH due to the way rethrow works.
David Majnemer42be08a2015-08-18 19:07:12 +0000261 int TryHigh = CatchLow - 1;
David Majnemer8cec2f22015-12-12 05:38:55 +0000262 for (const auto *CatchPad : Handlers) {
263 FuncInfo.FuncletBaseStateMap[CatchPad] = CatchLow;
264 for (const User *U : CatchPad->users()) {
265 const auto *UserI = cast<Instruction>(U);
David Majnemerd7746922016-02-23 07:18:15 +0000266 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
267 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
268 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemer0f16f3c2015-12-23 03:59:04 +0000269 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
David Majnemerd7746922016-02-23 07:18:15 +0000270 }
Andrew Kaylor4caa75f2016-02-12 21:10:16 +0000271 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
272 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
273 // If a nested cleanup pad reports a null unwind destination and the
274 // enclosing catch pad doesn't it must be post-dominated by an
275 // unreachable instruction.
276 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemer0f16f3c2015-12-23 03:59:04 +0000277 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
Andrew Kaylor4caa75f2016-02-12 21:10:16 +0000278 }
David Majnemer8cec2f22015-12-12 05:38:55 +0000279 }
280 }
David Majnemer42be08a2015-08-18 19:07:12 +0000281 int CatchHigh = FuncInfo.getLastStateNumber();
282 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000283 LLVM_DEBUG(dbgs() << "TryLow[" << BB->getName() << "]: " << TryLow << '\n');
284 LLVM_DEBUG(dbgs() << "TryHigh[" << BB->getName() << "]: " << TryHigh
285 << '\n');
286 LLVM_DEBUG(dbgs() << "CatchHigh[" << BB->getName() << "]: " << CatchHigh
287 << '\n');
David Majnemer42be08a2015-08-18 19:07:12 +0000288 } else {
David Majnemer8cec2f22015-12-12 05:38:55 +0000289 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
290
291 // It's possible for a cleanup to be visited twice: it might have multiple
292 // cleanupret instructions.
293 if (FuncInfo.EHPadStateMap.count(CleanupPad))
294 return;
295
296 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, BB);
297 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000298 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
299 << BB->getName() << '\n');
David Majnemer8cec2f22015-12-12 05:38:55 +0000300 for (const BasicBlock *PredBlock : predecessors(BB)) {
301 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
302 CleanupPad->getParentPad()))) {
303 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
304 CleanupState);
305 }
306 }
307 for (const User *U : CleanupPad->users()) {
308 const auto *UserI = cast<Instruction>(U);
309 if (UserI->isEHPad())
310 report_fatal_error("Cleanup funclets for the MSVC++ personality cannot "
311 "contain exceptional actions");
312 }
David Majnemer42be08a2015-08-18 19:07:12 +0000313 }
314}
315
Reid Kleckner646073b2015-10-01 21:38:24 +0000316static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
317 const Function *Filter, const BasicBlock *Handler) {
Reid Kleckner69d051c2015-09-09 21:10:03 +0000318 SEHUnwindMapEntry Entry;
319 Entry.ToState = ParentState;
Reid Kleckner646073b2015-10-01 21:38:24 +0000320 Entry.IsFinally = false;
Reid Kleckner69d051c2015-09-09 21:10:03 +0000321 Entry.Filter = Filter;
322 Entry.Handler = Handler;
323 FuncInfo.SEHUnwindMap.push_back(Entry);
324 return FuncInfo.SEHUnwindMap.size() - 1;
325}
326
Reid Kleckner646073b2015-10-01 21:38:24 +0000327static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
328 const BasicBlock *Handler) {
329 SEHUnwindMapEntry Entry;
330 Entry.ToState = ParentState;
331 Entry.IsFinally = true;
332 Entry.Filter = nullptr;
333 Entry.Handler = Handler;
334 FuncInfo.SEHUnwindMap.push_back(Entry);
335 return FuncInfo.SEHUnwindMap.size() - 1;
336}
337
David Majnemer8cec2f22015-12-12 05:38:55 +0000338static void calculateSEHStateNumbers(WinEHFuncInfo &FuncInfo,
339 const Instruction *FirstNonPHI,
340 int ParentState) {
341 const BasicBlock *BB = FirstNonPHI->getParent();
342 assert(BB->isEHPad() && "no a funclet!");
Reid Kleckner69d051c2015-09-09 21:10:03 +0000343
David Majnemer8cec2f22015-12-12 05:38:55 +0000344 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
345 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
346 "shouldn't revist catch funclets!");
347
Reid Kleckner69d051c2015-09-09 21:10:03 +0000348 // Extract the filter function and the __except basic block and create a
349 // state for them.
David Majnemer8cec2f22015-12-12 05:38:55 +0000350 assert(CatchSwitch->getNumHandlers() == 1 &&
Reid Kleckner69d051c2015-09-09 21:10:03 +0000351 "SEH doesn't have multiple handlers per __try");
David Majnemer8cec2f22015-12-12 05:38:55 +0000352 const auto *CatchPad =
353 cast<CatchPadInst>((*CatchSwitch->handler_begin())->getFirstNonPHI());
354 const BasicBlock *CatchPadBB = CatchPad->getParent();
Reid Kleckner646073b2015-10-01 21:38:24 +0000355 const Constant *FilterOrNull =
David Majnemer8cec2f22015-12-12 05:38:55 +0000356 cast<Constant>(CatchPad->getArgOperand(0)->stripPointerCasts());
Reid Kleckner646073b2015-10-01 21:38:24 +0000357 const Function *Filter = dyn_cast<Function>(FilterOrNull);
358 assert((Filter || FilterOrNull->isNullValue()) &&
359 "unexpected filter value");
David Majnemer4d2c1b62015-10-06 23:31:59 +0000360 int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
Reid Kleckner69d051c2015-09-09 21:10:03 +0000361
362 // Everything in the __try block uses TryState as its parent state.
David Majnemer8cec2f22015-12-12 05:38:55 +0000363 FuncInfo.EHPadStateMap[CatchSwitch] = TryState;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000364 LLVM_DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
365 << CatchPadBB->getName() << '\n');
David Majnemer8cec2f22015-12-12 05:38:55 +0000366 for (const BasicBlock *PredBlock : predecessors(BB))
367 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
368 CatchSwitch->getParentPad())))
369 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
370 TryState);
Reid Kleckner69d051c2015-09-09 21:10:03 +0000371
372 // Everything in the __except block unwinds to ParentState, just like code
373 // outside the __try.
David Majnemer8cec2f22015-12-12 05:38:55 +0000374 for (const User *U : CatchPad->users()) {
375 const auto *UserI = cast<Instruction>(U);
David Majnemerd7746922016-02-23 07:18:15 +0000376 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
377 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
378 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemer0f16f3c2015-12-23 03:59:04 +0000379 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
David Majnemerd7746922016-02-23 07:18:15 +0000380 }
Andrew Kaylor4caa75f2016-02-12 21:10:16 +0000381 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
382 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
383 // If a nested cleanup pad reports a null unwind destination and the
384 // enclosing catch pad doesn't it must be post-dominated by an
385 // unreachable instruction.
386 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemer0f16f3c2015-12-23 03:59:04 +0000387 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
Andrew Kaylor4caa75f2016-02-12 21:10:16 +0000388 }
David Majnemer8cec2f22015-12-12 05:38:55 +0000389 }
Reid Kleckner69d051c2015-09-09 21:10:03 +0000390 } else {
David Majnemer8cec2f22015-12-12 05:38:55 +0000391 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
392
393 // It's possible for a cleanup to be visited twice: it might have multiple
394 // cleanupret instructions.
395 if (FuncInfo.EHPadStateMap.count(CleanupPad))
396 return;
397
398 int CleanupState = addSEHFinally(FuncInfo, ParentState, BB);
399 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000400 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
401 << BB->getName() << '\n');
David Majnemer8cec2f22015-12-12 05:38:55 +0000402 for (const BasicBlock *PredBlock : predecessors(BB))
403 if ((PredBlock =
404 getEHPadFromPredecessor(PredBlock, CleanupPad->getParentPad())))
405 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
406 CleanupState);
407 for (const User *U : CleanupPad->users()) {
408 const auto *UserI = cast<Instruction>(U);
409 if (UserI->isEHPad())
410 report_fatal_error("Cleanup funclets for the SEH personality cannot "
411 "contain exceptional actions");
412 }
Reid Kleckner69d051c2015-09-09 21:10:03 +0000413 }
414}
415
David Majnemer8cec2f22015-12-12 05:38:55 +0000416static bool isTopLevelPadForMSVC(const Instruction *EHPad) {
417 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(EHPad))
418 return isa<ConstantTokenNone>(CatchSwitch->getParentPad()) &&
419 CatchSwitch->unwindsToCaller();
420 if (auto *CleanupPad = dyn_cast<CleanupPadInst>(EHPad))
421 return isa<ConstantTokenNone>(CleanupPad->getParentPad()) &&
422 getCleanupRetUnwindDest(CleanupPad) == nullptr;
423 if (isa<CatchPadInst>(EHPad))
424 return false;
425 llvm_unreachable("unexpected EHPad!");
Reid Kleckner69d051c2015-09-09 21:10:03 +0000426}
427
Reid Kleckner436444d2015-09-16 22:14:46 +0000428void llvm::calculateSEHStateNumbers(const Function *Fn,
Reid Kleckner69d051c2015-09-09 21:10:03 +0000429 WinEHFuncInfo &FuncInfo) {
430 // Don't compute state numbers twice.
431 if (!FuncInfo.SEHUnwindMap.empty())
432 return;
433
Reid Kleckner436444d2015-09-16 22:14:46 +0000434 for (const BasicBlock &BB : *Fn) {
David Majnemer8cec2f22015-12-12 05:38:55 +0000435 if (!BB.isEHPad())
Reid Kleckner69d051c2015-09-09 21:10:03 +0000436 continue;
David Majnemer8cec2f22015-12-12 05:38:55 +0000437 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
438 if (!isTopLevelPadForMSVC(FirstNonPHI))
439 continue;
440 ::calculateSEHStateNumbers(FuncInfo, FirstNonPHI, -1);
Reid Kleckner69d051c2015-09-09 21:10:03 +0000441 }
David Majnemer8cec2f22015-12-12 05:38:55 +0000442
443 calculateStateNumbersForInvokes(Fn, FuncInfo);
Reid Kleckner69d051c2015-09-09 21:10:03 +0000444}
445
Reid Kleckner436444d2015-09-16 22:14:46 +0000446void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
Reid Kleckner5f504422015-05-28 22:00:24 +0000447 WinEHFuncInfo &FuncInfo) {
448 // Return if it's already been done.
David Majnemer42be08a2015-08-18 19:07:12 +0000449 if (!FuncInfo.EHPadStateMap.empty())
450 return;
451
Reid Kleckner436444d2015-09-16 22:14:46 +0000452 for (const BasicBlock &BB : *Fn) {
David Majnemer42be08a2015-08-18 19:07:12 +0000453 if (!BB.isEHPad())
454 continue;
Joseph Tremoulet226889e2015-09-03 09:09:43 +0000455 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
David Majnemer8cec2f22015-12-12 05:38:55 +0000456 if (!isTopLevelPadForMSVC(FirstNonPHI))
David Majnemer42be08a2015-08-18 19:07:12 +0000457 continue;
David Majnemer8cec2f22015-12-12 05:38:55 +0000458 calculateCXXStateNumbers(FuncInfo, FirstNonPHI, -1);
David Majnemer42be08a2015-08-18 19:07:12 +0000459 }
David Majnemer8cec2f22015-12-12 05:38:55 +0000460
461 calculateStateNumbersForInvokes(Fn, FuncInfo);
Reid Kleckner5f504422015-05-28 22:00:24 +0000462}
David Majnemer7c58a662015-08-11 01:15:26 +0000463
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000464static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState,
465 int TryParentState, ClrHandlerType HandlerType,
466 uint32_t TypeToken, const BasicBlock *Handler) {
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000467 ClrEHUnwindMapEntry Entry;
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000468 Entry.HandlerParentState = HandlerParentState;
469 Entry.TryParentState = TryParentState;
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000470 Entry.Handler = Handler;
471 Entry.HandlerType = HandlerType;
472 Entry.TypeToken = TypeToken;
473 FuncInfo.ClrEHUnwindMap.push_back(Entry);
474 return FuncInfo.ClrEHUnwindMap.size() - 1;
475}
476
477void llvm::calculateClrEHStateNumbers(const Function *Fn,
478 WinEHFuncInfo &FuncInfo) {
479 // Return if it's already been done.
480 if (!FuncInfo.EHPadStateMap.empty())
481 return;
482
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000483 // This numbering assigns one state number to each catchpad and cleanuppad.
484 // It also computes two tree-like relations over states:
485 // 1) Each state has a "HandlerParentState", which is the state of the next
486 // outer handler enclosing this state's handler (same as nearest ancestor
487 // per the ParentPad linkage on EH pads, but skipping over catchswitches).
488 // 2) Each state has a "TryParentState", which:
489 // a) for a catchpad that's not the last handler on its catchswitch, is
490 // the state of the next catchpad on that catchswitch
491 // b) for all other pads, is the state of the pad whose try region is the
492 // next outer try region enclosing this state's try region. The "try
493 // regions are not present as such in the IR, but will be inferred
494 // based on the placement of invokes and pads which reach each other
495 // by exceptional exits
496 // Catchswitches do not get their own states, but each gets mapped to the
497 // state of its first catchpad.
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000498
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000499 // Step one: walk down from outermost to innermost funclets, assigning each
500 // catchpad and cleanuppad a state number. Add an entry to the
501 // ClrEHUnwindMap for each state, recording its HandlerParentState and
502 // handler attributes. Record the TryParentState as well for each catchpad
503 // that's not the last on its catchswitch, but initialize all other entries'
504 // TryParentStates to a sentinel -1 value that the next pass will update.
505
506 // Seed a worklist with pads that have no parent.
507 SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000508 for (const BasicBlock &BB : *Fn) {
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000509 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000510 const Value *ParentPad;
511 if (const auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI))
512 ParentPad = CPI->getParentPad();
513 else if (const auto *CSI = dyn_cast<CatchSwitchInst>(FirstNonPHI))
514 ParentPad = CSI->getParentPad();
515 else
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000516 continue;
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000517 if (isa<ConstantTokenNone>(ParentPad))
518 Worklist.emplace_back(FirstNonPHI, -1);
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000519 }
520
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000521 // Use the worklist to visit all pads, from outer to inner. Record
522 // HandlerParentState for all pads. Record TryParentState only for catchpads
523 // that aren't the last on their catchswitch (setting all other entries'
524 // TryParentStates to an initial value of -1). This loop is also responsible
525 // for setting the EHPadStateMap entry for all catchpads, cleanuppads, and
526 // catchswitches.
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000527 while (!Worklist.empty()) {
528 const Instruction *Pad;
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000529 int HandlerParentState;
530 std::tie(Pad, HandlerParentState) = Worklist.pop_back_val();
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000531
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000532 if (const auto *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
533 // Create the entry for this cleanup with the appropriate handler
Simon Pilgrim84d1e912016-11-20 13:47:59 +0000534 // properties. Finally and fault handlers are distinguished by arity.
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000535 ClrHandlerType HandlerType =
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000536 (Cleanup->getNumArgOperands() ? ClrHandlerType::Fault
537 : ClrHandlerType::Finally);
538 int CleanupState = addClrEHHandler(FuncInfo, HandlerParentState, -1,
539 HandlerType, 0, Pad->getParent());
540 // Queue any child EH pads on the worklist.
541 for (const User *U : Cleanup->users())
542 if (const auto *I = dyn_cast<Instruction>(U))
543 if (I->isEHPad())
544 Worklist.emplace_back(I, CleanupState);
545 // Remember this pad's state.
546 FuncInfo.EHPadStateMap[Cleanup] = CleanupState;
547 } else {
548 // Walk the handlers of this catchswitch in reverse order since all but
549 // the last need to set the following one as its TryParentState.
550 const auto *CatchSwitch = cast<CatchSwitchInst>(Pad);
551 int CatchState = -1, FollowerState = -1;
552 SmallVector<const BasicBlock *, 4> CatchBlocks(CatchSwitch->handlers());
553 for (auto CBI = CatchBlocks.rbegin(), CBE = CatchBlocks.rend();
554 CBI != CBE; ++CBI, FollowerState = CatchState) {
555 const BasicBlock *CatchBlock = *CBI;
556 // Create the entry for this catch with the appropriate handler
557 // properties.
558 const auto *Catch = cast<CatchPadInst>(CatchBlock->getFirstNonPHI());
David Majnemer8cec2f22015-12-12 05:38:55 +0000559 uint32_t TypeToken = static_cast<uint32_t>(
560 cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000561 CatchState =
562 addClrEHHandler(FuncInfo, HandlerParentState, FollowerState,
563 ClrHandlerType::Catch, TypeToken, CatchBlock);
564 // Queue any child EH pads on the worklist.
565 for (const User *U : Catch->users())
566 if (const auto *I = dyn_cast<Instruction>(U))
567 if (I->isEHPad())
568 Worklist.emplace_back(I, CatchState);
569 // Remember this catch's state.
570 FuncInfo.EHPadStateMap[Catch] = CatchState;
David Majnemer8cec2f22015-12-12 05:38:55 +0000571 }
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000572 // Associate the catchswitch with the state of its first catch.
573 assert(CatchSwitch->getNumHandlers());
574 FuncInfo.EHPadStateMap[CatchSwitch] = CatchState;
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000575 }
576 }
David Majnemer8cec2f22015-12-12 05:38:55 +0000577
Joseph Tremoulet7f410b12016-01-04 16:16:01 +0000578 // Step two: record the TryParentState of each state. For cleanuppads that
579 // don't have cleanuprets, we may need to infer this from their child pads,
580 // so visit pads in descendant-most to ancestor-most order.
581 for (auto Entry = FuncInfo.ClrEHUnwindMap.rbegin(),
582 End = FuncInfo.ClrEHUnwindMap.rend();
583 Entry != End; ++Entry) {
584 const Instruction *Pad =
585 Entry->Handler.get<const BasicBlock *>()->getFirstNonPHI();
586 // For most pads, the TryParentState is the state associated with the
587 // unwind dest of exceptional exits from it.
588 const BasicBlock *UnwindDest;
589 if (const auto *Catch = dyn_cast<CatchPadInst>(Pad)) {
590 // If a catch is not the last in its catchswitch, its TryParentState is
591 // the state associated with the next catch in the switch, even though
592 // that's not the unwind dest of exceptions escaping the catch. Those
593 // cases were already assigned a TryParentState in the first pass, so
594 // skip them.
595 if (Entry->TryParentState != -1)
596 continue;
597 // Otherwise, get the unwind dest from the catchswitch.
598 UnwindDest = Catch->getCatchSwitch()->getUnwindDest();
599 } else {
600 const auto *Cleanup = cast<CleanupPadInst>(Pad);
601 UnwindDest = nullptr;
602 for (const User *U : Cleanup->users()) {
603 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
604 // Common and unambiguous case -- cleanupret indicates cleanup's
605 // unwind dest.
606 UnwindDest = CleanupRet->getUnwindDest();
607 break;
608 }
609
610 // Get an unwind dest for the user
611 const BasicBlock *UserUnwindDest = nullptr;
612 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
613 UserUnwindDest = Invoke->getUnwindDest();
614 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(U)) {
615 UserUnwindDest = CatchSwitch->getUnwindDest();
616 } else if (auto *ChildCleanup = dyn_cast<CleanupPadInst>(U)) {
617 int UserState = FuncInfo.EHPadStateMap[ChildCleanup];
618 int UserUnwindState =
619 FuncInfo.ClrEHUnwindMap[UserState].TryParentState;
620 if (UserUnwindState != -1)
621 UserUnwindDest = FuncInfo.ClrEHUnwindMap[UserUnwindState]
622 .Handler.get<const BasicBlock *>();
623 }
624
625 // Not having an unwind dest for this user might indicate that it
626 // doesn't unwind, so can't be taken as proof that the cleanup itself
627 // may unwind to caller (see e.g. SimplifyUnreachable and
628 // RemoveUnwindEdge).
629 if (!UserUnwindDest)
630 continue;
631
632 // Now we have an unwind dest for the user, but we need to see if it
633 // unwinds all the way out of the cleanup or if it stays within it.
634 const Instruction *UserUnwindPad = UserUnwindDest->getFirstNonPHI();
635 const Value *UserUnwindParent;
636 if (auto *CSI = dyn_cast<CatchSwitchInst>(UserUnwindPad))
637 UserUnwindParent = CSI->getParentPad();
638 else
639 UserUnwindParent =
640 cast<CleanupPadInst>(UserUnwindPad)->getParentPad();
641
642 // The unwind stays within the cleanup iff it targets a child of the
643 // cleanup.
644 if (UserUnwindParent == Cleanup)
645 continue;
646
647 // This unwind exits the cleanup, so its dest is the cleanup's dest.
648 UnwindDest = UserUnwindDest;
649 break;
650 }
651 }
652
653 // Record the state of the unwind dest as the TryParentState.
654 int UnwindDestState;
655
656 // If UnwindDest is null at this point, either the pad in question can
657 // be exited by unwind to caller, or it cannot be exited by unwind. In
658 // either case, reporting such cases as unwinding to caller is correct.
659 // This can lead to EH tables that "look strange" -- if this pad's is in
660 // a parent funclet which has other children that do unwind to an enclosing
661 // pad, the try region for this pad will be missing the "duplicate" EH
662 // clause entries that you'd expect to see covering the whole parent. That
663 // should be benign, since the unwind never actually happens. If it were
664 // an issue, we could add a subsequent pass that pushes unwind dests down
665 // from parents that have them to children that appear to unwind to caller.
666 if (!UnwindDest) {
667 UnwindDestState = -1;
668 } else {
669 UnwindDestState = FuncInfo.EHPadStateMap[UnwindDest->getFirstNonPHI()];
670 }
671
672 Entry->TryParentState = UnwindDestState;
673 }
674
675 // Step three: transfer information from pads to invokes.
David Majnemer8cec2f22015-12-12 05:38:55 +0000676 calculateStateNumbersForInvokes(Fn, FuncInfo);
Joseph Tremoulet7d21fd62015-10-06 20:30:33 +0000677}
678
David Majnemer8cec2f22015-12-12 05:38:55 +0000679void WinEHPrepare::colorFunclets(Function &F) {
680 BlockColors = colorEHFunclets(F);
David Majnemer7c58a662015-08-11 01:15:26 +0000681
David Majnemer8cec2f22015-12-12 05:38:55 +0000682 // Invert the map from BB to colors to color to BBs.
683 for (BasicBlock &BB : F) {
684 ColorVector &Colors = BlockColors[&BB];
685 for (BasicBlock *Color : Colors)
686 FuncletBlocks[Color].push_back(&BB);
David Majnemer7c58a662015-08-11 01:15:26 +0000687 }
688}
689
Heejin Ahna6e37da2018-05-31 22:02:34 +0000690void WinEHPrepare::demotePHIsOnFunclets(Function &F,
691 bool DemoteCatchSwitchPHIOnly) {
Joseph Tremouletccc0cf32015-08-13 14:30:10 +0000692 // Strip PHI nodes off of EH pads.
693 SmallVector<PHINode *, 16> PHINodes;
David Majnemer7c58a662015-08-11 01:15:26 +0000694 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithac4d7b62015-10-09 22:56:24 +0000695 BasicBlock *BB = &*FI++;
David Majnemer7c58a662015-08-11 01:15:26 +0000696 if (!BB->isEHPad())
697 continue;
Heejin Ahna6e37da2018-05-31 22:02:34 +0000698 if (DemoteCatchSwitchPHIOnly && !isa<CatchSwitchInst>(BB->getFirstNonPHI()))
699 continue;
700
David Majnemer7c58a662015-08-11 01:15:26 +0000701 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Duncan P. N. Exon Smithac4d7b62015-10-09 22:56:24 +0000702 Instruction *I = &*BI++;
David Majnemer7c58a662015-08-11 01:15:26 +0000703 auto *PN = dyn_cast<PHINode>(I);
704 // Stop at the first non-PHI.
705 if (!PN)
706 break;
David Majnemer7c58a662015-08-11 01:15:26 +0000707
Joseph Tremouletccc0cf32015-08-13 14:30:10 +0000708 AllocaInst *SpillSlot = insertPHILoads(PN, F);
709 if (SpillSlot)
710 insertPHIStores(PN, SpillSlot);
711
712 PHINodes.push_back(PN);
David Majnemer7c58a662015-08-11 01:15:26 +0000713 }
714 }
715
Joseph Tremouletccc0cf32015-08-13 14:30:10 +0000716 for (auto *PN : PHINodes) {
717 // There may be lingering uses on other EH PHIs being removed
718 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
719 PN->eraseFromParent();
David Majnemer7c58a662015-08-11 01:15:26 +0000720 }
David Majnemer6badbab2015-09-16 18:40:24 +0000721}
David Majnemer7c58a662015-08-11 01:15:26 +0000722
David Majnemer8cec2f22015-12-12 05:38:55 +0000723void WinEHPrepare::cloneCommonBlocks(Function &F) {
David Majnemer7c58a662015-08-11 01:15:26 +0000724 // We need to clone all blocks which belong to multiple funclets. Values are
Simon Pilgrim84d1e912016-11-20 13:47:59 +0000725 // remapped throughout the funclet to propagate both the new instructions
David Majnemer7c58a662015-08-11 01:15:26 +0000726 // *and* the new basic blocks themselves.
David Majnemer8cec2f22015-12-12 05:38:55 +0000727 for (auto &Funclets : FuncletBlocks) {
728 BasicBlock *FuncletPadBB = Funclets.first;
729 std::vector<BasicBlock *> &BlocksInFunclet = Funclets.second;
Joseph Tremouletd5ab13d2016-01-02 15:22:36 +0000730 Value *FuncletToken;
731 if (FuncletPadBB == &F.getEntryBlock())
732 FuncletToken = ConstantTokenNone::get(F.getContext());
733 else
734 FuncletToken = FuncletPadBB->getFirstNonPHI();
David Majnemer7c58a662015-08-11 01:15:26 +0000735
David Majnemer8cec2f22015-12-12 05:38:55 +0000736 std::vector<std::pair<BasicBlock *, BasicBlock *>> Orig2Clone;
David Majnemer7c58a662015-08-11 01:15:26 +0000737 ValueToValueMapTy VMap;
David Majnemer8cec2f22015-12-12 05:38:55 +0000738 for (BasicBlock *BB : BlocksInFunclet) {
739 ColorVector &ColorsForBB = BlockColors[BB];
David Majnemer7c58a662015-08-11 01:15:26 +0000740 // We don't need to do anything if the block is monochromatic.
741 size_t NumColorsForBB = ColorsForBB.size();
742 if (NumColorsForBB == 1)
743 continue;
744
Andrew Kaylor805b66a2015-11-09 19:59:02 +0000745 DEBUG_WITH_TYPE("winehprepare-coloring",
746 dbgs() << " Cloning block \'" << BB->getName()
747 << "\' for funclet \'" << FuncletPadBB->getName()
748 << "\'.\n");
749
David Majnemer7c58a662015-08-11 01:15:26 +0000750 // Create a new basic block and copy instructions into it!
Joseph Tremoulet0bf9bba2015-08-28 01:12:35 +0000751 BasicBlock *CBB =
752 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
753 // Insert the clone immediately after the original to ensure determinism
754 // and to keep the same relative ordering of any funclet's blocks.
755 CBB->insertInto(&F, BB->getNextNode());
David Majnemer7c58a662015-08-11 01:15:26 +0000756
757 // Add basic block mapping.
758 VMap[BB] = CBB;
759
760 // Record delta operations that we need to perform to our color mappings.
David Majnemer8cec2f22015-12-12 05:38:55 +0000761 Orig2Clone.emplace_back(BB, CBB);
David Majnemer7c58a662015-08-11 01:15:26 +0000762 }
763
Joseph Tremoulet0e0be5a2015-10-07 19:29:56 +0000764 // If nothing was cloned, we're done cloning in this funclet.
765 if (Orig2Clone.empty())
766 continue;
767
David Majnemer7c58a662015-08-11 01:15:26 +0000768 // Update our color mappings to reflect that one block has lost a color and
769 // another has gained a color.
770 for (auto &BBMapping : Orig2Clone) {
771 BasicBlock *OldBlock = BBMapping.first;
772 BasicBlock *NewBlock = BBMapping.second;
773
David Majnemer8cec2f22015-12-12 05:38:55 +0000774 BlocksInFunclet.push_back(NewBlock);
775 ColorVector &NewColors = BlockColors[NewBlock];
776 assert(NewColors.empty() && "A new block should only have one color!");
777 NewColors.push_back(FuncletPadBB);
David Majnemer7c58a662015-08-11 01:15:26 +0000778
Andrew Kaylor805b66a2015-11-09 19:59:02 +0000779 DEBUG_WITH_TYPE("winehprepare-coloring",
780 dbgs() << " Assigned color \'" << FuncletPadBB->getName()
781 << "\' to block \'" << NewBlock->getName()
782 << "\'.\n");
783
David Majnemer8cec2f22015-12-12 05:38:55 +0000784 BlocksInFunclet.erase(
785 std::remove(BlocksInFunclet.begin(), BlocksInFunclet.end(), OldBlock),
786 BlocksInFunclet.end());
787 ColorVector &OldColors = BlockColors[OldBlock];
788 OldColors.erase(
789 std::remove(OldColors.begin(), OldColors.end(), FuncletPadBB),
790 OldColors.end());
Andrew Kaylor805b66a2015-11-09 19:59:02 +0000791
792 DEBUG_WITH_TYPE("winehprepare-coloring",
793 dbgs() << " Removed color \'" << FuncletPadBB->getName()
794 << "\' from block \'" << OldBlock->getName()
795 << "\'.\n");
David Majnemer7c58a662015-08-11 01:15:26 +0000796 }
797
Joseph Tremoulet0e0be5a2015-10-07 19:29:56 +0000798 // Loop over all of the instructions in this funclet, fixing up operand
David Majnemer7c58a662015-08-11 01:15:26 +0000799 // references as we go. This uses VMap to do all the hard work.
800 for (BasicBlock *BB : BlocksInFunclet)
801 // Loop over all instructions, fixing each one as we find it...
802 for (Instruction &I : *BB)
Joseph Tremoulet0e0be5a2015-10-07 19:29:56 +0000803 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithfff83572016-04-07 00:26:43 +0000804 RF_IgnoreMissingLocals | RF_NoModuleLevelChanges);
David Majnemerad53a652015-09-16 18:40:37 +0000805
Joseph Tremouletd5ab13d2016-01-02 15:22:36 +0000806 // Catchrets targeting cloned blocks need to be updated separately from
807 // the loop above because they are not in the current funclet.
808 SmallVector<CatchReturnInst *, 2> FixupCatchrets;
809 for (auto &BBMapping : Orig2Clone) {
810 BasicBlock *OldBlock = BBMapping.first;
811 BasicBlock *NewBlock = BBMapping.second;
812
813 FixupCatchrets.clear();
814 for (BasicBlock *Pred : predecessors(OldBlock))
815 if (auto *CatchRet = dyn_cast<CatchReturnInst>(Pred->getTerminator()))
Joseph Tremouletc5fde132016-01-15 21:16:19 +0000816 if (CatchRet->getCatchSwitchParentPad() == FuncletToken)
Joseph Tremouletd5ab13d2016-01-02 15:22:36 +0000817 FixupCatchrets.push_back(CatchRet);
818
819 for (CatchReturnInst *CatchRet : FixupCatchrets)
820 CatchRet->setSuccessor(NewBlock);
821 }
822
David Majnemer8cec2f22015-12-12 05:38:55 +0000823 auto UpdatePHIOnClonedBlock = [&](PHINode *PN, bool IsForOldBlock) {
824 unsigned NumPreds = PN->getNumIncomingValues();
825 for (unsigned PredIdx = 0, PredEnd = NumPreds; PredIdx != PredEnd;
826 ++PredIdx) {
827 BasicBlock *IncomingBlock = PN->getIncomingBlock(PredIdx);
Joseph Tremouletd5ab13d2016-01-02 15:22:36 +0000828 bool EdgeTargetsFunclet;
829 if (auto *CRI =
830 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
Joseph Tremouletc5fde132016-01-15 21:16:19 +0000831 EdgeTargetsFunclet = (CRI->getCatchSwitchParentPad() == FuncletToken);
Joseph Tremouletd5ab13d2016-01-02 15:22:36 +0000832 } else {
833 ColorVector &IncomingColors = BlockColors[IncomingBlock];
834 assert(!IncomingColors.empty() && "Block not colored!");
835 assert((IncomingColors.size() == 1 ||
836 llvm::all_of(IncomingColors,
837 [&](BasicBlock *Color) {
838 return Color != FuncletPadBB;
839 })) &&
840 "Cloning should leave this funclet's blocks monochromatic");
841 EdgeTargetsFunclet = (IncomingColors.front() == FuncletPadBB);
842 }
843 if (IsForOldBlock != EdgeTargetsFunclet)
David Majnemer8cec2f22015-12-12 05:38:55 +0000844 continue;
845 PN->removeIncomingValue(IncomingBlock, /*DeletePHIIfEmpty=*/false);
846 // Revisit the next entry.
847 --PredIdx;
848 --PredEnd;
849 }
850 };
851
852 for (auto &BBMapping : Orig2Clone) {
853 BasicBlock *OldBlock = BBMapping.first;
854 BasicBlock *NewBlock = BBMapping.second;
Benjamin Kramer66f3fb92017-12-30 15:27:33 +0000855 for (PHINode &OldPN : OldBlock->phis()) {
856 UpdatePHIOnClonedBlock(&OldPN, /*IsForOldBlock=*/true);
David Majnemer8cec2f22015-12-12 05:38:55 +0000857 }
Benjamin Kramer66f3fb92017-12-30 15:27:33 +0000858 for (PHINode &NewPN : NewBlock->phis()) {
859 UpdatePHIOnClonedBlock(&NewPN, /*IsForOldBlock=*/false);
David Majnemer8cec2f22015-12-12 05:38:55 +0000860 }
861 }
862
David Majnemerad53a652015-09-16 18:40:37 +0000863 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
864 // the PHI nodes for NewBB now.
865 for (auto &BBMapping : Orig2Clone) {
866 BasicBlock *OldBlock = BBMapping.first;
867 BasicBlock *NewBlock = BBMapping.second;
868 for (BasicBlock *SuccBB : successors(NewBlock)) {
Benjamin Kramer66f3fb92017-12-30 15:27:33 +0000869 for (PHINode &SuccPN : SuccBB->phis()) {
David Majnemerad53a652015-09-16 18:40:37 +0000870 // Ok, we have a PHI node. Figure out what the incoming value was for
871 // the OldBlock.
Benjamin Kramer66f3fb92017-12-30 15:27:33 +0000872 int OldBlockIdx = SuccPN.getBasicBlockIndex(OldBlock);
David Majnemerad53a652015-09-16 18:40:37 +0000873 if (OldBlockIdx == -1)
874 break;
Benjamin Kramer66f3fb92017-12-30 15:27:33 +0000875 Value *IV = SuccPN.getIncomingValue(OldBlockIdx);
David Majnemerad53a652015-09-16 18:40:37 +0000876
877 // Remap the value if necessary.
878 if (auto *Inst = dyn_cast<Instruction>(IV)) {
879 ValueToValueMapTy::iterator I = VMap.find(Inst);
880 if (I != VMap.end())
881 IV = I->second;
882 }
883
Benjamin Kramer66f3fb92017-12-30 15:27:33 +0000884 SuccPN.addIncoming(IV, NewBlock);
David Majnemerad53a652015-09-16 18:40:37 +0000885 }
886 }
887 }
888
889 for (ValueToValueMapTy::value_type VT : VMap) {
890 // If there were values defined in BB that are used outside the funclet,
891 // then we now have to update all uses of the value to use either the
892 // original value, the cloned value, or some PHI derived value. This can
893 // require arbitrary PHI insertion, of which we are prepared to do, clean
894 // these up now.
895 SmallVector<Use *, 16> UsesToRename;
896
897 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
898 if (!OldI)
899 continue;
900 auto *NewI = cast<Instruction>(VT.second);
901 // Scan all uses of this instruction to see if it is used outside of its
902 // funclet, and if so, record them in UsesToRename.
903 for (Use &U : OldI->uses()) {
904 Instruction *UserI = cast<Instruction>(U.getUser());
905 BasicBlock *UserBB = UserI->getParent();
David Majnemer8cec2f22015-12-12 05:38:55 +0000906 ColorVector &ColorsForUserBB = BlockColors[UserBB];
David Majnemerad53a652015-09-16 18:40:37 +0000907 assert(!ColorsForUserBB.empty());
908 if (ColorsForUserBB.size() > 1 ||
909 *ColorsForUserBB.begin() != FuncletPadBB)
910 UsesToRename.push_back(&U);
911 }
912
913 // If there are no uses outside the block, we're done with this
914 // instruction.
915 if (UsesToRename.empty())
916 continue;
917
918 // We found a use of OldI outside of the funclet. Rename all uses of OldI
919 // that are outside its funclet to be uses of the appropriate PHI node
920 // etc.
921 SSAUpdater SSAUpdate;
922 SSAUpdate.Initialize(OldI->getType(), OldI->getName());
923 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
924 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
925
926 while (!UsesToRename.empty())
927 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
928 }
David Majnemer7c58a662015-08-11 01:15:26 +0000929 }
David Majnemer6badbab2015-09-16 18:40:24 +0000930}
David Majnemer7c58a662015-08-11 01:15:26 +0000931
David Majnemerb46bb542015-12-15 21:27:27 +0000932void WinEHPrepare::removeImplausibleInstructions(Function &F) {
David Majnemerd8ea8742015-08-17 20:56:39 +0000933 // Remove implausible terminators and replace them with UnreachableInst.
934 for (auto &Funclet : FuncletBlocks) {
935 BasicBlock *FuncletPadBB = Funclet.first;
David Majnemer8cec2f22015-12-12 05:38:55 +0000936 std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
David Majnemerb46bb542015-12-15 21:27:27 +0000937 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
938 auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
939 auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
940 auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
David Majnemerd8ea8742015-08-17 20:56:39 +0000941
942 for (BasicBlock *BB : BlocksInFunclet) {
David Majnemerb46bb542015-12-15 21:27:27 +0000943 for (Instruction &I : *BB) {
944 CallSite CS(&I);
945 if (!CS)
946 continue;
947
948 Value *FuncletBundleOperand = nullptr;
949 if (auto BU = CS.getOperandBundle(LLVMContext::OB_funclet))
950 FuncletBundleOperand = BU->Inputs.front();
951
952 if (FuncletBundleOperand == FuncletPad)
953 continue;
954
David Majnemer20cfdfe2016-02-26 00:04:25 +0000955 // Skip call sites which are nounwind intrinsics or inline asm.
David Majnemerb46bb542015-12-15 21:27:27 +0000956 auto *CalledFn =
957 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Justin Lebar24dbd382016-07-28 23:58:15 +0000958 if (CalledFn && ((CalledFn->isIntrinsic() && CS.doesNotThrow()) ||
959 CS.isInlineAsm()))
David Majnemerb46bb542015-12-15 21:27:27 +0000960 continue;
961
962 // This call site was not part of this funclet, remove it.
963 if (CS.isInvoke()) {
964 // Remove the unwind edge if it was an invoke.
965 removeUnwindEdge(BB);
966 // Get a pointer to the new call.
967 BasicBlock::iterator CallI =
968 std::prev(BB->getTerminator()->getIterator());
969 auto *CI = cast<CallInst>(&*CallI);
David Majnemerdb5173a2016-06-25 08:19:55 +0000970 changeToUnreachable(CI, /*UseLLVMTrap=*/false);
David Majnemerb46bb542015-12-15 21:27:27 +0000971 } else {
David Majnemerdb5173a2016-06-25 08:19:55 +0000972 changeToUnreachable(&I, /*UseLLVMTrap=*/false);
David Majnemerb46bb542015-12-15 21:27:27 +0000973 }
974
975 // There are no more instructions in the block (except for unreachable),
976 // we are done.
977 break;
978 }
979
Chandler Carruth2aaf7222018-10-15 10:04:59 +0000980 Instruction *TI = BB->getTerminator();
David Majnemerd8ea8742015-08-17 20:56:39 +0000981 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
David Majnemerb46bb542015-12-15 21:27:27 +0000982 bool IsUnreachableRet = isa<ReturnInst>(TI) && FuncletPad;
David Majnemerd8ea8742015-08-17 20:56:39 +0000983 // The token consumed by a CatchReturnInst must match the funclet token.
984 bool IsUnreachableCatchret = false;
985 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
Joseph Tremouletd4a765f2015-08-23 00:26:33 +0000986 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
Joseph Tremoulet226889e2015-09-03 09:09:43 +0000987 // The token consumed by a CleanupReturnInst must match the funclet token.
David Majnemerd8ea8742015-08-17 20:56:39 +0000988 bool IsUnreachableCleanupret = false;
989 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
Joseph Tremouletd4a765f2015-08-23 00:26:33 +0000990 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
Joseph Tremoulet226889e2015-09-03 09:09:43 +0000991 if (IsUnreachableRet || IsUnreachableCatchret ||
David Majnemer8cec2f22015-12-12 05:38:55 +0000992 IsUnreachableCleanupret) {
David Majnemerdb5173a2016-06-25 08:19:55 +0000993 changeToUnreachable(TI, /*UseLLVMTrap=*/false);
David Majnemer8cec2f22015-12-12 05:38:55 +0000994 } else if (isa<InvokeInst>(TI)) {
David Majnemerb46bb542015-12-15 21:27:27 +0000995 if (Personality == EHPersonality::MSVC_CXX && CleanupPad) {
996 // Invokes within a cleanuppad for the MSVC++ personality never
997 // transfer control to their unwind edge: the personality will
998 // terminate the program.
David Majnemer8cec2f22015-12-12 05:38:55 +0000999 removeUnwindEdge(BB);
David Majnemerb46bb542015-12-15 21:27:27 +00001000 }
David Majnemerd8ea8742015-08-17 20:56:39 +00001001 }
1002 }
1003 }
David Majnemer6badbab2015-09-16 18:40:24 +00001004}
David Majnemerd8ea8742015-08-17 20:56:39 +00001005
David Majnemer6badbab2015-09-16 18:40:24 +00001006void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
David Majnemer7c58a662015-08-11 01:15:26 +00001007 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
1008 // branches, etc.
1009 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithac4d7b62015-10-09 22:56:24 +00001010 BasicBlock *BB = &*FI++;
David Majnemer7c58a662015-08-11 01:15:26 +00001011 SimplifyInstructionsInBlock(BB);
1012 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
1013 MergeBlockIntoPredecessor(BB);
1014 }
1015
David Majnemer7c58a662015-08-11 01:15:26 +00001016 // We might have some unreachable blocks after cleaning up some impossible
1017 // control flow.
1018 removeUnreachableBlocks(F);
David Majnemer6badbab2015-09-16 18:40:24 +00001019}
David Majnemer7c58a662015-08-11 01:15:26 +00001020
Florian Hahn8b712792017-07-31 10:07:49 +00001021#ifndef NDEBUG
David Majnemer6badbab2015-09-16 18:40:24 +00001022void WinEHPrepare::verifyPreparedFunclets(Function &F) {
David Majnemer7c58a662015-08-11 01:15:26 +00001023 for (BasicBlock &BB : F) {
1024 size_t NumColors = BlockColors[&BB].size();
1025 assert(NumColors == 1 && "Expected monochromatic BB!");
1026 if (NumColors == 0)
1027 report_fatal_error("Uncolored BB!");
1028 if (NumColors > 1)
1029 report_fatal_error("Multicolor BB!");
NAKAMURA Takumibaea3c82016-01-03 01:41:00 +00001030 assert((DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) &&
1031 "EH Pad still has a PHI!");
David Majnemer7c58a662015-08-11 01:15:26 +00001032 }
David Majnemer6badbab2015-09-16 18:40:24 +00001033}
Florian Hahn8b712792017-07-31 10:07:49 +00001034#endif
David Majnemer6badbab2015-09-16 18:40:24 +00001035
David Majnemer8cec2f22015-12-12 05:38:55 +00001036bool WinEHPrepare::prepareExplicitEH(Function &F) {
1037 // Remove unreachable blocks. It is not valuable to assign them a color and
1038 // their existence can trick us into thinking values are alive when they are
1039 // not.
1040 removeUnreachableBlocks(F);
1041
David Majnemer6badbab2015-09-16 18:40:24 +00001042 // Determine which blocks are reachable from which funclet entries.
David Majnemer8cec2f22015-12-12 05:38:55 +00001043 colorFunclets(F);
1044
1045 cloneCommonBlocks(F);
David Majnemer6badbab2015-09-16 18:40:24 +00001046
Reid Klecknerd1d6f532015-11-19 23:23:33 +00001047 if (!DisableDemotion)
Heejin Ahna6e37da2018-05-31 22:02:34 +00001048 demotePHIsOnFunclets(F, DemoteCatchSwitchPHIOnly ||
1049 DemoteCatchSwitchPHIOnlyOpt);
David Majnemer6badbab2015-09-16 18:40:24 +00001050
David Majnemerad53a652015-09-16 18:40:37 +00001051 if (!DisableCleanups) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001052 LLVM_DEBUG(verifyFunction(F));
David Majnemerb46bb542015-12-15 21:27:27 +00001053 removeImplausibleInstructions(F);
David Majnemer6badbab2015-09-16 18:40:24 +00001054
Nicola Zaghen0818e782018-05-14 12:53:11 +00001055 LLVM_DEBUG(verifyFunction(F));
David Majnemerad53a652015-09-16 18:40:37 +00001056 cleanupPreparedFunclets(F);
1057 }
David Majnemer6badbab2015-09-16 18:40:24 +00001058
Nicola Zaghen0818e782018-05-14 12:53:11 +00001059 LLVM_DEBUG(verifyPreparedFunclets(F));
David Majnemer71d29c12016-01-02 09:26:36 +00001060 // Recolor the CFG to verify that all is well.
Nicola Zaghen0818e782018-05-14 12:53:11 +00001061 LLVM_DEBUG(colorFunclets(F));
1062 LLVM_DEBUG(verifyPreparedFunclets(F));
David Majnemer7c58a662015-08-11 01:15:26 +00001063
1064 BlockColors.clear();
1065 FuncletBlocks.clear();
David Majnemer42be08a2015-08-18 19:07:12 +00001066
David Majnemer7c58a662015-08-11 01:15:26 +00001067 return true;
1068}
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001069
1070// TODO: Share loads when one use dominates another, or when a catchpad exit
1071// dominates uses (needs dominators).
1072AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
1073 BasicBlock *PHIBlock = PN->getParent();
1074 AllocaInst *SpillSlot = nullptr;
David Majnemer8cec2f22015-12-12 05:38:55 +00001075 Instruction *EHPad = PHIBlock->getFirstNonPHI();
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001076
Chandler Carruth9179aee2018-08-26 09:51:22 +00001077 if (!EHPad->isTerminator()) {
David Majnemer8cec2f22015-12-12 05:38:55 +00001078 // If the EHPad isn't a terminator, then we can insert a load in this block
1079 // that will dominate all uses.
Matt Arsenaulte0b3c332017-04-10 22:27:50 +00001080 SpillSlot = new AllocaInst(PN->getType(), DL->getAllocaAddrSpace(), nullptr,
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001081 Twine(PN->getName(), ".wineh.spillslot"),
Duncan P. N. Exon Smithac4d7b62015-10-09 22:56:24 +00001082 &F.getEntryBlock().front());
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001083 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
Duncan P. N. Exon Smithac4d7b62015-10-09 22:56:24 +00001084 &*PHIBlock->getFirstInsertionPt());
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001085 PN->replaceAllUsesWith(V);
1086 return SpillSlot;
1087 }
1088
David Majnemer8cec2f22015-12-12 05:38:55 +00001089 // Otherwise, we have a PHI on a terminator EHPad, and we give up and insert
1090 // loads of the slot before every use.
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001091 DenseMap<BasicBlock *, Value *> Loads;
1092 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1093 UI != UE;) {
1094 Use &U = *UI++;
1095 auto *UsingInst = cast<Instruction>(U.getUser());
David Majnemer8cec2f22015-12-12 05:38:55 +00001096 if (isa<PHINode>(UsingInst) && UsingInst->getParent()->isEHPad()) {
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001097 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
1098 // stores for it separately.
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001099 continue;
1100 }
1101 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
1102 }
1103 return SpillSlot;
1104}
1105
1106// TODO: improve store placement. Inserting at def is probably good, but need
1107// to be careful not to introduce interfering stores (needs liveness analysis).
1108// TODO: identify related phi nodes that can share spill slots, and share them
1109// (also needs liveness).
1110void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
1111 AllocaInst *SpillSlot) {
1112 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
1113 // stored to the spill slot by the end of the given Block.
1114 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
1115
1116 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
1117
1118 while (!Worklist.empty()) {
1119 BasicBlock *EHBlock;
1120 Value *InVal;
1121 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
1122
1123 PHINode *PN = dyn_cast<PHINode>(InVal);
1124 if (PN && PN->getParent() == EHBlock) {
1125 // The value is defined by another PHI we need to remove, with no room to
1126 // insert a store after the PHI, so each predecessor needs to store its
1127 // incoming value.
1128 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1129 Value *PredVal = PN->getIncomingValue(i);
1130
1131 // Undef can safely be skipped.
1132 if (isa<UndefValue>(PredVal))
1133 continue;
1134
1135 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
1136 }
1137 } else {
1138 // We need to store InVal, which dominates EHBlock, but can't put a store
1139 // in EHBlock, so need to put stores in each predecessor.
1140 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
1141 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
1142 }
1143 }
1144 }
1145}
1146
1147void WinEHPrepare::insertPHIStore(
1148 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
1149 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
1150
Chandler Carruth9179aee2018-08-26 09:51:22 +00001151 if (PredBlock->isEHPad() && PredBlock->getFirstNonPHI()->isTerminator()) {
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001152 // Pred is unsplittable, so we need to queue it on the worklist.
1153 Worklist.push_back({PredBlock, PredVal});
1154 return;
1155 }
1156
1157 // Otherwise, insert the store at the end of the basic block.
1158 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
1159}
1160
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001161void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
1162 DenseMap<BasicBlock *, Value *> &Loads,
1163 Function &F) {
1164 // Lazilly create the spill slot.
1165 if (!SpillSlot)
Matt Arsenaulte0b3c332017-04-10 22:27:50 +00001166 SpillSlot = new AllocaInst(V->getType(), DL->getAllocaAddrSpace(), nullptr,
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001167 Twine(V->getName(), ".wineh.spillslot"),
Duncan P. N. Exon Smithac4d7b62015-10-09 22:56:24 +00001168 &F.getEntryBlock().front());
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001169
1170 auto *UsingInst = cast<Instruction>(U.getUser());
1171 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
1172 // If this is a PHI node, we can't insert a load of the value before
1173 // the use. Instead insert the load in the predecessor block
1174 // corresponding to the incoming value.
1175 //
1176 // Note that if there are multiple edges from a basic block to this
1177 // PHI node that we cannot have multiple loads. The problem is that
1178 // the resulting PHI node will have multiple values (from each load)
1179 // coming in from the same block, which is illegal SSA form.
1180 // For this reason, we keep track of and reuse loads we insert.
1181 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
Joseph Tremoulet08b10aa2015-08-17 13:51:37 +00001182 if (auto *CatchRet =
1183 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1184 // Putting a load above a catchret and use on the phi would still leave
1185 // a cross-funclet def/use. We need to split the edge, change the
1186 // catchret to target the new block, and put the load there.
1187 BasicBlock *PHIBlock = UsingInst->getParent();
1188 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
1189 // SplitEdge gives us:
1190 // IncomingBlock:
1191 // ...
1192 // br label %NewBlock
1193 // NewBlock:
1194 // catchret label %PHIBlock
1195 // But we need:
1196 // IncomingBlock:
1197 // ...
1198 // catchret label %NewBlock
1199 // NewBlock:
1200 // br label %PHIBlock
1201 // So move the terminators to each others' blocks and swap their
1202 // successors.
1203 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
1204 Goto->removeFromParent();
1205 CatchRet->removeFromParent();
1206 IncomingBlock->getInstList().push_back(CatchRet);
1207 NewBlock->getInstList().push_back(Goto);
1208 Goto->setSuccessor(0, PHIBlock);
1209 CatchRet->setSuccessor(NewBlock);
1210 // Update the color mapping for the newly split edge.
Andrew Kaylor577bb062016-12-14 19:30:18 +00001211 // Grab a reference to the ColorVector to be inserted before getting the
1212 // reference to the vector we are copying because inserting the new
1213 // element in BlockColors might cause the map to be reallocated.
1214 ColorVector &ColorsForNewBlock = BlockColors[NewBlock];
David Majnemer8cec2f22015-12-12 05:38:55 +00001215 ColorVector &ColorsForPHIBlock = BlockColors[PHIBlock];
Andrew Kaylor577bb062016-12-14 19:30:18 +00001216 ColorsForNewBlock = ColorsForPHIBlock;
Joseph Tremoulet08b10aa2015-08-17 13:51:37 +00001217 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
David Majnemer8cec2f22015-12-12 05:38:55 +00001218 FuncletBlocks[FuncletPad].push_back(NewBlock);
Joseph Tremoulet08b10aa2015-08-17 13:51:37 +00001219 // Treat the new block as incoming for load insertion.
1220 IncomingBlock = NewBlock;
1221 }
Joseph Tremouletccc0cf32015-08-13 14:30:10 +00001222 Value *&Load = Loads[IncomingBlock];
1223 // Insert the load into the predecessor block
1224 if (!Load)
1225 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1226 /*Volatile=*/false, IncomingBlock->getTerminator());
1227
1228 U.set(Load);
1229 } else {
1230 // Reload right before the old use.
1231 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1232 /*Volatile=*/false, UsingInst);
1233 U.set(Load);
1234 }
1235}
Reid Klecknerc1814432015-09-28 23:56:30 +00001236
David Majnemer8cec2f22015-12-12 05:38:55 +00001237void WinEHFuncInfo::addIPToStateRange(const InvokeInst *II,
Reid Klecknerc1814432015-09-28 23:56:30 +00001238 MCSymbol *InvokeBegin,
1239 MCSymbol *InvokeEnd) {
David Majnemer8cec2f22015-12-12 05:38:55 +00001240 assert(InvokeStateMap.count(II) &&
1241 "should get invoke with precomputed state");
1242 LabelToStateMap[InvokeBegin] = std::make_pair(InvokeStateMap[II], InvokeEnd);
Reid Klecknerc1814432015-09-28 23:56:30 +00001243}
Chandler Carruthf79435e2015-12-29 09:24:39 +00001244
1245WinEHFuncInfo::WinEHFuncInfo() {}