1ed1ae86aSJohn McCall //===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
2ed1ae86aSJohn McCall //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ed1ae86aSJohn McCall //
7ed1ae86aSJohn McCall //===----------------------------------------------------------------------===//
8ed1ae86aSJohn McCall //
9ed1ae86aSJohn McCall // This file contains code dealing with the IR generation for cleanups
10ed1ae86aSJohn McCall // and related information.
11ed1ae86aSJohn McCall //
12ed1ae86aSJohn McCall // A "cleanup" is a piece of code which needs to be executed whenever
13ed1ae86aSJohn McCall // control transfers out of a particular scope.  This can be
14ed1ae86aSJohn McCall // conditionalized to occur only on exceptional control flow, only on
15ed1ae86aSJohn McCall // normal control flow, or both.
16ed1ae86aSJohn McCall //
17ed1ae86aSJohn McCall //===----------------------------------------------------------------------===//
18ed1ae86aSJohn McCall 
19ed1ae86aSJohn McCall #include "CGCleanup.h"
202da7fcdaSReid Kleckner #include "CodeGenFunction.h"
21a002bd54SReid Kleckner #include "llvm/Support/SaveAndRestore.h"
22ed1ae86aSJohn McCall 
23ed1ae86aSJohn McCall using namespace clang;
24ed1ae86aSJohn McCall using namespace CodeGen;
25ed1ae86aSJohn McCall 
needsSaving(RValue rv)26ed1ae86aSJohn McCall bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
27ed1ae86aSJohn McCall   if (rv.isScalar())
28ed1ae86aSJohn McCall     return DominatingLLVMValue::needsSaving(rv.getScalarVal());
29ed1ae86aSJohn McCall   if (rv.isAggregate())
307f416cc4SJohn McCall     return DominatingLLVMValue::needsSaving(rv.getAggregatePointer());
31ed1ae86aSJohn McCall   return true;
32ed1ae86aSJohn McCall }
33ed1ae86aSJohn McCall 
34ed1ae86aSJohn McCall DominatingValue<RValue>::saved_type
save(CodeGenFunction & CGF,RValue rv)35ed1ae86aSJohn McCall DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
36ed1ae86aSJohn McCall   if (rv.isScalar()) {
37ed1ae86aSJohn McCall     llvm::Value *V = rv.getScalarVal();
38ed1ae86aSJohn McCall 
39ed1ae86aSJohn McCall     // These automatically dominate and don't need to be saved.
40ed1ae86aSJohn McCall     if (!DominatingLLVMValue::needsSaving(V))
4174992f4aSNikita Popov       return saved_type(V, nullptr, ScalarLiteral);
42ed1ae86aSJohn McCall 
43ed1ae86aSJohn McCall     // Everything else needs an alloca.
447f416cc4SJohn McCall     Address addr =
457f416cc4SJohn McCall       CGF.CreateDefaultAlignTempAlloca(V->getType(), "saved-rvalue");
46ed1ae86aSJohn McCall     CGF.Builder.CreateStore(V, addr);
4774992f4aSNikita Popov     return saved_type(addr.getPointer(), nullptr, ScalarAddress);
48ed1ae86aSJohn McCall   }
49ed1ae86aSJohn McCall 
50ed1ae86aSJohn McCall   if (rv.isComplex()) {
51ed1ae86aSJohn McCall     CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
522192fe50SChris Lattner     llvm::Type *ComplexTy =
531d993270SSerge Guelton         llvm::StructType::get(V.first->getType(), V.second->getType());
547f416cc4SJohn McCall     Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex");
55751fe286SJames Y Knight     CGF.Builder.CreateStore(V.first, CGF.Builder.CreateStructGEP(addr, 0));
56751fe286SJames Y Knight     CGF.Builder.CreateStore(V.second, CGF.Builder.CreateStructGEP(addr, 1));
5774992f4aSNikita Popov     return saved_type(addr.getPointer(), nullptr, ComplexAddress);
58ed1ae86aSJohn McCall   }
59ed1ae86aSJohn McCall 
60ed1ae86aSJohn McCall   assert(rv.isAggregate());
617f416cc4SJohn McCall   Address V = rv.getAggregateAddress(); // TODO: volatile?
627f416cc4SJohn McCall   if (!DominatingLLVMValue::needsSaving(V.getPointer()))
6374992f4aSNikita Popov     return saved_type(V.getPointer(), V.getElementType(), AggregateLiteral,
647f416cc4SJohn McCall                       V.getAlignment().getQuantity());
65ed1ae86aSJohn McCall 
667f416cc4SJohn McCall   Address addr =
677f416cc4SJohn McCall     CGF.CreateTempAlloca(V.getType(), CGF.getPointerAlign(), "saved-rvalue");
687f416cc4SJohn McCall   CGF.Builder.CreateStore(V.getPointer(), addr);
6974992f4aSNikita Popov   return saved_type(addr.getPointer(), V.getElementType(), AggregateAddress,
707f416cc4SJohn McCall                     V.getAlignment().getQuantity());
71ed1ae86aSJohn McCall }
72ed1ae86aSJohn McCall 
73ed1ae86aSJohn McCall /// Given a saved r-value produced by SaveRValue, perform the code
74ed1ae86aSJohn McCall /// necessary to restore it to usability at the current insertion
75ed1ae86aSJohn McCall /// point.
restore(CodeGenFunction & CGF)76ed1ae86aSJohn McCall RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
777f416cc4SJohn McCall   auto getSavingAddress = [&](llvm::Value *value) {
7850650766SNikita Popov     auto *AI = cast<llvm::AllocaInst>(value);
7950650766SNikita Popov     return Address(value, AI->getAllocatedType(),
80*d9b8d13fSGuillaume Chatelet                    CharUnits::fromQuantity(AI->getAlign().value()));
817f416cc4SJohn McCall   };
82ed1ae86aSJohn McCall   switch (K) {
83ed1ae86aSJohn McCall   case ScalarLiteral:
84ed1ae86aSJohn McCall     return RValue::get(Value);
85ed1ae86aSJohn McCall   case ScalarAddress:
867f416cc4SJohn McCall     return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
87ed1ae86aSJohn McCall   case AggregateLiteral:
8850650766SNikita Popov     return RValue::getAggregate(
8974992f4aSNikita Popov         Address(Value, ElementType, CharUnits::fromQuantity(Align)));
907f416cc4SJohn McCall   case AggregateAddress: {
917f416cc4SJohn McCall     auto addr = CGF.Builder.CreateLoad(getSavingAddress(Value));
9250650766SNikita Popov     return RValue::getAggregate(
9374992f4aSNikita Popov         Address(addr, ElementType, CharUnits::fromQuantity(Align)));
947f416cc4SJohn McCall   }
9547fb9508SJohn McCall   case ComplexAddress: {
967f416cc4SJohn McCall     Address address = getSavingAddress(Value);
97751fe286SJames Y Knight     llvm::Value *real =
98751fe286SJames Y Knight         CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 0));
99751fe286SJames Y Knight     llvm::Value *imag =
100751fe286SJames Y Knight         CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 1));
10147fb9508SJohn McCall     return RValue::getComplex(real, imag);
10247fb9508SJohn McCall   }
103ed1ae86aSJohn McCall   }
104ed1ae86aSJohn McCall 
105ed1ae86aSJohn McCall   llvm_unreachable("bad saved r-value kind");
106ed1ae86aSJohn McCall }
107ed1ae86aSJohn McCall 
108ed1ae86aSJohn McCall /// Push an entry of the given size onto this protected-scope stack.
allocate(size_t Size)109ed1ae86aSJohn McCall char *EHScopeStack::allocate(size_t Size) {
11083aa9794SRui Ueyama   Size = llvm::alignTo(Size, ScopeStackAlignment);
111ed1ae86aSJohn McCall   if (!StartOfBuffer) {
112ed1ae86aSJohn McCall     unsigned Capacity = 1024;
113ed1ae86aSJohn McCall     while (Capacity < Size) Capacity *= 2;
114ed1ae86aSJohn McCall     StartOfBuffer = new char[Capacity];
115ed1ae86aSJohn McCall     StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
116ed1ae86aSJohn McCall   } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
117ed1ae86aSJohn McCall     unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
118ed1ae86aSJohn McCall     unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
119ed1ae86aSJohn McCall 
120ed1ae86aSJohn McCall     unsigned NewCapacity = CurrentCapacity;
121ed1ae86aSJohn McCall     do {
122ed1ae86aSJohn McCall       NewCapacity *= 2;
123ed1ae86aSJohn McCall     } while (NewCapacity < UsedCapacity + Size);
124ed1ae86aSJohn McCall 
125ed1ae86aSJohn McCall     char *NewStartOfBuffer = new char[NewCapacity];
126ed1ae86aSJohn McCall     char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
127ed1ae86aSJohn McCall     char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
128ed1ae86aSJohn McCall     memcpy(NewStartOfData, StartOfData, UsedCapacity);
129ed1ae86aSJohn McCall     delete [] StartOfBuffer;
130ed1ae86aSJohn McCall     StartOfBuffer = NewStartOfBuffer;
131ed1ae86aSJohn McCall     EndOfBuffer = NewEndOfBuffer;
132ed1ae86aSJohn McCall     StartOfData = NewStartOfData;
133ed1ae86aSJohn McCall   }
134ed1ae86aSJohn McCall 
135ed1ae86aSJohn McCall   assert(StartOfBuffer + Size <= StartOfData);
136ed1ae86aSJohn McCall   StartOfData -= Size;
137ed1ae86aSJohn McCall   return StartOfData;
138ed1ae86aSJohn McCall }
139ed1ae86aSJohn McCall 
deallocate(size_t Size)14053c7616eSJames Y Knight void EHScopeStack::deallocate(size_t Size) {
14183aa9794SRui Ueyama   StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
14253c7616eSJames Y Knight }
14353c7616eSJames Y Knight 
containsOnlyLifetimeMarkers(EHScopeStack::stable_iterator Old) const144dc012fa2SDavid Majnemer bool EHScopeStack::containsOnlyLifetimeMarkers(
145dc012fa2SDavid Majnemer     EHScopeStack::stable_iterator Old) const {
146dc012fa2SDavid Majnemer   for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {
147dc012fa2SDavid Majnemer     EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
148dc012fa2SDavid Majnemer     if (!cleanup || !cleanup->isLifetimeMarker())
149dc012fa2SDavid Majnemer       return false;
150dc012fa2SDavid Majnemer   }
151dc012fa2SDavid Majnemer 
152dc012fa2SDavid Majnemer   return true;
153dc012fa2SDavid Majnemer }
154dc012fa2SDavid Majnemer 
requiresLandingPad() const1558af7bb28SAkira Hatanaka bool EHScopeStack::requiresLandingPad() const {
1568af7bb28SAkira Hatanaka   for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {
1578af7bb28SAkira Hatanaka     // Skip lifetime markers.
1588af7bb28SAkira Hatanaka     if (auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si)))
1598af7bb28SAkira Hatanaka       if (cleanup->isLifetimeMarker()) {
1608af7bb28SAkira Hatanaka         si = cleanup->getEnclosingEHScope();
1618af7bb28SAkira Hatanaka         continue;
1628af7bb28SAkira Hatanaka       }
1638af7bb28SAkira Hatanaka     return true;
1648af7bb28SAkira Hatanaka   }
1658af7bb28SAkira Hatanaka 
1668af7bb28SAkira Hatanaka   return false;
1678af7bb28SAkira Hatanaka }
1688af7bb28SAkira Hatanaka 
169ed1ae86aSJohn McCall EHScopeStack::stable_iterator
getInnermostActiveNormalCleanup() const1708e4c74bbSJohn McCall EHScopeStack::getInnermostActiveNormalCleanup() const {
1718e4c74bbSJohn McCall   for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
1728e4c74bbSJohn McCall          si != se; ) {
1738e4c74bbSJohn McCall     EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
1748e4c74bbSJohn McCall     if (cleanup.isActive()) return si;
1758e4c74bbSJohn McCall     si = cleanup.getEnclosingNormalCleanup();
176ed1ae86aSJohn McCall   }
1778e4c74bbSJohn McCall   return stable_end();
1788e4c74bbSJohn McCall }
1798e4c74bbSJohn McCall 
180ed1ae86aSJohn McCall 
pushCleanup(CleanupKind Kind,size_t Size)181ed1ae86aSJohn McCall void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
182ed1ae86aSJohn McCall   char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
183ed1ae86aSJohn McCall   bool IsNormalCleanup = Kind & NormalCleanup;
184ed1ae86aSJohn McCall   bool IsEHCleanup = Kind & EHCleanup;
185421119fdSTim Shen   bool IsLifetimeMarker = Kind & LifetimeMarker;
186fa87fa97SJames Y Knight 
187fa87fa97SJames Y Knight   // Per C++ [except.terminate], it is implementation-defined whether none,
188fa87fa97SJames Y Knight   // some, or all cleanups are called before std::terminate. Thus, when
189fa87fa97SJames Y Knight   // terminate is the current EH scope, we may skip adding any EH cleanup
190fa87fa97SJames Y Knight   // scopes.
191fa87fa97SJames Y Knight   if (InnermostEHScope != stable_end() &&
192fa87fa97SJames Y Knight       find(InnermostEHScope)->getKind() == EHScope::Terminate)
193fa87fa97SJames Y Knight     IsEHCleanup = false;
194fa87fa97SJames Y Knight 
195ed1ae86aSJohn McCall   EHCleanupScope *Scope =
196ed1ae86aSJohn McCall     new (Buffer) EHCleanupScope(IsNormalCleanup,
197ed1ae86aSJohn McCall                                 IsEHCleanup,
198ed1ae86aSJohn McCall                                 Size,
199ed1ae86aSJohn McCall                                 BranchFixups.size(),
200ed1ae86aSJohn McCall                                 InnermostNormalCleanup,
2018e4c74bbSJohn McCall                                 InnermostEHScope);
202ed1ae86aSJohn McCall   if (IsNormalCleanup)
203ed1ae86aSJohn McCall     InnermostNormalCleanup = stable_begin();
204ed1ae86aSJohn McCall   if (IsEHCleanup)
2058e4c74bbSJohn McCall     InnermostEHScope = stable_begin();
206421119fdSTim Shen   if (IsLifetimeMarker)
207421119fdSTim Shen     Scope->setLifetimeMarker();
208ed1ae86aSJohn McCall 
209797ad701STen Tzen   // With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup
21033ba8bd2STen Tzen   if (CGF->getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&
211797ad701STen Tzen       CGF->getTarget().getCXXABI().isMicrosoft())
212797ad701STen Tzen     CGF->EmitSehCppScopeBegin();
213797ad701STen Tzen 
214ed1ae86aSJohn McCall   return Scope->getCleanupBuffer();
215ed1ae86aSJohn McCall }
216ed1ae86aSJohn McCall 
popCleanup()217ed1ae86aSJohn McCall void EHScopeStack::popCleanup() {
218ed1ae86aSJohn McCall   assert(!empty() && "popping exception stack when not empty");
219ed1ae86aSJohn McCall 
220ed1ae86aSJohn McCall   assert(isa<EHCleanupScope>(*begin()));
221ed1ae86aSJohn McCall   EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
222ed1ae86aSJohn McCall   InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
2238e4c74bbSJohn McCall   InnermostEHScope = Cleanup.getEnclosingEHScope();
22453c7616eSJames Y Knight   deallocate(Cleanup.getAllocatedSize());
225ed1ae86aSJohn McCall 
226ed1ae86aSJohn McCall   // Destroy the cleanup.
227b21aa76aSKostya Serebryany   Cleanup.Destroy();
228ed1ae86aSJohn McCall 
229ed1ae86aSJohn McCall   // Check whether we can shrink the branch-fixups stack.
230ed1ae86aSJohn McCall   if (!BranchFixups.empty()) {
231ed1ae86aSJohn McCall     // If we no longer have any normal cleanups, all the fixups are
232ed1ae86aSJohn McCall     // complete.
233ed1ae86aSJohn McCall     if (!hasNormalCleanups())
234ed1ae86aSJohn McCall       BranchFixups.clear();
235ed1ae86aSJohn McCall 
236ed1ae86aSJohn McCall     // Otherwise we can still trim out unnecessary nulls.
237ed1ae86aSJohn McCall     else
238ed1ae86aSJohn McCall       popNullFixups();
239ed1ae86aSJohn McCall   }
240ed1ae86aSJohn McCall }
241ed1ae86aSJohn McCall 
pushFilter(unsigned numFilters)2428e4c74bbSJohn McCall EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
2438e4c74bbSJohn McCall   assert(getInnermostEHScope() == stable_end());
2448e4c74bbSJohn McCall   char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
2458e4c74bbSJohn McCall   EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
2468e4c74bbSJohn McCall   InnermostEHScope = stable_begin();
2478e4c74bbSJohn McCall   return filter;
248ed1ae86aSJohn McCall }
249ed1ae86aSJohn McCall 
popFilter()250ed1ae86aSJohn McCall void EHScopeStack::popFilter() {
251ed1ae86aSJohn McCall   assert(!empty() && "popping exception stack when not empty");
252ed1ae86aSJohn McCall 
2538e4c74bbSJohn McCall   EHFilterScope &filter = cast<EHFilterScope>(*begin());
25453c7616eSJames Y Knight   deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
255ed1ae86aSJohn McCall 
2568e4c74bbSJohn McCall   InnermostEHScope = filter.getEnclosingEHScope();
257ed1ae86aSJohn McCall }
258ed1ae86aSJohn McCall 
pushCatch(unsigned numHandlers)2598e4c74bbSJohn McCall EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
2608e4c74bbSJohn McCall   char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
2618e4c74bbSJohn McCall   EHCatchScope *scope =
2628e4c74bbSJohn McCall     new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
2638e4c74bbSJohn McCall   InnermostEHScope = stable_begin();
2648e4c74bbSJohn McCall   return scope;
265ed1ae86aSJohn McCall }
266ed1ae86aSJohn McCall 
pushTerminate()267ed1ae86aSJohn McCall void EHScopeStack::pushTerminate() {
268ed1ae86aSJohn McCall   char *Buffer = allocate(EHTerminateScope::getSize());
2698e4c74bbSJohn McCall   new (Buffer) EHTerminateScope(InnermostEHScope);
2708e4c74bbSJohn McCall   InnermostEHScope = stable_begin();
271ed1ae86aSJohn McCall }
272ed1ae86aSJohn McCall 
273ed1ae86aSJohn McCall /// Remove any 'null' fixups on the stack.  However, we can't pop more
274ed1ae86aSJohn McCall /// fixups than the fixup depth on the innermost normal cleanup, or
275ed1ae86aSJohn McCall /// else fixups that we try to add to that cleanup will end up in the
276ed1ae86aSJohn McCall /// wrong place.  We *could* try to shrink fixup depths, but that's
277ed1ae86aSJohn McCall /// actually a lot of work for little benefit.
popNullFixups()278ed1ae86aSJohn McCall void EHScopeStack::popNullFixups() {
279ed1ae86aSJohn McCall   // We expect this to only be called when there's still an innermost
280ed1ae86aSJohn McCall   // normal cleanup;  otherwise there really shouldn't be any fixups.
281ed1ae86aSJohn McCall   assert(hasNormalCleanups());
282ed1ae86aSJohn McCall 
283ed1ae86aSJohn McCall   EHScopeStack::iterator it = find(InnermostNormalCleanup);
284ed1ae86aSJohn McCall   unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
285ed1ae86aSJohn McCall   assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
286ed1ae86aSJohn McCall 
287ed1ae86aSJohn McCall   while (BranchFixups.size() > MinSize &&
2888a13c418SCraig Topper          BranchFixups.back().Destination == nullptr)
289ed1ae86aSJohn McCall     BranchFixups.pop_back();
290ed1ae86aSJohn McCall }
291ed1ae86aSJohn McCall 
createCleanupActiveFlag()292f66e4f7dSRichard Smith Address CodeGenFunction::createCleanupActiveFlag() {
293ed1ae86aSJohn McCall   // Create a variable to decide whether the cleanup needs to be run.
294cbd80f49SYaxun Liu   Address active = CreateTempAllocaWithoutCast(
295cbd80f49SYaxun Liu       Builder.getInt1Ty(), CharUnits::One(), "cleanup.cond");
296ed1ae86aSJohn McCall 
297ed1ae86aSJohn McCall   // Initialize it to false at a site that's guaranteed to be run
298ed1ae86aSJohn McCall   // before each evaluation.
299f4beacd0SJohn McCall   setBeforeOutermostConditional(Builder.getFalse(), active);
300ed1ae86aSJohn McCall 
301ed1ae86aSJohn McCall   // Initialize it to true at the current location.
302ed1ae86aSJohn McCall   Builder.CreateStore(Builder.getTrue(), active);
303ed1ae86aSJohn McCall 
304f66e4f7dSRichard Smith   return active;
305f66e4f7dSRichard Smith }
306f66e4f7dSRichard Smith 
initFullExprCleanupWithFlag(Address ActiveFlag)307f66e4f7dSRichard Smith void CodeGenFunction::initFullExprCleanupWithFlag(Address ActiveFlag) {
308ed1ae86aSJohn McCall   // Set that as the active flag in the cleanup.
309ed1ae86aSJohn McCall   EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
3107f416cc4SJohn McCall   assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
311f66e4f7dSRichard Smith   cleanup.setActiveFlag(ActiveFlag);
312ed1ae86aSJohn McCall 
313ed1ae86aSJohn McCall   if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
314ed1ae86aSJohn McCall   if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
315ed1ae86aSJohn McCall }
316ed1ae86aSJohn McCall 
anchor()3175fcf8da3SJohn McCall void EHScopeStack::Cleanup::anchor() {}
318ed1ae86aSJohn McCall 
createStoreInstBefore(llvm::Value * value,Address addr,llvm::Instruction * beforeInst)3197f416cc4SJohn McCall static void createStoreInstBefore(llvm::Value *value, Address addr,
3207f416cc4SJohn McCall                                   llvm::Instruction *beforeInst) {
3217f416cc4SJohn McCall   auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
322c79099e0SGuillaume Chatelet   store->setAlignment(addr.getAlignment().getAsAlign());
3237f416cc4SJohn McCall }
3247f416cc4SJohn McCall 
createLoadInstBefore(Address addr,const Twine & name,llvm::Instruction * beforeInst)3257f416cc4SJohn McCall static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
3267f416cc4SJohn McCall                                             llvm::Instruction *beforeInst) {
327428d0b6fSEli Friedman   return new llvm::LoadInst(addr.getElementType(), addr.getPointer(), name,
328428d0b6fSEli Friedman                             false, addr.getAlignment().getAsAlign(),
329b11decc2SEli Friedman                             beforeInst);
3307f416cc4SJohn McCall }
3317f416cc4SJohn McCall 
332ed1ae86aSJohn McCall /// All the branch fixups on the EH stack have propagated out past the
333ed1ae86aSJohn McCall /// outermost normal cleanup; resolve them all by adding cases to the
334ed1ae86aSJohn McCall /// given switch instruction.
ResolveAllBranchFixups(CodeGenFunction & CGF,llvm::SwitchInst * Switch,llvm::BasicBlock * CleanupEntry)335ed1ae86aSJohn McCall static void ResolveAllBranchFixups(CodeGenFunction &CGF,
336ed1ae86aSJohn McCall                                    llvm::SwitchInst *Switch,
337ed1ae86aSJohn McCall                                    llvm::BasicBlock *CleanupEntry) {
338ed1ae86aSJohn McCall   llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
339ed1ae86aSJohn McCall 
340ed1ae86aSJohn McCall   for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
341ed1ae86aSJohn McCall     // Skip this fixup if its destination isn't set.
342ed1ae86aSJohn McCall     BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
3438a13c418SCraig Topper     if (Fixup.Destination == nullptr) continue;
344ed1ae86aSJohn McCall 
345ed1ae86aSJohn McCall     // If there isn't an OptimisticBranchBlock, then InitialBranch is
346ed1ae86aSJohn McCall     // still pointing directly to its destination; forward it to the
347ed1ae86aSJohn McCall     // appropriate cleanup entry.  This is required in the specific
348ed1ae86aSJohn McCall     // case of
349ed1ae86aSJohn McCall     //   { std::string s; goto lbl; }
350ed1ae86aSJohn McCall     //   lbl:
351ed1ae86aSJohn McCall     // i.e. where there's an unresolved fixup inside a single cleanup
352ed1ae86aSJohn McCall     // entry which we're currently popping.
3538a13c418SCraig Topper     if (Fixup.OptimisticBranchBlock == nullptr) {
3547f416cc4SJohn McCall       createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
355ed1ae86aSJohn McCall                             CGF.getNormalCleanupDestSlot(),
356ed1ae86aSJohn McCall                             Fixup.InitialBranch);
357ed1ae86aSJohn McCall       Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
358ed1ae86aSJohn McCall     }
359ed1ae86aSJohn McCall 
360ed1ae86aSJohn McCall     // Don't add this case to the switch statement twice.
36182e95a3cSDavid Blaikie     if (!CasesAdded.insert(Fixup.Destination).second)
36282e95a3cSDavid Blaikie       continue;
363ed1ae86aSJohn McCall 
364ed1ae86aSJohn McCall     Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
365ed1ae86aSJohn McCall                     Fixup.Destination);
366ed1ae86aSJohn McCall   }
367ed1ae86aSJohn McCall 
368ed1ae86aSJohn McCall   CGF.EHStack.clearFixups();
369ed1ae86aSJohn McCall }
370ed1ae86aSJohn McCall 
371ed1ae86aSJohn McCall /// Transitions the terminator of the given exit-block of a cleanup to
372ed1ae86aSJohn McCall /// be a cleanup switch.
TransitionToCleanupSwitch(CodeGenFunction & CGF,llvm::BasicBlock * Block)373ed1ae86aSJohn McCall static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
374ed1ae86aSJohn McCall                                                    llvm::BasicBlock *Block) {
375ed1ae86aSJohn McCall   // If it's a branch, turn it into a switch whose default
376ed1ae86aSJohn McCall   // destination is its original target.
377e303c87eSChandler Carruth   llvm::Instruction *Term = Block->getTerminator();
378ed1ae86aSJohn McCall   assert(Term && "can't transition block without terminator");
379ed1ae86aSJohn McCall 
380ed1ae86aSJohn McCall   if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
381ed1ae86aSJohn McCall     assert(Br->isUnconditional());
3827f416cc4SJohn McCall     auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
3837f416cc4SJohn McCall                                      "cleanup.dest", Term);
384ed1ae86aSJohn McCall     llvm::SwitchInst *Switch =
385ed1ae86aSJohn McCall       llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
386ed1ae86aSJohn McCall     Br->eraseFromParent();
387ed1ae86aSJohn McCall     return Switch;
388ed1ae86aSJohn McCall   } else {
389ed1ae86aSJohn McCall     return cast<llvm::SwitchInst>(Term);
390ed1ae86aSJohn McCall   }
391ed1ae86aSJohn McCall }
392ed1ae86aSJohn McCall 
ResolveBranchFixups(llvm::BasicBlock * Block)393ed1ae86aSJohn McCall void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
394ed1ae86aSJohn McCall   assert(Block && "resolving a null target block");
395ed1ae86aSJohn McCall   if (!EHStack.getNumBranchFixups()) return;
396ed1ae86aSJohn McCall 
397ed1ae86aSJohn McCall   assert(EHStack.hasNormalCleanups() &&
398ed1ae86aSJohn McCall          "branch fixups exist with no normal cleanups on stack");
399ed1ae86aSJohn McCall 
400ed1ae86aSJohn McCall   llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
401ed1ae86aSJohn McCall   bool ResolvedAny = false;
402ed1ae86aSJohn McCall 
403ed1ae86aSJohn McCall   for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
404ed1ae86aSJohn McCall     // Skip this fixup if its destination doesn't match.
405ed1ae86aSJohn McCall     BranchFixup &Fixup = EHStack.getBranchFixup(I);
406ed1ae86aSJohn McCall     if (Fixup.Destination != Block) continue;
407ed1ae86aSJohn McCall 
4088a13c418SCraig Topper     Fixup.Destination = nullptr;
409ed1ae86aSJohn McCall     ResolvedAny = true;
410ed1ae86aSJohn McCall 
411ed1ae86aSJohn McCall     // If it doesn't have an optimistic branch block, LatestBranch is
412ed1ae86aSJohn McCall     // already pointing to the right place.
413ed1ae86aSJohn McCall     llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
414ed1ae86aSJohn McCall     if (!BranchBB)
415ed1ae86aSJohn McCall       continue;
416ed1ae86aSJohn McCall 
417ed1ae86aSJohn McCall     // Don't process the same optimistic branch block twice.
41882e95a3cSDavid Blaikie     if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
419ed1ae86aSJohn McCall       continue;
420ed1ae86aSJohn McCall 
421ed1ae86aSJohn McCall     llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
422ed1ae86aSJohn McCall 
423ed1ae86aSJohn McCall     // Add a case to the switch.
424ed1ae86aSJohn McCall     Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
425ed1ae86aSJohn McCall   }
426ed1ae86aSJohn McCall 
427ed1ae86aSJohn McCall   if (ResolvedAny)
428ed1ae86aSJohn McCall     EHStack.popNullFixups();
429ed1ae86aSJohn McCall }
430ed1ae86aSJohn McCall 
431ed1ae86aSJohn McCall /// Pops cleanup blocks until the given savepoint is reached.
PopCleanupBlocks(EHScopeStack::stable_iterator Old,std::initializer_list<llvm::Value ** > ValuesToReload)432092d0652SReid Kleckner void CodeGenFunction::PopCleanupBlocks(
433092d0652SReid Kleckner     EHScopeStack::stable_iterator Old,
434092d0652SReid Kleckner     std::initializer_list<llvm::Value **> ValuesToReload) {
435ed1ae86aSJohn McCall   assert(Old.isValid());
436ed1ae86aSJohn McCall 
437092d0652SReid Kleckner   bool HadBranches = false;
438ed1ae86aSJohn McCall   while (EHStack.stable_begin() != Old) {
439ed1ae86aSJohn McCall     EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
440092d0652SReid Kleckner     HadBranches |= Scope.hasBranches();
441ed1ae86aSJohn McCall 
442ed1ae86aSJohn McCall     // As long as Old strictly encloses the scope's enclosing normal
443ed1ae86aSJohn McCall     // cleanup, we're going to emit another normal cleanup which
444ed1ae86aSJohn McCall     // fallthrough can propagate through.
445ed1ae86aSJohn McCall     bool FallThroughIsBranchThrough =
446ed1ae86aSJohn McCall       Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
447ed1ae86aSJohn McCall 
448dc237b52SAdrian Prantl     PopCleanupBlock(FallThroughIsBranchThrough);
449ed1ae86aSJohn McCall   }
450092d0652SReid Kleckner 
451092d0652SReid Kleckner   // If we didn't have any branches, the insertion point before cleanups must
452092d0652SReid Kleckner   // dominate the current insertion point and we don't need to reload any
453092d0652SReid Kleckner   // values.
454092d0652SReid Kleckner   if (!HadBranches)
455092d0652SReid Kleckner     return;
456092d0652SReid Kleckner 
457092d0652SReid Kleckner   // Spill and reload all values that the caller wants to be live at the current
458092d0652SReid Kleckner   // insertion point.
459092d0652SReid Kleckner   for (llvm::Value **ReloadedValue : ValuesToReload) {
460092d0652SReid Kleckner     auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
461092d0652SReid Kleckner     if (!Inst)
462092d0652SReid Kleckner       continue;
4630449316eSReid Kleckner 
4640449316eSReid Kleckner     // Don't spill static allocas, they dominate all cleanups. These are created
4650449316eSReid Kleckner     // by binding a reference to a local variable or temporary.
4660449316eSReid Kleckner     auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
4670449316eSReid Kleckner     if (AI && AI->isStaticAlloca())
4680449316eSReid Kleckner       continue;
4690449316eSReid Kleckner 
470092d0652SReid Kleckner     Address Tmp =
471092d0652SReid Kleckner         CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
472092d0652SReid Kleckner 
473092d0652SReid Kleckner     // Find an insertion point after Inst and spill it to the temporary.
474092d0652SReid Kleckner     llvm::BasicBlock::iterator InsertBefore;
475092d0652SReid Kleckner     if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
476092d0652SReid Kleckner       InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
477092d0652SReid Kleckner     else
478092d0652SReid Kleckner       InsertBefore = std::next(Inst->getIterator());
479092d0652SReid Kleckner     CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
480092d0652SReid Kleckner 
481092d0652SReid Kleckner     // Reload the value at the current insertion point.
482092d0652SReid Kleckner     *ReloadedValue = Builder.CreateLoad(Tmp);
483092d0652SReid Kleckner   }
484ed1ae86aSJohn McCall }
485ed1ae86aSJohn McCall 
4865d1159ebSNick Lewycky /// Pops cleanup blocks until the given savepoint is reached, then add the
4875d1159ebSNick Lewycky /// cleanups from the given savepoint in the lifetime-extended cleanups stack.
PopCleanupBlocks(EHScopeStack::stable_iterator Old,size_t OldLifetimeExtendedSize,std::initializer_list<llvm::Value ** > ValuesToReload)488092d0652SReid Kleckner void CodeGenFunction::PopCleanupBlocks(
489092d0652SReid Kleckner     EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
490092d0652SReid Kleckner     std::initializer_list<llvm::Value **> ValuesToReload) {
491092d0652SReid Kleckner   PopCleanupBlocks(Old, ValuesToReload);
4925d1159ebSNick Lewycky 
4935d1159ebSNick Lewycky   // Move our deferred cleanups onto the EH stack.
494736a947bSRichard Smith   for (size_t I = OldLifetimeExtendedSize,
495736a947bSRichard Smith               E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
496736a947bSRichard Smith     // Alignment should be guaranteed by the vptrs in the individual cleanups.
497c3f89253SBenjamin Kramer     assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
498736a947bSRichard Smith            "misaligned cleanup stack entry");
499736a947bSRichard Smith 
500736a947bSRichard Smith     LifetimeExtendedCleanupHeader &Header =
501736a947bSRichard Smith         reinterpret_cast<LifetimeExtendedCleanupHeader&>(
502736a947bSRichard Smith             LifetimeExtendedCleanupStack[I]);
503736a947bSRichard Smith     I += sizeof(Header);
504736a947bSRichard Smith 
505736a947bSRichard Smith     EHStack.pushCopyOfCleanup(Header.getKind(),
506736a947bSRichard Smith                               &LifetimeExtendedCleanupStack[I],
507736a947bSRichard Smith                               Header.getSize());
508736a947bSRichard Smith     I += Header.getSize();
509f66e4f7dSRichard Smith 
510f66e4f7dSRichard Smith     if (Header.isConditional()) {
511f66e4f7dSRichard Smith       Address ActiveFlag =
512f66e4f7dSRichard Smith           reinterpret_cast<Address &>(LifetimeExtendedCleanupStack[I]);
513f66e4f7dSRichard Smith       initFullExprCleanupWithFlag(ActiveFlag);
514f66e4f7dSRichard Smith       I += sizeof(ActiveFlag);
515f66e4f7dSRichard Smith     }
516736a947bSRichard Smith   }
517736a947bSRichard Smith   LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
518736a947bSRichard Smith }
519736a947bSRichard Smith 
CreateNormalEntry(CodeGenFunction & CGF,EHCleanupScope & Scope)520ed1ae86aSJohn McCall static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
521ed1ae86aSJohn McCall                                            EHCleanupScope &Scope) {
522ed1ae86aSJohn McCall   assert(Scope.isNormalCleanup());
523ed1ae86aSJohn McCall   llvm::BasicBlock *Entry = Scope.getNormalBlock();
524ed1ae86aSJohn McCall   if (!Entry) {
525ed1ae86aSJohn McCall     Entry = CGF.createBasicBlock("cleanup");
526ed1ae86aSJohn McCall     Scope.setNormalBlock(Entry);
527ed1ae86aSJohn McCall   }
528ed1ae86aSJohn McCall   return Entry;
529ed1ae86aSJohn McCall }
530ed1ae86aSJohn McCall 
531ed1ae86aSJohn McCall /// Attempts to reduce a cleanup's entry block to a fallthrough.  This
532ed1ae86aSJohn McCall /// is basically llvm::MergeBlockIntoPredecessor, except
533ed1ae86aSJohn McCall /// simplified/optimized for the tighter constraints on cleanup blocks.
534ed1ae86aSJohn McCall ///
535ed1ae86aSJohn McCall /// Returns the new block, whatever it is.
SimplifyCleanupEntry(CodeGenFunction & CGF,llvm::BasicBlock * Entry)536ed1ae86aSJohn McCall static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
537ed1ae86aSJohn McCall                                               llvm::BasicBlock *Entry) {
538ed1ae86aSJohn McCall   llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
539ed1ae86aSJohn McCall   if (!Pred) return Entry;
540ed1ae86aSJohn McCall 
541ed1ae86aSJohn McCall   llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
542ed1ae86aSJohn McCall   if (!Br || Br->isConditional()) return Entry;
543ed1ae86aSJohn McCall   assert(Br->getSuccessor(0) == Entry);
544ed1ae86aSJohn McCall 
545ed1ae86aSJohn McCall   // If we were previously inserting at the end of the cleanup entry
546ed1ae86aSJohn McCall   // block, we'll need to continue inserting at the end of the
547ed1ae86aSJohn McCall   // predecessor.
548ed1ae86aSJohn McCall   bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
549ed1ae86aSJohn McCall   assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
550ed1ae86aSJohn McCall 
551ed1ae86aSJohn McCall   // Kill the branch.
552ed1ae86aSJohn McCall   Br->eraseFromParent();
553ed1ae86aSJohn McCall 
554ed1ae86aSJohn McCall   // Replace all uses of the entry with the predecessor, in case there
555ed1ae86aSJohn McCall   // are phis in the cleanup.
556ed1ae86aSJohn McCall   Entry->replaceAllUsesWith(Pred);
557ed1ae86aSJohn McCall 
558e03c05c3SJay Foad   // Merge the blocks.
559e03c05c3SJay Foad   Pred->getInstList().splice(Pred->end(), Entry->getInstList());
560e03c05c3SJay Foad 
561ed1ae86aSJohn McCall   // Kill the entry block.
562ed1ae86aSJohn McCall   Entry->eraseFromParent();
563ed1ae86aSJohn McCall 
564ed1ae86aSJohn McCall   if (WasInsertBlock)
565ed1ae86aSJohn McCall     CGF.Builder.SetInsertPoint(Pred);
566ed1ae86aSJohn McCall 
567ed1ae86aSJohn McCall   return Pred;
568ed1ae86aSJohn McCall }
569ed1ae86aSJohn McCall 
EmitCleanup(CodeGenFunction & CGF,EHScopeStack::Cleanup * Fn,EHScopeStack::Cleanup::Flags flags,Address ActiveFlag)570ed1ae86aSJohn McCall static void EmitCleanup(CodeGenFunction &CGF,
571ed1ae86aSJohn McCall                         EHScopeStack::Cleanup *Fn,
57230317fdaSJohn McCall                         EHScopeStack::Cleanup::Flags flags,
5737f416cc4SJohn McCall                         Address ActiveFlag) {
574ed1ae86aSJohn McCall   // If there's an active flag, load it and skip the cleanup if it's
575ed1ae86aSJohn McCall   // false.
5768a13c418SCraig Topper   llvm::BasicBlock *ContBB = nullptr;
5777f416cc4SJohn McCall   if (ActiveFlag.isValid()) {
578ed1ae86aSJohn McCall     ContBB = CGF.createBasicBlock("cleanup.done");
579ed1ae86aSJohn McCall     llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
580ed1ae86aSJohn McCall     llvm::Value *IsActive
581ed1ae86aSJohn McCall       = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
582ed1ae86aSJohn McCall     CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
583ed1ae86aSJohn McCall     CGF.EmitBlock(CleanupBB);
584ed1ae86aSJohn McCall   }
585ed1ae86aSJohn McCall 
586ed1ae86aSJohn McCall   // Ask the cleanup to emit itself.
58730317fdaSJohn McCall   Fn->Emit(CGF, flags);
588ed1ae86aSJohn McCall   assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
589ed1ae86aSJohn McCall 
590ed1ae86aSJohn McCall   // Emit the continuation block if there was an active flag.
5917f416cc4SJohn McCall   if (ActiveFlag.isValid())
592ed1ae86aSJohn McCall     CGF.EmitBlock(ContBB);
593ed1ae86aSJohn McCall }
594ed1ae86aSJohn McCall 
ForwardPrebranchedFallthrough(llvm::BasicBlock * Exit,llvm::BasicBlock * From,llvm::BasicBlock * To)595ed1ae86aSJohn McCall static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
596ed1ae86aSJohn McCall                                           llvm::BasicBlock *From,
597ed1ae86aSJohn McCall                                           llvm::BasicBlock *To) {
598ed1ae86aSJohn McCall   // Exit is the exit block of a cleanup, so it always terminates in
599ed1ae86aSJohn McCall   // an unconditional branch or a switch.
600e303c87eSChandler Carruth   llvm::Instruction *Term = Exit->getTerminator();
601ed1ae86aSJohn McCall 
602ed1ae86aSJohn McCall   if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
603ed1ae86aSJohn McCall     assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
604ed1ae86aSJohn McCall     Br->setSuccessor(0, To);
605ed1ae86aSJohn McCall   } else {
606ed1ae86aSJohn McCall     llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
607ed1ae86aSJohn McCall     for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
608ed1ae86aSJohn McCall       if (Switch->getSuccessor(I) == From)
609ed1ae86aSJohn McCall         Switch->setSuccessor(I, To);
610ed1ae86aSJohn McCall   }
611ed1ae86aSJohn McCall }
612ed1ae86aSJohn McCall 
613f82bdf6dSJohn McCall /// We don't need a normal entry block for the given cleanup.
614f82bdf6dSJohn McCall /// Optimistic fixup branches can cause these blocks to come into
615f82bdf6dSJohn McCall /// existence anyway;  if so, destroy it.
616f82bdf6dSJohn McCall ///
617f82bdf6dSJohn McCall /// The validity of this transformation is very much specific to the
618f82bdf6dSJohn McCall /// exact ways in which we form branches to cleanup entries.
destroyOptimisticNormalEntry(CodeGenFunction & CGF,EHCleanupScope & scope)619f82bdf6dSJohn McCall static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
620f82bdf6dSJohn McCall                                          EHCleanupScope &scope) {
621f82bdf6dSJohn McCall   llvm::BasicBlock *entry = scope.getNormalBlock();
622f82bdf6dSJohn McCall   if (!entry) return;
623f82bdf6dSJohn McCall 
624f82bdf6dSJohn McCall   // Replace all the uses with unreachable.
625f82bdf6dSJohn McCall   llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
626f82bdf6dSJohn McCall   for (llvm::BasicBlock::use_iterator
627f82bdf6dSJohn McCall          i = entry->use_begin(), e = entry->use_end(); i != e; ) {
6284d01fff4SChandler Carruth     llvm::Use &use = *i;
629f82bdf6dSJohn McCall     ++i;
630f82bdf6dSJohn McCall 
631f82bdf6dSJohn McCall     use.set(unreachableBB);
632f82bdf6dSJohn McCall 
633f82bdf6dSJohn McCall     // The only uses should be fixup switches.
634f82bdf6dSJohn McCall     llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
6355fecf544SStepan Dyatkovskiy     if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
636f82bdf6dSJohn McCall       // Replace the switch with a branch.
637260161b8SChandler Carruth       llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
638f82bdf6dSJohn McCall 
639f82bdf6dSJohn McCall       // The switch operand is a load from the cleanup-dest alloca.
640f82bdf6dSJohn McCall       llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
641f82bdf6dSJohn McCall 
642f82bdf6dSJohn McCall       // Destroy the switch.
643f82bdf6dSJohn McCall       si->eraseFromParent();
644f82bdf6dSJohn McCall 
645f82bdf6dSJohn McCall       // Destroy the load.
6465cdf0383SJohn McCall       assert(condition->getOperand(0) == CGF.NormalCleanupDest.getPointer());
647f82bdf6dSJohn McCall       assert(condition->use_empty());
648f82bdf6dSJohn McCall       condition->eraseFromParent();
649f82bdf6dSJohn McCall     }
650f82bdf6dSJohn McCall   }
651f82bdf6dSJohn McCall 
652f82bdf6dSJohn McCall   assert(entry->use_empty());
653f82bdf6dSJohn McCall   delete entry;
654f82bdf6dSJohn McCall }
655f82bdf6dSJohn McCall 
656ed1ae86aSJohn McCall /// Pops a cleanup block.  If the block includes a normal cleanup, the
657ed1ae86aSJohn McCall /// current insertion point is threaded through the cleanup, as are
658ed1ae86aSJohn McCall /// any branch fixups on the cleanup.
PopCleanupBlock(bool FallthroughIsBranchThrough)659dc237b52SAdrian Prantl void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
660ed1ae86aSJohn McCall   assert(!EHStack.empty() && "cleanup stack is empty!");
661ed1ae86aSJohn McCall   assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
662ed1ae86aSJohn McCall   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
663ed1ae86aSJohn McCall   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
664ed1ae86aSJohn McCall 
665ed1ae86aSJohn McCall   // Remember activation information.
666ed1ae86aSJohn McCall   bool IsActive = Scope.isActive();
6677f416cc4SJohn McCall   Address NormalActiveFlag =
6687f416cc4SJohn McCall     Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
6697f416cc4SJohn McCall                                           : Address::invalid();
6707f416cc4SJohn McCall   Address EHActiveFlag =
6717f416cc4SJohn McCall     Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
6727f416cc4SJohn McCall                                       : Address::invalid();
673ed1ae86aSJohn McCall 
674ed1ae86aSJohn McCall   // Check whether we need an EH cleanup.  This is only true if we've
675ed1ae86aSJohn McCall   // generated a lazy EH cleanup block.
6768e4c74bbSJohn McCall   llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
6778a13c418SCraig Topper   assert(Scope.hasEHBranches() == (EHEntry != nullptr));
6788a13c418SCraig Topper   bool RequiresEHCleanup = (EHEntry != nullptr);
6798e4c74bbSJohn McCall   EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
680ed1ae86aSJohn McCall 
681ed1ae86aSJohn McCall   // Check the three conditions which might require a normal cleanup:
682ed1ae86aSJohn McCall 
683ed1ae86aSJohn McCall   // - whether there are branch fix-ups through this cleanup
684ed1ae86aSJohn McCall   unsigned FixupDepth = Scope.getFixupDepth();
685ed1ae86aSJohn McCall   bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
686ed1ae86aSJohn McCall 
687ed1ae86aSJohn McCall   // - whether there are branch-throughs or branch-afters
688ed1ae86aSJohn McCall   bool HasExistingBranches = Scope.hasBranches();
689ed1ae86aSJohn McCall 
690ed1ae86aSJohn McCall   // - whether there's a fallthrough
691ed1ae86aSJohn McCall   llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
6928a13c418SCraig Topper   bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
693ed1ae86aSJohn McCall 
694ed1ae86aSJohn McCall   // Branch-through fall-throughs leave the insertion point set to the
695ed1ae86aSJohn McCall   // end of the last cleanup, which points to the current scope.  The
696ed1ae86aSJohn McCall   // rest of IR gen doesn't need to worry about this; it only happens
697ed1ae86aSJohn McCall   // during the execution of PopCleanupBlocks().
698ed1ae86aSJohn McCall   bool HasPrebranchedFallthrough =
699ed1ae86aSJohn McCall     (FallthroughSource && FallthroughSource->getTerminator());
700ed1ae86aSJohn McCall 
701ed1ae86aSJohn McCall   // If this is a normal cleanup, then having a prebranched
702ed1ae86aSJohn McCall   // fallthrough implies that the fallthrough source unconditionally
703ed1ae86aSJohn McCall   // jumps here.
704ed1ae86aSJohn McCall   assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
705ed1ae86aSJohn McCall          (Scope.getNormalBlock() &&
706ed1ae86aSJohn McCall           FallthroughSource->getTerminator()->getSuccessor(0)
707ed1ae86aSJohn McCall             == Scope.getNormalBlock()));
708ed1ae86aSJohn McCall 
709ed1ae86aSJohn McCall   bool RequiresNormalCleanup = false;
710ed1ae86aSJohn McCall   if (Scope.isNormalCleanup() &&
711ed1ae86aSJohn McCall       (HasFixups || HasExistingBranches || HasFallthrough)) {
712ed1ae86aSJohn McCall     RequiresNormalCleanup = true;
713ed1ae86aSJohn McCall   }
714ed1ae86aSJohn McCall 
71545e42952SJohn McCall   // If we have a prebranched fallthrough into an inactive normal
71645e42952SJohn McCall   // cleanup, rewrite it so that it leads to the appropriate place.
71745e42952SJohn McCall   if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
71845e42952SJohn McCall     llvm::BasicBlock *prebranchDest;
719ed1ae86aSJohn McCall 
72045e42952SJohn McCall     // If the prebranch is semantically branching through the next
72145e42952SJohn McCall     // cleanup, just forward it to the next block, leaving the
72245e42952SJohn McCall     // insertion point in the prebranched block.
723ed1ae86aSJohn McCall     if (FallthroughIsBranchThrough) {
72445e42952SJohn McCall       EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
72545e42952SJohn McCall       prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
72645e42952SJohn McCall 
72745e42952SJohn McCall     // Otherwise, we need to make a new block.  If the normal cleanup
72845e42952SJohn McCall     // isn't being used at all, we could actually reuse the normal
72945e42952SJohn McCall     // entry block, but this is simpler, and it avoids conflicts with
73045e42952SJohn McCall     // dead optimistic fixup branches.
73145e42952SJohn McCall     } else {
73245e42952SJohn McCall       prebranchDest = createBasicBlock("forwarded-prebranch");
73345e42952SJohn McCall       EmitBlock(prebranchDest);
73445e42952SJohn McCall     }
73545e42952SJohn McCall 
73645e42952SJohn McCall     llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
73745e42952SJohn McCall     assert(normalEntry && !normalEntry->use_empty());
738ed1ae86aSJohn McCall 
739ed1ae86aSJohn McCall     ForwardPrebranchedFallthrough(FallthroughSource,
74045e42952SJohn McCall                                   normalEntry, prebranchDest);
741ed1ae86aSJohn McCall   }
742ed1ae86aSJohn McCall 
743ed1ae86aSJohn McCall   // If we don't need the cleanup at all, we're done.
744ed1ae86aSJohn McCall   if (!RequiresNormalCleanup && !RequiresEHCleanup) {
745f82bdf6dSJohn McCall     destroyOptimisticNormalEntry(*this, Scope);
746ed1ae86aSJohn McCall     EHStack.popCleanup(); // safe because there are no fixups
747ed1ae86aSJohn McCall     assert(EHStack.getNumBranchFixups() == 0 ||
748ed1ae86aSJohn McCall            EHStack.hasNormalCleanups());
749ed1ae86aSJohn McCall     return;
750ed1ae86aSJohn McCall   }
751ed1ae86aSJohn McCall 
75254a3b268SJames Y Knight   // Copy the cleanup emission data out.  This uses either a stack
75354a3b268SJames Y Knight   // array or malloc'd memory, depending on the size, which is
75454a3b268SJames Y Knight   // behavior that SmallVector would provide, if we could use it
75554a3b268SJames Y Knight   // here. Unfortunately, if you ask for a SmallVector<char>, the
75654a3b268SJames Y Knight   // alignment isn't sufficient.
7576c3e4ec4SBenjamin Kramer   auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
758ac868620SJF Bastien   alignas(EHScopeStack::ScopeStackAlignment) char
759ac868620SJF Bastien       CleanupBufferStack[8 * sizeof(void *)];
76054a3b268SJames Y Knight   std::unique_ptr<char[]> CleanupBufferHeap;
76154a3b268SJames Y Knight   size_t CleanupSize = Scope.getCleanupSize();
76254a3b268SJames Y Knight   EHScopeStack::Cleanup *Fn;
76354a3b268SJames Y Knight 
76454a3b268SJames Y Knight   if (CleanupSize <= sizeof(CleanupBufferStack)) {
765ac868620SJF Bastien     memcpy(CleanupBufferStack, CleanupSource, CleanupSize);
766ac868620SJF Bastien     Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack);
76754a3b268SJames Y Knight   } else {
76854a3b268SJames Y Knight     CleanupBufferHeap.reset(new char[CleanupSize]);
76954a3b268SJames Y Knight     memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
77054a3b268SJames Y Knight     Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
77154a3b268SJames Y Knight   }
772ed1ae86aSJohn McCall 
7738e4c74bbSJohn McCall   EHScopeStack::Cleanup::Flags cleanupFlags;
7748e4c74bbSJohn McCall   if (Scope.isNormalCleanup())
7758e4c74bbSJohn McCall     cleanupFlags.setIsNormalCleanupKind();
7768e4c74bbSJohn McCall   if (Scope.isEHCleanup())
7778e4c74bbSJohn McCall     cleanupFlags.setIsEHCleanupKind();
778ed1ae86aSJohn McCall 
779797ad701STen Tzen   // Under -EHa, invoke seh.scope.end() to mark scope end before dtor
780797ad701STen Tzen   bool IsEHa = getLangOpts().EHAsynch && !Scope.isLifetimeMarker();
781797ad701STen Tzen   const EHPersonality &Personality = EHPersonality::get(*this);
782ed1ae86aSJohn McCall   if (!RequiresNormalCleanup) {
783797ad701STen Tzen     // Mark CPP scope end for passed-by-value Arg temp
784797ad701STen Tzen     //   per Windows ABI which is "normally" Cleanup in callee
785797ad701STen Tzen     if (IsEHa && getInvokeDest()) {
786797ad701STen Tzen       if (Personality.isMSVCXXPersonality())
787797ad701STen Tzen         EmitSehCppScopeEnd();
788797ad701STen Tzen     }
789f82bdf6dSJohn McCall     destroyOptimisticNormalEntry(*this, Scope);
790ed1ae86aSJohn McCall     EHStack.popCleanup();
791ed1ae86aSJohn McCall   } else {
792ed1ae86aSJohn McCall     // If we have a fallthrough and no other need for the cleanup,
793ed1ae86aSJohn McCall     // emit it directly.
794797ad701STen Tzen     if (HasFallthrough && !HasPrebranchedFallthrough && !HasFixups &&
795797ad701STen Tzen         !HasExistingBranches) {
796797ad701STen Tzen 
797797ad701STen Tzen       // mark SEH scope end for fall-through flow
798797ad701STen Tzen       if (IsEHa && getInvokeDest()) {
799797ad701STen Tzen         if (Personality.isMSVCXXPersonality())
800797ad701STen Tzen           EmitSehCppScopeEnd();
801797ad701STen Tzen         else
802797ad701STen Tzen           EmitSehTryScopeEnd();
803797ad701STen Tzen       }
804ed1ae86aSJohn McCall 
805f82bdf6dSJohn McCall       destroyOptimisticNormalEntry(*this, Scope);
806ed1ae86aSJohn McCall       EHStack.popCleanup();
807ed1ae86aSJohn McCall 
80830317fdaSJohn McCall       EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
809ed1ae86aSJohn McCall 
810ed1ae86aSJohn McCall     // Otherwise, the best approach is to thread everything through
811ed1ae86aSJohn McCall     // the cleanup block and then try to clean up after ourselves.
812ed1ae86aSJohn McCall     } else {
813ed1ae86aSJohn McCall       // Force the entry block to exist.
814ed1ae86aSJohn McCall       llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
815ed1ae86aSJohn McCall 
816ed1ae86aSJohn McCall       // I.  Set up the fallthrough edge in.
817ed1ae86aSJohn McCall 
81845e42952SJohn McCall       CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
81945e42952SJohn McCall 
820ed1ae86aSJohn McCall       // If there's a fallthrough, we need to store the cleanup
821ed1ae86aSJohn McCall       // destination index.  For fall-throughs this is always zero.
822ed1ae86aSJohn McCall       if (HasFallthrough) {
823ed1ae86aSJohn McCall         if (!HasPrebranchedFallthrough)
824ed1ae86aSJohn McCall           Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
825ed1ae86aSJohn McCall 
82645e42952SJohn McCall       // Otherwise, save and clear the IP if we don't have fallthrough
82745e42952SJohn McCall       // because the cleanup is inactive.
828ed1ae86aSJohn McCall       } else if (FallthroughSource) {
829ed1ae86aSJohn McCall         assert(!IsActive && "source without fallthrough for active cleanup");
83045e42952SJohn McCall         savedInactiveFallthroughIP = Builder.saveAndClearIP();
831ed1ae86aSJohn McCall       }
832ed1ae86aSJohn McCall 
833ed1ae86aSJohn McCall       // II.  Emit the entry block.  This implicitly branches to it if
834ed1ae86aSJohn McCall       // we have fallthrough.  All the fixups and existing branches
835ed1ae86aSJohn McCall       // should already be branched to it.
836ed1ae86aSJohn McCall       EmitBlock(NormalEntry);
837ed1ae86aSJohn McCall 
838797ad701STen Tzen       // intercept normal cleanup to mark SEH scope end
839797ad701STen Tzen       if (IsEHa) {
840797ad701STen Tzen         if (Personality.isMSVCXXPersonality())
841797ad701STen Tzen           EmitSehCppScopeEnd();
842797ad701STen Tzen         else
843797ad701STen Tzen           EmitSehTryScopeEnd();
844797ad701STen Tzen       }
845797ad701STen Tzen 
846ed1ae86aSJohn McCall       // III.  Figure out where we're going and build the cleanup
847ed1ae86aSJohn McCall       // epilogue.
848ed1ae86aSJohn McCall 
849ed1ae86aSJohn McCall       bool HasEnclosingCleanups =
850ed1ae86aSJohn McCall         (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
851ed1ae86aSJohn McCall 
852ed1ae86aSJohn McCall       // Compute the branch-through dest if we need it:
853ed1ae86aSJohn McCall       //   - if there are branch-throughs threaded through the scope
854ed1ae86aSJohn McCall       //   - if fall-through is a branch-through
855ed1ae86aSJohn McCall       //   - if there are fixups that will be optimistically forwarded
856ed1ae86aSJohn McCall       //     to the enclosing cleanup
8578a13c418SCraig Topper       llvm::BasicBlock *BranchThroughDest = nullptr;
858ed1ae86aSJohn McCall       if (Scope.hasBranchThroughs() ||
859ed1ae86aSJohn McCall           (FallthroughSource && FallthroughIsBranchThrough) ||
860ed1ae86aSJohn McCall           (HasFixups && HasEnclosingCleanups)) {
861ed1ae86aSJohn McCall         assert(HasEnclosingCleanups);
862ed1ae86aSJohn McCall         EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
863ed1ae86aSJohn McCall         BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
864ed1ae86aSJohn McCall       }
865ed1ae86aSJohn McCall 
8668a13c418SCraig Topper       llvm::BasicBlock *FallthroughDest = nullptr;
867c749745bSBenjamin Kramer       SmallVector<llvm::Instruction*, 2> InstsToAppend;
868ed1ae86aSJohn McCall 
869ed1ae86aSJohn McCall       // If there's exactly one branch-after and no other threads,
870ed1ae86aSJohn McCall       // we can route it without a switch.
871ed1ae86aSJohn McCall       if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
872ed1ae86aSJohn McCall           Scope.getNumBranchAfters() == 1) {
873ed1ae86aSJohn McCall         assert(!BranchThroughDest || !IsActive);
874ed1ae86aSJohn McCall 
875dc012fa2SDavid Majnemer         // Clean up the possibly dead store to the cleanup dest slot.
876dc012fa2SDavid Majnemer         llvm::Instruction *NormalCleanupDestSlot =
8777f416cc4SJohn McCall             cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
878dc012fa2SDavid Majnemer         if (NormalCleanupDestSlot->hasOneUse()) {
879dc012fa2SDavid Majnemer           NormalCleanupDestSlot->user_back()->eraseFromParent();
880dc012fa2SDavid Majnemer           NormalCleanupDestSlot->eraseFromParent();
8815cdf0383SJohn McCall           NormalCleanupDest = Address::invalid();
882dc012fa2SDavid Majnemer         }
883dc012fa2SDavid Majnemer 
884ed1ae86aSJohn McCall         llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
885ed1ae86aSJohn McCall         InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
886ed1ae86aSJohn McCall 
887ed1ae86aSJohn McCall       // Build a switch-out if we need it:
888ed1ae86aSJohn McCall       //   - if there are branch-afters threaded through the scope
889ed1ae86aSJohn McCall       //   - if fall-through is a branch-after
890ed1ae86aSJohn McCall       //   - if there are fixups that have nowhere left to go and
891ed1ae86aSJohn McCall       //     so must be immediately resolved
892ed1ae86aSJohn McCall       } else if (Scope.getNumBranchAfters() ||
893ed1ae86aSJohn McCall                  (HasFallthrough && !FallthroughIsBranchThrough) ||
894ed1ae86aSJohn McCall                  (HasFixups && !HasEnclosingCleanups)) {
895ed1ae86aSJohn McCall 
896ed1ae86aSJohn McCall         llvm::BasicBlock *Default =
897ed1ae86aSJohn McCall           (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
898ed1ae86aSJohn McCall 
899ed1ae86aSJohn McCall         // TODO: base this on the number of branch-afters and fixups
900ed1ae86aSJohn McCall         const unsigned SwitchCapacity = 10;
901ed1ae86aSJohn McCall 
9024eabd006SAaron Smith         // pass the abnormal exit flag to Fn (SEH cleanup)
9034eabd006SAaron Smith         cleanupFlags.setHasExitSwitch();
9044eabd006SAaron Smith 
905ed1ae86aSJohn McCall         llvm::LoadInst *Load =
9067f416cc4SJohn McCall           createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
9077f416cc4SJohn McCall                                nullptr);
908ed1ae86aSJohn McCall         llvm::SwitchInst *Switch =
909ed1ae86aSJohn McCall           llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
910ed1ae86aSJohn McCall 
911ed1ae86aSJohn McCall         InstsToAppend.push_back(Load);
912ed1ae86aSJohn McCall         InstsToAppend.push_back(Switch);
913ed1ae86aSJohn McCall 
914ed1ae86aSJohn McCall         // Branch-after fallthrough.
915ed1ae86aSJohn McCall         if (FallthroughSource && !FallthroughIsBranchThrough) {
916ed1ae86aSJohn McCall           FallthroughDest = createBasicBlock("cleanup.cont");
917ed1ae86aSJohn McCall           if (HasFallthrough)
918ed1ae86aSJohn McCall             Switch->addCase(Builder.getInt32(0), FallthroughDest);
919ed1ae86aSJohn McCall         }
920ed1ae86aSJohn McCall 
921ed1ae86aSJohn McCall         for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
922ed1ae86aSJohn McCall           Switch->addCase(Scope.getBranchAfterIndex(I),
923ed1ae86aSJohn McCall                           Scope.getBranchAfterBlock(I));
924ed1ae86aSJohn McCall         }
925ed1ae86aSJohn McCall 
926ed1ae86aSJohn McCall         // If there aren't any enclosing cleanups, we can resolve all
927ed1ae86aSJohn McCall         // the fixups now.
928ed1ae86aSJohn McCall         if (HasFixups && !HasEnclosingCleanups)
929ed1ae86aSJohn McCall           ResolveAllBranchFixups(*this, Switch, NormalEntry);
930ed1ae86aSJohn McCall       } else {
931ed1ae86aSJohn McCall         // We should always have a branch-through destination in this case.
932ed1ae86aSJohn McCall         assert(BranchThroughDest);
933ed1ae86aSJohn McCall         InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
934ed1ae86aSJohn McCall       }
935ed1ae86aSJohn McCall 
936ed1ae86aSJohn McCall       // IV.  Pop the cleanup and emit it.
937ed1ae86aSJohn McCall       EHStack.popCleanup();
938ed1ae86aSJohn McCall       assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
939ed1ae86aSJohn McCall 
94030317fdaSJohn McCall       EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
941ed1ae86aSJohn McCall 
942ed1ae86aSJohn McCall       // Append the prepared cleanup prologue from above.
943ed1ae86aSJohn McCall       llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
944c749745bSBenjamin Kramer       for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
945c749745bSBenjamin Kramer         NormalExit->getInstList().push_back(InstsToAppend[I]);
946ed1ae86aSJohn McCall 
947ed1ae86aSJohn McCall       // Optimistically hope that any fixups will continue falling through.
948ed1ae86aSJohn McCall       for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
949ed1ae86aSJohn McCall            I < E; ++I) {
950ad7c5c16SJohn McCall         BranchFixup &Fixup = EHStack.getBranchFixup(I);
951ed1ae86aSJohn McCall         if (!Fixup.Destination) continue;
952ed1ae86aSJohn McCall         if (!Fixup.OptimisticBranchBlock) {
9537f416cc4SJohn McCall           createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
954ed1ae86aSJohn McCall                                 getNormalCleanupDestSlot(),
955ed1ae86aSJohn McCall                                 Fixup.InitialBranch);
956ed1ae86aSJohn McCall           Fixup.InitialBranch->setSuccessor(0, NormalEntry);
957ed1ae86aSJohn McCall         }
958ed1ae86aSJohn McCall         Fixup.OptimisticBranchBlock = NormalExit;
959ed1ae86aSJohn McCall       }
960ed1ae86aSJohn McCall 
961ed1ae86aSJohn McCall       // V.  Set up the fallthrough edge out.
962ed1ae86aSJohn McCall 
96345e42952SJohn McCall       // Case 1: a fallthrough source exists but doesn't branch to the
96445e42952SJohn McCall       // cleanup because the cleanup is inactive.
965ed1ae86aSJohn McCall       if (!HasFallthrough && FallthroughSource) {
96645e42952SJohn McCall         // Prebranched fallthrough was forwarded earlier.
96745e42952SJohn McCall         // Non-prebranched fallthrough doesn't need to be forwarded.
96845e42952SJohn McCall         // Either way, all we need to do is restore the IP we cleared before.
969ed1ae86aSJohn McCall         assert(!IsActive);
97045e42952SJohn McCall         Builder.restoreIP(savedInactiveFallthroughIP);
971ed1ae86aSJohn McCall 
972ed1ae86aSJohn McCall       // Case 2: a fallthrough source exists and should branch to the
973ed1ae86aSJohn McCall       // cleanup, but we're not supposed to branch through to the next
974ed1ae86aSJohn McCall       // cleanup.
975ed1ae86aSJohn McCall       } else if (HasFallthrough && FallthroughDest) {
976ed1ae86aSJohn McCall         assert(!FallthroughIsBranchThrough);
977ed1ae86aSJohn McCall         EmitBlock(FallthroughDest);
978ed1ae86aSJohn McCall 
979ed1ae86aSJohn McCall       // Case 3: a fallthrough source exists and should branch to the
980ed1ae86aSJohn McCall       // cleanup and then through to the next.
981ed1ae86aSJohn McCall       } else if (HasFallthrough) {
982ed1ae86aSJohn McCall         // Everything is already set up for this.
983ed1ae86aSJohn McCall 
984ed1ae86aSJohn McCall       // Case 4: no fallthrough source exists.
985ed1ae86aSJohn McCall       } else {
986ed1ae86aSJohn McCall         Builder.ClearInsertionPoint();
987ed1ae86aSJohn McCall       }
988ed1ae86aSJohn McCall 
989ed1ae86aSJohn McCall       // VI.  Assorted cleaning.
990ed1ae86aSJohn McCall 
991ed1ae86aSJohn McCall       // Check whether we can merge NormalEntry into a single predecessor.
992ed1ae86aSJohn McCall       // This might invalidate (non-IR) pointers to NormalEntry.
993ed1ae86aSJohn McCall       llvm::BasicBlock *NewNormalEntry =
994ed1ae86aSJohn McCall         SimplifyCleanupEntry(*this, NormalEntry);
995ed1ae86aSJohn McCall 
996ed1ae86aSJohn McCall       // If it did invalidate those pointers, and NormalEntry was the same
997ed1ae86aSJohn McCall       // as NormalExit, go back and patch up the fixups.
998ed1ae86aSJohn McCall       if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
999ed1ae86aSJohn McCall         for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1000ed1ae86aSJohn McCall                I < E; ++I)
1001ad7c5c16SJohn McCall           EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
1002ed1ae86aSJohn McCall     }
1003ed1ae86aSJohn McCall   }
1004ed1ae86aSJohn McCall 
1005ed1ae86aSJohn McCall   assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1006ed1ae86aSJohn McCall 
1007ed1ae86aSJohn McCall   // Emit the EH cleanup if required.
1008ed1ae86aSJohn McCall   if (RequiresEHCleanup) {
1009ed1ae86aSJohn McCall     CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1010ed1ae86aSJohn McCall 
1011ed1ae86aSJohn McCall     EmitBlock(EHEntry);
101255391524SReid Kleckner 
1013a002bd54SReid Kleckner     llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
1014a002bd54SReid Kleckner 
1015a002bd54SReid Kleckner     // Push a terminate scope or cleanupendpad scope around the potentially
1016a002bd54SReid Kleckner     // throwing cleanups. For funclet EH personalities, the cleanupendpad models
1017a002bd54SReid Kleckner     // program termination when cleanups throw.
101855391524SReid Kleckner     bool PushedTerminate = false;
10194e52d6f8SDavid Majnemer     SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
10204e52d6f8SDavid Majnemer         CurrentFuncletPad);
1021a002bd54SReid Kleckner     llvm::CleanupPadInst *CPI = nullptr;
1022c6479199SHeejin Ahn 
1023c6479199SHeejin Ahn     const EHPersonality &Personality = EHPersonality::get(*this);
1024c6479199SHeejin Ahn     if (Personality.usesFuncletPads()) {
10254e52d6f8SDavid Majnemer       llvm::Value *ParentPad = CurrentFuncletPad;
10264e52d6f8SDavid Majnemer       if (!ParentPad)
10274e52d6f8SDavid Majnemer         ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
10284e52d6f8SDavid Majnemer       CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
102955391524SReid Kleckner     }
103055391524SReid Kleckner 
1031c6479199SHeejin Ahn     // Non-MSVC personalities need to terminate when an EH cleanup throws.
1032c6479199SHeejin Ahn     if (!Personality.isMSVCPersonality()) {
1033c6479199SHeejin Ahn       EHStack.pushTerminate();
1034c6479199SHeejin Ahn       PushedTerminate = true;
1035c6479199SHeejin Ahn     }
1036c6479199SHeejin Ahn 
1037abab7760SEli Friedman     // We only actually emit the cleanup code if the cleanup is either
1038abab7760SEli Friedman     // active or was used before it was deactivated.
10397f416cc4SJohn McCall     if (EHActiveFlag.isValid() || IsActive) {
104030317fdaSJohn McCall       cleanupFlags.setIsForEHCleanup();
104130317fdaSJohn McCall       EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
1042abab7760SEli Friedman     }
1043ed1ae86aSJohn McCall 
1044e888a2f6SDavid Majnemer     if (CPI)
1045ce536a59SJoseph Tremoulet       Builder.CreateCleanupRet(CPI, NextAction);
1046dbf1045aSDavid Majnemer     else
1047dbf1045aSDavid Majnemer       Builder.CreateBr(NextAction);
1048ed1ae86aSJohn McCall 
104955391524SReid Kleckner     // Leave the terminate scope.
105055391524SReid Kleckner     if (PushedTerminate)
105155391524SReid Kleckner       EHStack.popTerminate();
105255391524SReid Kleckner 
1053ed1ae86aSJohn McCall     Builder.restoreIP(SavedIP);
1054ed1ae86aSJohn McCall 
1055ed1ae86aSJohn McCall     SimplifyCleanupEntry(*this, EHEntry);
1056ed1ae86aSJohn McCall   }
1057ed1ae86aSJohn McCall }
1058ed1ae86aSJohn McCall 
1059e25ffdf8SJustin Bogner /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1060e25ffdf8SJustin Bogner /// specified destination obviously has no cleanups to run.  'false' is always
1061e25ffdf8SJustin Bogner /// a conservatively correct answer for this method.
isObviouslyBranchWithoutCleanups(JumpDest Dest) const1062e25ffdf8SJustin Bogner bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
1063e25ffdf8SJustin Bogner   assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1064e25ffdf8SJustin Bogner          && "stale jump destination");
1065e25ffdf8SJustin Bogner 
1066e25ffdf8SJustin Bogner   // Calculate the innermost active normal cleanup.
1067e25ffdf8SJustin Bogner   EHScopeStack::stable_iterator TopCleanup =
1068e25ffdf8SJustin Bogner     EHStack.getInnermostActiveNormalCleanup();
1069e25ffdf8SJustin Bogner 
1070e25ffdf8SJustin Bogner   // If we're not in an active normal cleanup scope, or if the
1071e25ffdf8SJustin Bogner   // destination scope is within the innermost active normal cleanup
1072e25ffdf8SJustin Bogner   // scope, we don't need to worry about fixups.
1073e25ffdf8SJustin Bogner   if (TopCleanup == EHStack.stable_end() ||
1074e25ffdf8SJustin Bogner       TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
1075e25ffdf8SJustin Bogner     return true;
1076e25ffdf8SJustin Bogner 
1077e25ffdf8SJustin Bogner   // Otherwise, we might need some cleanups.
1078e25ffdf8SJustin Bogner   return false;
1079e25ffdf8SJustin Bogner }
1080e25ffdf8SJustin Bogner 
1081e25ffdf8SJustin Bogner 
1082ed1ae86aSJohn McCall /// Terminate the current block by emitting a branch which might leave
1083ed1ae86aSJohn McCall /// the current cleanup-protected scope.  The target scope may not yet
1084ed1ae86aSJohn McCall /// be known, in which case this will require a fixup.
1085ed1ae86aSJohn McCall ///
1086ed1ae86aSJohn McCall /// As a side-effect, this method clears the insertion point.
EmitBranchThroughCleanup(JumpDest Dest)1087ed1ae86aSJohn McCall void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
10881b93f1baSJohn McCall   assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1089ed1ae86aSJohn McCall          && "stale jump destination");
1090ed1ae86aSJohn McCall 
1091ed1ae86aSJohn McCall   if (!HaveInsertPoint())
1092ed1ae86aSJohn McCall     return;
1093ed1ae86aSJohn McCall 
1094ed1ae86aSJohn McCall   // Create the branch.
1095ed1ae86aSJohn McCall   llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1096ed1ae86aSJohn McCall 
1097ed1ae86aSJohn McCall   // Calculate the innermost active normal cleanup.
1098ed1ae86aSJohn McCall   EHScopeStack::stable_iterator
1099ed1ae86aSJohn McCall     TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1100ed1ae86aSJohn McCall 
1101ed1ae86aSJohn McCall   // If we're not in an active normal cleanup scope, or if the
1102ed1ae86aSJohn McCall   // destination scope is within the innermost active normal cleanup
1103ed1ae86aSJohn McCall   // scope, we don't need to worry about fixups.
1104ed1ae86aSJohn McCall   if (TopCleanup == EHStack.stable_end() ||
1105ed1ae86aSJohn McCall       TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
1106ed1ae86aSJohn McCall     Builder.ClearInsertionPoint();
1107ed1ae86aSJohn McCall     return;
1108ed1ae86aSJohn McCall   }
1109ed1ae86aSJohn McCall 
1110ed1ae86aSJohn McCall   // If we can't resolve the destination cleanup scope, just add this
1111ed1ae86aSJohn McCall   // to the current cleanup scope as a branch fixup.
1112ed1ae86aSJohn McCall   if (!Dest.getScopeDepth().isValid()) {
1113ed1ae86aSJohn McCall     BranchFixup &Fixup = EHStack.addBranchFixup();
1114ed1ae86aSJohn McCall     Fixup.Destination = Dest.getBlock();
1115ed1ae86aSJohn McCall     Fixup.DestinationIndex = Dest.getDestIndex();
1116ed1ae86aSJohn McCall     Fixup.InitialBranch = BI;
11178a13c418SCraig Topper     Fixup.OptimisticBranchBlock = nullptr;
1118ed1ae86aSJohn McCall 
1119ed1ae86aSJohn McCall     Builder.ClearInsertionPoint();
1120ed1ae86aSJohn McCall     return;
1121ed1ae86aSJohn McCall   }
1122ed1ae86aSJohn McCall 
1123ed1ae86aSJohn McCall   // Otherwise, thread through all the normal cleanups in scope.
1124ed1ae86aSJohn McCall 
1125ed1ae86aSJohn McCall   // Store the index at the start.
1126ed1ae86aSJohn McCall   llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
11277f416cc4SJohn McCall   createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
1128ed1ae86aSJohn McCall 
1129ed1ae86aSJohn McCall   // Adjust BI to point to the first cleanup block.
1130ed1ae86aSJohn McCall   {
1131ed1ae86aSJohn McCall     EHCleanupScope &Scope =
1132ed1ae86aSJohn McCall       cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1133ed1ae86aSJohn McCall     BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1134ed1ae86aSJohn McCall   }
1135ed1ae86aSJohn McCall 
1136ed1ae86aSJohn McCall   // Add this destination to all the scopes involved.
1137ed1ae86aSJohn McCall   EHScopeStack::stable_iterator I = TopCleanup;
1138ed1ae86aSJohn McCall   EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1139ed1ae86aSJohn McCall   if (E.strictlyEncloses(I)) {
1140ed1ae86aSJohn McCall     while (true) {
1141ed1ae86aSJohn McCall       EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1142ed1ae86aSJohn McCall       assert(Scope.isNormalCleanup());
1143ed1ae86aSJohn McCall       I = Scope.getEnclosingNormalCleanup();
1144ed1ae86aSJohn McCall 
1145ed1ae86aSJohn McCall       // If this is the last cleanup we're propagating through, tell it
1146ed1ae86aSJohn McCall       // that there's a resolved jump moving through it.
1147ed1ae86aSJohn McCall       if (!E.strictlyEncloses(I)) {
1148ed1ae86aSJohn McCall         Scope.addBranchAfter(Index, Dest.getBlock());
1149ed1ae86aSJohn McCall         break;
1150ed1ae86aSJohn McCall       }
1151ed1ae86aSJohn McCall 
1152524ae44dSNico Weber       // Otherwise, tell the scope that there's a jump propagating
1153ed1ae86aSJohn McCall       // through it.  If this isn't new information, all the rest of
1154ed1ae86aSJohn McCall       // the work has been done before.
1155ed1ae86aSJohn McCall       if (!Scope.addBranchThrough(Dest.getBlock()))
1156ed1ae86aSJohn McCall         break;
1157ed1ae86aSJohn McCall     }
1158ed1ae86aSJohn McCall   }
1159ed1ae86aSJohn McCall 
1160ed1ae86aSJohn McCall   Builder.ClearInsertionPoint();
1161ed1ae86aSJohn McCall }
1162ed1ae86aSJohn McCall 
IsUsedAsNormalCleanup(EHScopeStack & EHStack,EHScopeStack::stable_iterator C)1163ed1ae86aSJohn McCall static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1164ed1ae86aSJohn McCall                                   EHScopeStack::stable_iterator C) {
1165ed1ae86aSJohn McCall   // If we needed a normal block for any reason, that counts.
1166ed1ae86aSJohn McCall   if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1167ed1ae86aSJohn McCall     return true;
1168ed1ae86aSJohn McCall 
1169ed1ae86aSJohn McCall   // Check whether any enclosed cleanups were needed.
1170ed1ae86aSJohn McCall   for (EHScopeStack::stable_iterator
1171ed1ae86aSJohn McCall          I = EHStack.getInnermostNormalCleanup();
1172ed1ae86aSJohn McCall          I != C; ) {
1173ed1ae86aSJohn McCall     assert(C.strictlyEncloses(I));
1174ed1ae86aSJohn McCall     EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1175ed1ae86aSJohn McCall     if (S.getNormalBlock()) return true;
1176ed1ae86aSJohn McCall     I = S.getEnclosingNormalCleanup();
1177ed1ae86aSJohn McCall   }
1178ed1ae86aSJohn McCall 
1179ed1ae86aSJohn McCall   return false;
1180ed1ae86aSJohn McCall }
1181ed1ae86aSJohn McCall 
IsUsedAsEHCleanup(EHScopeStack & EHStack,EHScopeStack::stable_iterator cleanup)1182ed1ae86aSJohn McCall static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
11838e4c74bbSJohn McCall                               EHScopeStack::stable_iterator cleanup) {
1184ed1ae86aSJohn McCall   // If we needed an EH block for any reason, that counts.
11858e4c74bbSJohn McCall   if (EHStack.find(cleanup)->hasEHBranches())
1186ed1ae86aSJohn McCall     return true;
1187ed1ae86aSJohn McCall 
1188ed1ae86aSJohn McCall   // Check whether any enclosed cleanups were needed.
1189ed1ae86aSJohn McCall   for (EHScopeStack::stable_iterator
11908e4c74bbSJohn McCall          i = EHStack.getInnermostEHScope(); i != cleanup; ) {
11918e4c74bbSJohn McCall     assert(cleanup.strictlyEncloses(i));
11928e4c74bbSJohn McCall 
11938e4c74bbSJohn McCall     EHScope &scope = *EHStack.find(i);
11948e4c74bbSJohn McCall     if (scope.hasEHBranches())
11958e4c74bbSJohn McCall       return true;
11968e4c74bbSJohn McCall 
11978e4c74bbSJohn McCall     i = scope.getEnclosingEHScope();
1198ed1ae86aSJohn McCall   }
1199ed1ae86aSJohn McCall 
1200ed1ae86aSJohn McCall   return false;
1201ed1ae86aSJohn McCall }
1202ed1ae86aSJohn McCall 
1203ed1ae86aSJohn McCall enum ForActivation_t {
1204ed1ae86aSJohn McCall   ForActivation,
1205ed1ae86aSJohn McCall   ForDeactivation
1206ed1ae86aSJohn McCall };
1207ed1ae86aSJohn McCall 
1208ed1ae86aSJohn McCall /// The given cleanup block is changing activation state.  Configure a
1209ed1ae86aSJohn McCall /// cleanup variable if necessary.
1210ed1ae86aSJohn McCall ///
1211ed1ae86aSJohn McCall /// It would be good if we had some way of determining if there were
1212ed1ae86aSJohn McCall /// extra uses *after* the change-over point.
SetupCleanupBlockActivation(CodeGenFunction & CGF,EHScopeStack::stable_iterator C,ForActivation_t kind,llvm::Instruction * dominatingIP)1213ed1ae86aSJohn McCall static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1214ed1ae86aSJohn McCall                                         EHScopeStack::stable_iterator C,
1215f4beacd0SJohn McCall                                         ForActivation_t kind,
1216f4beacd0SJohn McCall                                         llvm::Instruction *dominatingIP) {
1217ed1ae86aSJohn McCall   EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1218ed1ae86aSJohn McCall 
1219e63abb5dSJohn McCall   // We always need the flag if we're activating the cleanup in a
1220e63abb5dSJohn McCall   // conditional context, because we have to assume that the current
1221e63abb5dSJohn McCall   // location doesn't necessarily dominate the cleanup's code.
1222e63abb5dSJohn McCall   bool isActivatedInConditional =
1223f4beacd0SJohn McCall     (kind == ForActivation && CGF.isInConditionalBranch());
1224e63abb5dSJohn McCall 
1225e63abb5dSJohn McCall   bool needFlag = false;
1226ed1ae86aSJohn McCall 
1227ed1ae86aSJohn McCall   // Calculate whether the cleanup was used:
1228ed1ae86aSJohn McCall 
1229ed1ae86aSJohn McCall   //   - as a normal cleanup
1230e63abb5dSJohn McCall   if (Scope.isNormalCleanup() &&
1231e63abb5dSJohn McCall       (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
1232ed1ae86aSJohn McCall     Scope.setTestFlagInNormalCleanup();
1233e63abb5dSJohn McCall     needFlag = true;
1234ed1ae86aSJohn McCall   }
1235ed1ae86aSJohn McCall 
1236ed1ae86aSJohn McCall   //  - as an EH cleanup
1237e63abb5dSJohn McCall   if (Scope.isEHCleanup() &&
1238e63abb5dSJohn McCall       (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
1239ed1ae86aSJohn McCall     Scope.setTestFlagInEHCleanup();
1240e63abb5dSJohn McCall     needFlag = true;
1241ed1ae86aSJohn McCall   }
1242ed1ae86aSJohn McCall 
1243ed1ae86aSJohn McCall   // If it hasn't yet been used as either, we're done.
1244e63abb5dSJohn McCall   if (!needFlag) return;
1245ed1ae86aSJohn McCall 
12467f416cc4SJohn McCall   Address var = Scope.getActiveFlag();
12477f416cc4SJohn McCall   if (!var.isValid()) {
12487f416cc4SJohn McCall     var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
12497f416cc4SJohn McCall                                "cleanup.isactive");
1250f4beacd0SJohn McCall     Scope.setActiveFlag(var);
1251f4beacd0SJohn McCall 
1252f4beacd0SJohn McCall     assert(dominatingIP && "no existing variable and no dominating IP!");
1253ed1ae86aSJohn McCall 
1254ed1ae86aSJohn McCall     // Initialize to true or false depending on whether it was
1255ed1ae86aSJohn McCall     // active up to this point.
12567f416cc4SJohn McCall     llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
1257f4beacd0SJohn McCall 
1258f4beacd0SJohn McCall     // If we're in a conditional block, ignore the dominating IP and
1259f4beacd0SJohn McCall     // use the outermost conditional branch.
1260f4beacd0SJohn McCall     if (CGF.isInConditionalBranch()) {
1261f4beacd0SJohn McCall       CGF.setBeforeOutermostConditional(value, var);
1262f4beacd0SJohn McCall     } else {
12637f416cc4SJohn McCall       createStoreInstBefore(value, var, dominatingIP);
1264f4beacd0SJohn McCall     }
1265ed1ae86aSJohn McCall   }
1266ed1ae86aSJohn McCall 
1267f4beacd0SJohn McCall   CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
1268ed1ae86aSJohn McCall }
1269ed1ae86aSJohn McCall 
1270ed1ae86aSJohn McCall /// Activate a cleanup that was created in an inactivated state.
ActivateCleanupBlock(EHScopeStack::stable_iterator C,llvm::Instruction * dominatingIP)1271f4beacd0SJohn McCall void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1272f4beacd0SJohn McCall                                            llvm::Instruction *dominatingIP) {
1273ed1ae86aSJohn McCall   assert(C != EHStack.stable_end() && "activating bottom of stack?");
1274ed1ae86aSJohn McCall   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1275ed1ae86aSJohn McCall   assert(!Scope.isActive() && "double activation");
1276ed1ae86aSJohn McCall 
1277f4beacd0SJohn McCall   SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
1278ed1ae86aSJohn McCall 
1279ed1ae86aSJohn McCall   Scope.setActive(true);
1280ed1ae86aSJohn McCall }
1281ed1ae86aSJohn McCall 
1282ed1ae86aSJohn McCall /// Deactive a cleanup that was created in an active state.
DeactivateCleanupBlock(EHScopeStack::stable_iterator C,llvm::Instruction * dominatingIP)1283f4beacd0SJohn McCall void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1284f4beacd0SJohn McCall                                              llvm::Instruction *dominatingIP) {
1285ed1ae86aSJohn McCall   assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1286ed1ae86aSJohn McCall   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1287ed1ae86aSJohn McCall   assert(Scope.isActive() && "double deactivation");
1288ed1ae86aSJohn McCall 
1289ccda3d29SAkira Hatanaka   // If it's the top of the stack, just pop it, but do so only if it belongs
1290ccda3d29SAkira Hatanaka   // to the current RunCleanupsScope.
1291ccda3d29SAkira Hatanaka   if (C == EHStack.stable_begin() &&
1292ccda3d29SAkira Hatanaka       CurrentCleanupScopeDepth.strictlyEncloses(C)) {
1293797ad701STen Tzen     // Per comment below, checking EHAsynch is not really necessary
1294797ad701STen Tzen     // it's there to assure zero-impact w/o EHAsynch option
1295797ad701STen Tzen     if (!Scope.isNormalCleanup() && getLangOpts().EHAsynch) {
1296797ad701STen Tzen       PopCleanupBlock();
1297797ad701STen Tzen     } else {
1298ed1ae86aSJohn McCall       // If it's a normal cleanup, we need to pretend that the
1299ed1ae86aSJohn McCall       // fallthrough is unreachable.
1300ed1ae86aSJohn McCall       CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1301ed1ae86aSJohn McCall       PopCleanupBlock();
1302ed1ae86aSJohn McCall       Builder.restoreIP(SavedIP);
1303797ad701STen Tzen     }
1304ed1ae86aSJohn McCall     return;
1305ed1ae86aSJohn McCall   }
1306ed1ae86aSJohn McCall 
1307ed1ae86aSJohn McCall   // Otherwise, follow the general case.
1308f4beacd0SJohn McCall   SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
1309ed1ae86aSJohn McCall 
1310ed1ae86aSJohn McCall   Scope.setActive(false);
1311ed1ae86aSJohn McCall }
1312ed1ae86aSJohn McCall 
getNormalCleanupDestSlot()13137f416cc4SJohn McCall Address CodeGenFunction::getNormalCleanupDestSlot() {
13145cdf0383SJohn McCall   if (!NormalCleanupDest.isValid())
1315ed1ae86aSJohn McCall     NormalCleanupDest =
13165cdf0383SJohn McCall       CreateDefaultAlignTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
13175cdf0383SJohn McCall   return NormalCleanupDest;
1318ed1ae86aSJohn McCall }
1319702b2841SPeter Collingbourne 
1320702b2841SPeter Collingbourne /// Emits all the code to cause the given temporary to be cleaned up.
EmitCXXTemporary(const CXXTemporary * Temporary,QualType TempType,Address Ptr)1321702b2841SPeter Collingbourne void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1322702b2841SPeter Collingbourne                                        QualType TempType,
13237f416cc4SJohn McCall                                        Address Ptr) {
13241425b455SPeter Collingbourne   pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
1325702b2841SPeter Collingbourne               /*useEHCleanup*/ true);
1326702b2841SPeter Collingbourne }
1327797ad701STen Tzen 
1328797ad701STen Tzen // Need to set "funclet" in OperandBundle properly for noThrow
1329797ad701STen Tzen //       intrinsic (see CGCall.cpp)
EmitSehScope(CodeGenFunction & CGF,llvm::FunctionCallee & SehCppScope)1330797ad701STen Tzen static void EmitSehScope(CodeGenFunction &CGF,
1331797ad701STen Tzen                          llvm::FunctionCallee &SehCppScope) {
1332797ad701STen Tzen   llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
13333f3642a7SBenjamin Kramer   assert(CGF.Builder.GetInsertBlock() && InvokeDest);
1334797ad701STen Tzen   llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
1335797ad701STen Tzen   SmallVector<llvm::OperandBundleDef, 1> BundleList =
1336797ad701STen Tzen       CGF.getBundlesForFunclet(SehCppScope.getCallee());
1337797ad701STen Tzen   if (CGF.CurrentFuncletPad)
1338797ad701STen Tzen     BundleList.emplace_back("funclet", CGF.CurrentFuncletPad);
1339797ad701STen Tzen   CGF.Builder.CreateInvoke(SehCppScope, Cont, InvokeDest, None, BundleList);
1340797ad701STen Tzen   CGF.EmitBlock(Cont);
1341797ad701STen Tzen }
1342797ad701STen Tzen 
1343797ad701STen Tzen // Invoke a llvm.seh.scope.begin at the beginning of a CPP scope for -EHa
EmitSehCppScopeBegin()1344797ad701STen Tzen void CodeGenFunction::EmitSehCppScopeBegin() {
1345797ad701STen Tzen   assert(getLangOpts().EHAsynch);
1346797ad701STen Tzen   llvm::FunctionType *FTy =
1347797ad701STen Tzen       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1348797ad701STen Tzen   llvm::FunctionCallee SehCppScope =
1349797ad701STen Tzen       CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.begin");
1350797ad701STen Tzen   EmitSehScope(*this, SehCppScope);
1351797ad701STen Tzen }
1352797ad701STen Tzen 
1353797ad701STen Tzen // Invoke a llvm.seh.scope.end at the end of a CPP scope for -EHa
1354797ad701STen Tzen //   llvm.seh.scope.end is emitted before popCleanup, so it's "invoked"
EmitSehCppScopeEnd()1355797ad701STen Tzen void CodeGenFunction::EmitSehCppScopeEnd() {
1356797ad701STen Tzen   assert(getLangOpts().EHAsynch);
1357797ad701STen Tzen   llvm::FunctionType *FTy =
1358797ad701STen Tzen       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1359797ad701STen Tzen   llvm::FunctionCallee SehCppScope =
1360797ad701STen Tzen       CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.end");
1361797ad701STen Tzen   EmitSehScope(*this, SehCppScope);
1362797ad701STen Tzen }
1363797ad701STen Tzen 
1364797ad701STen Tzen // Invoke a llvm.seh.try.begin at the beginning of a SEH scope for -EHa
EmitSehTryScopeBegin()1365797ad701STen Tzen void CodeGenFunction::EmitSehTryScopeBegin() {
1366797ad701STen Tzen   assert(getLangOpts().EHAsynch);
1367797ad701STen Tzen   llvm::FunctionType *FTy =
1368797ad701STen Tzen       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1369797ad701STen Tzen   llvm::FunctionCallee SehCppScope =
1370797ad701STen Tzen       CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.begin");
1371797ad701STen Tzen   EmitSehScope(*this, SehCppScope);
1372797ad701STen Tzen }
1373797ad701STen Tzen 
1374797ad701STen Tzen // Invoke a llvm.seh.try.end at the end of a SEH scope for -EHa
EmitSehTryScopeEnd()1375797ad701STen Tzen void CodeGenFunction::EmitSehTryScopeEnd() {
1376797ad701STen Tzen   assert(getLangOpts().EHAsynch);
1377797ad701STen Tzen   llvm::FunctionType *FTy =
1378797ad701STen Tzen       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1379797ad701STen Tzen   llvm::FunctionCallee SehCppScope =
1380797ad701STen Tzen       CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.end");
1381797ad701STen Tzen   EmitSehScope(*this, SehCppScope);
1382797ad701STen Tzen }
1383