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