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