1f4a2713aSLionel Sambuc //===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file contains code dealing with the IR generation for cleanups
11f4a2713aSLionel Sambuc // and related information.
12f4a2713aSLionel Sambuc //
13f4a2713aSLionel Sambuc // A "cleanup" is a piece of code which needs to be executed whenever
14f4a2713aSLionel Sambuc // control transfers out of a particular scope. This can be
15f4a2713aSLionel Sambuc // conditionalized to occur only on exceptional control flow, only on
16f4a2713aSLionel Sambuc // normal control flow, or both.
17f4a2713aSLionel Sambuc //
18f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
19f4a2713aSLionel Sambuc
20f4a2713aSLionel Sambuc #include "CGCleanup.h"
21f4a2713aSLionel Sambuc #include "CodeGenFunction.h"
22f4a2713aSLionel Sambuc
23f4a2713aSLionel Sambuc using namespace clang;
24f4a2713aSLionel Sambuc using namespace CodeGen;
25f4a2713aSLionel Sambuc
needsSaving(RValue rv)26f4a2713aSLionel Sambuc bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
27f4a2713aSLionel Sambuc if (rv.isScalar())
28f4a2713aSLionel Sambuc return DominatingLLVMValue::needsSaving(rv.getScalarVal());
29f4a2713aSLionel Sambuc if (rv.isAggregate())
30f4a2713aSLionel Sambuc return DominatingLLVMValue::needsSaving(rv.getAggregateAddr());
31f4a2713aSLionel Sambuc return true;
32f4a2713aSLionel Sambuc }
33f4a2713aSLionel Sambuc
34f4a2713aSLionel Sambuc DominatingValue<RValue>::saved_type
save(CodeGenFunction & CGF,RValue rv)35f4a2713aSLionel Sambuc DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
36f4a2713aSLionel Sambuc if (rv.isScalar()) {
37f4a2713aSLionel Sambuc llvm::Value *V = rv.getScalarVal();
38f4a2713aSLionel Sambuc
39f4a2713aSLionel Sambuc // These automatically dominate and don't need to be saved.
40f4a2713aSLionel Sambuc if (!DominatingLLVMValue::needsSaving(V))
41f4a2713aSLionel Sambuc return saved_type(V, ScalarLiteral);
42f4a2713aSLionel Sambuc
43f4a2713aSLionel Sambuc // Everything else needs an alloca.
44f4a2713aSLionel Sambuc llvm::Value *addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
45f4a2713aSLionel Sambuc CGF.Builder.CreateStore(V, addr);
46f4a2713aSLionel Sambuc return saved_type(addr, ScalarAddress);
47f4a2713aSLionel Sambuc }
48f4a2713aSLionel Sambuc
49f4a2713aSLionel Sambuc if (rv.isComplex()) {
50f4a2713aSLionel Sambuc CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
51f4a2713aSLionel Sambuc llvm::Type *ComplexTy =
52f4a2713aSLionel Sambuc llvm::StructType::get(V.first->getType(), V.second->getType(),
53*0a6a1f1dSLionel Sambuc (void*) nullptr);
54f4a2713aSLionel Sambuc llvm::Value *addr = CGF.CreateTempAlloca(ComplexTy, "saved-complex");
55f4a2713aSLionel Sambuc CGF.Builder.CreateStore(V.first, CGF.Builder.CreateStructGEP(addr, 0));
56f4a2713aSLionel Sambuc CGF.Builder.CreateStore(V.second, CGF.Builder.CreateStructGEP(addr, 1));
57f4a2713aSLionel Sambuc return saved_type(addr, ComplexAddress);
58f4a2713aSLionel Sambuc }
59f4a2713aSLionel Sambuc
60f4a2713aSLionel Sambuc assert(rv.isAggregate());
61f4a2713aSLionel Sambuc llvm::Value *V = rv.getAggregateAddr(); // TODO: volatile?
62f4a2713aSLionel Sambuc if (!DominatingLLVMValue::needsSaving(V))
63f4a2713aSLionel Sambuc return saved_type(V, AggregateLiteral);
64f4a2713aSLionel Sambuc
65f4a2713aSLionel Sambuc llvm::Value *addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
66f4a2713aSLionel Sambuc CGF.Builder.CreateStore(V, addr);
67f4a2713aSLionel Sambuc return saved_type(addr, AggregateAddress);
68f4a2713aSLionel Sambuc }
69f4a2713aSLionel Sambuc
70f4a2713aSLionel Sambuc /// Given a saved r-value produced by SaveRValue, perform the code
71f4a2713aSLionel Sambuc /// necessary to restore it to usability at the current insertion
72f4a2713aSLionel Sambuc /// point.
restore(CodeGenFunction & CGF)73f4a2713aSLionel Sambuc RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
74f4a2713aSLionel Sambuc switch (K) {
75f4a2713aSLionel Sambuc case ScalarLiteral:
76f4a2713aSLionel Sambuc return RValue::get(Value);
77f4a2713aSLionel Sambuc case ScalarAddress:
78f4a2713aSLionel Sambuc return RValue::get(CGF.Builder.CreateLoad(Value));
79f4a2713aSLionel Sambuc case AggregateLiteral:
80f4a2713aSLionel Sambuc return RValue::getAggregate(Value);
81f4a2713aSLionel Sambuc case AggregateAddress:
82f4a2713aSLionel Sambuc return RValue::getAggregate(CGF.Builder.CreateLoad(Value));
83f4a2713aSLionel Sambuc case ComplexAddress: {
84f4a2713aSLionel Sambuc llvm::Value *real =
85f4a2713aSLionel Sambuc CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(Value, 0));
86f4a2713aSLionel Sambuc llvm::Value *imag =
87f4a2713aSLionel Sambuc CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(Value, 1));
88f4a2713aSLionel Sambuc return RValue::getComplex(real, imag);
89f4a2713aSLionel Sambuc }
90f4a2713aSLionel Sambuc }
91f4a2713aSLionel Sambuc
92f4a2713aSLionel Sambuc llvm_unreachable("bad saved r-value kind");
93f4a2713aSLionel Sambuc }
94f4a2713aSLionel Sambuc
95f4a2713aSLionel Sambuc /// Push an entry of the given size onto this protected-scope stack.
allocate(size_t Size)96f4a2713aSLionel Sambuc char *EHScopeStack::allocate(size_t Size) {
97f4a2713aSLionel Sambuc if (!StartOfBuffer) {
98f4a2713aSLionel Sambuc unsigned Capacity = 1024;
99f4a2713aSLionel Sambuc while (Capacity < Size) Capacity *= 2;
100f4a2713aSLionel Sambuc StartOfBuffer = new char[Capacity];
101f4a2713aSLionel Sambuc StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
102f4a2713aSLionel Sambuc } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
103f4a2713aSLionel Sambuc unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
104f4a2713aSLionel Sambuc unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
105f4a2713aSLionel Sambuc
106f4a2713aSLionel Sambuc unsigned NewCapacity = CurrentCapacity;
107f4a2713aSLionel Sambuc do {
108f4a2713aSLionel Sambuc NewCapacity *= 2;
109f4a2713aSLionel Sambuc } while (NewCapacity < UsedCapacity + Size);
110f4a2713aSLionel Sambuc
111f4a2713aSLionel Sambuc char *NewStartOfBuffer = new char[NewCapacity];
112f4a2713aSLionel Sambuc char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
113f4a2713aSLionel Sambuc char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
114f4a2713aSLionel Sambuc memcpy(NewStartOfData, StartOfData, UsedCapacity);
115f4a2713aSLionel Sambuc delete [] StartOfBuffer;
116f4a2713aSLionel Sambuc StartOfBuffer = NewStartOfBuffer;
117f4a2713aSLionel Sambuc EndOfBuffer = NewEndOfBuffer;
118f4a2713aSLionel Sambuc StartOfData = NewStartOfData;
119f4a2713aSLionel Sambuc }
120f4a2713aSLionel Sambuc
121f4a2713aSLionel Sambuc assert(StartOfBuffer + Size <= StartOfData);
122f4a2713aSLionel Sambuc StartOfData -= Size;
123f4a2713aSLionel Sambuc return StartOfData;
124f4a2713aSLionel Sambuc }
125f4a2713aSLionel Sambuc
126f4a2713aSLionel Sambuc EHScopeStack::stable_iterator
getInnermostActiveNormalCleanup() const127f4a2713aSLionel Sambuc EHScopeStack::getInnermostActiveNormalCleanup() const {
128f4a2713aSLionel Sambuc for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
129f4a2713aSLionel Sambuc si != se; ) {
130f4a2713aSLionel Sambuc EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
131f4a2713aSLionel Sambuc if (cleanup.isActive()) return si;
132f4a2713aSLionel Sambuc si = cleanup.getEnclosingNormalCleanup();
133f4a2713aSLionel Sambuc }
134f4a2713aSLionel Sambuc return stable_end();
135f4a2713aSLionel Sambuc }
136f4a2713aSLionel Sambuc
getInnermostActiveEHScope() const137f4a2713aSLionel Sambuc EHScopeStack::stable_iterator EHScopeStack::getInnermostActiveEHScope() const {
138f4a2713aSLionel Sambuc for (stable_iterator si = getInnermostEHScope(), se = stable_end();
139f4a2713aSLionel Sambuc si != se; ) {
140f4a2713aSLionel Sambuc // Skip over inactive cleanups.
141f4a2713aSLionel Sambuc EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*find(si));
142f4a2713aSLionel Sambuc if (cleanup && !cleanup->isActive()) {
143f4a2713aSLionel Sambuc si = cleanup->getEnclosingEHScope();
144f4a2713aSLionel Sambuc continue;
145f4a2713aSLionel Sambuc }
146f4a2713aSLionel Sambuc
147f4a2713aSLionel Sambuc // All other scopes are always active.
148f4a2713aSLionel Sambuc return si;
149f4a2713aSLionel Sambuc }
150f4a2713aSLionel Sambuc
151f4a2713aSLionel Sambuc return stable_end();
152f4a2713aSLionel Sambuc }
153f4a2713aSLionel Sambuc
154f4a2713aSLionel Sambuc
pushCleanup(CleanupKind Kind,size_t Size)155f4a2713aSLionel Sambuc void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
156f4a2713aSLionel Sambuc assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
157f4a2713aSLionel Sambuc char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
158f4a2713aSLionel Sambuc bool IsNormalCleanup = Kind & NormalCleanup;
159f4a2713aSLionel Sambuc bool IsEHCleanup = Kind & EHCleanup;
160f4a2713aSLionel Sambuc bool IsActive = !(Kind & InactiveCleanup);
161f4a2713aSLionel Sambuc EHCleanupScope *Scope =
162f4a2713aSLionel Sambuc new (Buffer) EHCleanupScope(IsNormalCleanup,
163f4a2713aSLionel Sambuc IsEHCleanup,
164f4a2713aSLionel Sambuc IsActive,
165f4a2713aSLionel Sambuc Size,
166f4a2713aSLionel Sambuc BranchFixups.size(),
167f4a2713aSLionel Sambuc InnermostNormalCleanup,
168f4a2713aSLionel Sambuc InnermostEHScope);
169f4a2713aSLionel Sambuc if (IsNormalCleanup)
170f4a2713aSLionel Sambuc InnermostNormalCleanup = stable_begin();
171f4a2713aSLionel Sambuc if (IsEHCleanup)
172f4a2713aSLionel Sambuc InnermostEHScope = stable_begin();
173f4a2713aSLionel Sambuc
174f4a2713aSLionel Sambuc return Scope->getCleanupBuffer();
175f4a2713aSLionel Sambuc }
176f4a2713aSLionel Sambuc
popCleanup()177f4a2713aSLionel Sambuc void EHScopeStack::popCleanup() {
178f4a2713aSLionel Sambuc assert(!empty() && "popping exception stack when not empty");
179f4a2713aSLionel Sambuc
180f4a2713aSLionel Sambuc assert(isa<EHCleanupScope>(*begin()));
181f4a2713aSLionel Sambuc EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
182f4a2713aSLionel Sambuc InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
183f4a2713aSLionel Sambuc InnermostEHScope = Cleanup.getEnclosingEHScope();
184f4a2713aSLionel Sambuc StartOfData += Cleanup.getAllocatedSize();
185f4a2713aSLionel Sambuc
186f4a2713aSLionel Sambuc // Destroy the cleanup.
187*0a6a1f1dSLionel Sambuc Cleanup.Destroy();
188f4a2713aSLionel Sambuc
189f4a2713aSLionel Sambuc // Check whether we can shrink the branch-fixups stack.
190f4a2713aSLionel Sambuc if (!BranchFixups.empty()) {
191f4a2713aSLionel Sambuc // If we no longer have any normal cleanups, all the fixups are
192f4a2713aSLionel Sambuc // complete.
193f4a2713aSLionel Sambuc if (!hasNormalCleanups())
194f4a2713aSLionel Sambuc BranchFixups.clear();
195f4a2713aSLionel Sambuc
196f4a2713aSLionel Sambuc // Otherwise we can still trim out unnecessary nulls.
197f4a2713aSLionel Sambuc else
198f4a2713aSLionel Sambuc popNullFixups();
199f4a2713aSLionel Sambuc }
200f4a2713aSLionel Sambuc }
201f4a2713aSLionel Sambuc
pushFilter(unsigned numFilters)202f4a2713aSLionel Sambuc EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
203f4a2713aSLionel Sambuc assert(getInnermostEHScope() == stable_end());
204f4a2713aSLionel Sambuc char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
205f4a2713aSLionel Sambuc EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
206f4a2713aSLionel Sambuc InnermostEHScope = stable_begin();
207f4a2713aSLionel Sambuc return filter;
208f4a2713aSLionel Sambuc }
209f4a2713aSLionel Sambuc
popFilter()210f4a2713aSLionel Sambuc void EHScopeStack::popFilter() {
211f4a2713aSLionel Sambuc assert(!empty() && "popping exception stack when not empty");
212f4a2713aSLionel Sambuc
213f4a2713aSLionel Sambuc EHFilterScope &filter = cast<EHFilterScope>(*begin());
214f4a2713aSLionel Sambuc StartOfData += EHFilterScope::getSizeForNumFilters(filter.getNumFilters());
215f4a2713aSLionel Sambuc
216f4a2713aSLionel Sambuc InnermostEHScope = filter.getEnclosingEHScope();
217f4a2713aSLionel Sambuc }
218f4a2713aSLionel Sambuc
pushCatch(unsigned numHandlers)219f4a2713aSLionel Sambuc EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
220f4a2713aSLionel Sambuc char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
221f4a2713aSLionel Sambuc EHCatchScope *scope =
222f4a2713aSLionel Sambuc new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
223f4a2713aSLionel Sambuc InnermostEHScope = stable_begin();
224f4a2713aSLionel Sambuc return scope;
225f4a2713aSLionel Sambuc }
226f4a2713aSLionel Sambuc
pushTerminate()227f4a2713aSLionel Sambuc void EHScopeStack::pushTerminate() {
228f4a2713aSLionel Sambuc char *Buffer = allocate(EHTerminateScope::getSize());
229f4a2713aSLionel Sambuc new (Buffer) EHTerminateScope(InnermostEHScope);
230f4a2713aSLionel Sambuc InnermostEHScope = stable_begin();
231f4a2713aSLionel Sambuc }
232f4a2713aSLionel Sambuc
233f4a2713aSLionel Sambuc /// Remove any 'null' fixups on the stack. However, we can't pop more
234f4a2713aSLionel Sambuc /// fixups than the fixup depth on the innermost normal cleanup, or
235f4a2713aSLionel Sambuc /// else fixups that we try to add to that cleanup will end up in the
236f4a2713aSLionel Sambuc /// wrong place. We *could* try to shrink fixup depths, but that's
237f4a2713aSLionel Sambuc /// actually a lot of work for little benefit.
popNullFixups()238f4a2713aSLionel Sambuc void EHScopeStack::popNullFixups() {
239f4a2713aSLionel Sambuc // We expect this to only be called when there's still an innermost
240f4a2713aSLionel Sambuc // normal cleanup; otherwise there really shouldn't be any fixups.
241f4a2713aSLionel Sambuc assert(hasNormalCleanups());
242f4a2713aSLionel Sambuc
243f4a2713aSLionel Sambuc EHScopeStack::iterator it = find(InnermostNormalCleanup);
244f4a2713aSLionel Sambuc unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
245f4a2713aSLionel Sambuc assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
246f4a2713aSLionel Sambuc
247f4a2713aSLionel Sambuc while (BranchFixups.size() > MinSize &&
248*0a6a1f1dSLionel Sambuc BranchFixups.back().Destination == nullptr)
249f4a2713aSLionel Sambuc BranchFixups.pop_back();
250f4a2713aSLionel Sambuc }
251f4a2713aSLionel Sambuc
initFullExprCleanup()252f4a2713aSLionel Sambuc void CodeGenFunction::initFullExprCleanup() {
253f4a2713aSLionel Sambuc // Create a variable to decide whether the cleanup needs to be run.
254f4a2713aSLionel Sambuc llvm::AllocaInst *active
255f4a2713aSLionel Sambuc = CreateTempAlloca(Builder.getInt1Ty(), "cleanup.cond");
256f4a2713aSLionel Sambuc
257f4a2713aSLionel Sambuc // Initialize it to false at a site that's guaranteed to be run
258f4a2713aSLionel Sambuc // before each evaluation.
259f4a2713aSLionel Sambuc setBeforeOutermostConditional(Builder.getFalse(), active);
260f4a2713aSLionel Sambuc
261f4a2713aSLionel Sambuc // Initialize it to true at the current location.
262f4a2713aSLionel Sambuc Builder.CreateStore(Builder.getTrue(), active);
263f4a2713aSLionel Sambuc
264f4a2713aSLionel Sambuc // Set that as the active flag in the cleanup.
265f4a2713aSLionel Sambuc EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
266*0a6a1f1dSLionel Sambuc assert(!cleanup.getActiveFlag() && "cleanup already has active flag?");
267f4a2713aSLionel Sambuc cleanup.setActiveFlag(active);
268f4a2713aSLionel Sambuc
269f4a2713aSLionel Sambuc if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
270f4a2713aSLionel Sambuc if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
271f4a2713aSLionel Sambuc }
272f4a2713aSLionel Sambuc
anchor()273f4a2713aSLionel Sambuc void EHScopeStack::Cleanup::anchor() {}
274f4a2713aSLionel Sambuc
275f4a2713aSLionel Sambuc /// All the branch fixups on the EH stack have propagated out past the
276f4a2713aSLionel Sambuc /// outermost normal cleanup; resolve them all by adding cases to the
277f4a2713aSLionel Sambuc /// given switch instruction.
ResolveAllBranchFixups(CodeGenFunction & CGF,llvm::SwitchInst * Switch,llvm::BasicBlock * CleanupEntry)278f4a2713aSLionel Sambuc static void ResolveAllBranchFixups(CodeGenFunction &CGF,
279f4a2713aSLionel Sambuc llvm::SwitchInst *Switch,
280f4a2713aSLionel Sambuc llvm::BasicBlock *CleanupEntry) {
281f4a2713aSLionel Sambuc llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
282f4a2713aSLionel Sambuc
283f4a2713aSLionel Sambuc for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
284f4a2713aSLionel Sambuc // Skip this fixup if its destination isn't set.
285f4a2713aSLionel Sambuc BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
286*0a6a1f1dSLionel Sambuc if (Fixup.Destination == nullptr) continue;
287f4a2713aSLionel Sambuc
288f4a2713aSLionel Sambuc // If there isn't an OptimisticBranchBlock, then InitialBranch is
289f4a2713aSLionel Sambuc // still pointing directly to its destination; forward it to the
290f4a2713aSLionel Sambuc // appropriate cleanup entry. This is required in the specific
291f4a2713aSLionel Sambuc // case of
292f4a2713aSLionel Sambuc // { std::string s; goto lbl; }
293f4a2713aSLionel Sambuc // lbl:
294f4a2713aSLionel Sambuc // i.e. where there's an unresolved fixup inside a single cleanup
295f4a2713aSLionel Sambuc // entry which we're currently popping.
296*0a6a1f1dSLionel Sambuc if (Fixup.OptimisticBranchBlock == nullptr) {
297f4a2713aSLionel Sambuc new llvm::StoreInst(CGF.Builder.getInt32(Fixup.DestinationIndex),
298f4a2713aSLionel Sambuc CGF.getNormalCleanupDestSlot(),
299f4a2713aSLionel Sambuc Fixup.InitialBranch);
300f4a2713aSLionel Sambuc Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
301f4a2713aSLionel Sambuc }
302f4a2713aSLionel Sambuc
303f4a2713aSLionel Sambuc // Don't add this case to the switch statement twice.
304*0a6a1f1dSLionel Sambuc if (!CasesAdded.insert(Fixup.Destination).second)
305*0a6a1f1dSLionel Sambuc continue;
306f4a2713aSLionel Sambuc
307f4a2713aSLionel Sambuc Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
308f4a2713aSLionel Sambuc Fixup.Destination);
309f4a2713aSLionel Sambuc }
310f4a2713aSLionel Sambuc
311f4a2713aSLionel Sambuc CGF.EHStack.clearFixups();
312f4a2713aSLionel Sambuc }
313f4a2713aSLionel Sambuc
314f4a2713aSLionel Sambuc /// Transitions the terminator of the given exit-block of a cleanup to
315f4a2713aSLionel Sambuc /// be a cleanup switch.
TransitionToCleanupSwitch(CodeGenFunction & CGF,llvm::BasicBlock * Block)316f4a2713aSLionel Sambuc static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
317f4a2713aSLionel Sambuc llvm::BasicBlock *Block) {
318f4a2713aSLionel Sambuc // If it's a branch, turn it into a switch whose default
319f4a2713aSLionel Sambuc // destination is its original target.
320f4a2713aSLionel Sambuc llvm::TerminatorInst *Term = Block->getTerminator();
321f4a2713aSLionel Sambuc assert(Term && "can't transition block without terminator");
322f4a2713aSLionel Sambuc
323f4a2713aSLionel Sambuc if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
324f4a2713aSLionel Sambuc assert(Br->isUnconditional());
325f4a2713aSLionel Sambuc llvm::LoadInst *Load =
326f4a2713aSLionel Sambuc new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
327f4a2713aSLionel Sambuc llvm::SwitchInst *Switch =
328f4a2713aSLionel Sambuc llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
329f4a2713aSLionel Sambuc Br->eraseFromParent();
330f4a2713aSLionel Sambuc return Switch;
331f4a2713aSLionel Sambuc } else {
332f4a2713aSLionel Sambuc return cast<llvm::SwitchInst>(Term);
333f4a2713aSLionel Sambuc }
334f4a2713aSLionel Sambuc }
335f4a2713aSLionel Sambuc
ResolveBranchFixups(llvm::BasicBlock * Block)336f4a2713aSLionel Sambuc void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
337f4a2713aSLionel Sambuc assert(Block && "resolving a null target block");
338f4a2713aSLionel Sambuc if (!EHStack.getNumBranchFixups()) return;
339f4a2713aSLionel Sambuc
340f4a2713aSLionel Sambuc assert(EHStack.hasNormalCleanups() &&
341f4a2713aSLionel Sambuc "branch fixups exist with no normal cleanups on stack");
342f4a2713aSLionel Sambuc
343f4a2713aSLionel Sambuc llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
344f4a2713aSLionel Sambuc bool ResolvedAny = false;
345f4a2713aSLionel Sambuc
346f4a2713aSLionel Sambuc for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
347f4a2713aSLionel Sambuc // Skip this fixup if its destination doesn't match.
348f4a2713aSLionel Sambuc BranchFixup &Fixup = EHStack.getBranchFixup(I);
349f4a2713aSLionel Sambuc if (Fixup.Destination != Block) continue;
350f4a2713aSLionel Sambuc
351*0a6a1f1dSLionel Sambuc Fixup.Destination = nullptr;
352f4a2713aSLionel Sambuc ResolvedAny = true;
353f4a2713aSLionel Sambuc
354f4a2713aSLionel Sambuc // If it doesn't have an optimistic branch block, LatestBranch is
355f4a2713aSLionel Sambuc // already pointing to the right place.
356f4a2713aSLionel Sambuc llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
357f4a2713aSLionel Sambuc if (!BranchBB)
358f4a2713aSLionel Sambuc continue;
359f4a2713aSLionel Sambuc
360f4a2713aSLionel Sambuc // Don't process the same optimistic branch block twice.
361*0a6a1f1dSLionel Sambuc if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
362f4a2713aSLionel Sambuc continue;
363f4a2713aSLionel Sambuc
364f4a2713aSLionel Sambuc llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
365f4a2713aSLionel Sambuc
366f4a2713aSLionel Sambuc // Add a case to the switch.
367f4a2713aSLionel Sambuc Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
368f4a2713aSLionel Sambuc }
369f4a2713aSLionel Sambuc
370f4a2713aSLionel Sambuc if (ResolvedAny)
371f4a2713aSLionel Sambuc EHStack.popNullFixups();
372f4a2713aSLionel Sambuc }
373f4a2713aSLionel Sambuc
374f4a2713aSLionel Sambuc /// Pops cleanup blocks until the given savepoint is reached.
PopCleanupBlocks(EHScopeStack::stable_iterator Old)375f4a2713aSLionel Sambuc void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
376f4a2713aSLionel Sambuc assert(Old.isValid());
377f4a2713aSLionel Sambuc
378f4a2713aSLionel Sambuc while (EHStack.stable_begin() != Old) {
379f4a2713aSLionel Sambuc EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
380f4a2713aSLionel Sambuc
381f4a2713aSLionel Sambuc // As long as Old strictly encloses the scope's enclosing normal
382f4a2713aSLionel Sambuc // cleanup, we're going to emit another normal cleanup which
383f4a2713aSLionel Sambuc // fallthrough can propagate through.
384f4a2713aSLionel Sambuc bool FallThroughIsBranchThrough =
385f4a2713aSLionel Sambuc Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
386f4a2713aSLionel Sambuc
387f4a2713aSLionel Sambuc PopCleanupBlock(FallThroughIsBranchThrough);
388f4a2713aSLionel Sambuc }
389f4a2713aSLionel Sambuc }
390f4a2713aSLionel Sambuc
391f4a2713aSLionel Sambuc /// Pops cleanup blocks until the given savepoint is reached, then add the
392f4a2713aSLionel Sambuc /// cleanups from the given savepoint in the lifetime-extended cleanups stack.
393f4a2713aSLionel Sambuc void
PopCleanupBlocks(EHScopeStack::stable_iterator Old,size_t OldLifetimeExtendedSize)394f4a2713aSLionel Sambuc CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old,
395f4a2713aSLionel Sambuc size_t OldLifetimeExtendedSize) {
396f4a2713aSLionel Sambuc PopCleanupBlocks(Old);
397f4a2713aSLionel Sambuc
398f4a2713aSLionel Sambuc // Move our deferred cleanups onto the EH stack.
399f4a2713aSLionel Sambuc for (size_t I = OldLifetimeExtendedSize,
400f4a2713aSLionel Sambuc E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
401f4a2713aSLionel Sambuc // Alignment should be guaranteed by the vptrs in the individual cleanups.
402f4a2713aSLionel Sambuc assert((I % llvm::alignOf<LifetimeExtendedCleanupHeader>() == 0) &&
403f4a2713aSLionel Sambuc "misaligned cleanup stack entry");
404f4a2713aSLionel Sambuc
405f4a2713aSLionel Sambuc LifetimeExtendedCleanupHeader &Header =
406f4a2713aSLionel Sambuc reinterpret_cast<LifetimeExtendedCleanupHeader&>(
407f4a2713aSLionel Sambuc LifetimeExtendedCleanupStack[I]);
408f4a2713aSLionel Sambuc I += sizeof(Header);
409f4a2713aSLionel Sambuc
410f4a2713aSLionel Sambuc EHStack.pushCopyOfCleanup(Header.getKind(),
411f4a2713aSLionel Sambuc &LifetimeExtendedCleanupStack[I],
412f4a2713aSLionel Sambuc Header.getSize());
413f4a2713aSLionel Sambuc I += Header.getSize();
414f4a2713aSLionel Sambuc }
415f4a2713aSLionel Sambuc LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
416f4a2713aSLionel Sambuc }
417f4a2713aSLionel Sambuc
CreateNormalEntry(CodeGenFunction & CGF,EHCleanupScope & Scope)418f4a2713aSLionel Sambuc static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
419f4a2713aSLionel Sambuc EHCleanupScope &Scope) {
420f4a2713aSLionel Sambuc assert(Scope.isNormalCleanup());
421f4a2713aSLionel Sambuc llvm::BasicBlock *Entry = Scope.getNormalBlock();
422f4a2713aSLionel Sambuc if (!Entry) {
423f4a2713aSLionel Sambuc Entry = CGF.createBasicBlock("cleanup");
424f4a2713aSLionel Sambuc Scope.setNormalBlock(Entry);
425f4a2713aSLionel Sambuc }
426f4a2713aSLionel Sambuc return Entry;
427f4a2713aSLionel Sambuc }
428f4a2713aSLionel Sambuc
429f4a2713aSLionel Sambuc /// Attempts to reduce a cleanup's entry block to a fallthrough. This
430f4a2713aSLionel Sambuc /// is basically llvm::MergeBlockIntoPredecessor, except
431f4a2713aSLionel Sambuc /// simplified/optimized for the tighter constraints on cleanup blocks.
432f4a2713aSLionel Sambuc ///
433f4a2713aSLionel Sambuc /// Returns the new block, whatever it is.
SimplifyCleanupEntry(CodeGenFunction & CGF,llvm::BasicBlock * Entry)434f4a2713aSLionel Sambuc static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
435f4a2713aSLionel Sambuc llvm::BasicBlock *Entry) {
436f4a2713aSLionel Sambuc llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
437f4a2713aSLionel Sambuc if (!Pred) return Entry;
438f4a2713aSLionel Sambuc
439f4a2713aSLionel Sambuc llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
440f4a2713aSLionel Sambuc if (!Br || Br->isConditional()) return Entry;
441f4a2713aSLionel Sambuc assert(Br->getSuccessor(0) == Entry);
442f4a2713aSLionel Sambuc
443f4a2713aSLionel Sambuc // If we were previously inserting at the end of the cleanup entry
444f4a2713aSLionel Sambuc // block, we'll need to continue inserting at the end of the
445f4a2713aSLionel Sambuc // predecessor.
446f4a2713aSLionel Sambuc bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
447f4a2713aSLionel Sambuc assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
448f4a2713aSLionel Sambuc
449f4a2713aSLionel Sambuc // Kill the branch.
450f4a2713aSLionel Sambuc Br->eraseFromParent();
451f4a2713aSLionel Sambuc
452f4a2713aSLionel Sambuc // Replace all uses of the entry with the predecessor, in case there
453f4a2713aSLionel Sambuc // are phis in the cleanup.
454f4a2713aSLionel Sambuc Entry->replaceAllUsesWith(Pred);
455f4a2713aSLionel Sambuc
456f4a2713aSLionel Sambuc // Merge the blocks.
457f4a2713aSLionel Sambuc Pred->getInstList().splice(Pred->end(), Entry->getInstList());
458f4a2713aSLionel Sambuc
459f4a2713aSLionel Sambuc // Kill the entry block.
460f4a2713aSLionel Sambuc Entry->eraseFromParent();
461f4a2713aSLionel Sambuc
462f4a2713aSLionel Sambuc if (WasInsertBlock)
463f4a2713aSLionel Sambuc CGF.Builder.SetInsertPoint(Pred);
464f4a2713aSLionel Sambuc
465f4a2713aSLionel Sambuc return Pred;
466f4a2713aSLionel Sambuc }
467f4a2713aSLionel Sambuc
EmitCleanup(CodeGenFunction & CGF,EHScopeStack::Cleanup * Fn,EHScopeStack::Cleanup::Flags flags,llvm::Value * ActiveFlag)468f4a2713aSLionel Sambuc static void EmitCleanup(CodeGenFunction &CGF,
469f4a2713aSLionel Sambuc EHScopeStack::Cleanup *Fn,
470f4a2713aSLionel Sambuc EHScopeStack::Cleanup::Flags flags,
471f4a2713aSLionel Sambuc llvm::Value *ActiveFlag) {
472f4a2713aSLionel Sambuc // EH cleanups always occur within a terminate scope.
473f4a2713aSLionel Sambuc if (flags.isForEHCleanup()) CGF.EHStack.pushTerminate();
474f4a2713aSLionel Sambuc
475f4a2713aSLionel Sambuc // If there's an active flag, load it and skip the cleanup if it's
476f4a2713aSLionel Sambuc // false.
477*0a6a1f1dSLionel Sambuc llvm::BasicBlock *ContBB = nullptr;
478f4a2713aSLionel Sambuc if (ActiveFlag) {
479f4a2713aSLionel Sambuc ContBB = CGF.createBasicBlock("cleanup.done");
480f4a2713aSLionel Sambuc llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
481f4a2713aSLionel Sambuc llvm::Value *IsActive
482f4a2713aSLionel Sambuc = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
483f4a2713aSLionel Sambuc CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
484f4a2713aSLionel Sambuc CGF.EmitBlock(CleanupBB);
485f4a2713aSLionel Sambuc }
486f4a2713aSLionel Sambuc
487f4a2713aSLionel Sambuc // Ask the cleanup to emit itself.
488f4a2713aSLionel Sambuc Fn->Emit(CGF, flags);
489f4a2713aSLionel Sambuc assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
490f4a2713aSLionel Sambuc
491f4a2713aSLionel Sambuc // Emit the continuation block if there was an active flag.
492f4a2713aSLionel Sambuc if (ActiveFlag)
493f4a2713aSLionel Sambuc CGF.EmitBlock(ContBB);
494f4a2713aSLionel Sambuc
495f4a2713aSLionel Sambuc // Leave the terminate scope.
496f4a2713aSLionel Sambuc if (flags.isForEHCleanup()) CGF.EHStack.popTerminate();
497f4a2713aSLionel Sambuc }
498f4a2713aSLionel Sambuc
ForwardPrebranchedFallthrough(llvm::BasicBlock * Exit,llvm::BasicBlock * From,llvm::BasicBlock * To)499f4a2713aSLionel Sambuc static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
500f4a2713aSLionel Sambuc llvm::BasicBlock *From,
501f4a2713aSLionel Sambuc llvm::BasicBlock *To) {
502f4a2713aSLionel Sambuc // Exit is the exit block of a cleanup, so it always terminates in
503f4a2713aSLionel Sambuc // an unconditional branch or a switch.
504f4a2713aSLionel Sambuc llvm::TerminatorInst *Term = Exit->getTerminator();
505f4a2713aSLionel Sambuc
506f4a2713aSLionel Sambuc if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
507f4a2713aSLionel Sambuc assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
508f4a2713aSLionel Sambuc Br->setSuccessor(0, To);
509f4a2713aSLionel Sambuc } else {
510f4a2713aSLionel Sambuc llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
511f4a2713aSLionel Sambuc for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
512f4a2713aSLionel Sambuc if (Switch->getSuccessor(I) == From)
513f4a2713aSLionel Sambuc Switch->setSuccessor(I, To);
514f4a2713aSLionel Sambuc }
515f4a2713aSLionel Sambuc }
516f4a2713aSLionel Sambuc
517f4a2713aSLionel Sambuc /// We don't need a normal entry block for the given cleanup.
518f4a2713aSLionel Sambuc /// Optimistic fixup branches can cause these blocks to come into
519f4a2713aSLionel Sambuc /// existence anyway; if so, destroy it.
520f4a2713aSLionel Sambuc ///
521f4a2713aSLionel Sambuc /// The validity of this transformation is very much specific to the
522f4a2713aSLionel Sambuc /// exact ways in which we form branches to cleanup entries.
destroyOptimisticNormalEntry(CodeGenFunction & CGF,EHCleanupScope & scope)523f4a2713aSLionel Sambuc static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
524f4a2713aSLionel Sambuc EHCleanupScope &scope) {
525f4a2713aSLionel Sambuc llvm::BasicBlock *entry = scope.getNormalBlock();
526f4a2713aSLionel Sambuc if (!entry) return;
527f4a2713aSLionel Sambuc
528f4a2713aSLionel Sambuc // Replace all the uses with unreachable.
529f4a2713aSLionel Sambuc llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
530f4a2713aSLionel Sambuc for (llvm::BasicBlock::use_iterator
531f4a2713aSLionel Sambuc i = entry->use_begin(), e = entry->use_end(); i != e; ) {
532*0a6a1f1dSLionel Sambuc llvm::Use &use = *i;
533f4a2713aSLionel Sambuc ++i;
534f4a2713aSLionel Sambuc
535f4a2713aSLionel Sambuc use.set(unreachableBB);
536f4a2713aSLionel Sambuc
537f4a2713aSLionel Sambuc // The only uses should be fixup switches.
538f4a2713aSLionel Sambuc llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
539f4a2713aSLionel Sambuc if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
540f4a2713aSLionel Sambuc // Replace the switch with a branch.
541f4a2713aSLionel Sambuc llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
542f4a2713aSLionel Sambuc
543f4a2713aSLionel Sambuc // The switch operand is a load from the cleanup-dest alloca.
544f4a2713aSLionel Sambuc llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
545f4a2713aSLionel Sambuc
546f4a2713aSLionel Sambuc // Destroy the switch.
547f4a2713aSLionel Sambuc si->eraseFromParent();
548f4a2713aSLionel Sambuc
549f4a2713aSLionel Sambuc // Destroy the load.
550f4a2713aSLionel Sambuc assert(condition->getOperand(0) == CGF.NormalCleanupDest);
551f4a2713aSLionel Sambuc assert(condition->use_empty());
552f4a2713aSLionel Sambuc condition->eraseFromParent();
553f4a2713aSLionel Sambuc }
554f4a2713aSLionel Sambuc }
555f4a2713aSLionel Sambuc
556f4a2713aSLionel Sambuc assert(entry->use_empty());
557f4a2713aSLionel Sambuc delete entry;
558f4a2713aSLionel Sambuc }
559f4a2713aSLionel Sambuc
560f4a2713aSLionel Sambuc /// Pops a cleanup block. If the block includes a normal cleanup, the
561f4a2713aSLionel Sambuc /// current insertion point is threaded through the cleanup, as are
562f4a2713aSLionel Sambuc /// any branch fixups on the cleanup.
PopCleanupBlock(bool FallthroughIsBranchThrough)563f4a2713aSLionel Sambuc void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
564f4a2713aSLionel Sambuc assert(!EHStack.empty() && "cleanup stack is empty!");
565f4a2713aSLionel Sambuc assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
566f4a2713aSLionel Sambuc EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
567f4a2713aSLionel Sambuc assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
568f4a2713aSLionel Sambuc
569f4a2713aSLionel Sambuc // Remember activation information.
570f4a2713aSLionel Sambuc bool IsActive = Scope.isActive();
571f4a2713aSLionel Sambuc llvm::Value *NormalActiveFlag =
572*0a6a1f1dSLionel Sambuc Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : nullptr;
573f4a2713aSLionel Sambuc llvm::Value *EHActiveFlag =
574*0a6a1f1dSLionel Sambuc Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : nullptr;
575f4a2713aSLionel Sambuc
576f4a2713aSLionel Sambuc // Check whether we need an EH cleanup. This is only true if we've
577f4a2713aSLionel Sambuc // generated a lazy EH cleanup block.
578f4a2713aSLionel Sambuc llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
579*0a6a1f1dSLionel Sambuc assert(Scope.hasEHBranches() == (EHEntry != nullptr));
580*0a6a1f1dSLionel Sambuc bool RequiresEHCleanup = (EHEntry != nullptr);
581f4a2713aSLionel Sambuc EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
582f4a2713aSLionel Sambuc
583f4a2713aSLionel Sambuc // Check the three conditions which might require a normal cleanup:
584f4a2713aSLionel Sambuc
585f4a2713aSLionel Sambuc // - whether there are branch fix-ups through this cleanup
586f4a2713aSLionel Sambuc unsigned FixupDepth = Scope.getFixupDepth();
587f4a2713aSLionel Sambuc bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
588f4a2713aSLionel Sambuc
589f4a2713aSLionel Sambuc // - whether there are branch-throughs or branch-afters
590f4a2713aSLionel Sambuc bool HasExistingBranches = Scope.hasBranches();
591f4a2713aSLionel Sambuc
592f4a2713aSLionel Sambuc // - whether there's a fallthrough
593f4a2713aSLionel Sambuc llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
594*0a6a1f1dSLionel Sambuc bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
595f4a2713aSLionel Sambuc
596f4a2713aSLionel Sambuc // Branch-through fall-throughs leave the insertion point set to the
597f4a2713aSLionel Sambuc // end of the last cleanup, which points to the current scope. The
598f4a2713aSLionel Sambuc // rest of IR gen doesn't need to worry about this; it only happens
599f4a2713aSLionel Sambuc // during the execution of PopCleanupBlocks().
600f4a2713aSLionel Sambuc bool HasPrebranchedFallthrough =
601f4a2713aSLionel Sambuc (FallthroughSource && FallthroughSource->getTerminator());
602f4a2713aSLionel Sambuc
603f4a2713aSLionel Sambuc // If this is a normal cleanup, then having a prebranched
604f4a2713aSLionel Sambuc // fallthrough implies that the fallthrough source unconditionally
605f4a2713aSLionel Sambuc // jumps here.
606f4a2713aSLionel Sambuc assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
607f4a2713aSLionel Sambuc (Scope.getNormalBlock() &&
608f4a2713aSLionel Sambuc FallthroughSource->getTerminator()->getSuccessor(0)
609f4a2713aSLionel Sambuc == Scope.getNormalBlock()));
610f4a2713aSLionel Sambuc
611f4a2713aSLionel Sambuc bool RequiresNormalCleanup = false;
612f4a2713aSLionel Sambuc if (Scope.isNormalCleanup() &&
613f4a2713aSLionel Sambuc (HasFixups || HasExistingBranches || HasFallthrough)) {
614f4a2713aSLionel Sambuc RequiresNormalCleanup = true;
615f4a2713aSLionel Sambuc }
616f4a2713aSLionel Sambuc
617f4a2713aSLionel Sambuc // If we have a prebranched fallthrough into an inactive normal
618f4a2713aSLionel Sambuc // cleanup, rewrite it so that it leads to the appropriate place.
619f4a2713aSLionel Sambuc if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
620f4a2713aSLionel Sambuc llvm::BasicBlock *prebranchDest;
621f4a2713aSLionel Sambuc
622f4a2713aSLionel Sambuc // If the prebranch is semantically branching through the next
623f4a2713aSLionel Sambuc // cleanup, just forward it to the next block, leaving the
624f4a2713aSLionel Sambuc // insertion point in the prebranched block.
625f4a2713aSLionel Sambuc if (FallthroughIsBranchThrough) {
626f4a2713aSLionel Sambuc EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
627f4a2713aSLionel Sambuc prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
628f4a2713aSLionel Sambuc
629f4a2713aSLionel Sambuc // Otherwise, we need to make a new block. If the normal cleanup
630f4a2713aSLionel Sambuc // isn't being used at all, we could actually reuse the normal
631f4a2713aSLionel Sambuc // entry block, but this is simpler, and it avoids conflicts with
632f4a2713aSLionel Sambuc // dead optimistic fixup branches.
633f4a2713aSLionel Sambuc } else {
634f4a2713aSLionel Sambuc prebranchDest = createBasicBlock("forwarded-prebranch");
635f4a2713aSLionel Sambuc EmitBlock(prebranchDest);
636f4a2713aSLionel Sambuc }
637f4a2713aSLionel Sambuc
638f4a2713aSLionel Sambuc llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
639f4a2713aSLionel Sambuc assert(normalEntry && !normalEntry->use_empty());
640f4a2713aSLionel Sambuc
641f4a2713aSLionel Sambuc ForwardPrebranchedFallthrough(FallthroughSource,
642f4a2713aSLionel Sambuc normalEntry, prebranchDest);
643f4a2713aSLionel Sambuc }
644f4a2713aSLionel Sambuc
645f4a2713aSLionel Sambuc // If we don't need the cleanup at all, we're done.
646f4a2713aSLionel Sambuc if (!RequiresNormalCleanup && !RequiresEHCleanup) {
647f4a2713aSLionel Sambuc destroyOptimisticNormalEntry(*this, Scope);
648f4a2713aSLionel Sambuc EHStack.popCleanup(); // safe because there are no fixups
649f4a2713aSLionel Sambuc assert(EHStack.getNumBranchFixups() == 0 ||
650f4a2713aSLionel Sambuc EHStack.hasNormalCleanups());
651f4a2713aSLionel Sambuc return;
652f4a2713aSLionel Sambuc }
653f4a2713aSLionel Sambuc
654f4a2713aSLionel Sambuc // Copy the cleanup emission data out. Note that SmallVector
655f4a2713aSLionel Sambuc // guarantees maximal alignment for its buffer regardless of its
656f4a2713aSLionel Sambuc // type parameter.
657f4a2713aSLionel Sambuc SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
658f4a2713aSLionel Sambuc CleanupBuffer.reserve(Scope.getCleanupSize());
659f4a2713aSLionel Sambuc memcpy(CleanupBuffer.data(),
660f4a2713aSLionel Sambuc Scope.getCleanupBuffer(), Scope.getCleanupSize());
661f4a2713aSLionel Sambuc CleanupBuffer.set_size(Scope.getCleanupSize());
662f4a2713aSLionel Sambuc EHScopeStack::Cleanup *Fn =
663f4a2713aSLionel Sambuc reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
664f4a2713aSLionel Sambuc
665f4a2713aSLionel Sambuc EHScopeStack::Cleanup::Flags cleanupFlags;
666f4a2713aSLionel Sambuc if (Scope.isNormalCleanup())
667f4a2713aSLionel Sambuc cleanupFlags.setIsNormalCleanupKind();
668f4a2713aSLionel Sambuc if (Scope.isEHCleanup())
669f4a2713aSLionel Sambuc cleanupFlags.setIsEHCleanupKind();
670f4a2713aSLionel Sambuc
671f4a2713aSLionel Sambuc if (!RequiresNormalCleanup) {
672f4a2713aSLionel Sambuc destroyOptimisticNormalEntry(*this, Scope);
673f4a2713aSLionel Sambuc EHStack.popCleanup();
674f4a2713aSLionel Sambuc } else {
675f4a2713aSLionel Sambuc // If we have a fallthrough and no other need for the cleanup,
676f4a2713aSLionel Sambuc // emit it directly.
677f4a2713aSLionel Sambuc if (HasFallthrough && !HasPrebranchedFallthrough &&
678f4a2713aSLionel Sambuc !HasFixups && !HasExistingBranches) {
679f4a2713aSLionel Sambuc
680f4a2713aSLionel Sambuc destroyOptimisticNormalEntry(*this, Scope);
681f4a2713aSLionel Sambuc EHStack.popCleanup();
682f4a2713aSLionel Sambuc
683f4a2713aSLionel Sambuc EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
684f4a2713aSLionel Sambuc
685f4a2713aSLionel Sambuc // Otherwise, the best approach is to thread everything through
686f4a2713aSLionel Sambuc // the cleanup block and then try to clean up after ourselves.
687f4a2713aSLionel Sambuc } else {
688f4a2713aSLionel Sambuc // Force the entry block to exist.
689f4a2713aSLionel Sambuc llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
690f4a2713aSLionel Sambuc
691f4a2713aSLionel Sambuc // I. Set up the fallthrough edge in.
692f4a2713aSLionel Sambuc
693f4a2713aSLionel Sambuc CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
694f4a2713aSLionel Sambuc
695f4a2713aSLionel Sambuc // If there's a fallthrough, we need to store the cleanup
696f4a2713aSLionel Sambuc // destination index. For fall-throughs this is always zero.
697f4a2713aSLionel Sambuc if (HasFallthrough) {
698f4a2713aSLionel Sambuc if (!HasPrebranchedFallthrough)
699f4a2713aSLionel Sambuc Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
700f4a2713aSLionel Sambuc
701f4a2713aSLionel Sambuc // Otherwise, save and clear the IP if we don't have fallthrough
702f4a2713aSLionel Sambuc // because the cleanup is inactive.
703f4a2713aSLionel Sambuc } else if (FallthroughSource) {
704f4a2713aSLionel Sambuc assert(!IsActive && "source without fallthrough for active cleanup");
705f4a2713aSLionel Sambuc savedInactiveFallthroughIP = Builder.saveAndClearIP();
706f4a2713aSLionel Sambuc }
707f4a2713aSLionel Sambuc
708f4a2713aSLionel Sambuc // II. Emit the entry block. This implicitly branches to it if
709f4a2713aSLionel Sambuc // we have fallthrough. All the fixups and existing branches
710f4a2713aSLionel Sambuc // should already be branched to it.
711f4a2713aSLionel Sambuc EmitBlock(NormalEntry);
712f4a2713aSLionel Sambuc
713f4a2713aSLionel Sambuc // III. Figure out where we're going and build the cleanup
714f4a2713aSLionel Sambuc // epilogue.
715f4a2713aSLionel Sambuc
716f4a2713aSLionel Sambuc bool HasEnclosingCleanups =
717f4a2713aSLionel Sambuc (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
718f4a2713aSLionel Sambuc
719f4a2713aSLionel Sambuc // Compute the branch-through dest if we need it:
720f4a2713aSLionel Sambuc // - if there are branch-throughs threaded through the scope
721f4a2713aSLionel Sambuc // - if fall-through is a branch-through
722f4a2713aSLionel Sambuc // - if there are fixups that will be optimistically forwarded
723f4a2713aSLionel Sambuc // to the enclosing cleanup
724*0a6a1f1dSLionel Sambuc llvm::BasicBlock *BranchThroughDest = nullptr;
725f4a2713aSLionel Sambuc if (Scope.hasBranchThroughs() ||
726f4a2713aSLionel Sambuc (FallthroughSource && FallthroughIsBranchThrough) ||
727f4a2713aSLionel Sambuc (HasFixups && HasEnclosingCleanups)) {
728f4a2713aSLionel Sambuc assert(HasEnclosingCleanups);
729f4a2713aSLionel Sambuc EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
730f4a2713aSLionel Sambuc BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
731f4a2713aSLionel Sambuc }
732f4a2713aSLionel Sambuc
733*0a6a1f1dSLionel Sambuc llvm::BasicBlock *FallthroughDest = nullptr;
734f4a2713aSLionel Sambuc SmallVector<llvm::Instruction*, 2> InstsToAppend;
735f4a2713aSLionel Sambuc
736f4a2713aSLionel Sambuc // If there's exactly one branch-after and no other threads,
737f4a2713aSLionel Sambuc // we can route it without a switch.
738f4a2713aSLionel Sambuc if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
739f4a2713aSLionel Sambuc Scope.getNumBranchAfters() == 1) {
740f4a2713aSLionel Sambuc assert(!BranchThroughDest || !IsActive);
741f4a2713aSLionel Sambuc
742f4a2713aSLionel Sambuc // TODO: clean up the possibly dead stores to the cleanup dest slot.
743f4a2713aSLionel Sambuc llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
744f4a2713aSLionel Sambuc InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
745f4a2713aSLionel Sambuc
746f4a2713aSLionel Sambuc // Build a switch-out if we need it:
747f4a2713aSLionel Sambuc // - if there are branch-afters threaded through the scope
748f4a2713aSLionel Sambuc // - if fall-through is a branch-after
749f4a2713aSLionel Sambuc // - if there are fixups that have nowhere left to go and
750f4a2713aSLionel Sambuc // so must be immediately resolved
751f4a2713aSLionel Sambuc } else if (Scope.getNumBranchAfters() ||
752f4a2713aSLionel Sambuc (HasFallthrough && !FallthroughIsBranchThrough) ||
753f4a2713aSLionel Sambuc (HasFixups && !HasEnclosingCleanups)) {
754f4a2713aSLionel Sambuc
755f4a2713aSLionel Sambuc llvm::BasicBlock *Default =
756f4a2713aSLionel Sambuc (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
757f4a2713aSLionel Sambuc
758f4a2713aSLionel Sambuc // TODO: base this on the number of branch-afters and fixups
759f4a2713aSLionel Sambuc const unsigned SwitchCapacity = 10;
760f4a2713aSLionel Sambuc
761f4a2713aSLionel Sambuc llvm::LoadInst *Load =
762f4a2713aSLionel Sambuc new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
763f4a2713aSLionel Sambuc llvm::SwitchInst *Switch =
764f4a2713aSLionel Sambuc llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
765f4a2713aSLionel Sambuc
766f4a2713aSLionel Sambuc InstsToAppend.push_back(Load);
767f4a2713aSLionel Sambuc InstsToAppend.push_back(Switch);
768f4a2713aSLionel Sambuc
769f4a2713aSLionel Sambuc // Branch-after fallthrough.
770f4a2713aSLionel Sambuc if (FallthroughSource && !FallthroughIsBranchThrough) {
771f4a2713aSLionel Sambuc FallthroughDest = createBasicBlock("cleanup.cont");
772f4a2713aSLionel Sambuc if (HasFallthrough)
773f4a2713aSLionel Sambuc Switch->addCase(Builder.getInt32(0), FallthroughDest);
774f4a2713aSLionel Sambuc }
775f4a2713aSLionel Sambuc
776f4a2713aSLionel Sambuc for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
777f4a2713aSLionel Sambuc Switch->addCase(Scope.getBranchAfterIndex(I),
778f4a2713aSLionel Sambuc Scope.getBranchAfterBlock(I));
779f4a2713aSLionel Sambuc }
780f4a2713aSLionel Sambuc
781f4a2713aSLionel Sambuc // If there aren't any enclosing cleanups, we can resolve all
782f4a2713aSLionel Sambuc // the fixups now.
783f4a2713aSLionel Sambuc if (HasFixups && !HasEnclosingCleanups)
784f4a2713aSLionel Sambuc ResolveAllBranchFixups(*this, Switch, NormalEntry);
785f4a2713aSLionel Sambuc } else {
786f4a2713aSLionel Sambuc // We should always have a branch-through destination in this case.
787f4a2713aSLionel Sambuc assert(BranchThroughDest);
788f4a2713aSLionel Sambuc InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
789f4a2713aSLionel Sambuc }
790f4a2713aSLionel Sambuc
791f4a2713aSLionel Sambuc // IV. Pop the cleanup and emit it.
792f4a2713aSLionel Sambuc EHStack.popCleanup();
793f4a2713aSLionel Sambuc assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
794f4a2713aSLionel Sambuc
795f4a2713aSLionel Sambuc EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
796f4a2713aSLionel Sambuc
797f4a2713aSLionel Sambuc // Append the prepared cleanup prologue from above.
798f4a2713aSLionel Sambuc llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
799f4a2713aSLionel Sambuc for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
800f4a2713aSLionel Sambuc NormalExit->getInstList().push_back(InstsToAppend[I]);
801f4a2713aSLionel Sambuc
802f4a2713aSLionel Sambuc // Optimistically hope that any fixups will continue falling through.
803f4a2713aSLionel Sambuc for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
804f4a2713aSLionel Sambuc I < E; ++I) {
805f4a2713aSLionel Sambuc BranchFixup &Fixup = EHStack.getBranchFixup(I);
806f4a2713aSLionel Sambuc if (!Fixup.Destination) continue;
807f4a2713aSLionel Sambuc if (!Fixup.OptimisticBranchBlock) {
808f4a2713aSLionel Sambuc new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
809f4a2713aSLionel Sambuc getNormalCleanupDestSlot(),
810f4a2713aSLionel Sambuc Fixup.InitialBranch);
811f4a2713aSLionel Sambuc Fixup.InitialBranch->setSuccessor(0, NormalEntry);
812f4a2713aSLionel Sambuc }
813f4a2713aSLionel Sambuc Fixup.OptimisticBranchBlock = NormalExit;
814f4a2713aSLionel Sambuc }
815f4a2713aSLionel Sambuc
816f4a2713aSLionel Sambuc // V. Set up the fallthrough edge out.
817f4a2713aSLionel Sambuc
818f4a2713aSLionel Sambuc // Case 1: a fallthrough source exists but doesn't branch to the
819f4a2713aSLionel Sambuc // cleanup because the cleanup is inactive.
820f4a2713aSLionel Sambuc if (!HasFallthrough && FallthroughSource) {
821f4a2713aSLionel Sambuc // Prebranched fallthrough was forwarded earlier.
822f4a2713aSLionel Sambuc // Non-prebranched fallthrough doesn't need to be forwarded.
823f4a2713aSLionel Sambuc // Either way, all we need to do is restore the IP we cleared before.
824f4a2713aSLionel Sambuc assert(!IsActive);
825f4a2713aSLionel Sambuc Builder.restoreIP(savedInactiveFallthroughIP);
826f4a2713aSLionel Sambuc
827f4a2713aSLionel Sambuc // Case 2: a fallthrough source exists and should branch to the
828f4a2713aSLionel Sambuc // cleanup, but we're not supposed to branch through to the next
829f4a2713aSLionel Sambuc // cleanup.
830f4a2713aSLionel Sambuc } else if (HasFallthrough && FallthroughDest) {
831f4a2713aSLionel Sambuc assert(!FallthroughIsBranchThrough);
832f4a2713aSLionel Sambuc EmitBlock(FallthroughDest);
833f4a2713aSLionel Sambuc
834f4a2713aSLionel Sambuc // Case 3: a fallthrough source exists and should branch to the
835f4a2713aSLionel Sambuc // cleanup and then through to the next.
836f4a2713aSLionel Sambuc } else if (HasFallthrough) {
837f4a2713aSLionel Sambuc // Everything is already set up for this.
838f4a2713aSLionel Sambuc
839f4a2713aSLionel Sambuc // Case 4: no fallthrough source exists.
840f4a2713aSLionel Sambuc } else {
841f4a2713aSLionel Sambuc Builder.ClearInsertionPoint();
842f4a2713aSLionel Sambuc }
843f4a2713aSLionel Sambuc
844f4a2713aSLionel Sambuc // VI. Assorted cleaning.
845f4a2713aSLionel Sambuc
846f4a2713aSLionel Sambuc // Check whether we can merge NormalEntry into a single predecessor.
847f4a2713aSLionel Sambuc // This might invalidate (non-IR) pointers to NormalEntry.
848f4a2713aSLionel Sambuc llvm::BasicBlock *NewNormalEntry =
849f4a2713aSLionel Sambuc SimplifyCleanupEntry(*this, NormalEntry);
850f4a2713aSLionel Sambuc
851f4a2713aSLionel Sambuc // If it did invalidate those pointers, and NormalEntry was the same
852f4a2713aSLionel Sambuc // as NormalExit, go back and patch up the fixups.
853f4a2713aSLionel Sambuc if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
854f4a2713aSLionel Sambuc for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
855f4a2713aSLionel Sambuc I < E; ++I)
856f4a2713aSLionel Sambuc EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
857f4a2713aSLionel Sambuc }
858f4a2713aSLionel Sambuc }
859f4a2713aSLionel Sambuc
860f4a2713aSLionel Sambuc assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
861f4a2713aSLionel Sambuc
862f4a2713aSLionel Sambuc // Emit the EH cleanup if required.
863f4a2713aSLionel Sambuc if (RequiresEHCleanup) {
864*0a6a1f1dSLionel Sambuc ApplyDebugLocation AutoRestoreLocation(*this, CurEHLocation);
865f4a2713aSLionel Sambuc
866f4a2713aSLionel Sambuc CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
867f4a2713aSLionel Sambuc
868f4a2713aSLionel Sambuc EmitBlock(EHEntry);
869f4a2713aSLionel Sambuc
870f4a2713aSLionel Sambuc // We only actually emit the cleanup code if the cleanup is either
871f4a2713aSLionel Sambuc // active or was used before it was deactivated.
872f4a2713aSLionel Sambuc if (EHActiveFlag || IsActive) {
873f4a2713aSLionel Sambuc
874f4a2713aSLionel Sambuc cleanupFlags.setIsForEHCleanup();
875f4a2713aSLionel Sambuc EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
876f4a2713aSLionel Sambuc }
877f4a2713aSLionel Sambuc
878f4a2713aSLionel Sambuc Builder.CreateBr(getEHDispatchBlock(EHParent));
879f4a2713aSLionel Sambuc
880f4a2713aSLionel Sambuc Builder.restoreIP(SavedIP);
881f4a2713aSLionel Sambuc
882f4a2713aSLionel Sambuc SimplifyCleanupEntry(*this, EHEntry);
883f4a2713aSLionel Sambuc }
884f4a2713aSLionel Sambuc }
885f4a2713aSLionel Sambuc
886f4a2713aSLionel Sambuc /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
887f4a2713aSLionel Sambuc /// specified destination obviously has no cleanups to run. 'false' is always
888f4a2713aSLionel Sambuc /// a conservatively correct answer for this method.
isObviouslyBranchWithoutCleanups(JumpDest Dest) const889f4a2713aSLionel Sambuc bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
890f4a2713aSLionel Sambuc assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
891f4a2713aSLionel Sambuc && "stale jump destination");
892f4a2713aSLionel Sambuc
893f4a2713aSLionel Sambuc // Calculate the innermost active normal cleanup.
894f4a2713aSLionel Sambuc EHScopeStack::stable_iterator TopCleanup =
895f4a2713aSLionel Sambuc EHStack.getInnermostActiveNormalCleanup();
896f4a2713aSLionel Sambuc
897f4a2713aSLionel Sambuc // If we're not in an active normal cleanup scope, or if the
898f4a2713aSLionel Sambuc // destination scope is within the innermost active normal cleanup
899f4a2713aSLionel Sambuc // scope, we don't need to worry about fixups.
900f4a2713aSLionel Sambuc if (TopCleanup == EHStack.stable_end() ||
901f4a2713aSLionel Sambuc TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
902f4a2713aSLionel Sambuc return true;
903f4a2713aSLionel Sambuc
904f4a2713aSLionel Sambuc // Otherwise, we might need some cleanups.
905f4a2713aSLionel Sambuc return false;
906f4a2713aSLionel Sambuc }
907f4a2713aSLionel Sambuc
908f4a2713aSLionel Sambuc
909f4a2713aSLionel Sambuc /// Terminate the current block by emitting a branch which might leave
910f4a2713aSLionel Sambuc /// the current cleanup-protected scope. The target scope may not yet
911f4a2713aSLionel Sambuc /// be known, in which case this will require a fixup.
912f4a2713aSLionel Sambuc ///
913f4a2713aSLionel Sambuc /// As a side-effect, this method clears the insertion point.
EmitBranchThroughCleanup(JumpDest Dest)914f4a2713aSLionel Sambuc void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
915f4a2713aSLionel Sambuc assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
916f4a2713aSLionel Sambuc && "stale jump destination");
917f4a2713aSLionel Sambuc
918f4a2713aSLionel Sambuc if (!HaveInsertPoint())
919f4a2713aSLionel Sambuc return;
920f4a2713aSLionel Sambuc
921f4a2713aSLionel Sambuc // Create the branch.
922f4a2713aSLionel Sambuc llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
923f4a2713aSLionel Sambuc
924f4a2713aSLionel Sambuc // Calculate the innermost active normal cleanup.
925f4a2713aSLionel Sambuc EHScopeStack::stable_iterator
926f4a2713aSLionel Sambuc TopCleanup = EHStack.getInnermostActiveNormalCleanup();
927f4a2713aSLionel Sambuc
928f4a2713aSLionel Sambuc // If we're not in an active normal cleanup scope, or if the
929f4a2713aSLionel Sambuc // destination scope is within the innermost active normal cleanup
930f4a2713aSLionel Sambuc // scope, we don't need to worry about fixups.
931f4a2713aSLionel Sambuc if (TopCleanup == EHStack.stable_end() ||
932f4a2713aSLionel Sambuc TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
933f4a2713aSLionel Sambuc Builder.ClearInsertionPoint();
934f4a2713aSLionel Sambuc return;
935f4a2713aSLionel Sambuc }
936f4a2713aSLionel Sambuc
937f4a2713aSLionel Sambuc // If we can't resolve the destination cleanup scope, just add this
938f4a2713aSLionel Sambuc // to the current cleanup scope as a branch fixup.
939f4a2713aSLionel Sambuc if (!Dest.getScopeDepth().isValid()) {
940f4a2713aSLionel Sambuc BranchFixup &Fixup = EHStack.addBranchFixup();
941f4a2713aSLionel Sambuc Fixup.Destination = Dest.getBlock();
942f4a2713aSLionel Sambuc Fixup.DestinationIndex = Dest.getDestIndex();
943f4a2713aSLionel Sambuc Fixup.InitialBranch = BI;
944*0a6a1f1dSLionel Sambuc Fixup.OptimisticBranchBlock = nullptr;
945f4a2713aSLionel Sambuc
946f4a2713aSLionel Sambuc Builder.ClearInsertionPoint();
947f4a2713aSLionel Sambuc return;
948f4a2713aSLionel Sambuc }
949f4a2713aSLionel Sambuc
950f4a2713aSLionel Sambuc // Otherwise, thread through all the normal cleanups in scope.
951f4a2713aSLionel Sambuc
952f4a2713aSLionel Sambuc // Store the index at the start.
953f4a2713aSLionel Sambuc llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
954f4a2713aSLionel Sambuc new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
955f4a2713aSLionel Sambuc
956f4a2713aSLionel Sambuc // Adjust BI to point to the first cleanup block.
957f4a2713aSLionel Sambuc {
958f4a2713aSLionel Sambuc EHCleanupScope &Scope =
959f4a2713aSLionel Sambuc cast<EHCleanupScope>(*EHStack.find(TopCleanup));
960f4a2713aSLionel Sambuc BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
961f4a2713aSLionel Sambuc }
962f4a2713aSLionel Sambuc
963f4a2713aSLionel Sambuc // Add this destination to all the scopes involved.
964f4a2713aSLionel Sambuc EHScopeStack::stable_iterator I = TopCleanup;
965f4a2713aSLionel Sambuc EHScopeStack::stable_iterator E = Dest.getScopeDepth();
966f4a2713aSLionel Sambuc if (E.strictlyEncloses(I)) {
967f4a2713aSLionel Sambuc while (true) {
968f4a2713aSLionel Sambuc EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
969f4a2713aSLionel Sambuc assert(Scope.isNormalCleanup());
970f4a2713aSLionel Sambuc I = Scope.getEnclosingNormalCleanup();
971f4a2713aSLionel Sambuc
972f4a2713aSLionel Sambuc // If this is the last cleanup we're propagating through, tell it
973f4a2713aSLionel Sambuc // that there's a resolved jump moving through it.
974f4a2713aSLionel Sambuc if (!E.strictlyEncloses(I)) {
975f4a2713aSLionel Sambuc Scope.addBranchAfter(Index, Dest.getBlock());
976f4a2713aSLionel Sambuc break;
977f4a2713aSLionel Sambuc }
978f4a2713aSLionel Sambuc
979f4a2713aSLionel Sambuc // Otherwise, tell the scope that there's a jump propoagating
980f4a2713aSLionel Sambuc // through it. If this isn't new information, all the rest of
981f4a2713aSLionel Sambuc // the work has been done before.
982f4a2713aSLionel Sambuc if (!Scope.addBranchThrough(Dest.getBlock()))
983f4a2713aSLionel Sambuc break;
984f4a2713aSLionel Sambuc }
985f4a2713aSLionel Sambuc }
986f4a2713aSLionel Sambuc
987f4a2713aSLionel Sambuc Builder.ClearInsertionPoint();
988f4a2713aSLionel Sambuc }
989f4a2713aSLionel Sambuc
IsUsedAsNormalCleanup(EHScopeStack & EHStack,EHScopeStack::stable_iterator C)990f4a2713aSLionel Sambuc static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
991f4a2713aSLionel Sambuc EHScopeStack::stable_iterator C) {
992f4a2713aSLionel Sambuc // If we needed a normal block for any reason, that counts.
993f4a2713aSLionel Sambuc if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
994f4a2713aSLionel Sambuc return true;
995f4a2713aSLionel Sambuc
996f4a2713aSLionel Sambuc // Check whether any enclosed cleanups were needed.
997f4a2713aSLionel Sambuc for (EHScopeStack::stable_iterator
998f4a2713aSLionel Sambuc I = EHStack.getInnermostNormalCleanup();
999f4a2713aSLionel Sambuc I != C; ) {
1000f4a2713aSLionel Sambuc assert(C.strictlyEncloses(I));
1001f4a2713aSLionel Sambuc EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1002f4a2713aSLionel Sambuc if (S.getNormalBlock()) return true;
1003f4a2713aSLionel Sambuc I = S.getEnclosingNormalCleanup();
1004f4a2713aSLionel Sambuc }
1005f4a2713aSLionel Sambuc
1006f4a2713aSLionel Sambuc return false;
1007f4a2713aSLionel Sambuc }
1008f4a2713aSLionel Sambuc
IsUsedAsEHCleanup(EHScopeStack & EHStack,EHScopeStack::stable_iterator cleanup)1009f4a2713aSLionel Sambuc static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
1010f4a2713aSLionel Sambuc EHScopeStack::stable_iterator cleanup) {
1011f4a2713aSLionel Sambuc // If we needed an EH block for any reason, that counts.
1012f4a2713aSLionel Sambuc if (EHStack.find(cleanup)->hasEHBranches())
1013f4a2713aSLionel Sambuc return true;
1014f4a2713aSLionel Sambuc
1015f4a2713aSLionel Sambuc // Check whether any enclosed cleanups were needed.
1016f4a2713aSLionel Sambuc for (EHScopeStack::stable_iterator
1017f4a2713aSLionel Sambuc i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1018f4a2713aSLionel Sambuc assert(cleanup.strictlyEncloses(i));
1019f4a2713aSLionel Sambuc
1020f4a2713aSLionel Sambuc EHScope &scope = *EHStack.find(i);
1021f4a2713aSLionel Sambuc if (scope.hasEHBranches())
1022f4a2713aSLionel Sambuc return true;
1023f4a2713aSLionel Sambuc
1024f4a2713aSLionel Sambuc i = scope.getEnclosingEHScope();
1025f4a2713aSLionel Sambuc }
1026f4a2713aSLionel Sambuc
1027f4a2713aSLionel Sambuc return false;
1028f4a2713aSLionel Sambuc }
1029f4a2713aSLionel Sambuc
1030f4a2713aSLionel Sambuc enum ForActivation_t {
1031f4a2713aSLionel Sambuc ForActivation,
1032f4a2713aSLionel Sambuc ForDeactivation
1033f4a2713aSLionel Sambuc };
1034f4a2713aSLionel Sambuc
1035f4a2713aSLionel Sambuc /// The given cleanup block is changing activation state. Configure a
1036f4a2713aSLionel Sambuc /// cleanup variable if necessary.
1037f4a2713aSLionel Sambuc ///
1038f4a2713aSLionel Sambuc /// It would be good if we had some way of determining if there were
1039f4a2713aSLionel Sambuc /// extra uses *after* the change-over point.
SetupCleanupBlockActivation(CodeGenFunction & CGF,EHScopeStack::stable_iterator C,ForActivation_t kind,llvm::Instruction * dominatingIP)1040f4a2713aSLionel Sambuc static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1041f4a2713aSLionel Sambuc EHScopeStack::stable_iterator C,
1042f4a2713aSLionel Sambuc ForActivation_t kind,
1043f4a2713aSLionel Sambuc llvm::Instruction *dominatingIP) {
1044f4a2713aSLionel Sambuc EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1045f4a2713aSLionel Sambuc
1046f4a2713aSLionel Sambuc // We always need the flag if we're activating the cleanup in a
1047f4a2713aSLionel Sambuc // conditional context, because we have to assume that the current
1048f4a2713aSLionel Sambuc // location doesn't necessarily dominate the cleanup's code.
1049f4a2713aSLionel Sambuc bool isActivatedInConditional =
1050f4a2713aSLionel Sambuc (kind == ForActivation && CGF.isInConditionalBranch());
1051f4a2713aSLionel Sambuc
1052f4a2713aSLionel Sambuc bool needFlag = false;
1053f4a2713aSLionel Sambuc
1054f4a2713aSLionel Sambuc // Calculate whether the cleanup was used:
1055f4a2713aSLionel Sambuc
1056f4a2713aSLionel Sambuc // - as a normal cleanup
1057f4a2713aSLionel Sambuc if (Scope.isNormalCleanup() &&
1058f4a2713aSLionel Sambuc (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
1059f4a2713aSLionel Sambuc Scope.setTestFlagInNormalCleanup();
1060f4a2713aSLionel Sambuc needFlag = true;
1061f4a2713aSLionel Sambuc }
1062f4a2713aSLionel Sambuc
1063f4a2713aSLionel Sambuc // - as an EH cleanup
1064f4a2713aSLionel Sambuc if (Scope.isEHCleanup() &&
1065f4a2713aSLionel Sambuc (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
1066f4a2713aSLionel Sambuc Scope.setTestFlagInEHCleanup();
1067f4a2713aSLionel Sambuc needFlag = true;
1068f4a2713aSLionel Sambuc }
1069f4a2713aSLionel Sambuc
1070f4a2713aSLionel Sambuc // If it hasn't yet been used as either, we're done.
1071f4a2713aSLionel Sambuc if (!needFlag) return;
1072f4a2713aSLionel Sambuc
1073f4a2713aSLionel Sambuc llvm::AllocaInst *var = Scope.getActiveFlag();
1074f4a2713aSLionel Sambuc if (!var) {
1075f4a2713aSLionel Sambuc var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactive");
1076f4a2713aSLionel Sambuc Scope.setActiveFlag(var);
1077f4a2713aSLionel Sambuc
1078f4a2713aSLionel Sambuc assert(dominatingIP && "no existing variable and no dominating IP!");
1079f4a2713aSLionel Sambuc
1080f4a2713aSLionel Sambuc // Initialize to true or false depending on whether it was
1081f4a2713aSLionel Sambuc // active up to this point.
1082f4a2713aSLionel Sambuc llvm::Value *value = CGF.Builder.getInt1(kind == ForDeactivation);
1083f4a2713aSLionel Sambuc
1084f4a2713aSLionel Sambuc // If we're in a conditional block, ignore the dominating IP and
1085f4a2713aSLionel Sambuc // use the outermost conditional branch.
1086f4a2713aSLionel Sambuc if (CGF.isInConditionalBranch()) {
1087f4a2713aSLionel Sambuc CGF.setBeforeOutermostConditional(value, var);
1088f4a2713aSLionel Sambuc } else {
1089f4a2713aSLionel Sambuc new llvm::StoreInst(value, var, dominatingIP);
1090f4a2713aSLionel Sambuc }
1091f4a2713aSLionel Sambuc }
1092f4a2713aSLionel Sambuc
1093f4a2713aSLionel Sambuc CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
1094f4a2713aSLionel Sambuc }
1095f4a2713aSLionel Sambuc
1096f4a2713aSLionel Sambuc /// Activate a cleanup that was created in an inactivated state.
ActivateCleanupBlock(EHScopeStack::stable_iterator C,llvm::Instruction * dominatingIP)1097f4a2713aSLionel Sambuc void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1098f4a2713aSLionel Sambuc llvm::Instruction *dominatingIP) {
1099f4a2713aSLionel Sambuc assert(C != EHStack.stable_end() && "activating bottom of stack?");
1100f4a2713aSLionel Sambuc EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1101f4a2713aSLionel Sambuc assert(!Scope.isActive() && "double activation");
1102f4a2713aSLionel Sambuc
1103f4a2713aSLionel Sambuc SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
1104f4a2713aSLionel Sambuc
1105f4a2713aSLionel Sambuc Scope.setActive(true);
1106f4a2713aSLionel Sambuc }
1107f4a2713aSLionel Sambuc
1108f4a2713aSLionel Sambuc /// Deactive a cleanup that was created in an active state.
DeactivateCleanupBlock(EHScopeStack::stable_iterator C,llvm::Instruction * dominatingIP)1109f4a2713aSLionel Sambuc void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1110f4a2713aSLionel Sambuc llvm::Instruction *dominatingIP) {
1111f4a2713aSLionel Sambuc assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1112f4a2713aSLionel Sambuc EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1113f4a2713aSLionel Sambuc assert(Scope.isActive() && "double deactivation");
1114f4a2713aSLionel Sambuc
1115f4a2713aSLionel Sambuc // If it's the top of the stack, just pop it.
1116f4a2713aSLionel Sambuc if (C == EHStack.stable_begin()) {
1117f4a2713aSLionel Sambuc // If it's a normal cleanup, we need to pretend that the
1118f4a2713aSLionel Sambuc // fallthrough is unreachable.
1119f4a2713aSLionel Sambuc CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1120f4a2713aSLionel Sambuc PopCleanupBlock();
1121f4a2713aSLionel Sambuc Builder.restoreIP(SavedIP);
1122f4a2713aSLionel Sambuc return;
1123f4a2713aSLionel Sambuc }
1124f4a2713aSLionel Sambuc
1125f4a2713aSLionel Sambuc // Otherwise, follow the general case.
1126f4a2713aSLionel Sambuc SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
1127f4a2713aSLionel Sambuc
1128f4a2713aSLionel Sambuc Scope.setActive(false);
1129f4a2713aSLionel Sambuc }
1130f4a2713aSLionel Sambuc
getNormalCleanupDestSlot()1131f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1132f4a2713aSLionel Sambuc if (!NormalCleanupDest)
1133f4a2713aSLionel Sambuc NormalCleanupDest =
1134f4a2713aSLionel Sambuc CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1135f4a2713aSLionel Sambuc return NormalCleanupDest;
1136f4a2713aSLionel Sambuc }
1137f4a2713aSLionel Sambuc
1138f4a2713aSLionel Sambuc /// Emits all the code to cause the given temporary to be cleaned up.
EmitCXXTemporary(const CXXTemporary * Temporary,QualType TempType,llvm::Value * Ptr)1139f4a2713aSLionel Sambuc void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1140f4a2713aSLionel Sambuc QualType TempType,
1141f4a2713aSLionel Sambuc llvm::Value *Ptr) {
1142f4a2713aSLionel Sambuc pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
1143f4a2713aSLionel Sambuc /*useEHCleanup*/ true);
1144f4a2713aSLionel Sambuc }
1145