blob: 22055b2cb9029b5701ee27485d3e04f14616992e [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
284void CodeGenFunction::initFullExprCleanup() {
285 // Create a variable to decide whether the cleanup needs to be run.
John McCall7f416cc2015-09-08 08:05:57 +0000286 Address active = CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
287 "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
296 // Set that as the active flag in the cleanup.
297 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
John McCall7f416cc2015-09-08 08:05:57 +0000298 assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
John McCalled1ae862011-01-28 11:13:47 +0000299 cleanup.setActiveFlag(active);
300
301 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
302 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
303}
304
John McCall5fcf8da2011-07-12 00:15:30 +0000305void EHScopeStack::Cleanup::anchor() {}
John McCalled1ae862011-01-28 11:13:47 +0000306
John McCall7f416cc2015-09-08 08:05:57 +0000307static void createStoreInstBefore(llvm::Value *value, Address addr,
308 llvm::Instruction *beforeInst) {
309 auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
310 store->setAlignment(addr.getAlignment().getQuantity());
311}
312
313static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
314 llvm::Instruction *beforeInst) {
315 auto load = new llvm::LoadInst(addr.getPointer(), name, beforeInst);
316 load->setAlignment(addr.getAlignment().getQuantity());
317 return load;
318}
319
John McCalled1ae862011-01-28 11:13:47 +0000320/// All the branch fixups on the EH stack have propagated out past the
321/// outermost normal cleanup; resolve them all by adding cases to the
322/// given switch instruction.
323static void ResolveAllBranchFixups(CodeGenFunction &CGF,
324 llvm::SwitchInst *Switch,
325 llvm::BasicBlock *CleanupEntry) {
326 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
327
328 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
329 // Skip this fixup if its destination isn't set.
330 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
Craig Topper8a13c412014-05-21 05:09:00 +0000331 if (Fixup.Destination == nullptr) continue;
John McCalled1ae862011-01-28 11:13:47 +0000332
333 // If there isn't an OptimisticBranchBlock, then InitialBranch is
334 // still pointing directly to its destination; forward it to the
335 // appropriate cleanup entry. This is required in the specific
336 // case of
337 // { std::string s; goto lbl; }
338 // lbl:
339 // i.e. where there's an unresolved fixup inside a single cleanup
340 // entry which we're currently popping.
Craig Topper8a13c412014-05-21 05:09:00 +0000341 if (Fixup.OptimisticBranchBlock == nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +0000342 createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
343 CGF.getNormalCleanupDestSlot(),
344 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000345 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
346 }
347
348 // Don't add this case to the switch statement twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000349 if (!CasesAdded.insert(Fixup.Destination).second)
350 continue;
John McCalled1ae862011-01-28 11:13:47 +0000351
352 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
353 Fixup.Destination);
354 }
355
356 CGF.EHStack.clearFixups();
357}
358
359/// Transitions the terminator of the given exit-block of a cleanup to
360/// be a cleanup switch.
361static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
362 llvm::BasicBlock *Block) {
363 // If it's a branch, turn it into a switch whose default
364 // destination is its original target.
365 llvm::TerminatorInst *Term = Block->getTerminator();
366 assert(Term && "can't transition block without terminator");
367
368 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
369 assert(Br->isUnconditional());
John McCall7f416cc2015-09-08 08:05:57 +0000370 auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
371 "cleanup.dest", Term);
John McCalled1ae862011-01-28 11:13:47 +0000372 llvm::SwitchInst *Switch =
373 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
374 Br->eraseFromParent();
375 return Switch;
376 } else {
377 return cast<llvm::SwitchInst>(Term);
378 }
379}
380
381void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
382 assert(Block && "resolving a null target block");
383 if (!EHStack.getNumBranchFixups()) return;
384
385 assert(EHStack.hasNormalCleanups() &&
386 "branch fixups exist with no normal cleanups on stack");
387
388 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
389 bool ResolvedAny = false;
390
391 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
392 // Skip this fixup if its destination doesn't match.
393 BranchFixup &Fixup = EHStack.getBranchFixup(I);
394 if (Fixup.Destination != Block) continue;
395
Craig Topper8a13c412014-05-21 05:09:00 +0000396 Fixup.Destination = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000397 ResolvedAny = true;
398
399 // If it doesn't have an optimistic branch block, LatestBranch is
400 // already pointing to the right place.
401 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
402 if (!BranchBB)
403 continue;
404
405 // Don't process the same optimistic branch block twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000406 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
John McCalled1ae862011-01-28 11:13:47 +0000407 continue;
408
409 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
410
411 // Add a case to the switch.
412 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
413 }
414
415 if (ResolvedAny)
416 EHStack.popNullFixups();
417}
418
419/// Pops cleanup blocks until the given savepoint is reached.
Reid Kleckner092d0652017-03-06 22:18:34 +0000420void CodeGenFunction::PopCleanupBlocks(
421 EHScopeStack::stable_iterator Old,
422 std::initializer_list<llvm::Value **> ValuesToReload) {
John McCalled1ae862011-01-28 11:13:47 +0000423 assert(Old.isValid());
424
Reid Kleckner092d0652017-03-06 22:18:34 +0000425 bool HadBranches = false;
John McCalled1ae862011-01-28 11:13:47 +0000426 while (EHStack.stable_begin() != Old) {
427 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
Reid Kleckner092d0652017-03-06 22:18:34 +0000428 HadBranches |= Scope.hasBranches();
John McCalled1ae862011-01-28 11:13:47 +0000429
430 // As long as Old strictly encloses the scope's enclosing normal
431 // cleanup, we're going to emit another normal cleanup which
432 // fallthrough can propagate through.
433 bool FallThroughIsBranchThrough =
434 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
435
Adrian Prantldc237b52013-05-16 00:41:26 +0000436 PopCleanupBlock(FallThroughIsBranchThrough);
John McCalled1ae862011-01-28 11:13:47 +0000437 }
Reid Kleckner092d0652017-03-06 22:18:34 +0000438
439 // If we didn't have any branches, the insertion point before cleanups must
440 // dominate the current insertion point and we don't need to reload any
441 // values.
442 if (!HadBranches)
443 return;
444
445 // Spill and reload all values that the caller wants to be live at the current
446 // insertion point.
447 for (llvm::Value **ReloadedValue : ValuesToReload) {
448 auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
449 if (!Inst)
450 continue;
Reid Kleckner04493162017-05-31 19:59:41 +0000451
452 // Don't spill static allocas, they dominate all cleanups. These are created
453 // by binding a reference to a local variable or temporary.
454 auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
455 if (AI && AI->isStaticAlloca())
456 continue;
457
Reid Kleckner092d0652017-03-06 22:18:34 +0000458 Address Tmp =
459 CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
460
461 // Find an insertion point after Inst and spill it to the temporary.
462 llvm::BasicBlock::iterator InsertBefore;
463 if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
464 InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
465 else
466 InsertBefore = std::next(Inst->getIterator());
467 CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
468
469 // Reload the value at the current insertion point.
470 *ReloadedValue = Builder.CreateLoad(Tmp);
471 }
John McCalled1ae862011-01-28 11:13:47 +0000472}
473
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000474/// Pops cleanup blocks until the given savepoint is reached, then add the
475/// cleanups from the given savepoint in the lifetime-extended cleanups stack.
Reid Kleckner092d0652017-03-06 22:18:34 +0000476void CodeGenFunction::PopCleanupBlocks(
477 EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
478 std::initializer_list<llvm::Value **> ValuesToReload) {
479 PopCleanupBlocks(Old, ValuesToReload);
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000480
481 // Move our deferred cleanups onto the EH stack.
Richard Smith736a9472013-06-12 20:42:33 +0000482 for (size_t I = OldLifetimeExtendedSize,
483 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
484 // Alignment should be guaranteed by the vptrs in the individual cleanups.
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000485 assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
Richard Smith736a9472013-06-12 20:42:33 +0000486 "misaligned cleanup stack entry");
487
488 LifetimeExtendedCleanupHeader &Header =
489 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
490 LifetimeExtendedCleanupStack[I]);
491 I += sizeof(Header);
492
493 EHStack.pushCopyOfCleanup(Header.getKind(),
494 &LifetimeExtendedCleanupStack[I],
495 Header.getSize());
496 I += Header.getSize();
497 }
498 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
499}
500
John McCalled1ae862011-01-28 11:13:47 +0000501static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
502 EHCleanupScope &Scope) {
503 assert(Scope.isNormalCleanup());
504 llvm::BasicBlock *Entry = Scope.getNormalBlock();
505 if (!Entry) {
506 Entry = CGF.createBasicBlock("cleanup");
507 Scope.setNormalBlock(Entry);
508 }
509 return Entry;
510}
511
John McCalled1ae862011-01-28 11:13:47 +0000512/// Attempts to reduce a cleanup's entry block to a fallthrough. This
513/// is basically llvm::MergeBlockIntoPredecessor, except
514/// simplified/optimized for the tighter constraints on cleanup blocks.
515///
516/// Returns the new block, whatever it is.
517static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
518 llvm::BasicBlock *Entry) {
519 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
520 if (!Pred) return Entry;
521
522 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
523 if (!Br || Br->isConditional()) return Entry;
524 assert(Br->getSuccessor(0) == Entry);
525
526 // If we were previously inserting at the end of the cleanup entry
527 // block, we'll need to continue inserting at the end of the
528 // predecessor.
529 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
530 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
531
532 // Kill the branch.
533 Br->eraseFromParent();
534
John McCalled1ae862011-01-28 11:13:47 +0000535 // Replace all uses of the entry with the predecessor, in case there
536 // are phis in the cleanup.
537 Entry->replaceAllUsesWith(Pred);
538
Jay Foade03c05c2011-06-20 14:38:01 +0000539 // Merge the blocks.
540 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
541
John McCalled1ae862011-01-28 11:13:47 +0000542 // Kill the entry block.
543 Entry->eraseFromParent();
544
545 if (WasInsertBlock)
546 CGF.Builder.SetInsertPoint(Pred);
547
548 return Pred;
549}
550
551static void EmitCleanup(CodeGenFunction &CGF,
552 EHScopeStack::Cleanup *Fn,
John McCall30317fd2011-07-12 20:27:29 +0000553 EHScopeStack::Cleanup::Flags flags,
John McCall7f416cc2015-09-08 08:05:57 +0000554 Address ActiveFlag) {
John McCalled1ae862011-01-28 11:13:47 +0000555 // If there's an active flag, load it and skip the cleanup if it's
556 // false.
Craig Topper8a13c412014-05-21 05:09:00 +0000557 llvm::BasicBlock *ContBB = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000558 if (ActiveFlag.isValid()) {
John McCalled1ae862011-01-28 11:13:47 +0000559 ContBB = CGF.createBasicBlock("cleanup.done");
560 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
561 llvm::Value *IsActive
562 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
563 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
564 CGF.EmitBlock(CleanupBB);
565 }
566
567 // Ask the cleanup to emit itself.
John McCall30317fd2011-07-12 20:27:29 +0000568 Fn->Emit(CGF, flags);
John McCalled1ae862011-01-28 11:13:47 +0000569 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
570
571 // Emit the continuation block if there was an active flag.
John McCall7f416cc2015-09-08 08:05:57 +0000572 if (ActiveFlag.isValid())
John McCalled1ae862011-01-28 11:13:47 +0000573 CGF.EmitBlock(ContBB);
John McCalled1ae862011-01-28 11:13:47 +0000574}
575
576static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
577 llvm::BasicBlock *From,
578 llvm::BasicBlock *To) {
579 // Exit is the exit block of a cleanup, so it always terminates in
580 // an unconditional branch or a switch.
581 llvm::TerminatorInst *Term = Exit->getTerminator();
582
583 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
584 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
585 Br->setSuccessor(0, To);
586 } else {
587 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
588 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
589 if (Switch->getSuccessor(I) == From)
590 Switch->setSuccessor(I, To);
591 }
592}
593
John McCallf82bdf62011-08-06 06:53:52 +0000594/// We don't need a normal entry block for the given cleanup.
595/// Optimistic fixup branches can cause these blocks to come into
596/// existence anyway; if so, destroy it.
597///
598/// The validity of this transformation is very much specific to the
599/// exact ways in which we form branches to cleanup entries.
600static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
601 EHCleanupScope &scope) {
602 llvm::BasicBlock *entry = scope.getNormalBlock();
603 if (!entry) return;
604
605 // Replace all the uses with unreachable.
606 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
607 for (llvm::BasicBlock::use_iterator
608 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000609 llvm::Use &use = *i;
John McCallf82bdf62011-08-06 06:53:52 +0000610 ++i;
611
612 use.set(unreachableBB);
613
614 // The only uses should be fixup switches.
615 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
Stepan Dyatkovskiy5fecf5442012-02-01 07:50:21 +0000616 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
John McCallf82bdf62011-08-06 06:53:52 +0000617 // Replace the switch with a branch.
Chandler Carruth260161b2017-04-12 08:12:30 +0000618 llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
John McCallf82bdf62011-08-06 06:53:52 +0000619
620 // The switch operand is a load from the cleanup-dest alloca.
621 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
622
623 // Destroy the switch.
624 si->eraseFromParent();
625
626 // Destroy the load.
627 assert(condition->getOperand(0) == CGF.NormalCleanupDest);
628 assert(condition->use_empty());
629 condition->eraseFromParent();
630 }
631 }
632
633 assert(entry->use_empty());
634 delete entry;
635}
636
John McCalled1ae862011-01-28 11:13:47 +0000637/// Pops a cleanup block. If the block includes a normal cleanup, the
638/// current insertion point is threaded through the cleanup, as are
639/// any branch fixups on the cleanup.
Adrian Prantldc237b52013-05-16 00:41:26 +0000640void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCalled1ae862011-01-28 11:13:47 +0000641 assert(!EHStack.empty() && "cleanup stack is empty!");
642 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
643 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
644 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
645
646 // Remember activation information.
647 bool IsActive = Scope.isActive();
John McCall7f416cc2015-09-08 08:05:57 +0000648 Address NormalActiveFlag =
649 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
650 : Address::invalid();
651 Address EHActiveFlag =
652 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
653 : Address::invalid();
John McCalled1ae862011-01-28 11:13:47 +0000654
655 // Check whether we need an EH cleanup. This is only true if we've
656 // generated a lazy EH cleanup block.
John McCall8e4c74b2011-08-11 02:22:43 +0000657 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000658 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
659 bool RequiresEHCleanup = (EHEntry != nullptr);
John McCall8e4c74b2011-08-11 02:22:43 +0000660 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000661
662 // Check the three conditions which might require a normal cleanup:
663
664 // - whether there are branch fix-ups through this cleanup
665 unsigned FixupDepth = Scope.getFixupDepth();
666 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
667
668 // - whether there are branch-throughs or branch-afters
669 bool HasExistingBranches = Scope.hasBranches();
670
671 // - whether there's a fallthrough
672 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000673 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
John McCalled1ae862011-01-28 11:13:47 +0000674
675 // Branch-through fall-throughs leave the insertion point set to the
676 // end of the last cleanup, which points to the current scope. The
677 // rest of IR gen doesn't need to worry about this; it only happens
678 // during the execution of PopCleanupBlocks().
679 bool HasPrebranchedFallthrough =
680 (FallthroughSource && FallthroughSource->getTerminator());
681
682 // If this is a normal cleanup, then having a prebranched
683 // fallthrough implies that the fallthrough source unconditionally
684 // jumps here.
685 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
686 (Scope.getNormalBlock() &&
687 FallthroughSource->getTerminator()->getSuccessor(0)
688 == Scope.getNormalBlock()));
689
690 bool RequiresNormalCleanup = false;
691 if (Scope.isNormalCleanup() &&
692 (HasFixups || HasExistingBranches || HasFallthrough)) {
693 RequiresNormalCleanup = true;
694 }
695
John McCall45e42952011-08-07 07:05:57 +0000696 // If we have a prebranched fallthrough into an inactive normal
697 // cleanup, rewrite it so that it leads to the appropriate place.
698 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
699 llvm::BasicBlock *prebranchDest;
700
701 // If the prebranch is semantically branching through the next
702 // cleanup, just forward it to the next block, leaving the
703 // insertion point in the prebranched block.
John McCalled1ae862011-01-28 11:13:47 +0000704 if (FallthroughIsBranchThrough) {
John McCall45e42952011-08-07 07:05:57 +0000705 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
706 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
John McCalled1ae862011-01-28 11:13:47 +0000707
John McCall45e42952011-08-07 07:05:57 +0000708 // Otherwise, we need to make a new block. If the normal cleanup
709 // isn't being used at all, we could actually reuse the normal
710 // entry block, but this is simpler, and it avoids conflicts with
711 // dead optimistic fixup branches.
John McCalled1ae862011-01-28 11:13:47 +0000712 } else {
John McCall45e42952011-08-07 07:05:57 +0000713 prebranchDest = createBasicBlock("forwarded-prebranch");
714 EmitBlock(prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000715 }
John McCall45e42952011-08-07 07:05:57 +0000716
717 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
718 assert(normalEntry && !normalEntry->use_empty());
719
720 ForwardPrebranchedFallthrough(FallthroughSource,
721 normalEntry, prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000722 }
723
724 // If we don't need the cleanup at all, we're done.
725 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000726 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000727 EHStack.popCleanup(); // safe because there are no fixups
728 assert(EHStack.getNumBranchFixups() == 0 ||
729 EHStack.hasNormalCleanups());
730 return;
731 }
732
James Y Knight54a3b262015-12-30 03:58:33 +0000733 // Copy the cleanup emission data out. This uses either a stack
734 // array or malloc'd memory, depending on the size, which is
735 // behavior that SmallVector would provide, if we could use it
736 // here. Unfortunately, if you ask for a SmallVector<char>, the
737 // alignment isn't sufficient.
Benjamin Kramer6c3e4ec2015-08-04 12:34:30 +0000738 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
James Y Knight54a3b262015-12-30 03:58:33 +0000739 llvm::AlignedCharArray<EHScopeStack::ScopeStackAlignment, 8 * sizeof(void *)> CleanupBufferStack;
740 std::unique_ptr<char[]> CleanupBufferHeap;
741 size_t CleanupSize = Scope.getCleanupSize();
742 EHScopeStack::Cleanup *Fn;
743
744 if (CleanupSize <= sizeof(CleanupBufferStack)) {
745 memcpy(CleanupBufferStack.buffer, CleanupSource, CleanupSize);
746 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack.buffer);
747 } else {
748 CleanupBufferHeap.reset(new char[CleanupSize]);
749 memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
750 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
751 }
John McCalled1ae862011-01-28 11:13:47 +0000752
John McCall8e4c74b2011-08-11 02:22:43 +0000753 EHScopeStack::Cleanup::Flags cleanupFlags;
754 if (Scope.isNormalCleanup())
755 cleanupFlags.setIsNormalCleanupKind();
756 if (Scope.isEHCleanup())
757 cleanupFlags.setIsEHCleanupKind();
John McCalled1ae862011-01-28 11:13:47 +0000758
759 if (!RequiresNormalCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000760 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000761 EHStack.popCleanup();
762 } else {
763 // If we have a fallthrough and no other need for the cleanup,
764 // emit it directly.
765 if (HasFallthrough && !HasPrebranchedFallthrough &&
766 !HasFixups && !HasExistingBranches) {
767
John McCallf82bdf62011-08-06 06:53:52 +0000768 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000769 EHStack.popCleanup();
770
John McCall30317fd2011-07-12 20:27:29 +0000771 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000772
773 // Otherwise, the best approach is to thread everything through
774 // the cleanup block and then try to clean up after ourselves.
775 } else {
776 // Force the entry block to exist.
777 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
778
779 // I. Set up the fallthrough edge in.
780
John McCalla3654e32011-08-10 04:11:11 +0000781 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
John McCall45e42952011-08-07 07:05:57 +0000782
John McCalled1ae862011-01-28 11:13:47 +0000783 // If there's a fallthrough, we need to store the cleanup
784 // destination index. For fall-throughs this is always zero.
785 if (HasFallthrough) {
786 if (!HasPrebranchedFallthrough)
787 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
788
John McCall45e42952011-08-07 07:05:57 +0000789 // Otherwise, save and clear the IP if we don't have fallthrough
790 // because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000791 } else if (FallthroughSource) {
792 assert(!IsActive && "source without fallthrough for active cleanup");
John McCall45e42952011-08-07 07:05:57 +0000793 savedInactiveFallthroughIP = Builder.saveAndClearIP();
John McCalled1ae862011-01-28 11:13:47 +0000794 }
795
796 // II. Emit the entry block. This implicitly branches to it if
797 // we have fallthrough. All the fixups and existing branches
798 // should already be branched to it.
799 EmitBlock(NormalEntry);
800
801 // III. Figure out where we're going and build the cleanup
802 // epilogue.
803
804 bool HasEnclosingCleanups =
805 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
806
807 // Compute the branch-through dest if we need it:
808 // - if there are branch-throughs threaded through the scope
809 // - if fall-through is a branch-through
810 // - if there are fixups that will be optimistically forwarded
811 // to the enclosing cleanup
Craig Topper8a13c412014-05-21 05:09:00 +0000812 llvm::BasicBlock *BranchThroughDest = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000813 if (Scope.hasBranchThroughs() ||
814 (FallthroughSource && FallthroughIsBranchThrough) ||
815 (HasFixups && HasEnclosingCleanups)) {
816 assert(HasEnclosingCleanups);
817 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
818 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
819 }
820
Craig Topper8a13c412014-05-21 05:09:00 +0000821 llvm::BasicBlock *FallthroughDest = nullptr;
Benjamin Kramerc7497452015-02-17 16:53:08 +0000822 SmallVector<llvm::Instruction*, 2> InstsToAppend;
John McCalled1ae862011-01-28 11:13:47 +0000823
824 // If there's exactly one branch-after and no other threads,
825 // we can route it without a switch.
826 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
827 Scope.getNumBranchAfters() == 1) {
828 assert(!BranchThroughDest || !IsActive);
829
David Majnemerdc012fa2015-04-22 21:38:15 +0000830 // Clean up the possibly dead store to the cleanup dest slot.
831 llvm::Instruction *NormalCleanupDestSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000832 cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
David Majnemerdc012fa2015-04-22 21:38:15 +0000833 if (NormalCleanupDestSlot->hasOneUse()) {
834 NormalCleanupDestSlot->user_back()->eraseFromParent();
835 NormalCleanupDestSlot->eraseFromParent();
836 NormalCleanupDest = nullptr;
837 }
838
John McCalled1ae862011-01-28 11:13:47 +0000839 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
840 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
841
842 // Build a switch-out if we need it:
843 // - if there are branch-afters threaded through the scope
844 // - if fall-through is a branch-after
845 // - if there are fixups that have nowhere left to go and
846 // so must be immediately resolved
847 } else if (Scope.getNumBranchAfters() ||
848 (HasFallthrough && !FallthroughIsBranchThrough) ||
849 (HasFixups && !HasEnclosingCleanups)) {
850
851 llvm::BasicBlock *Default =
852 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
853
854 // TODO: base this on the number of branch-afters and fixups
855 const unsigned SwitchCapacity = 10;
856
857 llvm::LoadInst *Load =
John McCall7f416cc2015-09-08 08:05:57 +0000858 createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
859 nullptr);
John McCalled1ae862011-01-28 11:13:47 +0000860 llvm::SwitchInst *Switch =
861 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
862
863 InstsToAppend.push_back(Load);
864 InstsToAppend.push_back(Switch);
865
866 // Branch-after fallthrough.
867 if (FallthroughSource && !FallthroughIsBranchThrough) {
868 FallthroughDest = createBasicBlock("cleanup.cont");
869 if (HasFallthrough)
870 Switch->addCase(Builder.getInt32(0), FallthroughDest);
871 }
872
873 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
874 Switch->addCase(Scope.getBranchAfterIndex(I),
875 Scope.getBranchAfterBlock(I));
876 }
877
878 // If there aren't any enclosing cleanups, we can resolve all
879 // the fixups now.
880 if (HasFixups && !HasEnclosingCleanups)
881 ResolveAllBranchFixups(*this, Switch, NormalEntry);
882 } else {
883 // We should always have a branch-through destination in this case.
884 assert(BranchThroughDest);
885 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
886 }
887
888 // IV. Pop the cleanup and emit it.
889 EHStack.popCleanup();
890 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
891
John McCall30317fd2011-07-12 20:27:29 +0000892 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000893
894 // Append the prepared cleanup prologue from above.
895 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
Benjamin Kramerc7497452015-02-17 16:53:08 +0000896 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
897 NormalExit->getInstList().push_back(InstsToAppend[I]);
John McCalled1ae862011-01-28 11:13:47 +0000898
899 // Optimistically hope that any fixups will continue falling through.
900 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
901 I < E; ++I) {
John McCallad7c5c12011-02-08 08:22:06 +0000902 BranchFixup &Fixup = EHStack.getBranchFixup(I);
John McCalled1ae862011-01-28 11:13:47 +0000903 if (!Fixup.Destination) continue;
904 if (!Fixup.OptimisticBranchBlock) {
John McCall7f416cc2015-09-08 08:05:57 +0000905 createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
906 getNormalCleanupDestSlot(),
907 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000908 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
909 }
910 Fixup.OptimisticBranchBlock = NormalExit;
911 }
912
913 // V. Set up the fallthrough edge out.
914
John McCall45e42952011-08-07 07:05:57 +0000915 // Case 1: a fallthrough source exists but doesn't branch to the
916 // cleanup because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000917 if (!HasFallthrough && FallthroughSource) {
John McCall45e42952011-08-07 07:05:57 +0000918 // Prebranched fallthrough was forwarded earlier.
919 // Non-prebranched fallthrough doesn't need to be forwarded.
920 // Either way, all we need to do is restore the IP we cleared before.
John McCalled1ae862011-01-28 11:13:47 +0000921 assert(!IsActive);
John McCall45e42952011-08-07 07:05:57 +0000922 Builder.restoreIP(savedInactiveFallthroughIP);
John McCalled1ae862011-01-28 11:13:47 +0000923
924 // Case 2: a fallthrough source exists and should branch to the
925 // cleanup, but we're not supposed to branch through to the next
926 // cleanup.
927 } else if (HasFallthrough && FallthroughDest) {
928 assert(!FallthroughIsBranchThrough);
929 EmitBlock(FallthroughDest);
930
931 // Case 3: a fallthrough source exists and should branch to the
932 // cleanup and then through to the next.
933 } else if (HasFallthrough) {
934 // Everything is already set up for this.
935
936 // Case 4: no fallthrough source exists.
937 } else {
938 Builder.ClearInsertionPoint();
939 }
940
941 // VI. Assorted cleaning.
942
943 // Check whether we can merge NormalEntry into a single predecessor.
944 // This might invalidate (non-IR) pointers to NormalEntry.
945 llvm::BasicBlock *NewNormalEntry =
946 SimplifyCleanupEntry(*this, NormalEntry);
947
948 // If it did invalidate those pointers, and NormalEntry was the same
949 // as NormalExit, go back and patch up the fixups.
950 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
951 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
952 I < E; ++I)
John McCallad7c5c12011-02-08 08:22:06 +0000953 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCalled1ae862011-01-28 11:13:47 +0000954 }
955 }
956
957 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
958
959 // Emit the EH cleanup if required.
960 if (RequiresEHCleanup) {
961 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
962
963 EmitBlock(EHEntry);
Reid Kleckner55391522015-10-08 21:14:56 +0000964
Reid Klecknera002bd52015-10-28 23:06:42 +0000965 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
966
967 // Push a terminate scope or cleanupendpad scope around the potentially
968 // throwing cleanups. For funclet EH personalities, the cleanupendpad models
969 // program termination when cleanups throw.
Reid Kleckner55391522015-10-08 21:14:56 +0000970 bool PushedTerminate = false;
David Majnemer4e52d6f2015-12-12 05:39:21 +0000971 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
972 CurrentFuncletPad);
Reid Klecknera002bd52015-10-28 23:06:42 +0000973 llvm::CleanupPadInst *CPI = nullptr;
Reid Kleckner55391522015-10-08 21:14:56 +0000974 if (!EHPersonality::get(*this).usesFuncletPads()) {
975 EHStack.pushTerminate();
976 PushedTerminate = true;
Reid Klecknera002bd52015-10-28 23:06:42 +0000977 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000978 llvm::Value *ParentPad = CurrentFuncletPad;
979 if (!ParentPad)
980 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
981 CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
Reid Kleckner55391522015-10-08 21:14:56 +0000982 }
983
Eli Friedmanabab7762012-08-02 00:10:24 +0000984 // We only actually emit the cleanup code if the cleanup is either
985 // active or was used before it was deactivated.
John McCall7f416cc2015-09-08 08:05:57 +0000986 if (EHActiveFlag.isValid() || IsActive) {
Eli Friedmanabab7762012-08-02 00:10:24 +0000987 cleanupFlags.setIsForEHCleanup();
988 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
989 }
John McCalled1ae862011-01-28 11:13:47 +0000990
David Majnemere888a2f2015-08-15 03:21:08 +0000991 if (CPI)
Joseph Tremouletce536a52015-08-23 00:26:48 +0000992 Builder.CreateCleanupRet(CPI, NextAction);
David Majnemerdbf10452015-07-31 17:58:45 +0000993 else
994 Builder.CreateBr(NextAction);
John McCalled1ae862011-01-28 11:13:47 +0000995
Reid Kleckner55391522015-10-08 21:14:56 +0000996 // Leave the terminate scope.
997 if (PushedTerminate)
998 EHStack.popTerminate();
999
John McCalled1ae862011-01-28 11:13:47 +00001000 Builder.restoreIP(SavedIP);
1001
1002 SimplifyCleanupEntry(*this, EHEntry);
1003 }
1004}
1005
Justin Bognere25ffdf2014-01-21 00:35:11 +00001006/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1007/// specified destination obviously has no cleanups to run. 'false' is always
1008/// a conservatively correct answer for this method.
1009bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
1010 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1011 && "stale jump destination");
1012
1013 // Calculate the innermost active normal cleanup.
1014 EHScopeStack::stable_iterator TopCleanup =
1015 EHStack.getInnermostActiveNormalCleanup();
1016
1017 // If we're not in an active normal cleanup scope, or if the
1018 // destination scope is within the innermost active normal cleanup
1019 // scope, we don't need to worry about fixups.
1020 if (TopCleanup == EHStack.stable_end() ||
1021 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
1022 return true;
1023
1024 // Otherwise, we might need some cleanups.
1025 return false;
1026}
1027
1028
John McCalled1ae862011-01-28 11:13:47 +00001029/// Terminate the current block by emitting a branch which might leave
1030/// the current cleanup-protected scope. The target scope may not yet
1031/// be known, in which case this will require a fixup.
1032///
1033/// As a side-effect, this method clears the insertion point.
1034void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall1b93f1b2011-02-25 04:19:13 +00001035 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
John McCalled1ae862011-01-28 11:13:47 +00001036 && "stale jump destination");
1037
1038 if (!HaveInsertPoint())
1039 return;
1040
1041 // Create the branch.
1042 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1043
1044 // Calculate the innermost active normal cleanup.
1045 EHScopeStack::stable_iterator
1046 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1047
1048 // If we're not in an active normal cleanup scope, or if the
1049 // destination scope is within the innermost active normal cleanup
1050 // scope, we don't need to worry about fixups.
1051 if (TopCleanup == EHStack.stable_end() ||
1052 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
1053 Builder.ClearInsertionPoint();
1054 return;
1055 }
1056
1057 // If we can't resolve the destination cleanup scope, just add this
1058 // to the current cleanup scope as a branch fixup.
1059 if (!Dest.getScopeDepth().isValid()) {
1060 BranchFixup &Fixup = EHStack.addBranchFixup();
1061 Fixup.Destination = Dest.getBlock();
1062 Fixup.DestinationIndex = Dest.getDestIndex();
1063 Fixup.InitialBranch = BI;
Craig Topper8a13c412014-05-21 05:09:00 +00001064 Fixup.OptimisticBranchBlock = nullptr;
John McCalled1ae862011-01-28 11:13:47 +00001065
1066 Builder.ClearInsertionPoint();
1067 return;
1068 }
1069
1070 // Otherwise, thread through all the normal cleanups in scope.
1071
1072 // Store the index at the start.
1073 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
John McCall7f416cc2015-09-08 08:05:57 +00001074 createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
John McCalled1ae862011-01-28 11:13:47 +00001075
1076 // Adjust BI to point to the first cleanup block.
1077 {
1078 EHCleanupScope &Scope =
1079 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1080 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1081 }
1082
1083 // Add this destination to all the scopes involved.
1084 EHScopeStack::stable_iterator I = TopCleanup;
1085 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1086 if (E.strictlyEncloses(I)) {
1087 while (true) {
1088 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1089 assert(Scope.isNormalCleanup());
1090 I = Scope.getEnclosingNormalCleanup();
1091
1092 // If this is the last cleanup we're propagating through, tell it
1093 // that there's a resolved jump moving through it.
1094 if (!E.strictlyEncloses(I)) {
1095 Scope.addBranchAfter(Index, Dest.getBlock());
1096 break;
1097 }
1098
Nico Weber524ae442017-08-25 18:41:41 +00001099 // Otherwise, tell the scope that there's a jump propagating
John McCalled1ae862011-01-28 11:13:47 +00001100 // through it. If this isn't new information, all the rest of
1101 // the work has been done before.
1102 if (!Scope.addBranchThrough(Dest.getBlock()))
1103 break;
1104 }
1105 }
1106
1107 Builder.ClearInsertionPoint();
1108}
1109
John McCalled1ae862011-01-28 11:13:47 +00001110static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1111 EHScopeStack::stable_iterator C) {
1112 // If we needed a normal block for any reason, that counts.
1113 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1114 return true;
1115
1116 // Check whether any enclosed cleanups were needed.
1117 for (EHScopeStack::stable_iterator
1118 I = EHStack.getInnermostNormalCleanup();
1119 I != C; ) {
1120 assert(C.strictlyEncloses(I));
1121 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1122 if (S.getNormalBlock()) return true;
1123 I = S.getEnclosingNormalCleanup();
1124 }
1125
1126 return false;
1127}
1128
1129static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
John McCall8e4c74b2011-08-11 02:22:43 +00001130 EHScopeStack::stable_iterator cleanup) {
John McCalled1ae862011-01-28 11:13:47 +00001131 // If we needed an EH block for any reason, that counts.
John McCall8e4c74b2011-08-11 02:22:43 +00001132 if (EHStack.find(cleanup)->hasEHBranches())
John McCalled1ae862011-01-28 11:13:47 +00001133 return true;
1134
1135 // Check whether any enclosed cleanups were needed.
1136 for (EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +00001137 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1138 assert(cleanup.strictlyEncloses(i));
1139
1140 EHScope &scope = *EHStack.find(i);
1141 if (scope.hasEHBranches())
1142 return true;
1143
1144 i = scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +00001145 }
1146
1147 return false;
1148}
1149
1150enum ForActivation_t {
1151 ForActivation,
1152 ForDeactivation
1153};
1154
1155/// The given cleanup block is changing activation state. Configure a
1156/// cleanup variable if necessary.
1157///
1158/// It would be good if we had some way of determining if there were
1159/// extra uses *after* the change-over point.
1160static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1161 EHScopeStack::stable_iterator C,
John McCallf4beacd2011-11-10 10:43:54 +00001162 ForActivation_t kind,
1163 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001164 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1165
John McCalle63abb52011-11-10 09:22:44 +00001166 // We always need the flag if we're activating the cleanup in a
1167 // conditional context, because we have to assume that the current
1168 // location doesn't necessarily dominate the cleanup's code.
1169 bool isActivatedInConditional =
John McCallf4beacd2011-11-10 10:43:54 +00001170 (kind == ForActivation && CGF.isInConditionalBranch());
John McCalle63abb52011-11-10 09:22:44 +00001171
1172 bool needFlag = false;
John McCalled1ae862011-01-28 11:13:47 +00001173
1174 // Calculate whether the cleanup was used:
1175
1176 // - as a normal cleanup
John McCalle63abb52011-11-10 09:22:44 +00001177 if (Scope.isNormalCleanup() &&
1178 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001179 Scope.setTestFlagInNormalCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001180 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001181 }
1182
1183 // - as an EH cleanup
John McCalle63abb52011-11-10 09:22:44 +00001184 if (Scope.isEHCleanup() &&
1185 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001186 Scope.setTestFlagInEHCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001187 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001188 }
1189
1190 // If it hasn't yet been used as either, we're done.
John McCalle63abb52011-11-10 09:22:44 +00001191 if (!needFlag) return;
John McCalled1ae862011-01-28 11:13:47 +00001192
John McCall7f416cc2015-09-08 08:05:57 +00001193 Address var = Scope.getActiveFlag();
1194 if (!var.isValid()) {
1195 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1196 "cleanup.isactive");
John McCallf4beacd2011-11-10 10:43:54 +00001197 Scope.setActiveFlag(var);
1198
1199 assert(dominatingIP && "no existing variable and no dominating IP!");
John McCalled1ae862011-01-28 11:13:47 +00001200
1201 // Initialize to true or false depending on whether it was
1202 // active up to this point.
John McCall7f416cc2015-09-08 08:05:57 +00001203 llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
John McCallf4beacd2011-11-10 10:43:54 +00001204
1205 // If we're in a conditional block, ignore the dominating IP and
1206 // use the outermost conditional branch.
1207 if (CGF.isInConditionalBranch()) {
1208 CGF.setBeforeOutermostConditional(value, var);
1209 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001210 createStoreInstBefore(value, var, dominatingIP);
John McCallf4beacd2011-11-10 10:43:54 +00001211 }
John McCalled1ae862011-01-28 11:13:47 +00001212 }
1213
John McCallf4beacd2011-11-10 10:43:54 +00001214 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
John McCalled1ae862011-01-28 11:13:47 +00001215}
1216
1217/// Activate a cleanup that was created in an inactivated state.
John McCallf4beacd2011-11-10 10:43:54 +00001218void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1219 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001220 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1221 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1222 assert(!Scope.isActive() && "double activation");
1223
John McCallf4beacd2011-11-10 10:43:54 +00001224 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001225
1226 Scope.setActive(true);
1227}
1228
1229/// Deactive a cleanup that was created in an active state.
John McCallf4beacd2011-11-10 10:43:54 +00001230void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1231 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001232 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1233 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1234 assert(Scope.isActive() && "double deactivation");
1235
1236 // If it's the top of the stack, just pop it.
1237 if (C == EHStack.stable_begin()) {
1238 // If it's a normal cleanup, we need to pretend that the
1239 // fallthrough is unreachable.
1240 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1241 PopCleanupBlock();
1242 Builder.restoreIP(SavedIP);
1243 return;
1244 }
1245
1246 // Otherwise, follow the general case.
John McCallf4beacd2011-11-10 10:43:54 +00001247 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001248
1249 Scope.setActive(false);
1250}
1251
John McCall7f416cc2015-09-08 08:05:57 +00001252Address CodeGenFunction::getNormalCleanupDestSlot() {
John McCalled1ae862011-01-28 11:13:47 +00001253 if (!NormalCleanupDest)
1254 NormalCleanupDest =
1255 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
John McCall7f416cc2015-09-08 08:05:57 +00001256 return Address(NormalCleanupDest, CharUnits::fromQuantity(4));
John McCalled1ae862011-01-28 11:13:47 +00001257}
Peter Collingbourne702b2842011-11-27 22:09:22 +00001258
1259/// Emits all the code to cause the given temporary to be cleaned up.
1260void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1261 QualType TempType,
John McCall7f416cc2015-09-08 08:05:57 +00001262 Address Ptr) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001263 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
Peter Collingbourne702b2842011-11-27 22:09:22 +00001264 /*useEHCleanup*/ true);
1265}