blob: 5666a689af78d99638a8e651b920432c39e8b8dc [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");
David Blaikie1ed728c2015-04-05 22:45:47 +000055 CGF.Builder.CreateStore(V.first,
56 CGF.Builder.CreateStructGEP(ComplexTy, addr, 0));
57 CGF.Builder.CreateStore(V.second,
58 CGF.Builder.CreateStructGEP(ComplexTy, addr, 1));
John McCalled1ae862011-01-28 11:13:47 +000059 return saved_type(addr, ComplexAddress);
60 }
61
62 assert(rv.isAggregate());
63 llvm::Value *V = rv.getAggregateAddr(); // TODO: volatile?
64 if (!DominatingLLVMValue::needsSaving(V))
65 return saved_type(V, AggregateLiteral);
66
67 llvm::Value *addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
68 CGF.Builder.CreateStore(V, addr);
69 return saved_type(addr, AggregateAddress);
70}
71
72/// Given a saved r-value produced by SaveRValue, perform the code
73/// necessary to restore it to usability at the current insertion
74/// point.
75RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
76 switch (K) {
77 case ScalarLiteral:
78 return RValue::get(Value);
79 case ScalarAddress:
80 return RValue::get(CGF.Builder.CreateLoad(Value));
81 case AggregateLiteral:
82 return RValue::getAggregate(Value);
83 case AggregateAddress:
84 return RValue::getAggregate(CGF.Builder.CreateLoad(Value));
John McCall47fb9502013-03-07 21:37:08 +000085 case ComplexAddress: {
86 llvm::Value *real =
David Blaikie2e804282015-04-05 22:47:07 +000087 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(nullptr, Value, 0));
John McCall47fb9502013-03-07 21:37:08 +000088 llvm::Value *imag =
David Blaikie2e804282015-04-05 22:47:07 +000089 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(nullptr, Value, 1));
John McCall47fb9502013-03-07 21:37:08 +000090 return RValue::getComplex(real, imag);
91 }
John McCalled1ae862011-01-28 11:13:47 +000092 }
93
94 llvm_unreachable("bad saved r-value kind");
John McCalled1ae862011-01-28 11:13:47 +000095}
96
97/// Push an entry of the given size onto this protected-scope stack.
98char *EHScopeStack::allocate(size_t Size) {
James Y Knight53c76162015-07-17 18:21:37 +000099 Size = llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
John McCalled1ae862011-01-28 11:13:47 +0000100 if (!StartOfBuffer) {
101 unsigned Capacity = 1024;
102 while (Capacity < Size) Capacity *= 2;
103 StartOfBuffer = new char[Capacity];
104 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
105 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
106 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
107 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
108
109 unsigned NewCapacity = CurrentCapacity;
110 do {
111 NewCapacity *= 2;
112 } while (NewCapacity < UsedCapacity + Size);
113
114 char *NewStartOfBuffer = new char[NewCapacity];
115 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
116 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
117 memcpy(NewStartOfData, StartOfData, UsedCapacity);
118 delete [] StartOfBuffer;
119 StartOfBuffer = NewStartOfBuffer;
120 EndOfBuffer = NewEndOfBuffer;
121 StartOfData = NewStartOfData;
122 }
123
124 assert(StartOfBuffer + Size <= StartOfData);
125 StartOfData -= Size;
126 return StartOfData;
127}
128
James Y Knight53c76162015-07-17 18:21:37 +0000129void EHScopeStack::deallocate(size_t Size) {
130 StartOfData += llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
131}
132
David Majnemerdc012fa2015-04-22 21:38:15 +0000133bool EHScopeStack::containsOnlyLifetimeMarkers(
134 EHScopeStack::stable_iterator Old) const {
135 for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {
136 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
137 if (!cleanup || !cleanup->isLifetimeMarker())
138 return false;
139 }
140
141 return true;
142}
143
John McCalled1ae862011-01-28 11:13:47 +0000144EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +0000145EHScopeStack::getInnermostActiveNormalCleanup() const {
146 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
147 si != se; ) {
148 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
149 if (cleanup.isActive()) return si;
150 si = cleanup.getEnclosingNormalCleanup();
151 }
152 return stable_end();
153}
154
155EHScopeStack::stable_iterator EHScopeStack::getInnermostActiveEHScope() const {
156 for (stable_iterator si = getInnermostEHScope(), se = stable_end();
157 si != se; ) {
158 // Skip over inactive cleanups.
159 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*find(si));
160 if (cleanup && !cleanup->isActive()) {
161 si = cleanup->getEnclosingEHScope();
162 continue;
John McCalled1ae862011-01-28 11:13:47 +0000163 }
John McCall8e4c74b2011-08-11 02:22:43 +0000164
165 // All other scopes are always active.
166 return si;
167 }
168
John McCalled1ae862011-01-28 11:13:47 +0000169 return stable_end();
170}
171
172
173void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCalled1ae862011-01-28 11:13:47 +0000174 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
175 bool IsNormalCleanup = Kind & NormalCleanup;
176 bool IsEHCleanup = Kind & EHCleanup;
177 bool IsActive = !(Kind & InactiveCleanup);
178 EHCleanupScope *Scope =
179 new (Buffer) EHCleanupScope(IsNormalCleanup,
180 IsEHCleanup,
181 IsActive,
182 Size,
183 BranchFixups.size(),
184 InnermostNormalCleanup,
John McCall8e4c74b2011-08-11 02:22:43 +0000185 InnermostEHScope);
John McCalled1ae862011-01-28 11:13:47 +0000186 if (IsNormalCleanup)
187 InnermostNormalCleanup = stable_begin();
188 if (IsEHCleanup)
John McCall8e4c74b2011-08-11 02:22:43 +0000189 InnermostEHScope = stable_begin();
John McCalled1ae862011-01-28 11:13:47 +0000190
191 return Scope->getCleanupBuffer();
192}
193
194void EHScopeStack::popCleanup() {
195 assert(!empty() && "popping exception stack when not empty");
196
197 assert(isa<EHCleanupScope>(*begin()));
198 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
199 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
John McCall8e4c74b2011-08-11 02:22:43 +0000200 InnermostEHScope = Cleanup.getEnclosingEHScope();
James Y Knight53c76162015-07-17 18:21:37 +0000201 deallocate(Cleanup.getAllocatedSize());
John McCalled1ae862011-01-28 11:13:47 +0000202
John McCalled1ae862011-01-28 11:13:47 +0000203 // Destroy the cleanup.
Kostya Serebryanyb21aa762014-10-08 18:31:54 +0000204 Cleanup.Destroy();
John McCalled1ae862011-01-28 11:13:47 +0000205
206 // Check whether we can shrink the branch-fixups stack.
207 if (!BranchFixups.empty()) {
208 // If we no longer have any normal cleanups, all the fixups are
209 // complete.
210 if (!hasNormalCleanups())
211 BranchFixups.clear();
212
213 // Otherwise we can still trim out unnecessary nulls.
214 else
215 popNullFixups();
216 }
217}
218
John McCall8e4c74b2011-08-11 02:22:43 +0000219EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
220 assert(getInnermostEHScope() == stable_end());
221 char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
222 EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
223 InnermostEHScope = stable_begin();
224 return filter;
John McCalled1ae862011-01-28 11:13:47 +0000225}
226
227void EHScopeStack::popFilter() {
228 assert(!empty() && "popping exception stack when not empty");
229
John McCall8e4c74b2011-08-11 02:22:43 +0000230 EHFilterScope &filter = cast<EHFilterScope>(*begin());
James Y Knight53c76162015-07-17 18:21:37 +0000231 deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
John McCalled1ae862011-01-28 11:13:47 +0000232
John McCall8e4c74b2011-08-11 02:22:43 +0000233 InnermostEHScope = filter.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000234}
235
John McCall8e4c74b2011-08-11 02:22:43 +0000236EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
237 char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
238 EHCatchScope *scope =
239 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
240 InnermostEHScope = stable_begin();
241 return scope;
John McCalled1ae862011-01-28 11:13:47 +0000242}
243
244void EHScopeStack::pushTerminate() {
245 char *Buffer = allocate(EHTerminateScope::getSize());
John McCall8e4c74b2011-08-11 02:22:43 +0000246 new (Buffer) EHTerminateScope(InnermostEHScope);
247 InnermostEHScope = stable_begin();
John McCalled1ae862011-01-28 11:13:47 +0000248}
249
David Majnemerdbf10452015-07-31 17:58:45 +0000250void EHScopeStack::pushCatchEnd(llvm::BasicBlock *CatchEndBlockBB) {
251 char *Buffer = allocate(EHCatchEndScope::getSize());
252 auto *CES = new (Buffer) EHCatchEndScope(InnermostEHScope);
253 CES->setCachedEHDispatchBlock(CatchEndBlockBB);
254 InnermostEHScope = stable_begin();
255}
256
John McCalled1ae862011-01-28 11:13:47 +0000257/// Remove any 'null' fixups on the stack. However, we can't pop more
258/// fixups than the fixup depth on the innermost normal cleanup, or
259/// else fixups that we try to add to that cleanup will end up in the
260/// wrong place. We *could* try to shrink fixup depths, but that's
261/// actually a lot of work for little benefit.
262void EHScopeStack::popNullFixups() {
263 // We expect this to only be called when there's still an innermost
264 // normal cleanup; otherwise there really shouldn't be any fixups.
265 assert(hasNormalCleanups());
266
267 EHScopeStack::iterator it = find(InnermostNormalCleanup);
268 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
269 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
270
271 while (BranchFixups.size() > MinSize &&
Craig Topper8a13c412014-05-21 05:09:00 +0000272 BranchFixups.back().Destination == nullptr)
John McCalled1ae862011-01-28 11:13:47 +0000273 BranchFixups.pop_back();
274}
275
276void CodeGenFunction::initFullExprCleanup() {
277 // Create a variable to decide whether the cleanup needs to be run.
278 llvm::AllocaInst *active
279 = CreateTempAlloca(Builder.getInt1Ty(), "cleanup.cond");
280
281 // Initialize it to false at a site that's guaranteed to be run
282 // before each evaluation.
John McCallf4beacd2011-11-10 10:43:54 +0000283 setBeforeOutermostConditional(Builder.getFalse(), active);
John McCalled1ae862011-01-28 11:13:47 +0000284
285 // Initialize it to true at the current location.
286 Builder.CreateStore(Builder.getTrue(), active);
287
288 // Set that as the active flag in the cleanup.
289 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
Craig Topper8a13c412014-05-21 05:09:00 +0000290 assert(!cleanup.getActiveFlag() && "cleanup already has active flag?");
John McCalled1ae862011-01-28 11:13:47 +0000291 cleanup.setActiveFlag(active);
292
293 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
294 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
295}
296
John McCall5fcf8da2011-07-12 00:15:30 +0000297void EHScopeStack::Cleanup::anchor() {}
John McCalled1ae862011-01-28 11:13:47 +0000298
299/// All the branch fixups on the EH stack have propagated out past the
300/// outermost normal cleanup; resolve them all by adding cases to the
301/// given switch instruction.
302static void ResolveAllBranchFixups(CodeGenFunction &CGF,
303 llvm::SwitchInst *Switch,
304 llvm::BasicBlock *CleanupEntry) {
305 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
306
307 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
308 // Skip this fixup if its destination isn't set.
309 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
Craig Topper8a13c412014-05-21 05:09:00 +0000310 if (Fixup.Destination == nullptr) continue;
John McCalled1ae862011-01-28 11:13:47 +0000311
312 // If there isn't an OptimisticBranchBlock, then InitialBranch is
313 // still pointing directly to its destination; forward it to the
314 // appropriate cleanup entry. This is required in the specific
315 // case of
316 // { std::string s; goto lbl; }
317 // lbl:
318 // i.e. where there's an unresolved fixup inside a single cleanup
319 // entry which we're currently popping.
Craig Topper8a13c412014-05-21 05:09:00 +0000320 if (Fixup.OptimisticBranchBlock == nullptr) {
John McCalled1ae862011-01-28 11:13:47 +0000321 new llvm::StoreInst(CGF.Builder.getInt32(Fixup.DestinationIndex),
322 CGF.getNormalCleanupDestSlot(),
323 Fixup.InitialBranch);
324 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
325 }
326
327 // Don't add this case to the switch statement twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000328 if (!CasesAdded.insert(Fixup.Destination).second)
329 continue;
John McCalled1ae862011-01-28 11:13:47 +0000330
331 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
332 Fixup.Destination);
333 }
334
335 CGF.EHStack.clearFixups();
336}
337
338/// Transitions the terminator of the given exit-block of a cleanup to
339/// be a cleanup switch.
340static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
341 llvm::BasicBlock *Block) {
342 // If it's a branch, turn it into a switch whose default
343 // destination is its original target.
344 llvm::TerminatorInst *Term = Block->getTerminator();
345 assert(Term && "can't transition block without terminator");
346
347 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
348 assert(Br->isUnconditional());
349 llvm::LoadInst *Load =
350 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
351 llvm::SwitchInst *Switch =
352 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
353 Br->eraseFromParent();
354 return Switch;
355 } else {
356 return cast<llvm::SwitchInst>(Term);
357 }
358}
359
360void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
361 assert(Block && "resolving a null target block");
362 if (!EHStack.getNumBranchFixups()) return;
363
364 assert(EHStack.hasNormalCleanups() &&
365 "branch fixups exist with no normal cleanups on stack");
366
367 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
368 bool ResolvedAny = false;
369
370 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
371 // Skip this fixup if its destination doesn't match.
372 BranchFixup &Fixup = EHStack.getBranchFixup(I);
373 if (Fixup.Destination != Block) continue;
374
Craig Topper8a13c412014-05-21 05:09:00 +0000375 Fixup.Destination = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000376 ResolvedAny = true;
377
378 // If it doesn't have an optimistic branch block, LatestBranch is
379 // already pointing to the right place.
380 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
381 if (!BranchBB)
382 continue;
383
384 // Don't process the same optimistic branch block twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000385 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
John McCalled1ae862011-01-28 11:13:47 +0000386 continue;
387
388 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
389
390 // Add a case to the switch.
391 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
392 }
393
394 if (ResolvedAny)
395 EHStack.popNullFixups();
396}
397
398/// Pops cleanup blocks until the given savepoint is reached.
Adrian Prantldc237b52013-05-16 00:41:26 +0000399void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
John McCalled1ae862011-01-28 11:13:47 +0000400 assert(Old.isValid());
401
402 while (EHStack.stable_begin() != Old) {
403 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
404
405 // As long as Old strictly encloses the scope's enclosing normal
406 // cleanup, we're going to emit another normal cleanup which
407 // fallthrough can propagate through.
408 bool FallThroughIsBranchThrough =
409 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
410
Adrian Prantldc237b52013-05-16 00:41:26 +0000411 PopCleanupBlock(FallThroughIsBranchThrough);
John McCalled1ae862011-01-28 11:13:47 +0000412 }
413}
414
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000415/// Pops cleanup blocks until the given savepoint is reached, then add the
416/// cleanups from the given savepoint in the lifetime-extended cleanups stack.
Richard Smith736a9472013-06-12 20:42:33 +0000417void
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000418CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old,
419 size_t OldLifetimeExtendedSize) {
420 PopCleanupBlocks(Old);
421
422 // Move our deferred cleanups onto the EH stack.
Richard Smith736a9472013-06-12 20:42:33 +0000423 for (size_t I = OldLifetimeExtendedSize,
424 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
425 // Alignment should be guaranteed by the vptrs in the individual cleanups.
426 assert((I % llvm::alignOf<LifetimeExtendedCleanupHeader>() == 0) &&
427 "misaligned cleanup stack entry");
428
429 LifetimeExtendedCleanupHeader &Header =
430 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
431 LifetimeExtendedCleanupStack[I]);
432 I += sizeof(Header);
433
434 EHStack.pushCopyOfCleanup(Header.getKind(),
435 &LifetimeExtendedCleanupStack[I],
436 Header.getSize());
437 I += Header.getSize();
438 }
439 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
440}
441
John McCalled1ae862011-01-28 11:13:47 +0000442static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
443 EHCleanupScope &Scope) {
444 assert(Scope.isNormalCleanup());
445 llvm::BasicBlock *Entry = Scope.getNormalBlock();
446 if (!Entry) {
447 Entry = CGF.createBasicBlock("cleanup");
448 Scope.setNormalBlock(Entry);
449 }
450 return Entry;
451}
452
John McCalled1ae862011-01-28 11:13:47 +0000453/// Attempts to reduce a cleanup's entry block to a fallthrough. This
454/// is basically llvm::MergeBlockIntoPredecessor, except
455/// simplified/optimized for the tighter constraints on cleanup blocks.
456///
457/// Returns the new block, whatever it is.
458static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
459 llvm::BasicBlock *Entry) {
460 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
461 if (!Pred) return Entry;
462
463 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
464 if (!Br || Br->isConditional()) return Entry;
465 assert(Br->getSuccessor(0) == Entry);
466
467 // If we were previously inserting at the end of the cleanup entry
468 // block, we'll need to continue inserting at the end of the
469 // predecessor.
470 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
471 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
472
473 // Kill the branch.
474 Br->eraseFromParent();
475
John McCalled1ae862011-01-28 11:13:47 +0000476 // Replace all uses of the entry with the predecessor, in case there
477 // are phis in the cleanup.
478 Entry->replaceAllUsesWith(Pred);
479
Jay Foade03c05c2011-06-20 14:38:01 +0000480 // Merge the blocks.
481 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
482
John McCalled1ae862011-01-28 11:13:47 +0000483 // Kill the entry block.
484 Entry->eraseFromParent();
485
486 if (WasInsertBlock)
487 CGF.Builder.SetInsertPoint(Pred);
488
489 return Pred;
490}
491
492static void EmitCleanup(CodeGenFunction &CGF,
493 EHScopeStack::Cleanup *Fn,
John McCall30317fd2011-07-12 20:27:29 +0000494 EHScopeStack::Cleanup::Flags flags,
John McCalled1ae862011-01-28 11:13:47 +0000495 llvm::Value *ActiveFlag) {
Reid Klecknere5b06422015-04-08 22:48:50 +0000496 // Itanium EH cleanups occur within a terminate scope. Microsoft SEH doesn't
497 // have this behavior, and the Microsoft C++ runtime will call terminate for
498 // us if the cleanup throws.
499 bool PushedTerminate = false;
500 if (flags.isForEHCleanup() && !CGF.getTarget().getCXXABI().isMicrosoft()) {
501 CGF.EHStack.pushTerminate();
502 PushedTerminate = true;
503 }
John McCalled1ae862011-01-28 11:13:47 +0000504
505 // If there's an active flag, load it and skip the cleanup if it's
506 // false.
Craig Topper8a13c412014-05-21 05:09:00 +0000507 llvm::BasicBlock *ContBB = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000508 if (ActiveFlag) {
509 ContBB = CGF.createBasicBlock("cleanup.done");
510 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
511 llvm::Value *IsActive
512 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
513 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
514 CGF.EmitBlock(CleanupBB);
515 }
516
517 // Ask the cleanup to emit itself.
John McCall30317fd2011-07-12 20:27:29 +0000518 Fn->Emit(CGF, flags);
John McCalled1ae862011-01-28 11:13:47 +0000519 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
520
521 // Emit the continuation block if there was an active flag.
522 if (ActiveFlag)
523 CGF.EmitBlock(ContBB);
524
525 // Leave the terminate scope.
Reid Klecknere5b06422015-04-08 22:48:50 +0000526 if (PushedTerminate)
527 CGF.EHStack.popTerminate();
John McCalled1ae862011-01-28 11:13:47 +0000528}
529
530static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
531 llvm::BasicBlock *From,
532 llvm::BasicBlock *To) {
533 // Exit is the exit block of a cleanup, so it always terminates in
534 // an unconditional branch or a switch.
535 llvm::TerminatorInst *Term = Exit->getTerminator();
536
537 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
538 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
539 Br->setSuccessor(0, To);
540 } else {
541 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
542 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
543 if (Switch->getSuccessor(I) == From)
544 Switch->setSuccessor(I, To);
545 }
546}
547
John McCallf82bdf62011-08-06 06:53:52 +0000548/// We don't need a normal entry block for the given cleanup.
549/// Optimistic fixup branches can cause these blocks to come into
550/// existence anyway; if so, destroy it.
551///
552/// The validity of this transformation is very much specific to the
553/// exact ways in which we form branches to cleanup entries.
554static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
555 EHCleanupScope &scope) {
556 llvm::BasicBlock *entry = scope.getNormalBlock();
557 if (!entry) return;
558
559 // Replace all the uses with unreachable.
560 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
561 for (llvm::BasicBlock::use_iterator
562 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000563 llvm::Use &use = *i;
John McCallf82bdf62011-08-06 06:53:52 +0000564 ++i;
565
566 use.set(unreachableBB);
567
568 // The only uses should be fixup switches.
569 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
Stepan Dyatkovskiy5fecf5442012-02-01 07:50:21 +0000570 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
John McCallf82bdf62011-08-06 06:53:52 +0000571 // Replace the switch with a branch.
Stepan Dyatkovskiyfe3b0692012-03-11 06:09:37 +0000572 llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
John McCallf82bdf62011-08-06 06:53:52 +0000573
574 // The switch operand is a load from the cleanup-dest alloca.
575 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
576
577 // Destroy the switch.
578 si->eraseFromParent();
579
580 // Destroy the load.
581 assert(condition->getOperand(0) == CGF.NormalCleanupDest);
582 assert(condition->use_empty());
583 condition->eraseFromParent();
584 }
585 }
586
587 assert(entry->use_empty());
588 delete entry;
589}
590
John McCalled1ae862011-01-28 11:13:47 +0000591/// Pops a cleanup block. If the block includes a normal cleanup, the
592/// current insertion point is threaded through the cleanup, as are
593/// any branch fixups on the cleanup.
Adrian Prantldc237b52013-05-16 00:41:26 +0000594void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCalled1ae862011-01-28 11:13:47 +0000595 assert(!EHStack.empty() && "cleanup stack is empty!");
596 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
597 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
598 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
599
600 // Remember activation information.
601 bool IsActive = Scope.isActive();
602 llvm::Value *NormalActiveFlag =
Craig Topper8a13c412014-05-21 05:09:00 +0000603 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000604 llvm::Value *EHActiveFlag =
Craig Topper8a13c412014-05-21 05:09:00 +0000605 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000606
607 // Check whether we need an EH cleanup. This is only true if we've
608 // generated a lazy EH cleanup block.
John McCall8e4c74b2011-08-11 02:22:43 +0000609 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000610 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
611 bool RequiresEHCleanup = (EHEntry != nullptr);
John McCall8e4c74b2011-08-11 02:22:43 +0000612 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000613
614 // Check the three conditions which might require a normal cleanup:
615
616 // - whether there are branch fix-ups through this cleanup
617 unsigned FixupDepth = Scope.getFixupDepth();
618 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
619
620 // - whether there are branch-throughs or branch-afters
621 bool HasExistingBranches = Scope.hasBranches();
622
623 // - whether there's a fallthrough
624 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000625 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
John McCalled1ae862011-01-28 11:13:47 +0000626
627 // Branch-through fall-throughs leave the insertion point set to the
628 // end of the last cleanup, which points to the current scope. The
629 // rest of IR gen doesn't need to worry about this; it only happens
630 // during the execution of PopCleanupBlocks().
631 bool HasPrebranchedFallthrough =
632 (FallthroughSource && FallthroughSource->getTerminator());
633
634 // If this is a normal cleanup, then having a prebranched
635 // fallthrough implies that the fallthrough source unconditionally
636 // jumps here.
637 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
638 (Scope.getNormalBlock() &&
639 FallthroughSource->getTerminator()->getSuccessor(0)
640 == Scope.getNormalBlock()));
641
642 bool RequiresNormalCleanup = false;
643 if (Scope.isNormalCleanup() &&
644 (HasFixups || HasExistingBranches || HasFallthrough)) {
645 RequiresNormalCleanup = true;
646 }
647
John McCall45e42952011-08-07 07:05:57 +0000648 // If we have a prebranched fallthrough into an inactive normal
649 // cleanup, rewrite it so that it leads to the appropriate place.
650 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
651 llvm::BasicBlock *prebranchDest;
652
653 // If the prebranch is semantically branching through the next
654 // cleanup, just forward it to the next block, leaving the
655 // insertion point in the prebranched block.
John McCalled1ae862011-01-28 11:13:47 +0000656 if (FallthroughIsBranchThrough) {
John McCall45e42952011-08-07 07:05:57 +0000657 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
658 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
John McCalled1ae862011-01-28 11:13:47 +0000659
John McCall45e42952011-08-07 07:05:57 +0000660 // Otherwise, we need to make a new block. If the normal cleanup
661 // isn't being used at all, we could actually reuse the normal
662 // entry block, but this is simpler, and it avoids conflicts with
663 // dead optimistic fixup branches.
John McCalled1ae862011-01-28 11:13:47 +0000664 } else {
John McCall45e42952011-08-07 07:05:57 +0000665 prebranchDest = createBasicBlock("forwarded-prebranch");
666 EmitBlock(prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000667 }
John McCall45e42952011-08-07 07:05:57 +0000668
669 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
670 assert(normalEntry && !normalEntry->use_empty());
671
672 ForwardPrebranchedFallthrough(FallthroughSource,
673 normalEntry, prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000674 }
675
676 // If we don't need the cleanup at all, we're done.
677 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000678 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000679 EHStack.popCleanup(); // safe because there are no fixups
680 assert(EHStack.getNumBranchFixups() == 0 ||
681 EHStack.hasNormalCleanups());
682 return;
683 }
684
685 // Copy the cleanup emission data out. Note that SmallVector
686 // guarantees maximal alignment for its buffer regardless of its
687 // type parameter.
Benjamin Kramer6c3e4ec2015-08-04 12:34:30 +0000688 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
689 SmallVector<char, 8 * sizeof(void *)> CleanupBuffer(
690 CleanupSource, CleanupSource + Scope.getCleanupSize());
691 auto *Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBuffer.data());
John McCalled1ae862011-01-28 11:13:47 +0000692
John McCall8e4c74b2011-08-11 02:22:43 +0000693 EHScopeStack::Cleanup::Flags cleanupFlags;
694 if (Scope.isNormalCleanup())
695 cleanupFlags.setIsNormalCleanupKind();
696 if (Scope.isEHCleanup())
697 cleanupFlags.setIsEHCleanupKind();
John McCalled1ae862011-01-28 11:13:47 +0000698
699 if (!RequiresNormalCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000700 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000701 EHStack.popCleanup();
702 } else {
703 // If we have a fallthrough and no other need for the cleanup,
704 // emit it directly.
705 if (HasFallthrough && !HasPrebranchedFallthrough &&
706 !HasFixups && !HasExistingBranches) {
707
John McCallf82bdf62011-08-06 06:53:52 +0000708 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000709 EHStack.popCleanup();
710
John McCall30317fd2011-07-12 20:27:29 +0000711 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000712
713 // Otherwise, the best approach is to thread everything through
714 // the cleanup block and then try to clean up after ourselves.
715 } else {
716 // Force the entry block to exist.
717 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
718
719 // I. Set up the fallthrough edge in.
720
John McCalla3654e32011-08-10 04:11:11 +0000721 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
John McCall45e42952011-08-07 07:05:57 +0000722
John McCalled1ae862011-01-28 11:13:47 +0000723 // If there's a fallthrough, we need to store the cleanup
724 // destination index. For fall-throughs this is always zero.
725 if (HasFallthrough) {
726 if (!HasPrebranchedFallthrough)
727 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
728
John McCall45e42952011-08-07 07:05:57 +0000729 // Otherwise, save and clear the IP if we don't have fallthrough
730 // because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000731 } else if (FallthroughSource) {
732 assert(!IsActive && "source without fallthrough for active cleanup");
John McCall45e42952011-08-07 07:05:57 +0000733 savedInactiveFallthroughIP = Builder.saveAndClearIP();
John McCalled1ae862011-01-28 11:13:47 +0000734 }
735
736 // II. Emit the entry block. This implicitly branches to it if
737 // we have fallthrough. All the fixups and existing branches
738 // should already be branched to it.
739 EmitBlock(NormalEntry);
740
741 // III. Figure out where we're going and build the cleanup
742 // epilogue.
743
744 bool HasEnclosingCleanups =
745 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
746
747 // Compute the branch-through dest if we need it:
748 // - if there are branch-throughs threaded through the scope
749 // - if fall-through is a branch-through
750 // - if there are fixups that will be optimistically forwarded
751 // to the enclosing cleanup
Craig Topper8a13c412014-05-21 05:09:00 +0000752 llvm::BasicBlock *BranchThroughDest = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000753 if (Scope.hasBranchThroughs() ||
754 (FallthroughSource && FallthroughIsBranchThrough) ||
755 (HasFixups && HasEnclosingCleanups)) {
756 assert(HasEnclosingCleanups);
757 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
758 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
759 }
760
Craig Topper8a13c412014-05-21 05:09:00 +0000761 llvm::BasicBlock *FallthroughDest = nullptr;
Benjamin Kramerc7497452015-02-17 16:53:08 +0000762 SmallVector<llvm::Instruction*, 2> InstsToAppend;
John McCalled1ae862011-01-28 11:13:47 +0000763
764 // If there's exactly one branch-after and no other threads,
765 // we can route it without a switch.
766 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
767 Scope.getNumBranchAfters() == 1) {
768 assert(!BranchThroughDest || !IsActive);
769
David Majnemerdc012fa2015-04-22 21:38:15 +0000770 // Clean up the possibly dead store to the cleanup dest slot.
771 llvm::Instruction *NormalCleanupDestSlot =
772 cast<llvm::Instruction>(getNormalCleanupDestSlot());
773 if (NormalCleanupDestSlot->hasOneUse()) {
774 NormalCleanupDestSlot->user_back()->eraseFromParent();
775 NormalCleanupDestSlot->eraseFromParent();
776 NormalCleanupDest = nullptr;
777 }
778
John McCalled1ae862011-01-28 11:13:47 +0000779 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
780 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
781
782 // Build a switch-out if we need it:
783 // - if there are branch-afters threaded through the scope
784 // - if fall-through is a branch-after
785 // - if there are fixups that have nowhere left to go and
786 // so must be immediately resolved
787 } else if (Scope.getNumBranchAfters() ||
788 (HasFallthrough && !FallthroughIsBranchThrough) ||
789 (HasFixups && !HasEnclosingCleanups)) {
790
791 llvm::BasicBlock *Default =
792 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
793
794 // TODO: base this on the number of branch-afters and fixups
795 const unsigned SwitchCapacity = 10;
796
797 llvm::LoadInst *Load =
798 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
799 llvm::SwitchInst *Switch =
800 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
801
802 InstsToAppend.push_back(Load);
803 InstsToAppend.push_back(Switch);
804
805 // Branch-after fallthrough.
806 if (FallthroughSource && !FallthroughIsBranchThrough) {
807 FallthroughDest = createBasicBlock("cleanup.cont");
808 if (HasFallthrough)
809 Switch->addCase(Builder.getInt32(0), FallthroughDest);
810 }
811
812 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
813 Switch->addCase(Scope.getBranchAfterIndex(I),
814 Scope.getBranchAfterBlock(I));
815 }
816
817 // If there aren't any enclosing cleanups, we can resolve all
818 // the fixups now.
819 if (HasFixups && !HasEnclosingCleanups)
820 ResolveAllBranchFixups(*this, Switch, NormalEntry);
821 } else {
822 // We should always have a branch-through destination in this case.
823 assert(BranchThroughDest);
824 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
825 }
826
827 // IV. Pop the cleanup and emit it.
828 EHStack.popCleanup();
829 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
830
John McCall30317fd2011-07-12 20:27:29 +0000831 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000832
833 // Append the prepared cleanup prologue from above.
834 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
Benjamin Kramerc7497452015-02-17 16:53:08 +0000835 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
836 NormalExit->getInstList().push_back(InstsToAppend[I]);
John McCalled1ae862011-01-28 11:13:47 +0000837
838 // Optimistically hope that any fixups will continue falling through.
839 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
840 I < E; ++I) {
John McCallad7c5c12011-02-08 08:22:06 +0000841 BranchFixup &Fixup = EHStack.getBranchFixup(I);
John McCalled1ae862011-01-28 11:13:47 +0000842 if (!Fixup.Destination) continue;
843 if (!Fixup.OptimisticBranchBlock) {
844 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
845 getNormalCleanupDestSlot(),
846 Fixup.InitialBranch);
847 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
848 }
849 Fixup.OptimisticBranchBlock = NormalExit;
850 }
851
852 // V. Set up the fallthrough edge out.
853
John McCall45e42952011-08-07 07:05:57 +0000854 // Case 1: a fallthrough source exists but doesn't branch to the
855 // cleanup because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000856 if (!HasFallthrough && FallthroughSource) {
John McCall45e42952011-08-07 07:05:57 +0000857 // Prebranched fallthrough was forwarded earlier.
858 // Non-prebranched fallthrough doesn't need to be forwarded.
859 // Either way, all we need to do is restore the IP we cleared before.
John McCalled1ae862011-01-28 11:13:47 +0000860 assert(!IsActive);
John McCall45e42952011-08-07 07:05:57 +0000861 Builder.restoreIP(savedInactiveFallthroughIP);
John McCalled1ae862011-01-28 11:13:47 +0000862
863 // Case 2: a fallthrough source exists and should branch to the
864 // cleanup, but we're not supposed to branch through to the next
865 // cleanup.
866 } else if (HasFallthrough && FallthroughDest) {
867 assert(!FallthroughIsBranchThrough);
868 EmitBlock(FallthroughDest);
869
870 // Case 3: a fallthrough source exists and should branch to the
871 // cleanup and then through to the next.
872 } else if (HasFallthrough) {
873 // Everything is already set up for this.
874
875 // Case 4: no fallthrough source exists.
876 } else {
877 Builder.ClearInsertionPoint();
878 }
879
880 // VI. Assorted cleaning.
881
882 // Check whether we can merge NormalEntry into a single predecessor.
883 // This might invalidate (non-IR) pointers to NormalEntry.
884 llvm::BasicBlock *NewNormalEntry =
885 SimplifyCleanupEntry(*this, NormalEntry);
886
887 // If it did invalidate those pointers, and NormalEntry was the same
888 // as NormalExit, go back and patch up the fixups.
889 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
890 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
891 I < E; ++I)
John McCallad7c5c12011-02-08 08:22:06 +0000892 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCalled1ae862011-01-28 11:13:47 +0000893 }
894 }
895
896 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
897
898 // Emit the EH cleanup if required.
899 if (RequiresEHCleanup) {
900 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
901
902 EmitBlock(EHEntry);
David Majnemerdbf10452015-07-31 17:58:45 +0000903 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
904 if (CGM.getCodeGenOpts().NewMSEH &&
905 EHPersonality::get(*this).isMSVCPersonality()) {
906 if (NextAction)
907 Builder.CreateCleanupPad(VoidTy, NextAction);
908 else
909 Builder.CreateCleanupPad(VoidTy, {});
910 }
John McCall30317fd2011-07-12 20:27:29 +0000911
Eli Friedmanabab7762012-08-02 00:10:24 +0000912 // We only actually emit the cleanup code if the cleanup is either
913 // active or was used before it was deactivated.
914 if (EHActiveFlag || IsActive) {
Adrian Prantl52bf3c42013-05-03 20:11:48 +0000915
Eli Friedmanabab7762012-08-02 00:10:24 +0000916 cleanupFlags.setIsForEHCleanup();
917 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
918 }
John McCalled1ae862011-01-28 11:13:47 +0000919
David Majnemerdbf10452015-07-31 17:58:45 +0000920 if (CGM.getCodeGenOpts().NewMSEH && EHPersonality::get(*this).isMSVCPersonality())
921 Builder.CreateCleanupRet(NextAction);
922 else
923 Builder.CreateBr(NextAction);
John McCalled1ae862011-01-28 11:13:47 +0000924
925 Builder.restoreIP(SavedIP);
926
927 SimplifyCleanupEntry(*this, EHEntry);
928 }
929}
930
Justin Bognere25ffdf2014-01-21 00:35:11 +0000931/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
932/// specified destination obviously has no cleanups to run. 'false' is always
933/// a conservatively correct answer for this method.
934bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
935 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
936 && "stale jump destination");
937
938 // Calculate the innermost active normal cleanup.
939 EHScopeStack::stable_iterator TopCleanup =
940 EHStack.getInnermostActiveNormalCleanup();
941
942 // If we're not in an active normal cleanup scope, or if the
943 // destination scope is within the innermost active normal cleanup
944 // scope, we don't need to worry about fixups.
945 if (TopCleanup == EHStack.stable_end() ||
946 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
947 return true;
948
949 // Otherwise, we might need some cleanups.
950 return false;
951}
952
953
John McCalled1ae862011-01-28 11:13:47 +0000954/// Terminate the current block by emitting a branch which might leave
955/// the current cleanup-protected scope. The target scope may not yet
956/// be known, in which case this will require a fixup.
957///
958/// As a side-effect, this method clears the insertion point.
959void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall1b93f1b2011-02-25 04:19:13 +0000960 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
John McCalled1ae862011-01-28 11:13:47 +0000961 && "stale jump destination");
962
963 if (!HaveInsertPoint())
964 return;
965
966 // Create the branch.
967 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
968
969 // Calculate the innermost active normal cleanup.
970 EHScopeStack::stable_iterator
971 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
972
973 // If we're not in an active normal cleanup scope, or if the
974 // destination scope is within the innermost active normal cleanup
975 // scope, we don't need to worry about fixups.
976 if (TopCleanup == EHStack.stable_end() ||
977 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
978 Builder.ClearInsertionPoint();
979 return;
980 }
981
982 // If we can't resolve the destination cleanup scope, just add this
983 // to the current cleanup scope as a branch fixup.
984 if (!Dest.getScopeDepth().isValid()) {
985 BranchFixup &Fixup = EHStack.addBranchFixup();
986 Fixup.Destination = Dest.getBlock();
987 Fixup.DestinationIndex = Dest.getDestIndex();
988 Fixup.InitialBranch = BI;
Craig Topper8a13c412014-05-21 05:09:00 +0000989 Fixup.OptimisticBranchBlock = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000990
991 Builder.ClearInsertionPoint();
992 return;
993 }
994
995 // Otherwise, thread through all the normal cleanups in scope.
996
997 // Store the index at the start.
998 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
999 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
1000
1001 // Adjust BI to point to the first cleanup block.
1002 {
1003 EHCleanupScope &Scope =
1004 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1005 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1006 }
1007
1008 // Add this destination to all the scopes involved.
1009 EHScopeStack::stable_iterator I = TopCleanup;
1010 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1011 if (E.strictlyEncloses(I)) {
1012 while (true) {
1013 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1014 assert(Scope.isNormalCleanup());
1015 I = Scope.getEnclosingNormalCleanup();
1016
1017 // If this is the last cleanup we're propagating through, tell it
1018 // that there's a resolved jump moving through it.
1019 if (!E.strictlyEncloses(I)) {
1020 Scope.addBranchAfter(Index, Dest.getBlock());
1021 break;
1022 }
1023
1024 // Otherwise, tell the scope that there's a jump propoagating
1025 // through it. If this isn't new information, all the rest of
1026 // the work has been done before.
1027 if (!Scope.addBranchThrough(Dest.getBlock()))
1028 break;
1029 }
1030 }
1031
1032 Builder.ClearInsertionPoint();
1033}
1034
John McCalled1ae862011-01-28 11:13:47 +00001035static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1036 EHScopeStack::stable_iterator C) {
1037 // If we needed a normal block for any reason, that counts.
1038 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1039 return true;
1040
1041 // Check whether any enclosed cleanups were needed.
1042 for (EHScopeStack::stable_iterator
1043 I = EHStack.getInnermostNormalCleanup();
1044 I != C; ) {
1045 assert(C.strictlyEncloses(I));
1046 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1047 if (S.getNormalBlock()) return true;
1048 I = S.getEnclosingNormalCleanup();
1049 }
1050
1051 return false;
1052}
1053
1054static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
John McCall8e4c74b2011-08-11 02:22:43 +00001055 EHScopeStack::stable_iterator cleanup) {
John McCalled1ae862011-01-28 11:13:47 +00001056 // If we needed an EH block for any reason, that counts.
John McCall8e4c74b2011-08-11 02:22:43 +00001057 if (EHStack.find(cleanup)->hasEHBranches())
John McCalled1ae862011-01-28 11:13:47 +00001058 return true;
1059
1060 // Check whether any enclosed cleanups were needed.
1061 for (EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +00001062 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1063 assert(cleanup.strictlyEncloses(i));
1064
1065 EHScope &scope = *EHStack.find(i);
1066 if (scope.hasEHBranches())
1067 return true;
1068
1069 i = scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +00001070 }
1071
1072 return false;
1073}
1074
1075enum ForActivation_t {
1076 ForActivation,
1077 ForDeactivation
1078};
1079
1080/// The given cleanup block is changing activation state. Configure a
1081/// cleanup variable if necessary.
1082///
1083/// It would be good if we had some way of determining if there were
1084/// extra uses *after* the change-over point.
1085static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1086 EHScopeStack::stable_iterator C,
John McCallf4beacd2011-11-10 10:43:54 +00001087 ForActivation_t kind,
1088 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001089 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1090
John McCalle63abb52011-11-10 09:22:44 +00001091 // We always need the flag if we're activating the cleanup in a
1092 // conditional context, because we have to assume that the current
1093 // location doesn't necessarily dominate the cleanup's code.
1094 bool isActivatedInConditional =
John McCallf4beacd2011-11-10 10:43:54 +00001095 (kind == ForActivation && CGF.isInConditionalBranch());
John McCalle63abb52011-11-10 09:22:44 +00001096
1097 bool needFlag = false;
John McCalled1ae862011-01-28 11:13:47 +00001098
1099 // Calculate whether the cleanup was used:
1100
1101 // - as a normal cleanup
John McCalle63abb52011-11-10 09:22:44 +00001102 if (Scope.isNormalCleanup() &&
1103 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001104 Scope.setTestFlagInNormalCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001105 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001106 }
1107
1108 // - as an EH cleanup
John McCalle63abb52011-11-10 09:22:44 +00001109 if (Scope.isEHCleanup() &&
1110 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001111 Scope.setTestFlagInEHCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001112 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001113 }
1114
1115 // If it hasn't yet been used as either, we're done.
John McCalle63abb52011-11-10 09:22:44 +00001116 if (!needFlag) return;
John McCalled1ae862011-01-28 11:13:47 +00001117
John McCallf4beacd2011-11-10 10:43:54 +00001118 llvm::AllocaInst *var = Scope.getActiveFlag();
1119 if (!var) {
1120 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactive");
1121 Scope.setActiveFlag(var);
1122
1123 assert(dominatingIP && "no existing variable and no dominating IP!");
John McCalled1ae862011-01-28 11:13:47 +00001124
1125 // Initialize to true or false depending on whether it was
1126 // active up to this point.
John McCallf4beacd2011-11-10 10:43:54 +00001127 llvm::Value *value = CGF.Builder.getInt1(kind == ForDeactivation);
1128
1129 // If we're in a conditional block, ignore the dominating IP and
1130 // use the outermost conditional branch.
1131 if (CGF.isInConditionalBranch()) {
1132 CGF.setBeforeOutermostConditional(value, var);
1133 } else {
1134 new llvm::StoreInst(value, var, dominatingIP);
1135 }
John McCalled1ae862011-01-28 11:13:47 +00001136 }
1137
John McCallf4beacd2011-11-10 10:43:54 +00001138 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
John McCalled1ae862011-01-28 11:13:47 +00001139}
1140
1141/// Activate a cleanup that was created in an inactivated state.
John McCallf4beacd2011-11-10 10:43:54 +00001142void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1143 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001144 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1145 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1146 assert(!Scope.isActive() && "double activation");
1147
John McCallf4beacd2011-11-10 10:43:54 +00001148 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001149
1150 Scope.setActive(true);
1151}
1152
1153/// Deactive a cleanup that was created in an active state.
John McCallf4beacd2011-11-10 10:43:54 +00001154void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1155 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001156 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1157 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1158 assert(Scope.isActive() && "double deactivation");
1159
1160 // If it's the top of the stack, just pop it.
1161 if (C == EHStack.stable_begin()) {
1162 // If it's a normal cleanup, we need to pretend that the
1163 // fallthrough is unreachable.
1164 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1165 PopCleanupBlock();
1166 Builder.restoreIP(SavedIP);
1167 return;
1168 }
1169
1170 // Otherwise, follow the general case.
John McCallf4beacd2011-11-10 10:43:54 +00001171 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001172
1173 Scope.setActive(false);
1174}
1175
1176llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1177 if (!NormalCleanupDest)
1178 NormalCleanupDest =
1179 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1180 return NormalCleanupDest;
1181}
Peter Collingbourne702b2842011-11-27 22:09:22 +00001182
1183/// Emits all the code to cause the given temporary to be cleaned up.
1184void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1185 QualType TempType,
1186 llvm::Value *Ptr) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001187 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
Peter Collingbourne702b2842011-11-27 22:09:22 +00001188 /*useEHCleanup*/ true);
1189}