blob: cfd230997ed0c0c1373eb2d69aa94fb6652502ef [file] [log] [blame]
John McCalled1ae862011-01-28 11:13:47 +00001//===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
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 file contains code dealing with the IR generation for cleanups
11// and related information.
12//
13// A "cleanup" is a piece of code which needs to be executed whenever
14// control transfers out of a particular scope. This can be
15// conditionalized to occur only on exceptional control flow, only on
16// normal control flow, or both.
17//
18//===----------------------------------------------------------------------===//
19
John McCalled1ae862011-01-28 11:13:47 +000020#include "CGCleanup.h"
Reid Kleckner2da7fcd2013-06-09 16:56:53 +000021#include "CodeGenFunction.h"
Reid Klecknera002bd52015-10-28 23:06:42 +000022#include "llvm/Support/SaveAndRestore.h"
John McCalled1ae862011-01-28 11:13:47 +000023
24using namespace clang;
25using namespace CodeGen;
26
27bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
28 if (rv.isScalar())
29 return DominatingLLVMValue::needsSaving(rv.getScalarVal());
30 if (rv.isAggregate())
John McCall7f416cc2015-09-08 08:05:57 +000031 return DominatingLLVMValue::needsSaving(rv.getAggregatePointer());
John McCalled1ae862011-01-28 11:13:47 +000032 return true;
33}
34
35DominatingValue<RValue>::saved_type
36DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
37 if (rv.isScalar()) {
38 llvm::Value *V = rv.getScalarVal();
39
40 // These automatically dominate and don't need to be saved.
41 if (!DominatingLLVMValue::needsSaving(V))
42 return saved_type(V, ScalarLiteral);
43
44 // Everything else needs an alloca.
John McCall7f416cc2015-09-08 08:05:57 +000045 Address addr =
46 CGF.CreateDefaultAlignTempAlloca(V->getType(), "saved-rvalue");
John McCalled1ae862011-01-28 11:13:47 +000047 CGF.Builder.CreateStore(V, addr);
John McCall7f416cc2015-09-08 08:05:57 +000048 return saved_type(addr.getPointer(), ScalarAddress);
John McCalled1ae862011-01-28 11:13:47 +000049 }
50
51 if (rv.isComplex()) {
52 CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::Type *ComplexTy =
Serge Guelton1d993272017-05-09 19:31:30 +000054 llvm::StructType::get(V.first->getType(), V.second->getType());
John McCall7f416cc2015-09-08 08:05:57 +000055 Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex");
David Blaikie1ed728c2015-04-05 22:45:47 +000056 CGF.Builder.CreateStore(V.first,
John McCall7f416cc2015-09-08 08:05:57 +000057 CGF.Builder.CreateStructGEP(addr, 0, CharUnits()));
58 CharUnits offset = CharUnits::fromQuantity(
59 CGF.CGM.getDataLayout().getTypeAllocSize(V.first->getType()));
David Blaikie1ed728c2015-04-05 22:45:47 +000060 CGF.Builder.CreateStore(V.second,
John McCall7f416cc2015-09-08 08:05:57 +000061 CGF.Builder.CreateStructGEP(addr, 1, offset));
62 return saved_type(addr.getPointer(), ComplexAddress);
John McCalled1ae862011-01-28 11:13:47 +000063 }
64
65 assert(rv.isAggregate());
John McCall7f416cc2015-09-08 08:05:57 +000066 Address V = rv.getAggregateAddress(); // TODO: volatile?
67 if (!DominatingLLVMValue::needsSaving(V.getPointer()))
68 return saved_type(V.getPointer(), AggregateLiteral,
69 V.getAlignment().getQuantity());
John McCalled1ae862011-01-28 11:13:47 +000070
John McCall7f416cc2015-09-08 08:05:57 +000071 Address addr =
72 CGF.CreateTempAlloca(V.getType(), CGF.getPointerAlign(), "saved-rvalue");
73 CGF.Builder.CreateStore(V.getPointer(), addr);
74 return saved_type(addr.getPointer(), AggregateAddress,
75 V.getAlignment().getQuantity());
John McCalled1ae862011-01-28 11:13:47 +000076}
77
78/// Given a saved r-value produced by SaveRValue, perform the code
79/// necessary to restore it to usability at the current insertion
80/// point.
81RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +000082 auto getSavingAddress = [&](llvm::Value *value) {
83 auto alignment = cast<llvm::AllocaInst>(value)->getAlignment();
84 return Address(value, CharUnits::fromQuantity(alignment));
85 };
John McCalled1ae862011-01-28 11:13:47 +000086 switch (K) {
87 case ScalarLiteral:
88 return RValue::get(Value);
89 case ScalarAddress:
John McCall7f416cc2015-09-08 08:05:57 +000090 return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
John McCalled1ae862011-01-28 11:13:47 +000091 case AggregateLiteral:
John McCall7f416cc2015-09-08 08:05:57 +000092 return RValue::getAggregate(Address(Value, CharUnits::fromQuantity(Align)));
93 case AggregateAddress: {
94 auto addr = CGF.Builder.CreateLoad(getSavingAddress(Value));
95 return RValue::getAggregate(Address(addr, CharUnits::fromQuantity(Align)));
96 }
John McCall47fb9502013-03-07 21:37:08 +000097 case ComplexAddress: {
John McCall7f416cc2015-09-08 08:05:57 +000098 Address address = getSavingAddress(Value);
99 llvm::Value *real = CGF.Builder.CreateLoad(
100 CGF.Builder.CreateStructGEP(address, 0, CharUnits()));
101 CharUnits offset = CharUnits::fromQuantity(
102 CGF.CGM.getDataLayout().getTypeAllocSize(real->getType()));
103 llvm::Value *imag = CGF.Builder.CreateLoad(
104 CGF.Builder.CreateStructGEP(address, 1, offset));
John McCall47fb9502013-03-07 21:37:08 +0000105 return RValue::getComplex(real, imag);
106 }
John McCalled1ae862011-01-28 11:13:47 +0000107 }
108
109 llvm_unreachable("bad saved r-value kind");
John McCalled1ae862011-01-28 11:13:47 +0000110}
111
112/// Push an entry of the given size onto this protected-scope stack.
113char *EHScopeStack::allocate(size_t Size) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000114 Size = llvm::alignTo(Size, ScopeStackAlignment);
John McCalled1ae862011-01-28 11:13:47 +0000115 if (!StartOfBuffer) {
116 unsigned Capacity = 1024;
117 while (Capacity < Size) Capacity *= 2;
118 StartOfBuffer = new char[Capacity];
119 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
120 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
121 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
122 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
123
124 unsigned NewCapacity = CurrentCapacity;
125 do {
126 NewCapacity *= 2;
127 } while (NewCapacity < UsedCapacity + Size);
128
129 char *NewStartOfBuffer = new char[NewCapacity];
130 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
131 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
132 memcpy(NewStartOfData, StartOfData, UsedCapacity);
133 delete [] StartOfBuffer;
134 StartOfBuffer = NewStartOfBuffer;
135 EndOfBuffer = NewEndOfBuffer;
136 StartOfData = NewStartOfData;
137 }
138
139 assert(StartOfBuffer + Size <= StartOfData);
140 StartOfData -= Size;
141 return StartOfData;
142}
143
James Y Knight53c76162015-07-17 18:21:37 +0000144void EHScopeStack::deallocate(size_t Size) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000145 StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
James Y Knight53c76162015-07-17 18:21:37 +0000146}
147
David Majnemerdc012fa2015-04-22 21:38:15 +0000148bool EHScopeStack::containsOnlyLifetimeMarkers(
149 EHScopeStack::stable_iterator Old) const {
150 for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {
151 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
152 if (!cleanup || !cleanup->isLifetimeMarker())
153 return false;
154 }
155
156 return true;
157}
158
Akira Hatanaka8af7bb22016-04-01 22:58:55 +0000159bool EHScopeStack::requiresLandingPad() const {
160 for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {
161 // Skip lifetime markers.
162 if (auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si)))
163 if (cleanup->isLifetimeMarker()) {
164 si = cleanup->getEnclosingEHScope();
165 continue;
166 }
167 return true;
168 }
169
170 return false;
171}
172
John McCalled1ae862011-01-28 11:13:47 +0000173EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +0000174EHScopeStack::getInnermostActiveNormalCleanup() const {
175 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
176 si != se; ) {
177 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
178 if (cleanup.isActive()) return si;
179 si = cleanup.getEnclosingNormalCleanup();
180 }
181 return stable_end();
182}
183
John McCalled1ae862011-01-28 11:13:47 +0000184
185void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCalled1ae862011-01-28 11:13:47 +0000186 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
187 bool IsNormalCleanup = Kind & NormalCleanup;
188 bool IsEHCleanup = Kind & EHCleanup;
189 bool IsActive = !(Kind & InactiveCleanup);
Tim Shen421119f2016-07-01 21:08:47 +0000190 bool IsLifetimeMarker = Kind & LifetimeMarker;
John McCalled1ae862011-01-28 11:13:47 +0000191 EHCleanupScope *Scope =
192 new (Buffer) EHCleanupScope(IsNormalCleanup,
193 IsEHCleanup,
194 IsActive,
195 Size,
196 BranchFixups.size(),
197 InnermostNormalCleanup,
John McCall8e4c74b2011-08-11 02:22:43 +0000198 InnermostEHScope);
John McCalled1ae862011-01-28 11:13:47 +0000199 if (IsNormalCleanup)
200 InnermostNormalCleanup = stable_begin();
201 if (IsEHCleanup)
John McCall8e4c74b2011-08-11 02:22:43 +0000202 InnermostEHScope = stable_begin();
Tim Shen421119f2016-07-01 21:08:47 +0000203 if (IsLifetimeMarker)
204 Scope->setLifetimeMarker();
John McCalled1ae862011-01-28 11:13:47 +0000205
206 return Scope->getCleanupBuffer();
207}
208
209void EHScopeStack::popCleanup() {
210 assert(!empty() && "popping exception stack when not empty");
211
212 assert(isa<EHCleanupScope>(*begin()));
213 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
214 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
John McCall8e4c74b2011-08-11 02:22:43 +0000215 InnermostEHScope = Cleanup.getEnclosingEHScope();
James Y Knight53c76162015-07-17 18:21:37 +0000216 deallocate(Cleanup.getAllocatedSize());
John McCalled1ae862011-01-28 11:13:47 +0000217
John McCalled1ae862011-01-28 11:13:47 +0000218 // Destroy the cleanup.
Kostya Serebryanyb21aa762014-10-08 18:31:54 +0000219 Cleanup.Destroy();
John McCalled1ae862011-01-28 11:13:47 +0000220
221 // Check whether we can shrink the branch-fixups stack.
222 if (!BranchFixups.empty()) {
223 // If we no longer have any normal cleanups, all the fixups are
224 // complete.
225 if (!hasNormalCleanups())
226 BranchFixups.clear();
227
228 // Otherwise we can still trim out unnecessary nulls.
229 else
230 popNullFixups();
231 }
232}
233
John McCall8e4c74b2011-08-11 02:22:43 +0000234EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
235 assert(getInnermostEHScope() == stable_end());
236 char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
237 EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
238 InnermostEHScope = stable_begin();
239 return filter;
John McCalled1ae862011-01-28 11:13:47 +0000240}
241
242void EHScopeStack::popFilter() {
243 assert(!empty() && "popping exception stack when not empty");
244
John McCall8e4c74b2011-08-11 02:22:43 +0000245 EHFilterScope &filter = cast<EHFilterScope>(*begin());
James Y Knight53c76162015-07-17 18:21:37 +0000246 deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
John McCalled1ae862011-01-28 11:13:47 +0000247
John McCall8e4c74b2011-08-11 02:22:43 +0000248 InnermostEHScope = filter.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000249}
250
John McCall8e4c74b2011-08-11 02:22:43 +0000251EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
252 char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
253 EHCatchScope *scope =
254 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
255 InnermostEHScope = stable_begin();
256 return scope;
John McCalled1ae862011-01-28 11:13:47 +0000257}
258
259void EHScopeStack::pushTerminate() {
260 char *Buffer = allocate(EHTerminateScope::getSize());
John McCall8e4c74b2011-08-11 02:22:43 +0000261 new (Buffer) EHTerminateScope(InnermostEHScope);
262 InnermostEHScope = stable_begin();
John McCalled1ae862011-01-28 11:13:47 +0000263}
264
265/// Remove any 'null' fixups on the stack. However, we can't pop more
266/// fixups than the fixup depth on the innermost normal cleanup, or
267/// else fixups that we try to add to that cleanup will end up in the
268/// wrong place. We *could* try to shrink fixup depths, but that's
269/// actually a lot of work for little benefit.
270void EHScopeStack::popNullFixups() {
271 // We expect this to only be called when there's still an innermost
272 // normal cleanup; otherwise there really shouldn't be any fixups.
273 assert(hasNormalCleanups());
274
275 EHScopeStack::iterator it = find(InnermostNormalCleanup);
276 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
277 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
278
279 while (BranchFixups.size() > MinSize &&
Craig Topper8a13c412014-05-21 05:09:00 +0000280 BranchFixups.back().Destination == nullptr)
John McCalled1ae862011-01-28 11:13:47 +0000281 BranchFixups.pop_back();
282}
283
Richard Smithf66e4f72018-07-23 22:56:45 +0000284Address CodeGenFunction::createCleanupActiveFlag() {
John McCalled1ae862011-01-28 11:13:47 +0000285 // Create a variable to decide whether the cleanup needs to be run.
Yaxun Liucbd80f42018-06-16 01:20:52 +0000286 Address active = CreateTempAllocaWithoutCast(
287 Builder.getInt1Ty(), CharUnits::One(), "cleanup.cond");
John McCalled1ae862011-01-28 11:13:47 +0000288
289 // Initialize it to false at a site that's guaranteed to be run
290 // before each evaluation.
John McCallf4beacd2011-11-10 10:43:54 +0000291 setBeforeOutermostConditional(Builder.getFalse(), active);
John McCalled1ae862011-01-28 11:13:47 +0000292
293 // Initialize it to true at the current location.
294 Builder.CreateStore(Builder.getTrue(), active);
295
Richard Smithf66e4f72018-07-23 22:56:45 +0000296 return active;
297}
298
299void CodeGenFunction::initFullExprCleanupWithFlag(Address ActiveFlag) {
John McCalled1ae862011-01-28 11:13:47 +0000300 // Set that as the active flag in the cleanup.
301 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
John McCall7f416cc2015-09-08 08:05:57 +0000302 assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
Richard Smithf66e4f72018-07-23 22:56:45 +0000303 cleanup.setActiveFlag(ActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000304
305 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
306 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
307}
308
John McCall5fcf8da2011-07-12 00:15:30 +0000309void EHScopeStack::Cleanup::anchor() {}
John McCalled1ae862011-01-28 11:13:47 +0000310
John McCall7f416cc2015-09-08 08:05:57 +0000311static void createStoreInstBefore(llvm::Value *value, Address addr,
312 llvm::Instruction *beforeInst) {
313 auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
314 store->setAlignment(addr.getAlignment().getQuantity());
315}
316
317static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
318 llvm::Instruction *beforeInst) {
319 auto load = new llvm::LoadInst(addr.getPointer(), name, beforeInst);
320 load->setAlignment(addr.getAlignment().getQuantity());
321 return load;
322}
323
John McCalled1ae862011-01-28 11:13:47 +0000324/// All the branch fixups on the EH stack have propagated out past the
325/// outermost normal cleanup; resolve them all by adding cases to the
326/// given switch instruction.
327static void ResolveAllBranchFixups(CodeGenFunction &CGF,
328 llvm::SwitchInst *Switch,
329 llvm::BasicBlock *CleanupEntry) {
330 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
331
332 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
333 // Skip this fixup if its destination isn't set.
334 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
Craig Topper8a13c412014-05-21 05:09:00 +0000335 if (Fixup.Destination == nullptr) continue;
John McCalled1ae862011-01-28 11:13:47 +0000336
337 // If there isn't an OptimisticBranchBlock, then InitialBranch is
338 // still pointing directly to its destination; forward it to the
339 // appropriate cleanup entry. This is required in the specific
340 // case of
341 // { std::string s; goto lbl; }
342 // lbl:
343 // i.e. where there's an unresolved fixup inside a single cleanup
344 // entry which we're currently popping.
Craig Topper8a13c412014-05-21 05:09:00 +0000345 if (Fixup.OptimisticBranchBlock == nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +0000346 createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
347 CGF.getNormalCleanupDestSlot(),
348 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000349 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
350 }
351
352 // Don't add this case to the switch statement twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000353 if (!CasesAdded.insert(Fixup.Destination).second)
354 continue;
John McCalled1ae862011-01-28 11:13:47 +0000355
356 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
357 Fixup.Destination);
358 }
359
360 CGF.EHStack.clearFixups();
361}
362
363/// Transitions the terminator of the given exit-block of a cleanup to
364/// be a cleanup switch.
365static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
366 llvm::BasicBlock *Block) {
367 // If it's a branch, turn it into a switch whose default
368 // destination is its original target.
369 llvm::TerminatorInst *Term = Block->getTerminator();
370 assert(Term && "can't transition block without terminator");
371
372 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
373 assert(Br->isUnconditional());
John McCall7f416cc2015-09-08 08:05:57 +0000374 auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
375 "cleanup.dest", Term);
John McCalled1ae862011-01-28 11:13:47 +0000376 llvm::SwitchInst *Switch =
377 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
378 Br->eraseFromParent();
379 return Switch;
380 } else {
381 return cast<llvm::SwitchInst>(Term);
382 }
383}
384
385void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
386 assert(Block && "resolving a null target block");
387 if (!EHStack.getNumBranchFixups()) return;
388
389 assert(EHStack.hasNormalCleanups() &&
390 "branch fixups exist with no normal cleanups on stack");
391
392 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
393 bool ResolvedAny = false;
394
395 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
396 // Skip this fixup if its destination doesn't match.
397 BranchFixup &Fixup = EHStack.getBranchFixup(I);
398 if (Fixup.Destination != Block) continue;
399
Craig Topper8a13c412014-05-21 05:09:00 +0000400 Fixup.Destination = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000401 ResolvedAny = true;
402
403 // If it doesn't have an optimistic branch block, LatestBranch is
404 // already pointing to the right place.
405 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
406 if (!BranchBB)
407 continue;
408
409 // Don't process the same optimistic branch block twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000410 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
John McCalled1ae862011-01-28 11:13:47 +0000411 continue;
412
413 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
414
415 // Add a case to the switch.
416 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
417 }
418
419 if (ResolvedAny)
420 EHStack.popNullFixups();
421}
422
423/// Pops cleanup blocks until the given savepoint is reached.
Reid Kleckner092d0652017-03-06 22:18:34 +0000424void CodeGenFunction::PopCleanupBlocks(
425 EHScopeStack::stable_iterator Old,
426 std::initializer_list<llvm::Value **> ValuesToReload) {
John McCalled1ae862011-01-28 11:13:47 +0000427 assert(Old.isValid());
428
Reid Kleckner092d0652017-03-06 22:18:34 +0000429 bool HadBranches = false;
John McCalled1ae862011-01-28 11:13:47 +0000430 while (EHStack.stable_begin() != Old) {
431 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
Reid Kleckner092d0652017-03-06 22:18:34 +0000432 HadBranches |= Scope.hasBranches();
John McCalled1ae862011-01-28 11:13:47 +0000433
434 // As long as Old strictly encloses the scope's enclosing normal
435 // cleanup, we're going to emit another normal cleanup which
436 // fallthrough can propagate through.
437 bool FallThroughIsBranchThrough =
438 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
439
Adrian Prantldc237b52013-05-16 00:41:26 +0000440 PopCleanupBlock(FallThroughIsBranchThrough);
John McCalled1ae862011-01-28 11:13:47 +0000441 }
Reid Kleckner092d0652017-03-06 22:18:34 +0000442
443 // If we didn't have any branches, the insertion point before cleanups must
444 // dominate the current insertion point and we don't need to reload any
445 // values.
446 if (!HadBranches)
447 return;
448
449 // Spill and reload all values that the caller wants to be live at the current
450 // insertion point.
451 for (llvm::Value **ReloadedValue : ValuesToReload) {
452 auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
453 if (!Inst)
454 continue;
Reid Kleckner04493162017-05-31 19:59:41 +0000455
456 // Don't spill static allocas, they dominate all cleanups. These are created
457 // by binding a reference to a local variable or temporary.
458 auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
459 if (AI && AI->isStaticAlloca())
460 continue;
461
Reid Kleckner092d0652017-03-06 22:18:34 +0000462 Address Tmp =
463 CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
464
465 // Find an insertion point after Inst and spill it to the temporary.
466 llvm::BasicBlock::iterator InsertBefore;
467 if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
468 InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
469 else
470 InsertBefore = std::next(Inst->getIterator());
471 CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
472
473 // Reload the value at the current insertion point.
474 *ReloadedValue = Builder.CreateLoad(Tmp);
475 }
John McCalled1ae862011-01-28 11:13:47 +0000476}
477
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000478/// Pops cleanup blocks until the given savepoint is reached, then add the
479/// cleanups from the given savepoint in the lifetime-extended cleanups stack.
Reid Kleckner092d0652017-03-06 22:18:34 +0000480void CodeGenFunction::PopCleanupBlocks(
481 EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
482 std::initializer_list<llvm::Value **> ValuesToReload) {
483 PopCleanupBlocks(Old, ValuesToReload);
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000484
485 // Move our deferred cleanups onto the EH stack.
Richard Smith736a9472013-06-12 20:42:33 +0000486 for (size_t I = OldLifetimeExtendedSize,
487 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
488 // Alignment should be guaranteed by the vptrs in the individual cleanups.
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000489 assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
Richard Smith736a9472013-06-12 20:42:33 +0000490 "misaligned cleanup stack entry");
491
492 LifetimeExtendedCleanupHeader &Header =
493 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
494 LifetimeExtendedCleanupStack[I]);
495 I += sizeof(Header);
496
497 EHStack.pushCopyOfCleanup(Header.getKind(),
498 &LifetimeExtendedCleanupStack[I],
499 Header.getSize());
500 I += Header.getSize();
Richard Smithf66e4f72018-07-23 22:56:45 +0000501
502 if (Header.isConditional()) {
503 Address ActiveFlag =
504 reinterpret_cast<Address &>(LifetimeExtendedCleanupStack[I]);
505 initFullExprCleanupWithFlag(ActiveFlag);
506 I += sizeof(ActiveFlag);
507 }
Richard Smith736a9472013-06-12 20:42:33 +0000508 }
509 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
510}
511
John McCalled1ae862011-01-28 11:13:47 +0000512static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
513 EHCleanupScope &Scope) {
514 assert(Scope.isNormalCleanup());
515 llvm::BasicBlock *Entry = Scope.getNormalBlock();
516 if (!Entry) {
517 Entry = CGF.createBasicBlock("cleanup");
518 Scope.setNormalBlock(Entry);
519 }
520 return Entry;
521}
522
John McCalled1ae862011-01-28 11:13:47 +0000523/// Attempts to reduce a cleanup's entry block to a fallthrough. This
524/// is basically llvm::MergeBlockIntoPredecessor, except
525/// simplified/optimized for the tighter constraints on cleanup blocks.
526///
527/// Returns the new block, whatever it is.
528static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
529 llvm::BasicBlock *Entry) {
530 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
531 if (!Pred) return Entry;
532
533 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
534 if (!Br || Br->isConditional()) return Entry;
535 assert(Br->getSuccessor(0) == Entry);
536
537 // If we were previously inserting at the end of the cleanup entry
538 // block, we'll need to continue inserting at the end of the
539 // predecessor.
540 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
541 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
542
543 // Kill the branch.
544 Br->eraseFromParent();
545
John McCalled1ae862011-01-28 11:13:47 +0000546 // Replace all uses of the entry with the predecessor, in case there
547 // are phis in the cleanup.
548 Entry->replaceAllUsesWith(Pred);
549
Jay Foade03c05c2011-06-20 14:38:01 +0000550 // Merge the blocks.
551 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
552
John McCalled1ae862011-01-28 11:13:47 +0000553 // Kill the entry block.
554 Entry->eraseFromParent();
555
556 if (WasInsertBlock)
557 CGF.Builder.SetInsertPoint(Pred);
558
559 return Pred;
560}
561
562static void EmitCleanup(CodeGenFunction &CGF,
563 EHScopeStack::Cleanup *Fn,
John McCall30317fd2011-07-12 20:27:29 +0000564 EHScopeStack::Cleanup::Flags flags,
John McCall7f416cc2015-09-08 08:05:57 +0000565 Address ActiveFlag) {
John McCalled1ae862011-01-28 11:13:47 +0000566 // If there's an active flag, load it and skip the cleanup if it's
567 // false.
Craig Topper8a13c412014-05-21 05:09:00 +0000568 llvm::BasicBlock *ContBB = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000569 if (ActiveFlag.isValid()) {
John McCalled1ae862011-01-28 11:13:47 +0000570 ContBB = CGF.createBasicBlock("cleanup.done");
571 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
572 llvm::Value *IsActive
573 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
574 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
575 CGF.EmitBlock(CleanupBB);
576 }
577
578 // Ask the cleanup to emit itself.
John McCall30317fd2011-07-12 20:27:29 +0000579 Fn->Emit(CGF, flags);
John McCalled1ae862011-01-28 11:13:47 +0000580 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
581
582 // Emit the continuation block if there was an active flag.
John McCall7f416cc2015-09-08 08:05:57 +0000583 if (ActiveFlag.isValid())
John McCalled1ae862011-01-28 11:13:47 +0000584 CGF.EmitBlock(ContBB);
John McCalled1ae862011-01-28 11:13:47 +0000585}
586
587static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
588 llvm::BasicBlock *From,
589 llvm::BasicBlock *To) {
590 // Exit is the exit block of a cleanup, so it always terminates in
591 // an unconditional branch or a switch.
592 llvm::TerminatorInst *Term = Exit->getTerminator();
593
594 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
595 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
596 Br->setSuccessor(0, To);
597 } else {
598 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
599 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
600 if (Switch->getSuccessor(I) == From)
601 Switch->setSuccessor(I, To);
602 }
603}
604
John McCallf82bdf62011-08-06 06:53:52 +0000605/// We don't need a normal entry block for the given cleanup.
606/// Optimistic fixup branches can cause these blocks to come into
607/// existence anyway; if so, destroy it.
608///
609/// The validity of this transformation is very much specific to the
610/// exact ways in which we form branches to cleanup entries.
611static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
612 EHCleanupScope &scope) {
613 llvm::BasicBlock *entry = scope.getNormalBlock();
614 if (!entry) return;
615
616 // Replace all the uses with unreachable.
617 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
618 for (llvm::BasicBlock::use_iterator
619 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000620 llvm::Use &use = *i;
John McCallf82bdf62011-08-06 06:53:52 +0000621 ++i;
622
623 use.set(unreachableBB);
624
625 // The only uses should be fixup switches.
626 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
Stepan Dyatkovskiy5fecf5442012-02-01 07:50:21 +0000627 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
John McCallf82bdf62011-08-06 06:53:52 +0000628 // Replace the switch with a branch.
Chandler Carruth260161b2017-04-12 08:12:30 +0000629 llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
John McCallf82bdf62011-08-06 06:53:52 +0000630
631 // The switch operand is a load from the cleanup-dest alloca.
632 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
633
634 // Destroy the switch.
635 si->eraseFromParent();
636
637 // Destroy the load.
John McCall5cdf0382018-01-12 22:07:01 +0000638 assert(condition->getOperand(0) == CGF.NormalCleanupDest.getPointer());
John McCallf82bdf62011-08-06 06:53:52 +0000639 assert(condition->use_empty());
640 condition->eraseFromParent();
641 }
642 }
643
644 assert(entry->use_empty());
645 delete entry;
646}
647
John McCalled1ae862011-01-28 11:13:47 +0000648/// Pops a cleanup block. If the block includes a normal cleanup, the
649/// current insertion point is threaded through the cleanup, as are
650/// any branch fixups on the cleanup.
Adrian Prantldc237b52013-05-16 00:41:26 +0000651void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCalled1ae862011-01-28 11:13:47 +0000652 assert(!EHStack.empty() && "cleanup stack is empty!");
653 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
654 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
655 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
656
657 // Remember activation information.
658 bool IsActive = Scope.isActive();
John McCall7f416cc2015-09-08 08:05:57 +0000659 Address NormalActiveFlag =
660 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
661 : Address::invalid();
662 Address EHActiveFlag =
663 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
664 : Address::invalid();
John McCalled1ae862011-01-28 11:13:47 +0000665
666 // Check whether we need an EH cleanup. This is only true if we've
667 // generated a lazy EH cleanup block.
John McCall8e4c74b2011-08-11 02:22:43 +0000668 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000669 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
670 bool RequiresEHCleanup = (EHEntry != nullptr);
John McCall8e4c74b2011-08-11 02:22:43 +0000671 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000672
673 // Check the three conditions which might require a normal cleanup:
674
675 // - whether there are branch fix-ups through this cleanup
676 unsigned FixupDepth = Scope.getFixupDepth();
677 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
678
679 // - whether there are branch-throughs or branch-afters
680 bool HasExistingBranches = Scope.hasBranches();
681
682 // - whether there's a fallthrough
683 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000684 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
John McCalled1ae862011-01-28 11:13:47 +0000685
686 // Branch-through fall-throughs leave the insertion point set to the
687 // end of the last cleanup, which points to the current scope. The
688 // rest of IR gen doesn't need to worry about this; it only happens
689 // during the execution of PopCleanupBlocks().
690 bool HasPrebranchedFallthrough =
691 (FallthroughSource && FallthroughSource->getTerminator());
692
693 // If this is a normal cleanup, then having a prebranched
694 // fallthrough implies that the fallthrough source unconditionally
695 // jumps here.
696 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
697 (Scope.getNormalBlock() &&
698 FallthroughSource->getTerminator()->getSuccessor(0)
699 == Scope.getNormalBlock()));
700
701 bool RequiresNormalCleanup = false;
702 if (Scope.isNormalCleanup() &&
703 (HasFixups || HasExistingBranches || HasFallthrough)) {
704 RequiresNormalCleanup = true;
705 }
706
John McCall45e42952011-08-07 07:05:57 +0000707 // If we have a prebranched fallthrough into an inactive normal
708 // cleanup, rewrite it so that it leads to the appropriate place.
709 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
710 llvm::BasicBlock *prebranchDest;
711
712 // If the prebranch is semantically branching through the next
713 // cleanup, just forward it to the next block, leaving the
714 // insertion point in the prebranched block.
John McCalled1ae862011-01-28 11:13:47 +0000715 if (FallthroughIsBranchThrough) {
John McCall45e42952011-08-07 07:05:57 +0000716 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
717 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
John McCalled1ae862011-01-28 11:13:47 +0000718
John McCall45e42952011-08-07 07:05:57 +0000719 // Otherwise, we need to make a new block. If the normal cleanup
720 // isn't being used at all, we could actually reuse the normal
721 // entry block, but this is simpler, and it avoids conflicts with
722 // dead optimistic fixup branches.
John McCalled1ae862011-01-28 11:13:47 +0000723 } else {
John McCall45e42952011-08-07 07:05:57 +0000724 prebranchDest = createBasicBlock("forwarded-prebranch");
725 EmitBlock(prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000726 }
John McCall45e42952011-08-07 07:05:57 +0000727
728 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
729 assert(normalEntry && !normalEntry->use_empty());
730
731 ForwardPrebranchedFallthrough(FallthroughSource,
732 normalEntry, prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000733 }
734
735 // If we don't need the cleanup at all, we're done.
736 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000737 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000738 EHStack.popCleanup(); // safe because there are no fixups
739 assert(EHStack.getNumBranchFixups() == 0 ||
740 EHStack.hasNormalCleanups());
741 return;
742 }
743
James Y Knight54a3b262015-12-30 03:58:33 +0000744 // Copy the cleanup emission data out. This uses either a stack
745 // array or malloc'd memory, depending on the size, which is
746 // behavior that SmallVector would provide, if we could use it
747 // here. Unfortunately, if you ask for a SmallVector<char>, the
748 // alignment isn't sufficient.
Benjamin Kramer6c3e4ec2015-08-04 12:34:30 +0000749 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
James Y Knight54a3b262015-12-30 03:58:33 +0000750 llvm::AlignedCharArray<EHScopeStack::ScopeStackAlignment, 8 * sizeof(void *)> CleanupBufferStack;
751 std::unique_ptr<char[]> CleanupBufferHeap;
752 size_t CleanupSize = Scope.getCleanupSize();
753 EHScopeStack::Cleanup *Fn;
754
755 if (CleanupSize <= sizeof(CleanupBufferStack)) {
756 memcpy(CleanupBufferStack.buffer, CleanupSource, CleanupSize);
757 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack.buffer);
758 } else {
759 CleanupBufferHeap.reset(new char[CleanupSize]);
760 memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
761 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
762 }
John McCalled1ae862011-01-28 11:13:47 +0000763
John McCall8e4c74b2011-08-11 02:22:43 +0000764 EHScopeStack::Cleanup::Flags cleanupFlags;
765 if (Scope.isNormalCleanup())
766 cleanupFlags.setIsNormalCleanupKind();
767 if (Scope.isEHCleanup())
768 cleanupFlags.setIsEHCleanupKind();
John McCalled1ae862011-01-28 11:13:47 +0000769
770 if (!RequiresNormalCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000771 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000772 EHStack.popCleanup();
773 } else {
774 // If we have a fallthrough and no other need for the cleanup,
775 // emit it directly.
776 if (HasFallthrough && !HasPrebranchedFallthrough &&
777 !HasFixups && !HasExistingBranches) {
778
John McCallf82bdf62011-08-06 06:53:52 +0000779 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000780 EHStack.popCleanup();
781
John McCall30317fd2011-07-12 20:27:29 +0000782 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000783
784 // Otherwise, the best approach is to thread everything through
785 // the cleanup block and then try to clean up after ourselves.
786 } else {
787 // Force the entry block to exist.
788 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
789
790 // I. Set up the fallthrough edge in.
791
John McCalla3654e32011-08-10 04:11:11 +0000792 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
John McCall45e42952011-08-07 07:05:57 +0000793
John McCalled1ae862011-01-28 11:13:47 +0000794 // If there's a fallthrough, we need to store the cleanup
795 // destination index. For fall-throughs this is always zero.
796 if (HasFallthrough) {
797 if (!HasPrebranchedFallthrough)
798 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
799
John McCall45e42952011-08-07 07:05:57 +0000800 // Otherwise, save and clear the IP if we don't have fallthrough
801 // because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000802 } else if (FallthroughSource) {
803 assert(!IsActive && "source without fallthrough for active cleanup");
John McCall45e42952011-08-07 07:05:57 +0000804 savedInactiveFallthroughIP = Builder.saveAndClearIP();
John McCalled1ae862011-01-28 11:13:47 +0000805 }
806
807 // II. Emit the entry block. This implicitly branches to it if
808 // we have fallthrough. All the fixups and existing branches
809 // should already be branched to it.
810 EmitBlock(NormalEntry);
811
812 // III. Figure out where we're going and build the cleanup
813 // epilogue.
814
815 bool HasEnclosingCleanups =
816 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
817
818 // Compute the branch-through dest if we need it:
819 // - if there are branch-throughs threaded through the scope
820 // - if fall-through is a branch-through
821 // - if there are fixups that will be optimistically forwarded
822 // to the enclosing cleanup
Craig Topper8a13c412014-05-21 05:09:00 +0000823 llvm::BasicBlock *BranchThroughDest = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000824 if (Scope.hasBranchThroughs() ||
825 (FallthroughSource && FallthroughIsBranchThrough) ||
826 (HasFixups && HasEnclosingCleanups)) {
827 assert(HasEnclosingCleanups);
828 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
829 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
830 }
831
Craig Topper8a13c412014-05-21 05:09:00 +0000832 llvm::BasicBlock *FallthroughDest = nullptr;
Benjamin Kramerc7497452015-02-17 16:53:08 +0000833 SmallVector<llvm::Instruction*, 2> InstsToAppend;
John McCalled1ae862011-01-28 11:13:47 +0000834
835 // If there's exactly one branch-after and no other threads,
836 // we can route it without a switch.
837 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
838 Scope.getNumBranchAfters() == 1) {
839 assert(!BranchThroughDest || !IsActive);
840
David Majnemerdc012fa2015-04-22 21:38:15 +0000841 // Clean up the possibly dead store to the cleanup dest slot.
842 llvm::Instruction *NormalCleanupDestSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000843 cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
David Majnemerdc012fa2015-04-22 21:38:15 +0000844 if (NormalCleanupDestSlot->hasOneUse()) {
845 NormalCleanupDestSlot->user_back()->eraseFromParent();
846 NormalCleanupDestSlot->eraseFromParent();
John McCall5cdf0382018-01-12 22:07:01 +0000847 NormalCleanupDest = Address::invalid();
David Majnemerdc012fa2015-04-22 21:38:15 +0000848 }
849
John McCalled1ae862011-01-28 11:13:47 +0000850 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
851 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
852
853 // Build a switch-out if we need it:
854 // - if there are branch-afters threaded through the scope
855 // - if fall-through is a branch-after
856 // - if there are fixups that have nowhere left to go and
857 // so must be immediately resolved
858 } else if (Scope.getNumBranchAfters() ||
859 (HasFallthrough && !FallthroughIsBranchThrough) ||
860 (HasFixups && !HasEnclosingCleanups)) {
861
862 llvm::BasicBlock *Default =
863 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
864
865 // TODO: base this on the number of branch-afters and fixups
866 const unsigned SwitchCapacity = 10;
867
868 llvm::LoadInst *Load =
John McCall7f416cc2015-09-08 08:05:57 +0000869 createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
870 nullptr);
John McCalled1ae862011-01-28 11:13:47 +0000871 llvm::SwitchInst *Switch =
872 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
873
874 InstsToAppend.push_back(Load);
875 InstsToAppend.push_back(Switch);
876
877 // Branch-after fallthrough.
878 if (FallthroughSource && !FallthroughIsBranchThrough) {
879 FallthroughDest = createBasicBlock("cleanup.cont");
880 if (HasFallthrough)
881 Switch->addCase(Builder.getInt32(0), FallthroughDest);
882 }
883
884 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
885 Switch->addCase(Scope.getBranchAfterIndex(I),
886 Scope.getBranchAfterBlock(I));
887 }
888
889 // If there aren't any enclosing cleanups, we can resolve all
890 // the fixups now.
891 if (HasFixups && !HasEnclosingCleanups)
892 ResolveAllBranchFixups(*this, Switch, NormalEntry);
893 } else {
894 // We should always have a branch-through destination in this case.
895 assert(BranchThroughDest);
896 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
897 }
898
899 // IV. Pop the cleanup and emit it.
900 EHStack.popCleanup();
901 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
902
John McCall30317fd2011-07-12 20:27:29 +0000903 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000904
905 // Append the prepared cleanup prologue from above.
906 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
Benjamin Kramerc7497452015-02-17 16:53:08 +0000907 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
908 NormalExit->getInstList().push_back(InstsToAppend[I]);
John McCalled1ae862011-01-28 11:13:47 +0000909
910 // Optimistically hope that any fixups will continue falling through.
911 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
912 I < E; ++I) {
John McCallad7c5c12011-02-08 08:22:06 +0000913 BranchFixup &Fixup = EHStack.getBranchFixup(I);
John McCalled1ae862011-01-28 11:13:47 +0000914 if (!Fixup.Destination) continue;
915 if (!Fixup.OptimisticBranchBlock) {
John McCall7f416cc2015-09-08 08:05:57 +0000916 createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
917 getNormalCleanupDestSlot(),
918 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000919 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
920 }
921 Fixup.OptimisticBranchBlock = NormalExit;
922 }
923
924 // V. Set up the fallthrough edge out.
925
John McCall45e42952011-08-07 07:05:57 +0000926 // Case 1: a fallthrough source exists but doesn't branch to the
927 // cleanup because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000928 if (!HasFallthrough && FallthroughSource) {
John McCall45e42952011-08-07 07:05:57 +0000929 // Prebranched fallthrough was forwarded earlier.
930 // Non-prebranched fallthrough doesn't need to be forwarded.
931 // Either way, all we need to do is restore the IP we cleared before.
John McCalled1ae862011-01-28 11:13:47 +0000932 assert(!IsActive);
John McCall45e42952011-08-07 07:05:57 +0000933 Builder.restoreIP(savedInactiveFallthroughIP);
John McCalled1ae862011-01-28 11:13:47 +0000934
935 // Case 2: a fallthrough source exists and should branch to the
936 // cleanup, but we're not supposed to branch through to the next
937 // cleanup.
938 } else if (HasFallthrough && FallthroughDest) {
939 assert(!FallthroughIsBranchThrough);
940 EmitBlock(FallthroughDest);
941
942 // Case 3: a fallthrough source exists and should branch to the
943 // cleanup and then through to the next.
944 } else if (HasFallthrough) {
945 // Everything is already set up for this.
946
947 // Case 4: no fallthrough source exists.
948 } else {
949 Builder.ClearInsertionPoint();
950 }
951
952 // VI. Assorted cleaning.
953
954 // Check whether we can merge NormalEntry into a single predecessor.
955 // This might invalidate (non-IR) pointers to NormalEntry.
956 llvm::BasicBlock *NewNormalEntry =
957 SimplifyCleanupEntry(*this, NormalEntry);
958
959 // If it did invalidate those pointers, and NormalEntry was the same
960 // as NormalExit, go back and patch up the fixups.
961 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
962 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
963 I < E; ++I)
John McCallad7c5c12011-02-08 08:22:06 +0000964 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCalled1ae862011-01-28 11:13:47 +0000965 }
966 }
967
968 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
969
970 // Emit the EH cleanup if required.
971 if (RequiresEHCleanup) {
972 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
973
974 EmitBlock(EHEntry);
Reid Kleckner55391522015-10-08 21:14:56 +0000975
Reid Klecknera002bd52015-10-28 23:06:42 +0000976 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
977
978 // Push a terminate scope or cleanupendpad scope around the potentially
979 // throwing cleanups. For funclet EH personalities, the cleanupendpad models
980 // program termination when cleanups throw.
Reid Kleckner55391522015-10-08 21:14:56 +0000981 bool PushedTerminate = false;
David Majnemer4e52d6f2015-12-12 05:39:21 +0000982 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
983 CurrentFuncletPad);
Reid Klecknera002bd52015-10-28 23:06:42 +0000984 llvm::CleanupPadInst *CPI = nullptr;
Heejin Ahnc6479192018-05-31 22:18:13 +0000985
986 const EHPersonality &Personality = EHPersonality::get(*this);
987 if (Personality.usesFuncletPads()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000988 llvm::Value *ParentPad = CurrentFuncletPad;
989 if (!ParentPad)
990 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
991 CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
Reid Kleckner55391522015-10-08 21:14:56 +0000992 }
993
Heejin Ahnc6479192018-05-31 22:18:13 +0000994 // Non-MSVC personalities need to terminate when an EH cleanup throws.
995 if (!Personality.isMSVCPersonality()) {
996 EHStack.pushTerminate();
997 PushedTerminate = true;
998 }
999
Eli Friedmanabab7762012-08-02 00:10:24 +00001000 // We only actually emit the cleanup code if the cleanup is either
1001 // active or was used before it was deactivated.
John McCall7f416cc2015-09-08 08:05:57 +00001002 if (EHActiveFlag.isValid() || IsActive) {
Eli Friedmanabab7762012-08-02 00:10:24 +00001003 cleanupFlags.setIsForEHCleanup();
1004 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
1005 }
John McCalled1ae862011-01-28 11:13:47 +00001006
David Majnemere888a2f2015-08-15 03:21:08 +00001007 if (CPI)
Joseph Tremouletce536a52015-08-23 00:26:48 +00001008 Builder.CreateCleanupRet(CPI, NextAction);
David Majnemerdbf10452015-07-31 17:58:45 +00001009 else
1010 Builder.CreateBr(NextAction);
John McCalled1ae862011-01-28 11:13:47 +00001011
Reid Kleckner55391522015-10-08 21:14:56 +00001012 // Leave the terminate scope.
1013 if (PushedTerminate)
1014 EHStack.popTerminate();
1015
John McCalled1ae862011-01-28 11:13:47 +00001016 Builder.restoreIP(SavedIP);
1017
1018 SimplifyCleanupEntry(*this, EHEntry);
1019 }
1020}
1021
Justin Bognere25ffdf2014-01-21 00:35:11 +00001022/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1023/// specified destination obviously has no cleanups to run. 'false' is always
1024/// a conservatively correct answer for this method.
1025bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
1026 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1027 && "stale jump destination");
1028
1029 // Calculate the innermost active normal cleanup.
1030 EHScopeStack::stable_iterator TopCleanup =
1031 EHStack.getInnermostActiveNormalCleanup();
1032
1033 // If we're not in an active normal cleanup scope, or if the
1034 // destination scope is within the innermost active normal cleanup
1035 // scope, we don't need to worry about fixups.
1036 if (TopCleanup == EHStack.stable_end() ||
1037 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
1038 return true;
1039
1040 // Otherwise, we might need some cleanups.
1041 return false;
1042}
1043
1044
John McCalled1ae862011-01-28 11:13:47 +00001045/// Terminate the current block by emitting a branch which might leave
1046/// the current cleanup-protected scope. The target scope may not yet
1047/// be known, in which case this will require a fixup.
1048///
1049/// As a side-effect, this method clears the insertion point.
1050void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall1b93f1b2011-02-25 04:19:13 +00001051 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
John McCalled1ae862011-01-28 11:13:47 +00001052 && "stale jump destination");
1053
1054 if (!HaveInsertPoint())
1055 return;
1056
1057 // Create the branch.
1058 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1059
1060 // Calculate the innermost active normal cleanup.
1061 EHScopeStack::stable_iterator
1062 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1063
1064 // If we're not in an active normal cleanup scope, or if the
1065 // destination scope is within the innermost active normal cleanup
1066 // scope, we don't need to worry about fixups.
1067 if (TopCleanup == EHStack.stable_end() ||
1068 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
1069 Builder.ClearInsertionPoint();
1070 return;
1071 }
1072
1073 // If we can't resolve the destination cleanup scope, just add this
1074 // to the current cleanup scope as a branch fixup.
1075 if (!Dest.getScopeDepth().isValid()) {
1076 BranchFixup &Fixup = EHStack.addBranchFixup();
1077 Fixup.Destination = Dest.getBlock();
1078 Fixup.DestinationIndex = Dest.getDestIndex();
1079 Fixup.InitialBranch = BI;
Craig Topper8a13c412014-05-21 05:09:00 +00001080 Fixup.OptimisticBranchBlock = nullptr;
John McCalled1ae862011-01-28 11:13:47 +00001081
1082 Builder.ClearInsertionPoint();
1083 return;
1084 }
1085
1086 // Otherwise, thread through all the normal cleanups in scope.
1087
1088 // Store the index at the start.
1089 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
John McCall7f416cc2015-09-08 08:05:57 +00001090 createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
John McCalled1ae862011-01-28 11:13:47 +00001091
1092 // Adjust BI to point to the first cleanup block.
1093 {
1094 EHCleanupScope &Scope =
1095 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1096 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1097 }
1098
1099 // Add this destination to all the scopes involved.
1100 EHScopeStack::stable_iterator I = TopCleanup;
1101 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1102 if (E.strictlyEncloses(I)) {
1103 while (true) {
1104 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1105 assert(Scope.isNormalCleanup());
1106 I = Scope.getEnclosingNormalCleanup();
1107
1108 // If this is the last cleanup we're propagating through, tell it
1109 // that there's a resolved jump moving through it.
1110 if (!E.strictlyEncloses(I)) {
1111 Scope.addBranchAfter(Index, Dest.getBlock());
1112 break;
1113 }
1114
Nico Weber524ae442017-08-25 18:41:41 +00001115 // Otherwise, tell the scope that there's a jump propagating
John McCalled1ae862011-01-28 11:13:47 +00001116 // through it. If this isn't new information, all the rest of
1117 // the work has been done before.
1118 if (!Scope.addBranchThrough(Dest.getBlock()))
1119 break;
1120 }
1121 }
1122
1123 Builder.ClearInsertionPoint();
1124}
1125
John McCalled1ae862011-01-28 11:13:47 +00001126static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1127 EHScopeStack::stable_iterator C) {
1128 // If we needed a normal block for any reason, that counts.
1129 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1130 return true;
1131
1132 // Check whether any enclosed cleanups were needed.
1133 for (EHScopeStack::stable_iterator
1134 I = EHStack.getInnermostNormalCleanup();
1135 I != C; ) {
1136 assert(C.strictlyEncloses(I));
1137 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1138 if (S.getNormalBlock()) return true;
1139 I = S.getEnclosingNormalCleanup();
1140 }
1141
1142 return false;
1143}
1144
1145static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
John McCall8e4c74b2011-08-11 02:22:43 +00001146 EHScopeStack::stable_iterator cleanup) {
John McCalled1ae862011-01-28 11:13:47 +00001147 // If we needed an EH block for any reason, that counts.
John McCall8e4c74b2011-08-11 02:22:43 +00001148 if (EHStack.find(cleanup)->hasEHBranches())
John McCalled1ae862011-01-28 11:13:47 +00001149 return true;
1150
1151 // Check whether any enclosed cleanups were needed.
1152 for (EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +00001153 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1154 assert(cleanup.strictlyEncloses(i));
1155
1156 EHScope &scope = *EHStack.find(i);
1157 if (scope.hasEHBranches())
1158 return true;
1159
1160 i = scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +00001161 }
1162
1163 return false;
1164}
1165
1166enum ForActivation_t {
1167 ForActivation,
1168 ForDeactivation
1169};
1170
1171/// The given cleanup block is changing activation state. Configure a
1172/// cleanup variable if necessary.
1173///
1174/// It would be good if we had some way of determining if there were
1175/// extra uses *after* the change-over point.
1176static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1177 EHScopeStack::stable_iterator C,
John McCallf4beacd2011-11-10 10:43:54 +00001178 ForActivation_t kind,
1179 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001180 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1181
John McCalle63abb52011-11-10 09:22:44 +00001182 // We always need the flag if we're activating the cleanup in a
1183 // conditional context, because we have to assume that the current
1184 // location doesn't necessarily dominate the cleanup's code.
1185 bool isActivatedInConditional =
John McCallf4beacd2011-11-10 10:43:54 +00001186 (kind == ForActivation && CGF.isInConditionalBranch());
John McCalle63abb52011-11-10 09:22:44 +00001187
1188 bool needFlag = false;
John McCalled1ae862011-01-28 11:13:47 +00001189
1190 // Calculate whether the cleanup was used:
1191
1192 // - as a normal cleanup
John McCalle63abb52011-11-10 09:22:44 +00001193 if (Scope.isNormalCleanup() &&
1194 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001195 Scope.setTestFlagInNormalCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001196 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001197 }
1198
1199 // - as an EH cleanup
John McCalle63abb52011-11-10 09:22:44 +00001200 if (Scope.isEHCleanup() &&
1201 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001202 Scope.setTestFlagInEHCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001203 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001204 }
1205
1206 // If it hasn't yet been used as either, we're done.
John McCalle63abb52011-11-10 09:22:44 +00001207 if (!needFlag) return;
John McCalled1ae862011-01-28 11:13:47 +00001208
John McCall7f416cc2015-09-08 08:05:57 +00001209 Address var = Scope.getActiveFlag();
1210 if (!var.isValid()) {
1211 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1212 "cleanup.isactive");
John McCallf4beacd2011-11-10 10:43:54 +00001213 Scope.setActiveFlag(var);
1214
1215 assert(dominatingIP && "no existing variable and no dominating IP!");
John McCalled1ae862011-01-28 11:13:47 +00001216
1217 // Initialize to true or false depending on whether it was
1218 // active up to this point.
John McCall7f416cc2015-09-08 08:05:57 +00001219 llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
John McCallf4beacd2011-11-10 10:43:54 +00001220
1221 // If we're in a conditional block, ignore the dominating IP and
1222 // use the outermost conditional branch.
1223 if (CGF.isInConditionalBranch()) {
1224 CGF.setBeforeOutermostConditional(value, var);
1225 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001226 createStoreInstBefore(value, var, dominatingIP);
John McCallf4beacd2011-11-10 10:43:54 +00001227 }
John McCalled1ae862011-01-28 11:13:47 +00001228 }
1229
John McCallf4beacd2011-11-10 10:43:54 +00001230 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
John McCalled1ae862011-01-28 11:13:47 +00001231}
1232
1233/// Activate a cleanup that was created in an inactivated state.
John McCallf4beacd2011-11-10 10:43:54 +00001234void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1235 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001236 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1237 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1238 assert(!Scope.isActive() && "double activation");
1239
John McCallf4beacd2011-11-10 10:43:54 +00001240 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001241
1242 Scope.setActive(true);
1243}
1244
1245/// Deactive a cleanup that was created in an active state.
John McCallf4beacd2011-11-10 10:43:54 +00001246void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1247 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001248 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1249 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1250 assert(Scope.isActive() && "double deactivation");
1251
Akira Hatanakaccda3d22018-04-27 06:57:00 +00001252 // If it's the top of the stack, just pop it, but do so only if it belongs
1253 // to the current RunCleanupsScope.
1254 if (C == EHStack.stable_begin() &&
1255 CurrentCleanupScopeDepth.strictlyEncloses(C)) {
John McCalled1ae862011-01-28 11:13:47 +00001256 // If it's a normal cleanup, we need to pretend that the
1257 // fallthrough is unreachable.
1258 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1259 PopCleanupBlock();
1260 Builder.restoreIP(SavedIP);
1261 return;
1262 }
1263
1264 // Otherwise, follow the general case.
John McCallf4beacd2011-11-10 10:43:54 +00001265 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001266
1267 Scope.setActive(false);
1268}
1269
John McCall7f416cc2015-09-08 08:05:57 +00001270Address CodeGenFunction::getNormalCleanupDestSlot() {
John McCall5cdf0382018-01-12 22:07:01 +00001271 if (!NormalCleanupDest.isValid())
John McCalled1ae862011-01-28 11:13:47 +00001272 NormalCleanupDest =
John McCall5cdf0382018-01-12 22:07:01 +00001273 CreateDefaultAlignTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1274 return NormalCleanupDest;
John McCalled1ae862011-01-28 11:13:47 +00001275}
Peter Collingbourne702b2842011-11-27 22:09:22 +00001276
1277/// Emits all the code to cause the given temporary to be cleaned up.
1278void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1279 QualType TempType,
John McCall7f416cc2015-09-08 08:05:57 +00001280 Address Ptr) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001281 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
Peter Collingbourne702b2842011-11-27 22:09:22 +00001282 /*useEHCleanup*/ true);
1283}