[clang] [clang][bytecode] Support compile-time exceptions (PR #189410)
Timm Baeder via cfe-commits
cfe-commits at lists.llvm.org
Fri Dec 4 04:06:33 PST 2026
https://github.com/tbaederr updated https://github.com/llvm/llvm-project/pull/189410
>From dd58b9dc180cf6a7a9d62e987922ec155ae73f5a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= <tbaeder at redhat.com>
Date: Tue, 10 Feb 2026 16:06:17 +0100
Subject: [PATCH] Exceptions
---
.../include/clang/Basic/DiagnosticASTKinds.td | 5 +
clang/lib/AST/ByteCode/Block.h | 7 +-
clang/lib/AST/ByteCode/ByteCodeEmitter.cpp | 3 +-
clang/lib/AST/ByteCode/ByteCodeEmitter.h | 10 +
clang/lib/AST/ByteCode/CleanupScope.h | 530 ++
clang/lib/AST/ByteCode/Compiler.cpp | 968 +++-
clang/lib/AST/ByteCode/Compiler.h | 60 +-
clang/lib/AST/ByteCode/Context.cpp | 3 +
clang/lib/AST/ByteCode/Context.h | 2 +
clang/lib/AST/ByteCode/DeclOrExpr.h | 11 +-
clang/lib/AST/ByteCode/Descriptor.cpp | 2 +-
clang/lib/AST/ByteCode/Descriptor.h | 2 -
clang/lib/AST/ByteCode/Disasm.cpp | 102 +-
clang/lib/AST/ByteCode/EvalEmitter.cpp | 17 +
clang/lib/AST/ByteCode/EvalEmitter.h | 11 +
clang/lib/AST/ByteCode/Exceptions.cpp | 173 +
clang/lib/AST/ByteCode/Exceptions.h | 84 +
clang/lib/AST/ByteCode/Function.cpp | 18 +
clang/lib/AST/ByteCode/Function.h | 22 +-
clang/lib/AST/ByteCode/Interp.cpp | 338 +-
clang/lib/AST/ByteCode/Interp.h | 78 +-
clang/lib/AST/ByteCode/InterpFrame.cpp | 6 +-
clang/lib/AST/ByteCode/InterpFrame.h | 8 +-
clang/lib/AST/ByteCode/InterpStack.h | 2 +
clang/lib/AST/ByteCode/InterpState.cpp | 8 +
clang/lib/AST/ByteCode/InterpState.h | 25 +-
clang/lib/AST/ByteCode/Opcodes.td | 36 +-
clang/lib/AST/ByteCode/PrimType.h | 3 +
clang/lib/AST/ByteCode/Reflect.h | 8 +
clang/lib/AST/CMakeLists.txt | 1 +
clang/test/AST/ByteCode/cxx20.cpp | 15 +-
clang/test/AST/ByteCode/cxx23.cpp | 4 +-
clang/test/AST/ByteCode/exceptions.cpp | 4591 +++++++++++++++++
clang/test/AST/ByteCode/invalid.cpp | 30 +-
34 files changed, 6875 insertions(+), 308 deletions(-)
create mode 100644 clang/lib/AST/ByteCode/CleanupScope.h
create mode 100644 clang/lib/AST/ByteCode/Exceptions.cpp
create mode 100644 clang/lib/AST/ByteCode/Exceptions.h
create mode 100644 clang/test/AST/ByteCode/exceptions.cpp
diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td b/clang/include/clang/Basic/DiagnosticASTKinds.td
index 21294d32c8963b..dcd846a02454db 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -426,6 +426,11 @@ def note_constexpr_infer_alloc_token_no_metadata : Note<
"could not get token metadata for inferred type">;
def note_constexpr_infer_alloc_token_unsupported_mode
: Note<"alloc token mode not supported in constexpr">;
+def note_constexpr_uncaught_exception : Note<"uncaught exception of type %0: '%1'">;
+def note_constexpr_exception_in_noexcept_func : Note<"uncaught exception in noexcept function">;
+def note_constexpr_no_active_exception : Note<"rethrow with no active exception">;
+def note_constexpr_throw_with_active_exception : Note<"throw while another exception is already active">;
+def note_previous_throw : Note<"currently active exception thrown here">;
def warn_attribute_needs_aggregate : Warning<
"%0 attribute is ignored in non-aggregate type %1">,
diff --git a/clang/lib/AST/ByteCode/Block.h b/clang/lib/AST/ByteCode/Block.h
index 731790ab4aebfa..d4386150cacf19 100644
--- a/clang/lib/AST/ByteCode/Block.h
+++ b/clang/lib/AST/ByteCode/Block.h
@@ -108,12 +108,7 @@ class Block final {
/// Checks if the block is temporary.
bool isTemporary() const { return Desc->IsTemporary; }
bool isWeak() const { return Flags.V & BlockFlags::Weak; }
- bool isDynamic() const {
- bool Result = (DynAllocId != std::nullopt);
- assert((Result == Desc->isDynAlloc()) &&
- "Inconsistent block/descriptor dynamic alloc state");
- return Result;
- }
+ bool isDynamic() const { return DynAllocId != std::nullopt; }
bool isDead() const { return Flags.V & BlockFlags::Dead; }
bool isConstexprUnknown() const {
return Flags.V & BlockFlags::ConstexprUnknown;
diff --git a/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp b/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp
index d023fffccf131e..2d388c870cc489 100644
--- a/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp
+++ b/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp
@@ -83,7 +83,8 @@ void ByteCodeEmitter::compileFunc(const FunctionDecl *FuncDecl,
// Set the function's code.
Func->setCode(FuncDecl, NextLocalOffset, std::move(Code), std::move(SrcMap),
- std::move(Scopes), FuncDecl->hasBody(), IsValid);
+ std::move(Scopes), std::move(ExceptionTable),
+ FuncDecl->hasBody(), IsValid);
Func->setIsFullyCompiled(true);
}
diff --git a/clang/lib/AST/ByteCode/ByteCodeEmitter.h b/clang/lib/AST/ByteCode/ByteCodeEmitter.h
index f76da925533087..6ed81054cadfca 100644
--- a/clang/lib/AST/ByteCode/ByteCodeEmitter.h
+++ b/clang/lib/AST/ByteCode/ByteCodeEmitter.h
@@ -83,6 +83,15 @@ class ByteCodeEmitter {
llvm::SmallVector<SmallVector<Local, 8>, 2> Descriptors;
std::optional<SourceInfo> LocOverride = std::nullopt;
+ unsigned currentCodeSize() const { return Code.size(); }
+
+ void registerExceptionHandler(uint32_t TryIndex, uint32_t ParentTry,
+ unsigned Target, QualType T,
+ bool IsCleanup = false) {
+ ExceptionTable.emplace_back(TryBlockID(TryIndex, ParentTry), Target, T,
+ IsCleanup);
+ }
+
private:
/// Current compilation context.
Context &Ctx;
@@ -98,6 +107,7 @@ class ByteCodeEmitter {
llvm::DenseMap<LabelTy, llvm::SmallVector<unsigned, 5>> LabelRelocs;
/// Program code.
llvm::SmallVector<std::byte> Code;
+ llvm::SmallVector<ExceptionTableEntry, 0> ExceptionTable;
/// Opcode to expression mapping.
SourceMap SrcMap;
diff --git a/clang/lib/AST/ByteCode/CleanupScope.h b/clang/lib/AST/ByteCode/CleanupScope.h
new file mode 100644
index 00000000000000..bb00a27153375b
--- /dev/null
+++ b/clang/lib/AST/ByteCode/CleanupScope.h
@@ -0,0 +1,530 @@
+//===---------------------- CleanupScope.h ----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_AST_INTERP_CLEANUPSCOPE_H
+#define LLVM_CLANG_AST_INTERP_CLEANUPSCOPE_H
+
+#include "Compiler.h"
+#include "llvm/Support/SaveAndRestore.h"
+
+namespace clang {
+namespace interp {
+
+/// Entry on the cleanup stack: what unwinding must emit when an exception
+/// propagates out of the entry's region. Entries are pushed and popped RAII
+/// style; unwinding walks them innermost first, up to the enclosing try block.
+///
+/// VariableScope is the entry for local variables. Other entries clean up
+/// things that aren't locals, e.g. the storage of a new-expression whose
+/// initializer throws.
+template <class Emitter> class CleanupScope {
+public:
+ explicit CleanupScope(Compiler<Emitter> *Ctx)
+ : Ctx(Ctx), Parent(Ctx->Cleanups) {
+ Ctx->Cleanups = this;
+ }
+ virtual ~CleanupScope() {
+ assert(Ctx->Cleanups == this);
+ Ctx->Cleanups = Parent;
+ }
+ CleanupScope(const CleanupScope &) = delete;
+ CleanupScope &operator=(const CleanupScope &) = delete;
+
+ /// Emit the cleanup for unwinding.
+ virtual bool emitEHCleanup() = 0;
+ /// Emit the cleanup for leaving the region normally via break, continue or
+ /// return.
+ virtual bool emitNormalCleanup() { return true; }
+ /// Whether emitEHCleanup() emits anything.
+ virtual bool needsEHCleanup() const = 0;
+ /// Whether unwinding stops after this entry.
+ virtual bool isTryBoundary() const { return false; }
+ /// Whether code emitted inside this entry is part of unwinding, where an
+ /// exception escaping a destructor terminates ([except.terminate]).
+ virtual bool isTerminate() const { return false; }
+
+ CleanupScope *getParent() const { return Parent; }
+
+protected:
+ Compiler<Emitter> *Ctx;
+ CleanupScope *Parent;
+};
+
+/// Unwinding stops here; the try block's handlers take over. Pushed below the
+/// try block's own scope, so its locals are destroyed first.
+template <class Emitter>
+class TryBoundary final : public CleanupScope<Emitter> {
+public:
+ TryBoundary(Compiler<Emitter> *Ctx, uint32_t TryIndex)
+ : CleanupScope<Emitter>(Ctx), TryIndex(TryIndex) {}
+
+ bool emitEHCleanup() override { return true; }
+ bool needsEHCleanup() const override { return false; }
+ bool isTryBoundary() const override { return true; }
+
+ /// Index of the try block in the function's exception table.
+ const uint32_t TryIndex;
+};
+
+/// Active while unwinding code is emitted; see isTerminate().
+template <class Emitter>
+class TerminateScope final : public CleanupScope<Emitter> {
+public:
+ using CleanupScope<Emitter>::CleanupScope;
+
+ bool emitEHCleanup() override { return true; }
+ bool needsEHCleanup() const override { return false; }
+ bool isTerminate() const override { return true; }
+};
+
+/// The exception object of a handler: destroyed whenever the handler is left,
+/// normally or by unwinding. Pushed below the handler's own scope, so the
+/// catch parameter is destroyed first.
+template <class Emitter>
+class ExceptionObjectCleanup final : public CleanupScope<Emitter> {
+public:
+ /// \p PtrOffset is a local holding a pointer to the exception object.
+ ExceptionObjectCleanup(Compiler<Emitter> *Ctx, unsigned PtrOffset,
+ bool DtorMayThrow)
+ : CleanupScope<Emitter>(Ctx), PtrOffset(PtrOffset),
+ DtorMayThrow(DtorMayThrow) {}
+
+ bool emitEHCleanup() override { return emitDestroy(); }
+ bool emitNormalCleanup() override { return emitDestroy(); }
+ bool needsEHCleanup() const override { return true; }
+
+ /// Destroy the exception object (unless it's being rethrown).
+ bool emitDestroy() const {
+ if (!DtorMayThrow) {
+ if (!this->Ctx->emitGetLocal(PT_Ptr, PtrOffset, {}))
+ return false;
+ return this->Ctx->emitDestroyException({});
+ }
+
+ // The exception object's destructor may throw.
+ if (!this->Ctx->emitPushThrowTrap({}))
+ return false;
+ if (!this->Ctx->emitGetLocal(PT_Ptr, PtrOffset, {}))
+ return false;
+ if (!this->Ctx->emitDestroyException({}))
+ return false;
+ if (!this->Ctx->emitPopThrowTrap({}))
+ return false;
+ typename Emitter::LabelTy SkipLabel = this->Ctx->getLabel();
+ if (!this->Ctx->jumpFalse(SkipLabel, {}))
+ return false;
+
+ if (this->Ctx->isTerminating()) {
+ // The handler is exited by unwinding: terminate.
+ if (!this->Ctx->emitInvalidThrow({}))
+ return false;
+ } else {
+ // Propagate from here; the entries above are already destroyed.
+ if (!this->Ctx->emitUnwindScopes({}, this->getParent()))
+ return false;
+ if (!this->Ctx->emitCatch(this->Ctx->currentTryIndex(), {}))
+ return false;
+ }
+ this->Ctx->emitLabel(SkipLabel);
+ return true;
+ }
+
+private:
+ unsigned PtrOffset;
+ /// Whether destroying the exception object may throw.
+ bool DtorMayThrow;
+};
+
+/// Destroys the already constructed subobjects of an aggregate or array under
+/// construction when a later initializer throws:
+/// P p = {S{}, mayThrow()}; // Destroys p.a, but not p.b.
+/// Normal completion emits nothing; the complete object owns its subobjects.
+template <class Emitter>
+class SubobjectCleanupScope final : public CleanupScope<Emitter> {
+public:
+ /// \p PtrOffset is a local holding a pointer to the object; none means the
+ /// object is 'this' (a constructor's member initializers).
+ SubobjectCleanupScope(Compiler<Emitter> *Ctx, UnsignedOrNone PtrOffset)
+ : CleanupScope<Emitter>(Ctx), PtrOffset(PtrOffset) {}
+
+ void addField(unsigned Offset, const Descriptor *Desc) {
+ if (!Desc->hasTrivialDtor())
+ Subobjects.push_back({Subobject::Field, Offset, Desc});
+ }
+ void addBase(unsigned Offset, const Descriptor *Desc) {
+ if (!Desc->hasTrivialDtor())
+ Subobjects.push_back({Subobject::Base, Offset, Desc});
+ }
+ void addElem(unsigned Index, const Descriptor *Desc) {
+ if (!Desc->hasTrivialDtor())
+ Subobjects.push_back({Subobject::Elem, Index, Desc});
+ }
+ /// Only constructed (and so only destroyed) in the most-derived object.
+ void addVirtBase(const Descriptor *Desc) {
+ if (!Desc->hasTrivialDtor())
+ Subobjects.push_back({Subobject::VirtBase, 0, Desc});
+ }
+
+ bool needsEHCleanup() const override { return !Subobjects.empty(); }
+
+ bool emitEHCleanup() override {
+ for (const Subobject &S : llvm::reverse(Subobjects)) {
+ if (PtrOffset ? !this->Ctx->emitGetLocal(PT_Ptr, *PtrOffset, {})
+ : !this->Ctx->emitThis({}))
+ return false;
+
+ if (S.K == Subobject::VirtBase) {
+ // Skip if the object is a base class subobject; see
+ // compileConstructorBody().
+ typename Emitter::LabelTy SkipLabel = this->Ctx->getLabel();
+ if (!this->Ctx->emitIsBaseClass({}) ||
+ !this->Ctx->jumpTrue(SkipLabel, {}))
+ return false;
+ if (!this->Ctx->emitGetPtrVirtBase(
+ cast<CXXRecordDecl>(S.Desc->asDecl()), {}) ||
+ !this->Ctx->emitDestructionPop(S.Desc, {}))
+ return false;
+ this->Ctx->fallthrough(SkipLabel);
+ this->Ctx->emitLabel(SkipLabel);
+ if (!this->Ctx->emitPopPtr({}))
+ return false;
+ continue;
+ }
+
+ switch (S.K) {
+ case Subobject::Field:
+ if (!this->Ctx->emitGetPtrFieldPop(S.Offset, {}))
+ return false;
+ break;
+ case Subobject::Base:
+ if (!this->Ctx->emitGetPtrBasePop(S.Offset, /*NullOK=*/false, {}))
+ return false;
+ break;
+ case Subobject::Elem:
+ if (!this->Ctx->emitConstUint32(S.Offset, {}) ||
+ !this->Ctx->emitArrayElemPtrPopUint32({}))
+ return false;
+ break;
+ case Subobject::VirtBase:
+ llvm_unreachable("Handled above");
+ }
+
+ if (!this->Ctx->emitDestructionPop(S.Desc, {}))
+ return false;
+ }
+ return true;
+ }
+
+private:
+ struct Subobject {
+ enum Kind { Field, Base, Elem, VirtBase } K;
+ /// Field/base offset or element index.
+ unsigned Offset;
+ const Descriptor *Desc;
+ };
+
+ UnsignedOrNone PtrOffset;
+ /// Constructed so far, in construction order.
+ llvm::SmallVector<Subobject, 4> Subobjects;
+};
+
+/// Destroys a destructor's subobjects after its body, also when the body is
+/// left by a return or an exception ([except.ctor]p3):
+/// ~T() {
+/// return;
+/// }
+/// Members and bases are still destroyed.
+template <class Emitter>
+class DtorSubobjectsCleanup final : public CleanupScope<Emitter> {
+public:
+ DtorSubobjectsCleanup(Compiler<Emitter> *Ctx, const CXXDestructorDecl *Dtor,
+ const Record *R)
+ : CleanupScope<Emitter>(Ctx), Dtor(Dtor) {
+ // Destruction order: fields, bases, virtual bases; each in reverse.
+ if (!R->isUnion()) {
+ for (const Record::Field &F : llvm::reverse(R->fields())) {
+ if (F.Desc->hasTrivialDtor())
+ continue;
+ Subobjects.push_back({Subobject::Field, F.Offset, F.Desc, nullptr});
+ AnyMayThrow |= !F.Desc->hasNothrowDtor();
+ }
+ }
+ for (const Record::Base &B : llvm::reverse(R->bases())) {
+ if (B.R->hasTrivialDtor())
+ continue;
+ Subobjects.push_back({Subobject::Base, B.Offset, nullptr, B.R});
+ AnyMayThrow |= !B.R->hasNothrowDtor();
+ }
+ for (const Record::Base &B : llvm::reverse(R->virtual_bases())) {
+ if (B.R->hasTrivialDtor())
+ continue;
+ Subobjects.push_back({Subobject::VirtBase, 0, nullptr, B.R});
+ AnyMayThrow |= !B.R->hasNothrowDtor();
+ }
+ }
+
+ bool emitNormalCleanup() override { return emitDestroy(); }
+ bool emitEHCleanup() override { return emitDestroy(); }
+ bool needsEHCleanup() const override { return true; }
+
+ /// Destroy the subobjects not destroyed yet and end the object's lifetime.
+ bool emitDestroy() {
+ Compiler<Emitter> *Ctx = this->Ctx;
+ if (!Ctx->Ctx.ExceptionsEnabled || !AnyMayThrow)
+ return emitDestroyAll();
+
+ if (DestroyedUpTo == 0) {
+ if (!Ctx->emitThis(Dtor) || !Ctx->emitCheckDestruction(Dtor) ||
+ !Ctx->emitPopPtr(Dtor))
+ return false;
+ }
+
+ for (unsigned I = DestroyedUpTo, N = Subobjects.size(); I != N; ++I) {
+ // If subobject I's destructor throws, unwinding destroys the rest.
+ llvm::SaveAndRestore SR(DestroyedUpTo, I + 1);
+ if (!emitDestroy(Subobjects[I]))
+ return false;
+ }
+
+ return Ctx->emitThis(Dtor) && Ctx->emitMarkDestroyed(Dtor) &&
+ Ctx->emitPopPtr(Dtor);
+ }
+
+private:
+ /// Without exceptions, or if no subobject's destructor may throw, no
+ /// destruction is ever resumed partway, so 'this' stays on the stack
+ /// throughout.
+ bool emitDestroyAll() {
+ Compiler<Emitter> *Ctx = this->Ctx;
+ if (!Ctx->emitThis(Dtor) || !Ctx->emitCheckDestruction(Dtor))
+ return false;
+
+ LocOverrideScope<Emitter> LOS(Ctx, SourceInfo{});
+ std::optional<typename Emitter::LabelTy> VirtBasesEnd;
+ for (const Subobject &S : Subobjects) {
+ switch (S.K) {
+ case Subobject::Field:
+ if (!Ctx->emitGetPtrField(S.Offset, {}) ||
+ !Ctx->emitDestructionPop(S.Desc, {}))
+ return false;
+ break;
+ case Subobject::Base:
+ if (!Ctx->emitGetPtrBase(S.Offset, {}) ||
+ !Ctx->emitRecordDestructionPop(S.R, {}))
+ return false;
+ break;
+ case Subobject::VirtBase:
+ // Only the most-derived object destroys virtual bases. They come
+ // last, so skip all of them at once.
+ if (!VirtBasesEnd) {
+ VirtBasesEnd = Ctx->getLabel();
+ if (!Ctx->emitIsBaseClass({}) || !Ctx->jumpTrue(*VirtBasesEnd, {}))
+ return false;
+ }
+ if (!Ctx->emitGetPtrVirtBase(cast<CXXRecordDecl>(S.R->getDecl()), {}) ||
+ !Ctx->emitRecordDestructionPop(S.R, {}))
+ return false;
+ break;
+ }
+ }
+
+ if (VirtBasesEnd) {
+ Ctx->fallthrough(*VirtBasesEnd);
+ Ctx->emitLabel(*VirtBasesEnd);
+ }
+ return Ctx->emitMarkDestroyed(Dtor) && Ctx->emitPopPtr(Dtor);
+ }
+
+ struct Subobject {
+ enum Kind { Field, Base, VirtBase } K;
+ unsigned Offset;
+ /// Field descriptor; may be an array.
+ const Descriptor *Desc;
+ /// Base record.
+ const Record *R;
+ };
+
+ bool emitDestroy(const Subobject &S) {
+ Compiler<Emitter> *Ctx = this->Ctx;
+ LocOverrideScope<Emitter> LOS(Ctx, SourceInfo{});
+ if (!Ctx->emitThis({}))
+ return false;
+
+ switch (S.K) {
+ case Subobject::Field:
+ return Ctx->emitGetPtrFieldPop(S.Offset, {}) &&
+ Ctx->emitDestructionPop(S.Desc, {});
+ case Subobject::Base:
+ return Ctx->emitGetPtrBasePop(S.Offset, /*NullOK=*/false, {}) &&
+ Ctx->emitRecordDestructionPop(S.R, {});
+ case Subobject::VirtBase: {
+ // Only the most-derived object destroys virtual bases.
+ typename Emitter::LabelTy SkipLabel = Ctx->getLabel();
+ if (!Ctx->emitIsBaseClass({}) || !Ctx->jumpTrue(SkipLabel, {}))
+ return false;
+ if (!Ctx->emitGetPtrVirtBase(cast<CXXRecordDecl>(S.R->getDecl()), {}) ||
+ !Ctx->emitRecordDestructionPop(S.R, {}))
+ return false;
+ Ctx->fallthrough(SkipLabel);
+ Ctx->emitLabel(SkipLabel);
+ return Ctx->emitPopPtr({});
+ }
+ }
+ llvm_unreachable("Unhandled subobject kind");
+ }
+
+ const CXXDestructorDecl *Dtor;
+ llvm::SmallVector<Subobject, 4> Subobjects;
+ /// While destroying subobject I: I + 1, i.e. subobjects before that are
+ /// destroyed (or being destroyed).
+ unsigned DestroyedUpTo = 0;
+ /// Whether any subobject's destructor may throw.
+ bool AnyMayThrow = false;
+};
+
+/// Once the target constructor of a delegating constructor completes, the
+/// object is complete: an exception from the delegating constructor's body
+/// runs its destructor ([except.ctor]p4):
+/// T(int) : T() {
+/// throw 1;
+/// } // ~T() runs.
+template <class Emitter>
+class DelegatingCtorCleanup final : public CleanupScope<Emitter> {
+public:
+ DelegatingCtorCleanup(Compiler<Emitter> *Ctx, const Record *R)
+ : CleanupScope<Emitter>(Ctx), R(R) {
+ assert(R);
+ }
+
+ bool needsEHCleanup() const override { return true; }
+ bool emitEHCleanup() override {
+ return this->Ctx->emitThis({}) &&
+ this->Ctx->emitRecordDestructionPop(R, {});
+ }
+
+private:
+ const Record *R;
+};
+
+/// Destroys the remaining elements of an array when an element's destructor
+/// throws ([except.ctor]p3):
+/// S a[3];
+/// // ~S() of a[1] throws -> a[0] is still destroyed.
+/// While element I > 0 is destroyed, the array pointer is on top of the stack.
+template <class Emitter>
+class ArrayDestroyCleanup final : public CleanupScope<Emitter> {
+public:
+ ArrayDestroyCleanup(Compiler<Emitter> *Ctx, const Descriptor *ElemDesc,
+ SourceInfo Loc)
+ : CleanupScope<Emitter>(Ctx), ElemDesc(ElemDesc), Loc(Loc) {}
+
+ bool needsEHCleanup() const override { return Remaining != 0; }
+ bool emitEHCleanup() override {
+ if (Remaining == 0)
+ return true;
+ return this->Ctx->emitArrayElemsDestructionPop(ElemDesc, Remaining,
+ /*Cleanup=*/nullptr, Loc);
+ }
+
+ /// While element I is destroyed: I, i.e. elements [0, I) are still alive.
+ unsigned Remaining = 0;
+
+private:
+ const Descriptor *ElemDesc;
+ SourceInfo Loc;
+};
+
+/// Frees the storage of a new-expression whose initializer throws, without
+/// running destructors ([expr.new]p26):
+/// new T(mayThrow()); // T never existed; only the memory is released.
+template <class Emitter>
+class NewAllocCleanup final : public CleanupScope<Emitter> {
+public:
+ /// \p PtrOffset is a local holding the pointer returned by the allocation.
+ NewAllocCleanup(Compiler<Emitter> *Ctx, unsigned PtrOffset, bool IsArray)
+ : CleanupScope<Emitter>(Ctx), PtrOffset(PtrOffset), IsArray(IsArray) {}
+
+ bool needsEHCleanup() const override { return true; }
+ bool emitEHCleanup() override {
+ return this->Ctx->emitGetLocal(PT_Ptr, PtrOffset, {}) &&
+ this->Ctx->emitFree(IsArray, /*IsGlobalDelete=*/false,
+ /*RunDtors=*/false, {});
+ }
+
+ unsigned getPtrOffset() const { return PtrOffset; }
+
+private:
+ unsigned PtrOffset;
+ bool IsArray;
+};
+
+/// Destroys the elements of an array new-expression constructed so far by its
+/// runtime loop, in reverse order:
+/// new S[n]; // Element I throws -> destroys I-1, ..., 0.
+/// The loop counter holds the number of constructed elements.
+template <class Emitter>
+class ArrayElemsCleanup final : public CleanupScope<Emitter> {
+public:
+ ArrayElemsCleanup(Compiler<Emitter> *Ctx, const Expr *Source,
+ unsigned PtrOffset, unsigned IterOffset, PrimType IterT,
+ const Descriptor *ElemDesc)
+ : CleanupScope<Emitter>(Ctx), Source(Source), PtrOffset(PtrOffset),
+ IterOffset(IterOffset), IterT(IterT), ElemDesc(ElemDesc) {}
+
+ bool needsEHCleanup() const override { return true; }
+ bool emitEHCleanup() override {
+ Compiler<Emitter> *Ctx = this->Ctx;
+ typename Emitter::LabelTy StartLabel = Ctx->getLabel();
+ typename Emitter::LabelTy EndLabel = Ctx->getLabel();
+
+ // while (Iter > 0)
+ Ctx->fallthrough(StartLabel);
+ Ctx->emitLabel(StartLabel);
+ if (!Ctx->emitGetLocal(IterT, IterOffset, Source))
+ return false;
+ if (!Ctx->emitZero(IterT, Source))
+ return false;
+ if (!Ctx->emitGT(IterT, Source))
+ return false;
+ if (!Ctx->jumpFalse(EndLabel, Source))
+ return false;
+
+ // --Iter;
+ if (!Ctx->emitGetPtrLocal(IterOffset, Source))
+ return false;
+ if (!Ctx->emitDecPop(IterT, /*CanOverflow=*/false, Source))
+ return false;
+ // destroy Ptr[Iter];
+ if (!Ctx->emitGetLocal(PT_Ptr, PtrOffset, Source))
+ return false;
+ if (!Ctx->emitGetLocal(IterT, IterOffset, Source))
+ return false;
+ if (!Ctx->emitArrayElemPtrPop(IterT, Source))
+ return false;
+ if (!Ctx->emitDestructionPop(ElemDesc, Source))
+ return false;
+ if (!Ctx->jump(StartLabel, Source))
+ return false;
+
+ Ctx->fallthrough(EndLabel);
+ Ctx->emitLabel(EndLabel);
+ return true;
+ }
+
+private:
+ const Expr *Source;
+ const unsigned PtrOffset;
+ const unsigned IterOffset;
+ const PrimType IterT;
+ const Descriptor *ElemDesc;
+};
+
+} // namespace interp
+} // namespace clang
+
+#endif
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp b/clang/lib/AST/ByteCode/Compiler.cpp
index 0473235696c88e..0699dba8b778e5 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -9,6 +9,7 @@
#include "Compiler.h"
#include "../ExprConstShared.h"
#include "ByteCodeEmitter.h"
+#include "CleanupScope.h"
#include "Context.h"
#include "FixedPoint.h"
#include "Floating.h"
@@ -74,17 +75,29 @@ template <class Emitter> class RegisterLocalScope {
const ScopeKind VarScope;
};
-/// Scope chain managing the variable lifetimes.
-template <class Emitter> class VariableScope {
+[[maybe_unused]] static bool blockEndsInReturn(const Stmt *S) {
+ if (isa<ReturnStmt>(S))
+ return true;
+
+ if (const auto *CS = dyn_cast<CompoundStmt>(S); CS && !CS->body_empty())
+ return isa<ReturnStmt>(CS->body_back());
+
+ return false;
+}
+
+/// Scope chain managing the variable lifetimes. Also an entry on the cleanup
+/// stack: leaving the scope early (return, break, unwinding) destroys its
+/// locals.
+template <class Emitter> class VariableScope : public CleanupScope<Emitter> {
public:
VariableScope(Compiler<Emitter> *Ctx, ScopeKind Kind = ScopeKind::Block)
- : Ctx(Ctx), Parent(Ctx->VarScope), Kind(Kind) {
- if (Parent)
- this->LocalsAlwaysEnabled = Parent->LocalsAlwaysEnabled;
+ : CleanupScope<Emitter>(Ctx), ParentScope(Ctx->VarScope), Kind(Kind) {
+ if (ParentScope)
+ this->LocalsAlwaysEnabled = ParentScope->LocalsAlwaysEnabled;
Ctx->VarScope = this;
}
- virtual ~VariableScope() { Ctx->VarScope = this->Parent; }
+ ~VariableScope() override { this->Ctx->VarScope = this->ParentScope; }
virtual void addLocal(Scope::Local Local) {
llvm_unreachable("Shouldn't be called");
@@ -100,11 +113,11 @@ template <class Emitter> class VariableScope {
}
// If we reached the root scope and we're looking for a Block scope,
// attach it to the root instead of the current scope.
- if (!P->Parent && Kind == ScopeKind::Block) {
+ if (!P->ParentScope && Kind == ScopeKind::Block) {
P->addLocal(Local);
return;
}
- P = P->Parent;
+ P = P->ParentScope;
if (!P)
break;
}
@@ -115,8 +128,13 @@ template <class Emitter> class VariableScope {
virtual bool emitDestructors(const Expr *E = nullptr) { return true; }
virtual bool destroyLocals(const Expr *E = nullptr) { return true; }
- VariableScope *getParent() const { return Parent; }
+ bool emitEHCleanup() override { return true; }
+ bool emitNormalCleanup() override { return true; }
+ bool needsEHCleanup() const override { return false; }
+
+ VariableScope *getParentScope() const { return ParentScope; }
ScopeKind getKind() const { return Kind; }
+ bool is(ScopeKind K) const { return Kind == K; }
/// Whether locals added to this scope are enabled by default.
/// This is almost always true, except for the two branches
@@ -124,10 +142,8 @@ template <class Emitter> class VariableScope {
bool LocalsAlwaysEnabled = true;
protected:
- /// Compiler instance.
- Compiler<Emitter> *Ctx;
- /// Link to the parent scope.
- VariableScope *Parent;
+ /// Link to the parent variable scope.
+ VariableScope *ParentScope;
ScopeKind Kind;
};
@@ -162,6 +178,21 @@ template <class Emitter> class LocalScope : public VariableScope<Emitter> {
return Success;
}
+ // Side exits (return, break, unwinding) destroy the locals, but don't mark
+ // the scope destroyed: its normal end still needs its own Destroy.
+ bool emitEHCleanup() override { return emitExitDestroy(); }
+ bool emitNormalCleanup() override { return emitExitDestroy(); }
+ bool needsEHCleanup() const override { return NeedsCleanup; }
+
+ bool emitExitDestroy() {
+ if (!Idx)
+ return true;
+
+ bool Success = this->emitDestructors();
+ this->Ctx->emitDestroy(*Idx, SourceInfo{});
+ return Success;
+ }
+
void addLocal(Scope::Local Local) override {
if (!Idx) {
Idx = static_cast<unsigned>(this->Ctx->Descriptors.size());
@@ -170,6 +201,7 @@ template <class Emitter> class LocalScope : public VariableScope<Emitter> {
Local.EnabledByDefault = this->LocalsAlwaysEnabled;
this->Ctx->Descriptors[*Idx].emplace_back(Local);
+ NeedsCleanup |= !Local.Desc->hasTrivialDtor();
}
bool emitDestructors(const Expr *E = nullptr) override {
@@ -177,10 +209,14 @@ template <class Emitter> class LocalScope : public VariableScope<Emitter> {
return true;
// Emit destructor calls for local variables of record
- // type with a destructor.
- for (Scope::Local &Local : llvm::reverse(this->Ctx->Descriptors[*Idx])) {
+ // type with a destructor. If one throws, unwinding destroys only the
+ // locals before it; see DestroyedFrom.
+ const auto &Locals = this->Ctx->Descriptors[*Idx];
+ for (unsigned I = DestroyedFrom.value_or(Locals.size()); I-- > 0;) {
+ const Scope::Local &Local = Locals[I];
if (Local.Desc->hasTrivialDtor())
continue;
+ llvm::SaveAndRestore<UnsignedOrNone> SR(DestroyedFrom, I);
if (!Local.EnabledByDefault) {
typename Emitter::LabelTy EndLabel = this->Ctx->getLabel();
@@ -227,7 +263,11 @@ template <class Emitter> class LocalScope : public VariableScope<Emitter> {
/// Index of the scope in the chain.
UnsignedOrNone Idx = std::nullopt;
+ /// While emitting the destructor of local I: I, i.e. locals I and later are
+ /// destroyed (or being destroyed).
+ UnsignedOrNone DestroyedFrom = std::nullopt;
bool ExplicitlyDestroyed = false;
+ bool NeedsCleanup = false;
};
template <class Emitter> class ArrayIndexScope final {
@@ -2362,6 +2402,25 @@ bool Compiler<Emitter>::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
return this->emitLoadPop(*T, E);
}
+/// If a later initializer of \p QT may throw after an earlier subobject was
+/// constructed, save the pointer to the object (on top of the stack) in a local
+/// and open a SubobjectCleanupScope using it.
+template <class Emitter>
+bool Compiler<Emitter>::emitSubobjectCleanupScope(
+ std::optional<SubobjectCleanupScope<Emitter>> &SCS, QualType QT,
+ unsigned NumInits, const Expr *E) {
+ if (!Ctx.ExceptionsEnabled || NumInits < 2 ||
+ QT.isDestructedType() != QualType::DK_cxx_destructor)
+ return true;
+
+ unsigned PtrOffset =
+ this->allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/false);
+ if (!this->emitDupPtr(E) || !this->emitSetLocal(PT_Ptr, PtrOffset, E))
+ return false;
+ SCS.emplace(this, PtrOffset);
+ return true;
+}
+
template <class Emitter>
bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
const Expr *ArrayFiller, const Expr *E) {
@@ -2490,6 +2549,10 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
}
assert(!R->isUnion());
+ std::optional<SubobjectCleanupScope<Emitter>> SubobjectScope;
+ if (!emitSubobjectCleanupScope(SubobjectScope, QT, Inits.size(), E))
+ return false;
+
for (unsigned BI = 0; BI != R->getNumBases(); ++BI) {
const Expr *Init = Inits[BI];
const Record::Base *B = R->getBase(BI);
@@ -2499,6 +2562,8 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
return false;
if (!this->visitInitializerPop(Init))
return false;
+ if (SubobjectScope)
+ SubobjectScope->addBase(B->Offset, B->Desc);
}
unsigned FieldIndex = 0;
@@ -2523,6 +2588,8 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
return false;
} else if (!initCompositeField(FieldToInit, Init)) {
return false;
+ } else if (SubobjectScope) {
+ SubobjectScope->addField(FieldToInit->Offset, FieldToInit->Desc);
}
++FI;
@@ -2548,6 +2615,17 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
return this->delegate(Inits[0]);
OptPrimType InitT = classify(CAT->getElementType());
+
+ bool HasFiller = ArrayFiller && !isa<NoInitExpr>(ArrayFiller);
+ std::optional<SubobjectCleanupScope<Emitter>> SubobjectScope;
+ if (!emitSubobjectCleanupScope(SubobjectScope, QT, Inits.size() + HasFiller,
+ E))
+ return false;
+ const Descriptor *ElemDesc =
+ SubobjectScope
+ ? P.createDescriptor(E, CAT->getElementType().getTypePtr())
+ : nullptr;
+
unsigned ElementIndex = 0;
for (const Expr *Init : Inits) {
if (const auto *EmbedS =
@@ -2577,16 +2655,20 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
} else {
if (!this->visitArrayElemInit(ElementIndex, Init, InitT))
return false;
+ if (SubobjectScope)
+ SubobjectScope->addElem(ElementIndex, ElemDesc);
++ElementIndex;
}
}
// Expand the filler expression.
// FIXME: This should go away.
- if (ArrayFiller && !isa<NoInitExpr>(ArrayFiller)) {
+ if (HasFiller) {
for (; ElementIndex != NumElems; ++ElementIndex) {
if (!this->visitArrayElemInit(ElementIndex, ArrayFiller, InitT))
return false;
+ if (SubobjectScope)
+ SubobjectScope->addElem(ElementIndex, ElemDesc);
}
}
@@ -3111,27 +3193,29 @@ bool Compiler<Emitter>::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
template <class Emitter>
bool Compiler<Emitter>::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
const Expr *SourceExpr = E->getSourceExpr();
- if (!SourceExpr)
- return false;
if (Initializing) {
assert(!DiscardResult);
return this->visitInitializer(SourceExpr);
}
- PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end()) {
if (DiscardResult)
return true;
+ PrimType SubExprT = classify(It->first).value_or(PT_Ptr);
return this->emitGetLocal(SubExprT, It->second, E);
}
+ if (!SourceExpr)
+ return false;
+
if (!this->visit(SourceExpr))
return false;
// At this point we either have the evaluated source expression or a pointer
// to an object on the stack. We want to create a local variable that stores
// this value.
+ PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
if (!this->emitSetLocal(SubExprT, LocalIndex, E))
return false;
@@ -3863,10 +3947,281 @@ bool Compiler<Emitter>::VisitPredefinedExpr(const PredefinedExpr *E) {
template <class Emitter>
bool Compiler<Emitter>::VisitCXXThrowExpr(const CXXThrowExpr *E) {
- if (E->getSubExpr() && !this->discard(E->getSubExpr()))
+ if (this->InStmtExpr)
+ return this->emitUnsupported(E);
+
+ // We do allow this in EvalEmitter (but not CXXTryStmt), so we can later
+ // diagnose thrown exceptions as uncaught.
+
+ const Expr *SubExpr = E->getSubExpr();
+ if (!Ctx.ExceptionsEnabled) {
+ if (SubExpr && !this->discard(SubExpr))
+ return false;
+ return this->emitInvalid(E);
+ }
+
+ // "throw;", rethrow the current exception.
+ if (!SubExpr) {
+ // Mark first, so the handlers exited below don't destroy the
+ // exception being rethrown.
+ if (!this->emitMarkRethrown(E))
+ return false;
+
+ if (!this->emitUnwindScopes(E))
+ return false;
+ return this->emitReThrow(currentTryIndex(), E);
+ }
+
+ QualType ExceptionType = SubExpr->getType();
+ OptPrimType ExceptionT = classify(SubExpr);
+ const Descriptor *Desc;
+ if (ExceptionT)
+ Desc = P.createDescriptor(SubExpr, *ExceptionT);
+ else
+ Desc = P.createDescriptor(SubExpr, ExceptionType.getTypePtr(),
+ /*IsConst=*/false);
+
+ if (!this->emitAllocException(Desc, E))
return false;
- return this->emitInvalid(E);
+ if (ExceptionT) {
+ if (!this->visit(SubExpr))
+ return false;
+ if (!this->emitInit(*ExceptionT, E))
+ return false;
+ } else {
+ if (!this->visitInitializer(SubExpr))
+ return false;
+ }
+
+ // Save the new exception as the exception object.
+ if (!this->emitSaveException(ExceptionType, E))
+ return false;
+
+ if (!this->emitUnwindScopes(E))
+ return false;
+
+ // Throw the exception object we just created.
+ return this->emitThrow(currentTryIndex(), E);
+}
+
+template <class Emitter>
+bool Compiler<Emitter>::emitCatchHandlers(const CXXTryStmt *S,
+ uint32_t TryIndex, uint32_t ParentTry,
+ bool IsFunctionTryBlock) {
+
+ // Jump after handlers if nothing was thrown.
+ // "eh.resume"
+ LabelTy EndLabel = this->getLabel();
+ this->jump(EndLabel, S);
+
+ // Register and emit all handlers.
+ unsigned NumHandlers = S->getNumHandlers();
+ for (unsigned I = 0; I != NumHandlers; ++I) {
+ LocalScope<Emitter> CS(this);
+
+ const CXXCatchStmt *Handler = S->getHandler(I);
+ const Stmt *HandlerBlock = Handler->getHandlerBlock();
+ const VarDecl *ExceptionDecl = Handler->getExceptionDecl();
+ QualType CatchType = Handler->getCaughtType();
+
+ unsigned HandlerOffset = this->currentCodeSize();
+
+ this->registerExceptionHandler(TryIndex, ParentTry, HandlerOffset,
+ CatchType);
+
+ unsigned ExceptionPtrOffset =
+ this->allocateLocalPrimitive(Handler, PT_Ptr, /*IsConst=*/false);
+ bool ExceptionDtorMayThrow =
+ CatchType.isNull() || CatchType.getNonReferenceType()->isRecordType();
+ // Leaving the catch handler scope needs to destroy the exception object.
+ ExceptionObjectCleanup<Emitter> ExceptionCleanup(this, ExceptionPtrOffset,
+ ExceptionDtorMayThrow);
+ LocalScope<Emitter> CatchScope(this, ScopeKind::Catch);
+
+ if (!this->emitGetPtrExceptionValue(Handler))
+ return false;
+ if (!this->emitSetLocal(PT_Ptr, ExceptionPtrOffset, Handler))
+ return false;
+
+ if (ExceptionDecl) {
+ if (OptPrimType T = classify(CatchType)) {
+ unsigned LocalOffset = allocateLocalPrimitive(
+ ExceptionDecl, *T, CatchType.isConstQualified());
+ QualType Pointee = CatchType->getPointeeType();
+ bool BindsConvertedPointer =
+ CatchType->isReferenceType() &&
+ (Pointee->isPointerType() || Pointee->isMemberPointerType());
+
+ if (BindsConvertedPointer) {
+ // A T& handler, T a pointer, binds to the converted pointer, not to
+ // the exception object ([except.handle]p3). Like GCC and Clang, also
+ // for non-const T; see canCatch():
+ // throw &d;
+ // catch (B *&bp) // bp refers to a B* copy of the D*.
+ PrimType PointeeT = classifyPrim(Pointee);
+ unsigned TmpOffset =
+ allocateLocalPrimitive(Handler, PointeeT, /*IsConst=*/true);
+ if (!this->emitGetExceptionValue(PointeeT, S))
+ return false;
+ if (!this->emitSetLocal(PointeeT, TmpOffset, S))
+ return false;
+ if (!this->emitGetPtrLocal(TmpOffset, S))
+ return false;
+ } else if (CatchType->isReferenceType()) {
+ if (!this->emitGetPtrExceptionValue(S))
+ return false;
+ } else {
+ if (!this->emitGetExceptionValue(*T, S))
+ return false;
+ }
+ if (!this->emitSetLocal(*T, LocalOffset, S))
+ return false;
+ } else {
+ UnsignedOrNone LocalOffset =
+ allocateLocal(ExceptionDecl, CatchType, ScopeKind::Catch);
+ if (!LocalOffset)
+ return false;
+ if (!this->emitGetPtrLocal(*LocalOffset, Handler))
+ return false;
+
+ // Copy the exception object to the local variable, either via copy ctor
+ // or memcpy.
+ if (const Expr *Init = ExceptionDecl->getInit()) {
+ assert(OpaqueValueExpr::findInCopyConstruct(Init));
+ OpaqueExprs.insert(
+ {OpaqueValueExpr::findInCopyConstruct(Init), ExceptionPtrOffset});
+
+ // The handler isn't active yet: an exception escaping the copy
+ // terminates ([except.terminate]p1).
+ TerminateScope<Emitter> TS(this);
+ if (!this->visitInitializerPop(Init))
+ return false;
+ } else {
+ if (!this->emitGetPtrExceptionValue(Handler))
+ return false;
+ if (!this->emitMemcpy(Handler))
+ return false;
+ if (!this->emitPopPtr(Handler))
+ return false;
+ }
+ }
+ } else {
+ // This is a catch-all handler.
+ }
+
+ if (!this->visitStmt(HandlerBlock))
+ return false;
+
+ // function-try-blocks in constructors and destructors implicitly rethrow at
+ // the end of their catch handlers.
+ if (IsFunctionTryBlock && !this->emitMarkRethrown(Handler))
+ return false;
+
+ // Call destructors of the exception object and locals.
+ if (!CatchScope.destroyLocals())
+ return false;
+ if (!ExceptionCleanup.emitDestroy())
+ return false;
+
+ if (!CS.destroyLocals())
+ return false;
+
+ if (IsFunctionTryBlock) {
+ if (!this->emitReThrow(currentTryIndex(), S))
+ return false;
+ continue;
+ }
+
+ if (blockEndsInReturn(HandlerBlock))
+ continue;
+
+ // Jump over remaining handlers right to the end.
+ this->jump(EndLabel, S);
+ }
+
+ if (!IsFunctionTryBlock && !emitTryCleanupPad(S, TryIndex, ParentTry))
+ return false;
+
+ this->fallthrough(EndLabel);
+ this->emitLabel(EndLabel);
+
+ return true;
+}
+
+/// No handler of the try statement matched: destroy the scopes between it and
+/// the enclosing try (or the function), then re-dispatch via Catch. Registered
+/// after the handlers, so it has the lowest priority for this try block.
+///
+/// S outer;
+/// try {
+/// throw 1;
+/// } catch (float) {
+/// }
+/// Since no catch handler matched the thrown type, we need to destroy `outer`
+/// anyway.
+template <class Emitter>
+bool Compiler<Emitter>::emitTryCleanupPad(const CXXTryStmt *S,
+ uint32_t TryIndex,
+ uint32_t ParentTry) {
+ bool NeedsPad = false;
+ for (CleanupScope<Emitter> *C = this->Cleanups; C; C = C->getParent()) {
+ if (C->needsEHCleanup()) {
+ NeedsPad = true;
+ break;
+ }
+ if (C->isTryBoundary())
+ break;
+ }
+ if (!NeedsPad)
+ return true;
+
+ // Normal control flow must not enter the pad.
+ LabelTy EndLabel = this->getLabel();
+ this->jump(EndLabel, S);
+
+ unsigned PadOffset = this->currentCodeSize();
+ this->registerExceptionHandler(TryIndex, ParentTry, PadOffset,
+ /*T=*/QualType(), /*IsCleanup=*/true);
+
+ if (!this->emitUnwindScopes(S))
+ return false;
+ if (!this->emitCatch(currentTryIndex(), S))
+ return false;
+
+ this->emitLabel(EndLabel);
+ return true;
+}
+
+template <class Emitter>
+bool Compiler<Emitter>::visitCXXTryStmt(const CXXTryStmt *S) {
+ if constexpr (std::is_same_v<Emitter, EvalEmitter>)
+ return false;
+
+ if (!Ctx.ExceptionsEnabled) {
+ // Ignore all handlers.
+ return this->visitStmt(S->getTryBlock());
+ }
+
+ if (this->InStmtExpr)
+ return this->emitUnsupported(S);
+
+ // Code inside the try block dispatches exceptions to its handlers via
+ // the try block's index; see currentTryIndex().
+ uint32_t ParentTry = currentTryIndex();
+ uint32_t TryIndex = NumTryBlocks;
+ ++NumTryBlocks;
+ {
+ TryBoundary<Emitter> TB(this, TryIndex);
+ LocalScope<Emitter> Scope(this);
+ const auto *TryBlock = cast<CompoundStmt>(S->getTryBlock());
+ if (!this->visitStmt(TryBlock))
+ return false;
+ if (!Scope.destroyLocals())
+ return false;
+ }
+
+ return this->emitCatchHandlers(S, TryIndex, ParentTry);
}
template <class Emitter>
@@ -4033,19 +4388,23 @@ bool Compiler<Emitter>::VisitCXXConstructExpr(const CXXConstructExpr *E) {
VarArgSize +=
align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
}
- if (!this->emitCallVar(Func, VarArgSize, E))
+ if (!emitCallAndCatch(Func->canThrow(), E, [&] {
+ return this->emitCallVar(Func, VarArgSize, E);
+ }))
return false;
} else {
- if (!this->emitCall(Func, 0, E)) {
- // When discarding, we don't need the result anyway, so clean up
- // the instance dup we did earlier in case surrounding code wants
- // to keep evaluating.
- if (DiscardResult)
- (void)this->emitPopPtr(E);
+ if (!emitCallAndCatch(Func->canThrow(), E, [&] {
+ if (this->emitCall(Func, 0, E))
+ return true;
+ // When discarding, we don't need the result anyway, so clean up
+ // the instance dup we did earlier in case surrounding code wants
+ // to keep evaluating.
+ if (DiscardResult)
+ (void)this->emitPopPtr(E);
+ return false;
+ }))
return false;
- }
}
-
if (DiscardResult)
return this->emitPopPtr(E);
return true;
@@ -4068,7 +4427,7 @@ bool Compiler<Emitter>::VisitCXXConstructExpr(const CXXConstructExpr *E) {
return false;
}
- return this->emitCall(Func, 0, E);
+ return this->call(Func, E);
}
const ConstantArrayType *CAT =
@@ -4293,7 +4652,7 @@ bool Compiler<Emitter>::VisitCXXInheritedCtorInitExpr(
++ParamIndex;
}
- return this->emitCall(F, 0, E);
+ return this->call(F, E);
}
// FIXME: This function has become rather unwieldy, especially
@@ -4361,6 +4720,17 @@ bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
}
}
+ // A throwing initializer must free the allocation.
+ std::optional<NewAllocCleanup<Emitter>> AllocCleanup;
+ auto pushAllocCleanup = [&]() -> bool {
+ unsigned PtrOffset =
+ this->allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/false);
+ if (!this->emitDupPtr(E) || !this->emitSetLocal(PT_Ptr, PtrOffset, E))
+ return false;
+ AllocCleanup.emplace(this, PtrOffset, E->isArray());
+ return true;
+ };
+
if (E->isArray()) {
std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
if (!ArraySizeExpr)
@@ -4403,6 +4773,8 @@ bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
return false;
}
+ if (Ctx.ExceptionsEnabled && Init && !pushAllocCleanup())
+ return false;
}
if (Init) {
@@ -4469,6 +4841,13 @@ bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
if (!this->emitSetLocal(SizeT, Iter, E))
return false;
+ // A throwing element initializer must destroy the elements before it,
+ // including the statically initialized ones.
+ std::optional<ArrayElemsCleanup<Emitter>> ElemsCleanup;
+ if (AllocCleanup && Desc && !Desc->hasTrivialDtor())
+ ElemsCleanup.emplace(this, E, AllocCleanup->getPtrOffset(), Iter,
+ SizeT, Desc);
+
this->fallthrough(StartLabel);
this->emitLabel(StartLabel);
// Condition. Iter < ArrayLen?
@@ -4520,7 +4899,7 @@ bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
return false;
} else {
assert(CtorFunc);
- if (!this->emitCall(CtorFunc, 0, E))
+ if (!this->call(CtorFunc, E))
return false;
}
@@ -4548,6 +4927,8 @@ bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
// Allocate just one element.
if (!this->emitAlloc(Desc, E))
return false;
+ if (Ctx.ExceptionsEnabled && Init && !pushAllocCleanup())
+ return false;
}
if (Init) {
@@ -4571,6 +4952,25 @@ bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
return true;
}
+/// Whether destroying the object(s) deleted by \p E may throw. Overriders of a
+/// non-throwing virtual destructor must be non-throwing too, so the static
+/// type suffices.
+static bool deleteMayThrow(const CXXDeleteExpr *E) {
+ const CXXRecordDecl *RD =
+ E->getDestroyedType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
+ if (!RD || !RD->hasDefinition())
+ return false;
+
+ const CXXDestructorDecl *Dtor = RD->getDestructor();
+ if (!Dtor || Dtor->isTrivial())
+ return false;
+
+ const auto *FPT = Dtor->getType()->castAs<FunctionProtoType>();
+ if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
+ return true;
+ return FPT->canThrow() != CT_Cannot;
+}
+
template <class Emitter>
bool Compiler<Emitter>::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
if (E->containsErrors())
@@ -4584,7 +4984,12 @@ bool Compiler<Emitter>::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
if (!this->visit(E->getArgument()))
return false;
- return this->emitFree(E->isArrayForm(), E->isGlobalDelete(), E);
+ // A throwing destructor makes the delete-expression throw. Free still
+ // deallocates the memory.
+ return emitCallAndCatch(deleteMayThrow(E), E, [&] {
+ return this->emitFree(E->isArrayForm(), E->isGlobalDelete(),
+ /*RunDtors=*/true, E);
+ });
}
template <class Emitter>
@@ -5589,9 +5994,9 @@ UnsignedOrNone Compiler<Emitter>::allocateTemporary(const Expr *E) {
VariableScope<Emitter> *S = VarScope;
assert(S);
// Attach to topmost scope.
- while (S->getParent())
- S = S->getParent();
- assert(S && !S->getParent());
+ while (S->getParentScope())
+ S = S->getParentScope();
+ assert(S && !S->getParentScope());
S->addLocal(Local);
return Local.Offset;
}
@@ -6474,6 +6879,17 @@ static bool isTrivialMemoryOperation(const CXXMethodDecl *MD) {
(MD->isTrivial() && isReadByLvalueToRvalueConversion(MD->getParent()));
}
+/// Whether an indirect call may throw, from the callee's type: a pointer to a
+/// non-throwing function only points to non-throwing functions.
+static bool calleeMayThrow(const CallExpr *E) {
+ QualType T = E->getCallee()->getType();
+ if (QualType Pointee = T->getPointeeType(); !Pointee.isNull())
+ T = Pointee;
+ if (const auto *FPT = T->getAs<FunctionProtoType>())
+ return FPT->canThrow();
+ return true;
+}
+
template <class Emitter>
bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) {
if (E->containsErrors())
@@ -6671,11 +7087,14 @@ bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) {
return false;
}
+ bool MayThrow = Ctx.ExceptionsEnabled;
if (FuncDecl) {
const Function *Func = getFunction(FuncDecl);
if (!Func)
return false;
+ MayThrow = MayThrow && Func->canThrow();
+
// In error cases, the function may be called with fewer arguments than
// parameters.
if (E->getNumArgs() < Func->getNumWrittenParams())
@@ -6702,7 +7121,10 @@ bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) {
for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
- if (!this->emitCallVirt(Func, VarArgSize, E))
+ // Overriders of a non-throwing virtual function are non-throwing too.
+ if (!emitCallAndCatch(MayThrow, E, [&] {
+ return this->emitCallVirt(Func, VarArgSize, E);
+ }))
return false;
} else if (Func->isVariadic()) {
uint32_t VarArgSize = 0;
@@ -6711,10 +7133,13 @@ bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) {
(isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
- if (!this->emitCallVar(Func, VarArgSize, E))
+
+ if (!emitCallAndCatch(MayThrow, E, [&] {
+ return this->emitCallVar(Func, VarArgSize, E);
+ }))
return false;
} else {
- if (!this->emitCall(Func, 0, E))
+ if (!this->call(Func, E))
return false;
}
} else {
@@ -6722,6 +7147,8 @@ bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) {
// the stack. Cleanup of the returned value if necessary will be done after
// the function call completed.
+ MayThrow = MayThrow && calleeMayThrow(E);
+
// Sum the size of all args from the call expr.
uint32_t ArgSize = 0;
for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
@@ -6738,7 +7165,9 @@ bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) {
if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
return false;
}
- if (!this->emitCallPtr(ArgSize, E, E))
+
+ if (!emitCallAndCatch(MayThrow, E,
+ [&] { return this->emitCallPtr(ArgSize, E, E); }))
return false;
}
@@ -7050,17 +7479,27 @@ bool Compiler<Emitter>::visitReturnStmt(const ReturnStmt *RS) {
if (!this->visitInitializerPop(RE))
return false;
+ // The returned object is handed to the caller only once all locals
+ // are destroyed ([except.ctor]p2):
+ // S f() {
+ // T t;
+ // return S{};
+ // }
+ // ~T() throws -> ~S() runs.
+ llvm::SaveAndRestore RestoreRV(PendingReturnValue);
+ if (Ctx.ExceptionsEnabled) {
+ if (const Record *R = getRecord(RE->getType());
+ R && !R->hasTrivialDtor())
+ PendingReturnValue = R;
+ }
+
this->emitCleanup();
return this->emitRetVoid(RS);
}
}
// Void return.
- if (!this->emitCleanup())
- return false;
- if (DtorEpilogLabel)
- return this->jump(*DtorEpilogLabel, RS);
-
+ this->emitCleanup();
return this->emitRetVoid(RS);
}
@@ -7374,12 +7813,8 @@ bool Compiler<Emitter>::visitBreakStmt(const BreakStmt *S) {
if (!TargetLabel)
return false;
- for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
- C = C->getParent()) {
- if (!C->destroyLocals())
- return false;
- }
-
+ if (!this->emitCleanup(BreakScope))
+ return false;
return this->jump(*TargetLabel, S);
}
@@ -7418,11 +7853,8 @@ bool Compiler<Emitter>::visitContinueStmt(const ContinueStmt *S) {
if (!TargetLabel)
return false;
- for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
- C = C->getParent()) {
- if (!C->destroyLocals())
- return false;
- }
+ if (!this->emitCleanup(ContinueScope))
+ return false;
return this->jump(*TargetLabel, S);
}
@@ -7612,12 +8044,6 @@ bool Compiler<Emitter>::visitAttributedStmt(const AttributedStmt *S) {
return true;
}
-template <class Emitter>
-bool Compiler<Emitter>::visitCXXTryStmt(const CXXTryStmt *S) {
- // Ignore all handlers.
- return this->visitStmt(S->getTryBlock());
-}
-
/// template for (auto x : {1, 2}) {}
///
/// This is not a loop from an AST perspective at all since it has already
@@ -7706,15 +8132,12 @@ bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
return false;
}
- if (!this->emitCall(Func, 0, LambdaCallOp))
+ if (!this->call(Func, LambdaCallOp))
return false;
this->emitCleanup();
- if (ReturnType)
- return this->emitRet(*ReturnType, MD);
- // Nothing to do, since we emitted the RVO pointer above.
- return this->emitRetVoid(MD);
+ return this->emitFunctionReturn(MD, ReturnType);
}
template <class Emitter>
@@ -7745,8 +8168,10 @@ static bool initNeedsOverridenLoc(const CXXCtorInitializer *Init) {
return false;
}
+/// Compile the constructor initializers and the given body statement.
template <class Emitter>
-bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
+bool Compiler<Emitter>::compileConstructorBody(const CXXConstructorDecl *Ctor,
+ const Stmt *Body) {
assert(!ReturnType);
// Only start the lifetime of the instance pointer.
@@ -7797,7 +8222,7 @@ bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
// No special case for NumFields == 0 here, so the Memcpy op
// below also does its checks in those cases.
- assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
+ assert(cast<CompoundStmt>(Body)->body_empty());
if (!this->emitThis(Ctor))
return false;
@@ -7810,6 +8235,13 @@ bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
unsigned FieldInits = 0;
InitLinkScope<Emitter> InitScope(this, InitLink::This());
+
+ // A throwing initializer must destroy the bases and members initialized
+ // before it.
+ std::optional<SubobjectCleanupScope<Emitter>> MemberCleanup;
+ if (Ctx.ExceptionsEnabled && !IsUnion && !R->hasTrivialDtor())
+ MemberCleanup.emplace(this, std::nullopt);
+
// First, initialize virtual bases if the records has them.
if (R->getNumVirtualBases() > 0) {
if (!this->emitThis(Ctor))
@@ -7827,11 +8259,14 @@ bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
if (const Type *Base = Init->getBaseClass();
Base && Init->isBaseVirtual()) {
const auto *BaseDecl = Base->castAsCXXRecordDecl();
- assert(R->findVirtualBase(BaseDecl));
+ const Record::Base *VB = R->findVirtualBase(BaseDecl);
+ assert(VB);
if (!this->emitGetPtrThisVirtBase(BaseDecl, Ctor))
return false;
if (!this->visitInitializerPop(Init->getInit()))
return false;
+ if (MemberCleanup)
+ MemberCleanup->addVirtBase(VB->Desc);
}
if (!VirtLocalScope.destroyLocals())
return false;
@@ -7856,6 +8291,8 @@ bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
initNeedsOverridenLoc(Init));
if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
return false;
+ if (MemberCleanup)
+ MemberCleanup->addField(F->Offset, F->Desc);
++FieldInits;
} else if (const Type *Base = Init->getBaseClass()) {
const auto *BaseDecl = Base->castAsCXXRecordDecl();
@@ -7863,17 +8300,19 @@ bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
if (Init->isBaseVirtual()) {
// See above.
continue;
- } else {
- // Base class initializer.
- // Get This Base and call initializer on it.
- const Record::Base *B = R->getBase(BaseDecl);
- assert(B);
- if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
- return false;
}
+ // Base class initializer.
+ // Get This Base and call initializer on it.
+ const Record::Base *B = R->getBase(BaseDecl);
+ assert(B);
+ if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
+ return false;
+
if (!this->visitInitializerPop(InitExpr))
return false;
+ if (MemberCleanup)
+ MemberCleanup->addBase(B->Offset, B->Desc);
} else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
LocOverrideScope<Emitter> LOS(this, SourceInfo{},
initNeedsOverridenLoc(Init));
@@ -7882,6 +8321,7 @@ bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
unsigned NestedFieldOffset = 0;
const Record::Field *NestedField = nullptr;
+ bool InUnion = false;
for (unsigned I = 0; I != ChainSize; ++I) {
const auto *FD = cast<FieldDecl>(IFD->chain()[I]);
const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
@@ -7890,6 +8330,7 @@ bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
NestedField = FieldRecord->getField(FD);
assert(NestedField);
IsUnion = IsUnion || FieldRecord->isUnion();
+ InUnion = InUnion || FieldRecord->isUnion();
NestedFieldOffset += NestedField->Offset;
@@ -7903,6 +8344,9 @@ bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
IsUnion))
return false;
+ // Union members are never destroyed implicitly.
+ if (MemberCleanup && !InUnion)
+ MemberCleanup->addField(NestedFieldOffset, NestedField->Desc);
// Mark all chain links as initialized.
unsigned InitFieldOffset = 0;
@@ -7940,101 +8384,115 @@ bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
return false;
}
- if (const Stmt *Body = Ctor->getBody()) {
+ std::optional<DelegatingCtorCleanup<Emitter>> DelegatingCleanup;
+ if (Ctx.ExceptionsEnabled && Ctor->isDelegatingConstructor() &&
+ !R->hasTrivialDtor())
+ DelegatingCleanup.emplace(this, R);
+
+ if (Body) {
+ const auto *CS = cast<CompoundStmt>(Body);
// Only emit the CtorCheck op for non-empty CompoundStmt bodies.
// For non-CompoundStmts, always assume they are non-empty and emit it.
- if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
- if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
- return false;
- } else {
- if (!this->emitCtorCheck(SourceInfo{}))
- return false;
- }
+ if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
+ return false;
- if (!visitStmt(Body))
+ if (!visitCompoundStmt(CS))
return false;
}
- return this->emitRetVoid(SourceInfo{});
+ return true;
}
template <class Emitter>
-bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
- const RecordDecl *RD = Dtor->getParent();
- const Record *R = this->getRecord(RD);
- if (!R)
+bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
+ if (!this->compileConstructorBody(Ctor, Ctor->getBody()))
return false;
+ return this->emitFunctionReturn(Ctor, ReturnType);
+}
- if (!Dtor->isTrivial() && Dtor->getBody()) {
- // If we return somewhere in the destructor body, we still need to destroy
- // the members and bases.
- LabelTy EpilogLabel = this->getLabel();
- {
- llvm::SaveAndRestore<OptLabelTy> SaveLabel(DtorEpilogLabel, EpilogLabel);
- if (!this->visitStmt(Dtor->getBody()))
- return false;
- }
- this->fallthrough(EpilogLabel);
- this->emitLabel(EpilogLabel);
+/// Compile a constructor immediately followed by try statement.
+/// The constructor initializers must be part of the try statement
+/// and the catch handlers must rethrow.
+/// For detailed comments, see VisitCXXTryStmt.
+template <class Emitter>
+bool Compiler<Emitter>::compileTryConstructor(const CXXConstructorDecl *Ctor) {
+ // There is no assert(Ctx.ExceptionsEnabled) here since we use this for
+ // constructors with direct try statement bodies even if exceptions are
+ // disabled.
+ assert(!this->InStmtExpr);
+
+ const CXXTryStmt *S = cast<CXXTryStmt>(Ctor->getBody());
+ uint32_t ParentTry = currentTryIndex();
+ uint32_t TryIndex = NumTryBlocks;
+ ++NumTryBlocks;
+ {
+ TryBoundary<Emitter> TB(this, TryIndex);
+ LocalScope<Emitter> Scope(this);
+ const auto *TryBlock = cast<CompoundStmt>(S->getTryBlock());
+ if (!this->compileConstructorBody(Ctor, TryBlock))
+ return false;
+ if (!Scope.destroyLocals())
+ return false;
}
- if (!this->emitThis(Dtor))
- return false;
+ if (Ctx.ExceptionsEnabled) {
+ if (!this->emitCatchHandlers(S, TryIndex, ParentTry,
+ /*IsFunctionTryBlock=*/true))
+ return false;
+ }
- if (!this->emitCheckDestruction(Dtor))
- return false;
+ return this->emitFunctionReturn(Ctor, ReturnType);
+}
- assert(R);
- if (!R->isUnion()) {
+template <class Emitter>
+bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
+ if (!this->compileDestructorBody(Dtor, Dtor->getBody()))
+ return false;
+ return this->emitFunctionReturn(Dtor, ReturnType);
+}
- LocOverrideScope<Emitter> LOS(this, SourceInfo{});
- // First, destroy all fields.
- for (const Record::Field &Field : llvm::reverse(R->fields())) {
- const Descriptor *D = Field.Desc;
- if (D->hasTrivialDtor())
- continue;
- if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
- return false;
- if (!this->emitDestructionPop(D, SourceInfo{}))
- return false;
- }
- }
+template <class Emitter>
+bool Compiler<Emitter>::compileDestructorBody(const CXXDestructorDecl *Dtor,
+ const Stmt *Body) {
+ const RecordDecl *RD = Dtor->getParent();
+ const Record *R = this->getRecord(RD);
+ if (!R)
+ return false;
- for (const Record::Base &Base : llvm::reverse(R->bases())) {
- if (Base.R->hasTrivialDtor())
- continue;
- if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
- return false;
- if (!this->emitRecordDestructionPop(Base.R, {}))
+ // Pushed before the body, so a return or an exception leaving the body
+ // also destroys the subobjects.
+ DtorSubobjectsCleanup<Emitter> Subobjects(this, Dtor, R);
+ if (!Dtor->isTrivial() && Body) {
+ if (!this->visitStmt(Body))
return false;
}
- if (R->getNumVirtualBases() > 0) {
- LabelTy EndLabel = this->getLabel();
- // If this is a base class, skip the virtual bases.
- if (!this->emitIsBaseClass({}))
- return false;
- if (!this->jumpTrue(EndLabel, {}))
- return false;
+ return Subobjects.emitNormalCleanup();
+}
- for (const Record::Base &Base : llvm::reverse(R->virtual_bases())) {
- if (Base.R->hasTrivialDtor())
- continue;
- if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(Base.R->getDecl()),
- SourceInfo{}))
- return false;
- if (!this->emitRecordDestructionPop(Base.R, {}))
- return false;
- }
+template <class Emitter>
+bool Compiler<Emitter>::compileTryDestructor(const CXXDestructorDecl *Dtor) {
+ assert(Ctx.ExceptionsEnabled);
+ assert(!this->InStmtExpr);
- this->fallthrough(EndLabel);
- this->emitLabel(EndLabel);
+ const CXXTryStmt *S = cast<CXXTryStmt>(Dtor->getBody());
+ uint32_t ParentTry = currentTryIndex();
+ uint32_t TryIndex = NumTryBlocks;
+ ++NumTryBlocks;
+ {
+ TryBoundary<Emitter> TB(this, TryIndex);
+ LocalScope<Emitter> Scope(this);
+ const auto *TryBlock = cast<CompoundStmt>(S->getTryBlock());
+ if (!this->compileDestructorBody(Dtor, TryBlock))
+ return false;
+ if (!Scope.destroyLocals())
+ return false;
}
- if (!this->emitMarkDestroyed(Dtor))
+ if (!this->emitCatchHandlers(S, TryIndex, ParentTry,
+ /*IsFunctionTryBlock=*/true))
return false;
-
- return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
+ return this->emitFunctionReturn(Dtor, ReturnType);
}
template <class Emitter>
@@ -8059,10 +8517,17 @@ bool Compiler<Emitter>::visitFunc(const FunctionDecl *F) {
this->CompilingFunction = F;
- if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
+ if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F)) {
+ // Note that we use compileTryConstructor even if exceptions are disabled.
+ if (isa_and_nonnull<CXXTryStmt>(Ctor->getBody()))
+ return this->compileTryConstructor(Ctor);
return this->compileConstructor(Ctor);
- if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
+ }
+ if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
+ if (Ctx.ExceptionsEnabled && isa_and_nonnull<CXXTryStmt>(Dtor->getBody()))
+ return this->compileTryDestructor(Dtor);
return this->compileDestructor(Dtor);
+ }
// Emit custom code if this is a lambda static invoker.
if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
@@ -8077,14 +8542,25 @@ bool Compiler<Emitter>::visitFunc(const FunctionDecl *F) {
}
// Regular functions.
- if (const auto *Body = F->getBody())
+ if (const auto *Body = F->getBody()) {
if (!visitStmt(Body))
return false;
+ }
// Emit a guard return to protect against a code path missing one.
- if (F->getReturnType()->isVoidType())
- return this->emitRetVoid(SourceInfo{});
- return this->emitNoRet(SourceInfo{});
+ if (F->getReturnType()->isVoidType()) {
+ if (!this->emitRetVoid(SourceInfo{}))
+ return false;
+ } else if (!this->emitNoRet(SourceInfo{})) {
+ return false;
+ }
+
+ if (Ctx.ExceptionsEnabled) {
+ bool CanThrow = F->getType()->castAs<FunctionProtoType>()->canThrow();
+ if (CanThrow)
+ return this->emitAfterRet(SourceInfo{});
+ }
+ return true;
}
static uint32_t getBitWidth(const Expr *E) {
@@ -8821,9 +9297,16 @@ bool Compiler<Emitter>::VisitDesignatedInitUpdateExpr(
return this->visitInitializer(E->getUpdater());
}
-template <class Emitter> bool Compiler<Emitter>::emitCleanup() {
- for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) {
- if (!C->destroyLocals())
+template <class Emitter>
+bool Compiler<Emitter>::emitCleanup(const CleanupScope<Emitter> *Stop) {
+ // While C's cleanup is emitted, C is the innermost entry, like in codegen:
+ // inner entries are done, C itself tracks its partial state.
+ CleanupScope<Emitter> *Top = this->Cleanups;
+ llvm::SaveAndRestore RestoreTop(this->Cleanups);
+
+ for (CleanupScope<Emitter> *C = Top; C != Stop; C = C->getParent()) {
+ this->Cleanups = C;
+ if (!C->emitNormalCleanup())
return false;
}
return true;
@@ -9076,7 +9559,10 @@ bool Compiler<Emitter>::emitRecordDestructionPop(const Record *R,
return false;
assert(DtorFunc->hasThisPointer());
assert(DtorFunc->getNumParams() == 1);
- return this->emitCall(DtorFunc, 0, Loc);
+
+ return this->emitCallAndCatch(!R->hasNothrowDtor(), Loc, [&]() {
+ return this->emitCall(DtorFunc, 0, Loc);
+ });
}
/// When calling this, we have a pointer of the local-to-destroy
/// on the stack.
@@ -9096,20 +9582,18 @@ bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
if (N == 0)
return this->emitPopPtr(Loc);
- for (ssize_t I = N - 1; I >= 1; --I) {
- if (!this->emitConstUint64(I, Loc))
- return false;
- if (!this->emitArrayElemPtrUint64(Loc))
- return false;
- if (!this->emitDestructionPop(ElemDesc, Loc))
- return false;
+ std::optional<ArrayDestroyCleanup<Emitter>> Cleanup;
+ if (Ctx.ExceptionsEnabled && !ElemDesc->hasNothrowDtor()) {
+ // Innermost element type, for multidimensional arrays.
+ const Descriptor *Inner = ElemDesc;
+ while (Inner->isArray())
+ Inner = Inner->ElemDesc;
+
+ if (Inner->ElemRecord && !Inner->ElemRecord->hasTrivialDtor())
+ Cleanup.emplace(this, ElemDesc, Loc);
}
- // Last iteration, removes the instance pointer from the stack.
- if (!this->emitConstUint64(0, Loc))
- return false;
- if (!this->emitArrayElemPtrPopUint64(Loc))
- return false;
- return this->emitDestructionPop(ElemDesc, Loc);
+ return emitArrayElemsDestructionPop(ElemDesc, N,
+ Cleanup ? &*Cleanup : nullptr, Loc);
}
assert(Desc->ElemRecord);
@@ -9117,6 +9601,35 @@ bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
}
+/// Destroy elements N - 1, ..., 0 of the array pointer on the stack, and pop
+/// it. \p Cleanup, if any, tracks which elements are still alive.
+template <class Emitter>
+bool Compiler<Emitter>::emitArrayElemsDestructionPop(
+ const Descriptor *ElemDesc, unsigned N,
+ ArrayDestroyCleanup<Emitter> *Cleanup, SourceInfo Loc) {
+ assert(N > 0);
+
+ for (unsigned I = N - 1; I >= 1; --I) {
+ if (Cleanup)
+ Cleanup->Remaining = I;
+ if (!this->emitConstUint64(I, Loc))
+ return false;
+ if (!this->emitArrayElemPtrUint64(Loc))
+ return false;
+ if (!this->emitDestructionPop(ElemDesc, Loc))
+ return false;
+ }
+
+ // Last iteration, removes the array pointer from the stack.
+ if (Cleanup)
+ Cleanup->Remaining = 0;
+ if (!this->emitConstUint64(0, Loc))
+ return false;
+ if (!this->emitArrayElemPtrPopUint64(Loc))
+ return false;
+ return this->emitDestructionPop(ElemDesc, Loc);
+}
+
/// Create a dummy pointer for the given decl (or expr) and
/// push a pointer to it on the stack.
template <class Emitter>
@@ -9211,6 +9724,119 @@ bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
return true;
}
+template <class Emitter>
+bool Compiler<Emitter>::emitFunctionReturn(const FunctionDecl *FD,
+ OptPrimType ReturnType) {
+ bool NeedsAfterRet = false;
+ if (Ctx.ExceptionsEnabled)
+ NeedsAfterRet = FD->getType()->castAs<FunctionProtoType>()->canThrow();
+
+ if (!NeedsAfterRet) {
+ if (ReturnType)
+ return this->emitRet(*ReturnType, FD);
+
+ return this->emitRetVoid(FD);
+ }
+
+ if (ReturnType)
+ return this->emitRet(*ReturnType, FD) && this->emitAfterRet(FD);
+ return this->emitRetVoid(FD) && this->emitAfterRet(FD);
+}
+
+template <class Emitter>
+bool Compiler<Emitter>::call(const Function *Func, SourceInfo Loc) {
+ return emitCallAndCatch(Func->canThrow(), Loc,
+ [&] { return this->emitCall(Func, 0, Loc); });
+}
+
+/// Emit a call via \p EmitCall. If it may throw, dispatch an exception it
+/// throws: unwind the cleanup stack and jump to the handler. Without
+/// exceptions, this is just the call.
+template <class Emitter>
+bool Compiler<Emitter>::emitCallAndCatch(bool MayThrow, SourceInfo Loc,
+ llvm::function_ref<bool()> EmitCall) {
+ if (!Ctx.ExceptionsEnabled || !MayThrow)
+ return EmitCall();
+
+ LabelTy SkipLabel = this->getLabel();
+ if (!this->emitPushThrowTrap(Loc))
+ return false;
+ if (!EmitCall())
+ return false;
+ if (!this->emitPopThrowTrap(Loc))
+ return false;
+ if (!this->jumpFalse(SkipLabel, Loc))
+ return false;
+
+ // Exception thrown. During unwinding, that terminates.
+ if (this->isTerminating()) {
+ if (!this->emitInvalidThrow(Loc))
+ return false;
+ } else {
+ // Destroy what's left, e.g. the earlier locals of a scope being exited.
+ if (!this->emitUnwindScopes(Loc) ||
+ !this->emitCatch(currentTryIndex(), Loc))
+ return false;
+ }
+
+ this->emitLabel(SkipLabel);
+ return true;
+}
+
+/// Whether the code being emitted is part of unwinding.
+template <class Emitter> bool Compiler<Emitter>::isTerminating() const {
+ for (const CleanupScope<Emitter> *C = this->Cleanups; C; C = C->getParent()) {
+ if (C->isTerminate())
+ return true;
+ }
+ return false;
+}
+
+/// The try block whose handlers get exceptions thrown here, like codegen's
+/// getInvokeDest().
+/// T t;
+/// try {
+/// return;
+/// } catch (...) {
+/// }
+/// ~T() throwing isn't caught.
+template <class Emitter> uint32_t Compiler<Emitter>::currentTryIndex() const {
+ for (const CleanupScope<Emitter> *C = this->Cleanups; C; C = C->getParent()) {
+ if (C->isTryBoundary())
+ return static_cast<const TryBoundary<Emitter> *>(C)->TryIndex;
+ }
+ return TryBlockID::None;
+}
+
+/// An exception is propagating: emit the cleanups up to the enclosing try.
+/// Destructors throwing during this terminate ([except.terminate]).
+template <class Emitter>
+bool Compiler<Emitter>::emitUnwindScopes(SourceInfo Loc) {
+ return emitUnwindScopes(Loc, this->Cleanups);
+}
+
+/// Like above, but starting at \p From instead of the innermost entry.
+template <class Emitter>
+bool Compiler<Emitter>::emitUnwindScopes(SourceInfo Loc,
+ CleanupScope<Emitter> *From) {
+ TerminateScope<Emitter> TS(this);
+
+ // The returned object lives until the return completes, so it goes first.
+ if (PendingReturnValue) {
+ if (!this->emitRVOPtr(Loc) ||
+ !this->emitRecordDestructionPop(PendingReturnValue, Loc))
+ return false;
+ }
+
+ for (CleanupScope<Emitter> *C = From; C; C = C->getParent()) {
+ if (!C->emitEHCleanup())
+ return false;
+ if (C->isTryBoundary())
+ break;
+ }
+ return true;
+}
+
/// Replicate a scalar value into every scalar element of an aggregate.
/// The scalar is stored in a local at \p SrcOffset and a pointer to the
/// destination must be on top of the interpreter stack. Each element receives
diff --git a/clang/lib/AST/ByteCode/Compiler.h b/clang/lib/AST/ByteCode/Compiler.h
index 5805e413d7ae19..0a3b5be816ce5b 100644
--- a/clang/lib/AST/ByteCode/Compiler.h
+++ b/clang/lib/AST/ByteCode/Compiler.h
@@ -28,8 +28,16 @@ class QualType;
namespace interp {
+template <class Emitter> class ExceptionObjectCleanup;
+template <class Emitter> class SubobjectCleanupScope;
+template <class Emitter> class NewAllocCleanup;
+template <class Emitter> class DtorSubobjectsCleanup;
+template <class Emitter> class DelegatingCtorCleanup;
+template <class Emitter> class ArrayDestroyCleanup;
+template <class Emitter> class ArrayElemsCleanup;
template <class Emitter> class LocalScope;
template <class Emitter> class VariableScope;
+template <class Emitter> class CleanupScope;
template <class Emitter> class DeclScope;
template <class Emitter> class InitLinkScope;
template <class Emitter> class InitStackScope;
@@ -109,7 +117,7 @@ struct VarCreationState {
bool notCreated() const { return !S; }
};
-enum class ScopeKind { Block, FullExpression, Call };
+enum class ScopeKind { Block, FullExpression, Call, Catch };
/// Compilation context for expressions.
template <class Emitter>
@@ -275,8 +283,9 @@ class Compiler final : public ConstStmtVisitor<Compiler<Emitter>, bool>,
const Expr *Condition) override;
protected:
- /// Emits scope cleanup instructions.
- bool emitCleanup();
+ /// Emits scope cleanup instructions until we hit the \p Stop scope in the
+ /// chain.
+ bool emitCleanup(const CleanupScope<Emitter> *Stop = nullptr);
/// Returns a record type from a record or pointer type.
const RecordType *getRecordTy(QualType Ty);
@@ -361,8 +370,16 @@ class Compiler final : public ConstStmtVisitor<Compiler<Emitter>, bool>,
UnsignedOrNone allocateTemporary(const Expr *E);
private:
- friend class VariableScope<Emitter>;
+ friend class ExceptionObjectCleanup<Emitter>;
+ friend class SubobjectCleanupScope<Emitter>;
+ friend class NewAllocCleanup<Emitter>;
+ friend class DtorSubobjectsCleanup<Emitter>;
+ friend class DelegatingCtorCleanup<Emitter>;
+ friend class ArrayDestroyCleanup<Emitter>;
+ friend class ArrayElemsCleanup<Emitter>;
friend class LocalScope<Emitter>;
+ friend class VariableScope<Emitter>;
+ friend class CleanupScope<Emitter>;
friend class DeclScope<Emitter>;
friend class InitLinkScope<Emitter>;
friend class InitStackScope<Emitter>;
@@ -437,6 +454,9 @@ class Compiler final : public ConstStmtVisitor<Compiler<Emitter>, bool>,
const BinaryOperator *E);
bool emitRecordDestructionPop(const Record *R, SourceInfo Loc);
bool emitDestructionPop(const Descriptor *Desc, SourceInfo Loc);
+ bool emitArrayElemsDestructionPop(const Descriptor *ElemDesc, unsigned N,
+ ArrayDestroyCleanup<Emitter> *Cleanup,
+ SourceInfo Loc);
bool emitDummyPtr(DeclOrExpr D, const Expr *E, bool CU = false);
bool emitFloat(const APFloat &F, SourceInfo Info);
unsigned collectBaseOffset(const QualType BaseType,
@@ -468,7 +488,12 @@ class Compiler final : public ConstStmtVisitor<Compiler<Emitter>, bool>,
}
bool compileConstructor(const CXXConstructorDecl *Ctor);
+ bool compileConstructorBody(const CXXConstructorDecl *Ctor, const Stmt *Body);
+ bool compileTryConstructor(const CXXConstructorDecl *Ctor);
+
bool compileDestructor(const CXXDestructorDecl *Dtor);
+ bool compileDestructorBody(const CXXDestructorDecl *Dtor, const Stmt *Body);
+ bool compileTryDestructor(const CXXDestructorDecl *Dtor);
bool compileUnionAssignmentOperator(const CXXMethodDecl *MD);
bool checkLiteralType(const Expr *E);
@@ -476,6 +501,23 @@ class Compiler final : public ConstStmtVisitor<Compiler<Emitter>, bool>,
bool refersToUnion(const Expr *E);
+ bool emitFunctionReturn(const FunctionDecl *FD, OptPrimType ReturnType);
+
+ bool call(const Function *Func, SourceInfo Loc);
+ bool emitCallAndCatch(bool MayThrow, SourceInfo Loc,
+ llvm::function_ref<bool()> EmitCall);
+ bool
+ emitSubobjectCleanupScope(std::optional<SubobjectCleanupScope<Emitter>> &SCS,
+ QualType QT, unsigned NumInits, const Expr *E);
+ bool isTerminating() const;
+ bool emitUnwindScopes(SourceInfo Loc);
+ bool emitUnwindScopes(SourceInfo Loc, CleanupScope<Emitter> *From);
+ uint32_t currentTryIndex() const;
+ bool emitTryCleanupPad(const CXXTryStmt *S, uint32_t TryIndex,
+ uint32_t ParentTry);
+ bool emitCatchHandlers(const CXXTryStmt *S, uint32_t TryIndex,
+ uint32_t ParentTry, bool IsFunctionTryBlock = false);
+
protected:
/// Variable to storage mapping.
llvm::DenseMap<const ValueDecl *, Scope::Local> Locals;
@@ -485,6 +527,13 @@ class Compiler final : public ConstStmtVisitor<Compiler<Emitter>, bool>,
/// Current scope.
VariableScope<Emitter> *VarScope = nullptr;
+ /// Innermost entry of the cleanup stack; see CleanupScope.
+ CleanupScope<Emitter> *Cleanups = nullptr;
+ /// Record of the object being returned while the return's cleanups are
+ /// emitted; destroyed first when unwinding.
+ const Record *PendingReturnValue = nullptr;
+ /// Number of try blocks in the function, for try block indices.
+ uint32_t NumTryBlocks = 0;
/// Current argument index. Needed to emit ArrayInitIndexExpr.
std::optional<uint64_t> ArrayIndex;
@@ -516,9 +565,6 @@ class Compiler final : public ConstStmtVisitor<Compiler<Emitter>, bool>,
CaseMap CaseLabels;
/// Stack of label information for loops and switch statements.
llvm::SmallVector<LabelInfo> LabelInfoStack;
- /// In a destructor body: where a return jumps to, so the subobjects are
- /// still destroyed. See compileDestructor().
- OptLabelTy DtorEpilogLabel = std::nullopt;
const FunctionDecl *CompilingFunction = nullptr;
};
diff --git a/clang/lib/AST/ByteCode/Context.cpp b/clang/lib/AST/ByteCode/Context.cpp
index 0a0ed5fc394c86..c595b6a1717e3c 100644
--- a/clang/lib/AST/ByteCode/Context.cpp
+++ b/clang/lib/AST/ByteCode/Context.cpp
@@ -34,6 +34,9 @@ Context::Context(ASTContext &Ctx) : Ctx(Ctx), P(new Program(*this)) {
this->LongLongWidth = Ctx.getTargetInfo().getLongLongWidth();
assert(Ctx.getTargetInfo().getCharWidth() == 8 &&
"We're assuming 8 bit chars");
+
+ this->ExceptionsEnabled =
+ Ctx.getLangOpts().CPlusPlus26 && Ctx.getLangOpts().CXXExceptions;
}
Context::~Context() = default;
diff --git a/clang/lib/AST/ByteCode/Context.h b/clang/lib/AST/ByteCode/Context.h
index 262f5b47f87c2f..17b56a156d8324 100644
--- a/clang/lib/AST/ByteCode/Context.h
+++ b/clang/lib/AST/ByteCode/Context.h
@@ -48,6 +48,8 @@ class EvalIDScope;
/// Holds all information required to evaluate constexpr code in a module.
class Context final {
public:
+ bool ExceptionsEnabled;
+
/// Initialises the constexpr VM.
explicit Context(ASTContext &Ctx);
diff --git a/clang/lib/AST/ByteCode/DeclOrExpr.h b/clang/lib/AST/ByteCode/DeclOrExpr.h
index 14608f379001bf..0bfc7a7b47aad1 100644
--- a/clang/lib/AST/ByteCode/DeclOrExpr.h
+++ b/clang/lib/AST/ByteCode/DeclOrExpr.h
@@ -18,20 +18,25 @@ namespace clang {
namespace interp {
struct DeclOrExpr {
- llvm::PointerUnion<const Decl *, const Expr *> V;
+ llvm::PointerUnion<const Decl *, const Stmt *> V;
DeclOrExpr() : V(nullptr) {}
DeclOrExpr(std::nullptr_t) : V(nullptr) {}
DeclOrExpr(const Decl *VD) : V(VD) {}
DeclOrExpr(const Expr *E) : V(E) {}
+ DeclOrExpr(const Stmt *S) : V(S) {}
- bool isExpr() const { return isa_and_nonnull<const Expr *>(V); }
+ bool isStmt() const { return isa_and_nonnull<const Stmt *>(V); }
bool isDecl() const { return isa_and_nonnull<const Decl *>(V); }
+ bool isExpr() const { return isa_and_nonnull<const Expr>(asStmt()); }
bool isValueDecl() const { return isa_and_nonnull<ValueDecl>(asDecl()); }
bool isVarDecl() const { return isa_and_nonnull<VarDecl>(asDecl()); }
- const Expr *asExpr() const { return dyn_cast<const Expr *>(V); }
+ const Stmt *asStmt() const { return dyn_cast<const Stmt *>(V); }
const Decl *asDecl() const { return dyn_cast<const Decl *>(V); }
+ const Expr *asExpr() const {
+ return dyn_cast_if_present<const Expr>(asStmt());
+ }
const ValueDecl *asValueDecl() const {
return dyn_cast_if_present<ValueDecl>(asDecl());
}
diff --git a/clang/lib/AST/ByteCode/Descriptor.cpp b/clang/lib/AST/ByteCode/Descriptor.cpp
index 5266f4f11736ec..7509712e8c2f40 100644
--- a/clang/lib/AST/ByteCode/Descriptor.cpp
+++ b/clang/lib/AST/ByteCode/Descriptor.cpp
@@ -455,7 +455,7 @@ QualType Descriptor::getDataType(const ASTContext &Ctx) const {
return ElemType;
};
- if (isDynAlloc())
+ if (getDynAllocKind() != DynAllocKind::None)
return MakeArrayType(asExpr()->getType()->getPointeeType());
return getType();
diff --git a/clang/lib/AST/ByteCode/Descriptor.h b/clang/lib/AST/ByteCode/Descriptor.h
index 4bb596f0c0282b..27f3cb806ff6a8 100644
--- a/clang/lib/AST/ByteCode/Descriptor.h
+++ b/clang/lib/AST/ByteCode/Descriptor.h
@@ -279,8 +279,6 @@ struct Descriptor final {
DynAllocKind getDynAllocKind() const {
return asExpr() ? getDynAllocKindForExpr(asExpr()) : DynAllocKind::None;
}
- /// Checks if the descriptor is of a dynamic allocation.
- bool isDynAlloc() const { return getDynAllocKind() != DynAllocKind::None; }
/// Compute the alignment for a dynamic allocation.
CharUnits computeAlignForDynamicAlloc(const ASTContext &Ctx) const;
diff --git a/clang/lib/AST/ByteCode/Disasm.cpp b/clang/lib/AST/ByteCode/Disasm.cpp
index c1d9cde9b6455e..639fbc55ae56dc 100644
--- a/clang/lib/AST/ByteCode/Disasm.cpp
+++ b/clang/lib/AST/ByteCode/Disasm.cpp
@@ -124,6 +124,11 @@ template <> inline std::string printArg<FixedPoint>(CodePtr &OpPC) {
return Result;
}
+template <> inline std::string printArg<QualType>(CodePtr &OpPC) {
+ auto QT = reinterpret_cast<const void *>(OpPC.read<uintptr_t>());
+ return QualType::getFromOpaquePtr(QT).getAsString();
+}
+
static bool isJumpOpcode(Opcode Op) {
return Op == OP_Jmp || Op == OP_Jf || Op == OP_Jt;
}
@@ -161,10 +166,28 @@ LLVM_DUMP_METHOD void Function::dump(llvm::raw_ostream &OS,
OS << "rvo: " << hasRVO() << "\n";
OS << "this arg: " << hasThisPointer() << "\n";
+ // Print exception table, e.g. "#0: try 1 (parent 0) -> 24 catch (int)".
+ if (!ExceptionTable.empty()) {
+ OS << "exception table:\n";
+ for (auto [I, EE] : llvm::enumerate(ExceptionTable)) {
+ OS << " #" << I << ": try " << EE.TryID.ID << " (parent ";
+ if (EE.TryID.ParentID != TryBlockID::None)
+ OS << EE.TryID.ParentID;
+ else
+ OS << "none";
+ OS << ") -> " << EE.Target << " catch (";
+ if (!EE.CatchType.isNull())
+ OS << EE.CatchType.getAsString();
+ else
+ OS << "...";
+ OS << ")\n";
+ }
+ }
+
struct OpText {
size_t Addr;
std::string Op;
- bool IsJump;
+ std::optional<size_t> JumpTarget;
bool CurrentOp = false;
llvm::SmallVector<std::string> Args;
};
@@ -182,8 +205,17 @@ LLVM_DUMP_METHOD void Function::dump(llvm::raw_ostream &OS,
OpText Text;
auto Op = PC.read<Opcode>();
Text.Addr = Addr;
- Text.IsJump = isJumpOpcode(Op);
Text.CurrentOp = (PC == OpPC);
+
+ // The first argument of jumps is an offset relative to the end of the
+ // opcode and that argument. See ByteCodeEmitter::getOffset().
+ if (isJumpOpcode(Op)) {
+ CodePtr ArgPC = PC;
+ int32_t Offset = ArgPC.read<int32_t>();
+ Text.JumpTarget =
+ Addr + align(sizeof(Opcode)) + align(sizeof(int32_t)) + Offset;
+ }
+
switch (Op) {
#define GET_DISASM
#include "Opcodes.inc"
@@ -200,11 +232,9 @@ LLVM_DUMP_METHOD void Function::dump(llvm::raw_ostream &OS,
size_t To;
};
llvm::SmallVector<JmpData> Jumps;
- for (auto &Text : Code) {
- if (Text.IsJump)
- Jumps.push_back({Text.Addr, Text.Addr + std::stoi(Text.Args[0]) +
- align(sizeof(Opcode)) +
- align(sizeof(int32_t))});
+ for (const auto &Text : Code) {
+ if (Text.JumpTarget)
+ Jumps.push_back({Text.Addr, *Text.JumpTarget});
}
llvm::SmallVector<std::string> Text;
@@ -220,6 +250,7 @@ LLVM_DUMP_METHOD void Function::dump(llvm::raw_ostream &OS,
else
LS << " ";
}
+
LS << C.Addr;
LS.indent(LongestAddr - getNumDisplayWidth(C.Addr) + 4);
LS << C.Op;
@@ -227,53 +258,32 @@ LLVM_DUMP_METHOD void Function::dump(llvm::raw_ostream &OS,
for (auto &Arg : C.Args) {
LS << Arg << ' ';
}
+
Text.push_back(Line);
LongestLine = std::max(Line.size(), LongestLine);
}
assert(Code.size() == Text.size());
- auto spaces = [](unsigned N) -> std::string {
- std::string S;
- for (unsigned I = 0; I != N; ++I)
- S += ' ';
- return S;
- };
-
- // Now, draw the jump lines.
- for (auto &J : Jumps) {
- if (J.To > J.From) {
- bool FoundStart = false;
- for (size_t LineIndex = 0; LineIndex != Text.size(); ++LineIndex) {
- Text[LineIndex] += spaces(LongestLine - Text[LineIndex].size());
-
- if (Code[LineIndex].Addr == J.From) {
- Text[LineIndex] += " --+";
- FoundStart = true;
- } else if (Code[LineIndex].Addr == J.To) {
- Text[LineIndex] += " <-+";
- break;
- } else if (FoundStart) {
- Text[LineIndex] += " |";
- }
- }
- LongestLine += 5;
- } else {
- bool FoundStart = false;
- for (ssize_t LineIndex = Text.size() - 1; LineIndex >= 0; --LineIndex) {
- Text[LineIndex] += spaces(LongestLine - Text[LineIndex].size());
- if (Code[LineIndex].Addr == J.From) {
- Text[LineIndex] += " --+";
- FoundStart = true;
- } else if (Code[LineIndex].Addr == J.To) {
- Text[LineIndex] += " <-+";
- break;
- } else if (FoundStart) {
- Text[LineIndex] += " |";
- }
+ // Now, draw the jump lines. Walk from the jump towards its target.
+ for (const JmpData &J : Jumps) {
+ bool Forward = J.To > J.From;
+ bool FoundStart = false;
+ for (size_t I = 0, E = Text.size(); I != E; ++I) {
+ size_t LineIndex = Forward ? I : E - 1 - I;
+ Text[LineIndex].resize(LongestLine, ' ');
+
+ if (Code[LineIndex].Addr == J.From) {
+ Text[LineIndex] += " --+";
+ FoundStart = true;
+ } else if (Code[LineIndex].Addr == J.To) {
+ Text[LineIndex] += " <-+";
+ break;
+ } else if (FoundStart) {
+ Text[LineIndex] += " |";
}
- LongestLine += 5;
}
+ LongestLine += 5;
}
for (auto &Line : Text)
diff --git a/clang/lib/AST/ByteCode/EvalEmitter.cpp b/clang/lib/AST/ByteCode/EvalEmitter.cpp
index c7289893e47c66..2dadd04043269e 100644
--- a/clang/lib/AST/ByteCode/EvalEmitter.cpp
+++ b/clang/lib/AST/ByteCode/EvalEmitter.cpp
@@ -233,6 +233,9 @@ template <PrimType OpType> bool EvalEmitter::emitRet(SourceInfo Info) {
if (!isActive())
return true;
+ if (S.hasException())
+ return diagnoseUncaughtException(S, {});
+
using T = typename PrimConv<OpType>::T;
EvalResult.takeValue(S.Stk.pop<T>().toAPValue(Ctx.getASTContext()));
return true;
@@ -242,6 +245,9 @@ template <> bool EvalEmitter::emitRet<PT_MemberPtr>(SourceInfo Info) {
if (!isActive())
return true;
+ if (S.hasException())
+ return diagnoseUncaughtException(S, {});
+
const MemberPointer &MP = S.Stk.pop<MemberPointer>();
if (!EvalResult.checkMemberPointer(S, MP, Info, ConstexprKind))
return false;
@@ -254,6 +260,9 @@ template <> bool EvalEmitter::emitRet<PT_Ptr>(SourceInfo Info) {
if (!isActive())
return true;
+ if (S.hasException())
+ return diagnoseUncaughtException(S, {});
+
const Pointer &Ptr = S.Stk.pop<Pointer>();
// If we're returning a raw pointer, call our callback.
if (this->PtrCB)
@@ -318,11 +327,19 @@ template <> bool EvalEmitter::emitRet<PT_Ptr>(SourceInfo Info) {
}
bool EvalEmitter::emitRetVoid(SourceInfo Info) {
+
+ if (S.hasException())
+ return diagnoseUncaughtException(S, {});
+
EvalResult.setValid();
return true;
}
bool EvalEmitter::emitRetValue(SourceInfo Info) {
+
+ if (S.hasException())
+ return diagnoseUncaughtException(S, {});
+
const auto &Ptr = S.Stk.pop<Pointer>();
if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
diff --git a/clang/lib/AST/ByteCode/EvalEmitter.h b/clang/lib/AST/ByteCode/EvalEmitter.h
index 023b1d6d1fdb5d..816366ef0df380 100644
--- a/clang/lib/AST/ByteCode/EvalEmitter.h
+++ b/clang/lib/AST/ByteCode/EvalEmitter.h
@@ -77,6 +77,17 @@ class EvalEmitter : public SourceMapper {
EvalEmitter(Context &Ctx, Program &P, Expr::EvalStatus &Status,
InterpStack &Stk, FrameAllocator &FrameAlloc);
+ unsigned currentCodeSize() const {
+ llvm_unreachable("Should never be called on EvalEmitter");
+ return 0;
+ }
+
+ void registerExceptionHandler(uint32_t TryIndex, uint32_t ParentTry,
+ unsigned Target, QualType T,
+ bool IsCleanup = false) {
+ llvm_unreachable("Should never be called on EvalEmitter");
+ }
+
/// Define a label.
void emitLabel(LabelTy Label);
/// Create a label.
diff --git a/clang/lib/AST/ByteCode/Exceptions.cpp b/clang/lib/AST/ByteCode/Exceptions.cpp
new file mode 100644
index 00000000000000..4f836eaac03025
--- /dev/null
+++ b/clang/lib/AST/ByteCode/Exceptions.cpp
@@ -0,0 +1,173 @@
+//===-------------------------- Exceptions.cpp ------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "Exceptions.h"
+#include "Block.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/CXXInheritance.h"
+
+using namespace clang;
+using namespace clang::interp;
+
+static bool isPointerOrMemberPointerType(const Type *T) {
+ return T->isPointerType() || T->isMemberPointerType();
+}
+static bool isPointerOrMemberPointerType(QualType T) {
+ return isPointerOrMemberPointerType(T.getTypePtr());
+}
+
+bool ExceptionTableEntry::canCatch(QualType ThrowType,
+ const ASTContext &ASTCtx) const {
+ // Cleanup entries aren't "real" catch blocks, so just make them catch
+ // everything.
+ if (IsCleanup)
+ return true;
+
+ QualType CatchType = this->CatchType;
+
+ // "A handler is a match for an exception object of type E if ..."
+
+ // "The handler is of type cv T or cv T& and E and T are the same type
+ // (ignoring the top-level cv-qualifiers)"
+ if (CatchType.isNull() ||
+ ASTContext::hasSameType(CatchType.getUnqualifiedType(),
+ ThrowType.getUnqualifiedType()) ||
+ (CatchType->isReferenceType() &&
+ ASTContext::hasSameUnqualifiedType(CatchType->getPointeeType(),
+ ThrowType)))
+ return true;
+
+ assert(!CatchType.isNull());
+
+ // "the handler is of type cv T or const T& where T is a pointer or
+ // pointer-to-member type and E is std::nullptr_t"
+ if (ThrowType->isNullPtrType()) {
+ if (isPointerOrMemberPointerType(CatchType))
+ return true;
+
+ if (CatchType->isReferenceType() &&
+ (CatchType->getPointeeType()->isPointerType() ||
+ CatchType->getPointeeType()->isMemberPointerType()))
+ return true;
+ }
+
+ // [except.handle]p3 allows pointer conversions only for "cv T" and
+ // "const T&" handlers. GCC and Clang also apply them for non-const T&,
+ // since an Itanium ABI handler's type_info is the referenced type's:
+ // throw (D *)p;
+ // catch (B *&) // Matches.
+ // Follow them, so constant evaluation catches like the runtime does.
+ if (CatchType->isReferenceType())
+ CatchType = CatchType->getPointeeType();
+
+ // cv void* catches object pointers whose pointee is at most as
+ // cv-qualified, but no function pointers:
+ // throw (const int *)p; // Caught by const void*, not by void*.
+ if (CatchType->isVoidPointerType() && ThrowType->isPointerType() &&
+ !ThrowType->isFunctionPointerType() &&
+ CatchType->getPointeeType().isAtLeastAsQualifiedAs(
+ ThrowType->getPointeeType(), ASTCtx))
+ return true;
+
+ // "the handler is of type cv T or const T& where T is a pointer or
+ // pointer-to-member type and E is a pointer or pointer-to-member type that
+ // can be converted to T by one or more of ..."
+ if ((isPointerOrMemberPointerType(CatchType) ||
+ (CatchType->isReferenceType() &&
+ isPointerOrMemberPointerType(CatchType->getPointeeType()))) &&
+ isPointerOrMemberPointerType(ThrowType)) {
+
+ // "a function pointer conversion"
+ if (CatchType->isFunctionPointerType() &&
+ ThrowType->isFunctionPointerType()) {
+ const auto *FuncT =
+ CatchType->getPointeeType()->castAs<FunctionProtoType>();
+ const auto *FuncE =
+ ThrowType->getPointeeType()->castAs<FunctionProtoType>();
+
+ // We can catch a noexcept function as non-noexcept, but not the other way
+ // around.
+ if (FuncT->hasNoexceptExceptionSpec() &&
+ !FuncE->hasNoexceptExceptionSpec())
+ return false;
+ // Both being noexcept is also fine.
+ return ASTContext::hasSameType(FuncT, FuncE);
+ }
+
+ // "a qualification conversion"
+ if (CatchType->isPointerType() && ThrowType->isPointerType()) {
+ QualType PointeeT = CatchType->getPointeeType();
+ QualType PointeeE = ThrowType->getPointeeType();
+
+ if (ASTContext::hasSameType(PointeeT, PointeeE))
+ return true;
+
+ // We can catch T* as const T*, not the other way around.
+ if (!PointeeT.isConstQualified() && PointeeE.isConstQualified())
+ return false;
+
+ if (PointeeT.isConstQualified() && !PointeeE.isConstQualified() &&
+ ASTCtx.hasSimilarType(PointeeT, PointeeE))
+ return true;
+ }
+ }
+
+ // "the handler is of type cv T or cv T& and T is an unambiguous public base
+ // class of E"
+ if (CatchType.isConstQualified() && CatchType->isReferenceType() &&
+ ThrowType->isPointerType())
+ CatchType = CatchType->getPointeeType();
+
+ if (CatchType->isReferenceType() &&
+ !CatchType->getPointeeType()->isPointerType())
+ CatchType = CatchType->getPointeeType();
+
+ // T* can only catch T*, not T.
+ if (CatchType->isPointerType() && ThrowType->isPointerType()) {
+ CatchType = CatchType->getPointeeType();
+ ThrowType = ThrowType->getPointeeType();
+ }
+
+ if (CatchType->isRecordType() && ThrowType->isRecordType()) {
+ const CXXRecordDecl *CatchDecl = CatchType->getAsCXXRecordDecl();
+ const CXXRecordDecl *ThrowDecl = ThrowType->getAsCXXRecordDecl();
+ assert(CatchDecl);
+ assert(ThrowDecl);
+
+ if (CatchDecl == ThrowDecl)
+ return true;
+
+ CXXBasePaths Paths;
+ if (ThrowDecl->isDerivedFrom(CatchDecl, Paths)) {
+ if (Paths.isAmbiguous(ASTCtx.getCanonicalTagType(CatchDecl)))
+ return false;
+
+ if (Paths.front().Access != AS_public)
+ return false;
+
+ return true;
+ }
+ }
+
+ return false;
+}
+
+OptPrimType ThrowValue::getPrimType() const {
+ if (B->getDescriptor()->isPrimitive())
+ return B->getDescriptor()->getPrimType();
+ return std::nullopt;
+}
+
+llvm::raw_ostream &clang::interp::operator<<(llvm::raw_ostream &OS,
+ const ThrowValue &V) {
+ OS << "ThrownValue {" << V.B << " ";
+ V.B->getDescriptor()->dump(OS);
+ OS << ", Type " << V.Ty << ", Caught: " << V.Caught
+ << ", Rethrown: " << V.Rethrown << ", handlers: " << V.Handlers << "}";
+ return OS;
+}
diff --git a/clang/lib/AST/ByteCode/Exceptions.h b/clang/lib/AST/ByteCode/Exceptions.h
new file mode 100644
index 00000000000000..a0f4ee1d0dd89d
--- /dev/null
+++ b/clang/lib/AST/ByteCode/Exceptions.h
@@ -0,0 +1,84 @@
+//===----------------------- Exceptions.h ----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_AST_INTERP_EXCEPTIONS_H
+#define LLVM_CLANG_AST_INTERP_EXCEPTIONS_H
+
+#include "PrimType.h"
+#include "clang/Basic/SourceLocation.h"
+
+// FIXME:
+// 1) Since we compile functions anyway, we should record whether they have
+// any kind of throw/catch syntax and mark them nothrow if not.
+
+namespace clang {
+class Type;
+class ASTContext;
+class RecordDecl;
+
+namespace interp {
+class Block;
+
+struct TryBlockID final {
+ static constexpr uint32_t None = ~0u;
+ /// The try block this entry handles exceptions for.
+ uint32_t ID;
+ /// The enclosing try block, tried when no entry of TryIndex matches.
+ uint32_t ParentID;
+
+ TryBlockID(uint32_t ID, uint32_t ParentID) : ID(ID), ParentID(ParentID) {}
+};
+
+struct ExceptionTableEntry final {
+ TryBlockID TryID;
+ unsigned Target;
+ /// If CatchType is nullptr, this is a catch-all handler.
+ QualType CatchType;
+ /// Not a handler: destroys enclosing locals, then re-dispatches the
+ /// exception. Matches any type.
+ bool IsCleanup = false;
+
+ ExceptionTableEntry(TryBlockID ID, unsigned Target, QualType CatchType,
+ bool IsCleanup = false)
+ : TryID(ID), Target(Target), CatchType(CatchType), IsCleanup(IsCleanup) {}
+
+ /// Check if this exception table entry can catch an exception thrown of the
+ /// given type.
+ bool canCatch(QualType ThrowType, const ASTContext &ASTCtx) const;
+};
+
+/// A thrown value.
+struct ThrowValue final {
+ /// The type of the exception thrown. This is information from the AST and
+ /// includes casts.
+ QualType Ty;
+ /// The allocated memory for the exception object.
+ Block *B;
+ /// Where the exception was thrown.
+ SourceLocation Loc;
+
+ unsigned Handlers = 0;
+
+ /// Base class the active handler catches the exception object (or the
+ /// thrown pointer's pointee) as. See getBasePointer().
+ const RecordDecl *CastTo = nullptr;
+ bool Caught = false;
+ bool Rethrown = false;
+ bool Thrown = false;
+
+ explicit ThrowValue(QualType Ty, SourceLocation Loc, Block *B)
+ : Ty(Ty), B(B), Loc(Loc) {}
+
+ OptPrimType getPrimType() const;
+};
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const ThrowValue &V);
+
+} // namespace interp
+} // namespace clang
+#endif
diff --git a/clang/lib/AST/ByteCode/Function.cpp b/clang/lib/AST/ByteCode/Function.cpp
index 38b0ab7dfc7d62..21418115e8801c 100644
--- a/clang/lib/AST/ByteCode/Function.cpp
+++ b/clang/lib/AST/ByteCode/Function.cpp
@@ -66,3 +66,21 @@ SourceInfo Function::getSource(CodePtr PC) const {
unsigned Offset = PC - getCodeBegin();
return SrcMap.findSourceForOffset(Offset);
}
+
+std::optional<ExceptionTableEntry>
+Function::findCatchHandler(uint32_t TryIndex, QualType Ty,
+ const ASTContext &ASTCtx) const {
+ // Innermost try block first, then the enclosing ones.
+ while (TryIndex != TryBlockID::None) {
+ uint32_t ParentTry = TryBlockID::None;
+ for (const auto &E : ExceptionTable) {
+ if (E.TryID.ID != TryIndex)
+ continue;
+ if (E.canCatch(Ty, ASTCtx))
+ return E;
+ ParentTry = E.TryID.ParentID;
+ }
+ TryIndex = ParentTry;
+ }
+ return std::nullopt;
+}
diff --git a/clang/lib/AST/ByteCode/Function.h b/clang/lib/AST/ByteCode/Function.h
index 3531c5070b29cf..0eb30ab88756be 100644
--- a/clang/lib/AST/ByteCode/Function.h
+++ b/clang/lib/AST/ByteCode/Function.h
@@ -16,6 +16,7 @@
#define LLVM_CLANG_AST_INTERP_FUNCTION_H
#include "Descriptor.h"
+#include "Exceptions.h"
#include "Source.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
@@ -142,6 +143,16 @@ class Function final {
return getExpr()->getType();
}
+ bool canThrow() const {
+ if (const FunctionDecl *FD = getDecl()) {
+ if (const auto *PT = FD->getType()->getAs<FunctionProtoType>())
+ return PT->canThrow();
+ // FIXME: Is there a situation where we have a FunctionNoProtoType in C++
+ // and need to conservatively return true here?
+ }
+ return false;
+ }
+
/// Returns the name of the function decl this code
/// was generated for.
std::string getName() const {
@@ -258,6 +269,10 @@ class Function final {
return ArgSize - (align(primSize(PT_Ptr)) * (hasThisPointer() + hasRVO()));
}
+ std::optional<ExceptionTableEntry>
+ findCatchHandler(uint32_t TryIndex, QualType Ty,
+ const ASTContext &ASTCtx) const;
+
private:
/// Construct a function representing an actual function.
Function(FunctionDeclTy Source, unsigned ArgSize,
@@ -267,13 +282,15 @@ class Function final {
/// Sets the code of a function.
void setCode(FunctionDeclTy Source, unsigned NewFrameSize,
llvm::SmallVector<std::byte> &&NewCode, SourceMap &&NewSrcMap,
- llvm::SmallVector<Scope, 2> &&NewScopes, bool NewHasBody,
- bool NewIsValid) {
+ llvm::SmallVector<Scope, 2> &&NewScopes,
+ llvm::SmallVector<ExceptionTableEntry> &&ExceptionTable,
+ bool NewHasBody, bool NewIsValid) {
this->Source = Source;
FrameSize = NewFrameSize;
Code = std::move(NewCode);
SrcMap = std::move(NewSrcMap);
Scopes = std::move(NewScopes);
+ this->ExceptionTable = std::move(ExceptionTable);
IsValid = NewIsValid;
HasBody = NewHasBody;
}
@@ -302,6 +319,7 @@ class Function final {
unsigned ArgSize;
/// Function Kind.
FunctionKind Kind;
+ llvm::SmallVector<ExceptionTableEntry, 0> ExceptionTable;
/// Flag to indicate if the function is valid.
LLVM_PREFERRED_TYPE(bool)
unsigned IsValid : 1;
diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp
index 676d3b6a35ffcd..4801d078939e5b 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -199,20 +199,6 @@ static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC,
S.Note(VD->getLocation(), diag::note_declared_at);
}
-static bool CheckGlobal(InterpState &S, CodePtr OpPC, const Block *B) {
- if (auto ID = B->getDeclID()) {
- if (!B->isGlobal())
- return true;
-
- if (S.P.getCurrentDecl() == ID)
- return true;
-
- S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_modify_global);
- return false;
- }
- return true;
-}
-
namespace clang {
namespace interp {
@@ -274,6 +260,38 @@ static bool CheckTemporary(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
return CheckTemporary(S, OpPC, Ptr.block(), AK);
}
+static bool CheckGlobal(InterpState &S, CodePtr OpPC, const Block *B) {
+ if (auto ID = B->getDeclID()) {
+ if (!B->isGlobal())
+ return true;
+
+ if (S.P.getCurrentDecl() == ID)
+ return true;
+
+ S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_modify_global);
+ return false;
+ }
+ return true;
+}
+
+bool diagnoseUncaughtException(InterpState &S, CodePtr OpPC) {
+ assert(S.hasException());
+ const ThrowValue &Exception = S.getExceptionObject();
+ QualType UncaughtType = Exception.Ty;
+ std::string ValString;
+
+ if (OptPrimType ExceptionT = Exception.getPrimType()) {
+ TYPE_SWITCH(*ExceptionT, {
+ ValString = Exception.B->deref<T>().toDiagnosticString(S.getASTContext());
+ });
+ } else {
+ ValString = Pointer(Exception.B).toDiagnosticString(S.getASTContext());
+ }
+ S.FFDiag(Exception.Loc, diag::note_constexpr_uncaught_exception)
+ << UncaughtType << ValString;
+ return false;
+}
+
PRESERVE_NONE static bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset,
PrimType PT);
@@ -1489,10 +1507,17 @@ static bool RunDestructors(InterpState &S, CodePtr OpPC, const Block *B) {
const Descriptor *ElemDesc = Desc->ElemDesc;
assert(ElemDesc->isRecord());
+ // An escaping exception doesn't stop destruction of the remaining
+ // elements, but a second one terminates.
+ unsigned ExceptionsBefore = S.ThrownValues.size();
Pointer RP(const_cast<Block *>(B));
for (int I = static_cast<int>(N) - 1; I >= 0; --I) {
+ bool HadEscape =
+ S.hasInFlightException() && S.ThrownValues.size() > ExceptionsBefore;
if (!runRecordDestructor(S, OpPC, RP.atIndex(I).narrow(), ElemDesc))
return false;
+ if (HadEscape && S.ThrownValues.size() > ExceptionsBefore + 1)
+ return InvalidThrow(S, OpPC);
}
return true;
}
@@ -1501,6 +1526,34 @@ static bool RunDestructors(InterpState &S, CodePtr OpPC, const Block *B) {
return runRecordDestructor(S, OpPC, Pointer(const_cast<Block *>(B)), Desc);
}
+bool DestroyException(InterpState &S, CodePtr OpPC) {
+ const Pointer ExceptionPtr = S.Stk.pop<Pointer>();
+
+ if (auto *It = llvm::find_if(S.ThrownValues,
+ [=](const ThrowValue &V) -> bool {
+ return V.B == ExceptionPtr.block();
+ });
+ It != S.ThrownValues.end()) {
+ assert(It->Handlers > 0);
+ --It->Handlers;
+
+ if (!It->Rethrown) {
+ if (It->Handlers == 0) {
+ // Unlink first: the destructor may throw and grow ThrownValues.
+ Block *B = It->B;
+ S.ThrownValues.erase(It);
+ if (!RunDestructors(S, OpPC, B))
+ return false;
+ S.deallocate(B);
+ }
+ } else {
+ // The handler exits while its exception propagates. The handler
+ // catching it next keeps it alive.
+ }
+ }
+ return true;
+}
+
static bool hasVirtualDestructor(QualType T) {
if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
if (const CXXDestructorDecl *DD = RD->getDestructor())
@@ -1509,7 +1562,7 @@ static bool hasVirtualDestructor(QualType T) {
}
bool Free(InterpState &S, CodePtr OpPC, bool DeleteIsArrayForm,
- bool IsGlobalDelete) {
+ bool IsGlobalDelete, bool RunDtors) {
if (!CheckDynamicMemoryAllocation(S, OpPC))
return false;
@@ -1595,8 +1648,9 @@ bool Free(InterpState &S, CodePtr OpPC, bool DeleteIsArrayForm,
assert(Source);
assert(BlockToDelete);
- // Invoke destructors before deallocating the memory.
- if (!RunDestructors(S, OpPC, BlockToDelete))
+ // Invoke destructors before deallocating the memory. Not when freeing the
+ // storage of a new-expression whose initializer threw.
+ if (RunDtors && !RunDestructors(S, OpPC, BlockToDelete))
return false;
if (!Allocator.deallocate(Source, BlockToDelete)) {
@@ -2087,6 +2141,253 @@ static void compileFunction(InterpState &S, const Function *Func,
.compileFunc(Definition, const_cast<Function *>(Func));
}
+// We have a saved thrown value in InterpState.
+// Now try to catch that value in the current function.
+// If no corresponding catch handler is found, jump to the
+// AfterRet op at the end of the function.
+static bool catchException(InterpState &S, CodePtr OpPC, uint32_t TryIndex) {
+ assert(S.getContext().ExceptionsEnabled);
+ assert(S.hasException());
+ assert(!S.getExceptionObject().Caught);
+ assert(S.getExceptionObject().B->isInitialized());
+
+ ThrowValue &Exception = S.getExceptionObject();
+ // We've reached the bottom frame. We can't go any lower, so diagnose
+ // an uncaught exception.
+ const Function *CurrFunction = S.Current->getFunction();
+ if (!CurrFunction) {
+ assert(S.Current->isBottomFrame());
+ if (!S.checkingPotentialConstantExpression())
+ return diagnoseUncaughtException(S, OpPC);
+ return false;
+ }
+
+ std::optional<ExceptionTableEntry> CatchEntry =
+ CurrFunction->findCatchHandler(TryIndex, Exception.Ty, S.getASTContext());
+
+ if (!CatchEntry) {
+ // We didn't find an appropriate catch handler in the current function.
+ // Skip to the end of the function.
+ if (!S.Current->getFunction()->canThrow()) {
+ S.FFDiag(S.Current->getSource(OpPC),
+ diag::note_constexpr_exception_in_noexcept_func);
+ return false;
+ }
+ // Jump to the end of the function. The calling function will handle
+ // catching the exception.
+ S.PC = S.Current->getFunction()->getCodeEnd() - align(sizeof(Opcode));
+#ifndef NDEBUG
+ CodePtr PCCopy = S.PC;
+ Opcode Op = PCCopy.read<Opcode>();
+ assert(Op == OP_AfterRet);
+#endif
+ return true;
+ }
+
+ // There might be some values left on the stack that have been added in
+ // between entering the try{} block and the throw statement. We need to
+ // remove all of those so the stack is in a proper state after the catch
+ // handler finishes.
+ while (S.Stk.size() != S.Current->getFrameOffset())
+ S.Stk.discardSlow();
+
+ // Cleanup pads aren't handlers; the exception stays in flight.
+ if (CatchEntry->IsCleanup) {
+ S.PC = CurrFunction->getCodeBegin() + CatchEntry->Target;
+ return true;
+ }
+
+ // We *did* find a catch handler. We now need to cast the thrown value to
+ // the correct type, if necessary.
+
+ // NB: CaughtType may be null (for catch-all handlers).
+ QualType CaughtType = CatchEntry->CatchType;
+ QualType ThrownType = Exception.Ty;
+ assert(!ThrownType.isNull());
+
+ if (!CaughtType.isNull() && CaughtType->isReferenceType())
+ CaughtType = CaughtType->getPointeeType();
+
+ if (!CaughtType.isNull() && CaughtType->isPointerOrReferenceType())
+ CaughtType = CaughtType->getPointeeType();
+ if (ThrownType->isPointerOrReferenceType())
+ ThrownType = ThrownType->getPointeeType();
+
+ bool NeedsCast =
+ !CaughtType.isNull() &&
+ !ASTContext::hasSameUnqualifiedType(CaughtType, ThrownType) &&
+ CaughtType->isRecordType() && ThrownType->isRecordType();
+
+ // The base pointer itself is computed when the handler reads the exception;
+ // for thrown pointers it depends on the runtime pointee.
+ Exception.CastTo = NeedsCast ? CaughtType->getAsRecordDecl() : nullptr;
+
+ // Jump to the catch handler in this function.
+ S.PC = CurrFunction->getCodeBegin() + CatchEntry->Target;
+ Exception.Caught = true;
+ ++Exception.Handlers;
+ Exception.Rethrown = false;
+
+ return true;
+}
+
+bool Catch(InterpState &S, CodePtr OpPC, uint32_t TryIndex) {
+ return catchException(S, OpPC, TryIndex);
+}
+
+bool Throw(InterpState &S, CodePtr OpPC, uint32_t TryIndex) {
+ assert(S.getContext().ExceptionsEnabled);
+ assert(S.hasException());
+ S.getExceptionObject().Thrown = true;
+
+ return catchException(S, OpPC, TryIndex);
+}
+
+bool ReThrow(InterpState &S, CodePtr OpPC, uint32_t TryIndex) {
+ assert(S.getContext().ExceptionsEnabled);
+
+ if (!S.hasException() || !S.getExceptionObject().B->isInitialized()) {
+ S.FFDiag(S.Current->getSource(OpPC),
+ diag::note_constexpr_no_active_exception);
+ return false;
+ }
+
+ assert(S.hasException());
+ ThrowValue &Exception = S.getExceptionObject();
+ Exception.Caught = false;
+ Exception.CastTo = nullptr;
+ Exception.Rethrown = true;
+
+ return catchException(S, OpPC, TryIndex);
+}
+
+bool SaveException(InterpState &S, CodePtr OpPC, QualType Ty) {
+ assert(S.getContext().ExceptionsEnabled);
+ const Pointer &Ptr = S.Stk.pop<Pointer>();
+
+ // Must've been allocated via AllocException.
+ assert(Ptr.block()->getEvalID() == S.EvalID);
+ assert(Ptr.block()->isInitialized());
+
+ SourceLocation Loc = S.Current->getLocation(OpPC);
+ S.appendException(ThrowValue(Ty, Loc, const_cast<Block *>(Ptr.block())));
+ return true;
+}
+
+/// Allocate memory to store an exception object.
+bool AllocException(InterpState &S, const Descriptor *Desc) {
+ assert(S.getContext().ExceptionsEnabled);
+ assert(Desc);
+ char *Memory = (char *)S.allocate(sizeof(Block) + Desc->getAllocSize());
+ Block *B = new (Memory) Block(S.EvalID, Desc, Block::None);
+ B->invokeCtor();
+ S.Stk.push<Pointer>(B);
+ return true;
+}
+
+/// Emitted if an exception is invalid to be thrown, i.e.
+/// during automatic exception handling/unwinding.
+bool InvalidThrow(InterpState &S, CodePtr OpPC) {
+ assert(S.ThrownValues.size() >= 2);
+ S.FFDiag(S.getExceptionObject().Loc,
+ diag::note_constexpr_throw_with_active_exception, 1);
+ S.Note(S.ThrownValues[S.ThrownValues.size() - 2].Loc,
+ diag::note_previous_throw);
+ return false;
+}
+
+bool PushThrowTrap(InterpState &S) {
+ S.ThrowTraps.emplace_back(S.ThrownValues.size(), S.hasInFlightException());
+ return true;
+}
+
+/// Check if a new exception was thrown between this and the corresponding
+/// PushThrowTrap call.
+bool PopThrowTrap(InterpState &S, CodePtr OpPC) {
+ auto Trap = S.ThrowTraps.pop_back_val();
+
+ // An exception was thrown if an exception is in flight now that wasn't
+ // before, or a new one was thrown on top of the one already propagating.
+ bool Thrown =
+ S.hasInFlightException() &&
+ (!Trap.InFlightBefore || S.ThrownValues.size() > Trap.ExceptionsBefore);
+
+ if (Thrown && S.Current->isBottomFrame())
+ return diagnoseUncaughtException(S, OpPC);
+
+ S.Stk.push<Boolean>(Boolean::from(Thrown));
+ return true;
+}
+
+/// Mark the exception about to be rethrown, so exiting handlers
+/// (DestroyException) keep it alive. A missing exception is
+/// diagnosed later by ReThrow.
+bool MarkRethrown(InterpState &S) {
+ if (S.hasException())
+ S.getExceptionObject().Rethrown = true;
+ return true;
+}
+
+/// Push a pointer to the current exception object on the stack.
+bool GetPtrExceptionValue(InterpState &S) {
+ assert(S.getContext().ExceptionsEnabled);
+ assert(S.hasException());
+
+ const ThrowValue &Exception = S.getExceptionObject();
+ Pointer P = Pointer(Exception.B);
+ // Thrown pointers are cast in GetExceptionValue.
+ if (!Exception.CastTo || Exception.getPrimType()) {
+ S.Stk.push<Pointer>(P);
+ return true;
+ }
+
+ // The exception object is complete and canCatch() checked the base is
+ // unambiguous, so this can't fail.
+ std::optional<Pointer> Base = getBasePointer(P, Exception.CastTo);
+ assert(Base);
+ S.Stk.push<Pointer>(*Base);
+ return true;
+}
+
+/// Pointer to the base class \p Target of the object \p P points to.
+/// Virtual bases are looked up in the most-derived object, since their
+/// position depends on it:
+/// struct VD : virtual VB {};
+/// struct E : VD {};
+/// VD *p = &e; // p's VB lives in E's layout, not VD's.
+std::optional<Pointer> getBasePointer(const Pointer &P,
+ const RecordDecl *Target) {
+ if (!P.isBlockPointer() || !P.getFieldDesc()->isRecord())
+ return std::nullopt;
+
+ const Record *R = P.getRecord();
+ for (const Record::Base &B : R->bases()) {
+ Pointer BP = P.atField(B.Offset);
+ if (B.Decl == Target)
+ return BP;
+ if (std::optional<Pointer> Found = getBasePointer(BP, Target))
+ return Found;
+ }
+
+ if (R->getNumVirtualBases() == 0)
+ return std::nullopt;
+
+ Pointer Derived = P.stripBaseCasts();
+ const Record *DerivedR = Derived.getRecord();
+ for (const Record::Base &B : R->virtual_bases()) {
+ const Record::Base *VB = DerivedR->findVirtualBase(B.Decl);
+ if (!VB)
+ return std::nullopt;
+
+ Pointer VP = Derived.atField(VB->Offset);
+ if (B.Decl == Target)
+ return VP;
+ if (std::optional<Pointer> Found = getBasePointer(VP, Target))
+ return Found;
+ }
+ return std::nullopt;
+}
+
bool CallVar(InterpState &S, CodePtr OpPC, const Function *Func,
uint32_t VarArgSize) {
if (Func->hasThisPointer()) {
@@ -2125,6 +2426,7 @@ bool CallVar(InterpState &S, CodePtr OpPC, const Function *Func,
InterpStateCCOverride CCOverride(S, Func->isImmediate());
bool Success = Interpret(S);
S.exitFrame();
+
return Success;
}
@@ -3816,7 +4118,7 @@ bool TrivialCopy(InterpState &S, CodePtr OpPC, bool Activate,
Op == OP_RetSint64 || Op == OP_RetUint64 || Op == OP_RetIntAP ||
Op == OP_RetIntAPS || Op == OP_RetBool || Op == OP_RetFixedPoint ||
Op == OP_RetPtr || Op == OP_RetMemberPtr || Op == OP_RetFloat ||
- Op == OP_RetReflect || Op == OP_EndSpeculation;
+ Op == OP_RetReflect || Op == OP_EndSpeculation || Op == OP_AfterRet;
}
#if USE_TAILCALLS
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index f43c6c9227200d..b4d3f3563f80b6 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -80,6 +80,8 @@ bool diagnoseArrayIndex(InterpState &S, CodePtr OpPC, const APSInt &Index,
std::optional<uint64_t> NumElems = std::nullopt,
bool IsArray = true);
+bool diagnoseUncaughtException(InterpState &S, CodePtr OpPC);
+
/// Checks a direct load of a primitive value from a global or local variable.
bool CheckGlobalLoad(InterpState &S, CodePtr OpPC, const Block *B);
bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B);
@@ -111,6 +113,7 @@ bool CallVar(InterpState &S, CodePtr OpPC, const Function *Func,
uint32_t VarArgSize);
bool Call(InterpState &S, CodePtr OpPC, const Function *Func,
uint32_t VarArgSize);
+
bool CallVirt(InterpState &S, CodePtr OpPC, const Function *Func,
uint32_t VarArgSize);
bool CallBI(InterpState &S, CodePtr OpPC, const CallExpr *CE,
@@ -140,6 +143,9 @@ bool CastFloatingIntegralAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth,
bool CastFloatingIntegralAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth,
uint32_t FPOI);
+bool Throw(InterpState &S, CodePtr OpPC, uint32_t TryIndex);
+bool ReThrow(InterpState &S, CodePtr OpPC, uint32_t TryIndex);
+
enum class ShiftDir { Left, Right };
enum class ShiftFailure {
@@ -306,6 +312,71 @@ PRESERVE_NONE inline bool RetVoid(InterpState &S) {
return true;
}
+/// Inserted at the very end of functions that can throw, if exceptions are
+/// enabled. We rewind the stack to the start of the function frame and return
+/// nothing. If we arrive at an AfterRet op, we must have thrown an exception.
+PRESERVE_NONE inline bool AfterRet(InterpState &S) {
+ assert(S.getContext().ExceptionsEnabled);
+ assert(S.hasException());
+
+ while (S.Stk.size() != S.Current->getFrameOffset())
+ S.Stk.discardSlow();
+
+ return RetVoid(S);
+}
+
+bool SaveException(InterpState &S, CodePtr OpPC, QualType Ty);
+bool AllocException(InterpState &S, const Descriptor *Desc);
+bool Catch(InterpState &S, CodePtr OpPC, uint32_t TryIndex);
+bool InvalidThrow(InterpState &S, CodePtr OpPC);
+bool PushThrowTrap(InterpState &S);
+bool PopThrowTrap(InterpState &S, CodePtr OpPC);
+bool MarkRethrown(InterpState &S);
+bool GetPtrExceptionValue(InterpState &S);
+std::optional<Pointer> getBasePointer(const Pointer &P,
+ const RecordDecl *Target);
+bool DestroyException(InterpState &S, CodePtr OpPC);
+
+template <PrimType Name, class T = typename PrimConv<Name>::T>
+bool GetExceptionValue(InterpState &S) {
+ assert(S.getContext().ExceptionsEnabled);
+ assert(S.hasException());
+ assert(S.getExceptionObject().getPrimType() &&
+ "Thrown value must be primitive");
+
+ const ThrowValue &Exception = S.getExceptionObject();
+ // The catch handler might require a derived-to-base cast of the thrown
+ // pointer; catchException() determined the target base.
+ if constexpr (std::is_same_v<T, Pointer>) {
+ Pointer P = Exception.B->deref<Pointer>();
+ if (P.isZero() || !Exception.CastTo) {
+ S.Stk.push<Pointer>(P);
+ return true;
+ }
+
+ std::optional<Pointer> Base = getBasePointer(P, Exception.CastTo);
+ if (!Base)
+ return false;
+ S.Stk.push<Pointer>(*Base);
+ return true;
+ }
+
+ if constexpr (std::is_same_v<T, MemberPointer>) {
+ PrimType BlockPrimT = Exception.B->getDescriptor()->getPrimType();
+ if (BlockPrimT == PT_Ptr) {
+ // This should only happen for null pointers.
+ S.Stk.push<T>();
+ return true;
+ }
+ if (BlockPrimT != PT_MemberPtr)
+ return false;
+ }
+
+ assert(Exception.B->getDescriptor()->getPrimType() == Name);
+ S.Stk.push<T>(Exception.B->deref<T>());
+ return true;
+}
+
//===----------------------------------------------------------------------===//
// Add, Sub, Mul
//===----------------------------------------------------------------------===//
@@ -4032,7 +4103,7 @@ inline bool AllocCN(InterpState &S, CodePtr OpPC, const Descriptor *ElementDesc,
}
bool Free(InterpState &S, CodePtr OpPC, bool DeleteIsArrayForm,
- bool IsGlobalDelete);
+ bool IsGlobalDelete, bool RunDtors);
static inline bool IsConstantContext(InterpState &S) {
S.Stk.push<Boolean>(Boolean::from(S.inConstantContext()));
@@ -4230,6 +4301,11 @@ inline FixedPoint ReadArg<FixedPoint>(InterpState &S, CodePtr &OpPC) {
return FP;
}
+template <> inline QualType ReadArg<QualType>(InterpState &S, CodePtr &OpPC) {
+ auto QT = reinterpret_cast<const void *>(OpPC.read<uintptr_t>());
+ return QualType::getFromOpaquePtr(QT);
+}
+
} // namespace interp
} // namespace clang
diff --git a/clang/lib/AST/ByteCode/InterpFrame.cpp b/clang/lib/AST/ByteCode/InterpFrame.cpp
index df9bfe3d426e9b..ae5c132516fdf0 100644
--- a/clang/lib/AST/ByteCode/InterpFrame.cpp
+++ b/clang/lib/AST/ByteCode/InterpFrame.cpp
@@ -29,11 +29,9 @@ InterpFrame::InterpFrame(InterpState &S)
InterpFrame::InterpFrame(InterpState &S, const Function *Func,
InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
: Caller(Caller), S(S), Func(Func), RetPC(RetPC),
- Args(static_cast<char *>(S.Stk.top())), ArgSize(ArgSize) {
+ Args(static_cast<char *>(S.Stk.top())), ArgSize(ArgSize),
+ FrameOffset(S.Stk.size()) {
assert(Func);
-#ifndef NDEBUG
- FrameOffset = S.Stk.size();
-#endif
FuncFlags |= Func->hasRVO() * HasRVOFlag;
FuncFlags |= Func->hasThisPointer() * HasThisFlag;
diff --git a/clang/lib/AST/ByteCode/InterpFrame.h b/clang/lib/AST/ByteCode/InterpFrame.h
index 32df11c9ddb973..d34619eb31a06a 100644
--- a/clang/lib/AST/ByteCode/InterpFrame.h
+++ b/clang/lib/AST/ByteCode/InterpFrame.h
@@ -80,10 +80,8 @@ class InterpFrame final : public Frame {
/// Returns the current function.
const Function *getFunction() const { return Func; }
-#ifndef NDEBUG
/// Returns the offset on the stack at which the frame starts.
size_t getFrameOffset() const { return FrameOffset; }
-#endif
/// Returns the value of a local variable.
template <typename T> const T &getLocal(unsigned Offset) const {
@@ -230,12 +228,10 @@ class InterpFrame final : public Frame {
CodePtr RetPC;
/// Pointer to the arguments in the callee's frame.
char *Args = nullptr;
-#ifndef NDEBUG
- /// Offset on the stack at entry.
- size_t FrameOffset = 0;
-#endif
/// The size of all the arguments.
const unsigned ArgSize;
+ /// Offset on the stack at entry.
+ size_t FrameOffset = 0;
public:
unsigned MSVCConstexprAllowed = 0;
diff --git a/clang/lib/AST/ByteCode/InterpStack.h b/clang/lib/AST/ByteCode/InterpStack.h
index e648fa5312f13d..5c57f73f9cd9d5 100644
--- a/clang/lib/AST/ByteCode/InterpStack.h
+++ b/clang/lib/AST/ByteCode/InterpStack.h
@@ -58,6 +58,8 @@ class InterpStack final {
}
shrink(aligned_size<T>());
}
+
+ /// Like discard(), but not type-aware. Avoid using this.
void discardSlow();
/// Returns a reference to the value on the top of the stack.
diff --git a/clang/lib/AST/ByteCode/InterpState.cpp b/clang/lib/AST/ByteCode/InterpState.cpp
index 9c5b20d55d332b..acda1628449dee 100644
--- a/clang/lib/AST/ByteCode/InterpState.cpp
+++ b/clang/lib/AST/ByteCode/InterpState.cpp
@@ -70,6 +70,14 @@ bool InterpState::inConstantContext() const {
InterpState::~InterpState() {
assert(Current->isBottomFrame());
+ // Invoke the dtor func of the allocated exception object block.
+ for (ThrowValue &E : ThrownValues) {
+ Block *B = E.B;
+ if (B && B->isInitialized())
+ deallocate(B);
+ }
+ ThrownValues.clear();
+
while (DeadBlocks) {
DeadBlock *Next = DeadBlocks->Next;
diff --git a/clang/lib/AST/ByteCode/InterpState.h b/clang/lib/AST/ByteCode/InterpState.h
index ef7d210be0da4b..9bee7cfbef9c9e 100644
--- a/clang/lib/AST/ByteCode/InterpState.h
+++ b/clang/lib/AST/ByteCode/InterpState.h
@@ -15,6 +15,7 @@
#include "Context.h"
#include "DynamicAllocator.h"
+#include "Exceptions.h"
#include "Floating.h"
#include "FrameAllocator.h"
#include "Function.h"
@@ -36,6 +37,15 @@ struct StdAllocatorCaller {
explicit operator bool() { return Call; }
};
+struct ThrowTrap {
+ unsigned ExceptionsBefore = 0;
+ /// Whether an exception was already propagating when the trap was pushed,
+ /// e.g. a destructor called while unwinding.
+ bool InFlightBefore = false;
+ ThrowTrap(unsigned A, bool InFlight)
+ : ExceptionsBefore(A), InFlightBefore(InFlight) {}
+};
+
// FIXME: Create one for the "checking potential constant expression"
// evaluation.
enum class EvaluationKind : uint8_t {
@@ -87,6 +97,8 @@ class InterpState final : public State {
deallocateWithPointers(B);
}
+ llvm::SmallVector<ThrowTrap, 0> ThrowTraps;
+
/// Delegates source mapping to the mapper.
SourceInfo getSource(CodePtr PC) const { return M->getSource(PC); }
@@ -242,6 +254,16 @@ class InterpState final : public State {
--FrameDepth;
}
+ bool hasException() const { return !ThrownValues.empty(); }
+ ThrowValue &getExceptionObject() { return ThrownValues.back(); }
+ /// Thrown and not yet caught.
+ bool hasInFlightException() const {
+ return hasException() && ThrownValues.back().Thrown &&
+ !ThrownValues.back().Caught;
+ }
+ void appendException(ThrowValue &&V) { ThrownValues.push_back(std::move(V)); }
+ void popException() { ThrownValues.pop_back(); }
+
private:
friend class EvaluationResult;
friend class InterpStateCCOverride;
@@ -284,11 +306,12 @@ class InterpState final : public State {
const bool InfiniteSteps = false;
/// ID identifying this evaluation.
const unsigned EvalID;
- unsigned FrameDepth = 0;
+ unsigned FrameDepth = 0;
unsigned StringID = 0;
EvaluationKind EvalKind = EvaluationKind::None;
+ llvm::SmallVector<ThrowValue, 0> ThrownValues;
/// Things needed to do speculative execution.
SmallVectorImpl<PartialDiagnosticAt> *PrevDiags = nullptr;
diff --git a/clang/lib/AST/ByteCode/Opcodes.td b/clang/lib/AST/ByteCode/Opcodes.td
index 18c265a5dee5c1..82ee40dba35bbc 100644
--- a/clang/lib/AST/ByteCode/Opcodes.td
+++ b/clang/lib/AST/ByteCode/Opcodes.td
@@ -73,6 +73,7 @@ def ArgDesc : ArgType { let Name = "const Descriptor *"; }
def ArgPrimType : ArgType { let Name = "PrimType"; }
def ArgEnumDecl : ArgType { let Name = "const EnumDecl *"; }
def ArgTypePtr : ArgType { let Name = "const Type *"; }
+def ArgQualType : ArgType { let Name = "QualType"; }
def ArgVoidPtr : ArgType { let Name = "const void *"; }
def ArgReflectionKind : ArgType { let Name = "ReflectionKind"; }
def ArgDeclOrExpr : ArgType { let Name = "DeclOrExpr"; }
@@ -234,6 +235,39 @@ def NoRet : Opcode {
}
+/// Exceptions
+def AfterRet : SuccessOpcode {
+ let CanReturn = 1;
+}
+
+def Throw : Opcode { let Args = [ArgUint32]; }
+def ReThrow : Opcode { let Args = [ArgUint32]; }
+def SaveException : Opcode {
+ let Args = [ArgQualType];
+}
+
+def GetExceptionValue : Opcode {
+ let Types = [AllTypeClass];
+ let HasGroup = 1;
+ let NeedsOpPC = 0;
+}
+def GetPtrExceptionValue : SuccessOpcode;
+
+def AllocException : SuccessOpcode {
+ let Args = [ArgDesc];
+}
+
+def DestroyException : Opcode;
+def Catch : Opcode { let Args = [ArgUint32]; }
+
+def InvalidThrow : Opcode;
+def PushThrowTrap : SuccessOpcode;
+def PopThrowTrap : Opcode;
+def MarkRethrown : SuccessOpcode;
+
+
+
+/// Calls
def Call : Opcode {
let Args = [ArgFunction, ArgUint32];
}
@@ -1025,7 +1059,7 @@ def AllocCN : Opcode {
}
def Free : Opcode {
- let Args = [ArgBool, ArgBool];
+ let Args = [ArgBool, ArgBool, ArgBool];
}
def CheckNewTypeMismatch : Opcode { let Args = [ArgExpr]; }
diff --git a/clang/lib/AST/ByteCode/PrimType.h b/clang/lib/AST/ByteCode/PrimType.h
index 221ac8bb1bca66..0981f84cbe587b 100644
--- a/clang/lib/AST/ByteCode/PrimType.h
+++ b/clang/lib/AST/ByteCode/PrimType.h
@@ -13,6 +13,7 @@
#ifndef LLVM_CLANG_AST_INTERP_TYPE_H
#define LLVM_CLANG_AST_INTERP_TYPE_H
+#include "clang/AST/TypeBase.h"
#include "llvm/Support/raw_ostream.h"
#include <climits>
#include <cstddef>
@@ -104,6 +105,8 @@ class OptPrimType final {
};
static_assert(sizeof(OptPrimType) == sizeof(PrimType));
+inline QualType getSwappedBytes(QualType T) { return T; }
+
enum class CastKind : uint8_t {
Reinterpret,
ReinterpretLike,
diff --git a/clang/lib/AST/ByteCode/Reflect.h b/clang/lib/AST/ByteCode/Reflect.h
index 4be80f281bb898..8d93b86c01bc71 100644
--- a/clang/lib/AST/ByteCode/Reflect.h
+++ b/clang/lib/AST/ByteCode/Reflect.h
@@ -45,6 +45,14 @@ class Reflect final {
APValue toAPValue(const ASTContext &Ctx) const {
return APValue(Kind, Operand);
}
+
+ std::string toDiagnosticString(const ASTContext &) const {
+ // FIXME: Properly implement.
+ std::string Str;
+ llvm::raw_string_ostream OS(Str);
+ print(OS);
+ return Str;
+ }
};
inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Reflect &R) {
diff --git a/clang/lib/AST/CMakeLists.txt b/clang/lib/AST/CMakeLists.txt
index 5d910d71d7d74b..762f75cf360835 100644
--- a/clang/lib/AST/CMakeLists.txt
+++ b/clang/lib/AST/CMakeLists.txt
@@ -77,6 +77,7 @@ add_clang_library(clangAST
ByteCode/Descriptor.cpp
ByteCode/Disasm.cpp
ByteCode/EvalEmitter.cpp
+ ByteCode/Exceptions.cpp
ByteCode/Function.cpp
ByteCode/InterpBuiltin.cpp
ByteCode/InterpBuiltinBitCast.cpp
diff --git a/clang/test/AST/ByteCode/cxx20.cpp b/clang/test/AST/ByteCode/cxx20.cpp
index 0c1b5e2730511e..4f0081d20e3664 100644
--- a/clang/test/AST/ByteCode/cxx20.cpp
+++ b/clang/test/AST/ByteCode/cxx20.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=both,expected -fcxx-exceptions %s -DNEW_INTERP -fexperimental-new-constant-interpreter
-// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=both,ref -fcxx-exceptions %s
+// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=both,expected %s -DNEW_INTERP -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=both,ref %s
int x;
@@ -673,7 +673,7 @@ namespace ConstexprArrayInitLoopExprDestructors
struct Highlander {
int *p = 0;
constexpr Highlander() {}
- constexpr void set(int *p) { this->p = p; ++*p; if (*p != 1) throw "there can be only one"; }
+ constexpr void set(int *p) { this->p = p; ++*p; if (*p != 1) __builtin_abort(); }
constexpr ~Highlander() { --*p; }
};
@@ -776,7 +776,7 @@ namespace FailingDestructor {
constexpr ~D() {
if (!can_destroy)
- throw "oh no";
+ __builtin_abort();
}
};
template<D d>
@@ -1062,7 +1062,7 @@ namespace OnePastEndDtor {
namespace Virtual {
struct NonZeroOffset { int padding = 123; };
- constexpr void assert(bool b) { if (!b) throw 0; }
+ constexpr void assert(bool b) { if (!b) __builtin_abort(); }
// Ensure that we pick the right final overrider during construction.
struct A {
@@ -1190,9 +1190,8 @@ namespace DiscardedTrivialCXXConstructExpr {
int x;
};
- constexpr int foo(int x) { // ref-error {{never produces a constant expression}}
- throw S(3); // both-note {{not valid in a constant expression}} \
- // ref-note {{not valid in a constant expression}}
+ constexpr int foo(int x) { // both-error {{never produces a constant expression}}
+ __builtin_abort(); // both-note 2{{not valid in a constant expression}}
return 1;
}
diff --git a/clang/test/AST/ByteCode/cxx23.cpp b/clang/test/AST/ByteCode/cxx23.cpp
index fbff5cb9f448bb..77e02592ceee17 100644
--- a/clang/test/AST/ByteCode/cxx23.cpp
+++ b/clang/test/AST/ByteCode/cxx23.cpp
@@ -129,8 +129,8 @@ namespace StaticOperators {
struct S1 {
constexpr S1() { // all20-error {{never produces a constant expression}}
- throw; // all-note {{not valid in a constant expression}} \
- // all20-note {{not valid in a constant expression}}
+ __builtin_abort(); // all-note {{not valid in a constant expression}} \
+ // all20-note {{not valid in a constant expression}}
}
static constexpr int operator()() { return 3; } // ref20-warning {{C++23 extension}} \
// expected20-warning {{C++23 extension}}
diff --git a/clang/test/AST/ByteCode/exceptions.cpp b/clang/test/AST/ByteCode/exceptions.cpp
new file mode 100644
index 00000000000000..ea30b10215904a
--- /dev/null
+++ b/clang/test/AST/ByteCode/exceptions.cpp
@@ -0,0 +1,4591 @@
+// RUN: %clang_cc1 -fcxx-exceptions -std=c++26 -fexperimental-new-constant-interpreter -verify %s
+
+namespace std {
+ class exception {
+ public:
+ constexpr exception() noexcept {};
+ // constexpr exception(const exception&) noexcept;
+ // constexpr exception& operator=(const exception&) noexcept;
+ constexpr virtual ~exception() {};
+ // constexpr virtual const char* what() const noexcept;
+ };
+
+ template <typename T> struct remove_reference { using type = T; };
+ template <typename T> struct remove_reference<T &> { using type = T; };
+ template <typename T> struct remove_reference<T &&> { using type = T; };
+ template <typename T>
+ constexpr typename std::remove_reference<T>::type&& move(T &&t) noexcept {
+ return static_cast<typename std::remove_reference<T>::type &&>(t);
+ }
+};
+
+
+class Bad : std::exception {};
+
+namespace Simple {
+ constexpr int a() {
+ try {
+ } catch(int e){
+ return 12;
+ }
+ return -2;
+ }
+ static_assert(a() == -2);
+
+ constexpr int b() {
+ try {
+ throw 12;
+ } catch(int e){
+ return 12;
+ }
+ return -2;
+ }
+ static_assert(b() == 12);
+
+ constexpr int c() {
+ int m = 12;
+ try {
+ throw 12;
+ } catch(int e){
+ m = 140;
+ }
+ return m;
+ }
+ static_assert(c() == 140);
+
+ constexpr int d() {
+ int m = 12;
+ try {
+ throw 12;
+ } catch(int e){
+ m = 140;
+ } catch (float f) {
+ m = 15;
+ }
+ return m;
+ }
+ static_assert(d() == 140);
+
+ constexpr int e() {
+ int m = 12;
+ try {
+ throw 12;
+ } catch(int e){
+ m = e + 2;
+ }
+ return m;
+ }
+ static_assert(e() == 14);
+
+ constexpr int f() {
+ int m = 12;
+ try {
+ throw 12;
+ } catch(...){
+ m = 100;
+ }
+ return m;
+ }
+ static_assert(f() == 100);
+
+ constexpr int g() {
+ int m = 12;
+ try {
+ throw Bad();
+ } catch(Bad &B){
+ m = 100;
+ }
+ return m;
+ }
+ static_assert(g() == 100);
+
+ constexpr int h() {
+ int m = 12;
+ try {
+ throw ++m;
+ } catch(...){
+ }
+ return m;
+ }
+ static_assert(h() == 13);
+
+ constexpr int i(bool b) {
+ try {
+ if (b)
+ throw 12;
+ else
+ throw 14.0f;
+ } catch (int) {
+ return 100;
+ } catch (float) {
+ return 200;
+ }
+ return 0;
+ }
+ static_assert(i(true) == 100);
+ static_assert(i(false) == 200);
+}
+
+namespace Uncaught {
+
+ constexpr int a() {
+ throw 12; // expected-note {{uncaught exception of type 'int': '12'}}
+ return 0;
+ }
+ static_assert(a() == 13); // expected-error {{not an integral constant expression}}
+}
+
+namespace NoFrame {
+ static_assert((1, throw 2, 3) == 1); // expected-error {{not an integral constant expression}} \
+ // expected-note {{uncaught exception of type 'int': '2'}} \
+ // expected-warning {{left operand of comma operator has no effect}}
+
+}
+
+namespace CleanupAfterThrowingCall {
+ constexpr int a() {
+ throw 12;
+ return -12;
+ }
+ constexpr int test() {
+ try {
+ a();
+ } catch (int i) {
+ return 26;
+ }
+
+ return 120;
+ }
+ static_assert(test() == 26);
+
+ constexpr int b2() {
+ throw 1.0;
+ return 1;
+ }
+ constexpr int a2() {
+ b2();
+ throw 12;
+ return -12;
+ }
+ constexpr int test2() {
+
+ try {
+ a2();
+ } catch (int i) {
+ return 26;
+ } catch (double d ){
+ return (int)(d * 2);
+ }
+
+ return 120;
+ }
+ static_assert(test2() == 2);
+}
+
+namespace Dtors {
+ class Inc {
+ public:
+ int &m;
+ constexpr Inc(int &m) : m(m) {}
+ constexpr ~Inc() { ++m; }
+ };
+
+ constexpr int test1() {
+ int m = 10;
+ Inc _(m);
+
+ try {
+ throw 12;
+ } catch (int) {
+ return m;
+ }
+ }
+ static_assert(test1() == 10);
+
+ constexpr int test2() {
+ int m = 10;
+ try {
+ Inc _(m);
+ throw 12;
+ } catch (int) {
+ }
+ return m;
+ }
+ static_assert(test2() == 11);
+
+ struct checker {
+ int & counter;
+ constexpr ~checker() {
+ ++counter;
+ }
+ };
+
+ constexpr int test() {
+ int counter = 0;
+ {
+ try {
+ auto c1 = checker{counter};
+ throw 42;
+ } catch (...) {
+ return counter * 7;
+ }
+ }
+ return counter * 3;
+ }
+
+ constexpr int destruction_counter = test();
+ static_assert(destruction_counter == 7);
+}
+
+namespace Dtors2 {
+ struct S {
+ int *Dtors;
+ int X;
+ constexpr ~S() { ++*Dtors; }
+ };
+
+ constexpr int g() { return 1; }
+
+ constexpr int f() {
+ int Dtors = 0;
+ try {
+ throw S{&Dtors, 5};
+ } catch (S &s) {
+ g();
+ if (Dtors != 0)
+ return -1; // Exception destroyed early.
+ return s.X;
+ }
+ return 0;
+ }
+ static_assert(f() == 5);
+}
+
+namespace CatchArray {
+ template <typename T> consteval T test(T head, auto... tail) {
+ const T array[] = {head, tail...};
+ try {
+ throw array;
+ } catch (const T (&arr)[5]) {
+ return -2;
+ } catch (const T * ptr) {
+ return *ptr;
+ } catch (...) {
+ return -1;
+ }
+ }
+
+ constexpr auto r0 = test(1,2,3,4,5,6);
+ static_assert(r0 == 1);
+
+ constexpr auto r1 = test(1,2,3,4,5);
+ static_assert(r1 == 1);
+
+ constexpr auto r2 = test(1,2,3,4);
+ static_assert(r2 == 1);
+
+ constexpr auto r3 = test(7,1,2,3,4,5,6);
+ static_assert(r3 == 7);
+
+ constexpr auto r4 = test(8,1,2,3,4,5);
+ static_assert(r4 == 8);
+
+ constexpr auto r5 = test(9,1,2,3,4);
+ static_assert(r5 == 9);
+}
+
+namespace CatchVoidPtr {
+ consteval int test() {
+ int p = 3;
+ try {
+ throw &p;
+ } catch (void * ptr) {
+ return *static_cast<int *>(ptr);
+ }
+ }
+ static_assert(test() == 3);
+
+ constexpr void t() {
+ int p = 3; // expected-note {{declared here}}
+ throw &p;
+ }
+ consteval int test2() {
+ try {
+ t();
+ } catch (void * ptr) {
+ return *static_cast<int *>(ptr); // expected-note {{read of object outside its lifetime is not allowed in a constant expression}}
+ }
+ }
+ static_assert(test2() == 3); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+namespace Nullptr {
+ consteval int test_nullptr() {
+ try {
+ throw nullptr;
+ } catch (const int * ex) {
+ return true;
+ } catch (...) {
+ return false;
+ }
+ }
+ static_assert(test_nullptr());
+
+ consteval int test_zero() {
+ try {
+ throw 0;
+ } catch (const int * ex) {
+ return false;
+ } catch (...) {
+ return true;
+ }
+ }
+ static_assert(test_zero());
+
+
+ constexpr int reference() {
+ try {
+ throw nullptr;
+ } catch (const int *&a) {
+ return 20;
+ }
+ return -1;
+ }
+ static_assert(reference() == 20);
+
+ class A {};
+ class B : public A {};
+
+ constexpr int test() {
+ try {
+ throw (B*)nullptr;
+ } catch (A*) {
+ return 10;
+ }
+ return 100;
+ }
+ static_assert(test() == 10);
+}
+
+namespace CatchAll {
+ template <typename T, typename... Args> consteval int test(Args && ... args) {
+ try {
+ throw T{args...};
+ } catch (unsigned v) {
+ return static_cast<int>(v) * 2;
+ } catch (int v) {
+ return v * 3;
+ } catch (bool v) {
+ return static_cast<int>(v) * 5;
+ } catch (...) {
+ return -1;
+ }
+ return 0;
+ }
+
+ static_assert(test<unsigned>(42u) == 84);
+ static_assert(test<int>(13) == 39);
+ static_assert(test<bool>(true) == 5);
+ static_assert(test<long>(42) == -1);
+}
+
+namespace Copy {
+ class Child {};
+ constexpr int test() {
+
+ try {
+ throw Child{};
+ } catch (Child C) {
+ return 20;
+ }
+ return 30;
+ }
+ static_assert(test() == 20);
+
+ constexpr int a(){
+ throw Child{};
+ }
+ constexpr int test2() {
+
+ try {
+ a();
+ } catch (Child C) {
+ return 20;
+ }
+ return 30;
+ }
+ static_assert(test2() == 20);
+}
+
+namespace Inheritance {
+ class Parent2 {
+ public:
+ int F = 5;
+ constexpr int getFive() { return F; }
+ };
+ class Parent : public Parent2{
+ };
+ class Child : public Parent {};
+
+ constexpr int foo() {
+ try {
+ throw Child{};
+ } catch (Parent2 P) {
+ return P.getFive() + 9;
+ }
+ return 0;
+ }
+ static_assert(foo() == 14);
+
+ constexpr int foo2() {
+ Child C{};
+ try {
+ throw &C;
+ } catch (Parent2 *P) {
+ return P->getFive() + 12;
+ }
+ return 0;
+ }
+ static_assert(foo2() == 17);
+
+ constexpr int a() {
+ throw Child{};
+ };
+ constexpr int foo3() {
+ try {
+ a();
+ } catch (Parent2 P) {
+ return P.getFive();
+ }
+ return 0;
+ }
+ static_assert(foo3() == 5);
+
+ constexpr int b(Child *C) {
+ throw C;
+ };
+
+ constexpr int foo4() {
+ Child C{};
+ try {
+ b(&C);
+ } catch (Parent *P) {
+ return P->getFive();
+ }
+ return 0;
+ }
+ static_assert(foo4() == 5);
+
+ constexpr int doublePointer() {
+ auto s = Child{};
+ auto *ss = &s;
+
+ try {
+ throw &ss;;
+ } catch (Parent**) {
+ return 2;
+ } catch(...) {
+ return 1;
+ }
+ return -1;
+ }
+ static_assert(doublePointer() == 1);
+
+
+
+ class Base {};
+ class S : private Base {};
+ constexpr int foo5() {
+ try {
+ throw S{}; // expected-note {{uncaught exception of type 'S': '&S{}'}}
+ } catch (Base) {
+ return 10;
+ }
+ return -1;
+ }
+ static_assert(foo5() == -1); // expected-error {{not an integral constant expression}}
+
+ constexpr int foo6() {
+ auto s = Child{};
+ try {
+ throw &s;
+ } catch (Child*) {
+ return 2;
+ } catch(...) {
+ return 1;
+ }
+
+ return -1;
+ }
+ static_assert(foo6() == 2);
+
+ constexpr int foo7() {
+ try {
+ throw Child{};
+ } catch (Child*) {
+ return 2;
+ } catch(...) {
+ return 1;
+ }
+
+ return -1;
+ }
+ static_assert(foo7() == 1);
+
+ constexpr int foo8() {
+ auto s = Child{};
+ try {
+ throw &s;
+ } catch (Parent&) {
+ return 2;
+ } catch(...) {
+ return 1;
+ }
+
+ return -1;
+ }
+ static_assert(foo8() == 1);
+
+ constexpr int foo9() {
+ auto s = Child{};
+ try {
+ throw (Child&)s;
+ } catch (Parent&) {
+ return 2;
+ } catch(...) {
+ return 1;
+ }
+
+ return -1;
+ }
+ static_assert(foo9() == 2);
+
+ constexpr int foo10() {
+ auto s = Child{};
+ try {
+ throw (Child&)s;
+ } catch (Parent) {
+ return 2;
+ } catch(...) {
+ return 1;
+ }
+
+ return -1;
+ }
+ static_assert(foo10() == 2);
+
+ constexpr int foo11() {
+ auto s = Child{};
+ try {
+ throw (Child&&)s;
+ } catch (Parent2) {
+ return 2;
+ } catch(...) {
+ return 1;
+ }
+
+ return -1;
+ }
+ static_assert(foo11() == 2);
+
+
+ constexpr int foo12() {
+ auto s = Child{};
+ try {
+ throw s;
+ } catch (Parent&&) { // expected-error {{cannot catch exceptions by rvalue reference}}
+ return 2;
+ } catch(...) {
+ return 1;
+ }
+
+ return -1;
+ }
+ static_assert(foo12() == 2);
+
+ struct B {};
+ struct D : B {};
+ /// [except.handle]p3 only allows cv B* or const B*& to match, but GCC and
+ /// Clang codegen also match B*&; we do the same.
+ constexpr int h() {
+ try {
+ throw (D *)nullptr; // D *
+ } catch (B *&) {
+ return 1;
+ } catch (...) {
+ return 2;
+ }
+ return 0;
+ }
+ static_assert(h() == 1);
+}
+
+namespace Pointers {
+ static constexpr auto via_const_catch = 2;
+ static constexpr auto via_childs_get_value = 3;
+ static constexpr auto via_special_child_catch = 5;
+
+ struct parent {
+ int value;
+ explicit constexpr parent(int v) noexcept: value{v} { }
+ constexpr virtual int get_value() const noexcept {
+ return value;
+ }
+ constexpr virtual ~parent() = default;
+ };
+
+ struct modifying_child: parent {
+ explicit constexpr modifying_child(int v) noexcept: parent{v} { }
+ constexpr int get_value() const noexcept override {
+ return value * via_childs_get_value;
+ }
+ };
+
+ struct ordinary_child: parent {
+ explicit constexpr ordinary_child(int v) noexcept: parent{v} { }
+ };
+
+ struct special_child: parent {
+ explicit constexpr special_child(int v) noexcept: parent{v} { }
+ };
+
+ consteval int test(void (*fnc)()) {
+ int result = 0;
+ try {
+ fnc();
+ } catch (special_child * sch) {
+ result = sch->get_value() * via_special_child_catch;
+ delete sch;
+ } catch (const special_child * sch) {
+ result = sch->get_value() * via_special_child_catch * via_const_catch;
+ delete sch;
+ } catch (parent * exc) {
+ result = exc->get_value();
+ delete exc;
+ } catch (const parent * exc) {
+ result = exc->get_value() * via_const_catch;
+ delete exc;
+ }
+ return result;
+ }
+
+ constexpr auto r1 = test([] { throw new parent{1}; });
+ static_assert(r1 == 1);
+
+ constexpr auto r2 = test([] { throw new modifying_child{3}; });
+ static_assert(r2 == 3 * via_childs_get_value);
+
+ constexpr auto r3 = test([] { throw new ordinary_child{5}; });
+ static_assert(r3 == 5);
+
+ constexpr auto r4 = test([] { throw new special_child{17}; });
+ static_assert(r4 == 17 * via_special_child_catch);
+
+ constexpr int pointeeCatch() {
+ int x = 10;
+ try {
+ throw &x; // expected-note {{uncaught exception of type 'int *': '&x'}}
+ } catch (int ) {
+ return 10;
+ }
+ return 1;
+ }
+
+ static_assert(pointeeCatch() == 1); // expected-error {{not an integral constant expression}}
+
+ constexpr int g() {
+ int x = 0;
+ int *p = &x;
+ try {
+ throw &p;
+ } catch (const int **) {
+ return 1;
+ } catch (...) {
+ return 2;
+ }
+ return 0;
+ }
+ static_assert(g() == 2);
+
+ constexpr int constPtr() {
+ try {
+ throw (const void*)nullptr;
+ } catch(void*) {
+ return 1;
+ } catch(...) {
+ return 2;
+ }
+ return -1;
+ }
+ static_assert(constPtr() == 2);
+
+ /// cv void* only catches object pointers with an at most as qualified
+ /// pointee.
+ constexpr int toConstVoid() {
+ int x = 0;
+ try {
+ throw &x;
+ } catch (const void *) {
+ return 1;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(toConstVoid() == 1);
+
+ constexpr int i = 0;
+ constexpr int topLevelConst() {
+ try {
+ throw &i;
+ } catch (void *const) {
+ return 1;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(topLevelConst() == 2);
+
+ constexpr int volatileVoid() {
+ try {
+ throw (volatile int *)nullptr;
+ } catch (const void *) {
+ return 1;
+ } catch (const volatile void *) {
+ return 2;
+ }
+ }
+ static_assert(volatileVoid() == 2);
+
+ constexpr void fn() {}
+ constexpr int funcPtr() {
+ try {
+ throw &fn;
+ } catch (void *) {
+ return 1;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(funcPtr() == 2);
+
+}
+
+namespace References1 {
+ class Parent {
+ public:
+ int F = 10;
+ constexpr int getTen() { return F; }
+ };
+
+ class Child : public Parent {
+ public:
+ int F = 5;
+ constexpr int getFive() { return F; }
+
+ };
+
+ constexpr int foo() {
+ try {
+ throw Child{};
+ } catch (Child &C) {
+ return C.getFive();
+ }
+ return 0;
+ }
+ static_assert(foo() == 5);
+
+ constexpr int nested() {
+ throw Child{};
+ return 1;
+ };
+ constexpr int foo2() {
+ try {
+ nested();
+ } catch (Child &C) {
+ return C.getFive();
+ }
+ return 0;
+ }
+ static_assert(foo2() == 5);
+
+ constexpr int foo3() {
+ try {
+ throw Child{};
+ } catch (Parent &P) {
+ return P.getTen();
+ }
+ return 0;
+ }
+ static_assert(foo3() == 10);
+
+ constexpr int foo4() {
+ try {
+ nested();
+ } catch (Parent &P) {
+ return P.getTen();
+ }
+ return 0;
+ }
+ static_assert(foo4() == 10);
+
+ constexpr int foo5() {
+ try {
+ throw 13;
+ } catch (const int &a) {
+ return 25;
+ }
+ return -1;
+ }
+ static_assert(foo5() == 25);
+
+ consteval int reference_test(const int & ref) {
+ try {
+ throw ref;
+ } catch (const int & exc_ref) {
+ if (exc_ref != ref) {
+ return 3;
+ } else if (&exc_ref != &ref) {
+ return 2;
+ }
+ return 1;
+ }
+ }
+ static_assert(reference_test(10) == 2);
+
+ consteval bool copy_test(const int & ref) {
+ try {
+ throw ref;
+ } catch (const int exc_ref) {
+ if (exc_ref != ref) {
+ return 3;
+ } else if (&exc_ref == &ref) {
+ return 2;
+ }
+ return 1;
+ }
+ }
+ static_assert(copy_test(10) == 1);
+
+ consteval bool conversion_test(const int & ref) {
+ try {
+ throw ref;
+ } catch (const long exc_ref) {
+ if (exc_ref != ref) {
+ return 3;
+ } else if (static_cast<const void *>(&exc_ref) == static_cast<const void *>(&ref)) {
+ return 2;
+ }
+ return 4;
+ } catch (int) {
+ return 1;
+ }
+ }
+ static_assert(conversion_test(10) == 1);
+}
+
+namespace References2 {
+ static constexpr auto via_const_catch = 2;
+ static constexpr auto via_childs_get_value = 3;
+ static constexpr auto via_special_child_catch = 5;
+
+ struct parent {
+ int value;
+ explicit constexpr parent(int v) noexcept: value{v} { }
+ constexpr virtual int get_value() const noexcept {
+ return value;
+ }
+ constexpr virtual ~parent() = default;
+ };
+
+ struct modifying_child: parent {
+ explicit constexpr modifying_child(int v) noexcept: parent{v} { }
+ constexpr int get_value() const noexcept override {
+ return value * via_childs_get_value;
+ }
+ };
+
+ struct ordinary_child: parent {
+ explicit constexpr ordinary_child(int v) noexcept: parent{v} { }
+ };
+
+ struct special_child: parent {
+ explicit constexpr special_child(int v) noexcept: parent{v} { }
+ };
+
+ consteval int test(void (*fnc)()) {
+ int result = 0;
+ try {
+ fnc();
+ } catch (special_child & sch) {
+ result = sch.get_value() * via_special_child_catch;
+ } catch (const special_child & sch) {
+ result = sch.get_value() * via_special_child_catch * via_const_catch;
+ } catch (parent & exc) {
+ result = exc.get_value();
+ } catch (const parent & exc) {
+ result = exc.get_value() * via_const_catch;
+ }
+ return result;
+ }
+
+ constexpr auto r1 = test([] { throw parent{1}; });
+ static_assert(r1 == 1);
+
+ constexpr auto r2 = test([] { throw modifying_child{3}; });
+ static_assert(r2 == 3 * via_childs_get_value);
+
+ constexpr auto r3 = test([] { throw ordinary_child{5}; });
+ static_assert(r3 == 5);
+
+ constexpr auto r4 = test([] { throw special_child{17}; });
+ static_assert(r4 == 17 * via_special_child_catch);
+}
+
+namespace Comma {
+ constexpr int catch_it() {
+ try {
+ return (1, throw 2, 3); // expected-warning {{left operand of comma operator has no effect}}
+ } catch (int v) {
+ return v;
+ }
+ }
+ static_assert(catch_it() == 2);
+}
+
+namespace Lifetime {
+ [[noreturn]] constexpr auto create(int v) -> int {
+ throw v; // expected-note {{uncaught exception of type 'int': '42'}} \
+ // expected-note {{uncaught exception of type 'int': '56'}} \
+ // expected-note {{uncaught exception of type 'int': '32'}} \
+ // expected-note {{uncaught exception of type 'int': '4'}} \
+ // expected-note {{uncaught exception of type 'int': '1'}}
+ }
+
+ constexpr int convert(int x) {
+ return x;
+ }
+
+ constexpr auto value1 = convert(create(42)); // expected-error {{must be initialized by a constant expression}}
+
+
+ struct wrapper {
+ int value;
+ };
+
+ constexpr auto value2 = wrapper{create(56)}; // expected-error {{must be initialized by a constant expression}}
+ constexpr auto value3 = wrapper(create(32)); // expected-error {{must be initialized by a constant expression}}
+ constexpr auto value4 = (1,2,3,create(4)); // expected-error {{must be initialized by a constant expression}}
+
+ constexpr int fnc() {
+ const auto v = create(1);
+ return v;
+ }
+
+ constexpr auto value5 = fnc(); // expected-error {{must be initialized by a constant expression}}
+}
+
+namespace TheWorst {
+ constexpr int zomg() try {
+ throw 12;
+ } catch (int i) {
+ return 13;
+ }
+
+ constexpr int c() {
+ return zomg();
+ }
+ static_assert(c() == 13);
+
+
+ struct hanaxception {
+ int v;
+ };
+
+ struct checker {
+ int value;
+ constexpr checker(int v) try : value{v} {
+ if (v > 10) {
+ throw hanaxception{v};
+ }
+ } catch (const hanaxception h) {
+ }
+ };
+
+ constexpr int test() {
+ try {
+ auto c = checker{11};
+ } catch(...) {}
+ return 42;
+ }
+ constexpr int constructor_test = test();
+ static_assert(constructor_test == 42);
+}
+
+namespace Destructors {
+ struct F {
+ constexpr ~F() noexcept(false){
+ throw 42; // expected-note {{uncaught exception of type 'int': '42'}}
+ }
+ };
+ constexpr int test() {
+ try {
+ F f;
+ return 1337;
+ } catch (int i) {
+ return i;
+ }
+
+ return 12;
+ }
+ static_assert(test() == 42);
+
+ constexpr int test2() {
+ F f;
+ return 1337;
+ }
+ static_assert(test2() == 42); // expected-error {{not an integral constant expression}}
+
+
+ constexpr int test3() {
+ int n = 0;
+ struct D {
+ int *p;
+ constexpr D(int *p) : p(p) {}
+ constexpr ~D() { ++*p; }
+ };
+ try {
+ throw D{&n};
+ } catch (...) {
+ } // The exception object should be destroyed here.
+ return n;
+ }
+ static_assert(test3() == 1);
+
+ class Base {
+ public:
+ int &p;
+ constexpr ~Base() {
+ ++p;
+ }
+ };
+
+ class P : public Base {
+ public:
+ int &q;
+ constexpr P(int &p, int &q) : Base(p), q(q) {}
+ constexpr ~P() {
+ ++q;
+ }
+ };
+
+ constexpr int test4() {
+ int p = 0;
+ int q = 0;
+
+ try {
+ throw P(p, q);
+ } catch (P &P) {
+ } catch (Base &B) {
+ }
+ return (p * 10) + q;
+ }
+
+ static_assert(test4() == 11);
+}
+
+namespace Destructors2 {
+ struct S {
+ int &d;
+ int &c;
+ int &m;
+
+ constexpr S(int& d, int &c, int &m) : d(d), c(c), m(m) {}
+ constexpr ~S() { ++d; }
+ constexpr S(const S& s) : d(s.d), c(s.c), m(s.m) {
+ ++c;
+ }
+ constexpr S(S&& s) : d(s.d), c(s.c), m(s.m) {
+ ++m;
+ }
+ };
+
+ constexpr int inner(int &d, int &c, int &m) {
+ try {
+ throw S{d, c, m};
+ } catch (S& s) {
+ throw s; // Here is the one and only call to D::D(D&).
+ // First ~D call is here.
+ }
+ return -1;
+ }
+
+ constexpr int outer (){
+ int d = 0; // destructors
+ int c = 0; // copy ctors
+ int m = 0; // move ctors
+
+
+ try {
+ inner(d, c, m);
+ } catch(S& s) {
+ // Second call is here.
+ }
+ return (d * 100) + (c * 10) + m;
+ }
+ static_assert(outer() == 210);
+
+
+ constexpr int inner2(int &d, int &c, int &m) {
+ try {
+ throw S{d, c, m};
+ } catch (S& s) {
+ throw;
+ }
+ return -1;
+ }
+
+ constexpr int outer2(){
+ int d = 0; // destructors
+ int c = 0; // copy ctors
+ int m = 0; // move ctors
+
+
+ try {
+ inner2(d, c, m);
+ } catch(S& s) {
+ // Second call is here.
+ }
+ return (d * 100) + (c * 10) + m;
+ }
+ static_assert(outer2() == 100);
+
+}
+
+namespace Noexcept {
+ constexpr void throw_exception_here() noexcept(false) {
+ throw 42;
+ }
+
+ constexpr int test() noexcept {
+ throw_exception_here(); // expected-note {{uncaught exception in noexcept function}}
+ return 42;
+ }
+ constexpr int value = test(); // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{in call to}}
+}
+
+namespace Move {
+ struct foo {
+ int value;
+ constexpr foo(int v): value{v} {}
+ constexpr foo(foo && other): value{other.value + 1} {}
+ constexpr int get() const {
+ return value;
+ }
+ };
+
+ consteval int testMove() {
+ try {
+ throw std::move(foo{1});
+ } catch (const foo & f) {
+ return f.get();
+ }
+ return 8;
+ }
+ static_assert(testMove() == 2);
+}
+
+#if 0
+namespace UncaughtExceptions {
+ constexpr int foo() {
+ try {
+ throw 42;
+ } catch (...) {
+ return __builtin_uncaught_exceptions();
+ }
+ return -1;
+ }
+ static_assert(foo() == 0);
+
+ struct F{
+ constexpr ~F() {
+ if (__builtin_uncaught_exceptions() != 0) {
+ __builtin_abort(); // expected-note {{subexpression not valid in a constant expression}}
+ }
+ }
+ };
+ constexpr int foo2() {
+
+ try {
+ F f; // expected-note {{in call to}}
+ throw 42;
+ } catch (...) {
+ return 0;
+ }
+
+ return -1;
+ }
+ static_assert(foo2() == 0); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+
+ constexpr int foo3() {
+ try {
+ throw 42;
+ } catch (int) {
+ return __builtin_uncaught_exceptions();
+ }
+ return -1;
+ }
+ static_assert(foo3() == 0);
+}
+#endif
+
+namespace Uncaught2 {
+ class E : std::exception {
+ constexpr const char *what() const noexcept {
+ return "SOME EXCEPTION WHADDAYAKNOW";
+ }
+ };
+ constexpr int foo() {
+ // FIXME: Call what() instead(?)
+ throw E(); // expected-note {{uncaught exception of type 'E': '&E()'}}
+ return 1;
+ }
+ static_assert(foo() == 1); // expected-error {{static assertion expression is not an integral constant expression}}
+
+
+}
+
+namespace UnusualTypes {
+ constexpr int foo1() {
+ throw (int[]){1,2,3}; // expected-note {{uncaught exception of type 'int *': '&(int[3]){1, 2, 3}[0]'}}
+ return 1;
+ }
+ static_assert(foo1() == 1); // expected-error {{not an integral constant expression}}
+
+
+ constexpr int foo2() {
+ throw 1i; // expected-note {{uncaught exception of type '_Complex int': '&1i'}}
+ return 1;
+ }
+ static_assert(foo2() == 1); // expected-error {{not an integral constant expression}}
+}
+
+namespace VirtCallOnException {
+ struct A {
+ virtual constexpr int getNumber()const { return 10; }
+ };
+ struct B : A {};
+ struct C : B {
+ constexpr int getNumber() const override {
+ return 100;
+ }
+ };
+
+ constexpr int foo() {
+ try {
+ throw C{};
+ } catch (A& a) {
+ return a.getNumber();
+ }
+ return 1;
+ }
+ static_assert(foo() == 100);
+
+}
+
+namespace VirtCall {
+ struct A {
+ virtual constexpr int getNumber()const { return 10; }
+ };
+ struct B : A {};
+ struct C : B {
+ constexpr int getNumber() const override {
+ return 100;
+ }
+ };
+
+ constexpr void nested() {
+ throw C{};
+ }
+
+ struct F {
+ constexpr virtual int foo() {
+ throw C{};
+ return 0;
+ }
+ };
+
+ constexpr int foo() {
+ try {
+ F f;
+ f.foo();
+ } catch (A& a) {
+ return a.getNumber();
+ }
+ return 1;
+ }
+ static_assert(foo() == 100);
+}
+
+namespace Variadic {
+ constexpr void variadic(...) {
+ throw 123;
+ }
+ constexpr int foo() {
+ try {
+ variadic(1,2,3,4);
+ } catch (int a) {
+ return a;
+ }
+ return 1;
+ }
+ static_assert(foo() == 123);
+}
+
+namespace StmtExpr {
+ constexpr int foo() {
+ try {
+ return ({
+ int a = 123;
+ throw 100; // expected-note {{this use of statement expressions is not supported in a constant expression}}
+ 12;
+ })
+ == 12;
+ } catch (int) {
+ return 200;
+ }
+
+ return -1;
+ }
+ static_assert(foo() == 200); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+namespace TryBody {
+ constexpr int t() {
+ throw 100;
+ };
+
+ constexpr int test() try {
+ t();
+ return 1;
+ } catch (...) {
+
+ return 20;
+ }
+ static_assert(test() == 20);
+}
+
+namespace ReThrow {
+ constexpr int t() {
+ throw 100;
+ };
+
+ constexpr int test() {
+ try {
+ t();
+ return 1;
+ } catch (...) {
+ throw;
+ return -4;
+ }
+ return -10;
+ }
+ constexpr int test2() {
+ try {
+ test();
+ } catch (int a) {
+ return a;
+ }
+ return -1;
+ }
+ static_assert(test2() == 100);
+
+
+ constexpr int test3() {
+ throw; // expected-note {{rethrow with no active exception}}
+ }
+ static_assert(test3() == 100); // expected-error {{static assertion expression is not an integral constant expression}} \
+ // expected-note {{in call to}}
+
+ constexpr int test4() {
+ try {
+ throw 100; // expected-note {{uncaught exception of type 'int': '100'}}
+ } catch(int) {
+ throw;
+ }
+ }
+ static_assert(test4() == 100); // expected-error {{static assertion expression is not an integral constant expression}}
+}
+
+namespace PointerInThrownValue {
+ /// Used to crash because of lifetime issues between the Pointer
+ /// saved in ThrownValue and the InterpState.
+ struct P {};
+ struct C : P{
+ constexpr C() {}
+ };
+ constexpr int foo() {
+
+ try {
+ } catch (int e) {
+ }
+
+ try {
+ auto thrower = []() { throw C(); };
+ thrower();
+ } catch (const P&) {
+ return 100;
+ }
+
+ return -1;
+ }
+ static_assert(foo() == 100);
+}
+
+namespace CatchAfterCallWithExceptionAlreadySet {
+ struct P {};
+ struct C : P{
+ constexpr C() {}
+ };
+ constexpr int foo() {
+
+ try {
+ throw 42;
+ } catch (int e) {
+ }
+ try {
+ auto thrower = []() { throw C(); };
+ thrower();
+ } catch (const P&) {
+ return 100;
+ }
+
+ return -1;
+ }
+}
+
+namespace PtrIntoLocal {
+ constexpr int foo() {
+ try {
+ throw "help";
+ } catch (const char *p) {
+ return (int)p[2];
+ }
+ return -1;
+ }
+ static_assert(foo() == 'l');
+}
+
+namespace NestedTry {
+ constexpr int func(int n, int m) {
+ return 10;
+ }
+ constexpr int foo() {
+ try {
+ int a;
+ a = 10;
+ try {
+ int b;
+ b = 20;
+ func(10, ({throw 30; 20;})); // expected-note {{this use of statement expressions is not supported in a constant expression}}
+ throw b;
+
+
+ } catch(...) {
+ throw;
+ }
+ } catch(int x) {
+ return x;
+ }
+ return -1;
+ }
+ static_assert(foo() == 30); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+
+}
+
+namespace ThrowWithActiveException {
+ struct S {
+ constexpr ~S() noexcept(false) {
+ throw 2; // expected-note {{throw while another exception is already active}}
+ }
+ };
+
+ constexpr int f() {
+ try {
+ S s;
+ throw 1; // expected-note {{currently active exception thrown here}}
+ } catch (...) {
+ }
+ return 0;
+ }
+ static_assert(f() == 0); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+namespace DifferentCastAfterRethrow {
+ struct A {};
+ struct B : A {};
+ struct C : B {};
+
+ constexpr void a() {
+ throw C{};
+ };
+ constexpr void b() {
+ try {
+ a();
+ } catch (A) {
+ throw;
+ }
+ }
+ constexpr int c() {
+ try {
+ b();
+ } catch (B) {
+ return 10;
+ } catch (...) {
+ return -2;
+ }
+ return -1;
+ }
+ static_assert(c() == 10);
+}
+
+namespace MemberPointers {
+ struct S {
+ int m, n;
+ };
+ // constexpr int S::*pm = &S::m;
+ constexpr int S::* foo() {
+ try {
+ throw &S::m;
+ } catch (int S::* pm) {
+ return pm;
+ }
+ return nullptr;
+ }
+ static_assert(foo() == &S::m);
+
+ constexpr int S::* foo2() {
+ try {
+ throw &S::m;
+ } catch (int S::* &pm) {
+ return pm;
+ }
+ return nullptr;
+ }
+ static_assert(foo2() == &S::m);
+
+ /// Here, we catch the null pointer as a reference-to-member-pointer.
+ /// [except.handle]p3 only allows this for const references, but GCC and
+ /// Clang (at runtime and GCC also at compile time) accept it and bind pm to a
+ /// null member pointer; we do the same.
+ constexpr int S::* foo3() {
+ try {
+ throw nullptr;
+ } catch (int S::* &pm) {
+ return pm;
+ }
+ return &S::m;
+ }
+ static_assert(foo3() == nullptr);
+}
+
+namespace FunctionPointers {
+#define fold(x) (__builtin_constant_p(x) ? (x) : (x))
+ extern int zomg();
+
+ constexpr int foo() {
+ try {
+ throw &zomg;
+ } catch (int (*)()) {
+ return 2;
+ } catch (const int ) {
+ return 0;
+ }
+ return -1;
+ }
+ static_assert(foo() == 2);
+
+ /// void* doesn't catch function pointers.
+ constexpr int foo2() {
+ try {
+ throw &zomg;
+ } catch (void* p) {
+ return 1;
+ } catch (...) {
+ return 2;
+ }
+ return -1;
+ }
+ static_assert(foo2() == 2);
+
+
+ extern int zomg2() noexcept;
+ constexpr int foo3() {
+ try {
+ throw &zomg;
+ } catch ( int (*)()) {
+ return 13;
+ }
+ return -1;
+ }
+ static_assert(foo3() == 13);
+
+ constexpr int foo4() {
+ try {
+ throw &zomg2;
+ } catch ( int (*)() noexcept) {
+ return 13;
+ }
+ return -1;
+ }
+ static_assert(foo4() == 13);
+
+ constexpr int foo5() {
+ try {
+ throw &zomg; // expected-note {{uncaught exception of type 'int (*)()': '&zomg'}}
+ } catch ( int (*) () noexcept ) {
+ return 13;
+ }
+ return -1;
+ }
+ static_assert(foo5() == 0); // expected-error {{not an integral constant expression}}
+
+ constexpr int intfunc() { return 1; }
+ constexpr int foo6() {
+ try {
+ throw &intfunc; /// int (*)()
+ } catch (void (*)(int)) {
+ return 1;
+ } catch (int (*)()) {
+ return 2;
+ }
+ return 0;
+ }
+ static_assert(foo6() == 2);
+
+
+
+}
+
+namespace CopCtors {
+ struct S {
+ int &ConstCC;
+ int &CC;
+
+ constexpr S(int &CC, int &ConstCC) : CC(CC), ConstCC(ConstCC) {}
+
+ constexpr S(const S& s) :CC(s.CC), ConstCC(s.ConstCC) {
+ ++ConstCC;
+ }
+ constexpr S(S& s) :CC(s.CC), ConstCC(s.ConstCC) {
+ ++CC;
+ }
+ };
+
+ constexpr int foo() {
+ int CopyCtorCalled = 0;
+ int ConstCopyCtorCalled = 0;
+ try {
+ throw S(CopyCtorCalled, ConstCopyCtorCalled);
+ } catch (S) {
+ }
+ return CopyCtorCalled + (ConstCopyCtorCalled * 10);
+ }
+ static_assert(foo() == 1);
+
+ constexpr int foo2() {
+ int CopyCtorCalled = 0;
+ int ConstCopyCtorCalled = 0;
+ auto M = S(CopyCtorCalled, ConstCopyCtorCalled);
+ try {
+ throw M;
+ } catch (S) {
+ }
+ return CopyCtorCalled + (ConstCopyCtorCalled * 10);
+ }
+ static_assert(foo2() == 2);
+
+ constexpr int foo3() {
+ int CopyCtorCalled = 0;
+ int ConstCopyCtorCalled = 0;
+
+ const auto M = S(CopyCtorCalled, ConstCopyCtorCalled);
+ try {
+ throw M;
+ } catch (S) {
+ }
+
+ return CopyCtorCalled + (ConstCopyCtorCalled * 10);
+ }
+ static_assert(foo3() == 11);
+
+ struct E {
+ bool copied = false;
+ constexpr E(int) {}
+ constexpr E(const E&) { copied = true; }
+ };
+ constexpr int f() try {
+ throw E(1);
+ } catch (E e) {
+ return e.copied ? 42 : 0;
+ }
+ static_assert(f() == 42);
+}
+
+namespace CopyCtors2 {
+ struct S {
+ int &ConstCC;
+ int &ConstVolatileCC;
+ int &VolatileCC;
+ int &CC;
+
+ constexpr S(int &CC, int &ConstCC, int &ConstVolatileCC, int &VolatileCC) : CC(CC), ConstCC(ConstCC), ConstVolatileCC(ConstVolatileCC), VolatileCC(VolatileCC) {}
+ constexpr S(S& s) :CC(s.CC), ConstCC(s.ConstCC), ConstVolatileCC(s.ConstVolatileCC), VolatileCC(s.VolatileCC) {
+ ++CC;
+ }
+ constexpr S(const S& s) :CC(s.CC), ConstCC(s.ConstCC), ConstVolatileCC(s.ConstVolatileCC), VolatileCC(s.VolatileCC) {
+ ++ConstCC;
+ }
+ constexpr S(const volatile S& s) :CC(s.CC), ConstCC(s.ConstCC), ConstVolatileCC(s.ConstVolatileCC), VolatileCC(s.VolatileCC) {
+ ++ConstVolatileCC;
+ }
+ constexpr S(volatile S& s) :CC(s.CC), ConstCC(s.ConstCC), ConstVolatileCC(s.ConstVolatileCC), VolatileCC(s.VolatileCC) {
+ ++VolatileCC;
+ }
+ };
+
+ constexpr int foo1() {
+ int CopyCtorCalled = 0;
+ int ConstCopyCtorCalled = 0;
+ int ConstVolatileCopyCtorCalled = 0;
+ int VolatileCopyCtorCalled = 0;
+
+ auto M = S(CopyCtorCalled, ConstCopyCtorCalled, ConstVolatileCopyCtorCalled, VolatileCopyCtorCalled);
+ try {
+ throw M;
+ } catch (S) {
+ }
+
+ return (VolatileCopyCtorCalled * 1000) + (ConstVolatileCopyCtorCalled * 100) + (ConstCopyCtorCalled * 10) + CopyCtorCalled;
+ }
+ static_assert(foo1() == 2);
+
+ constexpr int foo2() {
+ int CopyCtorCalled = 0;
+ int ConstCopyCtorCalled = 0;
+ int ConstVolatileCopyCtorCalled = 0;
+ int VolatileCopyCtorCalled = 0;
+
+ const auto M = S(CopyCtorCalled, ConstCopyCtorCalled, ConstVolatileCopyCtorCalled, VolatileCopyCtorCalled);
+ try {
+ throw M;
+ } catch (S) {
+ }
+ return (VolatileCopyCtorCalled * 1000) + (ConstVolatileCopyCtorCalled * 100) + (ConstCopyCtorCalled * 10) + CopyCtorCalled;
+ }
+ static_assert(foo2() == 11);
+}
+
+/// There is no copy ctor taking a const parameter, so we have no exact match for the qualifiers of the thrown value. However, there is one taking a const volatile, so we pick that one.
+/// This matches GCC's behavior, except that gcc errors because of the volatile read.
+namespace CopyCtors3 {
+ struct S {
+ int &ConstCC;
+ int &ConstVolatileCC;
+ int &VolatileCC;
+ int &CC;
+
+ constexpr S(int &CC, int &ConstCC, int &ConstVolatileCC, int &VolatileCC) : CC(CC), ConstCC(ConstCC), ConstVolatileCC(ConstVolatileCC), VolatileCC(VolatileCC) {}
+ constexpr S(S& s) :CC(s.CC), ConstCC(s.ConstCC), ConstVolatileCC(s.ConstVolatileCC), VolatileCC(s.VolatileCC) {
+ ++CC;
+ }
+ // constexpr S(const S& s) :CC(s.CC), ConstCC(s.ConstCC), ConstVolatileCC(s.ConstVolatileCC), VolatileCC(s.VolatileCC) {
+ // ++ConstCC;
+ // }
+ constexpr S(volatile S& s) :CC(s.CC), ConstCC(s.ConstCC), ConstVolatileCC(s.ConstVolatileCC), VolatileCC(s.VolatileCC) {
+ ++VolatileCC;
+ }
+ constexpr S(const volatile S& s) :CC(s.CC), ConstCC(s.ConstCC), ConstVolatileCC(s.ConstVolatileCC), VolatileCC(s.VolatileCC) {
+ ++ConstVolatileCC;
+ }
+ };
+
+ constexpr int foo3() {
+ int CopyCtorCalled = 0;
+ int ConstCopyCtorCalled = 0;
+ int ConstVolatileCopyCtorCalled = 0;
+ int VolatileCopyCtorCalled = 0;
+
+ const auto M = S(CopyCtorCalled, ConstCopyCtorCalled, ConstVolatileCopyCtorCalled, VolatileCopyCtorCalled);
+ try {
+ throw M;
+ } catch (S) {
+ }
+
+ return (VolatileCopyCtorCalled * 1000) + (ConstVolatileCopyCtorCalled * 100) + (ConstCopyCtorCalled * 10) + CopyCtorCalled;
+ }
+ static_assert(foo3() == 101);
+}
+
+namespace QualificationConversion {
+ constexpr int foo() {
+ int a = 100;
+ try {
+ throw &a;
+ } catch ( const int *k) {
+ return *k;
+ }
+ return -1;
+ }
+ static_assert(foo() == 100);
+
+ constexpr int foo2() {
+ const int a = 100;
+ try {
+ throw &a;
+ } catch ( const int *k) {
+ return *k;
+ }
+ return -1;
+ }
+ static_assert(foo2() == 100);
+
+
+ constexpr int foo3() {
+ const int a = 100;
+ try {
+ throw &a; // expected-note {{uncaught exception of type 'const int *': '&a'}}
+ } catch (int *k) {
+ return *k;
+ }
+ return -1;
+ }
+ static_assert(foo3() == -1); // expected-error {{not an integral constant expression}}
+
+}
+
+namespace EvalEmitter {
+ int add(int a, int b) { return a + b; }
+ int f(int x) {
+ return add(({
+ try { x = 1; } catch (...) { x = 2; }
+ x;
+ }), 0) + 1;
+ }
+}
+
+namespace CatchOffsetRethrow {
+ struct A { int a = 1; };
+ struct B { int b = 2; };
+ struct C : A, B { int c = 3;};
+ constexpr int f() try {
+ try {
+ throw C{};
+ } catch (B &) {
+ throw;
+ };
+ } catch (C c) {
+ return c.c;
+ }
+ static_assert(f() == 3);
+}
+
+namespace RethrowNoActiveException {
+ constexpr int f() try {
+ try {
+ throw 1;
+ } catch (int) {
+ }
+ throw; // expected-note {{rethrow with no active exception}}
+ } catch (int) {
+ return 42;
+ }
+ static_assert(f() == 42); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+
+}
+
+namespace Cleanup {
+ struct D {
+ int *r;
+ constexpr ~D() { ++*r; }
+ };
+ constexpr void g(int &n) {
+ try {
+ throw D{&n};
+ } catch (...) {
+ return;
+ }
+ }
+ constexpr int ret_in_handler() {
+ int n = 0;
+ g(n);
+ return n;
+ }
+ static_assert(ret_in_handler() == 1);
+
+
+ constexpr int destroy_twice() {
+ int n = 0;
+ try { throw D{&n}; } catch (...) {}
+ try { throw 1; } catch (...) {}
+ return n;
+ }
+ static_assert(destroy_twice() == 1);
+}
+
+namespace Const {
+ constexpr int foo() {
+ try {
+ throw 10;
+ } catch (int m) {
+ ++m;
+ return m;
+ }
+ return -1;
+ }
+ static_assert(foo() == 11);
+
+ constexpr int foo2() {
+ try {
+ throw 10;
+ } catch (const int m) {
+ ++((int&)m); // expected-note {{modification of object of const-qualified type 'const int' is not allowed in a constant expression}}
+ return m;
+ }
+ return -1;
+ }
+ static_assert(foo2() == 11); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+namespace Mutable {
+ struct S {
+ mutable int m;
+ };
+ constexpr int foo() {
+ try {
+ throw S{10};
+ } catch (S& s) {
+ return s.m;
+ }
+ return -1;
+ }
+ static_assert(foo() == 10);
+}
+
+namespace Scope1 {
+ struct Inc {
+ int &m;
+ int v;
+ constexpr Inc(int &m, int v = 1) : m(m), v(v) {}
+ constexpr ~Inc() { m += v; }
+ };
+
+ constexpr int f() {
+ int m = 10;
+ try {
+
+ {
+ Inc _(m,3);
+ {
+ Inc aaa(m);
+ throw 12;
+ }
+ }
+
+ } catch (int) {
+ return m;
+ }
+ return -100;
+ }
+ static_assert(f() == 14);
+}
+
+namespace Scope2 {
+ struct Inc {
+ int &m;
+ int v;
+ constexpr Inc(int &m, int v = 1) : m(m), v(v) {}
+ constexpr ~Inc() { m += v; }
+ };
+
+ /// We have to copy the value of m into the exception object _before_ calling local destructors that might modify it.
+ constexpr int f() {
+ int m = 10;
+ try {
+ {
+ Inc _(m,3);
+ {
+ Inc aaa(m);
+ throw m;
+ }
+ }
+ } catch (int k) {
+ return k;
+ }
+
+ return -100;
+ }
+ static_assert(f() == 10);
+}
+
+namespace Scope3 {
+ struct Inc {
+ int &m;
+ int v;
+ constexpr Inc(int &m, int v = 1) : m(m), v(v) {}
+ constexpr ~Inc() { m += v; }
+ };
+ constexpr int g() {
+ int m = 10;
+ try {
+ Inc _(m);
+ {
+ Inc _(m);
+ throw 12;
+ }
+ } catch (int) {
+ return m;
+ }
+ }
+ static_assert(g() == 12);
+}
+
+namespace Lifetime {
+ constexpr int foo() {
+ int *p;
+ try {
+ int m = 10; // expected-note {{declared here}}
+ p = &m;
+ throw 10;
+ } catch(int) {
+ return *p; // expected-note {{read of object outside its lifetime is not allowed in a constant expression}}
+ }
+
+ return -10;
+ }
+ static_assert(foo() == 10); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+namespace LifetimeCall {
+ constexpr void t() { throw 1; }
+
+ constexpr int foo() {
+ int *p;
+ try {
+ int m = 10; // expected-note {{declared here}}
+ p = &m;
+ t();
+ } catch(int) {
+ return *p; // expected-note {{read of object outside its lifetime is not allowed in a constant expression}}
+ }
+
+ return -10;
+ }
+ static_assert(foo() == 10); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+namespace CallPtr {
+ constexpr int zomg() noexcept {
+ throw 'a'; // expected-note {{uncaught exception in noexcept function}}
+ return 1;
+ }
+ constexpr int test1() {
+ auto c = &zomg;
+ return c(); // expected-note {{in call to}}
+ }
+ static_assert(test1() == 1); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+
+ constexpr int zomg2() noexcept {
+ try {
+ throw 'a';
+ } catch (char) {
+ return 3;
+ }
+ return 1;
+ }
+ constexpr int test2() {
+ auto c = &zomg2;
+ return c();
+ }
+ static_assert(test2() == 3);
+
+ constexpr int zomg3() {
+ throw 'a';
+ return 1;
+ }
+ constexpr int test3() {
+ auto c = &zomg3;
+ try {
+ return c();
+ } catch (char) {
+ return 10;
+ }
+ return -1;
+ }
+ static_assert(test3() == 10);
+}
+
+namespace ThrowInCtor {
+ struct S {
+ constexpr S() {
+ throw 12;
+ }
+ constexpr S(int) {}
+ };
+
+ constexpr int foo() {
+ S{2};
+ try {
+ S{};
+ } catch(int) {
+ return 1;
+ }
+ return 2;
+ }
+ static_assert(foo() == 1);
+}
+
+namespace NoLeakHere {
+ struct bytes {
+ using size_t = unsigned int;
+ unsigned char d[4];
+
+ constexpr unsigned char operator[](size_t index) {
+ return d[index]; // expected-note {{read of uninitialized object}}
+ }
+ };
+ constexpr auto f = []() constexpr {
+ constexpr struct { unsigned short b1; unsigned char b0; } B = {0xc0ff, 0xee};
+ return __builtin_bit_cast(bytes, B);
+ };
+ constexpr auto _bad = f()[3]; // expected-error {{initialized by a constant expression}} \
+ // expected-note {{in call to}} \
+ // expected-note {{temporary created here}}
+}
+
+namespace CatchScopeDestroy {
+ struct S {
+ int *p;
+ int inc = 1;
+ constexpr S(int *p) : p(p) {}
+ constexpr S(const S &o) : p(o.p), inc(10) {}
+ constexpr ~S() { *p += inc; }
+ };
+
+ constexpr int fallOff() {
+ int n = 0;
+ try {
+ throw S{&n};
+ } catch (S s) {
+ }
+ return n;
+ }
+ static_assert(fallOff() == 11);
+
+ constexpr void ret(int &n) {
+ try {
+ throw S{&n};
+ } catch (S s) {
+ return;
+ }
+ }
+ constexpr int viaReturn() {
+ int n = 0;
+ ret(n);
+ return n;
+ }
+ static_assert(viaReturn() == 11);
+}
+
+namespace ThrowingCtorInitializers {
+ constexpr int thrower() { throw 1; }
+
+ struct InitThrows {
+ int m;
+ constexpr InitThrows(bool &c) try : m(thrower()) {
+ } catch (...) {
+ c = true;
+ }
+ };
+ constexpr bool initCaught() {
+ bool c = false;
+ try {
+ InitThrows a(c);
+ } catch (...) {
+ }
+ return c;
+ }
+ static_assert(initCaught());
+
+ /// Catch handlers in ctors need to rethrow at the end.
+ struct BodyThrows {
+ constexpr BodyThrows() try {
+ throw 1;
+ } catch (...) {
+ }
+ };
+ constexpr int bodyRethrows() {
+ try {
+ BodyThrows b;
+ } catch (int) {
+ return 12;
+ }
+ return 0;
+ }
+ static_assert(bodyRethrows() == 12);
+
+}
+
+namespace ThrowingDtors {
+ struct S {
+ constexpr ~S() noexcept(false) {
+ throw -1;
+ }
+ };
+
+ struct F {
+ S s;
+
+ constexpr ~F() try {
+ // Field is destroyed.
+ } catch(...) {
+ return;
+ }
+ };
+
+ constexpr int test() {
+ {
+ F f;
+ }
+ return 12;
+ }
+ static_assert(test() == 12);
+
+ struct DtorThrows {
+ constexpr ~DtorThrows() noexcept(false) try {
+ throw 1;
+ } catch (...) {
+ }
+ };
+ constexpr int dtorRethrows() {
+ try {
+ DtorThrows d;
+ } catch (int) {
+ return 1;
+ }
+ return 0;
+ }
+ static_assert(dtorRethrows() == 1);
+
+}
+
+namespace NestedException {
+ struct E { int x; };
+ struct F {};
+
+ /// Inner exception must not destroy the outer one.
+ constexpr int innerInHandler() {
+ try {
+ throw E{5};
+ } catch (E &e) {
+ try {
+ throw F();
+ } catch (F &) {
+ }
+ return e.x;
+ }
+ return 0;
+ }
+ static_assert(innerInHandler() == 5);
+
+ /// Outer exception is still rethrowable after inner one is handled.
+ constexpr int rethrowAfterInner() {
+ try {
+ try {
+ throw E{7};
+ } catch (E &) {
+ try {
+ throw F();
+ } catch (F &) {
+ }
+ throw;
+ }
+ } catch (E &e) {
+ return e.x;
+ }
+ return 0;
+ }
+ static_assert(rethrowAfterInner() == 7);
+
+ /// Throw and catch inside a destructor run during unwinding.
+ struct G {
+ constexpr ~G() {
+ try {
+ throw 1;
+ } catch (int) {
+ }
+ }
+ };
+ constexpr int throwDuringUnwind() {
+ try {
+ G g;
+ throw E{3};
+ } catch (E &e) {
+ return e.x;
+ }
+ return 0;
+ }
+ static_assert(throwDuringUnwind() == 3);
+}
+
+namespace DestroyedException {
+ constexpr int foo() {
+ int *p;
+ try {
+ throw 12; // expected-note {{declared here}}
+ } catch (int& s) {
+ p = &s;
+ }
+ *p = 10; // expected-note {{assignment to object outside its lifetime}}
+ return 0;
+ }
+ static_assert(foo() == 0); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+namespace ExceptionDoubleDestroy {
+ constexpr int f() {
+ try {
+ throw 1;
+ } catch (...) {
+ try {
+ throw;
+ } catch (...) {
+ }
+ }
+ return 0;
+ }
+ static_assert(f() == 0);
+}
+
+namespace RethrowCleanup {
+ struct Inc {
+ int &a;
+ constexpr Inc(int &a) : a(a) {}
+ constexpr ~Inc() { ++a; }
+ };
+
+ constexpr int f() {
+ int a = 0;
+ try {
+ throw 1;
+ } catch (...) {
+ try {
+ Inc I(a);
+ throw;
+ } catch (...) {
+ }
+ }
+ return a;
+ }
+ static_assert(f() == 1);
+}
+
+namespace {
+constexpr void g() { throw 2; }
+constexpr int f() {
+ try {
+
+ try {
+ throw 1;
+ } catch (int) {
+ g();
+ }
+
+ } catch (int a) {
+ return a;
+ }
+ return 0;
+}
+static_assert(f() == 2);
+}
+
+
+namespace RethrowInCallee {
+ constexpr void rethrow() { throw; }
+ constexpr int f() {
+ try {
+
+ try {
+ throw 1;
+ } catch (...) {
+ rethrow();
+ return 10;
+ }
+
+ } catch (int i) {
+ return i;
+ }
+ return 0;
+ }
+ static_assert(f() == 1);
+}
+
+namespace ReplaceException {
+ constexpr void replace() { try { throw; } catch (...) { throw 2; } }
+ constexpr int g() {
+ try {
+ try { throw 1; }
+ catch (...) { replace(); return 10; }
+ } catch (int i) { return i; }
+ return 0;
+ }
+ static_assert(g() == 2);
+}
+
+namespace SwallowException {
+ constexpr void swallow() {
+ try {
+ throw;
+ } catch (...) {
+ }
+ }
+ constexpr int h() {
+ try {
+ throw 1;
+ } catch (...) {
+ swallow();
+ return 1;
+ }
+ return 0;
+ }
+ static_assert(h() == 1);
+}
+
+namespace Rethrow2 {
+ constexpr void rethrow() {
+ throw;
+ }
+ constexpr int f() {
+ try {
+ try {
+ throw 1;
+ } catch (...) {
+ rethrow();
+ return 10;
+ }
+
+ } catch (int i) {
+ return i;
+
+ }
+ return 0;
+ }
+ static_assert(f() == 1);
+}
+
+/// A nested handler catching the rethrown exception must not end its lifetime.
+namespace SwallowThenUse {
+ struct E {
+ int *Dtors;
+ int V;
+ constexpr ~E() { ++*Dtors; }
+ };
+ constexpr void swallow() {
+ try { throw; } catch (...) {}
+ }
+
+ constexpr int f() {
+ try {
+ throw 1;
+ } catch (int &e) {
+ swallow();
+ return e;
+ }
+ return 0;
+ }
+ static_assert(f() == 1);
+
+ constexpr int g() {
+ int Dtors = 0;
+ int V = 0;
+ try {
+ throw E{&Dtors, 5};
+ } catch (E &e) {
+ swallow();
+ V = e.V;
+ }
+ return V * 10 + Dtors;
+ }
+ static_assert(g() == 51);
+}
+
+/// Rethrows exiting several handlers.
+namespace RethrowNestedHandlers {
+ // Rethrow from a handler nested in a handler of the same exception.
+ constexpr int f() {
+ try {
+ try { throw 1; }
+ catch (int &) { try { throw; } catch (...) { throw; } }
+ } catch (int i) { return i; }
+ return 0;
+ }
+ static_assert(f() == 1);
+
+ struct E {
+ int *Dtors;
+ int V;
+ constexpr ~E() { ++*Dtors; }
+ };
+
+ // Outer handler's different exception is destroyed when the inner rethrow exits it.
+ constexpr int g() {
+ int DA = 0, DB = 0, V = 0;
+ try {
+ try { throw E{&DA, 1}; }
+ catch (E &) {
+ try { throw E{&DB, 2}; }
+ catch (E &) { throw; }
+ }
+ } catch (E &e) { V = e.V; if (DA != 1 || DB != 0) return -1; }
+ return V * 100 + DA * 10 + DB;
+ }
+ static_assert(g() == 211);
+
+ // Function-try-block: by-value catch param destroyed before implicit rethrow.
+ struct S {
+ int X;
+ constexpr S(int *D) try : X(0) { throw E{D, 3}; } catch (E e) {}
+ };
+ constexpr int h() {
+ int D = 0;
+ try { S s(&D); } catch (E &e) { if (D != 1) return -1; }
+ return D;
+ }
+ static_assert(h() == 2);
+}
+
+/// No handler matches; locals outside the try must still be destroyed.
+namespace UnmatchedTryOuterDtor {
+ struct S {
+ int *p;
+ constexpr ~S() { ++*p; }
+ };
+ constexpr int f(int &n) {
+ S outer{&n};
+ try {
+ throw 1;
+ } catch (float) {}
+ return 0;
+ }
+ constexpr int test() {
+ int n = 0;
+ try {
+ f(n);
+ } catch (int) {}
+ return n;
+ }
+ static_assert(test() == 1);
+
+ /// Same, but propagating from a call and through nested try blocks.
+ constexpr void thrower() { throw 1; }
+ constexpr int nested() {
+ int n = 0;
+ try {
+ S a{&n};
+ try {
+ S b{&n};
+ try {
+ thrower();
+ } catch (float) {}
+ } catch (char) {}
+ } catch (int) {}
+ return n;
+ }
+ static_assert(nested() == 2);
+}
+
+/// Like ThrowWithActiveException, but the first exception comes from a call.
+namespace ThrowWithActiveExceptionFromCall {
+ struct S {
+ constexpr ~S() noexcept(false) {
+ throw 2; // expected-note {{throw while another exception is already active}}
+ }
+ };
+ constexpr void g() {
+ throw 1; // expected-note {{currently active exception thrown here}}
+ }
+ constexpr int f() {
+ try {
+ S s;
+ g();
+ } catch (...) {
+ }
+ return 0;
+ }
+ static_assert(f() == 0); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+namespace DeleteThrowingDtor {
+ struct T {
+ constexpr ~T() noexcept(false) { throw 1; }
+ };
+ struct S {
+ int *p;
+ constexpr ~S() { ++*p; }
+ };
+ constexpr void h() {}
+
+ /// The exception escapes the delete-expression; 'h()' isn't reached.
+ constexpr int single() {
+ try {
+ T *p = new T;
+ delete p;
+ h();
+ return 0;
+ } catch (int i) {
+ return i;
+ }
+ return 2;
+ }
+ static_assert(single() == 1);
+
+ /// Locals between the delete and the handler are destroyed.
+ constexpr int unwinds() {
+ int n = 0;
+ try {
+ S s{&n};
+ T *p = new T;
+ delete p;
+ } catch (int) {
+ }
+ return n;
+ }
+ static_assert(unwinds() == 1);
+
+ /// Propagates out of a function.
+ constexpr void del(T *p) { delete p; }
+ constexpr int fromCall() {
+ try {
+ del(new T);
+ } catch (int i) {
+ return i;
+ }
+ return 0;
+ }
+ static_assert(fromCall() == 1);
+
+ /// Only one element throws; the others are still destroyed.
+ struct U {
+ int *p;
+ bool Throws;
+ constexpr ~U() noexcept(false) {
+ ++*p;
+ if (Throws)
+ throw 3; // expected-note {{throw while another exception is already active}} \
+ // expected-note {{currently active exception thrown here}}
+ }
+ };
+ constexpr int array() {
+ int n = 0;
+ try {
+ U *p = new U[3]{{&n, false}, {&n, true}, {&n, false}};
+ delete[] p;
+ } catch (int i) {
+ return n * 10 + i;
+ }
+ return -1;
+ }
+ static_assert(array() == 33);
+
+ /// Two elements throw: terminate.
+ constexpr int array2() {
+ int n = 0;
+ try {
+ U *p = new U[2]{{&n, true}, {&n, true}};
+ delete[] p;
+ } catch (int) {
+ }
+ return 0;
+ }
+ static_assert(array2() == 0); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+/// The exception object's destructor throws when its handler exits.
+namespace ThrowingExceptionDtor {
+ struct X {
+ int v;
+ constexpr ~X() noexcept(false) {
+ throw 2; // expected-note {{throw while another exception is already active}}
+ }
+ };
+
+ /// Propagates from the handler's end.
+ constexpr int fallthrough() {
+ try {
+ try {
+ throw X{1};
+ } catch (X &) {
+ }
+ } catch (int i) {
+ return i;
+ }
+ return 0;
+ }
+ static_assert(fallthrough() == 2);
+
+ /// Same, leaving the handler via return; locals outside are destroyed.
+ struct S {
+ int *p;
+ constexpr ~S() { ++*p; }
+ };
+ constexpr int ret(int &n) {
+ S s{&n};
+ try {
+ throw X{1};
+ } catch (...) {
+ return 5;
+ }
+ return 0;
+ }
+ constexpr int viaReturn() {
+ int n = 0;
+ try {
+ ret(n);
+ } catch (int i) {
+ return n * 10 + i;
+ }
+ return -1;
+ }
+ static_assert(viaReturn() == 12);
+
+ /// The handler exits by unwinding: terminate.
+ constexpr int unwinding() {
+ try {
+ try {
+ throw X{1};
+ } catch (X &) {
+ throw 3; // expected-note {{currently active exception thrown here}}
+ }
+ } catch (...) {
+ }
+ return 0;
+ }
+ static_assert(unwinding() == 0); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+/// An initializer throws; the unconstructed object must not be destroyed.
+namespace UnconstructedLocal {
+ struct S {
+ int *p;
+ constexpr ~S() { ++*p; }
+ };
+ constexpr S mayThrow(int *p) {
+ throw 1;
+ return S{p};
+ }
+
+ constexpr int var() {
+ int n = 0;
+ try {
+ S a = mayThrow(&n);
+ } catch (...) {
+ }
+ return n;
+ }
+ static_assert(var() == 0);
+
+ /// Locals constructed before the throwing initializer are destroyed.
+ constexpr int earlier() {
+ int n = 0;
+ try {
+ S a{&n};
+ S b = mayThrow(&n);
+ } catch (...) {
+ }
+ return n;
+ }
+ static_assert(earlier() == 1);
+
+ constexpr int ref() {
+ int n = 0;
+ try {
+ const S &r = mayThrow(&n);
+ } catch (...) {
+ }
+ return n;
+ }
+ static_assert(ref() == 0);
+
+ constexpr int discarded() {
+ int n = 0;
+ try {
+ (void)S(mayThrow(&n));
+ } catch (...) {
+ }
+ return n;
+ }
+ static_assert(discarded() == 0);
+}
+
+/// A later initializer throws; already constructed subobjects are destroyed,
+/// in reverse order.
+namespace PartialAggregateInit {
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+ constexpr S mayThrow(int *) {
+ throw 1;
+ return S{nullptr, 0};
+ }
+
+ struct P {
+ S a, b, c;
+ };
+ constexpr int fields() {
+ int log = 0;
+ try {
+ P p = {S{&log, 1}, S{&log, 2}, mayThrow(&log)};
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(fields() == 21);
+
+ constexpr int array() {
+ int log = 0;
+ try {
+ S arr[3] = {S{&log, 1}, S{&log, 2}, mayThrow(&log)};
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(array() == 21);
+
+ /// Mixed with primitives and a temporary.
+ struct Q {
+ int i;
+ S a;
+ int j;
+ S b;
+ };
+ constexpr int mixed() {
+ int log = 0;
+ try {
+ const Q &q = {1, S{&log, 1}, 2, mayThrow(&log)};
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(mixed() == 1);
+
+ /// Bases.
+ struct B {
+ S s;
+ };
+ struct D : B {
+ S t;
+ };
+ constexpr int base() {
+ int log = 0;
+ try {
+ D d = {{S{&log, 1}}, mayThrow(&log)};
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(base() == 1);
+
+ /// Nested: the inner aggregate is complete, the outer one isn't.
+ struct N {
+ P p;
+ S s;
+ };
+ constexpr int nested() {
+ int log = 0;
+ try {
+ N n = {{S{&log, 1}, S{&log, 2}, S{&log, 3}}, mayThrow(&log)};
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(nested() == 321);
+
+ /// The throw happens inside the inner aggregate.
+ constexpr int nestedInner() {
+ int log = 0;
+ try {
+ S arr[2][2] = {{S{&log, 1}, S{&log, 2}}, {S{&log, 3}, mayThrow(&log)}};
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(nestedInner() == 321);
+
+ /// Array filler: the explicitly initialized element is destroyed when the
+ /// filler throws.
+ struct F {
+ int *log;
+ constexpr F(int *log) : log(log) {}
+ constexpr F() : log(nullptr) { throw 1; }
+ constexpr ~F() { ++*log; }
+ };
+ constexpr int filler() {
+ int log = 0;
+ try {
+ F arr[4] = {F{&log}};
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(filler() == 1);
+
+ /// Nothing throws: everything destroyed exactly once, at scope end.
+ constexpr int noThrow() {
+ int log = 0;
+ {
+ P p = {S{&log, 1}, S{&log, 2}, S{&log, 3}};
+ }
+ return log;
+ }
+ static_assert(noThrow() == 321);
+}
+
+/// A new-expression's initializer throws: constructed elements are destroyed
+/// and the storage is freed ([expr.new]p26).
+namespace NewInitializerThrows {
+ constexpr int thrower() {
+ throw 1;
+ return 0;
+ }
+
+ struct T {
+ int v;
+ constexpr T(int v) : v(v) {}
+ };
+ constexpr int single() {
+ try {
+ T *p = new T(thrower());
+ delete p;
+ } catch (int i) {
+ return i;
+ }
+ return 0;
+ }
+ static_assert(single() == 1);
+
+ constexpr int prim() {
+ try {
+ int *p = new int(thrower());
+ delete p;
+ } catch (int i) {
+ return i;
+ }
+ return 0;
+ }
+ static_assert(prim() == 1);
+
+ constexpr int direct() {
+ try {
+ T *p = new T((throw 2, 1));
+ delete p;
+ } catch (int i) {
+ return i;
+ }
+ return 0;
+ }
+ static_assert(direct() == 2);
+
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+ constexpr int array() {
+ int log = 0;
+ try {
+ S *p = new S[3]{S{&log, 1}, S{&log, 2}, {&log, thrower()}};
+ delete[] p;
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(array() == 21);
+
+ /// Runtime size: the elements built by the loop are destroyed, in reverse.
+ struct U {
+ int *log;
+ int id;
+ constexpr U(int *l, int i) : log(l), id(i) {}
+ constexpr U() : log(nullptr), id(0) { throw 3; }
+ constexpr ~U() { *log = *log * 10 + id; }
+ };
+ constexpr int runtimeFiller(int n) {
+ int log = 0;
+ try {
+ U *p = new U[n]{{&log, 1}, {&log, 2}};
+ delete[] p;
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(runtimeFiller(4) == 21);
+
+ constexpr int runtimeCtor(int n) {
+ try {
+ U *p = new U[n];
+ delete[] p;
+ } catch (int i) {
+ return i;
+ }
+ return 0;
+ }
+ static_assert(runtimeCtor(3) == 3);
+
+ constexpr int noThrow(int n) {
+ int log = 0;
+ U *p = new U[n]{{&log, 1}, {&log, 2}};
+ delete[] p;
+ return log;
+ }
+ static_assert(noThrow(2) == 21);
+
+ /// The new-expression completed; only the later throw unwinds.
+ constexpr int after() {
+ T *p = nullptr;
+ try {
+ p = new T(1);
+ thrower();
+ } catch (int) {
+ delete p;
+ return 1;
+ }
+ return 0;
+ }
+ static_assert(after() == 1);
+}
+
+/// A constructor throws: the members constructed so far are destroyed, in
+/// reverse order, and the object's own destructor isn't run.
+namespace CtorThrowsMemberCleanup {
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+ constexpr int thrower() {
+ throw 1;
+ return 0;
+ }
+
+ struct C {
+ S a;
+ S b;
+ int c;
+ constexpr C(int *log) : a{log, 1}, b{log, 2}, c(thrower()) {}
+ };
+ constexpr int memberInit() {
+ int log = 0;
+ try {
+ C c(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(memberInit() == 21);
+
+ struct C2 {
+ S a;
+ S b;
+ S c;
+ constexpr C2(int *log) : a{log, 1}, b{log, 2}, c{log, thrower()} {}
+ };
+ constexpr int memberInit2() {
+ int log = 0;
+ try {
+ C2 c(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(memberInit2() == 21);
+
+ /// Default member initializers.
+ struct D {
+ int *log;
+ S a{log, 1};
+ S b{log, thrower()};
+ constexpr D(int *l) : log(l) {}
+ };
+ constexpr int implicitInit() {
+ int log = 0;
+ try {
+ D d(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(implicitInit() == 1);
+
+ /// The body throws.
+ struct CB {
+ S a;
+ S b;
+ constexpr CB(int *log) : a{log, 1}, b{log, 2} { throw 1; }
+ constexpr ~CB() { *a.log = 99; }
+ };
+ constexpr int body() {
+ int log = 0;
+ try {
+ CB c(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(body() == 21);
+
+ /// Function-try-block: members are destroyed before the handler runs.
+ struct F {
+ S a;
+ S b;
+ constexpr F(int *log) try : a{log, 1}, b{log, thrower()} {
+ } catch (...) {
+ *log += 100;
+ }
+ };
+ constexpr int fnTry() {
+ int log = 0;
+ try {
+ F f(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(fnTry() == 101);
+
+ constexpr int viaNew() {
+ int log = 0;
+ try {
+ C *p = new C(&log);
+ delete p;
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(viaNew() == 21);
+
+ /// Neither normal completion nor a return from the body destroys members.
+ struct R {
+ S a;
+ S b;
+ constexpr R(int *log, bool Ret) : a{log, 1}, b{log, 2} {
+ if (Ret)
+ return;
+ }
+ };
+ constexpr int noThrow(bool Ret) {
+ int log = 0;
+ {
+ R r(&log, Ret);
+ }
+ return log;
+ }
+ static_assert(noThrow(false) == 21);
+ static_assert(noThrow(true) == 21);
+}
+
+/// A constructor throws after a base was constructed: the base is destroyed,
+/// after the members.
+namespace CtorThrowsBaseCleanup {
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+ constexpr int thrower() {
+ throw 1;
+ return 0;
+ }
+
+ struct BB {
+ S s;
+ };
+ struct DB : BB {
+ S t;
+ constexpr DB(int *log, int) : BB{{log, 1}}, t{log, (throw 1, 2)} {}
+ };
+ constexpr int base() {
+ int log = 0;
+ try {
+ DB d(&log, 0);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(base() == 1);
+
+ struct B1 {
+ S s;
+ constexpr B1(int *log) : s{log, 1} {}
+ };
+ struct B2 {
+ S s;
+ constexpr B2(int *log) : s{log, thrower()} {}
+ };
+ struct D2 : B1, B2 {
+ constexpr D2(int *log) : B1(log), B2(log) {}
+ };
+ constexpr int secondBase() {
+ int log = 0;
+ try {
+ D2 d(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(secondBase() == 1);
+
+ struct D3 : B1 {
+ S t;
+ constexpr D3(int *log) : B1(log), t{log, 2} { throw 1; }
+ };
+ constexpr int bodyOrder() {
+ int log = 0;
+ try {
+ D3 d(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(bodyOrder() == 21);
+
+ /// The base initializer's temporary is destroyed at the end of its
+ /// full-expression, the base on the later throw.
+ struct BT {
+ S s;
+ constexpr BT(int *log, const S &) : s{log, 1} {}
+ };
+ struct DT : BT {
+ S t;
+ constexpr DT(int *log) : BT(log, S{log, 5}), t{log, thrower()} {}
+ };
+ constexpr int temp() {
+ int log = 0;
+ try {
+ DT d(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(temp() == 51);
+}
+
+/// Virtual bases are destroyed last, and only by the most-derived object's
+/// constructor.
+namespace CtorThrowsVirtualBaseCleanup {
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+ constexpr int thrower() {
+ throw 1;
+ return 0;
+ }
+
+ struct VB {
+ S s;
+ constexpr VB(int *log) : s{log, 1} {}
+ };
+ struct DV : virtual VB {
+ S t;
+ constexpr DV(int *log) : VB(log), t{log, thrower()} {}
+ };
+ constexpr int virtMember() {
+ int log = 0;
+ try {
+ DV d(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(virtMember() == 1);
+
+ /// Members, then non-virtual bases, then virtual bases.
+ struct NB {
+ S s;
+ constexpr NB(int *log) : s{log, 2} {}
+ };
+ struct DO : virtual VB, NB {
+ S t;
+ constexpr DO(int *log) : VB(log), NB(log), t{log, 3} { throw 1; }
+ };
+ constexpr int order() {
+ int log = 0;
+ try {
+ DO d(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(order() == 321);
+
+ struct L : virtual VB {
+ constexpr L(int *log) : VB(log) {}
+ };
+ struct R : virtual VB {
+ constexpr R(int *log) : VB(log) {}
+ };
+ struct Diamond : L, R {
+ S t;
+ constexpr Diamond(int *log) : VB(log), L(log), R(log), t{log, thrower()} {}
+ };
+ constexpr int diamond() {
+ int log = 0;
+ try {
+ Diamond d(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(diamond() == 1);
+
+ /// The base subobject's constructor throws; it doesn't own the virtual base.
+ struct LT : virtual VB {
+ S u;
+ constexpr LT(int *log) : VB(log), u{log, thrower()} {}
+ };
+ struct DSub : LT {
+ constexpr DSub(int *log) : VB(log), LT(log) {}
+ };
+ constexpr int subobject() {
+ int log = 0;
+ try {
+ DSub d(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(subobject() == 1);
+
+ struct VB2 {
+ S s;
+ constexpr VB2(int *log) : s{log, thrower()} {}
+ };
+ struct DV2 : virtual VB, virtual VB2 {
+ constexpr DV2(int *log) : VB(log), VB2(log) {}
+ };
+ constexpr int secondVirtual() {
+ int log = 0;
+ try {
+ DV2 d(&log);
+ } catch (...) {
+ }
+ return log;
+ }
+ static_assert(secondVirtual() == 1);
+}
+
+/// Catching as a virtual base, or as a base of one.
+namespace VirtualBases {
+ struct A { int a = 3; };
+ struct VB : A { int v = 7; constexpr virtual ~VB() {} };
+ struct VD : virtual VB { int w = 1; };
+ struct M : VD { int m = 2; };
+
+ constexpr int virtCatch() {
+ try { throw VD{}; } catch (VB &b) { return b.v; }
+ }
+ static_assert(virtCatch() == 7);
+
+ constexpr int indirect() {
+ try { throw M{}; } catch (VB &b) { return b.v; }
+ }
+ static_assert(indirect() == 7);
+
+ constexpr int baseOfVirtual() {
+ try { throw VD{}; } catch (A &x) { return x.a; }
+ }
+ static_assert(baseOfVirtual() == 3);
+
+ constexpr int byValue() {
+ try { throw VD{}; } catch (VB b) { return b.v; }
+ }
+ static_assert(byValue() == 7);
+
+ constexpr int pointer() {
+ VD d;
+ try { throw &d; } catch (VB *b) { return b->v; }
+ }
+ static_assert(pointer() == 7);
+
+ /// The pointee is a base subobject; its virtual base lives in M's layout.
+ constexpr int pointerToSubobject() {
+ M m;
+ VD *p = &m;
+ try { throw p; } catch (VB *b) { return b->v; }
+ }
+ static_assert(pointerToSubobject() == 7);
+
+ constexpr int pointerBaseOfVirtual() {
+ M m;
+ VD *p = &m;
+ try { throw p; } catch (A *x) { return x->a; }
+ }
+ static_assert(pointerBaseOfVirtual() == 3);
+}
+
+/// A destructor throws on a normal exit: everything not yet destroyed is
+/// destroyed exactly once, including an already constructed return value.
+namespace NormalExitDtorThrows {
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+ struct TD {
+ constexpr ~TD() noexcept(false) { throw 16; }
+ };
+
+ constexpr S rv(int *log) {
+ S a{log, 1};
+ TD td;
+ return S{log, 7};
+ }
+ constexpr int returnValue() {
+ int log = 0;
+ try {
+ S s = rv(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(returnValue() == 71);
+
+ constexpr S rvNoThrow(int *log) {
+ S a{log, 1};
+ return S{log, 7};
+ }
+ constexpr int returnValueNoThrow() {
+ int log = 0;
+ {
+ S s = rvNoThrow(&log);
+ }
+ return log;
+ }
+ static_assert(returnValueNoThrow() == 17);
+
+ constexpr int blockEnd() {
+ int log = 0;
+ try {
+ S o{&log, 1};
+ {
+ TD td;
+ }
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(blockEnd() == 1);
+
+ constexpr int sameScope() {
+ int log = 0;
+ try {
+ S a{&log, 1};
+ TD td;
+ S b{&log, 2};
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(sameScope() == 21);
+
+ constexpr int breakWalk() {
+ int log = 0;
+ try {
+ S o{&log, 1};
+ for (;;) {
+ S a{&log, 2};
+ {
+ TD td;
+ S b{&log, 3};
+ break;
+ }
+ }
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(breakWalk() == 321);
+
+ constexpr int returnWalkImpl(int *log) {
+ S o{log, 1};
+ {
+ TD td;
+ S b{log, 3};
+ return 0;
+ }
+ }
+ constexpr int returnWalk() {
+ int log = 0;
+ try {
+ returnWalkImpl(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(returnWalk() == 31);
+
+ constexpr int use(const TD &) { return 0; }
+ constexpr int temporary() {
+ int log = 0;
+ try {
+ S a{&log, 1};
+ use(TD{});
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(temporary() == 1);
+
+ /// The exit leaves the inner try before ~TD() throws, so the inner
+ /// handler doesn't catch it.
+ constexpr int returnFromTryImpl(int *log) {
+ S o{log, 1};
+ TD td;
+ try {
+ S b{log, 3};
+ return 0;
+ } catch (...) {
+ *log = -1;
+ }
+ return 1;
+ }
+ constexpr int returnFromTry() {
+ int log = 0;
+ try {
+ returnFromTryImpl(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(returnFromTry() == 31);
+
+ constexpr S rvFromTry(int *log) {
+ S a{log, 1};
+ TD td;
+ try {
+ return S{log, 7};
+ } catch (...) {
+ *log = -1;
+ }
+ return S{log, 0};
+ }
+ constexpr int returnValueFromTry() {
+ int log = 0;
+ try {
+ S s = rvFromTry(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(returnValueFromTry() == 71);
+
+ constexpr int breakFromTry() {
+ int log = 0;
+ try {
+ S o{&log, 1};
+ for (;;) {
+ S a{&log, 2};
+ TD td;
+ try {
+ S b{&log, 3};
+ break;
+ } catch (...) {
+ log = -1;
+ }
+ }
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(breakFromTry() == 321);
+
+ constexpr int continueFromTry() {
+ int log = 0;
+ try {
+ S o{&log, 1};
+ for (int i = 0; i < 1; ++i) {
+ TD td;
+ try {
+ S b{&log, 3};
+ continue;
+ } catch (...) {
+ log = -1;
+ }
+ }
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(continueFromTry() == 31);
+
+ /// The return leaves the handler; the exception object is destroyed first.
+ constexpr int returnFromHandlerImpl(int *log) {
+ S o{log, 1};
+ TD td;
+ try {
+ throw 1.0;
+ } catch (double) {
+ S b{log, 3};
+ return 0;
+ }
+ return 1;
+ }
+ constexpr int returnFromHandler() {
+ int log = 0;
+ try {
+ returnFromHandlerImpl(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(returnFromHandler() == 31);
+
+ /// The return leaves two try blocks at once.
+ constexpr int returnFromNestedTryImpl(int *log) {
+ S o{log, 1};
+ TD td;
+ try {
+ try {
+ S b{log, 3};
+ return 0;
+ } catch (...) {
+ *log = -1;
+ }
+ } catch (...) {
+ *log = -2;
+ }
+ return 1;
+ }
+ constexpr int returnFromNestedTry() {
+ int log = 0;
+ try {
+ returnFromNestedTryImpl(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(returnFromNestedTry() == 31);
+
+ /// A try block's own locals are destroyed inside it.
+ constexpr int tryLocal() {
+ int R = 0;
+ try {
+ TD td;
+ } catch (int) {
+ R = 7;
+ }
+ return R;
+ }
+ static_assert(tryLocal() == 7);
+
+ /// Destruction order on a return from a try: a, then td throws, then the
+ /// returned object.
+ constexpr S rvFromTryOrder(int *log) {
+ TD td;
+ S a{log, 1};
+ try {
+ return S{log, 7};
+ } catch (...) {
+ *log = -1;
+ }
+ return S{log, 0};
+ }
+ constexpr int returnValueFromTryOrder() {
+ int log = 0;
+ try {
+ S s = rvFromTryOrder(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(returnValueFromTryOrder() == 17);
+
+ /// The return stays inside the constructor's function-try-block: its
+ /// handler runs after the members are destroyed, then rethrows.
+ struct C {
+ S m;
+ constexpr C(int *log) try : m{log, 1} {
+ TD td;
+ S b{log, 3};
+ return;
+ } catch (...) {
+ *log = *log * 10 + 5;
+ }
+ };
+ constexpr int ctorTryReturn() {
+ int log = 0;
+ try {
+ C c(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(ctorTryReturn() == 315);
+
+ /// A destructor body throws: the members are still destroyed.
+ struct DT {
+ int *log;
+ S m;
+ constexpr ~DT() noexcept(false) { throw 16; }
+ };
+ constexpr int dtorThrows() {
+ int log = 0;
+ try {
+ DT d{&log, {&log, 1}};
+ } catch (int) {
+ log = log * 10 + 9;
+ }
+ return log;
+ }
+ static_assert(dtorThrows() == 19);
+
+ /// The destructor's function-try-block handler runs after the members are
+ /// destroyed. Falling off its end rethrows.
+ struct DTry {
+ int *log;
+ S m;
+ constexpr ~DTry() noexcept(false) try {
+ TD td;
+ S b{log, 3};
+ return;
+ } catch (...) {
+ }
+ };
+ constexpr int dtorTryRethrow() {
+ int log = 0;
+ try {
+ DTry d{&log, {&log, 1}};
+ } catch (int) {
+ log = log * 10 + 9;
+ }
+ return log;
+ }
+ static_assert(dtorTryRethrow() == 319);
+
+ /// A return in the handler doesn't rethrow.
+ struct DTryReturn {
+ int *log;
+ S m;
+ constexpr ~DTryReturn() try {
+ TD td;
+ S b{log, 3};
+ return;
+ } catch (...) {
+ return;
+ }
+ };
+ constexpr int dtorTryReturnInHandler() {
+ int log = 0;
+ { DTryReturn d{&log, {&log, 1}}; }
+ return log;
+ }
+ static_assert(dtorTryReturnInHandler() == 31);
+
+ /// A member destructor throws: the remaining members and bases are still
+ /// destroyed, also when the destructor body is left by a return.
+ struct B {
+ int *log;
+ constexpr ~B() { *log = *log * 10 + 4; }
+ };
+ struct TM {
+ constexpr ~TM() noexcept(false) { throw 16; }
+ };
+ struct P : B {
+ S a;
+ TM t;
+ S c;
+ constexpr P(int *log) : B{log}, a{log, 1}, c{log, 3} {}
+ constexpr ~P() noexcept(false) {}
+ };
+ constexpr int memberThrows() {
+ int log = 0;
+ try {
+ P p(&log);
+ } catch (int) {
+ log = log * 10 + 9;
+ }
+ return log;
+ }
+ static_assert(memberThrows() == 3149);
+
+ struct P2 : B {
+ S a;
+ TM t;
+ S c;
+ constexpr P2(int *log) : B{log}, a{log, 1}, c{log, 3} {}
+ constexpr ~P2() noexcept(false) {
+ S x{this->a.log, 5};
+ return;
+ }
+ };
+ constexpr int memberThrowsAfterReturn() {
+ int log = 0;
+ try {
+ P2 p(&log);
+ } catch (int) {
+ log = log * 10 + 9;
+ }
+ return log;
+ }
+ static_assert(memberThrowsAfterReturn() == 53149);
+}
+
+/// No handler of the inner try matches and it has nothing to clean up, so
+/// the enclosing try's handlers are tried.
+namespace UnmatchedNested {
+ constexpr int f() {
+ int R = 0;
+ try {
+ try {
+ throw 1;
+ } catch (float) {
+ R = -1;
+ }
+ } catch (int) {
+ R = 5;
+ }
+ return R;
+ }
+ static_assert(f() == 5);
+}
+
+/// Once the target constructor completes, an exception from the delegating
+/// constructor's body runs the destructor.
+namespace DelegatingCtor {
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+ struct B {
+ int *log;
+ constexpr ~B() { *log = *log * 10 + 4; }
+ };
+
+ struct Del : B {
+ S m;
+ constexpr Del(int *log, int) : B{log}, m{log, 1} {}
+ constexpr Del(int *log) : Del(log, 0) { throw 16; }
+ };
+ constexpr int bodyThrows() {
+ int log = 0;
+ try {
+ Del d(&log);
+ } catch (int) {
+ log = log * 10 + 9;
+ }
+ return log;
+ }
+ static_assert(bodyThrows() == 149);
+
+ /// As a base subobject; the derived member isn't constructed yet.
+ struct Derived : Del {
+ S d;
+ constexpr Derived(int *log) : Del(log), d{log, 5} {}
+ };
+ constexpr int asBase() {
+ int log = 0;
+ try {
+ Derived x(&log);
+ } catch (int) {
+ log = log * 10 + 9;
+ }
+ return log;
+ }
+ static_assert(asBase() == 149);
+
+ /// The object is destroyed before the function-try-block handler runs.
+ struct DelTry : B {
+ S m;
+ constexpr DelTry(int *log, int) : B{log}, m{log, 1} {}
+ constexpr DelTry(int *log) try : DelTry(log, 0) {
+ throw 16;
+ } catch (...) {
+ *log = *log * 10 + 6;
+ }
+ };
+ constexpr int withTry() {
+ int log = 0;
+ try {
+ DelTry x(&log);
+ } catch (int) {
+ log = log * 10 + 9;
+ }
+ return log;
+ }
+ static_assert(withTry() == 1469);
+
+ /// A return doesn't destroy the object.
+ struct DelRet : B {
+ S m;
+ constexpr DelRet(int *log, int) : B{log}, m{log, 1} {}
+ constexpr DelRet(int *log) : DelRet(log, 0) { return; }
+ };
+ constexpr int withReturn() {
+ int log = 0;
+ { DelRet x(&log); }
+ return log;
+ }
+ static_assert(withReturn() == 14);
+}
+
+/// An element destructor throws: the remaining elements are still destroyed.
+namespace ArrayDestruction {
+ struct TE {
+ int *log;
+ int id;
+ bool t;
+ constexpr ~TE() noexcept(false) {
+ *log = *log * 10 + id;
+ if (t)
+ throw 16; // #te-throw
+ }
+ };
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+
+ constexpr int local(int T) {
+ int log = 0;
+ try {
+ TE a[3] = {{&log, 1, T == 0}, {&log, 2, T == 1}, {&log, 3, T == 2}};
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(local(0) == 321);
+ static_assert(local(1) == 321);
+ static_assert(local(2) == 321);
+
+ constexpr int multiDim(int T) {
+ int log = 0;
+ try {
+ TE a[2][2] = {{{&log, 1, false}, {&log, 2, T == 0}},
+ {{&log, 3, T == 1}, {&log, 4, false}}};
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(multiDim(0) == 4321);
+ static_assert(multiDim(1) == 4321);
+
+ struct AM {
+ TE a[3];
+ constexpr ~AM() noexcept(false) {}
+ };
+ constexpr int member() {
+ int log = 0;
+ try {
+ AM m{{{&log, 1, false}, {&log, 2, true}, {&log, 3, false}}};
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(member() == 321);
+
+ constexpr void returnExitImpl(int *log) {
+ S o{log, 5};
+ TE a[2] = {{log, 1, false}, {log, 2, true}};
+ return;
+ }
+ constexpr int returnExit() {
+ int log = 0;
+ try {
+ returnExitImpl(&log);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(returnExit() == 215);
+
+ /// A second element throwing during unwinding terminates.
+ constexpr int twoThrow() {
+ int log = 0;
+ try {
+ TE a[2] = {{&log, 1, true}, {&log, 2, true}};
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(twoThrow() == 21); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+ // expected-note@#te-throw {{throw while another exception is already active}}
+ // expected-note@#te-throw {{currently active exception thrown here}}
+}
+
+namespace Misc {
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+ struct T {
+ int *log;
+ int id;
+ constexpr T(int *log, int id, bool Throw) : log(log), id(id) {
+ if (Throw)
+ throw 16;
+ }
+ constexpr ~T() { *log = *log * 10 + id; }
+ };
+ constexpr bool mayThrow(bool B) {
+ if (B)
+ throw 16;
+ return true;
+ }
+ constexpr int use(const S &, bool) { return 0; }
+
+ /// An element constructor throws: the constructed elements are destroyed.
+ constexpr int arrayCtor() {
+ int log = 0;
+ try {
+ T a[3] = {{&log, 1, false}, {&log, 2, false}, {&log, 3, true}};
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(arrayCtor() == 21);
+
+ constexpr int newArrayCtor() {
+ int log = 0;
+ try {
+ T *p = new T[3]{{&log, 1, false}, {&log, 2, false}, {&log, 3, true}};
+ delete[] p;
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(newArrayCtor() == 21);
+
+ constexpr int newCtor() {
+ int log = 0;
+ try {
+ T *p = new T{&log, 1, true};
+ delete p;
+ } catch (int) {
+ return 7;
+ }
+ return 0;
+ }
+ static_assert(newCtor() == 7);
+
+ /// Temporaries of the full-expression are destroyed.
+ constexpr int fullExpr() {
+ int log = 0;
+ try {
+ use(S{&log, 1}, mayThrow(true));
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(fullExpr() == 1);
+
+ constexpr int conditional(bool B) {
+ int log = 0;
+ try {
+ use(B ? S{&log, 1} : S{&log, 2}, mayThrow(true));
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(conditional(true) == 1);
+ static_assert(conditional(false) == 2);
+
+ constexpr int rangeFor() {
+ int log = 0;
+ try {
+ S arr[2] = {{&log, 1}, {&log, 2}};
+ for (const S &s : arr) {
+ S x{&log, 5};
+ mayThrow(s.id == 2);
+ }
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(rangeFor() == 5521);
+
+ struct E {
+ int *log;
+ constexpr E(int *log) : log(log) {}
+ constexpr E(const E &o) : log(o.log) { *log = *log * 10 + 1; }
+ constexpr ~E() { *log = *log * 10 + 2; }
+ };
+ /// The catch parameter is a copy, destroyed before the exception object.
+ constexpr int catchByValue() {
+ int log = 0;
+ try {
+ throw E{&log};
+ } catch (E e) {
+ *e.log = *e.log * 10 + 3;
+ }
+ return log;
+ }
+ static_assert(catchByValue() == 1322);
+
+ struct P {
+ S a;
+ S b;
+ };
+ constexpr int structuredBinding() {
+ int log = 0;
+ try {
+ auto [x, y] = P{{&log, 1}, {&log, 2}};
+ mayThrow(true);
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(structuredBinding() == 21);
+
+ constexpr int defArg(int x = (throw 3, 0)) { return x; }
+ constexpr int defaultArg() {
+ try {
+ return defArg();
+ } catch (int i) {
+ return i;
+ }
+ }
+ static_assert(defaultArg() == 3);
+
+ constexpr int rethrowLocal() {
+ int log = 0;
+ try {
+ try {
+ throw 1;
+ } catch (...) {
+ S h{&log, 4};
+ throw;
+ }
+ } catch (int i) {
+ log = log * 10 + i;
+ }
+ return log;
+ }
+ static_assert(rethrowLocal() == 41);
+
+ constexpr void inner(int *log) {
+ S s{log, 1};
+ throw 2;
+ }
+ constexpr void middle(int *log) {
+ S s{log, 3};
+ inner(log);
+ }
+ constexpr int twoFrames() {
+ int log = 0;
+ try {
+ middle(&log);
+ } catch (int i) {
+ log = log * 10 + i;
+ }
+ return log;
+ }
+ static_assert(twoFrames() == 132);
+}
+
+namespace Misc2 {
+ struct S {
+ int *log;
+ int id;
+ constexpr ~S() { *log = *log * 10 + id; }
+ };
+ struct TD {
+ constexpr ~TD() noexcept(false) { throw 16; }
+ };
+
+ /// The break leaves the inner try before ~TD() throws.
+ constexpr int switchBreak() {
+ int log = 0;
+ try {
+ S o{&log, 1};
+ switch (1) {
+ case 1: {
+ TD td;
+ try {
+ S b{&log, 3};
+ break;
+ } catch (...) {
+ log = -1;
+ }
+ }
+ }
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(switchBreak() == 31);
+
+ constexpr int lifetimeExtended() {
+ int log = 0;
+ try {
+ S o{&log, 1};
+ const TD &r = TD{};
+ S b{&log, 3};
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(lifetimeExtended() == 31);
+
+ constexpr int lambda() {
+ int log = 0;
+ try {
+ [&] {
+ S o{&log, 1};
+ TD td;
+ try {
+ S b{&log, 3};
+ return;
+ } catch (...) {
+ log = -1;
+ }
+ }();
+ } catch (int) {
+ }
+ return log;
+ }
+ static_assert(lambda() == 31);
+
+ /// The rethrow refers to the outer handler's exception.
+ constexpr int nestedRethrow() {
+ int r = 0;
+ try {
+ try {
+ throw 1;
+ } catch (int) {
+ try {
+ throw 2.0;
+ } catch (double) {
+ r += 10;
+ }
+ throw;
+ }
+ } catch (int i) {
+ r += i;
+ }
+ return r;
+ }
+ static_assert(nestedRethrow() == 11);
+
+ struct EB {
+ int v;
+ };
+ struct ED : EB {
+ constexpr ED() : EB{7} {}
+ };
+ constexpr int catchBase() {
+ try {
+ throw ED{};
+ } catch (const EB &e) {
+ return e.v;
+ }
+ return 0;
+ }
+ static_assert(catchBase() == 7);
+
+ constexpr int deleteThrows() {
+ struct X {
+ int *log;
+ constexpr ~X() noexcept(false) {
+ *log = 5;
+ throw 16;
+ }
+ };
+ int log = 0;
+ try {
+ X *p = new X{&log};
+ delete p;
+ } catch (int) {
+ log = log * 10 + 9;
+ }
+ return log;
+ }
+ static_assert(deleteThrows() == 59);
+
+ /// A throw in a handler leaves it, destroying its locals.
+ constexpr int throwInHandler() {
+ int log = 0;
+ try {
+ S o{&log, 1};
+ try {
+ throw 1;
+ } catch (int) {
+ S h{&log, 2};
+ throw 2;
+ }
+ } catch (int i) {
+ log = log * 10 + i;
+ }
+ return log;
+ }
+ static_assert(throwInHandler() == 212);
+
+ constexpr int loopExits() {
+ int r = 0;
+ for (int i = 0; i < 3; ++i) {
+ try {
+ if (i == 0)
+ continue;
+ if (i == 1)
+ throw i;
+ break;
+ } catch (int) {
+ r += 10;
+ }
+ }
+ return r;
+ }
+ static_assert(loopExits() == 10);
+}
+
+/// An exception escaping the copy of a catch parameter terminates.
+namespace CatchParamCopyThrows {
+ struct C {
+ constexpr C() {}
+ constexpr C(const C &) {
+ throw 2; // expected-note {{throw while another exception is already active}}
+ }
+ };
+ constexpr int f() {
+ try {
+ try {
+ throw C{}; // expected-note {{currently active exception thrown here}}
+ } catch (C c) {
+ return 1;
+ }
+ } catch (int) {
+ return 2;
+ }
+ return 3;
+ }
+ static_assert(f() == 2); // expected-error {{not an integral constant expression}} \
+ // expected-note {{in call to}}
+}
+
+/// Handlers of reference-to-pointer type bind to the converted pointer.
+/// Like GCC and Clang, this also applies to non-const references, even though
+/// [except.handle]p3 only allows conversions for const T&.
+namespace PointerRefHandlers {
+ struct X { int x = 5; };
+ struct B { int a = 1; };
+ struct D : X, B {};
+ struct VD : virtual B { int w = 1; };
+ struct M : VD {};
+ struct S { int i = 4; };
+
+ constexpr int constRef() {
+ D d;
+ try {
+ throw &d;
+ } catch (B *const &bp) {
+ return bp->a;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(constRef() == 1);
+
+ constexpr int nonConstRef() {
+ D d;
+ try {
+ throw &d;
+ } catch (B *&bp) {
+ return bp->a;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(nonConstRef() == 1);
+
+ /// The pointee is a base subobject; its virtual base lives in M's layout.
+ constexpr int virtualBase() {
+ M m;
+ VD *p = &m;
+ try {
+ throw p;
+ } catch (B *const &bp) {
+ return bp->a;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(virtualBase() == 1);
+
+ constexpr int qualification() {
+ int i = 3;
+ try {
+ throw &i;
+ } catch (const int *const &p) {
+ return *p;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(qualification() == 3);
+
+ constexpr int voidRef() {
+ int i = 0;
+ try {
+ throw &i;
+ } catch (void *&p) {
+ return p == &i;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(voidRef() == 1);
+
+ constexpr int nullPtr() {
+ try {
+ throw nullptr;
+ } catch (B *const &bp) {
+ return bp == nullptr;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(nullPtr() == 1);
+
+ constexpr int memberPtr() {
+ S s;
+ try {
+ throw &S::i;
+ } catch (int S::*const &mp) {
+ return s.*mp;
+ } catch (...) {
+ return 2;
+ }
+ }
+ static_assert(memberPtr() == 4);
+}
+
+/// A member of an anonymous struct is destroyed when a later member
+/// initializer throws.
+namespace AnonStructMemberCleanup {
+ struct S {
+ int *p;
+ constexpr S(int v) : p(new int(v)) {
+ if (v == 9) {
+ delete p;
+ throw 1;
+ }
+ }
+ constexpr ~S() { delete p; }
+ };
+
+ struct A {
+ struct {
+ S s;
+ };
+ S t;
+ constexpr A() : s(1), t(9) {}
+ };
+
+ constexpr int f() {
+ try {
+ A a;
+ } catch (int) {
+ return 1;
+ }
+ return 0;
+ }
+ static_assert(f() == 1);
+
+ /// Nested anonymous structs.
+ struct N {
+ struct {
+ struct {
+ S s;
+ };
+ };
+ S t;
+ constexpr N() : s(1), t(9) {}
+ };
+
+ constexpr int nested() {
+ try {
+ N n;
+ } catch (int) {
+ return 1;
+ }
+ return 0;
+ }
+ static_assert(nested() == 1);
+
+ /// An anonymous union before the anonymous struct.
+ struct U {
+ union {
+ int i;
+ };
+ struct {
+ S s;
+ };
+ S t;
+ constexpr U() : i(0), s(1), t(9) {}
+ };
+
+ constexpr int afterUnion() {
+ try {
+ U u;
+ } catch (int) {
+ return 1;
+ }
+ return 0;
+ }
+ static_assert(afterUnion() == 1);
+
+ /// No throw: s is destroyed exactly once, by ~A().
+ struct B {
+ struct {
+ S s;
+ };
+ S t;
+ constexpr B() : s(1), t(2) {}
+ };
+ constexpr int noThrow() {
+ B b;
+ return *b.s.p + *b.t.p;
+ }
+ static_assert(noThrow() == 3);
+}
+
+namespace CopyCtorWithCleanup {
+ struct Tmp { constexpr ~Tmp() {} };
+ struct C {
+ int v = 3;
+ constexpr C() {}
+ constexpr C(const C &o, Tmp = Tmp()) : v(o.v) {}
+ };
+ constexpr int f() { try { throw C{}; } catch (C c) { return c.v; } }
+ static_assert(f() == 3);
+}
diff --git a/clang/test/AST/ByteCode/invalid.cpp b/clang/test/AST/ByteCode/invalid.cpp
index 784fd95baf1ddb..cb1670c8c0a298 100644
--- a/clang/test/AST/ByteCode/invalid.cpp
+++ b/clang/test/AST/ByteCode/invalid.cpp
@@ -1,31 +1,5 @@
-// RUN: %clang_cc1 -triple x86_64 -fcxx-exceptions -std=c++20 -fexperimental-new-constant-interpreter -verify=expected,both %s
-// RUN: %clang_cc1 -triple x86_64 -fcxx-exceptions -std=c++20 -verify=ref,both %s
-
-namespace Throw {
-
- constexpr int ConditionalThrow(bool t) {
- if (t)
- throw 4; // both-note {{subexpression not valid in a constant expression}}
-
- return 0;
- }
-
- static_assert(ConditionalThrow(false) == 0, "");
- static_assert(ConditionalThrow(true) == 0, ""); // both-error {{not an integral constant expression}} \
- // both-note {{in call to 'ConditionalThrow(true)'}}
-
- constexpr int Throw() { // both-error {{never produces a constant expression}}
- throw 5; // both-note {{subexpression not valid in a constant expression}}
- return 0;
- }
-
- constexpr int NoSubExpr() { // both-error {{never produces a constant expression}}
- throw; // both-note 2{{subexpression not valid}}
- return 0;
- }
- static_assert(NoSubExpr() == 0, ""); // both-error {{not an integral constant expression}} \
- // both-note {{in call to}}
-}
+// RUN: %clang_cc1 -triple x86_64 -std=c++20 -fexperimental-new-constant-interpreter -verify=expected,both %s
+// RUN: %clang_cc1 -triple x86_64 -std=c++20 -verify=ref,both %s
namespace Asm {
constexpr int ConditionalAsm(bool t) {
More information about the cfe-commits
mailing list