clang 24.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()) {
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(DominatingValue<Address>::save(CGF, V),
53 ? 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.
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));
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 this is anything other than a lifetime marker or fake use cleanup,
120 // then the scope stack does not contain only noop cleanups.
121 if (!cleanup)
122 return false;
123 if (!cleanup->isLifetimeMarker() && !cleanup->isFakeUse())
124 return false;
125 }
126
127 return true;
128}
129
131 for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {
132 // Skip lifetime markers.
133 if (auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si)))
134 if (cleanup->isLifetimeMarker()) {
135 si = cleanup->getEnclosingEHScope();
136 continue;
137 }
138 return true;
139 }
140
141 return false;
142}
143
147 si != se; ) {
148 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
149 if (cleanup.isActive()) return si;
150 si = cleanup.getEnclosingNormalCleanup();
151 }
152 return stable_end();
153}
154
155
156void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
157 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
158 bool IsNormalCleanup = Kind & NormalCleanup;
159 bool IsEHCleanup = Kind & EHCleanup;
160 bool IsLifetimeMarker = Kind & LifetimeMarker;
161 bool IsFakeUse = Kind & FakeUse;
162 bool IsSEHFinallyCleanup = Kind & SEHFinallyCleanup;
163 bool IsStackRestore = Kind & StackRestore;
164
165 // Per C++ [except.terminate], it is implementation-defined whether none,
166 // some, or all cleanups are called before std::terminate. Thus, when
167 // terminate is the current EH scope, we may skip adding any EH cleanup
168 // scopes.
169 if (InnermostEHScope != stable_end() &&
170 find(InnermostEHScope)->getKind() == EHScope::Terminate)
171 IsEHCleanup = false;
172
173 EHCleanupScope *Scope =
174 new (Buffer) EHCleanupScope(IsNormalCleanup,
175 IsEHCleanup,
176 Size,
177 BranchFixups.size(),
178 InnermostNormalCleanup,
179 InnermostEHScope);
180 if (IsNormalCleanup)
181 InnermostNormalCleanup = stable_begin();
182 if (IsEHCleanup)
183 InnermostEHScope = stable_begin();
184 if (IsLifetimeMarker)
185 Scope->setLifetimeMarker();
186 if (IsFakeUse)
187 Scope->setFakeUse();
188 if (IsSEHFinallyCleanup)
189 Scope->setSEHFinallyCleanup();
190 if (IsStackRestore)
191 Scope->setStackRestore();
192
193 // With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup
194 // If exceptions are disabled/ignored and SEH is not in use, then there is no
195 // invoke destination. SEH "works" even if exceptions are off. In practice,
196 // this means that C++ destructors and other EH cleanups don't run, which is
197 // consistent with MSVC's behavior, except in the presence of -EHa.
198 // Check getInvokeDest() to generate llvm.seh.scope.begin() as needed.
199 if (CGF->getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&
200 !IsSEHFinallyCleanup && CGF->getTarget().getCXXABI().isMicrosoft() &&
201 CGF->getInvokeDest())
202 CGF->EmitSehCppScopeBegin();
203
204 return Scope->getCleanupBuffer();
205}
206
208 assert(!empty() && "popping exception stack when not empty");
209
210 assert(isa<EHCleanupScope>(*begin()));
211 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
212 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
213 InnermostEHScope = Cleanup.getEnclosingEHScope();
214 deallocate(Cleanup.getAllocatedSize());
215
216 // Destroy the cleanup.
217 Cleanup.Destroy();
218
219 // Check whether we can shrink the branch-fixups stack.
220 if (!BranchFixups.empty()) {
221 // If we no longer have any normal cleanups, all the fixups are
222 // complete.
223 if (!hasNormalCleanups())
224 BranchFixups.clear();
225
226 // Otherwise we can still trim out unnecessary nulls.
227 else
229 }
230}
231
232EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
233 assert(getInnermostEHScope() == stable_end());
234 char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
235 EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
236 InnermostEHScope = stable_begin();
237 return filter;
238}
239
241 assert(!empty() && "popping exception stack when not empty");
242
243 EHFilterScope &filter = cast<EHFilterScope>(*begin());
245
246 InnermostEHScope = filter.getEnclosingEHScope();
247}
248
249EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
250 char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
251 EHCatchScope *scope =
252 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
253 InnermostEHScope = stable_begin();
254 return scope;
255}
256
258 char *Buffer = allocate(EHTerminateScope::getSize());
259 new (Buffer) EHTerminateScope(InnermostEHScope);
260 InnermostEHScope = stable_begin();
261}
262
263/// Remove any 'null' fixups on the stack. However, we can't pop more
264/// fixups than the fixup depth on the innermost normal cleanup, or
265/// else fixups that we try to add to that cleanup will end up in the
266/// wrong place. We *could* try to shrink fixup depths, but that's
267/// actually a lot of work for little benefit.
269 // We expect this to only be called when there's still an innermost
270 // normal cleanup; otherwise there really shouldn't be any fixups.
271 assert(hasNormalCleanups());
272
273 EHScopeStack::iterator it = find(InnermostNormalCleanup);
274 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
275 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
276
277 while (BranchFixups.size() > MinSize &&
278 BranchFixups.back().Destination == nullptr)
279 BranchFixups.pop_back();
280}
281
283 // Create a variable to decide whether the cleanup needs to be run.
285 Builder.getInt1Ty(), CharUnits::One(), "cleanup.cond");
286
287 // Initialize it to false at a site that's guaranteed to be run
288 // before each evaluation.
289 setBeforeOutermostConditional(Builder.getFalse(), active, *this);
290
291 // Initialize it to true at the current location.
292 Builder.CreateStore(Builder.getTrue(), active);
293
294 return active;
295}
296
298 // Set that as the active flag in the cleanup.
299 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
300 assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
301 cleanup.setActiveFlag(ActiveFlag);
302
303 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
304 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
305}
306
307void EHScopeStack::Cleanup::anchor() {}
308
309static void createStoreInstBefore(llvm::Value *value, Address addr,
310 llvm::BasicBlock::iterator beforeInst,
311 CodeGenFunction &CGF) {
312 auto store = new llvm::StoreInst(value, addr.emitRawPointer(CGF), beforeInst);
313 store->setAlignment(addr.getAlignment().getAsAlign());
314}
315
316static llvm::LoadInst *
317createLoadInstBefore(Address addr, const Twine &name,
318 llvm::BasicBlock::iterator beforeInst,
319 CodeGenFunction &CGF) {
320 return new llvm::LoadInst(addr.getElementType(), addr.emitRawPointer(CGF),
321 name, false, addr.getAlignment().getAsAlign(),
322 beforeInst);
323}
324
325static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
326 CodeGenFunction &CGF) {
327 return new llvm::LoadInst(addr.getElementType(), addr.emitRawPointer(CGF),
328 name, false, addr.getAlignment().getAsAlign());
329}
330
331/// All the branch fixups on the EH stack have propagated out past the
332/// outermost normal cleanup; resolve them all by adding cases to the
333/// given switch instruction.
335 llvm::SwitchInst *Switch,
336 llvm::BasicBlock *CleanupEntry) {
338
339 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
340 // Skip this fixup if its destination isn't set.
341 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
342 if (Fixup.Destination == nullptr) continue;
343
344 // If there isn't an OptimisticBranchBlock, then InitialBranch is
345 // still pointing directly to its destination; forward it to the
346 // appropriate cleanup entry. This is required in the specific
347 // case of
348 // { std::string s; goto lbl; }
349 // lbl:
350 // i.e. where there's an unresolved fixup inside a single cleanup
351 // entry which we're currently popping.
352 if (Fixup.OptimisticBranchBlock == nullptr) {
355 Fixup.InitialBranch->getIterator(), CGF);
356 Fixup.InitialBranch->setSuccessor(CleanupEntry);
357 }
358
359 // Don't add this case to the switch statement twice.
360 if (!CasesAdded.insert(Fixup.Destination).second)
361 continue;
362
363 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
364 Fixup.Destination);
365 }
366
367 CGF.EHStack.clearFixups();
368}
369
370/// Transitions the terminator of the given exit-block of a cleanup to
371/// be a cleanup switch.
372static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
373 llvm::BasicBlock *Block) {
374 // If it's a branch, turn it into a switch whose default
375 // destination is its original target.
376 llvm::Instruction *Term = Block->getTerminator();
377
378 if (llvm::UncondBrInst *Br = dyn_cast<llvm::UncondBrInst>(Term)) {
380 "cleanup.dest", Term->getIterator(), CGF);
381 llvm::SwitchInst *Switch =
382 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
383 Br->eraseFromParent();
384 return Switch;
385 } else {
386 return cast<llvm::SwitchInst>(Term);
387 }
388}
389
391 assert(Block && "resolving a null target block");
392 if (!EHStack.getNumBranchFixups()) return;
393
394 assert(EHStack.hasNormalCleanups() &&
395 "branch fixups exist with no normal cleanups on stack");
396
397 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
398 bool ResolvedAny = false;
399
400 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
401 // Skip this fixup if its destination doesn't match.
402 BranchFixup &Fixup = EHStack.getBranchFixup(I);
403 if (Fixup.Destination != Block) continue;
404
405 Fixup.Destination = nullptr;
406 ResolvedAny = true;
407
408 // If it doesn't have an optimistic branch block, LatestBranch is
409 // already pointing to the right place.
410 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
411 if (!BranchBB)
412 continue;
413
414 // Don't process the same optimistic branch block twice.
415 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
416 continue;
417
418 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
419
420 // Add a case to the switch.
421 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
422 }
423
424 if (ResolvedAny)
425 EHStack.popNullFixups();
426}
427
428/// Pops cleanup blocks until the given savepoint is reached.
431 std::initializer_list<llvm::Value **> ValuesToReload) {
432 assert(Old.isValid());
433
434 bool HadBranches = false;
435 while (EHStack.stable_begin() != Old) {
437 HadBranches |= Scope.hasBranches();
438
439 // As long as Old strictly encloses the scope's enclosing normal
440 // cleanup, we're going to emit another normal cleanup which
441 // fallthrough can propagate through.
442 bool FallThroughIsBranchThrough =
443 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
444
445 PopCleanupBlock(FallThroughIsBranchThrough);
446 }
447
448 // If we didn't have any branches, the insertion point before cleanups must
449 // dominate the current insertion point and we don't need to reload any
450 // values.
451 if (!HadBranches)
452 return;
453
454 // Spill and reload all values that the caller wants to be live at the current
455 // insertion point.
456 for (llvm::Value **ReloadedValue : ValuesToReload) {
457 auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
458 if (!Inst)
459 continue;
460
461 // Don't spill static allocas, they dominate all cleanups. These are created
462 // by binding a reference to a local variable or temporary.
463 auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
464 if (AI && AI->isStaticAlloca())
465 continue;
466
467 Address Tmp =
468 CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
469
470 // Find an insertion point after Inst and spill it to the temporary.
471 llvm::BasicBlock::iterator InsertBefore;
472 if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
473 InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
474 else
475 InsertBefore = std::next(Inst->getIterator());
476 CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
477
478 // Reload the value at the current insertion point.
479 *ReloadedValue = Builder.CreateLoad(Tmp);
480 }
481}
482
483/// Pops cleanup blocks until the given savepoint is reached, then add the
484/// cleanups from the given savepoint in the lifetime-extended cleanups stack.
486 EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
487 std::initializer_list<llvm::Value **> ValuesToReload) {
488 PopCleanupBlocks(Old, ValuesToReload);
489
490 // Move our deferred cleanups onto the EH stack.
491 for (size_t I = OldLifetimeExtendedSize,
492 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
493 // Alignment should be guaranteed by the vptrs in the individual cleanups.
494 assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
495 "misaligned cleanup stack entry");
496
498 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
500 I += sizeof(Header);
501
502 EHStack.pushCopyOfCleanup(Header.getKind(),
504 Header.getSize());
505 I += Header.getSize();
506
507 if (Header.isConditional()) {
508 RawAddress ActiveFlag =
509 reinterpret_cast<RawAddress &>(LifetimeExtendedCleanupStack[I]);
510 initFullExprCleanupWithFlag(ActiveFlag);
511 I += sizeof(ActiveFlag);
512 }
513 }
514 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
515}
516
517static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
519 assert(Scope.isNormalCleanup());
520 llvm::BasicBlock *Entry = Scope.getNormalBlock();
521 if (!Entry) {
522 Entry = CGF.createBasicBlock("cleanup");
523 Scope.setNormalBlock(Entry);
524 }
525 return Entry;
526}
527
528/// Attempts to reduce a cleanup's entry block to a fallthrough. This
529/// is basically llvm::MergeBlockIntoPredecessor, except
530/// simplified/optimized for the tighter constraints on cleanup blocks.
531///
532/// Returns the new block, whatever it is.
533static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
534 llvm::BasicBlock *Entry) {
535 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
536 if (!Pred) return Entry;
537
538 llvm::UncondBrInst *Br = dyn_cast<llvm::UncondBrInst>(Pred->getTerminator());
539 if (!Br)
540 return Entry;
541 assert(Br->getSuccessor() == Entry);
542
543 // If we were previously inserting at the end of the cleanup entry
544 // block, we'll need to continue inserting at the end of the
545 // predecessor.
546 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
547 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
548
549 // Kill the branch.
550 Br->eraseFromParent();
551
552 // Replace all uses of the entry with the predecessor, in case there
553 // are phis in the cleanup.
554 Entry->replaceAllUsesWith(Pred);
555
556 // Merge the blocks.
557 Pred->splice(Pred->end(), Entry);
558
559 // Kill the entry block.
560 Entry->eraseFromParent();
561
562 if (WasInsertBlock)
563 CGF.Builder.SetInsertPoint(Pred);
564
565 return Pred;
566}
567
569 EHScopeStack::Cleanup *Fn,
570 EHScopeStack::Cleanup::Flags flags,
571 Address ActiveFlag) {
572 // If there's an active flag, load it and skip the cleanup if it's
573 // false.
574 llvm::BasicBlock *ContBB = nullptr;
575 if (ActiveFlag.isValid()) {
576 ContBB = CGF.createBasicBlock("cleanup.done");
577 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
578 llvm::Value *IsActive
579 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
580 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
581 CGF.EmitBlock(CleanupBB);
582 }
583
584 // Ask the cleanup to emit itself.
585 Fn->Emit(CGF, flags);
586 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
587
588 // Emit the continuation block if there was an active flag.
589 if (ActiveFlag.isValid())
590 CGF.EmitBlock(ContBB);
591}
592
593static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
594 llvm::BasicBlock *From,
595 llvm::BasicBlock *To) {
596 // Exit is the exit block of a cleanup, so it always terminates in
597 // an unconditional branch or a switch.
598 llvm::Instruction *Term = Exit->getTerminator();
599
600 if (llvm::UncondBrInst *Br = dyn_cast<llvm::UncondBrInst>(Term)) {
601 assert(Br->getSuccessor() == From);
602 Br->setSuccessor(To);
603 } else {
604 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
605 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
606 if (Switch->getSuccessor(I) == From)
607 Switch->setSuccessor(I, To);
608 }
609}
610
611/// We don't need a normal entry block for the given cleanup.
612/// Optimistic fixup branches can cause these blocks to come into
613/// existence anyway; if so, destroy it.
614///
615/// The validity of this transformation is very much specific to the
616/// exact ways in which we form branches to cleanup entries.
618 EHCleanupScope &scope) {
619 llvm::BasicBlock *entry = scope.getNormalBlock();
620 if (!entry) return;
621
622 // Replace all the uses with unreachable.
623 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
624 for (llvm::BasicBlock::use_iterator
625 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
626 llvm::Use &use = *i;
627 ++i;
628
629 use.set(unreachableBB);
630
631 // The only uses should be fixup switches.
632 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
633 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
634 // Replace the switch with a branch.
635 llvm::UncondBrInst::Create(si->case_begin()->getCaseSuccessor(),
636 si->getIterator());
637
638 // The switch operand is a load from the cleanup-dest alloca.
639 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
640
641 // Destroy the switch.
642 si->eraseFromParent();
643
644 // Destroy the load.
645 assert(condition->getOperand(0) == CGF.NormalCleanupDest.getPointer());
646 assert(condition->use_empty());
647 condition->eraseFromParent();
648 }
649 }
650
651 assert(entry->use_empty());
652 delete entry;
653}
654
655/// Pops a cleanup block. If the block includes a normal cleanup, the
656/// current insertion point is threaded through the cleanup, as are
657/// any branch fixups on the cleanup.
658void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough,
659 bool ForDeactivation) {
660 assert(!EHStack.empty() && "cleanup stack is empty!");
661 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
663 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
664
665 // If we are deactivating a normal cleanup, we need to pretend that the
666 // fallthrough is unreachable. We restore this IP before returning.
667 CGBuilderTy::InsertPoint NormalDeactivateOrigIP;
668 if (ForDeactivation && (Scope.isNormalCleanup() || !getLangOpts().EHAsynch)) {
669 NormalDeactivateOrigIP = Builder.saveAndClearIP();
670 }
671 // Remember activation information.
672 bool IsActive = Scope.isActive();
673 Address NormalActiveFlag =
674 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
676 Address EHActiveFlag =
677 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
679
680 // Check whether we need an EH cleanup. This is only true if we've
681 // generated a lazy EH cleanup block.
682 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
683 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
684 bool RequiresEHCleanup = (EHEntry != nullptr);
685 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
686
687 // Check the three conditions which might require a normal cleanup:
688
689 // - whether there are branch fix-ups through this cleanup
690 unsigned FixupDepth = Scope.getFixupDepth();
691 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
692
693 // - whether there are branch-throughs or branch-afters
694 bool HasExistingBranches = Scope.hasBranches();
695
696 // - whether there's a fallthrough
697 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
698 bool HasFallthrough =
699 FallthroughSource != nullptr && (IsActive || HasExistingBranches);
700
701 // Branch-through fall-throughs leave the insertion point set to the
702 // end of the last cleanup, which points to the current scope. The
703 // rest of IR gen doesn't need to worry about this; it only happens
704 // during the execution of PopCleanupBlocks().
705 bool HasPrebranchedFallthrough =
706 (FallthroughSource && FallthroughSource->hasTerminator());
707
708 // If this is a normal cleanup, then having a prebranched
709 // fallthrough implies that the fallthrough source unconditionally
710 // jumps here.
711 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
712 (Scope.getNormalBlock() &&
713 FallthroughSource->getTerminator()->getSuccessor(0)
714 == Scope.getNormalBlock()));
715
716 bool RequiresNormalCleanup = false;
717 if (Scope.isNormalCleanup() &&
718 (HasFixups || HasExistingBranches || HasFallthrough)) {
719 RequiresNormalCleanup = true;
720 }
721
722 // If we have a prebranched fallthrough into an inactive normal
723 // cleanup, rewrite it so that it leads to the appropriate place.
724 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough &&
725 !RequiresNormalCleanup) {
726 // FIXME: Come up with a program which would need forwarding prebranched
727 // fallthrough and add tests. Otherwise delete this and assert against it.
728 assert(!IsActive);
729 llvm::BasicBlock *prebranchDest;
730
731 // If the prebranch is semantically branching through the next
732 // cleanup, just forward it to the next block, leaving the
733 // insertion point in the prebranched block.
734 if (FallthroughIsBranchThrough) {
735 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
736 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
737
738 // Otherwise, we need to make a new block. If the normal cleanup
739 // isn't being used at all, we could actually reuse the normal
740 // entry block, but this is simpler, and it avoids conflicts with
741 // dead optimistic fixup branches.
742 } else {
743 prebranchDest = createBasicBlock("forwarded-prebranch");
744 EmitBlock(prebranchDest);
745 }
746
747 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
748 assert(normalEntry && !normalEntry->use_empty());
749
750 ForwardPrebranchedFallthrough(FallthroughSource,
751 normalEntry, prebranchDest);
752 }
753
754 // If we don't need the cleanup at all, we're done.
755 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
757 EHStack.popCleanup(); // safe because there are no fixups
758 assert(EHStack.getNumBranchFixups() == 0 ||
759 EHStack.hasNormalCleanups());
760 if (NormalDeactivateOrigIP.isSet())
761 Builder.restoreIP(NormalDeactivateOrigIP);
762 return;
763 }
764
765 // Copy the cleanup emission data out. This uses either a stack
766 // array or malloc'd memory, depending on the size, which is
767 // behavior that SmallVector would provide, if we could use it
768 // here. Unfortunately, if you ask for a SmallVector<char>, the
769 // alignment isn't sufficient.
770 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
772 CleanupBufferStack[8 * sizeof(void *)];
773 std::unique_ptr<char[]> CleanupBufferHeap;
774 size_t CleanupSize = Scope.getCleanupSize();
775 EHScopeStack::Cleanup *Fn;
776
777 if (CleanupSize <= sizeof(CleanupBufferStack)) {
778 memcpy(CleanupBufferStack, CleanupSource, CleanupSize);
779 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack);
780 } else {
781 CleanupBufferHeap.reset(new char[CleanupSize]);
782 memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
783 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
784 }
785
786 EHScopeStack::Cleanup::Flags cleanupFlags;
787 if (Scope.isNormalCleanup())
788 cleanupFlags.setIsNormalCleanupKind();
789 if (Scope.isEHCleanup())
790 cleanupFlags.setIsEHCleanupKind();
791
792 // Under -EHa, invoke seh.scope.end() to mark scope end before dtor
793 bool IsEHa = getLangOpts().EHAsynch && !Scope.isLifetimeMarker();
794 bool IsSEHFinallyCleanup = Scope.isSEHFinallyCleanup();
795 if (!RequiresNormalCleanup) {
796 // Mark CPP scope end for passed-by-value Arg temp
797 // per Windows ABI which is "normally" Cleanup in callee
798 if (IsEHa && getInvokeDest()) {
799 // If we are deactivating a normal cleanup then we don't have a
800 // fallthrough. Restore original IP to emit CPP scope ends in the correct
801 // block.
802 if (NormalDeactivateOrigIP.isSet())
803 Builder.restoreIP(NormalDeactivateOrigIP);
804 if (Builder.GetInsertBlock() && !IsSEHFinallyCleanup)
806 if (NormalDeactivateOrigIP.isSet())
807 NormalDeactivateOrigIP = Builder.saveAndClearIP();
808 }
810 Scope.MarkEmitted();
811 EHStack.popCleanup();
812 } else {
813 // If we have a fallthrough and no other need for the cleanup,
814 // emit it directly.
815 if (HasFallthrough && !HasPrebranchedFallthrough && !HasFixups &&
816 !HasExistingBranches) {
817
818 // mark SEH scope end for fall-through flow
819 if (IsEHa && getInvokeDest()) {
820 if (Scope.isSEHFinallyCleanup())
822 else
824 }
825
827 Scope.MarkEmitted();
828 EHStack.popCleanup();
829
830 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
831
832 // Otherwise, the best approach is to thread everything through
833 // the cleanup block and then try to clean up after ourselves.
834 } else {
835 // Force the entry block to exist.
836 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
837
838 // I. Set up the fallthrough edge in.
839
840 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
841
842 // If there's a fallthrough, we need to store the cleanup
843 // destination index. For fall-throughs this is always zero.
844 if (HasFallthrough) {
845 if (!HasPrebranchedFallthrough)
846 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
847
848 // Otherwise, save and clear the IP if we don't have fallthrough
849 // because the cleanup is inactive.
850 } else if (FallthroughSource) {
851 assert(!IsActive && "source without fallthrough for active cleanup");
852 savedInactiveFallthroughIP = Builder.saveAndClearIP();
853 }
854
855 // II. Emit the entry block. This implicitly branches to it if
856 // we have fallthrough. All the fixups and existing branches
857 // should already be branched to it.
858 EmitBlock(NormalEntry);
859
860 // intercept normal cleanup to mark SEH scope end
861 if (IsEHa && getInvokeDest()) {
862 if (Scope.isSEHFinallyCleanup())
864 else
866 }
867
868 // III. Figure out where we're going and build the cleanup
869 // epilogue.
870
871 bool HasEnclosingCleanups =
872 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
873
874 // Compute the branch-through dest if we need it:
875 // - if there are branch-throughs threaded through the scope
876 // - if fall-through is a branch-through
877 // - if there are fixups that will be optimistically forwarded
878 // to the enclosing cleanup
879 llvm::BasicBlock *BranchThroughDest = nullptr;
880 if (Scope.hasBranchThroughs() ||
881 (FallthroughSource && FallthroughIsBranchThrough) ||
882 (HasFixups && HasEnclosingCleanups)) {
883 assert(HasEnclosingCleanups);
884 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
885 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
886 }
887
888 llvm::BasicBlock *FallthroughDest = nullptr;
890
891 // If there's exactly one branch-after and no other threads,
892 // we can route it without a switch.
893 // Skip for SEH, since ExitSwitch is used to generate code to indicate
894 // abnormal termination. (SEH: Except _leave and fall-through at
895 // the end, all other exits in a _try (return/goto/continue/break)
896 // are considered as abnormal terminations, using NormalCleanupDestSlot
897 // to indicate abnormal termination)
898 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
899 !currentFunctionUsesSEHTry() && Scope.getNumBranchAfters() == 1) {
900 assert(!BranchThroughDest || !IsActive);
901
902 // Clean up the possibly dead store to the cleanup dest slot.
903 llvm::Instruction *NormalCleanupDestSlot =
905 if (NormalCleanupDestSlot->hasOneUse()) {
906 NormalCleanupDestSlot->user_back()->eraseFromParent();
907 NormalCleanupDestSlot->eraseFromParent();
909 }
910
911 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
912 InstsToAppend.push_back(llvm::UncondBrInst::Create(BranchAfter));
913
914 // Build a switch-out if we need it:
915 // - if there are branch-afters threaded through the scope
916 // - if fall-through is a branch-after
917 // - if there are fixups that have nowhere left to go and
918 // so must be immediately resolved
919 } else if (Scope.getNumBranchAfters() ||
920 (HasFallthrough && !FallthroughIsBranchThrough) ||
921 (HasFixups && !HasEnclosingCleanups)) {
922
923 llvm::BasicBlock *Default =
924 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
925
926 // TODO: base this on the number of branch-afters and fixups
927 const unsigned SwitchCapacity = 10;
928
929 // pass the abnormal exit flag to Fn (SEH cleanup)
930 cleanupFlags.setHasExitSwitch();
931
932 llvm::LoadInst *Load = createLoadInstBefore(getNormalCleanupDestSlot(),
933 "cleanup.dest", *this);
934 llvm::SwitchInst *Switch =
935 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
936
937 InstsToAppend.push_back(Load);
938 InstsToAppend.push_back(Switch);
939
940 // Branch-after fallthrough.
941 if (FallthroughSource && !FallthroughIsBranchThrough) {
942 FallthroughDest = createBasicBlock("cleanup.cont");
943 if (HasFallthrough)
944 Switch->addCase(Builder.getInt32(0), FallthroughDest);
945 }
946
947 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
948 Switch->addCase(Scope.getBranchAfterIndex(I),
949 Scope.getBranchAfterBlock(I));
950 }
951
952 // If there aren't any enclosing cleanups, we can resolve all
953 // the fixups now.
954 if (HasFixups && !HasEnclosingCleanups)
955 ResolveAllBranchFixups(*this, Switch, NormalEntry);
956 } else {
957 // We should always have a branch-through destination in this case.
958 assert(BranchThroughDest);
959 InstsToAppend.push_back(llvm::UncondBrInst::Create(BranchThroughDest));
960 }
961
962 // IV. Pop the cleanup and emit it.
963 Scope.MarkEmitted();
964 EHStack.popCleanup();
965 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
966
967 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
968
969 // Append the prepared cleanup prologue from above.
970 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
971 for (llvm::Instruction *Inst : InstsToAppend)
972 Inst->insertInto(NormalExit, NormalExit->end());
973
974 // Optimistically hope that any fixups will continue falling through.
975 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
976 I < E; ++I) {
977 BranchFixup &Fixup = EHStack.getBranchFixup(I);
978 if (!Fixup.Destination)
979 continue;
980 if (!Fixup.OptimisticBranchBlock) {
983 Fixup.InitialBranch->getIterator(), *this);
984 Fixup.InitialBranch->setSuccessor(NormalEntry);
985 }
986 Fixup.OptimisticBranchBlock = NormalExit;
987 }
988
989 // V. Set up the fallthrough edge out.
990
991 // Case 1: a fallthrough source exists but doesn't branch to the
992 // cleanup because the cleanup is inactive.
993 if (!HasFallthrough && FallthroughSource) {
994 // Prebranched fallthrough was forwarded earlier.
995 // Non-prebranched fallthrough doesn't need to be forwarded.
996 // Either way, all we need to do is restore the IP we cleared before.
997 assert(!IsActive);
998 Builder.restoreIP(savedInactiveFallthroughIP);
999
1000 // Case 2: a fallthrough source exists and should branch to the
1001 // cleanup, but we're not supposed to branch through to the next
1002 // cleanup.
1003 } else if (HasFallthrough && FallthroughDest) {
1004 assert(!FallthroughIsBranchThrough);
1005 EmitBlock(FallthroughDest);
1006
1007 // Case 3: a fallthrough source exists and should branch to the
1008 // cleanup and then through to the next.
1009 } else if (HasFallthrough) {
1010 // Everything is already set up for this.
1011
1012 // Case 4: no fallthrough source exists.
1013 } else {
1014 Builder.ClearInsertionPoint();
1015 }
1016
1017 // VI. Assorted cleaning.
1018
1019 // Check whether we can merge NormalEntry into a single predecessor.
1020 // This might invalidate (non-IR) pointers to NormalEntry.
1021 llvm::BasicBlock *NewNormalEntry =
1022 SimplifyCleanupEntry(*this, NormalEntry);
1023
1024 // If it did invalidate those pointers, and NormalEntry was the same
1025 // as NormalExit, go back and patch up the fixups.
1026 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
1027 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1028 I < E; ++I)
1029 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
1030 }
1031 }
1032
1033 if (NormalDeactivateOrigIP.isSet())
1034 Builder.restoreIP(NormalDeactivateOrigIP);
1035 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1036
1037 // Emit the EH cleanup if required.
1038 if (RequiresEHCleanup) {
1039 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1040
1041 EmitBlock(EHEntry);
1042
1043 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
1044
1045 // Push a terminate scope or cleanupendpad scope around the potentially
1046 // throwing cleanups. For funclet EH personalities, the cleanupendpad models
1047 // program termination when cleanups throw.
1048 bool PushedTerminate = false;
1049 SaveAndRestore RestoreCurrentFuncletPad(CurrentFuncletPad);
1050 llvm::CleanupPadInst *CPI = nullptr;
1051
1052 const EHPersonality &Personality = EHPersonality::get(*this);
1053 if (Personality.usesFuncletPads()) {
1054 llvm::Value *ParentPad = CurrentFuncletPad;
1055 if (!ParentPad)
1056 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1057 CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
1058 }
1059
1060 // Non-MSVC personalities need to terminate when an EH cleanup throws.
1061 if (!Personality.isMSVCPersonality()) {
1062 EHStack.pushTerminate();
1063 PushedTerminate = true;
1064 } else if (IsEHa && getInvokeDest()) {
1065 if (!IsSEHFinallyCleanup)
1067 }
1068
1069 // We only actually emit the cleanup code if the cleanup is either
1070 // active or was used before it was deactivated.
1071 if (EHActiveFlag.isValid() || IsActive) {
1072 cleanupFlags.setIsForEHCleanup();
1073 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
1074 }
1075
1076 if (CPI)
1077 Builder.CreateCleanupRet(CPI, NextAction);
1078 else
1079 Builder.CreateBr(NextAction);
1080
1081 // Leave the terminate scope.
1082 if (PushedTerminate)
1083 EHStack.popTerminate();
1084
1085 Builder.restoreIP(SavedIP);
1086
1087 SimplifyCleanupEntry(*this, EHEntry);
1088 }
1089}
1090
1091/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1092/// specified destination obviously has no cleanups to run. 'false' is always
1093/// a conservatively correct answer for this method.
1095 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1096 && "stale jump destination");
1097
1098 // Calculate the innermost active normal cleanup.
1100 EHStack.getInnermostActiveNormalCleanup();
1101
1102 // If we're not in an active normal cleanup scope, or if the
1103 // destination scope is within the innermost active normal cleanup
1104 // scope, we don't need to worry about fixups.
1105 if (TopCleanup == EHStack.stable_end() ||
1106 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
1107 return true;
1108
1109 // Otherwise, we might need some cleanups.
1110 return false;
1111}
1112
1113
1114/// Terminate the current block by emitting a branch which might leave
1115/// the current cleanup-protected scope. The target scope may not yet
1116/// be known, in which case this will require a fixup.
1117///
1118/// As a side-effect, this method clears the insertion point.
1120 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1121 && "stale jump destination");
1122
1123 if (!HaveInsertPoint())
1124 return;
1125
1126 // Create the branch.
1127 llvm::UncondBrInst *BI = Builder.CreateBr(Dest.getBlock());
1128 addInstToCurrentSourceAtom(BI, nullptr);
1129
1130 // Calculate the innermost active normal cleanup.
1132 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1133
1134 // If we're not in an active normal cleanup scope, or if the
1135 // destination scope is within the innermost active normal cleanup
1136 // scope, we don't need to worry about fixups.
1137 if (TopCleanup == EHStack.stable_end() ||
1138 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
1139 Builder.ClearInsertionPoint();
1140 return;
1141 }
1142
1143 // If we can't resolve the destination cleanup scope, just add this
1144 // to the current cleanup scope as a branch fixup.
1145 if (!Dest.getScopeDepth().isValid()) {
1146 BranchFixup &Fixup = EHStack.addBranchFixup();
1147 Fixup.Destination = Dest.getBlock();
1148 Fixup.DestinationIndex = Dest.getDestIndex();
1149 Fixup.InitialBranch = BI;
1150 Fixup.OptimisticBranchBlock = nullptr;
1151
1152 Builder.ClearInsertionPoint();
1153 return;
1154 }
1155
1156 // Otherwise, thread through all the normal cleanups in scope.
1157
1158 // Store the index at the start.
1159 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1160 createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI->getIterator(),
1161 *this);
1162
1163 // Adjust BI to point to the first cleanup block.
1164 {
1166 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1167 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1168 }
1169
1170 // Add this destination to all the scopes involved.
1171 EHScopeStack::stable_iterator I = TopCleanup;
1173 if (E.strictlyEncloses(I)) {
1174 while (true) {
1176 assert(Scope.isNormalCleanup());
1177 I = Scope.getEnclosingNormalCleanup();
1178
1179 // If this is the last cleanup we're propagating through, tell it
1180 // that there's a resolved jump moving through it.
1181 if (!E.strictlyEncloses(I)) {
1182 Scope.addBranchAfter(Index, Dest.getBlock());
1183 break;
1184 }
1185
1186 // Otherwise, tell the scope that there's a jump propagating
1187 // through it. If this isn't new information, all the rest of
1188 // the work has been done before.
1189 if (!Scope.addBranchThrough(Dest.getBlock()))
1190 break;
1191 }
1192 }
1193
1194 Builder.ClearInsertionPoint();
1195}
1196
1197static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
1198 EHScopeStack::stable_iterator cleanup) {
1199 // If we needed an EH block for any reason, that counts.
1200 if (EHStack.find(cleanup)->hasEHBranches())
1201 return true;
1202
1203 // Check whether any enclosed cleanups were needed.
1204 for (EHScopeStack::stable_iterator
1205 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1206 assert(cleanup.strictlyEncloses(i));
1207
1208 EHScope &scope = *EHStack.find(i);
1209 if (scope.hasEHBranches())
1210 return true;
1211
1212 i = scope.getEnclosingEHScope();
1213 }
1214
1215 return false;
1216}
1217
1222
1223/// The given cleanup block is changing activation state. Configure a
1224/// cleanup variable if necessary.
1225///
1226/// It would be good if we had some way of determining if there were
1227/// extra uses *after* the change-over point.
1229 EHScopeStack::stable_iterator C,
1231 llvm::Instruction *dominatingIP) {
1233
1234 // We always need the flag if we're activating the cleanup in a
1235 // conditional context, because we have to assume that the current
1236 // location doesn't necessarily dominate the cleanup's code.
1237 bool isActivatedInConditional =
1239
1240 bool needFlag = false;
1241
1242 // Calculate whether the cleanup was used:
1243
1244 // - as a normal cleanup
1245 if (Scope.isNormalCleanup()) {
1246 Scope.setTestFlagInNormalCleanup();
1247 needFlag = true;
1248 }
1249
1250 // - as an EH cleanup
1251 if (Scope.isEHCleanup() &&
1252 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
1253 Scope.setTestFlagInEHCleanup();
1254 needFlag = true;
1255 }
1256
1257 // If it hasn't yet been used as either, we're done.
1258 if (!needFlag)
1259 return;
1260
1261 Address var = Scope.getActiveFlag();
1262 if (!var.isValid()) {
1263 CodeGenFunction::AllocaTrackerRAII AllocaTracker(CGF);
1264 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), LangAS::Default,
1265 CharUnits::One(), "cleanup.isactive");
1266 Scope.setActiveFlag(var);
1267 Scope.AddAuxAllocas(AllocaTracker.Take());
1268
1269 assert(dominatingIP && "no existing variable and no dominating IP!");
1270
1271 // Initialize to true or false depending on whether it was
1272 // active up to this point.
1273 llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
1274
1275 // If we're in a conditional block, ignore the dominating IP and
1276 // use the outermost conditional branch.
1277 if (CGF.isInConditionalBranch()) {
1278 CGF.setBeforeOutermostConditional(value, var, CGF);
1279 } else {
1280 createStoreInstBefore(value, var, dominatingIP->getIterator(), CGF);
1281 }
1282 }
1283
1284 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
1285}
1286
1287/// Activate a cleanup that was created in an inactivated state.
1289 llvm::Instruction *dominatingIP) {
1290 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1292 assert(!Scope.isActive() && "double activation");
1293
1294 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
1295
1296 Scope.setActive(true);
1297}
1298
1299/// Deactive a cleanup that was created in an active state.
1301 llvm::Instruction *dominatingIP) {
1302 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1304 assert(Scope.isActive() && "double deactivation");
1305
1306 // If it's the top of the stack, just pop it, but do so only if it belongs
1307 // to the current RunCleanupsScope.
1308 if (C == EHStack.stable_begin() &&
1309 CurrentCleanupScopeDepth.strictlyEncloses(C)) {
1310 PopCleanupBlock(/*FallthroughIsBranchThrough=*/false,
1311 /*ForDeactivation=*/true);
1312 return;
1313 }
1314
1315 // Otherwise, follow the general case.
1316 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
1317
1318 Scope.setActive(false);
1319}
1320
1322 if (!NormalCleanupDest.isValid())
1324 CreateDefaultAlignTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1325 return NormalCleanupDest;
1326}
1327
1328/// Emits all the code to cause the given temporary to be cleaned up.
1330 QualType TempType,
1331 Address Ptr) {
1333 /*useEHCleanup*/ true);
1334}
1335
1336// Need to set "funclet" in OperandBundle properly for noThrow
1337// intrinsic (see CGCall.cpp)
1339 llvm::FunctionCallee &SehCppScope) {
1340 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
1341 assert(CGF.Builder.GetInsertBlock() && InvokeDest);
1342 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
1344 CGF.getBundlesForFunclet(SehCppScope.getCallee());
1345 if (CGF.CurrentFuncletPad)
1346 BundleList.emplace_back("funclet", CGF.CurrentFuncletPad);
1347 CGF.Builder.CreateInvoke(SehCppScope, Cont, InvokeDest, {}, BundleList);
1348 CGF.EmitBlock(Cont);
1349}
1350
1351// Invoke a llvm.seh.scope.begin at the beginning of a CPP scope for -EHa
1353 assert(getLangOpts().EHAsynch);
1354 llvm::FunctionCallee SehCppScope =
1355 CGM.getIntrinsic(llvm::Intrinsic::seh_scope_begin);
1356 EmitSehScope(*this, SehCppScope);
1357}
1358
1359// Invoke a llvm.seh.scope.end at the end of a CPP scope for -EHa
1360// llvm.seh.scope.end is emitted before popCleanup, so it's "invoked"
1362 assert(getLangOpts().EHAsynch);
1363 llvm::FunctionCallee SehCppScope =
1364 CGM.getIntrinsic(llvm::Intrinsic::seh_scope_end);
1365 EmitSehScope(*this, SehCppScope);
1366}
1367
1368// Invoke a llvm.seh.try.begin at the beginning of a SEH scope for -EHa
1370 assert(getLangOpts().EHAsynch);
1371 llvm::FunctionCallee SehCppScope =
1372 CGM.getIntrinsic(llvm::Intrinsic::seh_try_begin);
1373 EmitSehScope(*this, SehCppScope);
1374}
1375
1376// Invoke a llvm.seh.try.end at the end of a SEH scope for -EHa
1378 assert(getLangOpts().EHAsynch);
1379 llvm::FunctionCallee SehCppScope =
1380 CGM.getIntrinsic(llvm::Intrinsic::seh_try_end);
1381 EmitSehScope(*this, SehCppScope);
1382}
#define V(N, I)
static llvm::LoadInst * createLoadInstBefore(Address addr, const Twine &name, llvm::BasicBlock::iterator beforeInst, CodeGenFunction &CGF)
static void EmitSehScope(CodeGenFunction &CGF, llvm::FunctionCallee &SehCppScope)
static llvm::BasicBlock * CreateNormalEntry(CodeGenFunction &CGF, EHCleanupScope &Scope)
ForActivation_t
@ ForActivation
@ ForDeactivation
static void EmitCleanup(CodeGenFunction &CGF, EHScopeStack::Cleanup *Fn, EHScopeStack::Cleanup::Flags flags, Address ActiveFlag)
static void destroyOptimisticNormalEntry(CodeGenFunction &CGF, EHCleanupScope &scope)
We don't need a normal entry block for the given cleanup.
static void SetupCleanupBlockActivation(CodeGenFunction &CGF, EHScopeStack::stable_iterator C, ForActivation_t kind, llvm::Instruction *dominatingIP)
The given cleanup block is changing activation state.
static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit, llvm::BasicBlock *From, llvm::BasicBlock *To)
static void createStoreInstBefore(llvm::Value *value, Address addr, llvm::BasicBlock::iterator beforeInst, CodeGenFunction &CGF)
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 ...
static bool IsUsedAsEHCleanup(EHScopeStack &EHStack, EHScopeStack::stable_iterator cleanup)
static llvm::BasicBlock * SimplifyCleanupEntry(CodeGenFunction &CGF, llvm::BasicBlock *Entry)
Attempts to reduce a cleanup's entry block to a fallthrough.
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.
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a an optional score condition
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Represents a C++ temporary.
Definition ExprCXX.h:1463
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:128
static Address invalid()
Definition Address.h:176
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:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
bool isValid() const
Definition Address.h:177
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:146
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
EHScopeStack::stable_iterator CurrentCleanupScopeDepth
void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
ActivateCleanupBlock - Activates an initially-inactive cleanup.
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
const LangOptions & getLangOpts() const
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
Definition CGDecl.cpp:2305
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
llvm::BasicBlock * getUnreachableBlock()
@ Default
! No language constraints on evaluation order.
void initFullExprCleanupWithFlag(RawAddress ActiveFlag)
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition CGExpr.cpp:185
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
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.
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
void ResolveBranchFixups(llvm::BasicBlock *Target)
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
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...
Definition CGExpr.cpp:162
void setBeforeOutermostConditional(llvm::Value *value, Address addr, CodeGenFunction &CGF)
SmallVector< llvm::OperandBundleDef, 1 > getBundlesForFunclet(llvm::Value *Callee)
Definition CGCall.cpp:5407
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
Definition CGExpr.cpp:111
llvm::SmallVector< char, 256 > LifetimeExtendedCleanupStack
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
Emits all the code to cause the given temporary to be cleaned up.
llvm::BasicBlock * getEHDispatchBlock(EHScopeStack::stable_iterator scope)
RawAddress NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
llvm::Instruction * CurrentFuncletPad
bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const
isObviouslyBranchWithoutCleanups - Return true if a branch to the specified destination obviously has...
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:654
A scope which attempts to handle some, possibly all, types of exceptions.
Definition CGCleanup.h:168
static size_t getSizeForNumHandlers(unsigned N)
Definition CGCleanup.h:198
A cleanup scope which generates the cleanup blocks lazily.
Definition CGCleanup.h:253
EHScopeStack::stable_iterator getEnclosingNormalCleanup() const
Definition CGCleanup.h:437
size_t getAllocatedSize() const
Definition CGCleanup.h:349
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:345
llvm::BasicBlock * getNormalBlock() const
Definition CGCleanup.h:389
An exceptions scope which filters exceptions thrown through it.
Definition CGCleanup.h:527
static size_t getSizeForNumFilters(unsigned numFilters)
Definition CGCleanup.h:546
unsigned getNumFilters() const
Definition CGCleanup.h:550
A saved depth on the scope stack.
bool encloses(stable_iterator I) const
Returns true if this scope encloses I.
bool strictlyEncloses(stable_iterator I) const
Returns true if this scope strictly encloses I: that is, if it encloses I and is not I.
A stack of scopes which respond to exceptions, including cleanups and catch blocks.
void popNullFixups()
Pops lazily-removed fixups from the end of the list.
BranchFixup & getBranchFixup(unsigned I)
stable_iterator getInnermostNormalCleanup() const
Returns the innermost normal cleanup on the stack, or stable_end() if there are no normal cleanups.
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
unsigned getNumBranchFixups() const
class EHFilterScope * pushFilter(unsigned NumFilters)
Push an exceptions filter on the stack.
stable_iterator getInnermostEHScope() const
bool empty() const
Determines whether the exception-scopes stack is empty.
bool containsOnlyNoopCleanups(stable_iterator Old) const
iterator begin() const
Returns an iterator pointing to the innermost EH scope.
Definition CGCleanup.h:641
void pushTerminate()
Push a terminate handler on the stack.
void popCleanup()
Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
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:665
stable_iterator getInnermostActiveNormalCleanup() const
void popFilter()
Pops an exceptions filter off the stack.
bool hasNormalCleanups() const
Determines whether there are any normal cleanups on the stack.
stable_iterator stabilize(iterator it) const
Translates an iterator into a stable_iterator.
Definition CGCleanup.h:672
static stable_iterator stable_end()
Create a stable reference to the bottom of the EH stack.
void clearFixups()
Clears the branch-fixups list.
class EHCatchScope * pushCatch(unsigned NumHandlers)
Push a set of catch handlers on the stack.
A protected scope for zero-cost EH handling.
Definition CGCleanup.h:45
EHScopeStack::stable_iterator getEnclosingEHScope() const
Definition CGCleanup.h:158
bool hasEHBranches() const
Definition CGCleanup.h:152
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
bool isAggregate() const
Definition CGValue.h:66
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:84
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
bool isComplex() const
Definition CGValue.h:65
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:79
An abstract representation of an aligned address.
Definition Address.h:42
llvm::Value * getPointer() const
Definition Address.h:66
static RawAddress invalid()
Definition Address.h:61
A (possibly-)qualified type.
Definition TypeBase.h:938
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition Format.cpp:4517
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned DestinationIndex
The destination index value.
llvm::BasicBlock * Destination
The ultimate destination of the branch.
llvm::BasicBlock * OptimisticBranchBlock
The block containing the terminator which needs to be modified into a switch if this fixup is resolve...
llvm::UncondBrInst * InitialBranch
The initial branch of the fixup.
llvm::SmallVector< llvm::AllocaInst * > Take()
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
EHScopeStack::stable_iterator getScopeDepth() const
Header for data within LifetimeExtendedCleanupStack.
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.
The exceptions personality for a function.
Definition CGCleanup.h:678
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:710