clang 19.0.0git
CGCleanup.cpp
Go to the documentation of this file.
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
23using namespace clang;
24using namespace CodeGen;
25
27 if (rv.isScalar())
29 if (rv.isAggregate())
31 return true;
32}
33
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());
51 return saved_type(
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.
61 switch (K) {
62 case ScalarLiteral:
63 case ScalarAddress:
64 return RValue::get(DominatingLLVMValue::restore(CGF, Vals.first));
65 case AggregateLiteral:
66 case AggregateAddress:
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.
80char *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
111void EHScopeStack::deallocate(size_t Size) {
112 StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
113}
114
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
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
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
152void *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
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())
189
190 return Scope->getCleanupBuffer();
191}
192
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
215 }
216}
217
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
227 assert(!empty() && "popping exception stack when not empty");
228
229 EHFilterScope &filter = cast<EHFilterScope>(*begin());
231
232 InnermostEHScope = filter.getEnclosingEHScope();
233}
234
235EHCatchScope *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
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.
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
269 // Create a variable to decide whether the cleanup needs to be run.
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
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
293void EHScopeStack::Cleanup::anchor() {}
294
295static 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
302static 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.
314 llvm::SwitchInst *Switch,
315 llvm::BasicBlock *CleanupEntry) {
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) {
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.
351static 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());
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
371void 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.
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.
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
498static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
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.
514static 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
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
573static 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.
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.
637void 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()
648 Address EHActiveFlag =
649 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
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) {
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());
737 CleanupBufferStack[8 * sizeof(void *)];
738 std::unique_ptr<char[]> CleanupBufferHeap;
739 size_t CleanupSize = Scope.getCleanupSize();
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 }
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
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;
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.
1045bool 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.
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.
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.
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 {
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
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.
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
1165static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
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.
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
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.
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.
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.
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
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.
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)
1314 llvm::FunctionCallee &SehCppScope) {
1315 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
1316 assert(CGF.Builder.GetInsertBlock() && InvokeDest);
1317 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
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
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"
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
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
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}
#define V(N, I)
Definition: ASTContext.h:3284
static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack, EHScopeStack::stable_iterator C)
Definition: CGCleanup.cpp:1146
static void EmitSehScope(CodeGenFunction &CGF, llvm::FunctionCallee &SehCppScope)
Definition: CGCleanup.cpp:1313
static llvm::BasicBlock * CreateNormalEntry(CodeGenFunction &CGF, EHCleanupScope &Scope)
Definition: CGCleanup.cpp:498
ForActivation_t
Definition: CGCleanup.cpp:1186
@ ForActivation
Definition: CGCleanup.cpp:1187
@ ForDeactivation
Definition: CGCleanup.cpp:1188
static void EmitCleanup(CodeGenFunction &CGF, EHScopeStack::Cleanup *Fn, EHScopeStack::Cleanup::Flags flags, Address ActiveFlag)
Definition: CGCleanup.cpp:548
static llvm::LoadInst * createLoadInstBefore(Address addr, const Twine &name, llvm::Instruction *beforeInst, CodeGenFunction &CGF)
Definition: CGCleanup.cpp:302
static void destroyOptimisticNormalEntry(CodeGenFunction &CGF, EHCleanupScope &scope)
We don't need a normal entry block for the given cleanup.
Definition: CGCleanup.cpp:597
static void SetupCleanupBlockActivation(CodeGenFunction &CGF, EHScopeStack::stable_iterator C, ForActivation_t kind, llvm::Instruction *dominatingIP)
The given cleanup block is changing activation state.
Definition: CGCleanup.cpp:1196
static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit, llvm::BasicBlock *From, llvm::BasicBlock *To)
Definition: CGCleanup.cpp:573
static void createStoreInstBefore(llvm::Value *value, Address addr, llvm::Instruction *beforeInst, CodeGenFunction &CGF)
Definition: CGCleanup.cpp:295
static void ResolveAllBranchFixups(CodeGenFunction &CGF, llvm::SwitchInst *Switch, llvm::BasicBlock *CleanupEntry)
All the branch fixups on the EH stack have propagated out past the outermost normal cleanup; resolve ...
Definition: CGCleanup.cpp:313
static bool IsUsedAsEHCleanup(EHScopeStack &EHStack, EHScopeStack::stable_iterator cleanup)
Definition: CGCleanup.cpp:1165
static llvm::BasicBlock * SimplifyCleanupEntry(CodeGenFunction &CGF, llvm::BasicBlock *Entry)
Attempts to reduce a cleanup's entry block to a fallthrough.
Definition: CGCleanup.cpp:514
static llvm::SwitchInst * TransitionToCleanupSwitch(CodeGenFunction &CGF, llvm::BasicBlock *Block)
Transitions the terminator of the given exit-block of a cleanup to be a cleanup switch.
Definition: CGCleanup.cpp:351
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1109
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Represents a C++ temporary.
Definition: ExprCXX.h:1453
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition: CharUnits.h:189
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:111
static Address invalid()
Definition: Address.h:153
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:220
CharUnits getAlignment() const
Definition: Address.h:166
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:184
bool isValid() const
Definition: Address.h:154
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
SmallVector< llvm::OperandBundleDef, 1 > getBundlesForFunclet(llvm::Value *Callee)
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, std::initializer_list< llvm::Value ** > ValuesToReload={})
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
llvm::BasicBlock * getUnreachableBlock()
const TargetInfo & getTarget() const
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
void initFullExprCleanupWithFlag(RawAddress ActiveFlag)
llvm::BasicBlock * getInvokeDest()
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
void setBeforeOutermostConditional(llvm::Value *value, Address addr, CodeGenFunction &CGF)
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
ActivateCleanupBlock - Activates an initially-inactive cleanup.
RawAddress NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const
isObviouslyBranchWithoutCleanups - Return true if a branch to the specified destination obviously has...
llvm::Instruction * CurrentFuncletPad
void ResolveBranchFixups(llvm::BasicBlock *Target)
A scope which attempts to handle some, possibly all, types of exceptions.
Definition: CGCleanup.h:155
static size_t getSizeForNumHandlers(unsigned N)
Definition: CGCleanup.h:185
A cleanup scope which generates the cleanup blocks lazily.
Definition: CGCleanup.h:240
static size_t getSizeForCleanupSize(size_t Size)
Gets the size required for a lazy cleanup scope with the given cleanup-data requirements.
Definition: CGCleanup.h:287
llvm::BasicBlock * getNormalBlock() const
Definition: CGCleanup.h:321
An exceptions scope which filters exceptions thrown through it.
Definition: CGCleanup.h:446
static size_t getSizeForNumFilters(unsigned numFilters)
Definition: CGCleanup.h:465
unsigned getNumFilters() const
Definition: CGCleanup.h:469
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
virtual void Emit(CodeGenFunction &CGF, Flags flags)=0
Emit the cleanup.
A non-stable pointer into the scope stack.
Definition: CGCleanup.h:500
A saved depth on the scope stack.
Definition: EHScopeStack.h:101
bool encloses(stable_iterator I) const
Returns true if this scope encloses I.
Definition: EHScopeStack.h:118
bool strictlyEncloses(stable_iterator I) const
Returns true if this scope strictly encloses I: that is, if it encloses I and is not I.
Definition: EHScopeStack.h:124
A stack of scopes which respond to exceptions, including cleanups and catch blocks.
Definition: EHScopeStack.h:94
class EHFilterScope * pushFilter(unsigned NumFilters)
Push an exceptions filter on the stack.
Definition: CGCleanup.cpp:218
BranchFixup & getBranchFixup(unsigned I)
Definition: EHScopeStack.h:417
stable_iterator getInnermostNormalCleanup() const
Returns the innermost normal cleanup on the stack, or stable_end() if there are no normal cleanups.
Definition: EHScopeStack.h:370
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:393
unsigned getNumBranchFixups() const
Definition: EHScopeStack.h:416
void popCleanup()
Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
Definition: CGCleanup.cpp:193
stable_iterator getInnermostEHScope() const
Definition: EHScopeStack.h:375
bool containsOnlyLifetimeMarkers(stable_iterator Old) const
Definition: CGCleanup.cpp:115
bool empty() const
Determines whether the exception-scopes stack is empty.
Definition: EHScopeStack.h:359
void popFilter()
Pops an exceptions filter off the stack.
Definition: CGCleanup.cpp:226
iterator begin() const
Returns an iterator pointing to the innermost EH scope.
Definition: CGCleanup.h:560
class EHCatchScope * pushCatch(unsigned NumHandlers)
Push a set of catch handlers on the stack.
Definition: CGCleanup.cpp:235
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
Definition: CGCleanup.h:584
void popNullFixups()
Pops lazily-removed fixups from the end of the list.
Definition: CGCleanup.cpp:254
bool hasNormalCleanups() const
Determines whether there are any normal cleanups on the stack.
Definition: EHScopeStack.h:364
stable_iterator getInnermostActiveNormalCleanup() const
Definition: CGCleanup.cpp:141
stable_iterator stabilize(iterator it) const
Translates an iterator into a stable_iterator.
Definition: CGCleanup.h:591
static stable_iterator stable_end()
Create a stable reference to the bottom of the EH stack.
Definition: EHScopeStack.h:398
void clearFixups()
Clears the branch-fixups list.
Definition: EHScopeStack.h:429
void pushTerminate()
Push a terminate handler on the stack.
Definition: CGCleanup.cpp:243
A protected scope for zero-cost EH handling.
Definition: CGCleanup.h:42
EHScopeStack::stable_iterator getEnclosingEHScope() const
Definition: CGCleanup.h:145
bool hasEHBranches() const
Definition: CGCleanup.h:139
An exceptions scope which calls std::terminate if any exception reaches it.
Definition: CGCleanup.h:488
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:41
bool isScalar() const
Definition: CGValue.h:63
static RValue get(llvm::Value *V)
Definition: CGValue.h:97
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition: CGValue.h:124
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:107
bool isAggregate() const
Definition: CGValue.h:65
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:82
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:70
bool isComplex() const
Definition: CGValue.h:64
bool isVolatileQualified() const
Definition: CGValue.h:67
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition: CGValue.h:77
An abstract representation of an aligned address.
Definition: Address.h:41
llvm::Value * getPointer() const
Definition: Address.h:65
static RawAddress invalid()
Definition: Address.h:60
A (possibly-)qualified type.
Definition: Type.h:940
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1307
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1391
The JSON file list parser is used to communicate input to InstallAPI.
unsigned DestinationIndex
The destination index value.
Definition: EHScopeStack.h:49
llvm::BasicBlock * Destination
The ultimate destination of the branch.
Definition: EHScopeStack.h:46
llvm::BasicBlock * OptimisticBranchBlock
The block containing the terminator which needs to be modified into a switch if this fixup is resolve...
Definition: EHScopeStack.h:40
llvm::BranchInst * InitialBranch
The initial branch of the fixup.
Definition: EHScopeStack.h:52
static llvm::Value * restore(CodeGenFunction &CGF, saved_type value)
static saved_type save(CodeGenFunction &CGF, llvm::Value *value)
static bool needsSaving(llvm::Value *value)
Answer whether the given value needs extra work to be saved.
A metaprogramming class for ensuring that a value will dominate an arbitrary position in a function.
Definition: EHScopeStack.h:65
The exceptions personality for a function.
Definition: CGCleanup.h:597
bool isMSVCXXPersonality() const
Definition: CGCleanup.h:640
static const EHPersonality & get(CodeGenModule &CGM, const FunctionDecl *FD)
bool usesFuncletPads() const
Does this personality use landingpads or the family of pad instructions designed to form funclets?
Definition: CGCleanup.h:629
bool isMSVCPersonality() const
Definition: CGCleanup.h:633