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