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