blob: 2678b33f392ba1eb849b390c8f696f36f7346d67 [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 =
Chris Lattner845511f2011-06-18 22:49:11 +000054 llvm::StructType::get(V.first->getType(), V.second->getType(),
Craig Topper8a13c412014-05-21 05:09:00 +000055 (void*) nullptr);
John McCall7f416cc2015-09-08 08:05:57 +000056 Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex");
David Blaikie1ed728c2015-04-05 22:45:47 +000057 CGF.Builder.CreateStore(V.first,
John McCall7f416cc2015-09-08 08:05:57 +000058 CGF.Builder.CreateStructGEP(addr, 0, CharUnits()));
59 CharUnits offset = CharUnits::fromQuantity(
60 CGF.CGM.getDataLayout().getTypeAllocSize(V.first->getType()));
David Blaikie1ed728c2015-04-05 22:45:47 +000061 CGF.Builder.CreateStore(V.second,
John McCall7f416cc2015-09-08 08:05:57 +000062 CGF.Builder.CreateStructGEP(addr, 1, offset));
63 return saved_type(addr.getPointer(), ComplexAddress);
John McCalled1ae862011-01-28 11:13:47 +000064 }
65
66 assert(rv.isAggregate());
John McCall7f416cc2015-09-08 08:05:57 +000067 Address V = rv.getAggregateAddress(); // TODO: volatile?
68 if (!DominatingLLVMValue::needsSaving(V.getPointer()))
69 return saved_type(V.getPointer(), AggregateLiteral,
70 V.getAlignment().getQuantity());
John McCalled1ae862011-01-28 11:13:47 +000071
John McCall7f416cc2015-09-08 08:05:57 +000072 Address addr =
73 CGF.CreateTempAlloca(V.getType(), CGF.getPointerAlign(), "saved-rvalue");
74 CGF.Builder.CreateStore(V.getPointer(), addr);
75 return saved_type(addr.getPointer(), AggregateAddress,
76 V.getAlignment().getQuantity());
John McCalled1ae862011-01-28 11:13:47 +000077}
78
79/// Given a saved r-value produced by SaveRValue, perform the code
80/// necessary to restore it to usability at the current insertion
81/// point.
82RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +000083 auto getSavingAddress = [&](llvm::Value *value) {
84 auto alignment = cast<llvm::AllocaInst>(value)->getAlignment();
85 return Address(value, CharUnits::fromQuantity(alignment));
86 };
John McCalled1ae862011-01-28 11:13:47 +000087 switch (K) {
88 case ScalarLiteral:
89 return RValue::get(Value);
90 case ScalarAddress:
John McCall7f416cc2015-09-08 08:05:57 +000091 return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
John McCalled1ae862011-01-28 11:13:47 +000092 case AggregateLiteral:
John McCall7f416cc2015-09-08 08:05:57 +000093 return RValue::getAggregate(Address(Value, CharUnits::fromQuantity(Align)));
94 case AggregateAddress: {
95 auto addr = CGF.Builder.CreateLoad(getSavingAddress(Value));
96 return RValue::getAggregate(Address(addr, CharUnits::fromQuantity(Align)));
97 }
John McCall47fb9502013-03-07 21:37:08 +000098 case ComplexAddress: {
John McCall7f416cc2015-09-08 08:05:57 +000099 Address address = getSavingAddress(Value);
100 llvm::Value *real = CGF.Builder.CreateLoad(
101 CGF.Builder.CreateStructGEP(address, 0, CharUnits()));
102 CharUnits offset = CharUnits::fromQuantity(
103 CGF.CGM.getDataLayout().getTypeAllocSize(real->getType()));
104 llvm::Value *imag = CGF.Builder.CreateLoad(
105 CGF.Builder.CreateStructGEP(address, 1, offset));
John McCall47fb9502013-03-07 21:37:08 +0000106 return RValue::getComplex(real, imag);
107 }
John McCalled1ae862011-01-28 11:13:47 +0000108 }
109
110 llvm_unreachable("bad saved r-value kind");
John McCalled1ae862011-01-28 11:13:47 +0000111}
112
113/// Push an entry of the given size onto this protected-scope stack.
114char *EHScopeStack::allocate(size_t Size) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000115 Size = llvm::alignTo(Size, ScopeStackAlignment);
John McCalled1ae862011-01-28 11:13:47 +0000116 if (!StartOfBuffer) {
117 unsigned Capacity = 1024;
118 while (Capacity < Size) Capacity *= 2;
119 StartOfBuffer = new char[Capacity];
120 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
121 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
122 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
123 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
124
125 unsigned NewCapacity = CurrentCapacity;
126 do {
127 NewCapacity *= 2;
128 } while (NewCapacity < UsedCapacity + Size);
129
130 char *NewStartOfBuffer = new char[NewCapacity];
131 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
132 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
133 memcpy(NewStartOfData, StartOfData, UsedCapacity);
134 delete [] StartOfBuffer;
135 StartOfBuffer = NewStartOfBuffer;
136 EndOfBuffer = NewEndOfBuffer;
137 StartOfData = NewStartOfData;
138 }
139
140 assert(StartOfBuffer + Size <= StartOfData);
141 StartOfData -= Size;
142 return StartOfData;
143}
144
James Y Knight53c76162015-07-17 18:21:37 +0000145void EHScopeStack::deallocate(size_t Size) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000146 StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
James Y Knight53c76162015-07-17 18:21:37 +0000147}
148
David Majnemerdc012fa2015-04-22 21:38:15 +0000149bool EHScopeStack::containsOnlyLifetimeMarkers(
150 EHScopeStack::stable_iterator Old) const {
151 for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {
152 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
153 if (!cleanup || !cleanup->isLifetimeMarker())
154 return false;
155 }
156
157 return true;
158}
159
John McCalled1ae862011-01-28 11:13:47 +0000160EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +0000161EHScopeStack::getInnermostActiveNormalCleanup() const {
162 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
163 si != se; ) {
164 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
165 if (cleanup.isActive()) return si;
166 si = cleanup.getEnclosingNormalCleanup();
167 }
168 return stable_end();
169}
170
John McCalled1ae862011-01-28 11:13:47 +0000171
172void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCalled1ae862011-01-28 11:13:47 +0000173 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
174 bool IsNormalCleanup = Kind & NormalCleanup;
175 bool IsEHCleanup = Kind & EHCleanup;
176 bool IsActive = !(Kind & InactiveCleanup);
177 EHCleanupScope *Scope =
178 new (Buffer) EHCleanupScope(IsNormalCleanup,
179 IsEHCleanup,
180 IsActive,
181 Size,
182 BranchFixups.size(),
183 InnermostNormalCleanup,
John McCall8e4c74b2011-08-11 02:22:43 +0000184 InnermostEHScope);
John McCalled1ae862011-01-28 11:13:47 +0000185 if (IsNormalCleanup)
186 InnermostNormalCleanup = stable_begin();
187 if (IsEHCleanup)
John McCall8e4c74b2011-08-11 02:22:43 +0000188 InnermostEHScope = stable_begin();
John McCalled1ae862011-01-28 11:13:47 +0000189
190 return Scope->getCleanupBuffer();
191}
192
193void EHScopeStack::popCleanup() {
194 assert(!empty() && "popping exception stack when not empty");
195
196 assert(isa<EHCleanupScope>(*begin()));
197 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
198 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
John McCall8e4c74b2011-08-11 02:22:43 +0000199 InnermostEHScope = Cleanup.getEnclosingEHScope();
James Y Knight53c76162015-07-17 18:21:37 +0000200 deallocate(Cleanup.getAllocatedSize());
John McCalled1ae862011-01-28 11:13:47 +0000201
John McCalled1ae862011-01-28 11:13:47 +0000202 // Destroy the cleanup.
Kostya Serebryanyb21aa762014-10-08 18:31:54 +0000203 Cleanup.Destroy();
John McCalled1ae862011-01-28 11:13:47 +0000204
205 // Check whether we can shrink the branch-fixups stack.
206 if (!BranchFixups.empty()) {
207 // If we no longer have any normal cleanups, all the fixups are
208 // complete.
209 if (!hasNormalCleanups())
210 BranchFixups.clear();
211
212 // Otherwise we can still trim out unnecessary nulls.
213 else
214 popNullFixups();
215 }
216}
217
John McCall8e4c74b2011-08-11 02:22:43 +0000218EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
219 assert(getInnermostEHScope() == stable_end());
220 char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
221 EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
222 InnermostEHScope = stable_begin();
223 return filter;
John McCalled1ae862011-01-28 11:13:47 +0000224}
225
226void EHScopeStack::popFilter() {
227 assert(!empty() && "popping exception stack when not empty");
228
John McCall8e4c74b2011-08-11 02:22:43 +0000229 EHFilterScope &filter = cast<EHFilterScope>(*begin());
James Y Knight53c76162015-07-17 18:21:37 +0000230 deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
John McCalled1ae862011-01-28 11:13:47 +0000231
John McCall8e4c74b2011-08-11 02:22:43 +0000232 InnermostEHScope = filter.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000233}
234
John McCall8e4c74b2011-08-11 02:22:43 +0000235EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
236 char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
237 EHCatchScope *scope =
238 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
239 InnermostEHScope = stable_begin();
240 return scope;
John McCalled1ae862011-01-28 11:13:47 +0000241}
242
243void EHScopeStack::pushTerminate() {
244 char *Buffer = allocate(EHTerminateScope::getSize());
John McCall8e4c74b2011-08-11 02:22:43 +0000245 new (Buffer) EHTerminateScope(InnermostEHScope);
246 InnermostEHScope = stable_begin();
John McCalled1ae862011-01-28 11:13:47 +0000247}
248
249/// Remove any 'null' fixups on the stack. However, we can't pop more
250/// fixups than the fixup depth on the innermost normal cleanup, or
251/// else fixups that we try to add to that cleanup will end up in the
252/// wrong place. We *could* try to shrink fixup depths, but that's
253/// actually a lot of work for little benefit.
254void EHScopeStack::popNullFixups() {
255 // We expect this to only be called when there's still an innermost
256 // normal cleanup; otherwise there really shouldn't be any fixups.
257 assert(hasNormalCleanups());
258
259 EHScopeStack::iterator it = find(InnermostNormalCleanup);
260 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
261 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
262
263 while (BranchFixups.size() > MinSize &&
Craig Topper8a13c412014-05-21 05:09:00 +0000264 BranchFixups.back().Destination == nullptr)
John McCalled1ae862011-01-28 11:13:47 +0000265 BranchFixups.pop_back();
266}
267
268void CodeGenFunction::initFullExprCleanup() {
269 // Create a variable to decide whether the cleanup needs to be run.
John McCall7f416cc2015-09-08 08:05:57 +0000270 Address active = CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
271 "cleanup.cond");
John McCalled1ae862011-01-28 11:13:47 +0000272
273 // Initialize it to false at a site that's guaranteed to be run
274 // before each evaluation.
John McCallf4beacd2011-11-10 10:43:54 +0000275 setBeforeOutermostConditional(Builder.getFalse(), active);
John McCalled1ae862011-01-28 11:13:47 +0000276
277 // Initialize it to true at the current location.
278 Builder.CreateStore(Builder.getTrue(), active);
279
280 // Set that as the active flag in the cleanup.
281 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
John McCall7f416cc2015-09-08 08:05:57 +0000282 assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
John McCalled1ae862011-01-28 11:13:47 +0000283 cleanup.setActiveFlag(active);
284
285 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
286 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
287}
288
John McCall5fcf8da2011-07-12 00:15:30 +0000289void EHScopeStack::Cleanup::anchor() {}
John McCalled1ae862011-01-28 11:13:47 +0000290
John McCall7f416cc2015-09-08 08:05:57 +0000291static void createStoreInstBefore(llvm::Value *value, Address addr,
292 llvm::Instruction *beforeInst) {
293 auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
294 store->setAlignment(addr.getAlignment().getQuantity());
295}
296
297static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
298 llvm::Instruction *beforeInst) {
299 auto load = new llvm::LoadInst(addr.getPointer(), name, beforeInst);
300 load->setAlignment(addr.getAlignment().getQuantity());
301 return load;
302}
303
John McCalled1ae862011-01-28 11:13:47 +0000304/// All the branch fixups on the EH stack have propagated out past the
305/// outermost normal cleanup; resolve them all by adding cases to the
306/// given switch instruction.
307static void ResolveAllBranchFixups(CodeGenFunction &CGF,
308 llvm::SwitchInst *Switch,
309 llvm::BasicBlock *CleanupEntry) {
310 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
311
312 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
313 // Skip this fixup if its destination isn't set.
314 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
Craig Topper8a13c412014-05-21 05:09:00 +0000315 if (Fixup.Destination == nullptr) continue;
John McCalled1ae862011-01-28 11:13:47 +0000316
317 // If there isn't an OptimisticBranchBlock, then InitialBranch is
318 // still pointing directly to its destination; forward it to the
319 // appropriate cleanup entry. This is required in the specific
320 // case of
321 // { std::string s; goto lbl; }
322 // lbl:
323 // i.e. where there's an unresolved fixup inside a single cleanup
324 // entry which we're currently popping.
Craig Topper8a13c412014-05-21 05:09:00 +0000325 if (Fixup.OptimisticBranchBlock == nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +0000326 createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
327 CGF.getNormalCleanupDestSlot(),
328 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000329 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
330 }
331
332 // Don't add this case to the switch statement twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000333 if (!CasesAdded.insert(Fixup.Destination).second)
334 continue;
John McCalled1ae862011-01-28 11:13:47 +0000335
336 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
337 Fixup.Destination);
338 }
339
340 CGF.EHStack.clearFixups();
341}
342
343/// Transitions the terminator of the given exit-block of a cleanup to
344/// be a cleanup switch.
345static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
346 llvm::BasicBlock *Block) {
347 // If it's a branch, turn it into a switch whose default
348 // destination is its original target.
349 llvm::TerminatorInst *Term = Block->getTerminator();
350 assert(Term && "can't transition block without terminator");
351
352 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
353 assert(Br->isUnconditional());
John McCall7f416cc2015-09-08 08:05:57 +0000354 auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
355 "cleanup.dest", Term);
John McCalled1ae862011-01-28 11:13:47 +0000356 llvm::SwitchInst *Switch =
357 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
358 Br->eraseFromParent();
359 return Switch;
360 } else {
361 return cast<llvm::SwitchInst>(Term);
362 }
363}
364
365void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
366 assert(Block && "resolving a null target block");
367 if (!EHStack.getNumBranchFixups()) return;
368
369 assert(EHStack.hasNormalCleanups() &&
370 "branch fixups exist with no normal cleanups on stack");
371
372 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
373 bool ResolvedAny = false;
374
375 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
376 // Skip this fixup if its destination doesn't match.
377 BranchFixup &Fixup = EHStack.getBranchFixup(I);
378 if (Fixup.Destination != Block) continue;
379
Craig Topper8a13c412014-05-21 05:09:00 +0000380 Fixup.Destination = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000381 ResolvedAny = true;
382
383 // If it doesn't have an optimistic branch block, LatestBranch is
384 // already pointing to the right place.
385 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
386 if (!BranchBB)
387 continue;
388
389 // Don't process the same optimistic branch block twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000390 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
John McCalled1ae862011-01-28 11:13:47 +0000391 continue;
392
393 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
394
395 // Add a case to the switch.
396 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
397 }
398
399 if (ResolvedAny)
400 EHStack.popNullFixups();
401}
402
403/// Pops cleanup blocks until the given savepoint is reached.
Adrian Prantldc237b52013-05-16 00:41:26 +0000404void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
John McCalled1ae862011-01-28 11:13:47 +0000405 assert(Old.isValid());
406
407 while (EHStack.stable_begin() != Old) {
408 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
409
410 // As long as Old strictly encloses the scope's enclosing normal
411 // cleanup, we're going to emit another normal cleanup which
412 // fallthrough can propagate through.
413 bool FallThroughIsBranchThrough =
414 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
415
Adrian Prantldc237b52013-05-16 00:41:26 +0000416 PopCleanupBlock(FallThroughIsBranchThrough);
John McCalled1ae862011-01-28 11:13:47 +0000417 }
418}
419
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000420/// Pops cleanup blocks until the given savepoint is reached, then add the
421/// cleanups from the given savepoint in the lifetime-extended cleanups stack.
Richard Smith736a9472013-06-12 20:42:33 +0000422void
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000423CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old,
424 size_t OldLifetimeExtendedSize) {
425 PopCleanupBlocks(Old);
426
427 // Move our deferred cleanups onto the EH stack.
Richard Smith736a9472013-06-12 20:42:33 +0000428 for (size_t I = OldLifetimeExtendedSize,
429 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
430 // Alignment should be guaranteed by the vptrs in the individual cleanups.
431 assert((I % llvm::alignOf<LifetimeExtendedCleanupHeader>() == 0) &&
432 "misaligned cleanup stack entry");
433
434 LifetimeExtendedCleanupHeader &Header =
435 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
436 LifetimeExtendedCleanupStack[I]);
437 I += sizeof(Header);
438
439 EHStack.pushCopyOfCleanup(Header.getKind(),
440 &LifetimeExtendedCleanupStack[I],
441 Header.getSize());
442 I += Header.getSize();
443 }
444 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
445}
446
John McCalled1ae862011-01-28 11:13:47 +0000447static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
448 EHCleanupScope &Scope) {
449 assert(Scope.isNormalCleanup());
450 llvm::BasicBlock *Entry = Scope.getNormalBlock();
451 if (!Entry) {
452 Entry = CGF.createBasicBlock("cleanup");
453 Scope.setNormalBlock(Entry);
454 }
455 return Entry;
456}
457
John McCalled1ae862011-01-28 11:13:47 +0000458/// Attempts to reduce a cleanup's entry block to a fallthrough. This
459/// is basically llvm::MergeBlockIntoPredecessor, except
460/// simplified/optimized for the tighter constraints on cleanup blocks.
461///
462/// Returns the new block, whatever it is.
463static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
464 llvm::BasicBlock *Entry) {
465 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
466 if (!Pred) return Entry;
467
468 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
469 if (!Br || Br->isConditional()) return Entry;
470 assert(Br->getSuccessor(0) == Entry);
471
472 // If we were previously inserting at the end of the cleanup entry
473 // block, we'll need to continue inserting at the end of the
474 // predecessor.
475 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
476 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
477
478 // Kill the branch.
479 Br->eraseFromParent();
480
John McCalled1ae862011-01-28 11:13:47 +0000481 // Replace all uses of the entry with the predecessor, in case there
482 // are phis in the cleanup.
483 Entry->replaceAllUsesWith(Pred);
484
Jay Foade03c05c2011-06-20 14:38:01 +0000485 // Merge the blocks.
486 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
487
John McCalled1ae862011-01-28 11:13:47 +0000488 // Kill the entry block.
489 Entry->eraseFromParent();
490
491 if (WasInsertBlock)
492 CGF.Builder.SetInsertPoint(Pred);
493
494 return Pred;
495}
496
497static void EmitCleanup(CodeGenFunction &CGF,
498 EHScopeStack::Cleanup *Fn,
John McCall30317fd2011-07-12 20:27:29 +0000499 EHScopeStack::Cleanup::Flags flags,
John McCall7f416cc2015-09-08 08:05:57 +0000500 Address ActiveFlag) {
John McCalled1ae862011-01-28 11:13:47 +0000501 // If there's an active flag, load it and skip the cleanup if it's
502 // false.
Craig Topper8a13c412014-05-21 05:09:00 +0000503 llvm::BasicBlock *ContBB = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000504 if (ActiveFlag.isValid()) {
John McCalled1ae862011-01-28 11:13:47 +0000505 ContBB = CGF.createBasicBlock("cleanup.done");
506 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
507 llvm::Value *IsActive
508 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
509 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
510 CGF.EmitBlock(CleanupBB);
511 }
512
513 // Ask the cleanup to emit itself.
John McCall30317fd2011-07-12 20:27:29 +0000514 Fn->Emit(CGF, flags);
John McCalled1ae862011-01-28 11:13:47 +0000515 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
516
517 // Emit the continuation block if there was an active flag.
John McCall7f416cc2015-09-08 08:05:57 +0000518 if (ActiveFlag.isValid())
John McCalled1ae862011-01-28 11:13:47 +0000519 CGF.EmitBlock(ContBB);
John McCalled1ae862011-01-28 11:13:47 +0000520}
521
522static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
523 llvm::BasicBlock *From,
524 llvm::BasicBlock *To) {
525 // Exit is the exit block of a cleanup, so it always terminates in
526 // an unconditional branch or a switch.
527 llvm::TerminatorInst *Term = Exit->getTerminator();
528
529 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
530 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
531 Br->setSuccessor(0, To);
532 } else {
533 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
534 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
535 if (Switch->getSuccessor(I) == From)
536 Switch->setSuccessor(I, To);
537 }
538}
539
John McCallf82bdf62011-08-06 06:53:52 +0000540/// We don't need a normal entry block for the given cleanup.
541/// Optimistic fixup branches can cause these blocks to come into
542/// existence anyway; if so, destroy it.
543///
544/// The validity of this transformation is very much specific to the
545/// exact ways in which we form branches to cleanup entries.
546static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
547 EHCleanupScope &scope) {
548 llvm::BasicBlock *entry = scope.getNormalBlock();
549 if (!entry) return;
550
551 // Replace all the uses with unreachable.
552 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
553 for (llvm::BasicBlock::use_iterator
554 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000555 llvm::Use &use = *i;
John McCallf82bdf62011-08-06 06:53:52 +0000556 ++i;
557
558 use.set(unreachableBB);
559
560 // The only uses should be fixup switches.
561 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
Stepan Dyatkovskiy5fecf5442012-02-01 07:50:21 +0000562 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
John McCallf82bdf62011-08-06 06:53:52 +0000563 // Replace the switch with a branch.
Stepan Dyatkovskiyfe3b0692012-03-11 06:09:37 +0000564 llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
John McCallf82bdf62011-08-06 06:53:52 +0000565
566 // The switch operand is a load from the cleanup-dest alloca.
567 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
568
569 // Destroy the switch.
570 si->eraseFromParent();
571
572 // Destroy the load.
573 assert(condition->getOperand(0) == CGF.NormalCleanupDest);
574 assert(condition->use_empty());
575 condition->eraseFromParent();
576 }
577 }
578
579 assert(entry->use_empty());
580 delete entry;
581}
582
John McCalled1ae862011-01-28 11:13:47 +0000583/// Pops a cleanup block. If the block includes a normal cleanup, the
584/// current insertion point is threaded through the cleanup, as are
585/// any branch fixups on the cleanup.
Adrian Prantldc237b52013-05-16 00:41:26 +0000586void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCalled1ae862011-01-28 11:13:47 +0000587 assert(!EHStack.empty() && "cleanup stack is empty!");
588 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
589 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
590 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
591
592 // Remember activation information.
593 bool IsActive = Scope.isActive();
John McCall7f416cc2015-09-08 08:05:57 +0000594 Address NormalActiveFlag =
595 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
596 : Address::invalid();
597 Address EHActiveFlag =
598 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
599 : Address::invalid();
John McCalled1ae862011-01-28 11:13:47 +0000600
601 // Check whether we need an EH cleanup. This is only true if we've
602 // generated a lazy EH cleanup block.
John McCall8e4c74b2011-08-11 02:22:43 +0000603 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000604 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
605 bool RequiresEHCleanup = (EHEntry != nullptr);
John McCall8e4c74b2011-08-11 02:22:43 +0000606 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000607
608 // Check the three conditions which might require a normal cleanup:
609
610 // - whether there are branch fix-ups through this cleanup
611 unsigned FixupDepth = Scope.getFixupDepth();
612 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
613
614 // - whether there are branch-throughs or branch-afters
615 bool HasExistingBranches = Scope.hasBranches();
616
617 // - whether there's a fallthrough
618 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000619 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
John McCalled1ae862011-01-28 11:13:47 +0000620
621 // Branch-through fall-throughs leave the insertion point set to the
622 // end of the last cleanup, which points to the current scope. The
623 // rest of IR gen doesn't need to worry about this; it only happens
624 // during the execution of PopCleanupBlocks().
625 bool HasPrebranchedFallthrough =
626 (FallthroughSource && FallthroughSource->getTerminator());
627
628 // If this is a normal cleanup, then having a prebranched
629 // fallthrough implies that the fallthrough source unconditionally
630 // jumps here.
631 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
632 (Scope.getNormalBlock() &&
633 FallthroughSource->getTerminator()->getSuccessor(0)
634 == Scope.getNormalBlock()));
635
636 bool RequiresNormalCleanup = false;
637 if (Scope.isNormalCleanup() &&
638 (HasFixups || HasExistingBranches || HasFallthrough)) {
639 RequiresNormalCleanup = true;
640 }
641
John McCall45e42952011-08-07 07:05:57 +0000642 // If we have a prebranched fallthrough into an inactive normal
643 // cleanup, rewrite it so that it leads to the appropriate place.
644 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
645 llvm::BasicBlock *prebranchDest;
646
647 // If the prebranch is semantically branching through the next
648 // cleanup, just forward it to the next block, leaving the
649 // insertion point in the prebranched block.
John McCalled1ae862011-01-28 11:13:47 +0000650 if (FallthroughIsBranchThrough) {
John McCall45e42952011-08-07 07:05:57 +0000651 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
652 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
John McCalled1ae862011-01-28 11:13:47 +0000653
John McCall45e42952011-08-07 07:05:57 +0000654 // Otherwise, we need to make a new block. If the normal cleanup
655 // isn't being used at all, we could actually reuse the normal
656 // entry block, but this is simpler, and it avoids conflicts with
657 // dead optimistic fixup branches.
John McCalled1ae862011-01-28 11:13:47 +0000658 } else {
John McCall45e42952011-08-07 07:05:57 +0000659 prebranchDest = createBasicBlock("forwarded-prebranch");
660 EmitBlock(prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000661 }
John McCall45e42952011-08-07 07:05:57 +0000662
663 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
664 assert(normalEntry && !normalEntry->use_empty());
665
666 ForwardPrebranchedFallthrough(FallthroughSource,
667 normalEntry, prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000668 }
669
670 // If we don't need the cleanup at all, we're done.
671 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000672 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000673 EHStack.popCleanup(); // safe because there are no fixups
674 assert(EHStack.getNumBranchFixups() == 0 ||
675 EHStack.hasNormalCleanups());
676 return;
677 }
678
James Y Knight54a3b262015-12-30 03:58:33 +0000679 // Copy the cleanup emission data out. This uses either a stack
680 // array or malloc'd memory, depending on the size, which is
681 // behavior that SmallVector would provide, if we could use it
682 // here. Unfortunately, if you ask for a SmallVector<char>, the
683 // alignment isn't sufficient.
Benjamin Kramer6c3e4ec2015-08-04 12:34:30 +0000684 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
James Y Knight54a3b262015-12-30 03:58:33 +0000685 llvm::AlignedCharArray<EHScopeStack::ScopeStackAlignment, 8 * sizeof(void *)> CleanupBufferStack;
686 std::unique_ptr<char[]> CleanupBufferHeap;
687 size_t CleanupSize = Scope.getCleanupSize();
688 EHScopeStack::Cleanup *Fn;
689
690 if (CleanupSize <= sizeof(CleanupBufferStack)) {
691 memcpy(CleanupBufferStack.buffer, CleanupSource, CleanupSize);
692 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack.buffer);
693 } else {
694 CleanupBufferHeap.reset(new char[CleanupSize]);
695 memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
696 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
697 }
John McCalled1ae862011-01-28 11:13:47 +0000698
John McCall8e4c74b2011-08-11 02:22:43 +0000699 EHScopeStack::Cleanup::Flags cleanupFlags;
700 if (Scope.isNormalCleanup())
701 cleanupFlags.setIsNormalCleanupKind();
702 if (Scope.isEHCleanup())
703 cleanupFlags.setIsEHCleanupKind();
John McCalled1ae862011-01-28 11:13:47 +0000704
705 if (!RequiresNormalCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000706 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000707 EHStack.popCleanup();
708 } else {
709 // If we have a fallthrough and no other need for the cleanup,
710 // emit it directly.
711 if (HasFallthrough && !HasPrebranchedFallthrough &&
712 !HasFixups && !HasExistingBranches) {
713
John McCallf82bdf62011-08-06 06:53:52 +0000714 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000715 EHStack.popCleanup();
716
John McCall30317fd2011-07-12 20:27:29 +0000717 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000718
719 // Otherwise, the best approach is to thread everything through
720 // the cleanup block and then try to clean up after ourselves.
721 } else {
722 // Force the entry block to exist.
723 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
724
725 // I. Set up the fallthrough edge in.
726
John McCalla3654e32011-08-10 04:11:11 +0000727 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
John McCall45e42952011-08-07 07:05:57 +0000728
John McCalled1ae862011-01-28 11:13:47 +0000729 // If there's a fallthrough, we need to store the cleanup
730 // destination index. For fall-throughs this is always zero.
731 if (HasFallthrough) {
732 if (!HasPrebranchedFallthrough)
733 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
734
John McCall45e42952011-08-07 07:05:57 +0000735 // Otherwise, save and clear the IP if we don't have fallthrough
736 // because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000737 } else if (FallthroughSource) {
738 assert(!IsActive && "source without fallthrough for active cleanup");
John McCall45e42952011-08-07 07:05:57 +0000739 savedInactiveFallthroughIP = Builder.saveAndClearIP();
John McCalled1ae862011-01-28 11:13:47 +0000740 }
741
742 // II. Emit the entry block. This implicitly branches to it if
743 // we have fallthrough. All the fixups and existing branches
744 // should already be branched to it.
745 EmitBlock(NormalEntry);
746
747 // III. Figure out where we're going and build the cleanup
748 // epilogue.
749
750 bool HasEnclosingCleanups =
751 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
752
753 // Compute the branch-through dest if we need it:
754 // - if there are branch-throughs threaded through the scope
755 // - if fall-through is a branch-through
756 // - if there are fixups that will be optimistically forwarded
757 // to the enclosing cleanup
Craig Topper8a13c412014-05-21 05:09:00 +0000758 llvm::BasicBlock *BranchThroughDest = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000759 if (Scope.hasBranchThroughs() ||
760 (FallthroughSource && FallthroughIsBranchThrough) ||
761 (HasFixups && HasEnclosingCleanups)) {
762 assert(HasEnclosingCleanups);
763 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
764 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
765 }
766
Craig Topper8a13c412014-05-21 05:09:00 +0000767 llvm::BasicBlock *FallthroughDest = nullptr;
Benjamin Kramerc7497452015-02-17 16:53:08 +0000768 SmallVector<llvm::Instruction*, 2> InstsToAppend;
John McCalled1ae862011-01-28 11:13:47 +0000769
770 // If there's exactly one branch-after and no other threads,
771 // we can route it without a switch.
772 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
773 Scope.getNumBranchAfters() == 1) {
774 assert(!BranchThroughDest || !IsActive);
775
David Majnemerdc012fa2015-04-22 21:38:15 +0000776 // Clean up the possibly dead store to the cleanup dest slot.
777 llvm::Instruction *NormalCleanupDestSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000778 cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
David Majnemerdc012fa2015-04-22 21:38:15 +0000779 if (NormalCleanupDestSlot->hasOneUse()) {
780 NormalCleanupDestSlot->user_back()->eraseFromParent();
781 NormalCleanupDestSlot->eraseFromParent();
782 NormalCleanupDest = nullptr;
783 }
784
John McCalled1ae862011-01-28 11:13:47 +0000785 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
786 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
787
788 // Build a switch-out if we need it:
789 // - if there are branch-afters threaded through the scope
790 // - if fall-through is a branch-after
791 // - if there are fixups that have nowhere left to go and
792 // so must be immediately resolved
793 } else if (Scope.getNumBranchAfters() ||
794 (HasFallthrough && !FallthroughIsBranchThrough) ||
795 (HasFixups && !HasEnclosingCleanups)) {
796
797 llvm::BasicBlock *Default =
798 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
799
800 // TODO: base this on the number of branch-afters and fixups
801 const unsigned SwitchCapacity = 10;
802
803 llvm::LoadInst *Load =
John McCall7f416cc2015-09-08 08:05:57 +0000804 createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
805 nullptr);
John McCalled1ae862011-01-28 11:13:47 +0000806 llvm::SwitchInst *Switch =
807 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
808
809 InstsToAppend.push_back(Load);
810 InstsToAppend.push_back(Switch);
811
812 // Branch-after fallthrough.
813 if (FallthroughSource && !FallthroughIsBranchThrough) {
814 FallthroughDest = createBasicBlock("cleanup.cont");
815 if (HasFallthrough)
816 Switch->addCase(Builder.getInt32(0), FallthroughDest);
817 }
818
819 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
820 Switch->addCase(Scope.getBranchAfterIndex(I),
821 Scope.getBranchAfterBlock(I));
822 }
823
824 // If there aren't any enclosing cleanups, we can resolve all
825 // the fixups now.
826 if (HasFixups && !HasEnclosingCleanups)
827 ResolveAllBranchFixups(*this, Switch, NormalEntry);
828 } else {
829 // We should always have a branch-through destination in this case.
830 assert(BranchThroughDest);
831 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
832 }
833
834 // IV. Pop the cleanup and emit it.
835 EHStack.popCleanup();
836 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
837
John McCall30317fd2011-07-12 20:27:29 +0000838 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000839
840 // Append the prepared cleanup prologue from above.
841 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
Benjamin Kramerc7497452015-02-17 16:53:08 +0000842 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
843 NormalExit->getInstList().push_back(InstsToAppend[I]);
John McCalled1ae862011-01-28 11:13:47 +0000844
845 // Optimistically hope that any fixups will continue falling through.
846 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
847 I < E; ++I) {
John McCallad7c5c12011-02-08 08:22:06 +0000848 BranchFixup &Fixup = EHStack.getBranchFixup(I);
John McCalled1ae862011-01-28 11:13:47 +0000849 if (!Fixup.Destination) continue;
850 if (!Fixup.OptimisticBranchBlock) {
John McCall7f416cc2015-09-08 08:05:57 +0000851 createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
852 getNormalCleanupDestSlot(),
853 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000854 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
855 }
856 Fixup.OptimisticBranchBlock = NormalExit;
857 }
858
859 // V. Set up the fallthrough edge out.
860
John McCall45e42952011-08-07 07:05:57 +0000861 // Case 1: a fallthrough source exists but doesn't branch to the
862 // cleanup because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000863 if (!HasFallthrough && FallthroughSource) {
John McCall45e42952011-08-07 07:05:57 +0000864 // Prebranched fallthrough was forwarded earlier.
865 // Non-prebranched fallthrough doesn't need to be forwarded.
866 // Either way, all we need to do is restore the IP we cleared before.
John McCalled1ae862011-01-28 11:13:47 +0000867 assert(!IsActive);
John McCall45e42952011-08-07 07:05:57 +0000868 Builder.restoreIP(savedInactiveFallthroughIP);
John McCalled1ae862011-01-28 11:13:47 +0000869
870 // Case 2: a fallthrough source exists and should branch to the
871 // cleanup, but we're not supposed to branch through to the next
872 // cleanup.
873 } else if (HasFallthrough && FallthroughDest) {
874 assert(!FallthroughIsBranchThrough);
875 EmitBlock(FallthroughDest);
876
877 // Case 3: a fallthrough source exists and should branch to the
878 // cleanup and then through to the next.
879 } else if (HasFallthrough) {
880 // Everything is already set up for this.
881
882 // Case 4: no fallthrough source exists.
883 } else {
884 Builder.ClearInsertionPoint();
885 }
886
887 // VI. Assorted cleaning.
888
889 // Check whether we can merge NormalEntry into a single predecessor.
890 // This might invalidate (non-IR) pointers to NormalEntry.
891 llvm::BasicBlock *NewNormalEntry =
892 SimplifyCleanupEntry(*this, NormalEntry);
893
894 // If it did invalidate those pointers, and NormalEntry was the same
895 // as NormalExit, go back and patch up the fixups.
896 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
897 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
898 I < E; ++I)
John McCallad7c5c12011-02-08 08:22:06 +0000899 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCalled1ae862011-01-28 11:13:47 +0000900 }
901 }
902
903 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
904
905 // Emit the EH cleanup if required.
906 if (RequiresEHCleanup) {
907 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
908
909 EmitBlock(EHEntry);
Reid Kleckner55391522015-10-08 21:14:56 +0000910
Reid Klecknera002bd52015-10-28 23:06:42 +0000911 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
912
913 // Push a terminate scope or cleanupendpad scope around the potentially
914 // throwing cleanups. For funclet EH personalities, the cleanupendpad models
915 // program termination when cleanups throw.
Reid Kleckner55391522015-10-08 21:14:56 +0000916 bool PushedTerminate = false;
David Majnemer4e52d6f2015-12-12 05:39:21 +0000917 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
918 CurrentFuncletPad);
Reid Klecknera002bd52015-10-28 23:06:42 +0000919 llvm::CleanupPadInst *CPI = nullptr;
Reid Kleckner55391522015-10-08 21:14:56 +0000920 if (!EHPersonality::get(*this).usesFuncletPads()) {
921 EHStack.pushTerminate();
922 PushedTerminate = true;
Reid Klecknera002bd52015-10-28 23:06:42 +0000923 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000924 llvm::Value *ParentPad = CurrentFuncletPad;
925 if (!ParentPad)
926 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
927 CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
Reid Kleckner55391522015-10-08 21:14:56 +0000928 }
929
Eli Friedmanabab7762012-08-02 00:10:24 +0000930 // We only actually emit the cleanup code if the cleanup is either
931 // active or was used before it was deactivated.
John McCall7f416cc2015-09-08 08:05:57 +0000932 if (EHActiveFlag.isValid() || IsActive) {
Eli Friedmanabab7762012-08-02 00:10:24 +0000933 cleanupFlags.setIsForEHCleanup();
934 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
935 }
John McCalled1ae862011-01-28 11:13:47 +0000936
David Majnemere888a2f2015-08-15 03:21:08 +0000937 if (CPI)
Joseph Tremouletce536a52015-08-23 00:26:48 +0000938 Builder.CreateCleanupRet(CPI, NextAction);
David Majnemerdbf10452015-07-31 17:58:45 +0000939 else
940 Builder.CreateBr(NextAction);
John McCalled1ae862011-01-28 11:13:47 +0000941
Reid Kleckner55391522015-10-08 21:14:56 +0000942 // Leave the terminate scope.
943 if (PushedTerminate)
944 EHStack.popTerminate();
945
John McCalled1ae862011-01-28 11:13:47 +0000946 Builder.restoreIP(SavedIP);
947
948 SimplifyCleanupEntry(*this, EHEntry);
949 }
950}
951
Justin Bognere25ffdf2014-01-21 00:35:11 +0000952/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
953/// specified destination obviously has no cleanups to run. 'false' is always
954/// a conservatively correct answer for this method.
955bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
956 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
957 && "stale jump destination");
958
959 // Calculate the innermost active normal cleanup.
960 EHScopeStack::stable_iterator TopCleanup =
961 EHStack.getInnermostActiveNormalCleanup();
962
963 // If we're not in an active normal cleanup scope, or if the
964 // destination scope is within the innermost active normal cleanup
965 // scope, we don't need to worry about fixups.
966 if (TopCleanup == EHStack.stable_end() ||
967 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
968 return true;
969
970 // Otherwise, we might need some cleanups.
971 return false;
972}
973
974
John McCalled1ae862011-01-28 11:13:47 +0000975/// Terminate the current block by emitting a branch which might leave
976/// the current cleanup-protected scope. The target scope may not yet
977/// be known, in which case this will require a fixup.
978///
979/// As a side-effect, this method clears the insertion point.
980void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall1b93f1b2011-02-25 04:19:13 +0000981 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
John McCalled1ae862011-01-28 11:13:47 +0000982 && "stale jump destination");
983
984 if (!HaveInsertPoint())
985 return;
986
987 // Create the branch.
988 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
989
990 // Calculate the innermost active normal cleanup.
991 EHScopeStack::stable_iterator
992 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
993
994 // If we're not in an active normal cleanup scope, or if the
995 // destination scope is within the innermost active normal cleanup
996 // scope, we don't need to worry about fixups.
997 if (TopCleanup == EHStack.stable_end() ||
998 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
999 Builder.ClearInsertionPoint();
1000 return;
1001 }
1002
1003 // If we can't resolve the destination cleanup scope, just add this
1004 // to the current cleanup scope as a branch fixup.
1005 if (!Dest.getScopeDepth().isValid()) {
1006 BranchFixup &Fixup = EHStack.addBranchFixup();
1007 Fixup.Destination = Dest.getBlock();
1008 Fixup.DestinationIndex = Dest.getDestIndex();
1009 Fixup.InitialBranch = BI;
Craig Topper8a13c412014-05-21 05:09:00 +00001010 Fixup.OptimisticBranchBlock = nullptr;
John McCalled1ae862011-01-28 11:13:47 +00001011
1012 Builder.ClearInsertionPoint();
1013 return;
1014 }
1015
1016 // Otherwise, thread through all the normal cleanups in scope.
1017
1018 // Store the index at the start.
1019 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
John McCall7f416cc2015-09-08 08:05:57 +00001020 createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
John McCalled1ae862011-01-28 11:13:47 +00001021
1022 // Adjust BI to point to the first cleanup block.
1023 {
1024 EHCleanupScope &Scope =
1025 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1026 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1027 }
1028
1029 // Add this destination to all the scopes involved.
1030 EHScopeStack::stable_iterator I = TopCleanup;
1031 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1032 if (E.strictlyEncloses(I)) {
1033 while (true) {
1034 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1035 assert(Scope.isNormalCleanup());
1036 I = Scope.getEnclosingNormalCleanup();
1037
1038 // If this is the last cleanup we're propagating through, tell it
1039 // that there's a resolved jump moving through it.
1040 if (!E.strictlyEncloses(I)) {
1041 Scope.addBranchAfter(Index, Dest.getBlock());
1042 break;
1043 }
1044
1045 // Otherwise, tell the scope that there's a jump propoagating
1046 // through it. If this isn't new information, all the rest of
1047 // the work has been done before.
1048 if (!Scope.addBranchThrough(Dest.getBlock()))
1049 break;
1050 }
1051 }
1052
1053 Builder.ClearInsertionPoint();
1054}
1055
John McCalled1ae862011-01-28 11:13:47 +00001056static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1057 EHScopeStack::stable_iterator C) {
1058 // If we needed a normal block for any reason, that counts.
1059 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1060 return true;
1061
1062 // Check whether any enclosed cleanups were needed.
1063 for (EHScopeStack::stable_iterator
1064 I = EHStack.getInnermostNormalCleanup();
1065 I != C; ) {
1066 assert(C.strictlyEncloses(I));
1067 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1068 if (S.getNormalBlock()) return true;
1069 I = S.getEnclosingNormalCleanup();
1070 }
1071
1072 return false;
1073}
1074
1075static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
John McCall8e4c74b2011-08-11 02:22:43 +00001076 EHScopeStack::stable_iterator cleanup) {
John McCalled1ae862011-01-28 11:13:47 +00001077 // If we needed an EH block for any reason, that counts.
John McCall8e4c74b2011-08-11 02:22:43 +00001078 if (EHStack.find(cleanup)->hasEHBranches())
John McCalled1ae862011-01-28 11:13:47 +00001079 return true;
1080
1081 // Check whether any enclosed cleanups were needed.
1082 for (EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +00001083 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1084 assert(cleanup.strictlyEncloses(i));
1085
1086 EHScope &scope = *EHStack.find(i);
1087 if (scope.hasEHBranches())
1088 return true;
1089
1090 i = scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +00001091 }
1092
1093 return false;
1094}
1095
1096enum ForActivation_t {
1097 ForActivation,
1098 ForDeactivation
1099};
1100
1101/// The given cleanup block is changing activation state. Configure a
1102/// cleanup variable if necessary.
1103///
1104/// It would be good if we had some way of determining if there were
1105/// extra uses *after* the change-over point.
1106static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1107 EHScopeStack::stable_iterator C,
John McCallf4beacd2011-11-10 10:43:54 +00001108 ForActivation_t kind,
1109 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001110 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1111
John McCalle63abb52011-11-10 09:22:44 +00001112 // We always need the flag if we're activating the cleanup in a
1113 // conditional context, because we have to assume that the current
1114 // location doesn't necessarily dominate the cleanup's code.
1115 bool isActivatedInConditional =
John McCallf4beacd2011-11-10 10:43:54 +00001116 (kind == ForActivation && CGF.isInConditionalBranch());
John McCalle63abb52011-11-10 09:22:44 +00001117
1118 bool needFlag = false;
John McCalled1ae862011-01-28 11:13:47 +00001119
1120 // Calculate whether the cleanup was used:
1121
1122 // - as a normal cleanup
John McCalle63abb52011-11-10 09:22:44 +00001123 if (Scope.isNormalCleanup() &&
1124 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001125 Scope.setTestFlagInNormalCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001126 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001127 }
1128
1129 // - as an EH cleanup
John McCalle63abb52011-11-10 09:22:44 +00001130 if (Scope.isEHCleanup() &&
1131 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001132 Scope.setTestFlagInEHCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001133 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001134 }
1135
1136 // If it hasn't yet been used as either, we're done.
John McCalle63abb52011-11-10 09:22:44 +00001137 if (!needFlag) return;
John McCalled1ae862011-01-28 11:13:47 +00001138
John McCall7f416cc2015-09-08 08:05:57 +00001139 Address var = Scope.getActiveFlag();
1140 if (!var.isValid()) {
1141 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1142 "cleanup.isactive");
John McCallf4beacd2011-11-10 10:43:54 +00001143 Scope.setActiveFlag(var);
1144
1145 assert(dominatingIP && "no existing variable and no dominating IP!");
John McCalled1ae862011-01-28 11:13:47 +00001146
1147 // Initialize to true or false depending on whether it was
1148 // active up to this point.
John McCall7f416cc2015-09-08 08:05:57 +00001149 llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
John McCallf4beacd2011-11-10 10:43:54 +00001150
1151 // If we're in a conditional block, ignore the dominating IP and
1152 // use the outermost conditional branch.
1153 if (CGF.isInConditionalBranch()) {
1154 CGF.setBeforeOutermostConditional(value, var);
1155 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001156 createStoreInstBefore(value, var, dominatingIP);
John McCallf4beacd2011-11-10 10:43:54 +00001157 }
John McCalled1ae862011-01-28 11:13:47 +00001158 }
1159
John McCallf4beacd2011-11-10 10:43:54 +00001160 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
John McCalled1ae862011-01-28 11:13:47 +00001161}
1162
1163/// Activate a cleanup that was created in an inactivated state.
John McCallf4beacd2011-11-10 10:43:54 +00001164void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1165 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001166 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1167 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1168 assert(!Scope.isActive() && "double activation");
1169
John McCallf4beacd2011-11-10 10:43:54 +00001170 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001171
1172 Scope.setActive(true);
1173}
1174
1175/// Deactive a cleanup that was created in an active state.
John McCallf4beacd2011-11-10 10:43:54 +00001176void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1177 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001178 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1179 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1180 assert(Scope.isActive() && "double deactivation");
1181
1182 // If it's the top of the stack, just pop it.
1183 if (C == EHStack.stable_begin()) {
1184 // If it's a normal cleanup, we need to pretend that the
1185 // fallthrough is unreachable.
1186 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1187 PopCleanupBlock();
1188 Builder.restoreIP(SavedIP);
1189 return;
1190 }
1191
1192 // Otherwise, follow the general case.
John McCallf4beacd2011-11-10 10:43:54 +00001193 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001194
1195 Scope.setActive(false);
1196}
1197
John McCall7f416cc2015-09-08 08:05:57 +00001198Address CodeGenFunction::getNormalCleanupDestSlot() {
John McCalled1ae862011-01-28 11:13:47 +00001199 if (!NormalCleanupDest)
1200 NormalCleanupDest =
1201 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
John McCall7f416cc2015-09-08 08:05:57 +00001202 return Address(NormalCleanupDest, CharUnits::fromQuantity(4));
John McCalled1ae862011-01-28 11:13:47 +00001203}
Peter Collingbourne702b2842011-11-27 22:09:22 +00001204
1205/// Emits all the code to cause the given temporary to be cleaned up.
1206void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1207 QualType TempType,
John McCall7f416cc2015-09-08 08:05:57 +00001208 Address Ptr) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001209 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
Peter Collingbourne702b2842011-11-27 22:09:22 +00001210 /*useEHCleanup*/ true);
1211}