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