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