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