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