xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/CodeGen/CGCleanup.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file contains code dealing with the IR generation for cleanups
107330f729Sjoerg // and related information.
117330f729Sjoerg //
127330f729Sjoerg // A "cleanup" is a piece of code which needs to be executed whenever
137330f729Sjoerg // control transfers out of a particular scope.  This can be
147330f729Sjoerg // conditionalized to occur only on exceptional control flow, only on
157330f729Sjoerg // normal control flow, or both.
167330f729Sjoerg //
177330f729Sjoerg //===----------------------------------------------------------------------===//
187330f729Sjoerg 
197330f729Sjoerg #include "CGCleanup.h"
207330f729Sjoerg #include "CodeGenFunction.h"
217330f729Sjoerg #include "llvm/Support/SaveAndRestore.h"
227330f729Sjoerg 
237330f729Sjoerg using namespace clang;
247330f729Sjoerg using namespace CodeGen;
257330f729Sjoerg 
needsSaving(RValue rv)267330f729Sjoerg bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
277330f729Sjoerg   if (rv.isScalar())
287330f729Sjoerg     return DominatingLLVMValue::needsSaving(rv.getScalarVal());
297330f729Sjoerg   if (rv.isAggregate())
307330f729Sjoerg     return DominatingLLVMValue::needsSaving(rv.getAggregatePointer());
317330f729Sjoerg   return true;
327330f729Sjoerg }
337330f729Sjoerg 
347330f729Sjoerg DominatingValue<RValue>::saved_type
save(CodeGenFunction & CGF,RValue rv)357330f729Sjoerg DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
367330f729Sjoerg   if (rv.isScalar()) {
377330f729Sjoerg     llvm::Value *V = rv.getScalarVal();
387330f729Sjoerg 
397330f729Sjoerg     // These automatically dominate and don't need to be saved.
407330f729Sjoerg     if (!DominatingLLVMValue::needsSaving(V))
417330f729Sjoerg       return saved_type(V, ScalarLiteral);
427330f729Sjoerg 
437330f729Sjoerg     // Everything else needs an alloca.
447330f729Sjoerg     Address addr =
457330f729Sjoerg       CGF.CreateDefaultAlignTempAlloca(V->getType(), "saved-rvalue");
467330f729Sjoerg     CGF.Builder.CreateStore(V, addr);
477330f729Sjoerg     return saved_type(addr.getPointer(), ScalarAddress);
487330f729Sjoerg   }
497330f729Sjoerg 
507330f729Sjoerg   if (rv.isComplex()) {
517330f729Sjoerg     CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
527330f729Sjoerg     llvm::Type *ComplexTy =
537330f729Sjoerg         llvm::StructType::get(V.first->getType(), V.second->getType());
547330f729Sjoerg     Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex");
557330f729Sjoerg     CGF.Builder.CreateStore(V.first, CGF.Builder.CreateStructGEP(addr, 0));
567330f729Sjoerg     CGF.Builder.CreateStore(V.second, CGF.Builder.CreateStructGEP(addr, 1));
577330f729Sjoerg     return saved_type(addr.getPointer(), ComplexAddress);
587330f729Sjoerg   }
597330f729Sjoerg 
607330f729Sjoerg   assert(rv.isAggregate());
617330f729Sjoerg   Address V = rv.getAggregateAddress(); // TODO: volatile?
627330f729Sjoerg   if (!DominatingLLVMValue::needsSaving(V.getPointer()))
637330f729Sjoerg     return saved_type(V.getPointer(), AggregateLiteral,
647330f729Sjoerg                       V.getAlignment().getQuantity());
657330f729Sjoerg 
667330f729Sjoerg   Address addr =
677330f729Sjoerg     CGF.CreateTempAlloca(V.getType(), CGF.getPointerAlign(), "saved-rvalue");
687330f729Sjoerg   CGF.Builder.CreateStore(V.getPointer(), addr);
697330f729Sjoerg   return saved_type(addr.getPointer(), AggregateAddress,
707330f729Sjoerg                     V.getAlignment().getQuantity());
717330f729Sjoerg }
727330f729Sjoerg 
737330f729Sjoerg /// Given a saved r-value produced by SaveRValue, perform the code
747330f729Sjoerg /// necessary to restore it to usability at the current insertion
757330f729Sjoerg /// point.
restore(CodeGenFunction & CGF)767330f729Sjoerg RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
777330f729Sjoerg   auto getSavingAddress = [&](llvm::Value *value) {
787330f729Sjoerg     auto alignment = cast<llvm::AllocaInst>(value)->getAlignment();
797330f729Sjoerg     return Address(value, CharUnits::fromQuantity(alignment));
807330f729Sjoerg   };
817330f729Sjoerg   switch (K) {
827330f729Sjoerg   case ScalarLiteral:
837330f729Sjoerg     return RValue::get(Value);
847330f729Sjoerg   case ScalarAddress:
857330f729Sjoerg     return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
867330f729Sjoerg   case AggregateLiteral:
877330f729Sjoerg     return RValue::getAggregate(Address(Value, CharUnits::fromQuantity(Align)));
887330f729Sjoerg   case AggregateAddress: {
897330f729Sjoerg     auto addr = CGF.Builder.CreateLoad(getSavingAddress(Value));
907330f729Sjoerg     return RValue::getAggregate(Address(addr, CharUnits::fromQuantity(Align)));
917330f729Sjoerg   }
927330f729Sjoerg   case ComplexAddress: {
937330f729Sjoerg     Address address = getSavingAddress(Value);
947330f729Sjoerg     llvm::Value *real =
957330f729Sjoerg         CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 0));
967330f729Sjoerg     llvm::Value *imag =
977330f729Sjoerg         CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 1));
987330f729Sjoerg     return RValue::getComplex(real, imag);
997330f729Sjoerg   }
1007330f729Sjoerg   }
1017330f729Sjoerg 
1027330f729Sjoerg   llvm_unreachable("bad saved r-value kind");
1037330f729Sjoerg }
1047330f729Sjoerg 
1057330f729Sjoerg /// Push an entry of the given size onto this protected-scope stack.
allocate(size_t Size)1067330f729Sjoerg char *EHScopeStack::allocate(size_t Size) {
1077330f729Sjoerg   Size = llvm::alignTo(Size, ScopeStackAlignment);
1087330f729Sjoerg   if (!StartOfBuffer) {
1097330f729Sjoerg     unsigned Capacity = 1024;
1107330f729Sjoerg     while (Capacity < Size) Capacity *= 2;
1117330f729Sjoerg     StartOfBuffer = new char[Capacity];
1127330f729Sjoerg     StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
1137330f729Sjoerg   } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
1147330f729Sjoerg     unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
1157330f729Sjoerg     unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
1167330f729Sjoerg 
1177330f729Sjoerg     unsigned NewCapacity = CurrentCapacity;
1187330f729Sjoerg     do {
1197330f729Sjoerg       NewCapacity *= 2;
1207330f729Sjoerg     } while (NewCapacity < UsedCapacity + Size);
1217330f729Sjoerg 
1227330f729Sjoerg     char *NewStartOfBuffer = new char[NewCapacity];
1237330f729Sjoerg     char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
1247330f729Sjoerg     char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
1257330f729Sjoerg     memcpy(NewStartOfData, StartOfData, UsedCapacity);
1267330f729Sjoerg     delete [] StartOfBuffer;
1277330f729Sjoerg     StartOfBuffer = NewStartOfBuffer;
1287330f729Sjoerg     EndOfBuffer = NewEndOfBuffer;
1297330f729Sjoerg     StartOfData = NewStartOfData;
1307330f729Sjoerg   }
1317330f729Sjoerg 
1327330f729Sjoerg   assert(StartOfBuffer + Size <= StartOfData);
1337330f729Sjoerg   StartOfData -= Size;
1347330f729Sjoerg   return StartOfData;
1357330f729Sjoerg }
1367330f729Sjoerg 
deallocate(size_t Size)1377330f729Sjoerg void EHScopeStack::deallocate(size_t Size) {
1387330f729Sjoerg   StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
1397330f729Sjoerg }
1407330f729Sjoerg 
containsOnlyLifetimeMarkers(EHScopeStack::stable_iterator Old) const1417330f729Sjoerg bool EHScopeStack::containsOnlyLifetimeMarkers(
1427330f729Sjoerg     EHScopeStack::stable_iterator Old) const {
1437330f729Sjoerg   for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {
1447330f729Sjoerg     EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
1457330f729Sjoerg     if (!cleanup || !cleanup->isLifetimeMarker())
1467330f729Sjoerg       return false;
1477330f729Sjoerg   }
1487330f729Sjoerg 
1497330f729Sjoerg   return true;
1507330f729Sjoerg }
1517330f729Sjoerg 
requiresLandingPad() const1527330f729Sjoerg bool EHScopeStack::requiresLandingPad() const {
1537330f729Sjoerg   for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {
1547330f729Sjoerg     // Skip lifetime markers.
1557330f729Sjoerg     if (auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si)))
1567330f729Sjoerg       if (cleanup->isLifetimeMarker()) {
1577330f729Sjoerg         si = cleanup->getEnclosingEHScope();
1587330f729Sjoerg         continue;
1597330f729Sjoerg       }
1607330f729Sjoerg     return true;
1617330f729Sjoerg   }
1627330f729Sjoerg 
1637330f729Sjoerg   return false;
1647330f729Sjoerg }
1657330f729Sjoerg 
1667330f729Sjoerg EHScopeStack::stable_iterator
getInnermostActiveNormalCleanup() const1677330f729Sjoerg EHScopeStack::getInnermostActiveNormalCleanup() const {
1687330f729Sjoerg   for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
1697330f729Sjoerg          si != se; ) {
1707330f729Sjoerg     EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
1717330f729Sjoerg     if (cleanup.isActive()) return si;
1727330f729Sjoerg     si = cleanup.getEnclosingNormalCleanup();
1737330f729Sjoerg   }
1747330f729Sjoerg   return stable_end();
1757330f729Sjoerg }
1767330f729Sjoerg 
1777330f729Sjoerg 
pushCleanup(CleanupKind Kind,size_t Size)1787330f729Sjoerg void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
1797330f729Sjoerg   char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
1807330f729Sjoerg   bool IsNormalCleanup = Kind & NormalCleanup;
1817330f729Sjoerg   bool IsEHCleanup = Kind & EHCleanup;
1827330f729Sjoerg   bool IsLifetimeMarker = Kind & LifetimeMarker;
1837330f729Sjoerg   EHCleanupScope *Scope =
1847330f729Sjoerg     new (Buffer) EHCleanupScope(IsNormalCleanup,
1857330f729Sjoerg                                 IsEHCleanup,
1867330f729Sjoerg                                 Size,
1877330f729Sjoerg                                 BranchFixups.size(),
1887330f729Sjoerg                                 InnermostNormalCleanup,
1897330f729Sjoerg                                 InnermostEHScope);
1907330f729Sjoerg   if (IsNormalCleanup)
1917330f729Sjoerg     InnermostNormalCleanup = stable_begin();
1927330f729Sjoerg   if (IsEHCleanup)
1937330f729Sjoerg     InnermostEHScope = stable_begin();
1947330f729Sjoerg   if (IsLifetimeMarker)
1957330f729Sjoerg     Scope->setLifetimeMarker();
1967330f729Sjoerg 
197*e038c9c4Sjoerg   // With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup
198*e038c9c4Sjoerg   if (CGF->getLangOpts().EHAsynch && IsEHCleanup &&
199*e038c9c4Sjoerg       CGF->getTarget().getCXXABI().isMicrosoft())
200*e038c9c4Sjoerg     CGF->EmitSehCppScopeBegin();
201*e038c9c4Sjoerg 
2027330f729Sjoerg   return Scope->getCleanupBuffer();
2037330f729Sjoerg }
2047330f729Sjoerg 
popCleanup()2057330f729Sjoerg void EHScopeStack::popCleanup() {
2067330f729Sjoerg   assert(!empty() && "popping exception stack when not empty");
2077330f729Sjoerg 
2087330f729Sjoerg   assert(isa<EHCleanupScope>(*begin()));
2097330f729Sjoerg   EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
2107330f729Sjoerg   InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
2117330f729Sjoerg   InnermostEHScope = Cleanup.getEnclosingEHScope();
2127330f729Sjoerg   deallocate(Cleanup.getAllocatedSize());
2137330f729Sjoerg 
2147330f729Sjoerg   // Destroy the cleanup.
2157330f729Sjoerg   Cleanup.Destroy();
2167330f729Sjoerg 
2177330f729Sjoerg   // Check whether we can shrink the branch-fixups stack.
2187330f729Sjoerg   if (!BranchFixups.empty()) {
2197330f729Sjoerg     // If we no longer have any normal cleanups, all the fixups are
2207330f729Sjoerg     // complete.
2217330f729Sjoerg     if (!hasNormalCleanups())
2227330f729Sjoerg       BranchFixups.clear();
2237330f729Sjoerg 
2247330f729Sjoerg     // Otherwise we can still trim out unnecessary nulls.
2257330f729Sjoerg     else
2267330f729Sjoerg       popNullFixups();
2277330f729Sjoerg   }
2287330f729Sjoerg }
2297330f729Sjoerg 
pushFilter(unsigned numFilters)2307330f729Sjoerg EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
2317330f729Sjoerg   assert(getInnermostEHScope() == stable_end());
2327330f729Sjoerg   char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
2337330f729Sjoerg   EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
2347330f729Sjoerg   InnermostEHScope = stable_begin();
2357330f729Sjoerg   return filter;
2367330f729Sjoerg }
2377330f729Sjoerg 
popFilter()2387330f729Sjoerg void EHScopeStack::popFilter() {
2397330f729Sjoerg   assert(!empty() && "popping exception stack when not empty");
2407330f729Sjoerg 
2417330f729Sjoerg   EHFilterScope &filter = cast<EHFilterScope>(*begin());
2427330f729Sjoerg   deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
2437330f729Sjoerg 
2447330f729Sjoerg   InnermostEHScope = filter.getEnclosingEHScope();
2457330f729Sjoerg }
2467330f729Sjoerg 
pushCatch(unsigned numHandlers)2477330f729Sjoerg EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
2487330f729Sjoerg   char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
2497330f729Sjoerg   EHCatchScope *scope =
2507330f729Sjoerg     new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
2517330f729Sjoerg   InnermostEHScope = stable_begin();
2527330f729Sjoerg   return scope;
2537330f729Sjoerg }
2547330f729Sjoerg 
pushTerminate()2557330f729Sjoerg void EHScopeStack::pushTerminate() {
2567330f729Sjoerg   char *Buffer = allocate(EHTerminateScope::getSize());
2577330f729Sjoerg   new (Buffer) EHTerminateScope(InnermostEHScope);
2587330f729Sjoerg   InnermostEHScope = stable_begin();
2597330f729Sjoerg }
2607330f729Sjoerg 
2617330f729Sjoerg /// Remove any 'null' fixups on the stack.  However, we can't pop more
2627330f729Sjoerg /// fixups than the fixup depth on the innermost normal cleanup, or
2637330f729Sjoerg /// else fixups that we try to add to that cleanup will end up in the
2647330f729Sjoerg /// wrong place.  We *could* try to shrink fixup depths, but that's
2657330f729Sjoerg /// actually a lot of work for little benefit.
popNullFixups()2667330f729Sjoerg void EHScopeStack::popNullFixups() {
2677330f729Sjoerg   // We expect this to only be called when there's still an innermost
2687330f729Sjoerg   // normal cleanup;  otherwise there really shouldn't be any fixups.
2697330f729Sjoerg   assert(hasNormalCleanups());
2707330f729Sjoerg 
2717330f729Sjoerg   EHScopeStack::iterator it = find(InnermostNormalCleanup);
2727330f729Sjoerg   unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
2737330f729Sjoerg   assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
2747330f729Sjoerg 
2757330f729Sjoerg   while (BranchFixups.size() > MinSize &&
2767330f729Sjoerg          BranchFixups.back().Destination == nullptr)
2777330f729Sjoerg     BranchFixups.pop_back();
2787330f729Sjoerg }
2797330f729Sjoerg 
createCleanupActiveFlag()2807330f729Sjoerg Address CodeGenFunction::createCleanupActiveFlag() {
2817330f729Sjoerg   // Create a variable to decide whether the cleanup needs to be run.
2827330f729Sjoerg   Address active = CreateTempAllocaWithoutCast(
2837330f729Sjoerg       Builder.getInt1Ty(), CharUnits::One(), "cleanup.cond");
2847330f729Sjoerg 
2857330f729Sjoerg   // Initialize it to false at a site that's guaranteed to be run
2867330f729Sjoerg   // before each evaluation.
2877330f729Sjoerg   setBeforeOutermostConditional(Builder.getFalse(), active);
2887330f729Sjoerg 
2897330f729Sjoerg   // Initialize it to true at the current location.
2907330f729Sjoerg   Builder.CreateStore(Builder.getTrue(), active);
2917330f729Sjoerg 
2927330f729Sjoerg   return active;
2937330f729Sjoerg }
2947330f729Sjoerg 
initFullExprCleanupWithFlag(Address ActiveFlag)2957330f729Sjoerg void CodeGenFunction::initFullExprCleanupWithFlag(Address ActiveFlag) {
2967330f729Sjoerg   // Set that as the active flag in the cleanup.
2977330f729Sjoerg   EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
2987330f729Sjoerg   assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
2997330f729Sjoerg   cleanup.setActiveFlag(ActiveFlag);
3007330f729Sjoerg 
3017330f729Sjoerg   if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
3027330f729Sjoerg   if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
3037330f729Sjoerg }
3047330f729Sjoerg 
anchor()3057330f729Sjoerg void EHScopeStack::Cleanup::anchor() {}
3067330f729Sjoerg 
createStoreInstBefore(llvm::Value * value,Address addr,llvm::Instruction * beforeInst)3077330f729Sjoerg static void createStoreInstBefore(llvm::Value *value, Address addr,
3087330f729Sjoerg                                   llvm::Instruction *beforeInst) {
3097330f729Sjoerg   auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
3107330f729Sjoerg   store->setAlignment(addr.getAlignment().getAsAlign());
3117330f729Sjoerg }
3127330f729Sjoerg 
createLoadInstBefore(Address addr,const Twine & name,llvm::Instruction * beforeInst)3137330f729Sjoerg static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
3147330f729Sjoerg                                             llvm::Instruction *beforeInst) {
315*e038c9c4Sjoerg   return new llvm::LoadInst(addr.getElementType(), addr.getPointer(), name,
316*e038c9c4Sjoerg                             false, addr.getAlignment().getAsAlign(),
317*e038c9c4Sjoerg                             beforeInst);
3187330f729Sjoerg }
3197330f729Sjoerg 
3207330f729Sjoerg /// All the branch fixups on the EH stack have propagated out past the
3217330f729Sjoerg /// outermost normal cleanup; resolve them all by adding cases to the
3227330f729Sjoerg /// given switch instruction.
ResolveAllBranchFixups(CodeGenFunction & CGF,llvm::SwitchInst * Switch,llvm::BasicBlock * CleanupEntry)3237330f729Sjoerg static void ResolveAllBranchFixups(CodeGenFunction &CGF,
3247330f729Sjoerg                                    llvm::SwitchInst *Switch,
3257330f729Sjoerg                                    llvm::BasicBlock *CleanupEntry) {
3267330f729Sjoerg   llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
3277330f729Sjoerg 
3287330f729Sjoerg   for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
3297330f729Sjoerg     // Skip this fixup if its destination isn't set.
3307330f729Sjoerg     BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
3317330f729Sjoerg     if (Fixup.Destination == nullptr) continue;
3327330f729Sjoerg 
3337330f729Sjoerg     // If there isn't an OptimisticBranchBlock, then InitialBranch is
3347330f729Sjoerg     // still pointing directly to its destination; forward it to the
3357330f729Sjoerg     // appropriate cleanup entry.  This is required in the specific
3367330f729Sjoerg     // case of
3377330f729Sjoerg     //   { std::string s; goto lbl; }
3387330f729Sjoerg     //   lbl:
3397330f729Sjoerg     // i.e. where there's an unresolved fixup inside a single cleanup
3407330f729Sjoerg     // entry which we're currently popping.
3417330f729Sjoerg     if (Fixup.OptimisticBranchBlock == nullptr) {
3427330f729Sjoerg       createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
3437330f729Sjoerg                             CGF.getNormalCleanupDestSlot(),
3447330f729Sjoerg                             Fixup.InitialBranch);
3457330f729Sjoerg       Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
3467330f729Sjoerg     }
3477330f729Sjoerg 
3487330f729Sjoerg     // Don't add this case to the switch statement twice.
3497330f729Sjoerg     if (!CasesAdded.insert(Fixup.Destination).second)
3507330f729Sjoerg       continue;
3517330f729Sjoerg 
3527330f729Sjoerg     Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
3537330f729Sjoerg                     Fixup.Destination);
3547330f729Sjoerg   }
3557330f729Sjoerg 
3567330f729Sjoerg   CGF.EHStack.clearFixups();
3577330f729Sjoerg }
3587330f729Sjoerg 
3597330f729Sjoerg /// Transitions the terminator of the given exit-block of a cleanup to
3607330f729Sjoerg /// be a cleanup switch.
TransitionToCleanupSwitch(CodeGenFunction & CGF,llvm::BasicBlock * Block)3617330f729Sjoerg static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
3627330f729Sjoerg                                                    llvm::BasicBlock *Block) {
3637330f729Sjoerg   // If it's a branch, turn it into a switch whose default
3647330f729Sjoerg   // destination is its original target.
3657330f729Sjoerg   llvm::Instruction *Term = Block->getTerminator();
3667330f729Sjoerg   assert(Term && "can't transition block without terminator");
3677330f729Sjoerg 
3687330f729Sjoerg   if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
3697330f729Sjoerg     assert(Br->isUnconditional());
3707330f729Sjoerg     auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
3717330f729Sjoerg                                      "cleanup.dest", Term);
3727330f729Sjoerg     llvm::SwitchInst *Switch =
3737330f729Sjoerg       llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
3747330f729Sjoerg     Br->eraseFromParent();
3757330f729Sjoerg     return Switch;
3767330f729Sjoerg   } else {
3777330f729Sjoerg     return cast<llvm::SwitchInst>(Term);
3787330f729Sjoerg   }
3797330f729Sjoerg }
3807330f729Sjoerg 
ResolveBranchFixups(llvm::BasicBlock * Block)3817330f729Sjoerg void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
3827330f729Sjoerg   assert(Block && "resolving a null target block");
3837330f729Sjoerg   if (!EHStack.getNumBranchFixups()) return;
3847330f729Sjoerg 
3857330f729Sjoerg   assert(EHStack.hasNormalCleanups() &&
3867330f729Sjoerg          "branch fixups exist with no normal cleanups on stack");
3877330f729Sjoerg 
3887330f729Sjoerg   llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
3897330f729Sjoerg   bool ResolvedAny = false;
3907330f729Sjoerg 
3917330f729Sjoerg   for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
3927330f729Sjoerg     // Skip this fixup if its destination doesn't match.
3937330f729Sjoerg     BranchFixup &Fixup = EHStack.getBranchFixup(I);
3947330f729Sjoerg     if (Fixup.Destination != Block) continue;
3957330f729Sjoerg 
3967330f729Sjoerg     Fixup.Destination = nullptr;
3977330f729Sjoerg     ResolvedAny = true;
3987330f729Sjoerg 
3997330f729Sjoerg     // If it doesn't have an optimistic branch block, LatestBranch is
4007330f729Sjoerg     // already pointing to the right place.
4017330f729Sjoerg     llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
4027330f729Sjoerg     if (!BranchBB)
4037330f729Sjoerg       continue;
4047330f729Sjoerg 
4057330f729Sjoerg     // Don't process the same optimistic branch block twice.
4067330f729Sjoerg     if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
4077330f729Sjoerg       continue;
4087330f729Sjoerg 
4097330f729Sjoerg     llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
4107330f729Sjoerg 
4117330f729Sjoerg     // Add a case to the switch.
4127330f729Sjoerg     Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
4137330f729Sjoerg   }
4147330f729Sjoerg 
4157330f729Sjoerg   if (ResolvedAny)
4167330f729Sjoerg     EHStack.popNullFixups();
4177330f729Sjoerg }
4187330f729Sjoerg 
4197330f729Sjoerg /// Pops cleanup blocks until the given savepoint is reached.
PopCleanupBlocks(EHScopeStack::stable_iterator Old,std::initializer_list<llvm::Value ** > ValuesToReload)4207330f729Sjoerg void CodeGenFunction::PopCleanupBlocks(
4217330f729Sjoerg     EHScopeStack::stable_iterator Old,
4227330f729Sjoerg     std::initializer_list<llvm::Value **> ValuesToReload) {
4237330f729Sjoerg   assert(Old.isValid());
4247330f729Sjoerg 
4257330f729Sjoerg   bool HadBranches = false;
4267330f729Sjoerg   while (EHStack.stable_begin() != Old) {
4277330f729Sjoerg     EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
4287330f729Sjoerg     HadBranches |= Scope.hasBranches();
4297330f729Sjoerg 
4307330f729Sjoerg     // As long as Old strictly encloses the scope's enclosing normal
4317330f729Sjoerg     // cleanup, we're going to emit another normal cleanup which
4327330f729Sjoerg     // fallthrough can propagate through.
4337330f729Sjoerg     bool FallThroughIsBranchThrough =
4347330f729Sjoerg       Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
4357330f729Sjoerg 
4367330f729Sjoerg     PopCleanupBlock(FallThroughIsBranchThrough);
4377330f729Sjoerg   }
4387330f729Sjoerg 
4397330f729Sjoerg   // If we didn't have any branches, the insertion point before cleanups must
4407330f729Sjoerg   // dominate the current insertion point and we don't need to reload any
4417330f729Sjoerg   // values.
4427330f729Sjoerg   if (!HadBranches)
4437330f729Sjoerg     return;
4447330f729Sjoerg 
4457330f729Sjoerg   // Spill and reload all values that the caller wants to be live at the current
4467330f729Sjoerg   // insertion point.
4477330f729Sjoerg   for (llvm::Value **ReloadedValue : ValuesToReload) {
4487330f729Sjoerg     auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
4497330f729Sjoerg     if (!Inst)
4507330f729Sjoerg       continue;
4517330f729Sjoerg 
4527330f729Sjoerg     // Don't spill static allocas, they dominate all cleanups. These are created
4537330f729Sjoerg     // by binding a reference to a local variable or temporary.
4547330f729Sjoerg     auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
4557330f729Sjoerg     if (AI && AI->isStaticAlloca())
4567330f729Sjoerg       continue;
4577330f729Sjoerg 
4587330f729Sjoerg     Address Tmp =
4597330f729Sjoerg         CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
4607330f729Sjoerg 
4617330f729Sjoerg     // Find an insertion point after Inst and spill it to the temporary.
4627330f729Sjoerg     llvm::BasicBlock::iterator InsertBefore;
4637330f729Sjoerg     if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
4647330f729Sjoerg       InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
4657330f729Sjoerg     else
4667330f729Sjoerg       InsertBefore = std::next(Inst->getIterator());
4677330f729Sjoerg     CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
4687330f729Sjoerg 
4697330f729Sjoerg     // Reload the value at the current insertion point.
4707330f729Sjoerg     *ReloadedValue = Builder.CreateLoad(Tmp);
4717330f729Sjoerg   }
4727330f729Sjoerg }
4737330f729Sjoerg 
4747330f729Sjoerg /// Pops cleanup blocks until the given savepoint is reached, then add the
4757330f729Sjoerg /// 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)4767330f729Sjoerg void CodeGenFunction::PopCleanupBlocks(
4777330f729Sjoerg     EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
4787330f729Sjoerg     std::initializer_list<llvm::Value **> ValuesToReload) {
4797330f729Sjoerg   PopCleanupBlocks(Old, ValuesToReload);
4807330f729Sjoerg 
4817330f729Sjoerg   // Move our deferred cleanups onto the EH stack.
4827330f729Sjoerg   for (size_t I = OldLifetimeExtendedSize,
4837330f729Sjoerg               E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
4847330f729Sjoerg     // Alignment should be guaranteed by the vptrs in the individual cleanups.
4857330f729Sjoerg     assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
4867330f729Sjoerg            "misaligned cleanup stack entry");
4877330f729Sjoerg 
4887330f729Sjoerg     LifetimeExtendedCleanupHeader &Header =
4897330f729Sjoerg         reinterpret_cast<LifetimeExtendedCleanupHeader&>(
4907330f729Sjoerg             LifetimeExtendedCleanupStack[I]);
4917330f729Sjoerg     I += sizeof(Header);
4927330f729Sjoerg 
4937330f729Sjoerg     EHStack.pushCopyOfCleanup(Header.getKind(),
4947330f729Sjoerg                               &LifetimeExtendedCleanupStack[I],
4957330f729Sjoerg                               Header.getSize());
4967330f729Sjoerg     I += Header.getSize();
4977330f729Sjoerg 
4987330f729Sjoerg     if (Header.isConditional()) {
4997330f729Sjoerg       Address ActiveFlag =
5007330f729Sjoerg           reinterpret_cast<Address &>(LifetimeExtendedCleanupStack[I]);
5017330f729Sjoerg       initFullExprCleanupWithFlag(ActiveFlag);
5027330f729Sjoerg       I += sizeof(ActiveFlag);
5037330f729Sjoerg     }
5047330f729Sjoerg   }
5057330f729Sjoerg   LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
5067330f729Sjoerg }
5077330f729Sjoerg 
CreateNormalEntry(CodeGenFunction & CGF,EHCleanupScope & Scope)5087330f729Sjoerg static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
5097330f729Sjoerg                                            EHCleanupScope &Scope) {
5107330f729Sjoerg   assert(Scope.isNormalCleanup());
5117330f729Sjoerg   llvm::BasicBlock *Entry = Scope.getNormalBlock();
5127330f729Sjoerg   if (!Entry) {
5137330f729Sjoerg     Entry = CGF.createBasicBlock("cleanup");
5147330f729Sjoerg     Scope.setNormalBlock(Entry);
5157330f729Sjoerg   }
5167330f729Sjoerg   return Entry;
5177330f729Sjoerg }
5187330f729Sjoerg 
5197330f729Sjoerg /// Attempts to reduce a cleanup's entry block to a fallthrough.  This
5207330f729Sjoerg /// is basically llvm::MergeBlockIntoPredecessor, except
5217330f729Sjoerg /// simplified/optimized for the tighter constraints on cleanup blocks.
5227330f729Sjoerg ///
5237330f729Sjoerg /// Returns the new block, whatever it is.
SimplifyCleanupEntry(CodeGenFunction & CGF,llvm::BasicBlock * Entry)5247330f729Sjoerg static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
5257330f729Sjoerg                                               llvm::BasicBlock *Entry) {
5267330f729Sjoerg   llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
5277330f729Sjoerg   if (!Pred) return Entry;
5287330f729Sjoerg 
5297330f729Sjoerg   llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
5307330f729Sjoerg   if (!Br || Br->isConditional()) return Entry;
5317330f729Sjoerg   assert(Br->getSuccessor(0) == Entry);
5327330f729Sjoerg 
5337330f729Sjoerg   // If we were previously inserting at the end of the cleanup entry
5347330f729Sjoerg   // block, we'll need to continue inserting at the end of the
5357330f729Sjoerg   // predecessor.
5367330f729Sjoerg   bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
5377330f729Sjoerg   assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
5387330f729Sjoerg 
5397330f729Sjoerg   // Kill the branch.
5407330f729Sjoerg   Br->eraseFromParent();
5417330f729Sjoerg 
5427330f729Sjoerg   // Replace all uses of the entry with the predecessor, in case there
5437330f729Sjoerg   // are phis in the cleanup.
5447330f729Sjoerg   Entry->replaceAllUsesWith(Pred);
5457330f729Sjoerg 
5467330f729Sjoerg   // Merge the blocks.
5477330f729Sjoerg   Pred->getInstList().splice(Pred->end(), Entry->getInstList());
5487330f729Sjoerg 
5497330f729Sjoerg   // Kill the entry block.
5507330f729Sjoerg   Entry->eraseFromParent();
5517330f729Sjoerg 
5527330f729Sjoerg   if (WasInsertBlock)
5537330f729Sjoerg     CGF.Builder.SetInsertPoint(Pred);
5547330f729Sjoerg 
5557330f729Sjoerg   return Pred;
5567330f729Sjoerg }
5577330f729Sjoerg 
EmitCleanup(CodeGenFunction & CGF,EHScopeStack::Cleanup * Fn,EHScopeStack::Cleanup::Flags flags,Address ActiveFlag)5587330f729Sjoerg static void EmitCleanup(CodeGenFunction &CGF,
5597330f729Sjoerg                         EHScopeStack::Cleanup *Fn,
5607330f729Sjoerg                         EHScopeStack::Cleanup::Flags flags,
5617330f729Sjoerg                         Address ActiveFlag) {
5627330f729Sjoerg   // If there's an active flag, load it and skip the cleanup if it's
5637330f729Sjoerg   // false.
5647330f729Sjoerg   llvm::BasicBlock *ContBB = nullptr;
5657330f729Sjoerg   if (ActiveFlag.isValid()) {
5667330f729Sjoerg     ContBB = CGF.createBasicBlock("cleanup.done");
5677330f729Sjoerg     llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
5687330f729Sjoerg     llvm::Value *IsActive
5697330f729Sjoerg       = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
5707330f729Sjoerg     CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
5717330f729Sjoerg     CGF.EmitBlock(CleanupBB);
5727330f729Sjoerg   }
5737330f729Sjoerg 
5747330f729Sjoerg   // Ask the cleanup to emit itself.
5757330f729Sjoerg   Fn->Emit(CGF, flags);
5767330f729Sjoerg   assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
5777330f729Sjoerg 
5787330f729Sjoerg   // Emit the continuation block if there was an active flag.
5797330f729Sjoerg   if (ActiveFlag.isValid())
5807330f729Sjoerg     CGF.EmitBlock(ContBB);
5817330f729Sjoerg }
5827330f729Sjoerg 
ForwardPrebranchedFallthrough(llvm::BasicBlock * Exit,llvm::BasicBlock * From,llvm::BasicBlock * To)5837330f729Sjoerg static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
5847330f729Sjoerg                                           llvm::BasicBlock *From,
5857330f729Sjoerg                                           llvm::BasicBlock *To) {
5867330f729Sjoerg   // Exit is the exit block of a cleanup, so it always terminates in
5877330f729Sjoerg   // an unconditional branch or a switch.
5887330f729Sjoerg   llvm::Instruction *Term = Exit->getTerminator();
5897330f729Sjoerg 
5907330f729Sjoerg   if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
5917330f729Sjoerg     assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
5927330f729Sjoerg     Br->setSuccessor(0, To);
5937330f729Sjoerg   } else {
5947330f729Sjoerg     llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
5957330f729Sjoerg     for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
5967330f729Sjoerg       if (Switch->getSuccessor(I) == From)
5977330f729Sjoerg         Switch->setSuccessor(I, To);
5987330f729Sjoerg   }
5997330f729Sjoerg }
6007330f729Sjoerg 
6017330f729Sjoerg /// We don't need a normal entry block for the given cleanup.
6027330f729Sjoerg /// Optimistic fixup branches can cause these blocks to come into
6037330f729Sjoerg /// existence anyway;  if so, destroy it.
6047330f729Sjoerg ///
6057330f729Sjoerg /// The validity of this transformation is very much specific to the
6067330f729Sjoerg /// exact ways in which we form branches to cleanup entries.
destroyOptimisticNormalEntry(CodeGenFunction & CGF,EHCleanupScope & scope)6077330f729Sjoerg static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
6087330f729Sjoerg                                          EHCleanupScope &scope) {
6097330f729Sjoerg   llvm::BasicBlock *entry = scope.getNormalBlock();
6107330f729Sjoerg   if (!entry) return;
6117330f729Sjoerg 
6127330f729Sjoerg   // Replace all the uses with unreachable.
6137330f729Sjoerg   llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
6147330f729Sjoerg   for (llvm::BasicBlock::use_iterator
6157330f729Sjoerg          i = entry->use_begin(), e = entry->use_end(); i != e; ) {
6167330f729Sjoerg     llvm::Use &use = *i;
6177330f729Sjoerg     ++i;
6187330f729Sjoerg 
6197330f729Sjoerg     use.set(unreachableBB);
6207330f729Sjoerg 
6217330f729Sjoerg     // The only uses should be fixup switches.
6227330f729Sjoerg     llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
6237330f729Sjoerg     if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
6247330f729Sjoerg       // Replace the switch with a branch.
6257330f729Sjoerg       llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
6267330f729Sjoerg 
6277330f729Sjoerg       // The switch operand is a load from the cleanup-dest alloca.
6287330f729Sjoerg       llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
6297330f729Sjoerg 
6307330f729Sjoerg       // Destroy the switch.
6317330f729Sjoerg       si->eraseFromParent();
6327330f729Sjoerg 
6337330f729Sjoerg       // Destroy the load.
6347330f729Sjoerg       assert(condition->getOperand(0) == CGF.NormalCleanupDest.getPointer());
6357330f729Sjoerg       assert(condition->use_empty());
6367330f729Sjoerg       condition->eraseFromParent();
6377330f729Sjoerg     }
6387330f729Sjoerg   }
6397330f729Sjoerg 
6407330f729Sjoerg   assert(entry->use_empty());
6417330f729Sjoerg   delete entry;
6427330f729Sjoerg }
6437330f729Sjoerg 
6447330f729Sjoerg /// Pops a cleanup block.  If the block includes a normal cleanup, the
6457330f729Sjoerg /// current insertion point is threaded through the cleanup, as are
6467330f729Sjoerg /// any branch fixups on the cleanup.
PopCleanupBlock(bool FallthroughIsBranchThrough)6477330f729Sjoerg void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
6487330f729Sjoerg   assert(!EHStack.empty() && "cleanup stack is empty!");
6497330f729Sjoerg   assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
6507330f729Sjoerg   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
6517330f729Sjoerg   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
6527330f729Sjoerg 
6537330f729Sjoerg   // Remember activation information.
6547330f729Sjoerg   bool IsActive = Scope.isActive();
6557330f729Sjoerg   Address NormalActiveFlag =
6567330f729Sjoerg     Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
6577330f729Sjoerg                                           : Address::invalid();
6587330f729Sjoerg   Address EHActiveFlag =
6597330f729Sjoerg     Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
6607330f729Sjoerg                                       : Address::invalid();
6617330f729Sjoerg 
6627330f729Sjoerg   // Check whether we need an EH cleanup.  This is only true if we've
6637330f729Sjoerg   // generated a lazy EH cleanup block.
6647330f729Sjoerg   llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
6657330f729Sjoerg   assert(Scope.hasEHBranches() == (EHEntry != nullptr));
6667330f729Sjoerg   bool RequiresEHCleanup = (EHEntry != nullptr);
6677330f729Sjoerg   EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
6687330f729Sjoerg 
6697330f729Sjoerg   // Check the three conditions which might require a normal cleanup:
6707330f729Sjoerg 
6717330f729Sjoerg   // - whether there are branch fix-ups through this cleanup
6727330f729Sjoerg   unsigned FixupDepth = Scope.getFixupDepth();
6737330f729Sjoerg   bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
6747330f729Sjoerg 
6757330f729Sjoerg   // - whether there are branch-throughs or branch-afters
6767330f729Sjoerg   bool HasExistingBranches = Scope.hasBranches();
6777330f729Sjoerg 
6787330f729Sjoerg   // - whether there's a fallthrough
6797330f729Sjoerg   llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
6807330f729Sjoerg   bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
6817330f729Sjoerg 
6827330f729Sjoerg   // Branch-through fall-throughs leave the insertion point set to the
6837330f729Sjoerg   // end of the last cleanup, which points to the current scope.  The
6847330f729Sjoerg   // rest of IR gen doesn't need to worry about this; it only happens
6857330f729Sjoerg   // during the execution of PopCleanupBlocks().
6867330f729Sjoerg   bool HasPrebranchedFallthrough =
6877330f729Sjoerg     (FallthroughSource && FallthroughSource->getTerminator());
6887330f729Sjoerg 
6897330f729Sjoerg   // If this is a normal cleanup, then having a prebranched
6907330f729Sjoerg   // fallthrough implies that the fallthrough source unconditionally
6917330f729Sjoerg   // jumps here.
6927330f729Sjoerg   assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
6937330f729Sjoerg          (Scope.getNormalBlock() &&
6947330f729Sjoerg           FallthroughSource->getTerminator()->getSuccessor(0)
6957330f729Sjoerg             == Scope.getNormalBlock()));
6967330f729Sjoerg 
6977330f729Sjoerg   bool RequiresNormalCleanup = false;
6987330f729Sjoerg   if (Scope.isNormalCleanup() &&
6997330f729Sjoerg       (HasFixups || HasExistingBranches || HasFallthrough)) {
7007330f729Sjoerg     RequiresNormalCleanup = true;
7017330f729Sjoerg   }
7027330f729Sjoerg 
7037330f729Sjoerg   // If we have a prebranched fallthrough into an inactive normal
7047330f729Sjoerg   // cleanup, rewrite it so that it leads to the appropriate place.
7057330f729Sjoerg   if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
7067330f729Sjoerg     llvm::BasicBlock *prebranchDest;
7077330f729Sjoerg 
7087330f729Sjoerg     // If the prebranch is semantically branching through the next
7097330f729Sjoerg     // cleanup, just forward it to the next block, leaving the
7107330f729Sjoerg     // insertion point in the prebranched block.
7117330f729Sjoerg     if (FallthroughIsBranchThrough) {
7127330f729Sjoerg       EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
7137330f729Sjoerg       prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
7147330f729Sjoerg 
7157330f729Sjoerg     // Otherwise, we need to make a new block.  If the normal cleanup
7167330f729Sjoerg     // isn't being used at all, we could actually reuse the normal
7177330f729Sjoerg     // entry block, but this is simpler, and it avoids conflicts with
7187330f729Sjoerg     // dead optimistic fixup branches.
7197330f729Sjoerg     } else {
7207330f729Sjoerg       prebranchDest = createBasicBlock("forwarded-prebranch");
7217330f729Sjoerg       EmitBlock(prebranchDest);
7227330f729Sjoerg     }
7237330f729Sjoerg 
7247330f729Sjoerg     llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
7257330f729Sjoerg     assert(normalEntry && !normalEntry->use_empty());
7267330f729Sjoerg 
7277330f729Sjoerg     ForwardPrebranchedFallthrough(FallthroughSource,
7287330f729Sjoerg                                   normalEntry, prebranchDest);
7297330f729Sjoerg   }
7307330f729Sjoerg 
7317330f729Sjoerg   // If we don't need the cleanup at all, we're done.
7327330f729Sjoerg   if (!RequiresNormalCleanup && !RequiresEHCleanup) {
7337330f729Sjoerg     destroyOptimisticNormalEntry(*this, Scope);
7347330f729Sjoerg     EHStack.popCleanup(); // safe because there are no fixups
7357330f729Sjoerg     assert(EHStack.getNumBranchFixups() == 0 ||
7367330f729Sjoerg            EHStack.hasNormalCleanups());
7377330f729Sjoerg     return;
7387330f729Sjoerg   }
7397330f729Sjoerg 
7407330f729Sjoerg   // Copy the cleanup emission data out.  This uses either a stack
7417330f729Sjoerg   // array or malloc'd memory, depending on the size, which is
7427330f729Sjoerg   // behavior that SmallVector would provide, if we could use it
7437330f729Sjoerg   // here. Unfortunately, if you ask for a SmallVector<char>, the
7447330f729Sjoerg   // alignment isn't sufficient.
7457330f729Sjoerg   auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
7467330f729Sjoerg   alignas(EHScopeStack::ScopeStackAlignment) char
7477330f729Sjoerg       CleanupBufferStack[8 * sizeof(void *)];
7487330f729Sjoerg   std::unique_ptr<char[]> CleanupBufferHeap;
7497330f729Sjoerg   size_t CleanupSize = Scope.getCleanupSize();
7507330f729Sjoerg   EHScopeStack::Cleanup *Fn;
7517330f729Sjoerg 
7527330f729Sjoerg   if (CleanupSize <= sizeof(CleanupBufferStack)) {
7537330f729Sjoerg     memcpy(CleanupBufferStack, CleanupSource, CleanupSize);
7547330f729Sjoerg     Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack);
7557330f729Sjoerg   } else {
7567330f729Sjoerg     CleanupBufferHeap.reset(new char[CleanupSize]);
7577330f729Sjoerg     memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
7587330f729Sjoerg     Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
7597330f729Sjoerg   }
7607330f729Sjoerg 
7617330f729Sjoerg   EHScopeStack::Cleanup::Flags cleanupFlags;
7627330f729Sjoerg   if (Scope.isNormalCleanup())
7637330f729Sjoerg     cleanupFlags.setIsNormalCleanupKind();
7647330f729Sjoerg   if (Scope.isEHCleanup())
7657330f729Sjoerg     cleanupFlags.setIsEHCleanupKind();
7667330f729Sjoerg 
767*e038c9c4Sjoerg   // Under -EHa, invoke seh.scope.end() to mark scope end before dtor
768*e038c9c4Sjoerg   bool IsEHa = getLangOpts().EHAsynch && !Scope.isLifetimeMarker();
769*e038c9c4Sjoerg   const EHPersonality &Personality = EHPersonality::get(*this);
7707330f729Sjoerg   if (!RequiresNormalCleanup) {
771*e038c9c4Sjoerg     // Mark CPP scope end for passed-by-value Arg temp
772*e038c9c4Sjoerg     //   per Windows ABI which is "normally" Cleanup in callee
773*e038c9c4Sjoerg     if (IsEHa && getInvokeDest()) {
774*e038c9c4Sjoerg       if (Personality.isMSVCXXPersonality())
775*e038c9c4Sjoerg         EmitSehCppScopeEnd();
776*e038c9c4Sjoerg     }
7777330f729Sjoerg     destroyOptimisticNormalEntry(*this, Scope);
7787330f729Sjoerg     EHStack.popCleanup();
7797330f729Sjoerg   } else {
7807330f729Sjoerg     // If we have a fallthrough and no other need for the cleanup,
7817330f729Sjoerg     // emit it directly.
782*e038c9c4Sjoerg     if (HasFallthrough && !HasPrebranchedFallthrough && !HasFixups &&
783*e038c9c4Sjoerg         !HasExistingBranches) {
784*e038c9c4Sjoerg 
785*e038c9c4Sjoerg       // mark SEH scope end for fall-through flow
786*e038c9c4Sjoerg       if (IsEHa && getInvokeDest()) {
787*e038c9c4Sjoerg         if (Personality.isMSVCXXPersonality())
788*e038c9c4Sjoerg           EmitSehCppScopeEnd();
789*e038c9c4Sjoerg         else
790*e038c9c4Sjoerg           EmitSehTryScopeEnd();
791*e038c9c4Sjoerg       }
7927330f729Sjoerg 
7937330f729Sjoerg       destroyOptimisticNormalEntry(*this, Scope);
7947330f729Sjoerg       EHStack.popCleanup();
7957330f729Sjoerg 
7967330f729Sjoerg       EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
7977330f729Sjoerg 
7987330f729Sjoerg     // Otherwise, the best approach is to thread everything through
7997330f729Sjoerg     // the cleanup block and then try to clean up after ourselves.
8007330f729Sjoerg     } else {
8017330f729Sjoerg       // Force the entry block to exist.
8027330f729Sjoerg       llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
8037330f729Sjoerg 
8047330f729Sjoerg       // I.  Set up the fallthrough edge in.
8057330f729Sjoerg 
8067330f729Sjoerg       CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
8077330f729Sjoerg 
8087330f729Sjoerg       // If there's a fallthrough, we need to store the cleanup
8097330f729Sjoerg       // destination index.  For fall-throughs this is always zero.
8107330f729Sjoerg       if (HasFallthrough) {
8117330f729Sjoerg         if (!HasPrebranchedFallthrough)
8127330f729Sjoerg           Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
8137330f729Sjoerg 
8147330f729Sjoerg       // Otherwise, save and clear the IP if we don't have fallthrough
8157330f729Sjoerg       // because the cleanup is inactive.
8167330f729Sjoerg       } else if (FallthroughSource) {
8177330f729Sjoerg         assert(!IsActive && "source without fallthrough for active cleanup");
8187330f729Sjoerg         savedInactiveFallthroughIP = Builder.saveAndClearIP();
8197330f729Sjoerg       }
8207330f729Sjoerg 
8217330f729Sjoerg       // II.  Emit the entry block.  This implicitly branches to it if
8227330f729Sjoerg       // we have fallthrough.  All the fixups and existing branches
8237330f729Sjoerg       // should already be branched to it.
8247330f729Sjoerg       EmitBlock(NormalEntry);
8257330f729Sjoerg 
826*e038c9c4Sjoerg       // intercept normal cleanup to mark SEH scope end
827*e038c9c4Sjoerg       if (IsEHa) {
828*e038c9c4Sjoerg         if (Personality.isMSVCXXPersonality())
829*e038c9c4Sjoerg           EmitSehCppScopeEnd();
830*e038c9c4Sjoerg         else
831*e038c9c4Sjoerg           EmitSehTryScopeEnd();
832*e038c9c4Sjoerg       }
833*e038c9c4Sjoerg 
8347330f729Sjoerg       // III.  Figure out where we're going and build the cleanup
8357330f729Sjoerg       // epilogue.
8367330f729Sjoerg 
8377330f729Sjoerg       bool HasEnclosingCleanups =
8387330f729Sjoerg         (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
8397330f729Sjoerg 
8407330f729Sjoerg       // Compute the branch-through dest if we need it:
8417330f729Sjoerg       //   - if there are branch-throughs threaded through the scope
8427330f729Sjoerg       //   - if fall-through is a branch-through
8437330f729Sjoerg       //   - if there are fixups that will be optimistically forwarded
8447330f729Sjoerg       //     to the enclosing cleanup
8457330f729Sjoerg       llvm::BasicBlock *BranchThroughDest = nullptr;
8467330f729Sjoerg       if (Scope.hasBranchThroughs() ||
8477330f729Sjoerg           (FallthroughSource && FallthroughIsBranchThrough) ||
8487330f729Sjoerg           (HasFixups && HasEnclosingCleanups)) {
8497330f729Sjoerg         assert(HasEnclosingCleanups);
8507330f729Sjoerg         EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
8517330f729Sjoerg         BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
8527330f729Sjoerg       }
8537330f729Sjoerg 
8547330f729Sjoerg       llvm::BasicBlock *FallthroughDest = nullptr;
8557330f729Sjoerg       SmallVector<llvm::Instruction*, 2> InstsToAppend;
8567330f729Sjoerg 
8577330f729Sjoerg       // If there's exactly one branch-after and no other threads,
8587330f729Sjoerg       // we can route it without a switch.
8597330f729Sjoerg       if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
8607330f729Sjoerg           Scope.getNumBranchAfters() == 1) {
8617330f729Sjoerg         assert(!BranchThroughDest || !IsActive);
8627330f729Sjoerg 
8637330f729Sjoerg         // Clean up the possibly dead store to the cleanup dest slot.
8647330f729Sjoerg         llvm::Instruction *NormalCleanupDestSlot =
8657330f729Sjoerg             cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
8667330f729Sjoerg         if (NormalCleanupDestSlot->hasOneUse()) {
8677330f729Sjoerg           NormalCleanupDestSlot->user_back()->eraseFromParent();
8687330f729Sjoerg           NormalCleanupDestSlot->eraseFromParent();
8697330f729Sjoerg           NormalCleanupDest = Address::invalid();
8707330f729Sjoerg         }
8717330f729Sjoerg 
8727330f729Sjoerg         llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
8737330f729Sjoerg         InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
8747330f729Sjoerg 
8757330f729Sjoerg       // Build a switch-out if we need it:
8767330f729Sjoerg       //   - if there are branch-afters threaded through the scope
8777330f729Sjoerg       //   - if fall-through is a branch-after
8787330f729Sjoerg       //   - if there are fixups that have nowhere left to go and
8797330f729Sjoerg       //     so must be immediately resolved
8807330f729Sjoerg       } else if (Scope.getNumBranchAfters() ||
8817330f729Sjoerg                  (HasFallthrough && !FallthroughIsBranchThrough) ||
8827330f729Sjoerg                  (HasFixups && !HasEnclosingCleanups)) {
8837330f729Sjoerg 
8847330f729Sjoerg         llvm::BasicBlock *Default =
8857330f729Sjoerg           (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
8867330f729Sjoerg 
8877330f729Sjoerg         // TODO: base this on the number of branch-afters and fixups
8887330f729Sjoerg         const unsigned SwitchCapacity = 10;
8897330f729Sjoerg 
890*e038c9c4Sjoerg         // pass the abnormal exit flag to Fn (SEH cleanup)
891*e038c9c4Sjoerg         cleanupFlags.setHasExitSwitch();
892*e038c9c4Sjoerg 
8937330f729Sjoerg         llvm::LoadInst *Load =
8947330f729Sjoerg           createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
8957330f729Sjoerg                                nullptr);
8967330f729Sjoerg         llvm::SwitchInst *Switch =
8977330f729Sjoerg           llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
8987330f729Sjoerg 
8997330f729Sjoerg         InstsToAppend.push_back(Load);
9007330f729Sjoerg         InstsToAppend.push_back(Switch);
9017330f729Sjoerg 
9027330f729Sjoerg         // Branch-after fallthrough.
9037330f729Sjoerg         if (FallthroughSource && !FallthroughIsBranchThrough) {
9047330f729Sjoerg           FallthroughDest = createBasicBlock("cleanup.cont");
9057330f729Sjoerg           if (HasFallthrough)
9067330f729Sjoerg             Switch->addCase(Builder.getInt32(0), FallthroughDest);
9077330f729Sjoerg         }
9087330f729Sjoerg 
9097330f729Sjoerg         for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
9107330f729Sjoerg           Switch->addCase(Scope.getBranchAfterIndex(I),
9117330f729Sjoerg                           Scope.getBranchAfterBlock(I));
9127330f729Sjoerg         }
9137330f729Sjoerg 
9147330f729Sjoerg         // If there aren't any enclosing cleanups, we can resolve all
9157330f729Sjoerg         // the fixups now.
9167330f729Sjoerg         if (HasFixups && !HasEnclosingCleanups)
9177330f729Sjoerg           ResolveAllBranchFixups(*this, Switch, NormalEntry);
9187330f729Sjoerg       } else {
9197330f729Sjoerg         // We should always have a branch-through destination in this case.
9207330f729Sjoerg         assert(BranchThroughDest);
9217330f729Sjoerg         InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
9227330f729Sjoerg       }
9237330f729Sjoerg 
9247330f729Sjoerg       // IV.  Pop the cleanup and emit it.
9257330f729Sjoerg       EHStack.popCleanup();
9267330f729Sjoerg       assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
9277330f729Sjoerg 
9287330f729Sjoerg       EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
9297330f729Sjoerg 
9307330f729Sjoerg       // Append the prepared cleanup prologue from above.
9317330f729Sjoerg       llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
9327330f729Sjoerg       for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
9337330f729Sjoerg         NormalExit->getInstList().push_back(InstsToAppend[I]);
9347330f729Sjoerg 
9357330f729Sjoerg       // Optimistically hope that any fixups will continue falling through.
9367330f729Sjoerg       for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
9377330f729Sjoerg            I < E; ++I) {
9387330f729Sjoerg         BranchFixup &Fixup = EHStack.getBranchFixup(I);
9397330f729Sjoerg         if (!Fixup.Destination) continue;
9407330f729Sjoerg         if (!Fixup.OptimisticBranchBlock) {
9417330f729Sjoerg           createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
9427330f729Sjoerg                                 getNormalCleanupDestSlot(),
9437330f729Sjoerg                                 Fixup.InitialBranch);
9447330f729Sjoerg           Fixup.InitialBranch->setSuccessor(0, NormalEntry);
9457330f729Sjoerg         }
9467330f729Sjoerg         Fixup.OptimisticBranchBlock = NormalExit;
9477330f729Sjoerg       }
9487330f729Sjoerg 
9497330f729Sjoerg       // V.  Set up the fallthrough edge out.
9507330f729Sjoerg 
9517330f729Sjoerg       // Case 1: a fallthrough source exists but doesn't branch to the
9527330f729Sjoerg       // cleanup because the cleanup is inactive.
9537330f729Sjoerg       if (!HasFallthrough && FallthroughSource) {
9547330f729Sjoerg         // Prebranched fallthrough was forwarded earlier.
9557330f729Sjoerg         // Non-prebranched fallthrough doesn't need to be forwarded.
9567330f729Sjoerg         // Either way, all we need to do is restore the IP we cleared before.
9577330f729Sjoerg         assert(!IsActive);
9587330f729Sjoerg         Builder.restoreIP(savedInactiveFallthroughIP);
9597330f729Sjoerg 
9607330f729Sjoerg       // Case 2: a fallthrough source exists and should branch to the
9617330f729Sjoerg       // cleanup, but we're not supposed to branch through to the next
9627330f729Sjoerg       // cleanup.
9637330f729Sjoerg       } else if (HasFallthrough && FallthroughDest) {
9647330f729Sjoerg         assert(!FallthroughIsBranchThrough);
9657330f729Sjoerg         EmitBlock(FallthroughDest);
9667330f729Sjoerg 
9677330f729Sjoerg       // Case 3: a fallthrough source exists and should branch to the
9687330f729Sjoerg       // cleanup and then through to the next.
9697330f729Sjoerg       } else if (HasFallthrough) {
9707330f729Sjoerg         // Everything is already set up for this.
9717330f729Sjoerg 
9727330f729Sjoerg       // Case 4: no fallthrough source exists.
9737330f729Sjoerg       } else {
9747330f729Sjoerg         Builder.ClearInsertionPoint();
9757330f729Sjoerg       }
9767330f729Sjoerg 
9777330f729Sjoerg       // VI.  Assorted cleaning.
9787330f729Sjoerg 
9797330f729Sjoerg       // Check whether we can merge NormalEntry into a single predecessor.
9807330f729Sjoerg       // This might invalidate (non-IR) pointers to NormalEntry.
9817330f729Sjoerg       llvm::BasicBlock *NewNormalEntry =
9827330f729Sjoerg         SimplifyCleanupEntry(*this, NormalEntry);
9837330f729Sjoerg 
9847330f729Sjoerg       // If it did invalidate those pointers, and NormalEntry was the same
9857330f729Sjoerg       // as NormalExit, go back and patch up the fixups.
9867330f729Sjoerg       if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
9877330f729Sjoerg         for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
9887330f729Sjoerg                I < E; ++I)
9897330f729Sjoerg           EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
9907330f729Sjoerg     }
9917330f729Sjoerg   }
9927330f729Sjoerg 
9937330f729Sjoerg   assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
9947330f729Sjoerg 
9957330f729Sjoerg   // Emit the EH cleanup if required.
9967330f729Sjoerg   if (RequiresEHCleanup) {
9977330f729Sjoerg     CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
9987330f729Sjoerg 
9997330f729Sjoerg     EmitBlock(EHEntry);
10007330f729Sjoerg 
10017330f729Sjoerg     llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
10027330f729Sjoerg 
10037330f729Sjoerg     // Push a terminate scope or cleanupendpad scope around the potentially
10047330f729Sjoerg     // throwing cleanups. For funclet EH personalities, the cleanupendpad models
10057330f729Sjoerg     // program termination when cleanups throw.
10067330f729Sjoerg     bool PushedTerminate = false;
10077330f729Sjoerg     SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
10087330f729Sjoerg         CurrentFuncletPad);
10097330f729Sjoerg     llvm::CleanupPadInst *CPI = nullptr;
10107330f729Sjoerg 
10117330f729Sjoerg     const EHPersonality &Personality = EHPersonality::get(*this);
10127330f729Sjoerg     if (Personality.usesFuncletPads()) {
10137330f729Sjoerg       llvm::Value *ParentPad = CurrentFuncletPad;
10147330f729Sjoerg       if (!ParentPad)
10157330f729Sjoerg         ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
10167330f729Sjoerg       CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
10177330f729Sjoerg     }
10187330f729Sjoerg 
10197330f729Sjoerg     // Non-MSVC personalities need to terminate when an EH cleanup throws.
10207330f729Sjoerg     if (!Personality.isMSVCPersonality()) {
10217330f729Sjoerg       EHStack.pushTerminate();
10227330f729Sjoerg       PushedTerminate = true;
10237330f729Sjoerg     }
10247330f729Sjoerg 
10257330f729Sjoerg     // We only actually emit the cleanup code if the cleanup is either
10267330f729Sjoerg     // active or was used before it was deactivated.
10277330f729Sjoerg     if (EHActiveFlag.isValid() || IsActive) {
10287330f729Sjoerg       cleanupFlags.setIsForEHCleanup();
10297330f729Sjoerg       EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
10307330f729Sjoerg     }
10317330f729Sjoerg 
10327330f729Sjoerg     if (CPI)
10337330f729Sjoerg       Builder.CreateCleanupRet(CPI, NextAction);
10347330f729Sjoerg     else
10357330f729Sjoerg       Builder.CreateBr(NextAction);
10367330f729Sjoerg 
10377330f729Sjoerg     // Leave the terminate scope.
10387330f729Sjoerg     if (PushedTerminate)
10397330f729Sjoerg       EHStack.popTerminate();
10407330f729Sjoerg 
10417330f729Sjoerg     Builder.restoreIP(SavedIP);
10427330f729Sjoerg 
10437330f729Sjoerg     SimplifyCleanupEntry(*this, EHEntry);
10447330f729Sjoerg   }
10457330f729Sjoerg }
10467330f729Sjoerg 
10477330f729Sjoerg /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
10487330f729Sjoerg /// specified destination obviously has no cleanups to run.  'false' is always
10497330f729Sjoerg /// a conservatively correct answer for this method.
isObviouslyBranchWithoutCleanups(JumpDest Dest) const10507330f729Sjoerg bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
10517330f729Sjoerg   assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
10527330f729Sjoerg          && "stale jump destination");
10537330f729Sjoerg 
10547330f729Sjoerg   // Calculate the innermost active normal cleanup.
10557330f729Sjoerg   EHScopeStack::stable_iterator TopCleanup =
10567330f729Sjoerg     EHStack.getInnermostActiveNormalCleanup();
10577330f729Sjoerg 
10587330f729Sjoerg   // If we're not in an active normal cleanup scope, or if the
10597330f729Sjoerg   // destination scope is within the innermost active normal cleanup
10607330f729Sjoerg   // scope, we don't need to worry about fixups.
10617330f729Sjoerg   if (TopCleanup == EHStack.stable_end() ||
10627330f729Sjoerg       TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
10637330f729Sjoerg     return true;
10647330f729Sjoerg 
10657330f729Sjoerg   // Otherwise, we might need some cleanups.
10667330f729Sjoerg   return false;
10677330f729Sjoerg }
10687330f729Sjoerg 
10697330f729Sjoerg 
10707330f729Sjoerg /// Terminate the current block by emitting a branch which might leave
10717330f729Sjoerg /// the current cleanup-protected scope.  The target scope may not yet
10727330f729Sjoerg /// be known, in which case this will require a fixup.
10737330f729Sjoerg ///
10747330f729Sjoerg /// As a side-effect, this method clears the insertion point.
EmitBranchThroughCleanup(JumpDest Dest)10757330f729Sjoerg void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
10767330f729Sjoerg   assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
10777330f729Sjoerg          && "stale jump destination");
10787330f729Sjoerg 
10797330f729Sjoerg   if (!HaveInsertPoint())
10807330f729Sjoerg     return;
10817330f729Sjoerg 
10827330f729Sjoerg   // Create the branch.
10837330f729Sjoerg   llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
10847330f729Sjoerg 
10857330f729Sjoerg   // Calculate the innermost active normal cleanup.
10867330f729Sjoerg   EHScopeStack::stable_iterator
10877330f729Sjoerg     TopCleanup = EHStack.getInnermostActiveNormalCleanup();
10887330f729Sjoerg 
10897330f729Sjoerg   // If we're not in an active normal cleanup scope, or if the
10907330f729Sjoerg   // destination scope is within the innermost active normal cleanup
10917330f729Sjoerg   // scope, we don't need to worry about fixups.
10927330f729Sjoerg   if (TopCleanup == EHStack.stable_end() ||
10937330f729Sjoerg       TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
10947330f729Sjoerg     Builder.ClearInsertionPoint();
10957330f729Sjoerg     return;
10967330f729Sjoerg   }
10977330f729Sjoerg 
10987330f729Sjoerg   // If we can't resolve the destination cleanup scope, just add this
10997330f729Sjoerg   // to the current cleanup scope as a branch fixup.
11007330f729Sjoerg   if (!Dest.getScopeDepth().isValid()) {
11017330f729Sjoerg     BranchFixup &Fixup = EHStack.addBranchFixup();
11027330f729Sjoerg     Fixup.Destination = Dest.getBlock();
11037330f729Sjoerg     Fixup.DestinationIndex = Dest.getDestIndex();
11047330f729Sjoerg     Fixup.InitialBranch = BI;
11057330f729Sjoerg     Fixup.OptimisticBranchBlock = nullptr;
11067330f729Sjoerg 
11077330f729Sjoerg     Builder.ClearInsertionPoint();
11087330f729Sjoerg     return;
11097330f729Sjoerg   }
11107330f729Sjoerg 
11117330f729Sjoerg   // Otherwise, thread through all the normal cleanups in scope.
11127330f729Sjoerg 
11137330f729Sjoerg   // Store the index at the start.
11147330f729Sjoerg   llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
11157330f729Sjoerg   createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
11167330f729Sjoerg 
11177330f729Sjoerg   // Adjust BI to point to the first cleanup block.
11187330f729Sjoerg   {
11197330f729Sjoerg     EHCleanupScope &Scope =
11207330f729Sjoerg       cast<EHCleanupScope>(*EHStack.find(TopCleanup));
11217330f729Sjoerg     BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
11227330f729Sjoerg   }
11237330f729Sjoerg 
11247330f729Sjoerg   // Add this destination to all the scopes involved.
11257330f729Sjoerg   EHScopeStack::stable_iterator I = TopCleanup;
11267330f729Sjoerg   EHScopeStack::stable_iterator E = Dest.getScopeDepth();
11277330f729Sjoerg   if (E.strictlyEncloses(I)) {
11287330f729Sjoerg     while (true) {
11297330f729Sjoerg       EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
11307330f729Sjoerg       assert(Scope.isNormalCleanup());
11317330f729Sjoerg       I = Scope.getEnclosingNormalCleanup();
11327330f729Sjoerg 
11337330f729Sjoerg       // If this is the last cleanup we're propagating through, tell it
11347330f729Sjoerg       // that there's a resolved jump moving through it.
11357330f729Sjoerg       if (!E.strictlyEncloses(I)) {
11367330f729Sjoerg         Scope.addBranchAfter(Index, Dest.getBlock());
11377330f729Sjoerg         break;
11387330f729Sjoerg       }
11397330f729Sjoerg 
11407330f729Sjoerg       // Otherwise, tell the scope that there's a jump propagating
11417330f729Sjoerg       // through it.  If this isn't new information, all the rest of
11427330f729Sjoerg       // the work has been done before.
11437330f729Sjoerg       if (!Scope.addBranchThrough(Dest.getBlock()))
11447330f729Sjoerg         break;
11457330f729Sjoerg     }
11467330f729Sjoerg   }
11477330f729Sjoerg 
11487330f729Sjoerg   Builder.ClearInsertionPoint();
11497330f729Sjoerg }
11507330f729Sjoerg 
IsUsedAsNormalCleanup(EHScopeStack & EHStack,EHScopeStack::stable_iterator C)11517330f729Sjoerg static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
11527330f729Sjoerg                                   EHScopeStack::stable_iterator C) {
11537330f729Sjoerg   // If we needed a normal block for any reason, that counts.
11547330f729Sjoerg   if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
11557330f729Sjoerg     return true;
11567330f729Sjoerg 
11577330f729Sjoerg   // Check whether any enclosed cleanups were needed.
11587330f729Sjoerg   for (EHScopeStack::stable_iterator
11597330f729Sjoerg          I = EHStack.getInnermostNormalCleanup();
11607330f729Sjoerg          I != C; ) {
11617330f729Sjoerg     assert(C.strictlyEncloses(I));
11627330f729Sjoerg     EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
11637330f729Sjoerg     if (S.getNormalBlock()) return true;
11647330f729Sjoerg     I = S.getEnclosingNormalCleanup();
11657330f729Sjoerg   }
11667330f729Sjoerg 
11677330f729Sjoerg   return false;
11687330f729Sjoerg }
11697330f729Sjoerg 
IsUsedAsEHCleanup(EHScopeStack & EHStack,EHScopeStack::stable_iterator cleanup)11707330f729Sjoerg static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
11717330f729Sjoerg                               EHScopeStack::stable_iterator cleanup) {
11727330f729Sjoerg   // If we needed an EH block for any reason, that counts.
11737330f729Sjoerg   if (EHStack.find(cleanup)->hasEHBranches())
11747330f729Sjoerg     return true;
11757330f729Sjoerg 
11767330f729Sjoerg   // Check whether any enclosed cleanups were needed.
11777330f729Sjoerg   for (EHScopeStack::stable_iterator
11787330f729Sjoerg          i = EHStack.getInnermostEHScope(); i != cleanup; ) {
11797330f729Sjoerg     assert(cleanup.strictlyEncloses(i));
11807330f729Sjoerg 
11817330f729Sjoerg     EHScope &scope = *EHStack.find(i);
11827330f729Sjoerg     if (scope.hasEHBranches())
11837330f729Sjoerg       return true;
11847330f729Sjoerg 
11857330f729Sjoerg     i = scope.getEnclosingEHScope();
11867330f729Sjoerg   }
11877330f729Sjoerg 
11887330f729Sjoerg   return false;
11897330f729Sjoerg }
11907330f729Sjoerg 
11917330f729Sjoerg enum ForActivation_t {
11927330f729Sjoerg   ForActivation,
11937330f729Sjoerg   ForDeactivation
11947330f729Sjoerg };
11957330f729Sjoerg 
11967330f729Sjoerg /// The given cleanup block is changing activation state.  Configure a
11977330f729Sjoerg /// cleanup variable if necessary.
11987330f729Sjoerg ///
11997330f729Sjoerg /// It would be good if we had some way of determining if there were
12007330f729Sjoerg /// extra uses *after* the change-over point.
SetupCleanupBlockActivation(CodeGenFunction & CGF,EHScopeStack::stable_iterator C,ForActivation_t kind,llvm::Instruction * dominatingIP)12017330f729Sjoerg static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
12027330f729Sjoerg                                         EHScopeStack::stable_iterator C,
12037330f729Sjoerg                                         ForActivation_t kind,
12047330f729Sjoerg                                         llvm::Instruction *dominatingIP) {
12057330f729Sjoerg   EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
12067330f729Sjoerg 
12077330f729Sjoerg   // We always need the flag if we're activating the cleanup in a
12087330f729Sjoerg   // conditional context, because we have to assume that the current
12097330f729Sjoerg   // location doesn't necessarily dominate the cleanup's code.
12107330f729Sjoerg   bool isActivatedInConditional =
12117330f729Sjoerg     (kind == ForActivation && CGF.isInConditionalBranch());
12127330f729Sjoerg 
12137330f729Sjoerg   bool needFlag = false;
12147330f729Sjoerg 
12157330f729Sjoerg   // Calculate whether the cleanup was used:
12167330f729Sjoerg 
12177330f729Sjoerg   //   - as a normal cleanup
12187330f729Sjoerg   if (Scope.isNormalCleanup() &&
12197330f729Sjoerg       (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
12207330f729Sjoerg     Scope.setTestFlagInNormalCleanup();
12217330f729Sjoerg     needFlag = true;
12227330f729Sjoerg   }
12237330f729Sjoerg 
12247330f729Sjoerg   //  - as an EH cleanup
12257330f729Sjoerg   if (Scope.isEHCleanup() &&
12267330f729Sjoerg       (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
12277330f729Sjoerg     Scope.setTestFlagInEHCleanup();
12287330f729Sjoerg     needFlag = true;
12297330f729Sjoerg   }
12307330f729Sjoerg 
12317330f729Sjoerg   // If it hasn't yet been used as either, we're done.
12327330f729Sjoerg   if (!needFlag) return;
12337330f729Sjoerg 
12347330f729Sjoerg   Address var = Scope.getActiveFlag();
12357330f729Sjoerg   if (!var.isValid()) {
12367330f729Sjoerg     var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
12377330f729Sjoerg                                "cleanup.isactive");
12387330f729Sjoerg     Scope.setActiveFlag(var);
12397330f729Sjoerg 
12407330f729Sjoerg     assert(dominatingIP && "no existing variable and no dominating IP!");
12417330f729Sjoerg 
12427330f729Sjoerg     // Initialize to true or false depending on whether it was
12437330f729Sjoerg     // active up to this point.
12447330f729Sjoerg     llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
12457330f729Sjoerg 
12467330f729Sjoerg     // If we're in a conditional block, ignore the dominating IP and
12477330f729Sjoerg     // use the outermost conditional branch.
12487330f729Sjoerg     if (CGF.isInConditionalBranch()) {
12497330f729Sjoerg       CGF.setBeforeOutermostConditional(value, var);
12507330f729Sjoerg     } else {
12517330f729Sjoerg       createStoreInstBefore(value, var, dominatingIP);
12527330f729Sjoerg     }
12537330f729Sjoerg   }
12547330f729Sjoerg 
12557330f729Sjoerg   CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
12567330f729Sjoerg }
12577330f729Sjoerg 
12587330f729Sjoerg /// Activate a cleanup that was created in an inactivated state.
ActivateCleanupBlock(EHScopeStack::stable_iterator C,llvm::Instruction * dominatingIP)12597330f729Sjoerg void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
12607330f729Sjoerg                                            llvm::Instruction *dominatingIP) {
12617330f729Sjoerg   assert(C != EHStack.stable_end() && "activating bottom of stack?");
12627330f729Sjoerg   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
12637330f729Sjoerg   assert(!Scope.isActive() && "double activation");
12647330f729Sjoerg 
12657330f729Sjoerg   SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
12667330f729Sjoerg 
12677330f729Sjoerg   Scope.setActive(true);
12687330f729Sjoerg }
12697330f729Sjoerg 
12707330f729Sjoerg /// Deactive a cleanup that was created in an active state.
DeactivateCleanupBlock(EHScopeStack::stable_iterator C,llvm::Instruction * dominatingIP)12717330f729Sjoerg void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
12727330f729Sjoerg                                              llvm::Instruction *dominatingIP) {
12737330f729Sjoerg   assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
12747330f729Sjoerg   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
12757330f729Sjoerg   assert(Scope.isActive() && "double deactivation");
12767330f729Sjoerg 
12777330f729Sjoerg   // If it's the top of the stack, just pop it, but do so only if it belongs
12787330f729Sjoerg   // to the current RunCleanupsScope.
12797330f729Sjoerg   if (C == EHStack.stable_begin() &&
12807330f729Sjoerg       CurrentCleanupScopeDepth.strictlyEncloses(C)) {
1281*e038c9c4Sjoerg     // Per comment below, checking EHAsynch is not really necessary
1282*e038c9c4Sjoerg     // it's there to assure zero-impact w/o EHAsynch option
1283*e038c9c4Sjoerg     if (!Scope.isNormalCleanup() && getLangOpts().EHAsynch) {
1284*e038c9c4Sjoerg       PopCleanupBlock();
1285*e038c9c4Sjoerg     } else {
12867330f729Sjoerg       // If it's a normal cleanup, we need to pretend that the
12877330f729Sjoerg       // fallthrough is unreachable.
12887330f729Sjoerg       CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
12897330f729Sjoerg       PopCleanupBlock();
12907330f729Sjoerg       Builder.restoreIP(SavedIP);
1291*e038c9c4Sjoerg     }
12927330f729Sjoerg     return;
12937330f729Sjoerg   }
12947330f729Sjoerg 
12957330f729Sjoerg   // Otherwise, follow the general case.
12967330f729Sjoerg   SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
12977330f729Sjoerg 
12987330f729Sjoerg   Scope.setActive(false);
12997330f729Sjoerg }
13007330f729Sjoerg 
getNormalCleanupDestSlot()13017330f729Sjoerg Address CodeGenFunction::getNormalCleanupDestSlot() {
13027330f729Sjoerg   if (!NormalCleanupDest.isValid())
13037330f729Sjoerg     NormalCleanupDest =
13047330f729Sjoerg       CreateDefaultAlignTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
13057330f729Sjoerg   return NormalCleanupDest;
13067330f729Sjoerg }
13077330f729Sjoerg 
13087330f729Sjoerg /// Emits all the code to cause the given temporary to be cleaned up.
EmitCXXTemporary(const CXXTemporary * Temporary,QualType TempType,Address Ptr)13097330f729Sjoerg void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
13107330f729Sjoerg                                        QualType TempType,
13117330f729Sjoerg                                        Address Ptr) {
13127330f729Sjoerg   pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
13137330f729Sjoerg               /*useEHCleanup*/ true);
13147330f729Sjoerg }
1315*e038c9c4Sjoerg 
1316*e038c9c4Sjoerg // Need to set "funclet" in OperandBundle properly for noThrow
1317*e038c9c4Sjoerg //       intrinsic (see CGCall.cpp)
EmitSehScope(CodeGenFunction & CGF,llvm::FunctionCallee & SehCppScope)1318*e038c9c4Sjoerg static void EmitSehScope(CodeGenFunction &CGF,
1319*e038c9c4Sjoerg                          llvm::FunctionCallee &SehCppScope) {
1320*e038c9c4Sjoerg   llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
1321*e038c9c4Sjoerg   assert(CGF.Builder.GetInsertBlock() && InvokeDest);
1322*e038c9c4Sjoerg   llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
1323*e038c9c4Sjoerg   SmallVector<llvm::OperandBundleDef, 1> BundleList =
1324*e038c9c4Sjoerg       CGF.getBundlesForFunclet(SehCppScope.getCallee());
1325*e038c9c4Sjoerg   if (CGF.CurrentFuncletPad)
1326*e038c9c4Sjoerg     BundleList.emplace_back("funclet", CGF.CurrentFuncletPad);
1327*e038c9c4Sjoerg   CGF.Builder.CreateInvoke(SehCppScope, Cont, InvokeDest, None, BundleList);
1328*e038c9c4Sjoerg   CGF.EmitBlock(Cont);
1329*e038c9c4Sjoerg }
1330*e038c9c4Sjoerg 
1331*e038c9c4Sjoerg // Invoke a llvm.seh.scope.begin at the beginning of a CPP scope for -EHa
EmitSehCppScopeBegin()1332*e038c9c4Sjoerg void CodeGenFunction::EmitSehCppScopeBegin() {
1333*e038c9c4Sjoerg   assert(getLangOpts().EHAsynch);
1334*e038c9c4Sjoerg   llvm::FunctionType *FTy =
1335*e038c9c4Sjoerg       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1336*e038c9c4Sjoerg   llvm::FunctionCallee SehCppScope =
1337*e038c9c4Sjoerg       CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.begin");
1338*e038c9c4Sjoerg   EmitSehScope(*this, SehCppScope);
1339*e038c9c4Sjoerg }
1340*e038c9c4Sjoerg 
1341*e038c9c4Sjoerg // Invoke a llvm.seh.scope.end at the end of a CPP scope for -EHa
1342*e038c9c4Sjoerg //   llvm.seh.scope.end is emitted before popCleanup, so it's "invoked"
EmitSehCppScopeEnd()1343*e038c9c4Sjoerg void CodeGenFunction::EmitSehCppScopeEnd() {
1344*e038c9c4Sjoerg   assert(getLangOpts().EHAsynch);
1345*e038c9c4Sjoerg   llvm::FunctionType *FTy =
1346*e038c9c4Sjoerg       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1347*e038c9c4Sjoerg   llvm::FunctionCallee SehCppScope =
1348*e038c9c4Sjoerg       CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.end");
1349*e038c9c4Sjoerg   EmitSehScope(*this, SehCppScope);
1350*e038c9c4Sjoerg }
1351*e038c9c4Sjoerg 
1352*e038c9c4Sjoerg // Invoke a llvm.seh.try.begin at the beginning of a SEH scope for -EHa
EmitSehTryScopeBegin()1353*e038c9c4Sjoerg void CodeGenFunction::EmitSehTryScopeBegin() {
1354*e038c9c4Sjoerg   assert(getLangOpts().EHAsynch);
1355*e038c9c4Sjoerg   llvm::FunctionType *FTy =
1356*e038c9c4Sjoerg       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1357*e038c9c4Sjoerg   llvm::FunctionCallee SehCppScope =
1358*e038c9c4Sjoerg       CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.begin");
1359*e038c9c4Sjoerg   EmitSehScope(*this, SehCppScope);
1360*e038c9c4Sjoerg }
1361*e038c9c4Sjoerg 
1362*e038c9c4Sjoerg // Invoke a llvm.seh.try.end at the end of a SEH scope for -EHa
EmitSehTryScopeEnd()1363*e038c9c4Sjoerg void CodeGenFunction::EmitSehTryScopeEnd() {
1364*e038c9c4Sjoerg   assert(getLangOpts().EHAsynch);
1365*e038c9c4Sjoerg   llvm::FunctionType *FTy =
1366*e038c9c4Sjoerg       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1367*e038c9c4Sjoerg   llvm::FunctionCallee SehCppScope =
1368*e038c9c4Sjoerg       CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.end");
1369*e038c9c4Sjoerg   EmitSehScope(*this, SehCppScope);
1370*e038c9c4Sjoerg }
1371