clang API Documentation

CGCleanup.cpp
Go to the documentation of this file.
00001 //===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains code dealing with the IR generation for cleanups
00011 // and related information.
00012 //
00013 // A "cleanup" is a piece of code which needs to be executed whenever
00014 // control transfers out of a particular scope.  This can be
00015 // conditionalized to occur only on exceptional control flow, only on
00016 // normal control flow, or both.
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #include "CGCleanup.h"
00021 #include "CodeGenFunction.h"
00022 
00023 using namespace clang;
00024 using namespace CodeGen;
00025 
00026 bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
00027   if (rv.isScalar())
00028     return DominatingLLVMValue::needsSaving(rv.getScalarVal());
00029   if (rv.isAggregate())
00030     return DominatingLLVMValue::needsSaving(rv.getAggregateAddr());
00031   return true;
00032 }
00033 
00034 DominatingValue<RValue>::saved_type
00035 DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
00036   if (rv.isScalar()) {
00037     llvm::Value *V = rv.getScalarVal();
00038 
00039     // These automatically dominate and don't need to be saved.
00040     if (!DominatingLLVMValue::needsSaving(V))
00041       return saved_type(V, ScalarLiteral);
00042 
00043     // Everything else needs an alloca.
00044     llvm::Value *addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
00045     CGF.Builder.CreateStore(V, addr);
00046     return saved_type(addr, ScalarAddress);
00047   }
00048 
00049   if (rv.isComplex()) {
00050     CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
00051     llvm::Type *ComplexTy =
00052       llvm::StructType::get(V.first->getType(), V.second->getType(),
00053                             (void*) nullptr);
00054     llvm::Value *addr = CGF.CreateTempAlloca(ComplexTy, "saved-complex");
00055     CGF.Builder.CreateStore(V.first, CGF.Builder.CreateStructGEP(addr, 0));
00056     CGF.Builder.CreateStore(V.second, CGF.Builder.CreateStructGEP(addr, 1));
00057     return saved_type(addr, ComplexAddress);
00058   }
00059 
00060   assert(rv.isAggregate());
00061   llvm::Value *V = rv.getAggregateAddr(); // TODO: volatile?
00062   if (!DominatingLLVMValue::needsSaving(V))
00063     return saved_type(V, AggregateLiteral);
00064 
00065   llvm::Value *addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
00066   CGF.Builder.CreateStore(V, addr);
00067   return saved_type(addr, AggregateAddress);  
00068 }
00069 
00070 /// Given a saved r-value produced by SaveRValue, perform the code
00071 /// necessary to restore it to usability at the current insertion
00072 /// point.
00073 RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
00074   switch (K) {
00075   case ScalarLiteral:
00076     return RValue::get(Value);
00077   case ScalarAddress:
00078     return RValue::get(CGF.Builder.CreateLoad(Value));
00079   case AggregateLiteral:
00080     return RValue::getAggregate(Value);
00081   case AggregateAddress:
00082     return RValue::getAggregate(CGF.Builder.CreateLoad(Value));
00083   case ComplexAddress: {
00084     llvm::Value *real =
00085       CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(Value, 0));
00086     llvm::Value *imag =
00087       CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(Value, 1));
00088     return RValue::getComplex(real, imag);
00089   }
00090   }
00091 
00092   llvm_unreachable("bad saved r-value kind");
00093 }
00094 
00095 /// Push an entry of the given size onto this protected-scope stack.
00096 char *EHScopeStack::allocate(size_t Size) {
00097   if (!StartOfBuffer) {
00098     unsigned Capacity = 1024;
00099     while (Capacity < Size) Capacity *= 2;
00100     StartOfBuffer = new char[Capacity];
00101     StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
00102   } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
00103     unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
00104     unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
00105 
00106     unsigned NewCapacity = CurrentCapacity;
00107     do {
00108       NewCapacity *= 2;
00109     } while (NewCapacity < UsedCapacity + Size);
00110 
00111     char *NewStartOfBuffer = new char[NewCapacity];
00112     char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
00113     char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
00114     memcpy(NewStartOfData, StartOfData, UsedCapacity);
00115     delete [] StartOfBuffer;
00116     StartOfBuffer = NewStartOfBuffer;
00117     EndOfBuffer = NewEndOfBuffer;
00118     StartOfData = NewStartOfData;
00119   }
00120 
00121   assert(StartOfBuffer + Size <= StartOfData);
00122   StartOfData -= Size;
00123   return StartOfData;
00124 }
00125 
00126 EHScopeStack::stable_iterator
00127 EHScopeStack::getInnermostActiveNormalCleanup() const {
00128   for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
00129          si != se; ) {
00130     EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
00131     if (cleanup.isActive()) return si;
00132     si = cleanup.getEnclosingNormalCleanup();
00133   }
00134   return stable_end();
00135 }
00136 
00137 EHScopeStack::stable_iterator EHScopeStack::getInnermostActiveEHScope() const {
00138   for (stable_iterator si = getInnermostEHScope(), se = stable_end();
00139          si != se; ) {
00140     // Skip over inactive cleanups.
00141     EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*find(si));
00142     if (cleanup && !cleanup->isActive()) {
00143       si = cleanup->getEnclosingEHScope();
00144       continue;
00145     }
00146 
00147     // All other scopes are always active.
00148     return si;
00149   }
00150 
00151   return stable_end();
00152 }
00153 
00154 
00155 void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
00156   assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
00157   char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
00158   bool IsNormalCleanup = Kind & NormalCleanup;
00159   bool IsEHCleanup = Kind & EHCleanup;
00160   bool IsActive = !(Kind & InactiveCleanup);
00161   EHCleanupScope *Scope =
00162     new (Buffer) EHCleanupScope(IsNormalCleanup,
00163                                 IsEHCleanup,
00164                                 IsActive,
00165                                 Size,
00166                                 BranchFixups.size(),
00167                                 InnermostNormalCleanup,
00168                                 InnermostEHScope);
00169   if (IsNormalCleanup)
00170     InnermostNormalCleanup = stable_begin();
00171   if (IsEHCleanup)
00172     InnermostEHScope = stable_begin();
00173 
00174   return Scope->getCleanupBuffer();
00175 }
00176 
00177 void EHScopeStack::popCleanup() {
00178   assert(!empty() && "popping exception stack when not empty");
00179 
00180   assert(isa<EHCleanupScope>(*begin()));
00181   EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
00182   InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
00183   InnermostEHScope = Cleanup.getEnclosingEHScope();
00184   StartOfData += Cleanup.getAllocatedSize();
00185 
00186   // Destroy the cleanup.
00187   Cleanup.Destroy();
00188 
00189   // Check whether we can shrink the branch-fixups stack.
00190   if (!BranchFixups.empty()) {
00191     // If we no longer have any normal cleanups, all the fixups are
00192     // complete.
00193     if (!hasNormalCleanups())
00194       BranchFixups.clear();
00195 
00196     // Otherwise we can still trim out unnecessary nulls.
00197     else
00198       popNullFixups();
00199   }
00200 }
00201 
00202 EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
00203   assert(getInnermostEHScope() == stable_end());
00204   char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
00205   EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
00206   InnermostEHScope = stable_begin();
00207   return filter;
00208 }
00209 
00210 void EHScopeStack::popFilter() {
00211   assert(!empty() && "popping exception stack when not empty");
00212 
00213   EHFilterScope &filter = cast<EHFilterScope>(*begin());
00214   StartOfData += EHFilterScope::getSizeForNumFilters(filter.getNumFilters());
00215 
00216   InnermostEHScope = filter.getEnclosingEHScope();
00217 }
00218 
00219 EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
00220   char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
00221   EHCatchScope *scope =
00222     new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
00223   InnermostEHScope = stable_begin();
00224   return scope;
00225 }
00226 
00227 void EHScopeStack::pushTerminate() {
00228   char *Buffer = allocate(EHTerminateScope::getSize());
00229   new (Buffer) EHTerminateScope(InnermostEHScope);
00230   InnermostEHScope = stable_begin();
00231 }
00232 
00233 /// Remove any 'null' fixups on the stack.  However, we can't pop more
00234 /// fixups than the fixup depth on the innermost normal cleanup, or
00235 /// else fixups that we try to add to that cleanup will end up in the
00236 /// wrong place.  We *could* try to shrink fixup depths, but that's
00237 /// actually a lot of work for little benefit.
00238 void EHScopeStack::popNullFixups() {
00239   // We expect this to only be called when there's still an innermost
00240   // normal cleanup;  otherwise there really shouldn't be any fixups.
00241   assert(hasNormalCleanups());
00242 
00243   EHScopeStack::iterator it = find(InnermostNormalCleanup);
00244   unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
00245   assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
00246 
00247   while (BranchFixups.size() > MinSize &&
00248          BranchFixups.back().Destination == nullptr)
00249     BranchFixups.pop_back();
00250 }
00251 
00252 void CodeGenFunction::initFullExprCleanup() {
00253   // Create a variable to decide whether the cleanup needs to be run.
00254   llvm::AllocaInst *active
00255     = CreateTempAlloca(Builder.getInt1Ty(), "cleanup.cond");
00256 
00257   // Initialize it to false at a site that's guaranteed to be run
00258   // before each evaluation.
00259   setBeforeOutermostConditional(Builder.getFalse(), active);
00260 
00261   // Initialize it to true at the current location.
00262   Builder.CreateStore(Builder.getTrue(), active);
00263 
00264   // Set that as the active flag in the cleanup.
00265   EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
00266   assert(!cleanup.getActiveFlag() && "cleanup already has active flag?");
00267   cleanup.setActiveFlag(active);
00268 
00269   if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
00270   if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
00271 }
00272 
00273 void EHScopeStack::Cleanup::anchor() {}
00274 
00275 /// All the branch fixups on the EH stack have propagated out past the
00276 /// outermost normal cleanup; resolve them all by adding cases to the
00277 /// given switch instruction.
00278 static void ResolveAllBranchFixups(CodeGenFunction &CGF,
00279                                    llvm::SwitchInst *Switch,
00280                                    llvm::BasicBlock *CleanupEntry) {
00281   llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
00282 
00283   for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
00284     // Skip this fixup if its destination isn't set.
00285     BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
00286     if (Fixup.Destination == nullptr) continue;
00287 
00288     // If there isn't an OptimisticBranchBlock, then InitialBranch is
00289     // still pointing directly to its destination; forward it to the
00290     // appropriate cleanup entry.  This is required in the specific
00291     // case of
00292     //   { std::string s; goto lbl; }
00293     //   lbl:
00294     // i.e. where there's an unresolved fixup inside a single cleanup
00295     // entry which we're currently popping.
00296     if (Fixup.OptimisticBranchBlock == nullptr) {
00297       new llvm::StoreInst(CGF.Builder.getInt32(Fixup.DestinationIndex),
00298                           CGF.getNormalCleanupDestSlot(),
00299                           Fixup.InitialBranch);
00300       Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
00301     }
00302 
00303     // Don't add this case to the switch statement twice.
00304     if (!CasesAdded.insert(Fixup.Destination)) continue;
00305 
00306     Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
00307                     Fixup.Destination);
00308   }
00309 
00310   CGF.EHStack.clearFixups();
00311 }
00312 
00313 /// Transitions the terminator of the given exit-block of a cleanup to
00314 /// be a cleanup switch.
00315 static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
00316                                                    llvm::BasicBlock *Block) {
00317   // If it's a branch, turn it into a switch whose default
00318   // destination is its original target.
00319   llvm::TerminatorInst *Term = Block->getTerminator();
00320   assert(Term && "can't transition block without terminator");
00321 
00322   if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
00323     assert(Br->isUnconditional());
00324     llvm::LoadInst *Load =
00325       new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
00326     llvm::SwitchInst *Switch =
00327       llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
00328     Br->eraseFromParent();
00329     return Switch;
00330   } else {
00331     return cast<llvm::SwitchInst>(Term);
00332   }
00333 }
00334 
00335 void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
00336   assert(Block && "resolving a null target block");
00337   if (!EHStack.getNumBranchFixups()) return;
00338 
00339   assert(EHStack.hasNormalCleanups() &&
00340          "branch fixups exist with no normal cleanups on stack");
00341 
00342   llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
00343   bool ResolvedAny = false;
00344 
00345   for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
00346     // Skip this fixup if its destination doesn't match.
00347     BranchFixup &Fixup = EHStack.getBranchFixup(I);
00348     if (Fixup.Destination != Block) continue;
00349 
00350     Fixup.Destination = nullptr;
00351     ResolvedAny = true;
00352 
00353     // If it doesn't have an optimistic branch block, LatestBranch is
00354     // already pointing to the right place.
00355     llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
00356     if (!BranchBB)
00357       continue;
00358 
00359     // Don't process the same optimistic branch block twice.
00360     if (!ModifiedOptimisticBlocks.insert(BranchBB))
00361       continue;
00362 
00363     llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
00364 
00365     // Add a case to the switch.
00366     Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
00367   }
00368 
00369   if (ResolvedAny)
00370     EHStack.popNullFixups();
00371 }
00372 
00373 /// Pops cleanup blocks until the given savepoint is reached.
00374 void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
00375   assert(Old.isValid());
00376 
00377   while (EHStack.stable_begin() != Old) {
00378     EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
00379 
00380     // As long as Old strictly encloses the scope's enclosing normal
00381     // cleanup, we're going to emit another normal cleanup which
00382     // fallthrough can propagate through.
00383     bool FallThroughIsBranchThrough =
00384       Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
00385 
00386     PopCleanupBlock(FallThroughIsBranchThrough);
00387   }
00388 }
00389 
00390 /// Pops cleanup blocks until the given savepoint is reached, then add the
00391 /// cleanups from the given savepoint in the lifetime-extended cleanups stack.
00392 void
00393 CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old,
00394                                   size_t OldLifetimeExtendedSize) {
00395   PopCleanupBlocks(Old);
00396 
00397   // Move our deferred cleanups onto the EH stack.
00398   for (size_t I = OldLifetimeExtendedSize,
00399               E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
00400     // Alignment should be guaranteed by the vptrs in the individual cleanups.
00401     assert((I % llvm::alignOf<LifetimeExtendedCleanupHeader>() == 0) &&
00402            "misaligned cleanup stack entry");
00403 
00404     LifetimeExtendedCleanupHeader &Header =
00405         reinterpret_cast<LifetimeExtendedCleanupHeader&>(
00406             LifetimeExtendedCleanupStack[I]);
00407     I += sizeof(Header);
00408 
00409     EHStack.pushCopyOfCleanup(Header.getKind(),
00410                               &LifetimeExtendedCleanupStack[I],
00411                               Header.getSize());
00412     I += Header.getSize();
00413   }
00414   LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
00415 }
00416 
00417 static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
00418                                            EHCleanupScope &Scope) {
00419   assert(Scope.isNormalCleanup());
00420   llvm::BasicBlock *Entry = Scope.getNormalBlock();
00421   if (!Entry) {
00422     Entry = CGF.createBasicBlock("cleanup");
00423     Scope.setNormalBlock(Entry);
00424   }
00425   return Entry;
00426 }
00427 
00428 /// Attempts to reduce a cleanup's entry block to a fallthrough.  This
00429 /// is basically llvm::MergeBlockIntoPredecessor, except
00430 /// simplified/optimized for the tighter constraints on cleanup blocks.
00431 ///
00432 /// Returns the new block, whatever it is.
00433 static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
00434                                               llvm::BasicBlock *Entry) {
00435   llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
00436   if (!Pred) return Entry;
00437 
00438   llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
00439   if (!Br || Br->isConditional()) return Entry;
00440   assert(Br->getSuccessor(0) == Entry);
00441 
00442   // If we were previously inserting at the end of the cleanup entry
00443   // block, we'll need to continue inserting at the end of the
00444   // predecessor.
00445   bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
00446   assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
00447 
00448   // Kill the branch.
00449   Br->eraseFromParent();
00450 
00451   // Replace all uses of the entry with the predecessor, in case there
00452   // are phis in the cleanup.
00453   Entry->replaceAllUsesWith(Pred);
00454 
00455   // Merge the blocks.
00456   Pred->getInstList().splice(Pred->end(), Entry->getInstList());
00457 
00458   // Kill the entry block.
00459   Entry->eraseFromParent();
00460 
00461   if (WasInsertBlock)
00462     CGF.Builder.SetInsertPoint(Pred);
00463 
00464   return Pred;
00465 }
00466 
00467 static void EmitCleanup(CodeGenFunction &CGF,
00468                         EHScopeStack::Cleanup *Fn,
00469                         EHScopeStack::Cleanup::Flags flags,
00470                         llvm::Value *ActiveFlag) {
00471   // EH cleanups always occur within a terminate scope.
00472   if (flags.isForEHCleanup()) CGF.EHStack.pushTerminate();
00473 
00474   // If there's an active flag, load it and skip the cleanup if it's
00475   // false.
00476   llvm::BasicBlock *ContBB = nullptr;
00477   if (ActiveFlag) {
00478     ContBB = CGF.createBasicBlock("cleanup.done");
00479     llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
00480     llvm::Value *IsActive
00481       = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
00482     CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
00483     CGF.EmitBlock(CleanupBB);
00484   }
00485 
00486   // Ask the cleanup to emit itself.
00487   Fn->Emit(CGF, flags);
00488   assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
00489 
00490   // Emit the continuation block if there was an active flag.
00491   if (ActiveFlag)
00492     CGF.EmitBlock(ContBB);
00493 
00494   // Leave the terminate scope.
00495   if (flags.isForEHCleanup()) CGF.EHStack.popTerminate();
00496 }
00497 
00498 static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
00499                                           llvm::BasicBlock *From,
00500                                           llvm::BasicBlock *To) {
00501   // Exit is the exit block of a cleanup, so it always terminates in
00502   // an unconditional branch or a switch.
00503   llvm::TerminatorInst *Term = Exit->getTerminator();
00504 
00505   if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
00506     assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
00507     Br->setSuccessor(0, To);
00508   } else {
00509     llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
00510     for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
00511       if (Switch->getSuccessor(I) == From)
00512         Switch->setSuccessor(I, To);
00513   }
00514 }
00515 
00516 /// We don't need a normal entry block for the given cleanup.
00517 /// Optimistic fixup branches can cause these blocks to come into
00518 /// existence anyway;  if so, destroy it.
00519 ///
00520 /// The validity of this transformation is very much specific to the
00521 /// exact ways in which we form branches to cleanup entries.
00522 static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
00523                                          EHCleanupScope &scope) {
00524   llvm::BasicBlock *entry = scope.getNormalBlock();
00525   if (!entry) return;
00526 
00527   // Replace all the uses with unreachable.
00528   llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
00529   for (llvm::BasicBlock::use_iterator
00530          i = entry->use_begin(), e = entry->use_end(); i != e; ) {
00531     llvm::Use &use = *i;
00532     ++i;
00533 
00534     use.set(unreachableBB);
00535     
00536     // The only uses should be fixup switches.
00537     llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
00538     if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
00539       // Replace the switch with a branch.
00540       llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
00541 
00542       // The switch operand is a load from the cleanup-dest alloca.
00543       llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
00544 
00545       // Destroy the switch.
00546       si->eraseFromParent();
00547 
00548       // Destroy the load.
00549       assert(condition->getOperand(0) == CGF.NormalCleanupDest);
00550       assert(condition->use_empty());
00551       condition->eraseFromParent();
00552     }
00553   }
00554   
00555   assert(entry->use_empty());
00556   delete entry;
00557 }
00558 
00559 /// Pops a cleanup block.  If the block includes a normal cleanup, the
00560 /// current insertion point is threaded through the cleanup, as are
00561 /// any branch fixups on the cleanup.
00562 void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
00563   assert(!EHStack.empty() && "cleanup stack is empty!");
00564   assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
00565   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
00566   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
00567 
00568   // Remember activation information.
00569   bool IsActive = Scope.isActive();
00570   llvm::Value *NormalActiveFlag =
00571     Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : nullptr;
00572   llvm::Value *EHActiveFlag = 
00573     Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : nullptr;
00574 
00575   // Check whether we need an EH cleanup.  This is only true if we've
00576   // generated a lazy EH cleanup block.
00577   llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
00578   assert(Scope.hasEHBranches() == (EHEntry != nullptr));
00579   bool RequiresEHCleanup = (EHEntry != nullptr);
00580   EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
00581 
00582   // Check the three conditions which might require a normal cleanup:
00583 
00584   // - whether there are branch fix-ups through this cleanup
00585   unsigned FixupDepth = Scope.getFixupDepth();
00586   bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
00587 
00588   // - whether there are branch-throughs or branch-afters
00589   bool HasExistingBranches = Scope.hasBranches();
00590 
00591   // - whether there's a fallthrough
00592   llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
00593   bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
00594 
00595   // Branch-through fall-throughs leave the insertion point set to the
00596   // end of the last cleanup, which points to the current scope.  The
00597   // rest of IR gen doesn't need to worry about this; it only happens
00598   // during the execution of PopCleanupBlocks().
00599   bool HasPrebranchedFallthrough =
00600     (FallthroughSource && FallthroughSource->getTerminator());
00601 
00602   // If this is a normal cleanup, then having a prebranched
00603   // fallthrough implies that the fallthrough source unconditionally
00604   // jumps here.
00605   assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
00606          (Scope.getNormalBlock() &&
00607           FallthroughSource->getTerminator()->getSuccessor(0)
00608             == Scope.getNormalBlock()));
00609 
00610   bool RequiresNormalCleanup = false;
00611   if (Scope.isNormalCleanup() &&
00612       (HasFixups || HasExistingBranches || HasFallthrough)) {
00613     RequiresNormalCleanup = true;
00614   }
00615 
00616   // If we have a prebranched fallthrough into an inactive normal
00617   // cleanup, rewrite it so that it leads to the appropriate place.
00618   if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
00619     llvm::BasicBlock *prebranchDest;
00620     
00621     // If the prebranch is semantically branching through the next
00622     // cleanup, just forward it to the next block, leaving the
00623     // insertion point in the prebranched block.
00624     if (FallthroughIsBranchThrough) {
00625       EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
00626       prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
00627 
00628     // Otherwise, we need to make a new block.  If the normal cleanup
00629     // isn't being used at all, we could actually reuse the normal
00630     // entry block, but this is simpler, and it avoids conflicts with
00631     // dead optimistic fixup branches.
00632     } else {
00633       prebranchDest = createBasicBlock("forwarded-prebranch");
00634       EmitBlock(prebranchDest);
00635     }
00636 
00637     llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
00638     assert(normalEntry && !normalEntry->use_empty());
00639 
00640     ForwardPrebranchedFallthrough(FallthroughSource,
00641                                   normalEntry, prebranchDest);
00642   }
00643 
00644   // If we don't need the cleanup at all, we're done.
00645   if (!RequiresNormalCleanup && !RequiresEHCleanup) {
00646     destroyOptimisticNormalEntry(*this, Scope);
00647     EHStack.popCleanup(); // safe because there are no fixups
00648     assert(EHStack.getNumBranchFixups() == 0 ||
00649            EHStack.hasNormalCleanups());
00650     return;
00651   }
00652 
00653   // Copy the cleanup emission data out.  Note that SmallVector
00654   // guarantees maximal alignment for its buffer regardless of its
00655   // type parameter.
00656   SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
00657   CleanupBuffer.reserve(Scope.getCleanupSize());
00658   memcpy(CleanupBuffer.data(),
00659          Scope.getCleanupBuffer(), Scope.getCleanupSize());
00660   CleanupBuffer.set_size(Scope.getCleanupSize());
00661   EHScopeStack::Cleanup *Fn =
00662     reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
00663 
00664   EHScopeStack::Cleanup::Flags cleanupFlags;
00665   if (Scope.isNormalCleanup())
00666     cleanupFlags.setIsNormalCleanupKind();
00667   if (Scope.isEHCleanup())
00668     cleanupFlags.setIsEHCleanupKind();
00669 
00670   if (!RequiresNormalCleanup) {
00671     destroyOptimisticNormalEntry(*this, Scope);
00672     EHStack.popCleanup();
00673   } else {
00674     // If we have a fallthrough and no other need for the cleanup,
00675     // emit it directly.
00676     if (HasFallthrough && !HasPrebranchedFallthrough &&
00677         !HasFixups && !HasExistingBranches) {
00678 
00679       destroyOptimisticNormalEntry(*this, Scope);
00680       EHStack.popCleanup();
00681 
00682       EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
00683 
00684     // Otherwise, the best approach is to thread everything through
00685     // the cleanup block and then try to clean up after ourselves.
00686     } else {
00687       // Force the entry block to exist.
00688       llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
00689 
00690       // I.  Set up the fallthrough edge in.
00691 
00692       CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
00693 
00694       // If there's a fallthrough, we need to store the cleanup
00695       // destination index.  For fall-throughs this is always zero.
00696       if (HasFallthrough) {
00697         if (!HasPrebranchedFallthrough)
00698           Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
00699 
00700       // Otherwise, save and clear the IP if we don't have fallthrough
00701       // because the cleanup is inactive.
00702       } else if (FallthroughSource) {
00703         assert(!IsActive && "source without fallthrough for active cleanup");
00704         savedInactiveFallthroughIP = Builder.saveAndClearIP();
00705       }
00706 
00707       // II.  Emit the entry block.  This implicitly branches to it if
00708       // we have fallthrough.  All the fixups and existing branches
00709       // should already be branched to it.
00710       EmitBlock(NormalEntry);
00711 
00712       // III.  Figure out where we're going and build the cleanup
00713       // epilogue.
00714 
00715       bool HasEnclosingCleanups =
00716         (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
00717 
00718       // Compute the branch-through dest if we need it:
00719       //   - if there are branch-throughs threaded through the scope
00720       //   - if fall-through is a branch-through
00721       //   - if there are fixups that will be optimistically forwarded
00722       //     to the enclosing cleanup
00723       llvm::BasicBlock *BranchThroughDest = nullptr;
00724       if (Scope.hasBranchThroughs() ||
00725           (FallthroughSource && FallthroughIsBranchThrough) ||
00726           (HasFixups && HasEnclosingCleanups)) {
00727         assert(HasEnclosingCleanups);
00728         EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
00729         BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
00730       }
00731 
00732       llvm::BasicBlock *FallthroughDest = nullptr;
00733       SmallVector<llvm::Instruction*, 2> InstsToAppend;
00734 
00735       // If there's exactly one branch-after and no other threads,
00736       // we can route it without a switch.
00737       if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
00738           Scope.getNumBranchAfters() == 1) {
00739         assert(!BranchThroughDest || !IsActive);
00740 
00741         // TODO: clean up the possibly dead stores to the cleanup dest slot.
00742         llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
00743         InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
00744 
00745       // Build a switch-out if we need it:
00746       //   - if there are branch-afters threaded through the scope
00747       //   - if fall-through is a branch-after
00748       //   - if there are fixups that have nowhere left to go and
00749       //     so must be immediately resolved
00750       } else if (Scope.getNumBranchAfters() ||
00751                  (HasFallthrough && !FallthroughIsBranchThrough) ||
00752                  (HasFixups && !HasEnclosingCleanups)) {
00753 
00754         llvm::BasicBlock *Default =
00755           (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
00756 
00757         // TODO: base this on the number of branch-afters and fixups
00758         const unsigned SwitchCapacity = 10;
00759 
00760         llvm::LoadInst *Load =
00761           new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
00762         llvm::SwitchInst *Switch =
00763           llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
00764 
00765         InstsToAppend.push_back(Load);
00766         InstsToAppend.push_back(Switch);
00767 
00768         // Branch-after fallthrough.
00769         if (FallthroughSource && !FallthroughIsBranchThrough) {
00770           FallthroughDest = createBasicBlock("cleanup.cont");
00771           if (HasFallthrough)
00772             Switch->addCase(Builder.getInt32(0), FallthroughDest);
00773         }
00774 
00775         for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
00776           Switch->addCase(Scope.getBranchAfterIndex(I),
00777                           Scope.getBranchAfterBlock(I));
00778         }
00779 
00780         // If there aren't any enclosing cleanups, we can resolve all
00781         // the fixups now.
00782         if (HasFixups && !HasEnclosingCleanups)
00783           ResolveAllBranchFixups(*this, Switch, NormalEntry);
00784       } else {
00785         // We should always have a branch-through destination in this case.
00786         assert(BranchThroughDest);
00787         InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
00788       }
00789 
00790       // IV.  Pop the cleanup and emit it.
00791       EHStack.popCleanup();
00792       assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
00793 
00794       EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
00795 
00796       // Append the prepared cleanup prologue from above.
00797       llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
00798       for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
00799         NormalExit->getInstList().push_back(InstsToAppend[I]);
00800 
00801       // Optimistically hope that any fixups will continue falling through.
00802       for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
00803            I < E; ++I) {
00804         BranchFixup &Fixup = EHStack.getBranchFixup(I);
00805         if (!Fixup.Destination) continue;
00806         if (!Fixup.OptimisticBranchBlock) {
00807           new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
00808                               getNormalCleanupDestSlot(),
00809                               Fixup.InitialBranch);
00810           Fixup.InitialBranch->setSuccessor(0, NormalEntry);
00811         }
00812         Fixup.OptimisticBranchBlock = NormalExit;
00813       }
00814 
00815       // V.  Set up the fallthrough edge out.
00816       
00817       // Case 1: a fallthrough source exists but doesn't branch to the
00818       // cleanup because the cleanup is inactive.
00819       if (!HasFallthrough && FallthroughSource) {
00820         // Prebranched fallthrough was forwarded earlier.
00821         // Non-prebranched fallthrough doesn't need to be forwarded.
00822         // Either way, all we need to do is restore the IP we cleared before.
00823         assert(!IsActive);
00824         Builder.restoreIP(savedInactiveFallthroughIP);
00825 
00826       // Case 2: a fallthrough source exists and should branch to the
00827       // cleanup, but we're not supposed to branch through to the next
00828       // cleanup.
00829       } else if (HasFallthrough && FallthroughDest) {
00830         assert(!FallthroughIsBranchThrough);
00831         EmitBlock(FallthroughDest);
00832 
00833       // Case 3: a fallthrough source exists and should branch to the
00834       // cleanup and then through to the next.
00835       } else if (HasFallthrough) {
00836         // Everything is already set up for this.
00837 
00838       // Case 4: no fallthrough source exists.
00839       } else {
00840         Builder.ClearInsertionPoint();
00841       }
00842 
00843       // VI.  Assorted cleaning.
00844 
00845       // Check whether we can merge NormalEntry into a single predecessor.
00846       // This might invalidate (non-IR) pointers to NormalEntry.
00847       llvm::BasicBlock *NewNormalEntry =
00848         SimplifyCleanupEntry(*this, NormalEntry);
00849 
00850       // If it did invalidate those pointers, and NormalEntry was the same
00851       // as NormalExit, go back and patch up the fixups.
00852       if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
00853         for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
00854                I < E; ++I)
00855           EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
00856     }
00857   }
00858 
00859   assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
00860 
00861   // Emit the EH cleanup if required.
00862   if (RequiresEHCleanup) {
00863     CGDebugInfo *DI = getDebugInfo();
00864     SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
00865     if (DI)
00866       DI->EmitLocation(Builder, CurEHLocation);
00867 
00868     CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
00869 
00870     EmitBlock(EHEntry);
00871 
00872     // We only actually emit the cleanup code if the cleanup is either
00873     // active or was used before it was deactivated.
00874     if (EHActiveFlag || IsActive) {
00875 
00876       cleanupFlags.setIsForEHCleanup();
00877       EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
00878     }
00879 
00880     Builder.CreateBr(getEHDispatchBlock(EHParent));
00881 
00882     Builder.restoreIP(SavedIP);
00883 
00884     SimplifyCleanupEntry(*this, EHEntry);
00885   }
00886 }
00887 
00888 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
00889 /// specified destination obviously has no cleanups to run.  'false' is always
00890 /// a conservatively correct answer for this method.
00891 bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
00892   assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
00893          && "stale jump destination");
00894   
00895   // Calculate the innermost active normal cleanup.
00896   EHScopeStack::stable_iterator TopCleanup =
00897     EHStack.getInnermostActiveNormalCleanup();
00898   
00899   // If we're not in an active normal cleanup scope, or if the
00900   // destination scope is within the innermost active normal cleanup
00901   // scope, we don't need to worry about fixups.
00902   if (TopCleanup == EHStack.stable_end() ||
00903       TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
00904     return true;
00905 
00906   // Otherwise, we might need some cleanups.
00907   return false;
00908 }
00909 
00910 
00911 /// Terminate the current block by emitting a branch which might leave
00912 /// the current cleanup-protected scope.  The target scope may not yet
00913 /// be known, in which case this will require a fixup.
00914 ///
00915 /// As a side-effect, this method clears the insertion point.
00916 void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
00917   assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
00918          && "stale jump destination");
00919 
00920   if (!HaveInsertPoint())
00921     return;
00922 
00923   // Create the branch.
00924   llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
00925 
00926   // Calculate the innermost active normal cleanup.
00927   EHScopeStack::stable_iterator
00928     TopCleanup = EHStack.getInnermostActiveNormalCleanup();
00929 
00930   // If we're not in an active normal cleanup scope, or if the
00931   // destination scope is within the innermost active normal cleanup
00932   // scope, we don't need to worry about fixups.
00933   if (TopCleanup == EHStack.stable_end() ||
00934       TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
00935     Builder.ClearInsertionPoint();
00936     return;
00937   }
00938 
00939   // If we can't resolve the destination cleanup scope, just add this
00940   // to the current cleanup scope as a branch fixup.
00941   if (!Dest.getScopeDepth().isValid()) {
00942     BranchFixup &Fixup = EHStack.addBranchFixup();
00943     Fixup.Destination = Dest.getBlock();
00944     Fixup.DestinationIndex = Dest.getDestIndex();
00945     Fixup.InitialBranch = BI;
00946     Fixup.OptimisticBranchBlock = nullptr;
00947 
00948     Builder.ClearInsertionPoint();
00949     return;
00950   }
00951 
00952   // Otherwise, thread through all the normal cleanups in scope.
00953 
00954   // Store the index at the start.
00955   llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
00956   new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
00957 
00958   // Adjust BI to point to the first cleanup block.
00959   {
00960     EHCleanupScope &Scope =
00961       cast<EHCleanupScope>(*EHStack.find(TopCleanup));
00962     BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
00963   }
00964 
00965   // Add this destination to all the scopes involved.
00966   EHScopeStack::stable_iterator I = TopCleanup;
00967   EHScopeStack::stable_iterator E = Dest.getScopeDepth();
00968   if (E.strictlyEncloses(I)) {
00969     while (true) {
00970       EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
00971       assert(Scope.isNormalCleanup());
00972       I = Scope.getEnclosingNormalCleanup();
00973 
00974       // If this is the last cleanup we're propagating through, tell it
00975       // that there's a resolved jump moving through it.
00976       if (!E.strictlyEncloses(I)) {
00977         Scope.addBranchAfter(Index, Dest.getBlock());
00978         break;
00979       }
00980 
00981       // Otherwise, tell the scope that there's a jump propoagating
00982       // through it.  If this isn't new information, all the rest of
00983       // the work has been done before.
00984       if (!Scope.addBranchThrough(Dest.getBlock()))
00985         break;
00986     }
00987   }
00988   
00989   Builder.ClearInsertionPoint();
00990 }
00991 
00992 static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
00993                                   EHScopeStack::stable_iterator C) {
00994   // If we needed a normal block for any reason, that counts.
00995   if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
00996     return true;
00997 
00998   // Check whether any enclosed cleanups were needed.
00999   for (EHScopeStack::stable_iterator
01000          I = EHStack.getInnermostNormalCleanup();
01001          I != C; ) {
01002     assert(C.strictlyEncloses(I));
01003     EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
01004     if (S.getNormalBlock()) return true;
01005     I = S.getEnclosingNormalCleanup();
01006   }
01007 
01008   return false;
01009 }
01010 
01011 static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
01012                               EHScopeStack::stable_iterator cleanup) {
01013   // If we needed an EH block for any reason, that counts.
01014   if (EHStack.find(cleanup)->hasEHBranches())
01015     return true;
01016 
01017   // Check whether any enclosed cleanups were needed.
01018   for (EHScopeStack::stable_iterator
01019          i = EHStack.getInnermostEHScope(); i != cleanup; ) {
01020     assert(cleanup.strictlyEncloses(i));
01021 
01022     EHScope &scope = *EHStack.find(i);
01023     if (scope.hasEHBranches())
01024       return true;
01025 
01026     i = scope.getEnclosingEHScope();
01027   }
01028 
01029   return false;
01030 }
01031 
01032 enum ForActivation_t {
01033   ForActivation,
01034   ForDeactivation
01035 };
01036 
01037 /// The given cleanup block is changing activation state.  Configure a
01038 /// cleanup variable if necessary.
01039 ///
01040 /// It would be good if we had some way of determining if there were
01041 /// extra uses *after* the change-over point.
01042 static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
01043                                         EHScopeStack::stable_iterator C,
01044                                         ForActivation_t kind,
01045                                         llvm::Instruction *dominatingIP) {
01046   EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
01047 
01048   // We always need the flag if we're activating the cleanup in a
01049   // conditional context, because we have to assume that the current
01050   // location doesn't necessarily dominate the cleanup's code.
01051   bool isActivatedInConditional =
01052     (kind == ForActivation && CGF.isInConditionalBranch());
01053 
01054   bool needFlag = false;
01055 
01056   // Calculate whether the cleanup was used:
01057 
01058   //   - as a normal cleanup
01059   if (Scope.isNormalCleanup() &&
01060       (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
01061     Scope.setTestFlagInNormalCleanup();
01062     needFlag = true;
01063   }
01064 
01065   //  - as an EH cleanup
01066   if (Scope.isEHCleanup() &&
01067       (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
01068     Scope.setTestFlagInEHCleanup();
01069     needFlag = true;
01070   }
01071 
01072   // If it hasn't yet been used as either, we're done.
01073   if (!needFlag) return;
01074 
01075   llvm::AllocaInst *var = Scope.getActiveFlag();
01076   if (!var) {
01077     var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactive");
01078     Scope.setActiveFlag(var);
01079 
01080     assert(dominatingIP && "no existing variable and no dominating IP!");
01081 
01082     // Initialize to true or false depending on whether it was
01083     // active up to this point.
01084     llvm::Value *value = CGF.Builder.getInt1(kind == ForDeactivation);
01085 
01086     // If we're in a conditional block, ignore the dominating IP and
01087     // use the outermost conditional branch.
01088     if (CGF.isInConditionalBranch()) {
01089       CGF.setBeforeOutermostConditional(value, var);
01090     } else {
01091       new llvm::StoreInst(value, var, dominatingIP);
01092     }
01093   }
01094 
01095   CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
01096 }
01097 
01098 /// Activate a cleanup that was created in an inactivated state.
01099 void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
01100                                            llvm::Instruction *dominatingIP) {
01101   assert(C != EHStack.stable_end() && "activating bottom of stack?");
01102   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
01103   assert(!Scope.isActive() && "double activation");
01104 
01105   SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
01106 
01107   Scope.setActive(true);
01108 }
01109 
01110 /// Deactive a cleanup that was created in an active state.
01111 void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
01112                                              llvm::Instruction *dominatingIP) {
01113   assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
01114   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
01115   assert(Scope.isActive() && "double deactivation");
01116 
01117   // If it's the top of the stack, just pop it.
01118   if (C == EHStack.stable_begin()) {
01119     // If it's a normal cleanup, we need to pretend that the
01120     // fallthrough is unreachable.
01121     CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
01122     PopCleanupBlock();
01123     Builder.restoreIP(SavedIP);
01124     return;
01125   }
01126 
01127   // Otherwise, follow the general case.
01128   SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
01129 
01130   Scope.setActive(false);
01131 }
01132 
01133 llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
01134   if (!NormalCleanupDest)
01135     NormalCleanupDest =
01136       CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
01137   return NormalCleanupDest;
01138 }
01139 
01140 /// Emits all the code to cause the given temporary to be cleaned up.
01141 void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
01142                                        QualType TempType,
01143                                        llvm::Value *Ptr) {
01144   pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
01145               /*useEHCleanup*/ true);
01146 }