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
26bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
27 if (rv.isScalar())
28 return DominatingLLVMValue::needsSaving(value: rv.getScalarVal());
29 if (rv.isAggregate())
30 return DominatingValue<Address>::needsSaving(value: rv.getAggregateAddress());
31 return true;
32}
33
34DominatingValue<RValue>::saved_type
35DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
36 if (rv.isScalar()) {
37 llvm::Value *V = rv.getScalarVal();
38 return saved_type(DominatingLLVMValue::save(CGF, value: V),
39 DominatingLLVMValue::needsSaving(value: V) ? ScalarAddress
40 : ScalarLiteral);
41 }
42
43 if (rv.isComplex()) {
44 CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
45 return saved_type(DominatingLLVMValue::save(CGF, value: V.first),
46 DominatingLLVMValue::save(CGF, value: V.second));
47 }
48
49 assert(rv.isAggregate());
50 Address V = rv.getAggregateAddress();
51 return saved_type(DominatingValue<Address>::save(CGF, value: V),
52 DominatingValue<Address>::needsSaving(value: 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.
60RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
61 switch (K) {
62 case ScalarLiteral:
63 case ScalarAddress:
64 return RValue::get(V: DominatingLLVMValue::restore(CGF, value: Vals.first));
65 case AggregateLiteral:
66 case AggregateAddress:
67 return RValue::getAggregate(
68 addr: DominatingValue<Address>::restore(CGF, value: AggregateAddr));
69 case ComplexAddress: {
70 llvm::Value *real = DominatingLLVMValue::restore(CGF, value: Vals.first);
71 llvm::Value *imag = DominatingLLVMValue::restore(CGF, value: Vals.second);
72 return RValue::getComplex(V1: real, V2: 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(Value: Size, Align: 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(dest: NewStartOfData, src: StartOfData, n: 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(Value: Size, Align: ScopeStackAlignment);
113}
114
115bool EHScopeStack::containsOnlyNoopCleanups(
116 EHScopeStack::stable_iterator Old) const {
117 for (EHScopeStack::iterator it = begin(); stabilize(ir: it) != Old; it++) {
118 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(Val: &*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
130bool EHScopeStack::requiresLandingPad() const {
131 for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {
132 // Skip lifetime markers.
133 if (auto *cleanup = dyn_cast<EHCleanupScope>(Val: &*find(sp: si)))
134 if (cleanup->isLifetimeMarker()) {
135 si = cleanup->getEnclosingEHScope();
136 continue;
137 }
138 return true;
139 }
140
141 return false;
142}
143
144EHScopeStack::stable_iterator
145EHScopeStack::getInnermostActiveNormalCleanup() const {
146 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
147 si != se; ) {
148 EHCleanupScope &cleanup = cast<EHCleanupScope>(Val&: *find(sp: 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(Size: 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(sp: 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
207void EHScopeStack::popCleanup() {
208 assert(!empty() && "popping exception stack when not empty");
209
210 assert(isa<EHCleanupScope>(*begin()));
211 EHCleanupScope &Cleanup = cast<EHCleanupScope>(Val&: *begin());
212 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
213 InnermostEHScope = Cleanup.getEnclosingEHScope();
214 deallocate(Size: 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
228 popNullFixups();
229 }
230}
231
232EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
233 assert(getInnermostEHScope() == stable_end());
234 char *buffer = allocate(Size: EHFilterScope::getSizeForNumFilters(numFilters));
235 EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
236 InnermostEHScope = stable_begin();
237 return filter;
238}
239
240void EHScopeStack::popFilter() {
241 assert(!empty() && "popping exception stack when not empty");
242
243 EHFilterScope &filter = cast<EHFilterScope>(Val&: *begin());
244 deallocate(Size: EHFilterScope::getSizeForNumFilters(numFilters: filter.getNumFilters()));
245
246 InnermostEHScope = filter.getEnclosingEHScope();
247}
248
249EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
250 char *buffer = allocate(Size: EHCatchScope::getSizeForNumHandlers(N: numHandlers));
251 EHCatchScope *scope =
252 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
253 InnermostEHScope = stable_begin();
254 return scope;
255}
256
257void EHScopeStack::pushTerminate() {
258 char *Buffer = allocate(Size: 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.
268void EHScopeStack::popNullFixups() {
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(sp: InnermostNormalCleanup);
274 unsigned MinSize = cast<EHCleanupScope>(Val&: *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
282RawAddress CodeGenFunction::createCleanupActiveFlag() {
283 // Create a variable to decide whether the cleanup needs to be run.
284 RawAddress active = CreateTempAllocaWithoutCast(
285 Ty: Builder.getInt1Ty(), align: CharUnits::One(), Name: "cleanup.cond");
286
287 // Initialize it to false at a site that's guaranteed to be run
288 // before each evaluation.
289 setBeforeOutermostConditional(value: Builder.getFalse(), addr: active, CGF&: *this);
290
291 // Initialize it to true at the current location.
292 Builder.CreateStore(Val: Builder.getTrue(), Addr: active);
293
294 return active;
295}
296
297void CodeGenFunction::initFullExprCleanupWithFlag(RawAddress ActiveFlag) {
298 // Set that as the active flag in the cleanup.
299 EHCleanupScope &cleanup = cast<EHCleanupScope>(Val&: *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.
334static void ResolveAllBranchFixups(CodeGenFunction &CGF,
335 llvm::SwitchInst *Switch,
336 llvm::BasicBlock *CleanupEntry) {
337 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
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) {
353 createStoreInstBefore(value: CGF.Builder.getInt32(C: Fixup.DestinationIndex),
354 addr: CGF.getNormalCleanupDestSlot(),
355 beforeInst: 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(Ptr: Fixup.Destination).second)
361 continue;
362
363 Switch->addCase(OnVal: CGF.Builder.getInt32(C: Fixup.DestinationIndex),
364 Dest: 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>(Val: Term)) {
379 auto Load = createLoadInstBefore(addr: CGF.getNormalCleanupDestSlot(),
380 name: "cleanup.dest", beforeInst: Term->getIterator(), CGF);
381 llvm::SwitchInst *Switch =
382 llvm::SwitchInst::Create(Value: Load, Default: Br->getSuccessor(i: 0), NumCases: 4, InsertBefore: Block);
383 Br->eraseFromParent();
384 return Switch;
385 } else {
386 return cast<llvm::SwitchInst>(Val: Term);
387 }
388}
389
390void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
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(Ptr: BranchBB).second)
416 continue;
417
418 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(CGF&: *this, Block: BranchBB);
419
420 // Add a case to the switch.
421 Switch->addCase(OnVal: Builder.getInt32(C: Fixup.DestinationIndex), Dest: Block);
422 }
423
424 if (ResolvedAny)
425 EHStack.popNullFixups();
426}
427
428/// Pops cleanup blocks until the given savepoint is reached.
429void CodeGenFunction::PopCleanupBlocks(
430 EHScopeStack::stable_iterator Old,
431 std::initializer_list<llvm::Value **> ValuesToReload) {
432 assert(Old.isValid());
433
434 bool HadBranches = false;
435 while (EHStack.stable_begin() != Old) {
436 EHCleanupScope &Scope = cast<EHCleanupScope>(Val&: *EHStack.begin());
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(I: 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>(Val: *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>(Val: Inst);
464 if (AI && AI->isStaticAlloca())
465 continue;
466
467 Address Tmp =
468 CreateDefaultAlignTempAlloca(Ty: Inst->getType(), Name: "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>(Val: Inst))
473 InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
474 else
475 InsertBefore = std::next(x: Inst->getIterator());
476 CGBuilderTy(CGM, &*InsertBefore).CreateStore(Val: Inst, Addr: Tmp);
477
478 // Reload the value at the current insertion point.
479 *ReloadedValue = Builder.CreateLoad(Addr: 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.
485void CodeGenFunction::PopCleanupBlocks(
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
497 LifetimeExtendedCleanupHeader &Header =
498 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
499 LifetimeExtendedCleanupStack[I]);
500 I += sizeof(Header);
501
502 EHStack.pushCopyOfCleanup(Kind: Header.getKind(),
503 Cleanup: &LifetimeExtendedCleanupStack[I],
504 Size: 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(N: OldLifetimeExtendedSize);
515}
516
517static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
518 EHCleanupScope &Scope) {
519 assert(Scope.isNormalCleanup());
520 llvm::BasicBlock *Entry = Scope.getNormalBlock();
521 if (!Entry) {
522 Entry = CGF.createBasicBlock(name: "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>(Val: 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(V: Pred);
555
556 // Merge the blocks.
557 Pred->splice(ToIt: Pred->end(), FromBB: 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
568static void EmitCleanup(CodeGenFunction &CGF,
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(name: "cleanup.done");
577 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock(name: "cleanup.action");
578 llvm::Value *IsActive
579 = CGF.Builder.CreateLoad(Addr: ActiveFlag, Name: "cleanup.is_active");
580 CGF.Builder.CreateCondBr(Cond: IsActive, True: CleanupBB, False: ContBB);
581 CGF.EmitBlock(BB: 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(BB: 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>(Val: Term)) {
601 assert(Br->getSuccessor() == From);
602 Br->setSuccessor(To);
603 } else {
604 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Val: Term);
605 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
606 if (Switch->getSuccessor(idx: I) == From)
607 Switch->setSuccessor(idx: I, NewSucc: 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.
617static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
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>(Val: use.getUser());
633 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
634 // Replace the switch with a branch.
635 llvm::UncondBrInst::Create(Target: si->case_begin()->getCaseSuccessor(),
636 InsertBefore: si->getIterator());
637
638 // The switch operand is a load from the cleanup-dest alloca.
639 llvm::LoadInst *condition = cast<llvm::LoadInst>(Val: 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!");
662 EHCleanupScope &Scope = cast<EHCleanupScope>(Val&: *EHStack.begin());
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()
675 : Address::invalid();
676 Address EHActiveFlag =
677 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
678 : Address::invalid();
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(sp: Scope.getEnclosingNormalCleanup());
736 prebranchDest = CreateNormalEntry(CGF&: *this, Scope&: cast<EHCleanupScope>(Val&: 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(name: "forwarded-prebranch");
744 EmitBlock(BB: prebranchDest);
745 }
746
747 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
748 assert(normalEntry && !normalEntry->use_empty());
749
750 ForwardPrebranchedFallthrough(Exit: FallthroughSource,
751 From: normalEntry, To: prebranchDest);
752 }
753
754 // If we don't need the cleanup at all, we're done.
755 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
756 destroyOptimisticNormalEntry(CGF&: *this, scope&: Scope);
757 EHStack.popCleanup(); // safe because there are no fixups
758 assert(EHStack.getNumBranchFixups() == 0 ||
759 EHStack.hasNormalCleanups());
760 if (NormalDeactivateOrigIP.isValid())
761 Builder.restoreIP(IP: 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());
771 alignas(EHScopeStack::ScopeStackAlignment) char
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(dest: CleanupBufferStack, src: CleanupSource, n: CleanupSize);
779 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack);
780 } else {
781 CleanupBufferHeap.reset(p: new char[CleanupSize]);
782 memcpy(dest: CleanupBufferHeap.get(), src: CleanupSource, n: 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.isValid())
803 Builder.restoreIP(IP: NormalDeactivateOrigIP);
804 if (Builder.GetInsertBlock() && !IsSEHFinallyCleanup)
805 EmitSehCppScopeEnd();
806 if (NormalDeactivateOrigIP.isValid())
807 NormalDeactivateOrigIP = Builder.saveAndClearIP();
808 }
809 destroyOptimisticNormalEntry(CGF&: *this, scope&: Scope);
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())
821 EmitSehTryScopeEnd();
822 else
823 EmitSehCppScopeEnd();
824 }
825
826 destroyOptimisticNormalEntry(CGF&: *this, scope&: Scope);
827 Scope.MarkEmitted();
828 EHStack.popCleanup();
829
830 EmitCleanup(CGF&: *this, Fn, flags: cleanupFlags, ActiveFlag: 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(CGF&: *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(Val: Builder.getInt32(C: 0), Addr: 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(BB: NormalEntry);
859
860 // intercept normal cleanup to mark SEH scope end
861 if (IsEHa && getInvokeDest()) {
862 if (Scope.isSEHFinallyCleanup())
863 EmitSehTryScopeEnd();
864 else
865 EmitSehCppScopeEnd();
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(sp: Scope.getEnclosingNormalCleanup());
885 BranchThroughDest = CreateNormalEntry(CGF&: *this, Scope&: cast<EHCleanupScope>(Val&: S));
886 }
887
888 llvm::BasicBlock *FallthroughDest = nullptr;
889 SmallVector<llvm::Instruction*, 2> InstsToAppend;
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 =
904 cast<llvm::Instruction>(Val: getNormalCleanupDestSlot().getPointer());
905 if (NormalCleanupDestSlot->hasOneUse()) {
906 NormalCleanupDestSlot->user_back()->eraseFromParent();
907 NormalCleanupDestSlot->eraseFromParent();
908 NormalCleanupDest = RawAddress::invalid();
909 }
910
911 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(I: 0);
912 InstsToAppend.push_back(Elt: llvm::UncondBrInst::Create(Target: 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(addr: getNormalCleanupDestSlot(),
933 name: "cleanup.dest", CGF&: *this);
934 llvm::SwitchInst *Switch =
935 llvm::SwitchInst::Create(Value: Load, Default, NumCases: SwitchCapacity);
936
937 InstsToAppend.push_back(Elt: Load);
938 InstsToAppend.push_back(Elt: Switch);
939
940 // Branch-after fallthrough.
941 if (FallthroughSource && !FallthroughIsBranchThrough) {
942 FallthroughDest = createBasicBlock(name: "cleanup.cont");
943 if (HasFallthrough)
944 Switch->addCase(OnVal: Builder.getInt32(C: 0), Dest: FallthroughDest);
945 }
946
947 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
948 Switch->addCase(OnVal: Scope.getBranchAfterIndex(I),
949 Dest: 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(CGF&: *this, Switch, CleanupEntry: NormalEntry);
956 } else {
957 // We should always have a branch-through destination in this case.
958 assert(BranchThroughDest);
959 InstsToAppend.push_back(Elt: llvm::UncondBrInst::Create(Target: 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(CGF&: *this, Fn, flags: cleanupFlags, ActiveFlag: 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(ParentBB: NormalExit, It: 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) {
981 createStoreInstBefore(value: Builder.getInt32(C: Fixup.DestinationIndex),
982 addr: getNormalCleanupDestSlot(),
983 beforeInst: Fixup.InitialBranch->getIterator(), CGF&: *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(IP: 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(BB: 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(CGF&: *this, Entry: 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.isValid())
1034 Builder.restoreIP(IP: 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(BB: EHEntry);
1042
1043 llvm::BasicBlock *NextAction = getEHDispatchBlock(scope: 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 = getEHPersonality(CGF&: *this);
1053 if (Personality.usesFuncletPads()) {
1054 llvm::Value *ParentPad = CurrentFuncletPad;
1055 if (!ParentPad)
1056 ParentPad = llvm::ConstantTokenNone::get(Context&: 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)
1066 EmitSehCppScopeEnd();
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(CGF&: *this, Fn, flags: cleanupFlags, ActiveFlag: EHActiveFlag);
1074 }
1075
1076 if (CPI)
1077 Builder.CreateCleanupRet(CleanupPad: CPI, UnwindBB: NextAction);
1078 else
1079 Builder.CreateBr(Dest: NextAction);
1080
1081 // Leave the terminate scope.
1082 if (PushedTerminate)
1083 EHStack.popTerminate();
1084
1085 Builder.restoreIP(IP: SavedIP);
1086
1087 SimplifyCleanupEntry(CGF&: *this, Entry: 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.
1094bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
1095 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1096 && "stale jump destination");
1097
1098 // Calculate the innermost active normal cleanup.
1099 EHScopeStack::stable_iterator TopCleanup =
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(I: 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.
1119void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
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: Dest.getBlock());
1128 addInstToCurrentSourceAtom(KeyInstruction: BI, Backup: nullptr);
1129
1130 // Calculate the innermost active normal cleanup.
1131 EHScopeStack::stable_iterator
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(I: 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(C: Dest.getDestIndex());
1160 createStoreInstBefore(value: Index, addr: getNormalCleanupDestSlot(), beforeInst: BI->getIterator(),
1161 CGF&: *this);
1162
1163 // Adjust BI to point to the first cleanup block.
1164 {
1165 EHCleanupScope &Scope =
1166 cast<EHCleanupScope>(Val&: *EHStack.find(sp: TopCleanup));
1167 BI->setSuccessor(idx: 0, NewSucc: CreateNormalEntry(CGF&: *this, Scope));
1168 }
1169
1170 // Add this destination to all the scopes involved.
1171 EHScopeStack::stable_iterator I = TopCleanup;
1172 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1173 if (E.strictlyEncloses(I)) {
1174 while (true) {
1175 EHCleanupScope &Scope = cast<EHCleanupScope>(Val&: *EHStack.find(sp: I));
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, Block: 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(Block: 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(sp: 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(sp: i);
1209 if (scope.hasEHBranches())
1210 return true;
1211
1212 i = scope.getEnclosingEHScope();
1213 }
1214
1215 return false;
1216}
1217
1218enum ForActivation_t {
1219 ForActivation,
1220 ForDeactivation
1221};
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.
1228static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1229 EHScopeStack::stable_iterator C,
1230 ForActivation_t kind,
1231 llvm::Instruction *dominatingIP) {
1232 EHCleanupScope &Scope = cast<EHCleanupScope>(Val&: *CGF.EHStack.find(sp: C));
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 =
1238 (kind == ForActivation && CGF.isInConditionalBranch());
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(EHStack&: CGF.EHStack, cleanup: 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(Ty: CGF.Builder.getInt1Ty(), UseAddrSpace: LangAS::Default,
1265 align: CharUnits::One(), Name: "cleanup.isactive");
1266 Scope.setActiveFlag(var);
1267 Scope.AddAuxAllocas(Allocas: 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(V: 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, addr: var, CGF);
1279 } else {
1280 createStoreInstBefore(value, addr: var, beforeInst: dominatingIP->getIterator(), CGF);
1281 }
1282 }
1283
1284 CGF.Builder.CreateStore(Val: CGF.Builder.getInt1(V: kind == ForActivation), Addr: var);
1285}
1286
1287/// Activate a cleanup that was created in an inactivated state.
1288void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1289 llvm::Instruction *dominatingIP) {
1290 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1291 EHCleanupScope &Scope = cast<EHCleanupScope>(Val&: *EHStack.find(sp: C));
1292 assert(!Scope.isActive() && "double activation");
1293
1294 SetupCleanupBlockActivation(CGF&: *this, C, kind: ForActivation, dominatingIP);
1295
1296 Scope.setActive(true);
1297}
1298
1299/// Deactive a cleanup that was created in an active state.
1300void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1301 llvm::Instruction *dominatingIP) {
1302 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1303 EHCleanupScope &Scope = cast<EHCleanupScope>(Val&: *EHStack.find(sp: C));
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(I: C)) {
1310 PopCleanupBlock(/*FallthroughIsBranchThrough=*/false,
1311 /*ForDeactivation=*/true);
1312 return;
1313 }
1314
1315 // Otherwise, follow the general case.
1316 SetupCleanupBlockActivation(CGF&: *this, C, kind: ForDeactivation, dominatingIP);
1317
1318 Scope.setActive(false);
1319}
1320
1321RawAddress CodeGenFunction::getNormalCleanupDestSlot() {
1322 if (!NormalCleanupDest.isValid())
1323 NormalCleanupDest =
1324 CreateDefaultAlignTempAlloca(Ty: Builder.getInt32Ty(), Name: "cleanup.dest.slot");
1325 return NormalCleanupDest;
1326}
1327
1328/// Emits all the code to cause the given temporary to be cleaned up.
1329void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1330 QualType TempType,
1331 Address Ptr) {
1332 pushDestroy(kind: NormalAndEHCleanup, addr: Ptr, type: TempType, destroyer: destroyCXXObject,
1333 /*useEHCleanup*/ useEHCleanupForArray: true);
1334}
1335
1336// Need to set "funclet" in OperandBundle properly for noThrow
1337// intrinsic (see CGCall.cpp)
1338static void EmitSehScope(CodeGenFunction &CGF,
1339 llvm::FunctionCallee &SehCppScope) {
1340 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
1341 assert(CGF.Builder.GetInsertBlock() && InvokeDest);
1342 llvm::BasicBlock *Cont = CGF.createBasicBlock(name: "invoke.cont");
1343 SmallVector<llvm::OperandBundleDef, 1> BundleList =
1344 CGF.getBundlesForFunclet(Callee: SehCppScope.getCallee());
1345 if (CGF.CurrentFuncletPad)
1346 BundleList.emplace_back(Args: "funclet", Args&: CGF.CurrentFuncletPad);
1347 CGF.Builder.CreateInvoke(Callee: SehCppScope, NormalDest: Cont, UnwindDest: InvokeDest, Args: {}, OpBundles: BundleList);
1348 CGF.EmitBlock(BB: Cont);
1349}
1350
1351// Invoke a llvm.seh.scope.begin at the beginning of a CPP scope for -EHa
1352void CodeGenFunction::EmitSehCppScopeBegin() {
1353 assert(getLangOpts().EHAsynch);
1354 llvm::FunctionCallee SehCppScope =
1355 CGM.getIntrinsic(IID: llvm::Intrinsic::seh_scope_begin);
1356 EmitSehScope(CGF&: *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"
1361void CodeGenFunction::EmitSehCppScopeEnd() {
1362 assert(getLangOpts().EHAsynch);
1363 llvm::FunctionCallee SehCppScope =
1364 CGM.getIntrinsic(IID: llvm::Intrinsic::seh_scope_end);
1365 EmitSehScope(CGF&: *this, SehCppScope);
1366}
1367
1368// Invoke a llvm.seh.try.begin at the beginning of a SEH scope for -EHa
1369void CodeGenFunction::EmitSehTryScopeBegin() {
1370 assert(getLangOpts().EHAsynch);
1371 llvm::FunctionCallee SehCppScope =
1372 CGM.getIntrinsic(IID: llvm::Intrinsic::seh_try_begin);
1373 EmitSehScope(CGF&: *this, SehCppScope);
1374}
1375
1376// Invoke a llvm.seh.try.end at the end of a SEH scope for -EHa
1377void CodeGenFunction::EmitSehTryScopeEnd() {
1378 assert(getLangOpts().EHAsynch);
1379 llvm::FunctionCallee SehCppScope =
1380 CGM.getIntrinsic(IID: llvm::Intrinsic::seh_try_end);
1381 EmitSehScope(CGF&: *this, SehCppScope);
1382}
1383