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