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