blob: 12c587ee95afc724f71527ffe41b592186a40512 [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"
John McCalled1ae862011-01-28 11:13:47 +000022
23using namespace clang;
24using namespace CodeGen;
25
26bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
27 if (rv.isScalar())
28 return DominatingLLVMValue::needsSaving(rv.getScalarVal());
29 if (rv.isAggregate())
30 return DominatingLLVMValue::needsSaving(rv.getAggregateAddr());
31 return true;
32}
33
34DominatingValue<RValue>::saved_type
35DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
36 if (rv.isScalar()) {
37 llvm::Value *V = rv.getScalarVal();
38
39 // These automatically dominate and don't need to be saved.
40 if (!DominatingLLVMValue::needsSaving(V))
41 return saved_type(V, ScalarLiteral);
42
43 // Everything else needs an alloca.
44 llvm::Value *addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
45 CGF.Builder.CreateStore(V, addr);
46 return saved_type(addr, ScalarAddress);
47 }
48
49 if (rv.isComplex()) {
50 CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
Chris Lattner2192fe52011-07-18 04:24:23 +000051 llvm::Type *ComplexTy =
Chris Lattner845511f2011-06-18 22:49:11 +000052 llvm::StructType::get(V.first->getType(), V.second->getType(),
Craig Topper8a13c412014-05-21 05:09:00 +000053 (void*) nullptr);
John McCalled1ae862011-01-28 11:13:47 +000054 llvm::Value *addr = CGF.CreateTempAlloca(ComplexTy, "saved-complex");
John McCall47fb9502013-03-07 21:37:08 +000055 CGF.Builder.CreateStore(V.first, CGF.Builder.CreateStructGEP(addr, 0));
56 CGF.Builder.CreateStore(V.second, CGF.Builder.CreateStructGEP(addr, 1));
John McCalled1ae862011-01-28 11:13:47 +000057 return saved_type(addr, ComplexAddress);
58 }
59
60 assert(rv.isAggregate());
61 llvm::Value *V = rv.getAggregateAddr(); // TODO: volatile?
62 if (!DominatingLLVMValue::needsSaving(V))
63 return saved_type(V, AggregateLiteral);
64
65 llvm::Value *addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
66 CGF.Builder.CreateStore(V, addr);
67 return saved_type(addr, AggregateAddress);
68}
69
70/// Given a saved r-value produced by SaveRValue, perform the code
71/// necessary to restore it to usability at the current insertion
72/// point.
73RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
74 switch (K) {
75 case ScalarLiteral:
76 return RValue::get(Value);
77 case ScalarAddress:
78 return RValue::get(CGF.Builder.CreateLoad(Value));
79 case AggregateLiteral:
80 return RValue::getAggregate(Value);
81 case AggregateAddress:
82 return RValue::getAggregate(CGF.Builder.CreateLoad(Value));
John McCall47fb9502013-03-07 21:37:08 +000083 case ComplexAddress: {
84 llvm::Value *real =
85 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(Value, 0));
86 llvm::Value *imag =
87 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(Value, 1));
88 return RValue::getComplex(real, imag);
89 }
John McCalled1ae862011-01-28 11:13:47 +000090 }
91
92 llvm_unreachable("bad saved r-value kind");
John McCalled1ae862011-01-28 11:13:47 +000093}
94
95/// Push an entry of the given size onto this protected-scope stack.
96char *EHScopeStack::allocate(size_t Size) {
97 if (!StartOfBuffer) {
98 unsigned Capacity = 1024;
99 while (Capacity < Size) Capacity *= 2;
100 StartOfBuffer = new char[Capacity];
101 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
102 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
103 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
104 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
105
106 unsigned NewCapacity = CurrentCapacity;
107 do {
108 NewCapacity *= 2;
109 } while (NewCapacity < UsedCapacity + Size);
110
111 char *NewStartOfBuffer = new char[NewCapacity];
112 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
113 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
114 memcpy(NewStartOfData, StartOfData, UsedCapacity);
115 delete [] StartOfBuffer;
116 StartOfBuffer = NewStartOfBuffer;
117 EndOfBuffer = NewEndOfBuffer;
118 StartOfData = NewStartOfData;
119 }
120
121 assert(StartOfBuffer + Size <= StartOfData);
122 StartOfData -= Size;
123 return StartOfData;
124}
125
126EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +0000127EHScopeStack::getInnermostActiveNormalCleanup() const {
128 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
129 si != se; ) {
130 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
131 if (cleanup.isActive()) return si;
132 si = cleanup.getEnclosingNormalCleanup();
133 }
134 return stable_end();
135}
136
137EHScopeStack::stable_iterator EHScopeStack::getInnermostActiveEHScope() const {
138 for (stable_iterator si = getInnermostEHScope(), se = stable_end();
139 si != se; ) {
140 // Skip over inactive cleanups.
141 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*find(si));
142 if (cleanup && !cleanup->isActive()) {
143 si = cleanup->getEnclosingEHScope();
144 continue;
John McCalled1ae862011-01-28 11:13:47 +0000145 }
John McCall8e4c74b2011-08-11 02:22:43 +0000146
147 // All other scopes are always active.
148 return si;
149 }
150
John McCalled1ae862011-01-28 11:13:47 +0000151 return stable_end();
152}
153
154
155void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
156 assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
157 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
158 bool IsNormalCleanup = Kind & NormalCleanup;
159 bool IsEHCleanup = Kind & EHCleanup;
160 bool IsActive = !(Kind & InactiveCleanup);
161 EHCleanupScope *Scope =
162 new (Buffer) EHCleanupScope(IsNormalCleanup,
163 IsEHCleanup,
164 IsActive,
165 Size,
166 BranchFixups.size(),
167 InnermostNormalCleanup,
John McCall8e4c74b2011-08-11 02:22:43 +0000168 InnermostEHScope);
John McCalled1ae862011-01-28 11:13:47 +0000169 if (IsNormalCleanup)
170 InnermostNormalCleanup = stable_begin();
171 if (IsEHCleanup)
John McCall8e4c74b2011-08-11 02:22:43 +0000172 InnermostEHScope = stable_begin();
John McCalled1ae862011-01-28 11:13:47 +0000173
174 return Scope->getCleanupBuffer();
175}
176
177void EHScopeStack::popCleanup() {
178 assert(!empty() && "popping exception stack when not empty");
179
180 assert(isa<EHCleanupScope>(*begin()));
181 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
182 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
John McCall8e4c74b2011-08-11 02:22:43 +0000183 InnermostEHScope = Cleanup.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000184 StartOfData += Cleanup.getAllocatedSize();
185
John McCalled1ae862011-01-28 11:13:47 +0000186 // Destroy the cleanup.
Kostya Serebryanyb21aa762014-10-08 18:31:54 +0000187 Cleanup.Destroy();
John McCalled1ae862011-01-28 11:13:47 +0000188
189 // Check whether we can shrink the branch-fixups stack.
190 if (!BranchFixups.empty()) {
191 // If we no longer have any normal cleanups, all the fixups are
192 // complete.
193 if (!hasNormalCleanups())
194 BranchFixups.clear();
195
196 // Otherwise we can still trim out unnecessary nulls.
197 else
198 popNullFixups();
199 }
200}
201
John McCall8e4c74b2011-08-11 02:22:43 +0000202EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
203 assert(getInnermostEHScope() == stable_end());
204 char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
205 EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
206 InnermostEHScope = stable_begin();
207 return filter;
John McCalled1ae862011-01-28 11:13:47 +0000208}
209
210void EHScopeStack::popFilter() {
211 assert(!empty() && "popping exception stack when not empty");
212
John McCall8e4c74b2011-08-11 02:22:43 +0000213 EHFilterScope &filter = cast<EHFilterScope>(*begin());
214 StartOfData += EHFilterScope::getSizeForNumFilters(filter.getNumFilters());
John McCalled1ae862011-01-28 11:13:47 +0000215
John McCall8e4c74b2011-08-11 02:22:43 +0000216 InnermostEHScope = filter.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000217}
218
John McCall8e4c74b2011-08-11 02:22:43 +0000219EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
220 char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
221 EHCatchScope *scope =
222 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
223 InnermostEHScope = stable_begin();
224 return scope;
John McCalled1ae862011-01-28 11:13:47 +0000225}
226
227void EHScopeStack::pushTerminate() {
228 char *Buffer = allocate(EHTerminateScope::getSize());
John McCall8e4c74b2011-08-11 02:22:43 +0000229 new (Buffer) EHTerminateScope(InnermostEHScope);
230 InnermostEHScope = stable_begin();
John McCalled1ae862011-01-28 11:13:47 +0000231}
232
233/// Remove any 'null' fixups on the stack. However, we can't pop more
234/// fixups than the fixup depth on the innermost normal cleanup, or
235/// else fixups that we try to add to that cleanup will end up in the
236/// wrong place. We *could* try to shrink fixup depths, but that's
237/// actually a lot of work for little benefit.
238void EHScopeStack::popNullFixups() {
239 // We expect this to only be called when there's still an innermost
240 // normal cleanup; otherwise there really shouldn't be any fixups.
241 assert(hasNormalCleanups());
242
243 EHScopeStack::iterator it = find(InnermostNormalCleanup);
244 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
245 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
246
247 while (BranchFixups.size() > MinSize &&
Craig Topper8a13c412014-05-21 05:09:00 +0000248 BranchFixups.back().Destination == nullptr)
John McCalled1ae862011-01-28 11:13:47 +0000249 BranchFixups.pop_back();
250}
251
252void CodeGenFunction::initFullExprCleanup() {
253 // Create a variable to decide whether the cleanup needs to be run.
254 llvm::AllocaInst *active
255 = CreateTempAlloca(Builder.getInt1Ty(), "cleanup.cond");
256
257 // Initialize it to false at a site that's guaranteed to be run
258 // before each evaluation.
John McCallf4beacd2011-11-10 10:43:54 +0000259 setBeforeOutermostConditional(Builder.getFalse(), active);
John McCalled1ae862011-01-28 11:13:47 +0000260
261 // Initialize it to true at the current location.
262 Builder.CreateStore(Builder.getTrue(), active);
263
264 // Set that as the active flag in the cleanup.
265 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
Craig Topper8a13c412014-05-21 05:09:00 +0000266 assert(!cleanup.getActiveFlag() && "cleanup already has active flag?");
John McCalled1ae862011-01-28 11:13:47 +0000267 cleanup.setActiveFlag(active);
268
269 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
270 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
271}
272
John McCall5fcf8da2011-07-12 00:15:30 +0000273void EHScopeStack::Cleanup::anchor() {}
John McCalled1ae862011-01-28 11:13:47 +0000274
275/// All the branch fixups on the EH stack have propagated out past the
276/// outermost normal cleanup; resolve them all by adding cases to the
277/// given switch instruction.
278static void ResolveAllBranchFixups(CodeGenFunction &CGF,
279 llvm::SwitchInst *Switch,
280 llvm::BasicBlock *CleanupEntry) {
281 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
282
283 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
284 // Skip this fixup if its destination isn't set.
285 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
Craig Topper8a13c412014-05-21 05:09:00 +0000286 if (Fixup.Destination == nullptr) continue;
John McCalled1ae862011-01-28 11:13:47 +0000287
288 // If there isn't an OptimisticBranchBlock, then InitialBranch is
289 // still pointing directly to its destination; forward it to the
290 // appropriate cleanup entry. This is required in the specific
291 // case of
292 // { std::string s; goto lbl; }
293 // lbl:
294 // i.e. where there's an unresolved fixup inside a single cleanup
295 // entry which we're currently popping.
Craig Topper8a13c412014-05-21 05:09:00 +0000296 if (Fixup.OptimisticBranchBlock == nullptr) {
John McCalled1ae862011-01-28 11:13:47 +0000297 new llvm::StoreInst(CGF.Builder.getInt32(Fixup.DestinationIndex),
298 CGF.getNormalCleanupDestSlot(),
299 Fixup.InitialBranch);
300 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
301 }
302
303 // Don't add this case to the switch statement twice.
304 if (!CasesAdded.insert(Fixup.Destination)) continue;
305
306 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
307 Fixup.Destination);
308 }
309
310 CGF.EHStack.clearFixups();
311}
312
313/// Transitions the terminator of the given exit-block of a cleanup to
314/// be a cleanup switch.
315static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
316 llvm::BasicBlock *Block) {
317 // If it's a branch, turn it into a switch whose default
318 // destination is its original target.
319 llvm::TerminatorInst *Term = Block->getTerminator();
320 assert(Term && "can't transition block without terminator");
321
322 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
323 assert(Br->isUnconditional());
324 llvm::LoadInst *Load =
325 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
326 llvm::SwitchInst *Switch =
327 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
328 Br->eraseFromParent();
329 return Switch;
330 } else {
331 return cast<llvm::SwitchInst>(Term);
332 }
333}
334
335void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
336 assert(Block && "resolving a null target block");
337 if (!EHStack.getNumBranchFixups()) return;
338
339 assert(EHStack.hasNormalCleanups() &&
340 "branch fixups exist with no normal cleanups on stack");
341
342 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
343 bool ResolvedAny = false;
344
345 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
346 // Skip this fixup if its destination doesn't match.
347 BranchFixup &Fixup = EHStack.getBranchFixup(I);
348 if (Fixup.Destination != Block) continue;
349
Craig Topper8a13c412014-05-21 05:09:00 +0000350 Fixup.Destination = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000351 ResolvedAny = true;
352
353 // If it doesn't have an optimistic branch block, LatestBranch is
354 // already pointing to the right place.
355 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
356 if (!BranchBB)
357 continue;
358
359 // Don't process the same optimistic branch block twice.
360 if (!ModifiedOptimisticBlocks.insert(BranchBB))
361 continue;
362
363 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
364
365 // Add a case to the switch.
366 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
367 }
368
369 if (ResolvedAny)
370 EHStack.popNullFixups();
371}
372
373/// Pops cleanup blocks until the given savepoint is reached.
Adrian Prantldc237b52013-05-16 00:41:26 +0000374void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
John McCalled1ae862011-01-28 11:13:47 +0000375 assert(Old.isValid());
376
377 while (EHStack.stable_begin() != Old) {
378 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
379
380 // As long as Old strictly encloses the scope's enclosing normal
381 // cleanup, we're going to emit another normal cleanup which
382 // fallthrough can propagate through.
383 bool FallThroughIsBranchThrough =
384 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
385
Adrian Prantldc237b52013-05-16 00:41:26 +0000386 PopCleanupBlock(FallThroughIsBranchThrough);
John McCalled1ae862011-01-28 11:13:47 +0000387 }
388}
389
Arnaud A. de Grandmaison42d314d2014-10-02 12:19:51 +0000390/// Move our deferred cleanups onto the EH stack.
Richard Smith736a9472013-06-12 20:42:33 +0000391void
Arnaud A. de Grandmaison42d314d2014-10-02 12:19:51 +0000392CodeGenFunction::MoveDeferedCleanups(size_t OldLifetimeExtendedSize) {
Richard Smith736a9472013-06-12 20:42:33 +0000393 for (size_t I = OldLifetimeExtendedSize,
394 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
395 // Alignment should be guaranteed by the vptrs in the individual cleanups.
396 assert((I % llvm::alignOf<LifetimeExtendedCleanupHeader>() == 0) &&
397 "misaligned cleanup stack entry");
398
399 LifetimeExtendedCleanupHeader &Header =
400 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
401 LifetimeExtendedCleanupStack[I]);
402 I += sizeof(Header);
403
404 EHStack.pushCopyOfCleanup(Header.getKind(),
405 &LifetimeExtendedCleanupStack[I],
406 Header.getSize());
407 I += Header.getSize();
408 }
409 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
410}
411
Arnaud A. de Grandmaison42d314d2014-10-02 12:19:51 +0000412/// Pops cleanup blocks until the given savepoint is reached, then add the
413/// cleanups from the given savepoint in the lifetime-extended cleanups stack.
414void
415CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old,
416 size_t OldLifetimeExtendedSize) {
417 PopCleanupBlocks(Old);
418
419 // Move our deferred cleanups onto the EH stack.
420 MoveDeferedCleanups(OldLifetimeExtendedSize);
421}
422
John McCalled1ae862011-01-28 11:13:47 +0000423static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
424 EHCleanupScope &Scope) {
425 assert(Scope.isNormalCleanup());
426 llvm::BasicBlock *Entry = Scope.getNormalBlock();
427 if (!Entry) {
428 Entry = CGF.createBasicBlock("cleanup");
429 Scope.setNormalBlock(Entry);
430 }
431 return Entry;
432}
433
John McCalled1ae862011-01-28 11:13:47 +0000434/// Attempts to reduce a cleanup's entry block to a fallthrough. This
435/// is basically llvm::MergeBlockIntoPredecessor, except
436/// simplified/optimized for the tighter constraints on cleanup blocks.
437///
438/// Returns the new block, whatever it is.
439static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
440 llvm::BasicBlock *Entry) {
441 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
442 if (!Pred) return Entry;
443
444 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
445 if (!Br || Br->isConditional()) return Entry;
446 assert(Br->getSuccessor(0) == Entry);
447
448 // If we were previously inserting at the end of the cleanup entry
449 // block, we'll need to continue inserting at the end of the
450 // predecessor.
451 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
452 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
453
454 // Kill the branch.
455 Br->eraseFromParent();
456
John McCalled1ae862011-01-28 11:13:47 +0000457 // Replace all uses of the entry with the predecessor, in case there
458 // are phis in the cleanup.
459 Entry->replaceAllUsesWith(Pred);
460
Jay Foade03c05c2011-06-20 14:38:01 +0000461 // Merge the blocks.
462 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
463
John McCalled1ae862011-01-28 11:13:47 +0000464 // Kill the entry block.
465 Entry->eraseFromParent();
466
467 if (WasInsertBlock)
468 CGF.Builder.SetInsertPoint(Pred);
469
470 return Pred;
471}
472
473static void EmitCleanup(CodeGenFunction &CGF,
474 EHScopeStack::Cleanup *Fn,
John McCall30317fd2011-07-12 20:27:29 +0000475 EHScopeStack::Cleanup::Flags flags,
John McCalled1ae862011-01-28 11:13:47 +0000476 llvm::Value *ActiveFlag) {
477 // EH cleanups always occur within a terminate scope.
John McCall30317fd2011-07-12 20:27:29 +0000478 if (flags.isForEHCleanup()) CGF.EHStack.pushTerminate();
John McCalled1ae862011-01-28 11:13:47 +0000479
480 // If there's an active flag, load it and skip the cleanup if it's
481 // false.
Craig Topper8a13c412014-05-21 05:09:00 +0000482 llvm::BasicBlock *ContBB = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000483 if (ActiveFlag) {
484 ContBB = CGF.createBasicBlock("cleanup.done");
485 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
486 llvm::Value *IsActive
487 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
488 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
489 CGF.EmitBlock(CleanupBB);
490 }
491
492 // Ask the cleanup to emit itself.
John McCall30317fd2011-07-12 20:27:29 +0000493 Fn->Emit(CGF, flags);
John McCalled1ae862011-01-28 11:13:47 +0000494 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
495
496 // Emit the continuation block if there was an active flag.
497 if (ActiveFlag)
498 CGF.EmitBlock(ContBB);
499
500 // Leave the terminate scope.
John McCall30317fd2011-07-12 20:27:29 +0000501 if (flags.isForEHCleanup()) CGF.EHStack.popTerminate();
John McCalled1ae862011-01-28 11:13:47 +0000502}
503
504static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
505 llvm::BasicBlock *From,
506 llvm::BasicBlock *To) {
507 // Exit is the exit block of a cleanup, so it always terminates in
508 // an unconditional branch or a switch.
509 llvm::TerminatorInst *Term = Exit->getTerminator();
510
511 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
512 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
513 Br->setSuccessor(0, To);
514 } else {
515 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
516 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
517 if (Switch->getSuccessor(I) == From)
518 Switch->setSuccessor(I, To);
519 }
520}
521
John McCallf82bdf62011-08-06 06:53:52 +0000522/// We don't need a normal entry block for the given cleanup.
523/// Optimistic fixup branches can cause these blocks to come into
524/// existence anyway; if so, destroy it.
525///
526/// The validity of this transformation is very much specific to the
527/// exact ways in which we form branches to cleanup entries.
528static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
529 EHCleanupScope &scope) {
530 llvm::BasicBlock *entry = scope.getNormalBlock();
531 if (!entry) return;
532
533 // Replace all the uses with unreachable.
534 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
535 for (llvm::BasicBlock::use_iterator
536 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000537 llvm::Use &use = *i;
John McCallf82bdf62011-08-06 06:53:52 +0000538 ++i;
539
540 use.set(unreachableBB);
541
542 // The only uses should be fixup switches.
543 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
Stepan Dyatkovskiy5fecf5442012-02-01 07:50:21 +0000544 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
John McCallf82bdf62011-08-06 06:53:52 +0000545 // Replace the switch with a branch.
Stepan Dyatkovskiyfe3b0692012-03-11 06:09:37 +0000546 llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
John McCallf82bdf62011-08-06 06:53:52 +0000547
548 // The switch operand is a load from the cleanup-dest alloca.
549 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
550
551 // Destroy the switch.
552 si->eraseFromParent();
553
554 // Destroy the load.
555 assert(condition->getOperand(0) == CGF.NormalCleanupDest);
556 assert(condition->use_empty());
557 condition->eraseFromParent();
558 }
559 }
560
561 assert(entry->use_empty());
562 delete entry;
563}
564
John McCalled1ae862011-01-28 11:13:47 +0000565/// Pops a cleanup block. If the block includes a normal cleanup, the
566/// current insertion point is threaded through the cleanup, as are
567/// any branch fixups on the cleanup.
Adrian Prantldc237b52013-05-16 00:41:26 +0000568void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCalled1ae862011-01-28 11:13:47 +0000569 assert(!EHStack.empty() && "cleanup stack is empty!");
570 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
571 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
572 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
573
574 // Remember activation information.
575 bool IsActive = Scope.isActive();
576 llvm::Value *NormalActiveFlag =
Craig Topper8a13c412014-05-21 05:09:00 +0000577 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000578 llvm::Value *EHActiveFlag =
Craig Topper8a13c412014-05-21 05:09:00 +0000579 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000580
581 // Check whether we need an EH cleanup. This is only true if we've
582 // generated a lazy EH cleanup block.
John McCall8e4c74b2011-08-11 02:22:43 +0000583 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000584 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
585 bool RequiresEHCleanup = (EHEntry != nullptr);
John McCall8e4c74b2011-08-11 02:22:43 +0000586 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000587
588 // Check the three conditions which might require a normal cleanup:
589
590 // - whether there are branch fix-ups through this cleanup
591 unsigned FixupDepth = Scope.getFixupDepth();
592 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
593
594 // - whether there are branch-throughs or branch-afters
595 bool HasExistingBranches = Scope.hasBranches();
596
597 // - whether there's a fallthrough
598 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000599 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
John McCalled1ae862011-01-28 11:13:47 +0000600
601 // Branch-through fall-throughs leave the insertion point set to the
602 // end of the last cleanup, which points to the current scope. The
603 // rest of IR gen doesn't need to worry about this; it only happens
604 // during the execution of PopCleanupBlocks().
605 bool HasPrebranchedFallthrough =
606 (FallthroughSource && FallthroughSource->getTerminator());
607
608 // If this is a normal cleanup, then having a prebranched
609 // fallthrough implies that the fallthrough source unconditionally
610 // jumps here.
611 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
612 (Scope.getNormalBlock() &&
613 FallthroughSource->getTerminator()->getSuccessor(0)
614 == Scope.getNormalBlock()));
615
616 bool RequiresNormalCleanup = false;
617 if (Scope.isNormalCleanup() &&
618 (HasFixups || HasExistingBranches || HasFallthrough)) {
619 RequiresNormalCleanup = true;
620 }
621
John McCall45e42952011-08-07 07:05:57 +0000622 // If we have a prebranched fallthrough into an inactive normal
623 // cleanup, rewrite it so that it leads to the appropriate place.
624 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
625 llvm::BasicBlock *prebranchDest;
626
627 // If the prebranch is semantically branching through the next
628 // cleanup, just forward it to the next block, leaving the
629 // insertion point in the prebranched block.
John McCalled1ae862011-01-28 11:13:47 +0000630 if (FallthroughIsBranchThrough) {
John McCall45e42952011-08-07 07:05:57 +0000631 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
632 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
John McCalled1ae862011-01-28 11:13:47 +0000633
John McCall45e42952011-08-07 07:05:57 +0000634 // Otherwise, we need to make a new block. If the normal cleanup
635 // isn't being used at all, we could actually reuse the normal
636 // entry block, but this is simpler, and it avoids conflicts with
637 // dead optimistic fixup branches.
John McCalled1ae862011-01-28 11:13:47 +0000638 } else {
John McCall45e42952011-08-07 07:05:57 +0000639 prebranchDest = createBasicBlock("forwarded-prebranch");
640 EmitBlock(prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000641 }
John McCall45e42952011-08-07 07:05:57 +0000642
643 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
644 assert(normalEntry && !normalEntry->use_empty());
645
646 ForwardPrebranchedFallthrough(FallthroughSource,
647 normalEntry, prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000648 }
649
650 // If we don't need the cleanup at all, we're done.
651 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000652 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000653 EHStack.popCleanup(); // safe because there are no fixups
654 assert(EHStack.getNumBranchFixups() == 0 ||
655 EHStack.hasNormalCleanups());
656 return;
657 }
658
659 // Copy the cleanup emission data out. Note that SmallVector
660 // guarantees maximal alignment for its buffer regardless of its
661 // type parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000662 SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
John McCalled1ae862011-01-28 11:13:47 +0000663 CleanupBuffer.reserve(Scope.getCleanupSize());
664 memcpy(CleanupBuffer.data(),
665 Scope.getCleanupBuffer(), Scope.getCleanupSize());
666 CleanupBuffer.set_size(Scope.getCleanupSize());
667 EHScopeStack::Cleanup *Fn =
668 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
669
John McCall8e4c74b2011-08-11 02:22:43 +0000670 EHScopeStack::Cleanup::Flags cleanupFlags;
671 if (Scope.isNormalCleanup())
672 cleanupFlags.setIsNormalCleanupKind();
673 if (Scope.isEHCleanup())
674 cleanupFlags.setIsEHCleanupKind();
John McCalled1ae862011-01-28 11:13:47 +0000675
676 if (!RequiresNormalCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000677 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000678 EHStack.popCleanup();
679 } else {
680 // If we have a fallthrough and no other need for the cleanup,
681 // emit it directly.
682 if (HasFallthrough && !HasPrebranchedFallthrough &&
683 !HasFixups && !HasExistingBranches) {
684
John McCallf82bdf62011-08-06 06:53:52 +0000685 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000686 EHStack.popCleanup();
687
John McCall30317fd2011-07-12 20:27:29 +0000688 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000689
690 // Otherwise, the best approach is to thread everything through
691 // the cleanup block and then try to clean up after ourselves.
692 } else {
693 // Force the entry block to exist.
694 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
695
696 // I. Set up the fallthrough edge in.
697
John McCalla3654e32011-08-10 04:11:11 +0000698 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
John McCall45e42952011-08-07 07:05:57 +0000699
John McCalled1ae862011-01-28 11:13:47 +0000700 // If there's a fallthrough, we need to store the cleanup
701 // destination index. For fall-throughs this is always zero.
702 if (HasFallthrough) {
703 if (!HasPrebranchedFallthrough)
704 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
705
John McCall45e42952011-08-07 07:05:57 +0000706 // Otherwise, save and clear the IP if we don't have fallthrough
707 // because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000708 } else if (FallthroughSource) {
709 assert(!IsActive && "source without fallthrough for active cleanup");
John McCall45e42952011-08-07 07:05:57 +0000710 savedInactiveFallthroughIP = Builder.saveAndClearIP();
John McCalled1ae862011-01-28 11:13:47 +0000711 }
712
713 // II. Emit the entry block. This implicitly branches to it if
714 // we have fallthrough. All the fixups and existing branches
715 // should already be branched to it.
716 EmitBlock(NormalEntry);
717
718 // III. Figure out where we're going and build the cleanup
719 // epilogue.
720
721 bool HasEnclosingCleanups =
722 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
723
724 // Compute the branch-through dest if we need it:
725 // - if there are branch-throughs threaded through the scope
726 // - if fall-through is a branch-through
727 // - if there are fixups that will be optimistically forwarded
728 // to the enclosing cleanup
Craig Topper8a13c412014-05-21 05:09:00 +0000729 llvm::BasicBlock *BranchThroughDest = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000730 if (Scope.hasBranchThroughs() ||
731 (FallthroughSource && FallthroughIsBranchThrough) ||
732 (HasFixups && HasEnclosingCleanups)) {
733 assert(HasEnclosingCleanups);
734 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
735 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
736 }
737
Craig Topper8a13c412014-05-21 05:09:00 +0000738 llvm::BasicBlock *FallthroughDest = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000739 SmallVector<llvm::Instruction*, 2> InstsToAppend;
John McCalled1ae862011-01-28 11:13:47 +0000740
741 // If there's exactly one branch-after and no other threads,
742 // we can route it without a switch.
743 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
744 Scope.getNumBranchAfters() == 1) {
745 assert(!BranchThroughDest || !IsActive);
746
747 // TODO: clean up the possibly dead stores to the cleanup dest slot.
748 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
749 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
750
751 // Build a switch-out if we need it:
752 // - if there are branch-afters threaded through the scope
753 // - if fall-through is a branch-after
754 // - if there are fixups that have nowhere left to go and
755 // so must be immediately resolved
756 } else if (Scope.getNumBranchAfters() ||
757 (HasFallthrough && !FallthroughIsBranchThrough) ||
758 (HasFixups && !HasEnclosingCleanups)) {
759
760 llvm::BasicBlock *Default =
761 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
762
763 // TODO: base this on the number of branch-afters and fixups
764 const unsigned SwitchCapacity = 10;
765
766 llvm::LoadInst *Load =
767 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
768 llvm::SwitchInst *Switch =
769 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
770
771 InstsToAppend.push_back(Load);
772 InstsToAppend.push_back(Switch);
773
774 // Branch-after fallthrough.
775 if (FallthroughSource && !FallthroughIsBranchThrough) {
776 FallthroughDest = createBasicBlock("cleanup.cont");
777 if (HasFallthrough)
778 Switch->addCase(Builder.getInt32(0), FallthroughDest);
779 }
780
781 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
782 Switch->addCase(Scope.getBranchAfterIndex(I),
783 Scope.getBranchAfterBlock(I));
784 }
785
786 // If there aren't any enclosing cleanups, we can resolve all
787 // the fixups now.
788 if (HasFixups && !HasEnclosingCleanups)
789 ResolveAllBranchFixups(*this, Switch, NormalEntry);
790 } else {
791 // We should always have a branch-through destination in this case.
792 assert(BranchThroughDest);
793 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
794 }
795
796 // IV. Pop the cleanup and emit it.
797 EHStack.popCleanup();
798 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
799
John McCall30317fd2011-07-12 20:27:29 +0000800 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000801
802 // Append the prepared cleanup prologue from above.
803 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
804 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
805 NormalExit->getInstList().push_back(InstsToAppend[I]);
806
807 // Optimistically hope that any fixups will continue falling through.
808 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
809 I < E; ++I) {
John McCallad7c5c12011-02-08 08:22:06 +0000810 BranchFixup &Fixup = EHStack.getBranchFixup(I);
John McCalled1ae862011-01-28 11:13:47 +0000811 if (!Fixup.Destination) continue;
812 if (!Fixup.OptimisticBranchBlock) {
813 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
814 getNormalCleanupDestSlot(),
815 Fixup.InitialBranch);
816 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
817 }
818 Fixup.OptimisticBranchBlock = NormalExit;
819 }
820
821 // V. Set up the fallthrough edge out.
822
John McCall45e42952011-08-07 07:05:57 +0000823 // Case 1: a fallthrough source exists but doesn't branch to the
824 // cleanup because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000825 if (!HasFallthrough && FallthroughSource) {
John McCall45e42952011-08-07 07:05:57 +0000826 // Prebranched fallthrough was forwarded earlier.
827 // Non-prebranched fallthrough doesn't need to be forwarded.
828 // Either way, all we need to do is restore the IP we cleared before.
John McCalled1ae862011-01-28 11:13:47 +0000829 assert(!IsActive);
John McCall45e42952011-08-07 07:05:57 +0000830 Builder.restoreIP(savedInactiveFallthroughIP);
John McCalled1ae862011-01-28 11:13:47 +0000831
832 // Case 2: a fallthrough source exists and should branch to the
833 // cleanup, but we're not supposed to branch through to the next
834 // cleanup.
835 } else if (HasFallthrough && FallthroughDest) {
836 assert(!FallthroughIsBranchThrough);
837 EmitBlock(FallthroughDest);
838
839 // Case 3: a fallthrough source exists and should branch to the
840 // cleanup and then through to the next.
841 } else if (HasFallthrough) {
842 // Everything is already set up for this.
843
844 // Case 4: no fallthrough source exists.
845 } else {
846 Builder.ClearInsertionPoint();
847 }
848
849 // VI. Assorted cleaning.
850
851 // Check whether we can merge NormalEntry into a single predecessor.
852 // This might invalidate (non-IR) pointers to NormalEntry.
853 llvm::BasicBlock *NewNormalEntry =
854 SimplifyCleanupEntry(*this, NormalEntry);
855
856 // If it did invalidate those pointers, and NormalEntry was the same
857 // as NormalExit, go back and patch up the fixups.
858 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
859 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
860 I < E; ++I)
John McCallad7c5c12011-02-08 08:22:06 +0000861 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCalled1ae862011-01-28 11:13:47 +0000862 }
863 }
864
865 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
866
867 // Emit the EH cleanup if required.
868 if (RequiresEHCleanup) {
Adrian Prantld1b151e2014-01-17 00:15:10 +0000869 CGDebugInfo *DI = getDebugInfo();
870 SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
871 if (DI)
Adrian Prantldc237b52013-05-16 00:41:26 +0000872 DI->EmitLocation(Builder, CurEHLocation);
Adrian Prantl52bf3c42013-05-03 20:11:48 +0000873
John McCalled1ae862011-01-28 11:13:47 +0000874 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
875
876 EmitBlock(EHEntry);
John McCall30317fd2011-07-12 20:27:29 +0000877
Eli Friedmanabab7762012-08-02 00:10:24 +0000878 // We only actually emit the cleanup code if the cleanup is either
879 // active or was used before it was deactivated.
880 if (EHActiveFlag || IsActive) {
Adrian Prantl52bf3c42013-05-03 20:11:48 +0000881
Eli Friedmanabab7762012-08-02 00:10:24 +0000882 cleanupFlags.setIsForEHCleanup();
883 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
884 }
John McCalled1ae862011-01-28 11:13:47 +0000885
John McCall8e4c74b2011-08-11 02:22:43 +0000886 Builder.CreateBr(getEHDispatchBlock(EHParent));
John McCalled1ae862011-01-28 11:13:47 +0000887
888 Builder.restoreIP(SavedIP);
889
890 SimplifyCleanupEntry(*this, EHEntry);
891 }
892}
893
Justin Bognere25ffdf2014-01-21 00:35:11 +0000894/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
895/// specified destination obviously has no cleanups to run. 'false' is always
896/// a conservatively correct answer for this method.
897bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
898 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
899 && "stale jump destination");
900
901 // Calculate the innermost active normal cleanup.
902 EHScopeStack::stable_iterator TopCleanup =
903 EHStack.getInnermostActiveNormalCleanup();
904
905 // If we're not in an active normal cleanup scope, or if the
906 // destination scope is within the innermost active normal cleanup
907 // scope, we don't need to worry about fixups.
908 if (TopCleanup == EHStack.stable_end() ||
909 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
910 return true;
911
912 // Otherwise, we might need some cleanups.
913 return false;
914}
915
916
John McCalled1ae862011-01-28 11:13:47 +0000917/// Terminate the current block by emitting a branch which might leave
918/// the current cleanup-protected scope. The target scope may not yet
919/// be known, in which case this will require a fixup.
920///
921/// As a side-effect, this method clears the insertion point.
922void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall1b93f1b2011-02-25 04:19:13 +0000923 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
John McCalled1ae862011-01-28 11:13:47 +0000924 && "stale jump destination");
925
926 if (!HaveInsertPoint())
927 return;
928
929 // Create the branch.
930 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
931
932 // Calculate the innermost active normal cleanup.
933 EHScopeStack::stable_iterator
934 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
935
936 // If we're not in an active normal cleanup scope, or if the
937 // destination scope is within the innermost active normal cleanup
938 // scope, we don't need to worry about fixups.
939 if (TopCleanup == EHStack.stable_end() ||
940 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
941 Builder.ClearInsertionPoint();
942 return;
943 }
944
945 // If we can't resolve the destination cleanup scope, just add this
946 // to the current cleanup scope as a branch fixup.
947 if (!Dest.getScopeDepth().isValid()) {
948 BranchFixup &Fixup = EHStack.addBranchFixup();
949 Fixup.Destination = Dest.getBlock();
950 Fixup.DestinationIndex = Dest.getDestIndex();
951 Fixup.InitialBranch = BI;
Craig Topper8a13c412014-05-21 05:09:00 +0000952 Fixup.OptimisticBranchBlock = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000953
954 Builder.ClearInsertionPoint();
955 return;
956 }
957
958 // Otherwise, thread through all the normal cleanups in scope.
959
960 // Store the index at the start.
961 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
962 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
963
964 // Adjust BI to point to the first cleanup block.
965 {
966 EHCleanupScope &Scope =
967 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
968 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
969 }
970
971 // Add this destination to all the scopes involved.
972 EHScopeStack::stable_iterator I = TopCleanup;
973 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
974 if (E.strictlyEncloses(I)) {
975 while (true) {
976 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
977 assert(Scope.isNormalCleanup());
978 I = Scope.getEnclosingNormalCleanup();
979
980 // If this is the last cleanup we're propagating through, tell it
981 // that there's a resolved jump moving through it.
982 if (!E.strictlyEncloses(I)) {
983 Scope.addBranchAfter(Index, Dest.getBlock());
984 break;
985 }
986
987 // Otherwise, tell the scope that there's a jump propoagating
988 // through it. If this isn't new information, all the rest of
989 // the work has been done before.
990 if (!Scope.addBranchThrough(Dest.getBlock()))
991 break;
992 }
993 }
994
995 Builder.ClearInsertionPoint();
996}
997
John McCalled1ae862011-01-28 11:13:47 +0000998static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
999 EHScopeStack::stable_iterator C) {
1000 // If we needed a normal block for any reason, that counts.
1001 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1002 return true;
1003
1004 // Check whether any enclosed cleanups were needed.
1005 for (EHScopeStack::stable_iterator
1006 I = EHStack.getInnermostNormalCleanup();
1007 I != C; ) {
1008 assert(C.strictlyEncloses(I));
1009 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1010 if (S.getNormalBlock()) return true;
1011 I = S.getEnclosingNormalCleanup();
1012 }
1013
1014 return false;
1015}
1016
1017static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
John McCall8e4c74b2011-08-11 02:22:43 +00001018 EHScopeStack::stable_iterator cleanup) {
John McCalled1ae862011-01-28 11:13:47 +00001019 // If we needed an EH block for any reason, that counts.
John McCall8e4c74b2011-08-11 02:22:43 +00001020 if (EHStack.find(cleanup)->hasEHBranches())
John McCalled1ae862011-01-28 11:13:47 +00001021 return true;
1022
1023 // Check whether any enclosed cleanups were needed.
1024 for (EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +00001025 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1026 assert(cleanup.strictlyEncloses(i));
1027
1028 EHScope &scope = *EHStack.find(i);
1029 if (scope.hasEHBranches())
1030 return true;
1031
1032 i = scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +00001033 }
1034
1035 return false;
1036}
1037
1038enum ForActivation_t {
1039 ForActivation,
1040 ForDeactivation
1041};
1042
1043/// The given cleanup block is changing activation state. Configure a
1044/// cleanup variable if necessary.
1045///
1046/// It would be good if we had some way of determining if there were
1047/// extra uses *after* the change-over point.
1048static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1049 EHScopeStack::stable_iterator C,
John McCallf4beacd2011-11-10 10:43:54 +00001050 ForActivation_t kind,
1051 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001052 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1053
John McCalle63abb52011-11-10 09:22:44 +00001054 // We always need the flag if we're activating the cleanup in a
1055 // conditional context, because we have to assume that the current
1056 // location doesn't necessarily dominate the cleanup's code.
1057 bool isActivatedInConditional =
John McCallf4beacd2011-11-10 10:43:54 +00001058 (kind == ForActivation && CGF.isInConditionalBranch());
John McCalle63abb52011-11-10 09:22:44 +00001059
1060 bool needFlag = false;
John McCalled1ae862011-01-28 11:13:47 +00001061
1062 // Calculate whether the cleanup was used:
1063
1064 // - as a normal cleanup
John McCalle63abb52011-11-10 09:22:44 +00001065 if (Scope.isNormalCleanup() &&
1066 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001067 Scope.setTestFlagInNormalCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001068 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001069 }
1070
1071 // - as an EH cleanup
John McCalle63abb52011-11-10 09:22:44 +00001072 if (Scope.isEHCleanup() &&
1073 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001074 Scope.setTestFlagInEHCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001075 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001076 }
1077
1078 // If it hasn't yet been used as either, we're done.
John McCalle63abb52011-11-10 09:22:44 +00001079 if (!needFlag) return;
John McCalled1ae862011-01-28 11:13:47 +00001080
John McCallf4beacd2011-11-10 10:43:54 +00001081 llvm::AllocaInst *var = Scope.getActiveFlag();
1082 if (!var) {
1083 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactive");
1084 Scope.setActiveFlag(var);
1085
1086 assert(dominatingIP && "no existing variable and no dominating IP!");
John McCalled1ae862011-01-28 11:13:47 +00001087
1088 // Initialize to true or false depending on whether it was
1089 // active up to this point.
John McCallf4beacd2011-11-10 10:43:54 +00001090 llvm::Value *value = CGF.Builder.getInt1(kind == ForDeactivation);
1091
1092 // If we're in a conditional block, ignore the dominating IP and
1093 // use the outermost conditional branch.
1094 if (CGF.isInConditionalBranch()) {
1095 CGF.setBeforeOutermostConditional(value, var);
1096 } else {
1097 new llvm::StoreInst(value, var, dominatingIP);
1098 }
John McCalled1ae862011-01-28 11:13:47 +00001099 }
1100
John McCallf4beacd2011-11-10 10:43:54 +00001101 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
John McCalled1ae862011-01-28 11:13:47 +00001102}
1103
1104/// Activate a cleanup that was created in an inactivated state.
John McCallf4beacd2011-11-10 10:43:54 +00001105void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1106 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001107 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1108 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1109 assert(!Scope.isActive() && "double activation");
1110
John McCallf4beacd2011-11-10 10:43:54 +00001111 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001112
1113 Scope.setActive(true);
1114}
1115
1116/// Deactive a cleanup that was created in an active state.
John McCallf4beacd2011-11-10 10:43:54 +00001117void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1118 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001119 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1120 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1121 assert(Scope.isActive() && "double deactivation");
1122
1123 // If it's the top of the stack, just pop it.
1124 if (C == EHStack.stable_begin()) {
1125 // If it's a normal cleanup, we need to pretend that the
1126 // fallthrough is unreachable.
1127 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1128 PopCleanupBlock();
1129 Builder.restoreIP(SavedIP);
1130 return;
1131 }
1132
1133 // Otherwise, follow the general case.
John McCallf4beacd2011-11-10 10:43:54 +00001134 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001135
1136 Scope.setActive(false);
1137}
1138
1139llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1140 if (!NormalCleanupDest)
1141 NormalCleanupDest =
1142 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1143 return NormalCleanupDest;
1144}
Peter Collingbourne702b2842011-11-27 22:09:22 +00001145
1146/// Emits all the code to cause the given temporary to be cleaned up.
1147void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1148 QualType TempType,
1149 llvm::Value *Ptr) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001150 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
Peter Collingbourne702b2842011-11-27 22:09:22 +00001151 /*useEHCleanup*/ true);
1152}