Timm =?utf-8?q?Bäder?= <[email protected]> Message-ID: <llvm.org/llvm/llvm-project/pull/[email protected]> In-Reply-To:
https://github.com/tbaederr created https://github.com/llvm/llvm-project/pull/242995 This implements array fillers for global declarations. When a global declarations is initialized by a an `InitListExpr` of appropriate form, we only allocate as many array elements as the `InitListExpr` has initializers. We additionaly append another element as the filler slot. When reading from an array, we check if the pointer points after the allocated elements and if so, we read from the filler instead. The filler also isn't writable of course. Still broken are: - test/AST/ast-dump-APValue-array.cpp: We do not support array fillers for the second dimension of a multidimensional array, so the value for `arr_f` is: ``` |-value: Array size=3 | |-element: Array size=5 | | |-elements: Float 1.000000e+00, Float 2.000000e+00, Float 3.000000e+00, Float 4.000000e+00 | | `-element: Float 5.000000e+00 | `-filler: 2 x Array size=5 | |-elements: Float 0.000000e+00, Float 0.000000e+00, Float 0.000000e+00, Float 0.000000e+00 | `-element: Float 0.000000e+00 ``` where the current interpreter uses: ``` |-value: Array size=3 | |-element: Array size=5 | | |-elements: Float 1.000000e+00, Float 2.000000e+00, Float 3.000000e+00, Float 4.000000e+00 | | `-element: Float 5.000000e+00 | `-filler: 2 x Array size=5 | `-filler: 5 x Float 0.000000e+00 ``` - tests/AST/ast-dump-APValue-struct: Since we don't do array fillers for struct members, `S5::arr0` does not get a filler. The slowdown on c-t-t is _almost_ negligible but it's much worse in my own benchmarks, an almost 10% slowdown. That's because we're introducing an additional check (`>= Pointee->getSize()`) in every `load()` or `deref()` operation (via the new `data(Offset)`). Similarly, `getOffsetInParent()` is worse than the old `getInlineDesc()->Offset`. >From 0d5e61ef2a5c9b2ecf837419802ec0fd31bfedba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timm=20B=C3=A4der?= <[email protected]> Date: Tue, 10 Nov 2026 14:26:15 +0100 Subject: [PATCH 1/2] Test --- clang/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt index fbb4cfaf090059..d3854da59e00ce 100644 --- a/clang/CMakeLists.txt +++ b/clang/CMakeLists.txt @@ -529,7 +529,7 @@ option(CLANG_ENABLE_STATIC_ANALYZER option(CLANG_ENABLE_PROTO_FUZZER "Build Clang protobuf fuzzer." OFF) option(CLANG_USE_EXPERIMENTAL_CONST_INTERP - "Use the new experimental constant interpreter for compile-time evaluation." OFF) + "Use the new experimental constant interpreter for compile-time evaluation." ON) if (DEFINED CLANG_ENABLE_ARCMT) set(CLANG_ENABLE_OBJC_REWRITER ${CLANG_ENABLE_ARCMT}) >From 707fd692f409a96452306d5d2009478167c6ef72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timm=20B=C3=A4der?= <[email protected]> Date: Mon, 26 Oct 2026 08:52:17 +0100 Subject: [PATCH 2/2] [clang][bytecode] Support array fillers Still broken are: - test/AST/ast-dump-APValue-array.cpp --- clang/lib/AST/ByteCode/Block.h | 10 +- clang/lib/AST/ByteCode/Compiler.cpp | 66 ++++--- clang/lib/AST/ByteCode/Compiler.h | 3 + clang/lib/AST/ByteCode/Context.cpp | 14 +- clang/lib/AST/ByteCode/Descriptor.cpp | 46 +++-- clang/lib/AST/ByteCode/Descriptor.h | 49 +++++- clang/lib/AST/ByteCode/DynamicAllocator.cpp | 10 +- clang/lib/AST/ByteCode/EvaluationResult.cpp | 10 +- clang/lib/AST/ByteCode/Interp.cpp | 21 ++- .../lib/AST/ByteCode/InterpBuiltinBitCast.cpp | 13 +- clang/lib/AST/ByteCode/MemberPointer.cpp | 6 +- clang/lib/AST/ByteCode/Pointer.cpp | 51 +++--- clang/lib/AST/ByteCode/Pointer.h | 75 ++++++-- clang/lib/AST/ByteCode/Program.cpp | 100 ++++++++++- .../AST/ByteCode/array-fillers-ast-dump.cpp | 67 +++++++ .../AST/ByteCode/array-fillers-codegen.cpp | 17 ++ clang/test/AST/ByteCode/array-fillers.cpp | 163 ++++++++++++++++++ .../cxx11-initializer-aggregate.cpp | 6 +- .../test/SemaCXX/aggregate-initialization.cpp | 5 + clang/test/SemaCXX/large-array-init.cpp | 4 +- 20 files changed, 610 insertions(+), 126 deletions(-) create mode 100644 clang/test/AST/ByteCode/array-fillers-ast-dump.cpp create mode 100644 clang/test/AST/ByteCode/array-fillers-codegen.cpp create mode 100644 clang/test/AST/ByteCode/array-fillers.cpp diff --git a/clang/lib/AST/ByteCode/Block.h b/clang/lib/AST/ByteCode/Block.h index 731790ab4aebfa..52986622c686b6 100644 --- a/clang/lib/AST/ByteCode/Block.h +++ b/clang/lib/AST/ByteCode/Block.h @@ -71,12 +71,14 @@ class Block final { Block(unsigned EvalID, UnsignedOrNone DeclID, const Descriptor *Desc, BlockKind K, BlockFlags Flags = BlockFlags::empty()) - : Desc(Desc), DescSize(Desc->getAllocSize()), DeclID(DeclID), + : Desc(Desc), DescSize(Desc->getAllocSize()), + AddressableSize(Desc->getAddressableSize()), DeclID(DeclID), EvalID(EvalID), Flags(Flags), Kind(K), MDSize(getMetadataSize(K)) {} Block(unsigned EvalID, const Descriptor *Desc, BlockKind K, BlockFlags Flags = BlockFlags::empty()) - : Desc(Desc), DescSize(Desc->getAllocSize()), EvalID(EvalID), + : Desc(Desc), DescSize(Desc->getAllocSize()), + AddressableSize(Desc->getAddressableSize()), EvalID(EvalID), Flags(Flags), Kind(K), MDSize(getMetadataSize(K)) {} /// Number of bytes needed to allocate the block. @@ -121,6 +123,9 @@ class Block final { bool isAccessible() const { return Flags.V == 0; } /// Returns the size of the block, excluding metadata. unsigned getSize() const { return DescSize; } + /// Returns the size of the block as seen by pointers, excluding metadata. + /// Exceeds getSize() for arrays with a filler, see Descriptor::HasFiller. + unsigned getAddressableSize() const { return AddressableSize; } /// Returns the size of the block, including metadata. unsigned getAllocSize() const { return DescSize + MDSize; } /// Returns the declaration ID. @@ -227,6 +232,7 @@ class Block final { Pointer *Pointers = nullptr; /// Size of the data(), excluding block-level metadata. const unsigned DescSize; + const unsigned AddressableSize; /// Unique identifier of the declaration. const UnsignedOrNone DeclID = std::nullopt; const unsigned EvalID = ~0u; diff --git a/clang/lib/AST/ByteCode/Compiler.cpp b/clang/lib/AST/ByteCode/Compiler.cpp index 5044656e3afff1..bacb8b77a5b492 100644 --- a/clang/lib/AST/ByteCode/Compiler.cpp +++ b/clang/lib/AST/ByteCode/Compiler.cpp @@ -2562,12 +2562,19 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits, } } - // Expand the filler expression. - // FIXME: This should go away. + // Expand the filler expression. Global arrays with a filler only store + // one filler element. if (ArrayFiller && !isa<NoInitExpr>(ArrayFiller)) { - for (; ElementIndex != NumElems; ++ElementIndex) { + if (FillerSlotInit == E) { + // Only initialize the filler element. if (!this->visitArrayElemInit(ElementIndex, ArrayFiller, InitT)) return false; + } else { + // Expand the InitListExpr's filler to all the allocated array elements. + for (; ElementIndex != NumElems; ++ElementIndex) { + if (!this->visitArrayElemInit(ElementIndex, ArrayFiller, InitT)) + return false; + } } } @@ -3212,38 +3219,38 @@ bool Compiler<Emitter>::VisitStringLiteral(const StringLiteral *E) { unsigned ArraySize = CAT->getZExtSize(); unsigned N = std::min(ArraySize, E->getLength()); unsigned CharWidth = E->getCharByteWidth(); + assert(CharWidth == 1 || CharWidth == 2 || CharWidth == 4); + + auto initElem = [&](unsigned Index, uint32_t CodeUnit) -> bool { + if (CharWidth == 1) + return this->emitConstSint8(CodeUnit, E) && + this->emitInitElemSint8(Index, E); + else if (CharWidth == 2) + return this->emitConstUint16(CodeUnit, E) && + this->emitInitElemUint16(Index, E); + else + return this->emitConstUint32(CodeUnit, E) && + this->emitInitElemUint32(Index, E); + }; for (unsigned I = 0; I != N; ++I) { uint32_t CodeUnit = E->getCodeUnit(I); - - if (CharWidth == 1) { - this->emitConstSint8(CodeUnit, E); - this->emitInitElemSint8(I, E); - } else if (CharWidth == 2) { - this->emitConstUint16(CodeUnit, E); - this->emitInitElemUint16(I, E); - } else if (CharWidth == 4) { - this->emitConstUint32(CodeUnit, E); - this->emitInitElemUint32(I, E); - } else { - llvm_unreachable("unsupported character width"); - } + if (!initElem(I, CodeUnit)) + return false; } + // Special case: If this is initializing a global variable with an array + // filler, skip the rest of the string since it's just the filler element + // anyway. + // FIXME: For the `foo[100] = {"abc"}` case, the FillerSlotInit is the + // InitListExpr, not the StringLiteral, so this has no effect. + if (FillerSlotInit == E) + return initElem(N, 0); + // Fill up the rest of the char array with NUL bytes. for (unsigned I = N; I != ArraySize; ++I) { - if (CharWidth == 1) { - this->emitConstSint8(0, E); - this->emitInitElemSint8(I, E); - } else if (CharWidth == 2) { - this->emitConstUint16(0, E); - this->emitInitElemUint16(I, E); - } else if (CharWidth == 4) { - this->emitConstUint32(0, E); - this->emitInitElemUint32(I, E); - } else { - llvm_unreachable("unsupported character width"); - } + if (!initElem(I, 0)) + return false; } return true; @@ -5765,6 +5772,9 @@ VarCreationState Compiler<Emitter>::visitVarDecl(const VarDecl *VD, if (!this->emitStartInit(Init)) return false; + const Descriptor *Desc = P.getGlobal(*GlobalIndex)->getDescriptor(); + llvm::SaveAndRestore FillerSAR(FillerSlotInit, + Desc->hasFiller() ? Init : nullptr); if (!visitInitializer(Init)) return false; diff --git a/clang/lib/AST/ByteCode/Compiler.h b/clang/lib/AST/ByteCode/Compiler.h index 72fbef7c8b2920..e196945f4c68d4 100644 --- a/clang/lib/AST/ByteCode/Compiler.h +++ b/clang/lib/AST/ByteCode/Compiler.h @@ -499,6 +499,9 @@ class Compiler final : public ConstStmtVisitor<Compiler<Emitter>, bool>, /// variable. This is set in visitInitializer(). bool Initializing = false; const VarDecl *InitializingDecl = nullptr; + /// Root initializer of the global array being initialized, if that array + /// only stores one filler element. See Descriptor::HasFiller. + const Expr *FillerSlotInit = nullptr; llvm::SmallVector<InitLink> InitStack; bool InitStackActive = false; diff --git a/clang/lib/AST/ByteCode/Context.cpp b/clang/lib/AST/ByteCode/Context.cpp index 0a0ed5fc394c86..a6bed003cfa30d 100644 --- a/clang/lib/AST/ByteCode/Context.cpp +++ b/clang/lib/AST/ByteCode/Context.cpp @@ -262,10 +262,14 @@ bool Context::evaluateStringRepr(const EvalSettings &Settings, const char *Addr = reinterpret_cast<const char *>(Ptr.getRawAddress()); - if (Ptr.isStringPointer()) + if (Ptr.isStringPointer()) { Result.assign(Addr, Size - static_cast<unsigned>(Limited)); - else - Result.assign(Addr, Size); + } else { + // Filler elements are zero. + unsigned NumContiguous = Ptr.getNumContiguousElems(Size); + Result.assign(Addr, NumContiguous); + Result.append(Size - NumContiguous, '\0'); + } } return true; @@ -322,7 +326,7 @@ bool Context::evaluateString(const EvalSettings &Settings, const Expr *E, Result.assign(Chars, N - 1); return true; } - unsigned Length = strnlen(Chars, N); + unsigned Length = strnlen(Chars, Ptr.getNumContiguousElems(N)); // Wasn't null terminated. if (N == Length) return false; @@ -403,7 +407,7 @@ std::optional<uint64_t> Context::evaluateStrlen(const EvalSettings &Settings, unsigned N = Ptr.getNumElems(); if (Ptr.elemSize() == 1) { - unsigned Size = N - Ptr.getIndex(); + unsigned Size = Ptr.getNumContiguousElems(N) - Ptr.getIndex(); Result = strnlen(reinterpret_cast<const char *>(Ptr.getRawAddress()), Size); return Result != Size; diff --git a/clang/lib/AST/ByteCode/Descriptor.cpp b/clang/lib/AST/ByteCode/Descriptor.cpp index 67e09cb004a88a..768f72b6c39809 100644 --- a/clang/lib/AST/ByteCode/Descriptor.cpp +++ b/clang/lib/AST/ByteCode/Descriptor.cpp @@ -39,7 +39,7 @@ static void dtorArrayTy(std::byte *Ptr, const Descriptor *D) { if constexpr (needsDtor<T>()) { Ptr += sizeof(InitMapPtr); - for (unsigned I = 0, NE = D->getNumElems(); I != NE; ++I) { + for (unsigned I = 0, NE = D->getNumStoredElems(); I != NE; ++I) { reinterpret_cast<T *>(Ptr)[I].~T(); } } @@ -48,7 +48,7 @@ static void dtorArrayTy(std::byte *Ptr, const Descriptor *D) { static void ctorArrayDesc(std::byte *Ptr, bool IsConst, bool IsMutable, bool IsVolatile, bool IsActive, bool InUnion, const Descriptor *D) { - const unsigned NumElems = D->getNumElems(); + const unsigned NumElems = D->getNumStoredElems(); const unsigned ElemSize = D->ElemDesc->getAllocSize() + sizeof(InlineDescriptor); @@ -78,7 +78,7 @@ static void ctorArrayDesc(std::byte *Ptr, bool IsConst, bool IsMutable, } static void dtorArrayDesc(std::byte *Ptr, const Descriptor *D) { - const unsigned NumElems = D->getNumElems(); + const unsigned NumElems = D->getNumStoredElems(); const unsigned ElemSize = D->ElemDesc->getAllocSize() + sizeof(InlineDescriptor); @@ -272,7 +272,7 @@ static void ctorArrayTy(std::byte *Ptr, bool, bool, bool, bool, bool, if constexpr (needsCtor<T>()) { Ptr += sizeof(InitMapPtr); - for (unsigned I = 0, NE = D->getNumElems(); I < NE; ++I) { + for (unsigned I = 0, NE = D->getNumStoredElems(); I != NE; ++I) { new (&reinterpret_cast<T *>(Ptr)[I]) T(); } } @@ -301,17 +301,24 @@ Descriptor::Descriptor(DeclOrExpr D, const Type *SourceTy, PrimType Type, assert(Source && "Missing source"); } -/// Primitive arrays. +/// Primitive arrays, possibly with a filler. A filler array is not padded, so +/// every byte past its storage belongs to a filler element. Descriptor::Descriptor(DeclOrExpr D, const Type *SourceTy, PrimType Type, - size_t NumElems, bool IsConst, bool IsTemporary, - bool IsMutable, bool IsVolatile) + size_t NumElems, size_t NumStoredElems, bool IsConst, + bool IsTemporary, bool IsMutable, bool IsVolatile) : Source(D), SourceType(SourceTy), ElemSize(primSize(Type)), - Size(ElemSize * NumElems), AllocSize(align(Size) + sizeof(InitMapPtr)), - PrimT(Type), IsConst(IsConst), IsMutable(IsMutable), - IsTemporary(IsTemporary), IsVolatile(IsVolatile), IsArray(true), - CtorFn(nullptr), DtorFn(getDtorArrayPrim(Type)) { + Size(ElemSize * NumElems), + AllocSize((NumStoredElems == NumElems ? align(Size) + : ElemSize * NumStoredElems) + + sizeof(InitMapPtr)), + NumStoredElems(NumStoredElems), PrimT(Type), IsConst(IsConst), + IsMutable(IsMutable), IsTemporary(IsTemporary), IsVolatile(IsVolatile), + IsArray(true), HasFiller(NumStoredElems != NumElems), CtorFn(nullptr), + DtorFn(getDtorArrayPrim(Type)) { assert(Source && "Missing source"); assert(NumElems <= (MaxArrayElemBytes / ElemSize)); + assert(NumStoredElems <= NumElems); + assert(!HasFiller || NumStoredElems != 0); } /// Primitive unknown-size arrays. @@ -324,18 +331,23 @@ Descriptor::Descriptor(DeclOrExpr D, PrimType Type, bool IsConst, assert(Source && "Missing source"); } -/// Arrays of composite elements. +/// Arrays of composite elements, possibly with a filler. Elements are larger +/// than alignof(void *), so a filler array is never padded. Descriptor::Descriptor(DeclOrExpr D, const Type *SourceTy, - const Descriptor *Elem, unsigned NumElems, bool IsConst, - bool IsTemporary, bool IsMutable) + const Descriptor *Elem, unsigned NumElems, + unsigned NumStoredElems, bool IsConst, bool IsTemporary, + bool IsMutable) : Source(D), SourceType(SourceTy), ElemSize(Elem->getAllocSize() + sizeof(InlineDescriptor)), Size(ElemSize * NumElems), - AllocSize(std::max<size_t>(alignof(void *), Size)), ElemDesc(Elem), - IsConst(IsConst), IsMutable(IsMutable), IsTemporary(IsTemporary), - IsArray(true), CtorFn(ctorArrayDesc), + AllocSize(std::max<size_t>(alignof(void *), ElemSize * NumStoredElems)), + NumStoredElems(NumStoredElems), ElemDesc(Elem), IsConst(IsConst), + IsMutable(IsMutable), IsTemporary(IsTemporary), IsArray(true), + HasFiller(NumStoredElems != NumElems), CtorFn(ctorArrayDesc), DtorFn(Elem->DtorFn ? dtorArrayDesc : nullptr) { assert(Source && "Missing source"); + assert(NumStoredElems <= NumElems); + assert(!HasFiller || NumStoredElems != 0); } /// Unknown-size arrays of composite elements. diff --git a/clang/lib/AST/ByteCode/Descriptor.h b/clang/lib/AST/ByteCode/Descriptor.h index 564ce64e6f40c5..4426de4bf8ed72 100644 --- a/clang/lib/AST/ByteCode/Descriptor.h +++ b/clang/lib/AST/ByteCode/Descriptor.h @@ -134,6 +134,10 @@ struct Descriptor final { const unsigned Size; /// Size of the allocation (storage), in host bytes. const unsigned AllocSize; + /// Number of array elements backed by storage. + /// This is either the same as `getNumElems()`, or it is + /// less and HasFiller is true. + const unsigned NumStoredElems = 0; /// Value to denote arrays of unknown size. static constexpr unsigned UnknownSizeMark = (unsigned)-1; @@ -163,6 +167,8 @@ struct Descriptor final { const bool IsVolatile = false; /// Flag indicating if the block is an array. const bool IsArray = false; + /// Whether NumStoredElems is less than the number of elements. + const bool HasFiller = false; /// Storage management methods. const BlockCtorFn CtorFn = nullptr; @@ -174,7 +180,8 @@ struct Descriptor final { /// Allocates a descriptor for an array of primitives. Descriptor(DeclOrExpr D, const Type *SourceTy, PrimType Type, size_t NumElems, - bool IsConst, bool IsTemporary, bool IsMutable, bool IsVolatile); + size_t NumStoredElems, bool IsConst, bool IsTemporary, + bool IsMutable, bool IsVolatile); /// Allocates a descriptor for an array of primitives of unknown size. Descriptor(DeclOrExpr D, PrimType Type, bool IsConst, bool IsTemporary, @@ -182,7 +189,8 @@ struct Descriptor final { /// Allocates a descriptor for an array of composites. Descriptor(DeclOrExpr D, const Type *SourceTy, const Descriptor *Elem, - unsigned NumElems, bool IsConst, bool IsTemporary, bool IsMutable); + unsigned NumElems, unsigned NumStoredElems, bool IsConst, + bool IsTemporary, bool IsMutable); /// Allocates a descriptor for an array of composites of unknown size. Descriptor(DeclOrExpr D, const Descriptor *Elem, bool IsTemporary, @@ -249,6 +257,43 @@ struct Descriptor final { unsigned getNumElems() const { return Size == UnknownSizeMark ? 0 : (getSize() / getElemSize()); } + /// Returns the number of array elements backed by storage. + unsigned getNumStoredElems() const { return NumStoredElems; } + /// Checks if filler elements share storage, see NumStoredElems. + bool hasFiller() const { return HasFiller; } + /// Maps an element index to the index of its storage. + unsigned toStoredIndex(unsigned I) const { + if (LLVM_LIKELY(!HasFiller)) + return I; + return std::min(I, NumStoredElems - 1); + } + /// Returns the byte offset of the filler slot in the data. + unsigned getFillerOffset() const { + assert(HasFiller); + unsigned Offset = (NumStoredElems - 1) * ElemSize; + if (isPrimitiveArray()) + Offset += sizeof(InitMapPtr); + return Offset; + } + /// Maps a byte offset into the data to the offset of its storage. + uint64_t toStorageOffset(uint64_t Offset) const { + if (LLVM_LIKELY(!HasFiller)) + return Offset; + + // Offsets past the filler slot wrap around inside of it, e.g. with an + // element size of 4 and the slot at 8, offset 21 maps to 9. + uint64_t FillerOffset = getFillerOffset(); + if (Offset < FillerOffset) + return Offset; + return FillerOffset + ((Offset - FillerOffset) % ElemSize); + } + /// Returns the data size as seen by pointers. Same as getAllocSize(), + /// plus the filler elements without storage. + unsigned getAddressableSize() const { + if (LLVM_LIKELY(!HasFiller)) + return AllocSize; + return AllocSize + ((getNumElems() - NumStoredElems) * ElemSize); + } /// Checks if the descriptor is of an array of primitives. bool isPrimitiveArray() const { return IsArray && !ElemDesc; } diff --git a/clang/lib/AST/ByteCode/DynamicAllocator.cpp b/clang/lib/AST/ByteCode/DynamicAllocator.cpp index be02fbf0158df6..e946497b291ab1 100644 --- a/clang/lib/AST/ByteCode/DynamicAllocator.cpp +++ b/clang/lib/AST/ByteCode/DynamicAllocator.cpp @@ -37,10 +37,10 @@ Block *DynamicAllocator::allocate(const Expr *Source, PrimType T, Form AllocForm) { // Create a new descriptor for an array of the specified size and // element type. - const Descriptor *D = - allocateDescriptor(Source, nullptr, T, NumElements, /*IsConst=*/false, - /*IsTemporary=*/false, /*IsMutable=*/false, - /*IsVolatile=*/false); + const Descriptor *D = allocateDescriptor( + Source, nullptr, T, NumElements, NumElements, /*IsConst=*/false, + /*IsTemporary=*/false, /*IsMutable=*/false, + /*IsVolatile=*/false); return allocate(D, EvalID, AllocForm); } @@ -52,7 +52,7 @@ Block *DynamicAllocator::allocate(const Descriptor *ElementDesc, // element type. // FIXME: Pass proper element type. const Descriptor *D = allocateDescriptor( - ElementDesc->asExpr(), nullptr, ElementDesc, NumElements, + ElementDesc->asExpr(), nullptr, ElementDesc, NumElements, NumElements, /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false); return allocate(D, EvalID, AllocForm); } diff --git a/clang/lib/AST/ByteCode/EvaluationResult.cpp b/clang/lib/AST/ByteCode/EvaluationResult.cpp index d44239545e5b49..fb2ce44f36887b 100644 --- a/clang/lib/AST/ByteCode/EvaluationResult.cpp +++ b/clang/lib/AST/ByteCode/EvaluationResult.cpp @@ -53,7 +53,7 @@ static bool CheckArrayInitialized(InterpState &S, SourceLocation Loc, const Descriptor *BaseDesc = BasePtr.getFieldDesc(); assert(BaseDesc->isArray()); - size_t NumElems = BaseDesc->getNumElems(); + size_t NumElems = BaseDesc->getNumStoredElems(); if (NumElems == 0) return true; @@ -246,7 +246,7 @@ static void collectBlocks(PtrView Ptr, } if (Desc->isPrimitiveArray() && Desc->getPrimType() == PT_Ptr) { - for (unsigned I = 0; I != Desc->getNumElems(); ++I) { + for (unsigned I = 0, N = Desc->getNumStoredElems(); I != N; ++I) { Pointer ElemPointee = Ptr.elem<Pointer>(I); if (isUsefulPtr(ElemPointee) && !Blocks.contains(ElemPointee.block())) collectBlocks(ElemPointee.view(), Blocks); @@ -255,7 +255,7 @@ static void collectBlocks(PtrView Ptr, } if (Desc->isCompositeArray() && isOrHasPtr(Desc->ElemDesc)) { - for (unsigned I = 0; I != Desc->getNumElems(); ++I) { + for (unsigned I = 0, N = Desc->getNumStoredElems(); I != N; ++I) { PtrView ElemPtr = Ptr.atIndex(I).narrow(); collectBlocks(ElemPtr, Blocks); } @@ -504,7 +504,7 @@ static bool lvalFields(InterpState &S, const ASTContext &Ctx, PtrView Ptr, } if (FieldDesc->isPrimitiveArray() && FieldDesc->getPrimType() == PT_Ptr) { - for (unsigned I = 0; I != FieldDesc->getNumElems(); ++I) { + for (unsigned I = 0, N = FieldDesc->getNumStoredElems(); I != N; ++I) { Pointer Pointee = Ptr.elem<Pointer>(I); if (!Pointee.isBlockPointer() || @@ -521,7 +521,7 @@ static bool lvalFields(InterpState &S, const ASTContext &Ctx, PtrView Ptr, if (FieldDesc->ElemRecord && !FieldDesc->ElemRecord->hasPtrField()) return true; - for (unsigned I = 0; I != FieldDesc->getNumElems(); ++I) { + for (unsigned I = 0, N = FieldDesc->getNumStoredElems(); I != N; ++I) { PtrView Elem = Ptr.atIndex(I).narrow(); if (!lvalFields(S, Ctx, Elem, FieldDesc->getElemQualType(), Info, ConstexprKind, CheckedBlocks)) diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp index 0377dbe6c130fc..e39515bcc3166d 100644 --- a/clang/lib/AST/ByteCode/Interp.cpp +++ b/clang/lib/AST/ByteCode/Interp.cpp @@ -213,6 +213,17 @@ static bool CheckGlobal(InterpState &S, CodePtr OpPC, const Block *B) { return true; } +/// Filler elements share storage, so modifying one would modify all of them. +/// See Descriptor::HasFiller. +static bool CheckFiller(InterpState &S, CodePtr OpPC, PtrView Ptr) { + assert(!Ptr.isZero()); + if (!Ptr.isFillerElement()) + return true; + + S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_modify_global); + return false; +} + namespace clang { namespace interp { @@ -1110,6 +1121,8 @@ bool CheckStore(InterpState &S, CodePtr OpPC, const Pointer &Ptr, return false; if (!CheckConst(S, OpPC, P)) return false; + if (!CheckFiller(S, OpPC, P)) + return false; if (!CheckVolatile(S, OpPC, P, AK)) return false; if (!CheckMutable(S, OpPC, P, AK)) @@ -1749,7 +1762,7 @@ static bool getField(InterpState &S, CodePtr OpPC, const Pointer &Ptr, if (!Ptr.getFieldDesc()->isRecord()) return false; - if ((Ptr.getByteOffset() + Off) >= Ptr.block()->getSize()) + if ((Ptr.getByteOffset() + Off) >= Ptr.block()->getAddressableSize()) return false; S.Stk.push<Pointer>(Ptr.atField(Off)); @@ -3274,7 +3287,7 @@ static void finishGlobalRecurse(InterpState &S, PtrView Ptr) { } if (const Descriptor *D = Ptr.getFieldDesc(); D && D->isArray()) { - unsigned NumElems = D->getNumElems(); + unsigned NumElems = D->getNumStoredElems(); if (NumElems == 0) return; @@ -3293,13 +3306,13 @@ static void finishGlobalRecurse(InterpState &S, PtrView Ptr) { }); if (AllSingleWord) return; - for (unsigned I = 1; I != D->getNumElems(); ++I) { + for (unsigned I = 1; I != NumElems; ++I) { PtrView EP = Ptr.atIndex(I); copyPrimitiveMemory(S, EP, PT); } } else { assert(D->isCompositeArray()); - for (unsigned I = 0; I != D->getNumElems(); ++I) { + for (unsigned I = 0; I != NumElems; ++I) { PtrView EP = Ptr.atIndex(I).narrow(); finishGlobalRecurse(S, EP); } diff --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp index 32343e8d79b725..bd14f5e49b49c8 100644 --- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp +++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp @@ -93,12 +93,13 @@ convertToBlockPointer(const Context &Ctx, const StringPointer &SP) { assert(CharType); // Create a descriptor for the string. - std::unique_ptr<Descriptor> Desc = std::make_unique<Descriptor>( - S, S->getType().getTypePtr(), *CharType, StringLength + 1, - /*IsConst=*/true, - /*isTemporary=*/false, - /*isMutable=*/false, - /*IsVolatile=*/false); + std::unique_ptr<Descriptor> Desc = + std::make_unique<Descriptor>(S, S->getType().getTypePtr(), *CharType, + StringLength + 1, StringLength + 1, + /*IsConst=*/true, + /*isTemporary=*/false, + /*isMutable=*/false, + /*IsVolatile=*/false); // Allocate storage for the string. // The byte length does not include the null terminator. diff --git a/clang/lib/AST/ByteCode/MemberPointer.cpp b/clang/lib/AST/ByteCode/MemberPointer.cpp index b912633e8c10c4..14e42b559e58ec 100644 --- a/clang/lib/AST/ByteCode/MemberPointer.cpp +++ b/clang/lib/AST/ByteCode/MemberPointer.cpp @@ -45,7 +45,7 @@ std::optional<Pointer> MemberPointer::toPointer(const Context &Ctx) const { const Record *FieldRecord = Ctx.getRecord(FieldParent); Offset += FieldRecord->getField(FD)->Offset; - if (Offset > CastedBase.block()->getSize()) + if (Offset > CastedBase.block()->getAddressableSize()) return std::nullopt; if (const RecordDecl *BaseDecl = Base.getDeclPtr().getRecord()->getDecl(); @@ -64,10 +64,10 @@ std::optional<Pointer> MemberPointer::toPointer(const Context &Ctx) const { } assert(BaseRecord); - if (Offset > CastedBase.block()->getSize()) + if (Offset > CastedBase.block()->getAddressableSize()) return std::nullopt; - assert(Offset <= CastedBase.block()->getSize()); + assert(Offset <= CastedBase.block()->getAddressableSize()); return Pointer(const_cast<Block *>(Base.block()), Offset, Offset); } diff --git a/clang/lib/AST/ByteCode/Pointer.cpp b/clang/lib/AST/ByteCode/Pointer.cpp index a1b9fa4ca11735..ab3bf611f5d32e 100644 --- a/clang/lib/AST/ByteCode/Pointer.cpp +++ b/clang/lib/AST/ByteCode/Pointer.cpp @@ -742,7 +742,7 @@ bool PtrView::isElementInitialized(unsigned Index) const { if (!IM.hasInitMap()) return false; - return IM->isElementInitialized(Index); + return IM->isElementInitialized(Desc->toStoredIndex(Index)); } return isInitialized(); } @@ -757,7 +757,7 @@ bool Pointer::isElementAlive(unsigned Index) const { if (IM.allInitialized()) return true; - return IM->isElementAlive(Index); + return IM->isElementAlive(getFieldDesc()->toStoredIndex(Index)); } Lifetime PtrView::getLifetime() const { @@ -780,7 +780,9 @@ Lifetime PtrView::getLifetime() const { return getArray().getLifetime(); } - return IM->isElementAlive(getIndex()) ? Lifetime::Started : Lifetime::Ended; + return IM->isElementAlive(Desc->toStoredIndex(getIndex())) + ? Lifetime::Started + : Lifetime::Ended; } return getDescriptor(Offset)->LifeState; @@ -801,12 +803,14 @@ void PtrView::setLifeState(Lifetime L) const { assert(L == Lifetime::Started || L == Lifetime::Ended); InitMapPtr &IM = getInitMap(); if (!IM.hasInitMap()) - IM.setInitMap(new InitMap(Desc->getNumElems(), IM.allInitialized())); + IM.setInitMap( + new InitMap(Desc->getNumStoredElems(), IM.allInitialized())); + unsigned Index = Desc->toStoredIndex(getIndex()); if (L == Lifetime::Ended) - IM->endElementLifetime(getIndex()); + IM->endElementLifetime(Index); else if (L == Lifetime::Started) - IM->startElementLifetime(getIndex()); + IM->startElementLifetime(Index); assert(isArrayRoot() || (this->getLifetime() == L)); return; } @@ -848,13 +852,12 @@ void PtrView::initializeElement(unsigned Index) const { if (IM.allInitialized()) return; - if (!IM.hasInitMap()) { - const Descriptor *Desc = getFieldDesc(); - IM.setInitMap(new InitMap(Desc->getNumElems())); - } + const Descriptor *Desc = getFieldDesc(); + if (!IM.hasInitMap()) + IM.setInitMap(new InitMap(Desc->getNumStoredElems())); assert(IM.hasInitMap()); - if (IM->initializeElement(Index)) + if (IM->initializeElement(Desc->toStoredIndex(Index))) IM.noteAllInitialized(); } @@ -1196,20 +1199,28 @@ static bool toRValue(const Context &Ctx, QualType Ty, PtrView Ptr, APValue &R) { if (const auto *AT = Ty->getAsArrayTypeUnsafe()) { if (!FieldDesc->isArray()) return false; - const size_t NumElems = Ptr.getNumElems(); QualType ElemTy = AT->getElementType(); - R = APValue(APValue::UninitArray{}, NumElems, NumElems); - - bool Ok = true; OptPrimType ElemT = Ctx.classify(ElemTy); - for (unsigned I = 0; I != NumElems; ++I) { - APValue &Slot = R.getArrayInitializedElt(I); + auto elemToRValue = [&](unsigned I, APValue &Slot) -> bool { if (ElemT) { TYPE_SWITCH(*ElemT, Slot = Ptr.elem<T>(I).toAPValue(ASTCtx)); - } else { - Ok &= toRValue(Ctx, ElemTy, Ptr.atIndex(I).narrow(), Slot); + return true; } - } + return toRValue(Ctx, ElemTy, Ptr.atIndex(I).narrow(), Slot); + }; + + // The filler slot becomes the APValue filler. + unsigned NumElems = Ptr.getNumElems(); + size_t InitializedElems = NumElems; + if (FieldDesc->hasFiller()) + InitializedElems = FieldDesc->getNumStoredElems() - 1; + R = APValue(APValue::UninitArray{}, InitializedElems, NumElems); + + bool Ok = true; + for (unsigned I = 0; I != InitializedElems; ++I) + Ok &= elemToRValue(I, R.getArrayInitializedElt(I)); + if (R.hasArrayFiller()) + Ok &= elemToRValue(InitializedElems, R.getArrayFiller()); return Ok; } diff --git a/clang/lib/AST/ByteCode/Pointer.h b/clang/lib/AST/ByteCode/Pointer.h index 04aaacd5d96512..0620a5d46dbeb4 100644 --- a/clang/lib/AST/ByteCode/Pointer.h +++ b/clang/lib/AST/ByteCode/Pointer.h @@ -68,7 +68,7 @@ struct PtrView { } InlineDescriptor *getInlineDesc() const { - assert(Base <= Pointee->getSize()); + assert(Base <= Pointee->getAddressableSize()); assert(Base != 0); return getDescriptor(Base); } @@ -76,7 +76,30 @@ struct PtrView { InlineDescriptor *getDescriptor(unsigned Offset) const { assert(Offset != 0 && "Not a nested pointer"); assert(Offset >= sizeof(InlineDescriptor)); - return reinterpret_cast<InlineDescriptor *>(Pointee->data() + Offset) - 1; + return reinterpret_cast<InlineDescriptor *>( + data(Offset - sizeof(InlineDescriptor))); + } + + /// Returns the address of the byte at \p Off. Filler elements share the + /// storage of the filler slot, see Descriptor::HasFiller. + std::byte *data(uint64_t Off) const { + if (LLVM_UNLIKELY(Off >= Pointee->getSize())) + Off = getDeclDesc()->toStorageOffset(Off); + return Pointee->data() + Off; + } + + /// Returns the distance from Base to the parent object. Filler elements + /// share the inline descriptor of the filler slot, whose offset is only + /// correct for the slot itself. + unsigned getOffsetInParent() const { + unsigned Off = getInlineDesc()->Offset; + if (LLVM_LIKELY(Base < Pointee->getSize())) + return Off; + + // A filler element of the root array. + if (getDeclDesc()->toStorageOffset(Base) == Off) + return Base; + return Off; } const Descriptor *getFieldDesc() const { @@ -132,7 +155,7 @@ struct PtrView { return PtrView{Pointee, Base, Base}; // Step into the containing array, if inside one. - unsigned Next = Base - getInlineDesc()->Offset; + unsigned Next = Base - getOffsetInParent(); const Descriptor *Desc = (Next == 0) ? getDeclDesc() : getDescriptor(Next)->Desc; if (!Desc->IsArray) @@ -171,7 +194,7 @@ struct PtrView { return getFieldDesc()->isUnknownSizeArray(); } - bool isPastEnd() const { return Offset > Pointee->getSize(); } + bool isPastEnd() const { return Offset > Pointee->getAddressableSize(); } unsigned getOffset() const { assert(Offset != PastEndMark); @@ -248,10 +271,9 @@ struct PtrView { assert(Pointee); if (isArrayRoot()) - return *reinterpret_cast<T *>(Pointee->data() + Base + - sizeof(InitMapPtr)); + return *reinterpret_cast<T *>(data(Base + sizeof(InitMapPtr))); - return *reinterpret_cast<T *>(Pointee->data() + Offset); + return *reinterpret_cast<T *>(data(Offset)); } template <typename T> T &elem(unsigned I) const { @@ -262,13 +284,13 @@ struct PtrView { unsigned ElemByteOffset = I * getFieldDesc()->getElemSize(); unsigned ReadOffset = Base + sizeof(InitMapPtr) + ElemByteOffset; - assert(ReadOffset + sizeof(T) <= Pointee->getSize()); + assert(ReadOffset + sizeof(T) <= Pointee->getAddressableSize()); - return *reinterpret_cast<T *>(Pointee->data() + ReadOffset); + return *reinterpret_cast<T *>(data(ReadOffset)); } [[nodiscard]] PtrView getBase() const { - unsigned NewBase = Base - getInlineDesc()->Offset; + unsigned NewBase = Base - getOffsetInParent(); return PtrView{Pointee, NewBase, NewBase}; } @@ -330,7 +352,7 @@ struct PtrView { bool allElementsInitialized() const; bool isElementInitialized(unsigned Index) const; InitMapPtr &getInitMap() const { - return *reinterpret_cast<InitMapPtr *>(Pointee->data() + Base); + return *reinterpret_cast<InitMapPtr *>(data(Base)); } void initialize() const; void activate() const; @@ -340,6 +362,11 @@ struct PtrView { void startLifetime() const { setLifeState(Lifetime::Started); } void endLifetime() const { setLifeState(Lifetime::Ended); } + bool isFillerElement() const { + const Descriptor *Desc = getDeclDesc(); + return Desc->hasFiller() && Offset >= Desc->getFillerOffset(); + } + bool operator==(const PtrView &Other) const { return Other.Pointee == Pointee && Base == Other.Base && Offset == Other.Offset; @@ -1025,7 +1052,7 @@ class Pointer { Lit->getBytes().data() + (Offset * Lit->getCharByteWidth())); } assert(isBlockPointer()); - return BS.Pointee->data() + Offset; + return view().data(Offset); } /// Returns the index into an array. @@ -1066,12 +1093,28 @@ class Pointer { if (isStringPointer()) return Offset >= (Str.getLiteral()->getLength() + 1); - return !isZero() && Offset > BS.Pointee->getSize(); + return !isZero() && Offset > BS.Pointee->getAddressableSize(); } /// Checks if the pointer is an out-of-bounds element pointer. bool isElementPastEnd() const { return Offset == PtrView::PastEndMark; } + /// Returns how many of the \p N elements starting at this pointer are + /// stored contiguously. The rest are zero filler elements. + unsigned getNumContiguousElems(unsigned N) const { + if (!isBlockPointer()) + return N; + const Descriptor *Desc = getFieldDesc(); + if (!Desc->hasFiller()) + return N; + + unsigned NumStored = Desc->getNumStoredElems(); + unsigned Index = getIndex(); + if (Index >= NumStored) + return 0; + return std::min(N, NumStored - Index); + } + /// Checks if the pointer is pointing to a zero-size array. bool isZeroSizeArray() const { if (isFunctionPointer()) @@ -1112,7 +1155,7 @@ class Pointer { assert(isBlockPointer()); assert(BS.Pointee); assert(isDereferencable()); - assert(Offset + sizeof(T) <= BS.Pointee->getSize()); + assert(Offset + sizeof(T) <= BS.Pointee->getAddressableSize()); return view().deref<T>(); } @@ -1121,7 +1164,7 @@ class Pointer { if (isBlockPointer()) { assert(BS.Pointee); assert(isDereferencable()); - assert(Offset + sizeof(T) <= BS.Pointee->getSize()); + assert(Offset + sizeof(T) <= BS.Pointee->getAddressableSize()); return view().deref<T>(); } @@ -1343,7 +1386,7 @@ class Pointer { /// Returns the embedded descriptor preceding a field. InlineDescriptor *getInlineDesc() const { assert(isBlockPointer()); - assert(BS.Base <= BS.Pointee->getSize()); + assert(BS.Base <= BS.Pointee->getAddressableSize()); assert(BS.Base != 0); return getDescriptor(BS.Base); } diff --git a/clang/lib/AST/ByteCode/Program.cpp b/clang/lib/AST/ByteCode/Program.cpp index 665280814fcc60..157abe5448d048 100644 --- a/clang/lib/AST/ByteCode/Program.cpp +++ b/clang/lib/AST/ByteCode/Program.cpp @@ -13,7 +13,9 @@ #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclTemplate.h" +#include "clang/AST/ExprCXX.h" +#define DEBUG_TYPE "exprconstant" using namespace clang; using namespace clang::interp; @@ -161,7 +163,7 @@ UnsignedOrNone Program::createGlobal(DeclOrExpr D, QualType Ty, bool IsExtern, /*IsMutable=*/false, IsVolatile); else Desc = createDescriptor(D, Ty.getTypePtr(), IsConst, IsTemporary, - /*IsMutable=*/false, IsVolatile); + /*IsMutable=*/false, IsVolatile, Init); if (!Desc) return std::nullopt; @@ -336,6 +338,75 @@ Record *Program::getOrCreateRecord(const RecordDecl *RD) { return R; } +// The expression we use for the filler can only work if the computed value for +// it is independent of its position in the array. We cannot really *know* if an +// expression has this propery, so we're conservative here. +// +// To summarize, we only allow ImplicitValueInitExprs, or InitListExprs +// consisting of such. +static bool maybeDependentArrayFiller(const Expr *Filler) { + assert(Filler); + + if (isa<ImplicitValueInitExpr>(Filler)) + return false; + if (const auto *ILE = dyn_cast<InitListExpr>(Filler)) { + for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) { + if (maybeDependentArrayFiller(ILE->getInit(I))) + return true; + } + + if (const Expr *F = ILE->getArrayFiller()) + return maybeDependentArrayFiller(F); + return false; + } + return true; +} + +/// Returns how many of the \p NumElems elements of an array initialized by +/// \p Init need storage. Elements initialized by a zero filler share one +/// element, e.g. `int A[100] = {1, 2};` stores 3 elements. +/// +/// The returned value includes the filler element. +static size_t getNumStoredElems(const VarDecl *VD, size_t NumElems, + const Expr *Init) { + assert(Init); + // Only global variables. + if (!Context::shouldBeGloballyIndexed(VD)) + return NumElems; + + // char foo[1000] = "abc" + if (const auto *SL = dyn_cast<StringLiteral>(Init)) + return std::min<size_t>(SL->getLength() + 1, NumElems); + + const auto *ILE = dyn_cast<InitListExpr>(Init); + if (!ILE) + return NumElems; + + // char foo[1000] = {"abc"} + if (ILE->isStringLiteralInit()) { + // ObjCEncodeExpr can also appear here. + if (const auto *SL = dyn_cast<StringLiteral>(ILE->getInit(0))) + return std::min<size_t>(SL->getLength() + 1, NumElems); + return NumElems; + } + + // An EmbedExpr initializes more than one element. + if (llvm::any_of(ILE->inits(), [](const Expr *E) { + return isa<EmbedExpr>(E->IgnoreParenImpCasts()); + })) + return NumElems; + + assert(ILE->getType()->isArrayType()); + const Expr *Filler = ILE->getArrayFiller(); + if (!Filler) + return NumElems; + + if (maybeDependentArrayFiller(Filler)) + return NumElems; + + return std::min<size_t>(ILE->getNumInits() + 1, NumElems); +} + Descriptor *Program::createDescriptor(DeclOrExpr D, const Type *Ty, bool IsConst, bool IsTemporary, bool IsMutable, bool IsVolatile, @@ -354,14 +425,23 @@ Descriptor *Program::createDescriptor(DeclOrExpr D, const Type *Ty, // Array of well-known bounds. if (const auto *CAT = dyn_cast<ConstantArrayType>(ArrayType)) { size_t NumElems = CAT->getZExtSize(); + // The actual number of elements we will allocate storage for. + size_t NumStoredElems = NumElems; + if (Init && D.isVarDecl()) + NumStoredElems = getNumStoredElems(D.asVarDecl(), NumElems, Init); + + // This only relevant for tests/SemaCXX/large-array-init.cpp. + LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " + << (NumStoredElems - 1) << ".\n"); + if (OptPrimType T = Ctx.classify(ElemTy)) { // Arrays of primitives. unsigned ElemSize = primSize(*T); if ((Descriptor::MaxArrayElemBytes / ElemSize) < NumElems) { return nullptr; } - return allocateDescriptor(D, CAT, *T, NumElems, IsConst, IsTemporary, - IsMutable, IsVolatile); + return allocateDescriptor(D, CAT, *T, NumElems, NumStoredElems, IsConst, + IsTemporary, IsMutable, IsVolatile); } // Arrays of composites. In this case, the array is a list of pointers, // followed by the actual elements. @@ -372,8 +452,8 @@ Descriptor *Program::createDescriptor(DeclOrExpr D, const Type *Ty, unsigned ElemSize = ElemDesc->getAllocSize() + sizeof(InlineDescriptor); if (std::numeric_limits<unsigned>::max() / ElemSize <= NumElems) return nullptr; - return allocateDescriptor(D, Ty, ElemDesc, NumElems, IsConst, IsTemporary, - IsMutable); + return allocateDescriptor(D, Ty, ElemDesc, NumElems, NumStoredElems, + IsConst, IsTemporary, IsMutable); } // Array of unknown bounds - cannot be accessed and pointer arithmetic @@ -405,7 +485,7 @@ Descriptor *Program::createDescriptor(DeclOrExpr D, const Type *Ty, if (!ElemTy) return nullptr; - return allocateDescriptor(D, CT, *ElemTy, 2, IsConst, IsTemporary, + return allocateDescriptor(D, CT, *ElemTy, 2, 2, IsConst, IsTemporary, IsMutable, IsVolatile); } @@ -415,7 +495,8 @@ Descriptor *Program::createDescriptor(DeclOrExpr D, const Type *Ty, if (!ElemTy) return nullptr; - return allocateDescriptor(D, VT, *ElemTy, VT->getNumElements(), IsConst, + unsigned NumElems = VT->getNumElements(); + return allocateDescriptor(D, VT, *ElemTy, NumElems, NumElems, IsConst, IsTemporary, IsMutable, IsVolatile); } @@ -425,8 +506,9 @@ Descriptor *Program::createDescriptor(DeclOrExpr D, const Type *Ty, if (!ElemTy) return nullptr; - return allocateDescriptor(D, MT, *ElemTy, MT->getNumElementsFlattened(), - IsConst, IsTemporary, IsMutable, IsVolatile); + unsigned NumElems = MT->getNumElementsFlattened(); + return allocateDescriptor(D, MT, *ElemTy, NumElems, NumElems, IsConst, + IsTemporary, IsMutable, IsVolatile); } return nullptr; diff --git a/clang/test/AST/ByteCode/array-fillers-ast-dump.cpp b/clang/test/AST/ByteCode/array-fillers-ast-dump.cpp new file mode 100644 index 00000000000000..4e3eb5d6e23c50 --- /dev/null +++ b/clang/test/AST/ByteCode/array-fillers-ast-dump.cpp @@ -0,0 +1,67 @@ +// RUN: %clang_cc1 -std=c++20 -fexperimental-new-constant-interpreter -ast-dump %s | FileCheck %s +// RUN: %clang_cc1 -std=c++20 -ast-dump %s | FileCheck %s + +/// The APValue of arrays with a zero filler uses an array filler. + +struct S { int a; int b; }; + +constexpr int GlobalInts[100] = {1, 2}; +// CHECK: VarDecl {{.*}} GlobalInts 'const int[100]' +// CHECK-NEXT: value: Array size=100 +// CHECK-NEXT: elements: Int 1, Int 2 +// CHECK-NEXT: filler: 98 x Int 0 + +constexpr char GlobalStr[10] = "abc"; +// CHECK: VarDecl {{.*}} GlobalStr 'const char[10]' +// CHECK-NEXT: value: Array size=10 +// CHECK-NEXT: elements: Int 97, Int 98, Int 99 +// CHECK-NEXT: filler: 7 x Int 0 + +constexpr char GlobalStr2[10] = {"abc"}; +// CHECK: VarDecl {{.*}} GlobalStr2 'const char[10]' +// CHECK-NEXT: value: Array size=10 +// CHECK-NEXT: elements: Int 97, Int 98, Int 99 +// CHECK-NEXT: filler: 7 x Int 0 + +constexpr S GlobalRecords[10] = {{1, 2}}; +// CHECK: VarDecl {{.*}} GlobalRecords 'const S[10]' +// CHECK-NEXT: value: Array size=10 +// CHECK-NEXT: element: Struct +// CHECK-NEXT: fields: Int 1, Int 2 +// CHECK-NEXT: filler: 9 x Struct +// CHECK-NEXT: fields: Int 0, Int 0 + +constexpr int GlobalNoFiller[3] = {1, 2, 3}; +// CHECK: VarDecl {{.*}} GlobalNoFiller 'const int[3]' +// CHECK-NEXT: value: Array size=3 +// CHECK-NEXT: elements: Int 1, Int 2, Int 3 +// CHECK-NEXT: InitListExpr + +void func() { + constexpr int LocalInts[100] = {1, 2}; + constexpr S LocalRecords[10] = {{1, 2}}; +} +// CHECK: VarDecl {{.*}} LocalInts 'const int[100]' +// CHECK-NEXT: value: Array size=100 +// CHECK-NEXT: elements: Int 1, Int 2 +// CHECK-NEXT: filler: 98 x Int 0 + +// CHECK: VarDecl {{.*}} LocalRecords 'const S[10]' +// CHECK-NEXT: value: Array size=10 +// CHECK-NEXT: element: Struct +// CHECK-NEXT: fields: Int 1, Int 2 +// CHECK-NEXT: filler: 9 x Struct +// CHECK-NEXT: fields: Int 0, Int 0 + + +struct S2 { int a = 10; }; +constexpr S2 s2[3] = {}; +// CHECK: VarDecl {{.*}} s2 'const S2[3]' +// CHECK-NEXT: value: Array size=3 +// CHECK-NEXT: element: Struct +// CHECK-NEXT: field: Int 10 +// CHECK-NEXT: element: Struct +// CHECK-NEXT: field: Int 10 +// CHECK-NEXT: element: Struct +// CHECK-NEXT: field: Int 10 + diff --git a/clang/test/AST/ByteCode/array-fillers-codegen.cpp b/clang/test/AST/ByteCode/array-fillers-codegen.cpp new file mode 100644 index 00000000000000..5fca08d06cfe82 --- /dev/null +++ b/clang/test/AST/ByteCode/array-fillers-codegen.cpp @@ -0,0 +1,17 @@ +// RUN: %clang_cc1 -std=c++20 -triple x86_64-linux -fexperimental-new-constant-interpreter -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -std=c++20 -triple x86_64-linux -emit-llvm -o - %s | FileCheck %s + +struct S { + int a; + int b; +}; + +// CHECK: @GA = global <{ %struct.S, [99 x %struct.S] }> <{ %struct.S { i32 1, i32 2 }, [99 x %struct.S] zeroinitializer }> +S GA[100] = {{1, 2}}; +// CHECK: @GP = global ptr getelementptr (i8, ptr @GA, i64 484) +int *GP = &GA[60].b; + +constexpr int A[100] = {1, 2}; +// CHECK: @_ZL1A = internal constant <{ i32, i32, [98 x i32] }> <{ i32 1, i32 2, [98 x i32] zeroinitializer }> +const int *UseA() { return A; } + diff --git a/clang/test/AST/ByteCode/array-fillers.cpp b/clang/test/AST/ByteCode/array-fillers.cpp new file mode 100644 index 00000000000000..d7793a2b54516c --- /dev/null +++ b/clang/test/AST/ByteCode/array-fillers.cpp @@ -0,0 +1,163 @@ +// RUN: %clang_cc1 -std=c++20 -fexperimental-new-constant-interpreter -verify=expected,both %s +// RUN: %clang_cc1 -std=c++20 -verify=ref,both %s + +/// Global arrays with a zero filler only store the explicit elements and +/// one filler element. + +constexpr int A[100] = {1, 2}; +static_assert(A[0] == 1); +static_assert(A[1] == 2); +static_assert(A[2] == 0); +static_assert(A[99] == 0); +static_assert(*(A + 77) == 0); +static_assert(&A[50] - &A[0] == 50); +static_assert(&A[50] != &A[51]); +static_assert(&A[50] < &A[51]); +static_assert(A + 100 == &A[99] + 1); +static_assert(A[100] == 0); // both-error {{not an integral constant expression}} \ + // both-note {{read of dereferenced one-past-the-end pointer}} + +constexpr int sum(const int *P, int N) { + int R = 0; + for (int I = 0; I != N; ++I) + R += P[I]; + return R; +} +static_assert(sum(A, 100) == 3); + +constexpr int Z[100] = {}; +static_assert(Z[0] == 0); +static_assert(Z[99] == 0); + +constexpr char Str[100] = {'a', 'b'}; +static_assert(__builtin_strlen(Str) == 2); +static_assert(__builtin_strlen(Str + 50) == 0); + +constexpr double D[10] = {1.0}; +static_assert(D[0] == 1.0); +static_assert(D[5] == 0.0); + +constexpr int X = 0; +constexpr const int *P[10] = {&X}; +static_assert(P[0] == &X); +static_assert(P[5] == nullptr); + +struct S { + int a; + int b; +}; +constexpr S SA[100] = {{1, 2}}; +static_assert(SA[0].a == 1); +static_assert(SA[1].b == 0); +static_assert(SA[50].a == 0); +static_assert(&SA[50] - &SA[0] == 50); +static_assert(&SA[50].b == &SA[50].b); +static_assert(&SA[50].b != &SA[51].b); +constexpr int S::*MP = &S::b; +static_assert(SA[60].*MP == 0); +constexpr const S *SP = &SA[70]; +static_assert(SP->b == 0); +static_assert(SP - SA == 70); + +constexpr int M[10][10] = {{1}, {2}}; +static_assert(M[0][0] == 1); +static_assert(M[1][0] == 2); +static_assert(M[5][5] == 0); +static_assert(&M[5][5] - &M[5][0] == 5); + +struct T { + int a = 0; + S s[3]; +}; +constexpr T TA[10] = {{1, {{1, 2}}}}; +static_assert(TA[0].s[0].b == 2); +static_assert(TA[5].s[2].b == 0); + +namespace Ctor { + struct S { + int a; + constexpr S() : a(12) {} + constexpr S(int a) : a(a) {} + }; + + constexpr S foo[100] = {{13}}; + static_assert(foo[0].a == 13); + static_assert(foo[1].a == 12); + static_assert(foo[99].a == 12); +} + +namespace StringLiterals { + constexpr char s1[4] = "abc"; + static_assert(s1[0] == 'a'); + static_assert(s1[1] == 'b'); + static_assert(s1[2] == 'c'); + static_assert(s1[3] == '\0'); + + constexpr char s2[100] = "abc"; + static_assert(s2[0] == 'a'); + static_assert(s2[1] == 'b'); + static_assert(s2[2] == 'c'); + static_assert(s2[3] == '\0'); + static_assert(s2[99] == '\0'); + + constexpr char s3[100] = {"abc"}; + static_assert(s3[0] == 'a'); + static_assert(s3[1] == 'b'); + static_assert(s3[2] == 'c'); + static_assert(s3[3] == '\0'); + static_assert(s3[99] == '\0'); +} + +namespace NoFiller { + struct A { + constexpr A() : p(&p) {} + void *p; + }; + constexpr A a[10]; + static_assert(a[0].p == &a[0].p, ""); + static_assert(a[9].p == &a[9].p, ""); + static_assert(a[0].p != &a[9].p, ""); + static_assert(a[9].p != &a[0].p, ""); + + constexpr A b[10] = {}; + static_assert(b[0].p == &b[0].p, ""); + static_assert(b[9].p == &b[9].p, ""); + static_assert(b[0].p != &b[9].p, ""); + static_assert(b[9].p != &b[0].p, ""); +} + +namespace NoFiller2 { + struct A { + constexpr A() : p(&p){} + void*p; + }; + struct W { + A arr[2]; + }; + constexpr W w[10] = { {} }; + + static_assert(w[5].arr[0].p == &w[5].arr[0].p); +} + +namespace Dtor { + constexpr int F[5] = {1,2}; + + using T = int; + constexpr int test1() { // both-error {{never produces a constant expression}} + F[4].~T(); // both-note 2{{a constant expression cannot modify an object that is visible outside that expression}} + return 1; + } + static_assert(test1() == 1); // both-error {{not an integral constant expression}} \ + // both-note {{in call to}} + + struct S { + constexpr ~S() {} + }; + constexpr S FS[5] = {}; + constexpr int test2() {// both-error {{never produces a constant expression}} + FS[4].~S();// both-note 2{{a constant expression cannot modify an object that is visible outside that expression}} + return 1; + } + static_assert(test2() == 1);// both-error {{not an integral constant expression}} \ + // both-note {{in call to}} +} diff --git a/clang/test/CodeGenCXX/cxx11-initializer-aggregate.cpp b/clang/test/CodeGenCXX/cxx11-initializer-aggregate.cpp index 81ad6e0560a6e4..0cddc796b43138 100644 --- a/clang/test/CodeGenCXX/cxx11-initializer-aggregate.cpp +++ b/clang/test/CodeGenCXX/cxx11-initializer-aggregate.cpp @@ -1,5 +1,7 @@ -// RUN: %clang_cc1 -std=c++11 -emit-llvm -o - %s -triple x86_64-linux-gnu | FileCheck %s -// RUN: %clang_cc1 -std=c++17 -emit-llvm -o - %s -triple x86_64-linux-gnu | FileCheck %s +// RUN: %clang_cc1 -std=c++11 -emit-llvm -o - %s -triple x86_64-linux-gnu | FileCheck %s +// RUN: %clang_cc1 -std=c++17 -emit-llvm -o - %s -triple x86_64-linux-gnu | FileCheck %s +// RUN: %clang_cc1 -std=c++11 -emit-llvm -o - %s -triple x86_64-linux-gnu -fexperimental-new-constant-interpreter | FileCheck %s +// RUN: %clang_cc1 -std=c++17 -emit-llvm -o - %s -triple x86_64-linux-gnu -fexperimental-new-constant-interpreter | FileCheck %s struct A { int a, b; int f(); }; diff --git a/clang/test/SemaCXX/aggregate-initialization.cpp b/clang/test/SemaCXX/aggregate-initialization.cpp index a4bf0bece2da8d..8f03454a35c0cc 100644 --- a/clang/test/SemaCXX/aggregate-initialization.cpp +++ b/clang/test/SemaCXX/aggregate-initialization.cpp @@ -2,6 +2,11 @@ // RUN: %clang_cc1 -fsyntax-only -verify -std=c++14 %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++17 %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++2a %s +// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s -fexperimental-new-constant-interpreter +// RUN: %clang_cc1 -fsyntax-only -verify -std=c++14 %s -fexperimental-new-constant-interpreter +// RUN: %clang_cc1 -fsyntax-only -verify -std=c++17 %s -fexperimental-new-constant-interpreter +// RUN: %clang_cc1 -fsyntax-only -verify -std=c++2a %s -fexperimental-new-constant-interpreter + // Verify that using an initializer list for a non-aggregate looks for // constructors.. diff --git a/clang/test/SemaCXX/large-array-init.cpp b/clang/test/SemaCXX/large-array-init.cpp index ba73428059783d..94afa745b26db1 100644 --- a/clang/test/SemaCXX/large-array-init.cpp +++ b/clang/test/SemaCXX/large-array-init.cpp @@ -1,5 +1,5 @@ -// RUN: %clang_cc1 -S -o %t.ll -mllvm -debug-only=exprconstant %s 2>&1 | \ -// RUN: FileCheck %s +// RUN: %clang_cc1 -S -o %t.ll -mllvm -debug-only=exprconstant %s 2>&1 | FileCheck %s +// RUN: %clang_cc1 -S -o %t.ll -mllvm -debug-only=exprconstant -fexperimental-new-constant-interpreter %s 2>&1 | FileCheck %s // REQUIRES: asserts struct S { int i; }; _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
