[clang] [CIR] Add bytecode encodings for struct and union types (PR #247883)
Bruno Cardoso Lopes via cfe-commits
cfe-commits at lists.llvm.org
Wed Dec 2 13:47:48 PST 2026
https://github.com/bcardosolopes updated https://github.com/llvm/llvm-project/pull/247883
>From 008de390052d1f32677cb44928e67527d62c074f Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Thu, 19 Nov 2026 06:41:50 -0800
Subject: [PATCH 1/2] [CIR] Add bytecode encodings for struct and union types
Struct and union types were the last CIR types stored as their printed
text in bytecode. The printed form of a record expands every record it
reaches that has not been printed yet, so the text grows with the depth
of nesting and dominates CIR bytecode for C++.
A named record can refer to itself, so the reader creates it incomplete
and publishes it with tryStartCyclicRead (#229910) before reading its
members; a reference back to it from the members resolves to that
instance. The body is then verified and set with a new completeChecked,
which reports an invalid body, or one that conflicts with the body the
record already has, as a diagnostic instead of asserting. Anonymous
records cannot refer to themselves and are built once their members are
read.
Bytecode output for two of the CIR codegen TUs (-fclangir -emit-cir
-c on preprocessed sources, same binaries):
CIRGenModule.cpp: 7.3 GB, 4m41s, 10 GB RSS -> 4.5 MB, 19s, 1.2 GB RSS
CIRGenExprCXX.cpp: 3.9 GB, 2m11s, 6 GB RSS -> 2.0 MB, 12s, 0.9 GB RSS
For scale, their -O3 LLVM bitcode is 1.4 MB and 0.5 MB.
Assisted-by: Claude Opus 5.5
---
.../CIR/Dialect/IR/CIRDialectBytecode.td | 41 ++-
.../include/clang/CIR/Dialect/IR/CIRTypes.td | 17 +
.../lib/CIR/Dialect/IR/CIRDialectBytecode.cpp | 66 ++++
clang/lib/CIR/Dialect/IR/CIRTypes.cpp | 29 ++
clang/test/CIR/Bytecode/records.cir | 89 +++++
clang/test/CIR/Bytecode/types.cir | 5 +-
clang/unittests/CIR/CMakeLists.txt | 3 +
clang/unittests/CIR/RecordBytecodeTest.cpp | 332 ++++++++++++++++++
8 files changed, 576 insertions(+), 6 deletions(-)
create mode 100644 clang/test/CIR/Bytecode/records.cir
create mode 100644 clang/unittests/CIR/RecordBytecodeTest.cpp
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRDialectBytecode.td b/clang/include/clang/CIR/Dialect/IR/CIRDialectBytecode.td
index 326d7f4910bd6..7f160a5b7536f 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRDialectBytecode.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRDialectBytecode.td
@@ -63,6 +63,8 @@ class EnumParam<string name> :
def CtorKindParam : EnumParam<"CtorKind">;
def AssignKindParam : EnumParam<"AssignKind">;
def VectorAbiKindParam : EnumParam<"VectorAbiKind">;
+def RecordMemberKindParam :
+ WithBuilder<"$_args", EnumParam<"RecordMemberKind">>;
def CheckedInt :
WithParser<"succeeded(readCheckedInt($_reader, $_var))",
@@ -426,6 +428,40 @@ def TBAATagAttr : DialectAttribute<(attr
"[&]() { return reader.emitError(); }, context, $_args)";
}
+// Publishes a named record before its members are read; see startRecordRead.
+class RecordStart<string type, string keyArgs> :
+ WithParser<"succeeded(startRecordRead($_reader, context, name, $_var" #
+ keyArgs # "))",
+ WithBuilder<"$_args",
+ WithPrinter<"",
+ WithType<type>>>>;
+
+def StructType : DialectType<(type
+ OptionalAttribute<"mlir::StringAttr">:$name,
+ Bool:$is_class,
+ RecordStart<"cir::StructType", ", is_class">:$partial,
+ Bool:$incomplete,
+ Bool:$packed,
+ Array<Type>:$members,
+ Array<List<RecordMemberKindParam>>:$member_kinds
+)> {
+ let cBuilder = "buildStruct(reader, context, partial, name, is_class, " #
+ "incomplete, packed, members, member_kinds)";
+}
+
+def UnionType : DialectType<(type
+ OptionalAttribute<"mlir::StringAttr">:$name,
+ RecordStart<"cir::UnionType", "">:$partial,
+ Bool:$incomplete,
+ Bool:$packed,
+ Array<Type>:$members,
+ OptionalType:$padding,
+ Array<List<RecordMemberKindParam>>:$member_kinds
+)> {
+ let cBuilder = "buildUnion(reader, context, partial, name, incomplete, " #
+ "packed, members, padding, member_kinds)";
+}
+
def CIRDialectAttributes : DialectAttributes<"CIR"> {
let elems = [
OptInfoAttr,
@@ -498,8 +534,9 @@ def CIRDialectTypes : DialectTypes<"CIR"> {
CatchTokenType,
MFloat8Type,
SveCountType,
- // APPEND ONLY, as for the attributes. Types not listed here, including
- // the mutable struct and union types, keep the assembly-format fallback.
+ StructType,
+ UnionType,
+ // APPEND ONLY, as for the attributes.
];
}
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
index c576204f1058f..d44342f1f7054 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
@@ -1137,6 +1137,14 @@ def CIR_StructType : CIR_Type<"Struct", "struct", [
void complete(llvm::ArrayRef<mlir::Type> members, bool packed,
llvm::ArrayRef<cir::RecordMemberKind> memberKinds);
+ /// Like complete(), but reports an invalid body, or one that differs from
+ /// the body this struct already has, through \p emitError instead of
+ /// asserting. For bodies that come from untrusted input.
+ llvm::LogicalResult
+ completeChecked(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
+ llvm::ArrayRef<mlir::Type> members, bool packed,
+ llvm::ArrayRef<cir::RecordMemberKind> memberKinds);
+
/// Whether any member is marked pad.
bool getPadded() const;
@@ -1313,6 +1321,15 @@ def CIR_UnionType : CIR_Type<"Union", "union", [
mlir::Type padding,
llvm::ArrayRef<cir::RecordMemberKind> memberKinds);
+ /// Like complete(), but reports an invalid body, or one that differs from
+ /// the body this union already has, through \p emitError instead of
+ /// asserting. For bodies that come from untrusted input.
+ llvm::LogicalResult
+ completeChecked(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
+ llvm::ArrayRef<mlir::Type> members, bool packed,
+ mlir::Type padding,
+ llvm::ArrayRef<cir::RecordMemberKind> memberKinds);
+
uint64_t getElementOffset(const mlir::DataLayout &, unsigned) const {
return 0;
}
diff --git a/clang/lib/CIR/Dialect/IR/CIRDialectBytecode.cpp b/clang/lib/CIR/Dialect/IR/CIRDialectBytecode.cpp
index 56df18b630dc8..341e9cbe3b1ec 100644
--- a/clang/lib/CIR/Dialect/IR/CIRDialectBytecode.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRDialectBytecode.cpp
@@ -152,6 +152,72 @@ static LogicalResult readEnum(DialectBytecodeReader &reader, EnumTy &result,
return success();
}
+// A named record may refer to itself, so it is published incomplete before its
+// members are read. An anonymous one cannot, and is built after them.
+template <typename RecordTy, typename... KeyArgs>
+static LogicalResult startRecordRead(DialectBytecodeReader &reader,
+ MLIRContext *context, StringAttr name,
+ RecordTy &result, KeyArgs... keyArgs) {
+ result = {};
+ if (!name)
+ return success();
+ result = RecordTy::getChecked([&]() { return reader.emitError(); }, context,
+ name, keyArgs...);
+ if (!result)
+ return failure();
+ return reader.tryStartCyclicRead(result);
+}
+
+static LogicalResult verifyRecordEntry(DialectBytecodeReader &reader,
+ StringAttr name, bool incomplete,
+ bool hasBody) {
+ if (!incomplete)
+ return success();
+ if (!name)
+ return reader.emitError() << "anonymous records must be complete";
+ if (hasBody)
+ return reader.emitError()
+ << "incomplete record '" << name.getValue() << "' has a body";
+ return success();
+}
+
+static StructType buildStruct(DialectBytecodeReader &reader,
+ MLIRContext *context, StructType partial,
+ StringAttr name, bool isClass, bool incomplete,
+ bool packed, ArrayRef<Type> members,
+ ArrayRef<RecordMemberKind> memberKinds) {
+ auto emitError = [&]() { return reader.emitError(); };
+ if (failed(verifyRecordEntry(reader, name, incomplete,
+ packed || !members.empty() ||
+ !memberKinds.empty())))
+ return {};
+ if (!name)
+ return StructType::getChecked(emitError, context, members, packed, isClass,
+ memberKinds);
+ if (!incomplete &&
+ failed(partial.completeChecked(emitError, members, packed, memberKinds)))
+ return {};
+ return partial;
+}
+
+static UnionType buildUnion(DialectBytecodeReader &reader, MLIRContext *context,
+ UnionType partial, StringAttr name, bool incomplete,
+ bool packed, ArrayRef<Type> members, Type padding,
+ ArrayRef<RecordMemberKind> memberKinds) {
+ auto emitError = [&]() { return reader.emitError(); };
+ if (failed(verifyRecordEntry(reader, name, incomplete,
+ packed || !members.empty() || padding ||
+ !memberKinds.empty())))
+ return {};
+ if (!name)
+ return UnionType::getChecked(emitError, context, members, packed, padding,
+ memberKinds);
+ if (!incomplete && failed(partial.completeChecked(emitError, members, packed,
+ padding, memberKinds)))
+ return {};
+ return partial;
+}
+
// A varint narrowed to a fixed-width integer; out-of-range values fail
// instead of truncating.
template <typename IntTy>
diff --git a/clang/lib/CIR/Dialect/IR/CIRTypes.cpp b/clang/lib/CIR/Dialect/IR/CIRTypes.cpp
index 4f4d63de2d510..6c22dfa44c6ae 100644
--- a/clang/lib/CIR/Dialect/IR/CIRTypes.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRTypes.cpp
@@ -416,6 +416,21 @@ void StructType::complete(ArrayRef<Type> members, bool packed,
llvm_unreachable("failed to complete struct");
}
+LogicalResult
+StructType::completeChecked(function_ref<mlir::InFlightDiagnostic()> emitError,
+ ArrayRef<Type> members, bool packed,
+ ArrayRef<RecordMemberKind> memberKinds) {
+ assert(getName() && "anonymous records are complete when built");
+ if (failed(verifyInvariants(emitError, members, getName(),
+ /*incomplete=*/false, packed, memberKinds,
+ isClass())))
+ return failure();
+ if (failed(mutate(members, packed, memberKinds)))
+ return emitError() << "record '" << getName().getValue()
+ << "' redefined with a different body";
+ return success();
+}
+
bool StructType::isLayoutIdentical(const StructType &other) {
if (getImpl() == other.getImpl())
return true;
@@ -614,6 +629,20 @@ void UnionType::complete(ArrayRef<Type> members, bool packed,
llvm_unreachable("failed to complete union");
}
+LogicalResult UnionType::completeChecked(
+ function_ref<mlir::InFlightDiagnostic()> emitError, ArrayRef<Type> members,
+ bool packed, mlir::Type padding, ArrayRef<RecordMemberKind> memberKinds) {
+ assert(getName() && "anonymous records are complete when built");
+ if (failed(verifyInvariants(emitError, members, getName(),
+ /*incomplete=*/false, packed, padding,
+ memberKinds)))
+ return failure();
+ if (failed(mutate(members, packed, padding, memberKinds)))
+ return emitError() << "record '" << getName().getValue()
+ << "' redefined with a different body";
+ return success();
+}
+
mlir::Type
UnionType::getUnionStorageType(const mlir::DataLayout &dataLayout) const {
return getUnionStorageType(dataLayout, getMembers());
diff --git a/clang/test/CIR/Bytecode/records.cir b/clang/test/CIR/Bytecode/records.cir
new file mode 100644
index 0000000000000..6289d4f9d3e27
--- /dev/null
+++ b/clang/test/CIR/Bytecode/records.cir
@@ -0,0 +1,89 @@
+// RUN: cir-opt %s -verify-roundtrip | FileCheck %s
+// RUN: cir-opt %s --emit-bytecode | llvm-strings \
+// RUN: | FileCheck %s --check-prefix=NATIVE
+// RUN: cir-opt %s --emit-bytecode | cir-opt | FileCheck %s
+
+// Round-trip struct and union types, including ones that refer to themselves
+// directly or through another record.
+//
+// Check no type is string-encoded in the blob.
+// NATIVE-NOT: !cir.
+
+!s8i = !cir.int<s, 8>
+!u8i = !cir.int<u, 8>
+!s32i = !cir.int<s, 32>
+!u32i = !cir.int<u, 32>
+
+!rec_Plain = !cir.struct<"Plain" {data !s32i, data !s8i}>
+!rec_Class = !cir.struct<class "Class" {data !s32i}>
+!rec_Packed = !cir.struct<"Packed" packed {data !s8i, data !s32i}>
+!rec_Pad = !cir.struct<"Pad" {data !s8i, pad !cir.array<!u8i x 3>, data !s32i}>
+!rec_Bits = !cir.struct<"Bits"
+ {bitfield !cir.bitfield<!u32i, [#cir.bitfield_decl<!s32i, 4>]>,
+ empty !cir.bitfield<[#cir.bitfield_decl<!s32i, 0, unnamed>]>}>
+!rec_Empty = !cir.struct<"Empty" {}>
+!rec_Inc = !cir.struct<"Inc" incomplete>
+!rec_IncClass = !cir.struct<class "IncClass" incomplete>
+!rec_Anon = !cir.struct<{data !s32i, data !cir.ptr<!rec_Inc>}>
+
+// A self-reference, and two records that refer to each other.
+!rec_Node = !cir.struct<"Node" {data !s32i, data !cir.ptr<!cir.struct<"Node">>}>
+!rec_A = !cir.struct<"A" {data !cir.ptr<!cir.struct<"B"
+ {data !cir.ptr<!cir.struct<"A">>, data !s8i}>>}>
+
+// A cycle longer than the reader's nesting limit, so part of it is deferred.
+!rec_C1 = !cir.struct<"C1" {data !cir.ptr<!cir.struct<"C2" {data !cir.ptr<
+ !cir.struct<"C3" {data !cir.ptr<!cir.struct<"C4" {data !cir.ptr<
+ !cir.struct<"C5" {data !cir.ptr<!cir.struct<"C6" {data !cir.ptr<
+ !cir.struct<"C7" {data !cir.ptr<!cir.struct<"C1">>}>>}>>}>>}>>}>>}>>}>
+!rec_U = !cir.union<"U" {data !s32i, data !s8i}>
+!rec_UPad = !cir.union<"UPad" {data !s32i, data !s8i},
+ padding = {!cir.array<!u8i x 4>}>
+!rec_UInc = !cir.union<"UInc" incomplete>
+!rec_UAnon = !cir.union<{data !s32i, data !u8i}>
+!rec_UNode = !cir.union<"UNode" {data !s32i,
+ data !cir.ptr<!cir.union<"UNode">>}>
+
+// A union deep enough that it is first deferred, used by a constant whose
+// verifier needs the union to be complete.
+!rec_D3 = !cir.struct<"D3" {data !s32i}>
+!rec_D2 = !cir.struct<"D2" {data !cir.ptr<!rec_D3>}>
+!rec_D1 = !cir.struct<"D1" {data !cir.ptr<!rec_D2>}>
+!rec_UDeep = !cir.union<"UDeep" {data !s32i, data !cir.ptr<!rec_D1>}>
+
+module {
+ cir.func private @structs(!rec_Plain, !rec_Class, !rec_Packed, !rec_Pad,
+ !rec_Bits, !rec_Empty, !cir.ptr<!rec_Inc>,
+ !cir.ptr<!rec_IncClass>, !rec_Anon)
+ cir.func private @pointer(!cir.ptr<!rec_Node>)
+ cir.func private @recursive(!rec_Node, !rec_A, !rec_C1)
+ cir.func private @unions(!rec_U, !rec_UPad, !cir.ptr<!rec_UInc>, !rec_UAnon,
+ !rec_UNode)
+ cir.global external @udeep = #cir.const_record<{#cir.int<1> : !s32i}>
+ : !rec_UDeep
+}
+
+// CHECK-DAG: !rec_Plain = !cir.struct<"Plain" {data !s32i, data !s8i}>
+// CHECK-DAG: !rec_Class = !cir.struct<class "Class" {data !s32i}>
+// CHECK-DAG: !rec_Packed = !cir.struct<"Packed" packed {data !s8i, data !s32i}>
+// CHECK-DAG: !rec_Pad = !cir.struct<"Pad" {data !s8i, pad !cir.array<!u8i x 3>, data !s32i}>
+// CHECK-DAG: !rec_Bits = !cir.struct<"Bits" {bitfield !cir.bitfield<!u32i, [#cir.bitfield_decl<!s32i, 4>]>, empty !cir.bitfield<[#cir.bitfield_decl<!s32i, 0, unnamed>]>}>
+// CHECK-DAG: !rec_Empty = !cir.struct<"Empty" {}>
+// CHECK-DAG: !rec_Inc = !cir.struct<"Inc" incomplete>
+// CHECK-DAG: !rec_IncClass = !cir.struct<class "IncClass" incomplete>
+// CHECK-DAG: !rec_anon_struct = !cir.struct<{data !s32i, data !cir.ptr<!rec_Inc>}>
+// CHECK-DAG: !rec_Node = !cir.struct<"Node" {data !s32i, data !cir.ptr<!cir.struct<"Node">>}>
+// CHECK-DAG: !rec_A = !cir.struct<"A" {data !cir.ptr<!rec_B>}>
+// CHECK-DAG: !rec_B = !cir.struct<"B" {data !cir.ptr<!cir.struct<"A" {data !cir.ptr<!cir.struct<"B">>}>>, data !s8i}>
+// CHECK-DAG: !rec_C1 = !cir.struct<"C1" {data !cir.ptr<!rec_C2>}>
+// CHECK-DAG: !rec_C7 = !cir.struct<"C7" {data !cir.ptr<!cir.struct<"C1" {data !cir.ptr<!cir.struct<"C2" {data !cir.ptr<!cir.struct<"C3" {data !cir.ptr<!cir.struct<"C4" {data !cir.ptr<!cir.struct<"C5" {data !cir.ptr<!cir.struct<"C6" {data !cir.ptr<!cir.struct<"C7">>}>>}>>}>>}>>}>>}>>}>
+// CHECK-DAG: !rec_U = !cir.union<"U" {data !s32i, data !s8i}>
+// CHECK-DAG: !rec_UPad = !cir.union<"UPad" {data !s32i, data !s8i}, padding = {!cir.array<!u8i x 4>}>
+// CHECK-DAG: !rec_UInc = !cir.union<"UInc" incomplete>
+// CHECK-DAG: !rec_anon_union = !cir.union<{data !s32i, data !u8i}>
+// CHECK-DAG: !rec_UNode = !cir.union<"UNode" {data !s32i, data !cir.ptr<!cir.union<"UNode">>}>
+// CHECK: cir.func private @structs(!rec_Plain, !rec_Class, !rec_Packed, !rec_Pad, !rec_Bits, !rec_Empty, !cir.ptr<!rec_Inc>, !cir.ptr<!rec_IncClass>, !rec_anon_struct)
+// CHECK: cir.func private @pointer(!cir.ptr<!rec_Node>)
+// CHECK: cir.func private @recursive(!rec_Node, !rec_A, !rec_C1)
+// CHECK: cir.func private @unions(!rec_U, !rec_UPad, !cir.ptr<!rec_UInc>, !rec_anon_union, !rec_UNode)
+// CHECK: cir.global external @udeep = #cir.const_record<{#cir.int<1> : !s32i}> : !rec_UDeep
diff --git a/clang/test/CIR/Bytecode/types.cir b/clang/test/CIR/Bytecode/types.cir
index 0abb17897d9e5..2781c6e53b854 100644
--- a/clang/test/CIR/Bytecode/types.cir
+++ b/clang/test/CIR/Bytecode/types.cir
@@ -5,10 +5,7 @@
// Round-trip the non-recursive CIR types.
//
-// Check no type is string-encoded in the blob. Struct and union types still
-// use the fallback, so the only one is the class of the member pointers.
-// NATIVE-NOT: !cir.
-// NATIVE: !cir.struct<"S" incomplete>
+// Check no type is string-encoded in the blob.
// NATIVE-NOT: !cir.
!s8i = !cir.int<s, 8>
diff --git a/clang/unittests/CIR/CMakeLists.txt b/clang/unittests/CIR/CMakeLists.txt
index 929eefc4d061b..ebb5506d2bcb9 100644
--- a/clang/unittests/CIR/CMakeLists.txt
+++ b/clang/unittests/CIR/CMakeLists.txt
@@ -11,6 +11,7 @@ add_distinct_clang_unittest(CIRUnitTests
GetFloatingPointTypeTest.cpp
IntTypeABIAlignTest.cpp
PointerLikeTest.cpp
+ RecordBytecodeTest.cpp
RecordMemberKindTest.cpp
RecordTypeMetadataTest.cpp
RecordTypeVerifyTest.cpp
@@ -24,6 +25,8 @@ add_distinct_clang_unittest(CIRUnitTests
clangCIRFrontendAction
MLIRCIR
CIROpenACCSupport
+ MLIRBytecodeReader
+ MLIRBytecodeWriter
MLIRIR
MLIROpenACCDialect
MLIRParser
diff --git a/clang/unittests/CIR/RecordBytecodeTest.cpp b/clang/unittests/CIR/RecordBytecodeTest.cpp
new file mode 100644
index 0000000000000..5d9ecd9e837a4
--- /dev/null
+++ b/clang/unittests/CIR/RecordBytecodeTest.cpp
@@ -0,0 +1,332 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Unit tests for the diagnostics of the struct and union bytecode readers. The
+// writer never produces an invalid record, so the invalid encodings are written
+// by a writer callback.
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Bytecode/BytecodeImplementation.h"
+#include "mlir/Bytecode/BytecodeReader.h"
+#include "mlir/Bytecode/BytecodeWriter.h"
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/Diagnostics.h"
+#include "mlir/IR/MLIRContext.h"
+#include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "clang/CIR/Dialect/IR/CIRTypes.h"
+#include "llvm/Support/MemoryBufferRef.h"
+#include "gtest/gtest.h"
+
+using namespace mlir;
+using namespace cir;
+
+namespace {
+
+/// Keeps the type code, the first value a generated type writer emits.
+struct TypeCodeRecorder : DialectBytecodeWriter {
+ std::optional<uint64_t> code;
+
+ void writeVarInt(uint64_t value) override {
+ if (!code)
+ code = value;
+ }
+ void writeAttribute(Attribute) override {}
+ void writeOptionalAttribute(Attribute) override {}
+ void writeType(Type) override {}
+ void writeResourceHandle(const AsmDialectResourceHandle &) override {}
+ void writeSignedVarInt(int64_t) override {}
+ void writeAPIntWithKnownWidth(const APInt &) override {}
+ void writeAPFloatWithKnownSemantics(const APFloat &) override {}
+ void writeOwnedString(StringRef) override {}
+ void writeOwnedBlob(ArrayRef<char>) override {}
+ void writeUnownedBlob(ArrayRef<char>) override {}
+ void writeOwnedBool(bool) override {}
+ int64_t getBytecodeVersion() const override { return 0; }
+ FailureOr<const DialectVersion *>
+ getDialectVersion(StringRef) const override {
+ return failure();
+ }
+};
+
+uint64_t getTypeCode(Type type) {
+ TypeCodeRecorder recorder;
+ auto *iface =
+ type.getDialect().getRegisteredInterface<BytecodeDialectInterface>();
+ EXPECT_TRUE(succeeded(iface->writeType(type, recorder)));
+ return recorder.code.value_or(0);
+}
+
+using EncodeFn =
+ llvm::function_ref<void(MLIRContext &, DialectBytecodeWriter &)>;
+
+class RecordBytecodeTest : public ::testing::Test {
+protected:
+ static void SetUpTestSuite() {
+ MLIRContext context;
+ context.loadDialect<CIRDialect>();
+ auto name = StringAttr::get(&context, "R");
+ structCode =
+ getTypeCode(StructType::get(&context, name, /*is_class=*/false));
+ unionCode = getTypeCode(UnionType::get(&context, name));
+ }
+
+ static inline uint64_t structCode;
+ static inline uint64_t unionCode;
+
+ /// Write a module that refers to one record, encoded by `encode`.
+ static std::string write(EncodeFn encode) {
+ MLIRContext context;
+ context.loadDialect<CIRDialect>();
+ auto placeholder = StructType::get(
+ &context, StringAttr::get(&context, "placeholder"), /*is_class=*/false);
+ OwningOpRef<ModuleOp> module = ModuleOp::create(UnknownLoc::get(&context));
+ (*module)->setAttr("test.record", TypeAttr::get(placeholder));
+
+ BytecodeWriterConfig config;
+ config.attachTypeCallback(
+ [&](Type type, std::optional<StringRef> &dialectGroupName,
+ DialectBytecodeWriter &writer) -> LogicalResult {
+ if (type != placeholder)
+ return failure();
+ dialectGroupName = "cir";
+ encode(context, writer);
+ return success();
+ });
+ std::string bytecode;
+ llvm::raw_string_ostream os(bytecode);
+ EXPECT_TRUE(succeeded(writeBytecodeToFile(*module, os, config)));
+ return bytecode;
+ }
+
+ /// Read `bytecode`, after `setup` has prepared the context, and return the
+ /// diagnostics.
+ static std::string read(
+ llvm::StringRef bytecode,
+ llvm::function_ref<void(MLIRContext &)> setup = [](MLIRContext &) {}) {
+ MLIRContext context;
+ context.loadDialect<CIRDialect>();
+ setup(context);
+ std::string diagnostics;
+ ScopedDiagnosticHandler handler(&context, [&](Diagnostic &diag) {
+ diagnostics += diag.str() + "\n";
+ return success();
+ });
+ Block block;
+ ParserConfig config(&context);
+ EXPECT_TRUE(failed(readBytecodeFile(
+ llvm::MemoryBufferRef(bytecode, "records"), &block, config)));
+ return diagnostics;
+ }
+
+ static IntType getS32(MLIRContext &context) {
+ return IntType::get(&context, 32, /*isSigned=*/true);
+ }
+
+ /// A null `name` writes an anonymous struct.
+ static void writeStruct(DialectBytecodeWriter &writer, StringAttr name,
+ bool incomplete, ArrayRef<Type> members,
+ ArrayRef<uint64_t> memberKinds, bool packed = false) {
+ writer.writeVarInt(structCode);
+ writer.writeOptionalAttribute(name);
+ writer.writeOwnedBool(/*is_class=*/false);
+ writer.writeOwnedBool(incomplete);
+ writer.writeOwnedBool(packed);
+ writer.writeTypes(members);
+ writer.writeList(memberKinds,
+ [&](uint64_t kind) { writer.writeVarInt(kind); });
+ }
+
+ /// A null `name` writes an anonymous union.
+ static void writeUnion(DialectBytecodeWriter &writer, StringAttr name,
+ bool incomplete, ArrayRef<Type> members, Type padding,
+ ArrayRef<uint64_t> memberKinds) {
+ writer.writeVarInt(unionCode);
+ writer.writeOptionalAttribute(name);
+ writer.writeOwnedBool(incomplete);
+ writer.writeOwnedBool(/*packed=*/false);
+ writer.writeTypes(members);
+ writer.writeOwnedBool(static_cast<bool>(padding));
+ if (padding)
+ writer.writeType(padding);
+ writer.writeList(memberKinds,
+ [&](uint64_t kind) { writer.writeVarInt(kind); });
+ }
+
+ static constexpr uint64_t data =
+ static_cast<uint64_t>(RecordMemberKind::Data);
+ static constexpr uint64_t pad = static_cast<uint64_t>(RecordMemberKind::Pad);
+};
+
+TEST_F(RecordBytecodeTest, EmptyName) {
+ std::string diags =
+ read(write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr::get(&context, ""), /*incomplete=*/true,
+ {}, {});
+ }));
+ EXPECT_NE(diags.find("identified records cannot have an empty name"),
+ std::string::npos)
+ << diags;
+}
+
+TEST_F(RecordBytecodeTest, IncompleteAnonymous) {
+ std::string diags =
+ read(write([](MLIRContext &, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr(), /*incomplete=*/true, {}, {});
+ }));
+ EXPECT_NE(diags.find("anonymous records must be complete"), std::string::npos)
+ << diags;
+}
+
+// Each part of a body: members, packing, member kinds, and union padding.
+TEST_F(RecordBytecodeTest, IncompleteWithBody) {
+ auto expectRejected = [](EncodeFn encode, llvm::StringRef name) {
+ std::string diags = read(write(encode));
+ EXPECT_NE(diags.find(("incomplete record '" + name + "' has a body").str()),
+ std::string::npos)
+ << diags;
+ };
+ expectRejected(
+ [](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr::get(&context, "R"), /*incomplete=*/true,
+ {getS32(context)}, {data});
+ },
+ "R");
+ expectRejected(
+ [](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr::get(&context, "R"), /*incomplete=*/true,
+ {}, {}, /*packed=*/true);
+ },
+ "R");
+ expectRejected(
+ [](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr::get(&context, "R"), /*incomplete=*/true,
+ {}, {data});
+ },
+ "R");
+ expectRejected(
+ [](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeUnion(writer, StringAttr::get(&context, "U"), /*incomplete=*/true,
+ {}, IntType::get(&context, 8, /*isSigned=*/false), {});
+ },
+ "U");
+}
+
+TEST_F(RecordBytecodeTest, InvalidMemberKind) {
+ std::string diags =
+ read(write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr::get(&context, "R"),
+ /*incomplete=*/false, {getS32(context)}, {99});
+ }));
+ EXPECT_NE(diags.find("invalid RecordMemberKind value 99"), std::string::npos)
+ << diags;
+}
+
+TEST_F(RecordBytecodeTest, AnonymousMemberKindCount) {
+ std::string diags =
+ read(write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr(), /*incomplete=*/false,
+ {getS32(context)}, {});
+ }));
+ EXPECT_NE(diags.find("expected 1 member kinds, got 0"), std::string::npos)
+ << diags;
+}
+
+TEST_F(RecordBytecodeTest, NamedVoidMember) {
+ std::string diags =
+ read(write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr::get(&context, "R"),
+ /*incomplete=*/false, {VoidType::get(&context)}, {data});
+ }));
+ EXPECT_NE(diags.find("record member at index 0 cannot be void"),
+ std::string::npos)
+ << diags;
+}
+
+TEST_F(RecordBytecodeTest, NonCIRMember) {
+ std::string diags =
+ read(write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr::get(&context, "R"),
+ /*incomplete=*/false, {IntegerType::get(&context, 32)},
+ {data});
+ }));
+ EXPECT_NE(diags.find("record member at index 0 must be a CIR type"),
+ std::string::npos)
+ << diags;
+}
+
+TEST_F(RecordBytecodeTest, UnionPadKind) {
+ std::string diags =
+ read(write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeUnion(writer, StringAttr::get(&context, "U"), /*incomplete=*/false,
+ {getS32(context)}, Type(), {pad});
+ }));
+ EXPECT_NE(diags.find("a union member cannot be marked pad"),
+ std::string::npos)
+ << diags;
+}
+
+TEST_F(RecordBytecodeTest, UnionPadding) {
+ std::string diags =
+ read(write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeUnion(writer, StringAttr::get(&context, "U"), /*incomplete=*/false,
+ {getS32(context)}, getS32(context), {data});
+ }));
+ EXPECT_NE(diags.find("union padding must be !u8i or an array of !u8i"),
+ std::string::npos)
+ << diags;
+}
+
+TEST_F(RecordBytecodeTest, AnonymousUnionPadKind) {
+ std::string diags =
+ read(write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeUnion(writer, StringAttr(), /*incomplete=*/false,
+ {getS32(context)}, Type(), {pad});
+ }));
+ EXPECT_NE(diags.find("a union member cannot be marked pad"),
+ std::string::npos)
+ << diags;
+}
+
+// A context that already holds the record with another body.
+TEST_F(RecordBytecodeTest, StructRedefined) {
+ std::string diags =
+ read(write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeStruct(writer, StringAttr::get(&context, "R"),
+ /*incomplete=*/false, {getS32(context)}, {data});
+ }),
+ [](MLIRContext &context) {
+ auto existing = StructType::get(
+ &context, StringAttr::get(&context, "R"), /*is_class=*/false);
+ existing.complete({IntType::get(&context, 8, /*isSigned=*/true)},
+ /*packed=*/false, {RecordMemberKind::Data});
+ });
+ EXPECT_NE(diags.find("record 'R' redefined with a different body"),
+ std::string::npos)
+ << diags;
+}
+
+TEST_F(RecordBytecodeTest, UnionRedefined) {
+ std::string diags = read(
+ write([](MLIRContext &context, DialectBytecodeWriter &writer) {
+ writeUnion(writer, StringAttr::get(&context, "U"), /*incomplete=*/false,
+ {getS32(context)}, Type(), {data});
+ }),
+ [](MLIRContext &context) {
+ auto existing =
+ UnionType::get(&context, StringAttr::get(&context, "U"));
+ existing.complete({IntType::get(&context, 8, /*isSigned=*/true)},
+ /*packed=*/false, /*padding=*/Type(),
+ {RecordMemberKind::Data});
+ });
+ EXPECT_NE(diags.find("record 'U' redefined with a different body"),
+ std::string::npos)
+ << diags;
+}
+
+} // namespace
>From aa0b2b024c986a6a3ab08c1fa9ac384784fd480d Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 2 Dec 2026 12:06:30 -0800
Subject: [PATCH 2/2] [CIR] Share record completion between complete and
completeChecked
completeRecord does the verification and mutation for both record kinds,
and complete() delegates to completeChecked(). Unit test nits: HasSubstr,
and a check that a type writer starts with the type code.
---
.../include/clang/CIR/Dialect/IR/CIRTypes.td | 18 ++++
clang/lib/CIR/Dialect/IR/CIRTypes.cpp | 78 ++++++++++-------
clang/unittests/CIR/RecordBytecodeTest.cpp | 85 +++++++++----------
3 files changed, 103 insertions(+), 78 deletions(-)
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
index d44342f1f7054..df4a9e26ecab4 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
@@ -1145,6 +1145,15 @@ def CIR_StructType : CIR_Type<"Struct", "struct", [
llvm::ArrayRef<mlir::Type> members, bool packed,
llvm::ArrayRef<cir::RecordMemberKind> memberKinds);
+ // The completion shared with the other record kind needs mutate().
+ template <typename RecordTy>
+ friend llvm::LogicalResult
+ completeRecord(RecordTy record,
+ llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
+ llvm::ArrayRef<mlir::Type> members, bool packed,
+ mlir::Type padding,
+ llvm::ArrayRef<cir::RecordMemberKind> memberKinds);
+
/// Whether any member is marked pad.
bool getPadded() const;
@@ -1330,6 +1339,15 @@ def CIR_UnionType : CIR_Type<"Union", "union", [
mlir::Type padding,
llvm::ArrayRef<cir::RecordMemberKind> memberKinds);
+ // The completion shared with the other record kind needs mutate().
+ template <typename RecordTy>
+ friend llvm::LogicalResult
+ completeRecord(RecordTy record,
+ llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
+ llvm::ArrayRef<mlir::Type> members, bool packed,
+ mlir::Type padding,
+ llvm::ArrayRef<cir::RecordMemberKind> memberKinds);
+
uint64_t getElementOffset(const mlir::DataLayout &, unsigned) const {
return 0;
}
diff --git a/clang/lib/CIR/Dialect/IR/CIRTypes.cpp b/clang/lib/CIR/Dialect/IR/CIRTypes.cpp
index 6c22dfa44c6ae..ddfc4741c397d 100644
--- a/clang/lib/CIR/Dialect/IR/CIRTypes.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRTypes.cpp
@@ -403,32 +403,56 @@ void StructType::removeABIConversionNamePrefix() {
recordName.getType());
}
+namespace cir {
+/// Completes a named struct or union. \p padding is only used by unions.
+template <typename RecordTy>
+LogicalResult completeRecord(RecordTy record,
+ function_ref<mlir::InFlightDiagnostic()> emitError,
+ ArrayRef<Type> members, bool packed, Type padding,
+ ArrayRef<RecordMemberKind> memberKinds) {
+ mlir::StringAttr name = record.getName();
+ assert(name && "anonymous records are complete when built");
+ // mutate() bypasses the verifier, so check what get() would have checked.
+ LogicalResult mutated = failure();
+ if constexpr (std::is_same_v<RecordTy, StructType>) {
+ assert(!padding && "structs have no padding member");
+ if (failed(StructType::verifyInvariants(emitError, members, name,
+ /*incomplete=*/false, packed,
+ memberKinds, record.isClass())))
+ return failure();
+ mutated = record.mutate(members, packed, memberKinds);
+ } else if constexpr (std::is_same_v<RecordTy, UnionType>) {
+ if (failed(UnionType::verifyInvariants(emitError, members, name,
+ /*incomplete=*/false, packed,
+ padding, memberKinds)))
+ return failure();
+ mutated = record.mutate(members, packed, padding, memberKinds);
+ } else {
+ static_assert(!std::is_same_v<RecordTy, RecordTy>,
+ "completeRecord expects a StructType or a UnionType");
+ }
+ if (failed(mutated))
+ return emitError() << "record '" << name.getValue()
+ << "' redefined with a different body";
+ return success();
+}
+} // namespace cir
+
void StructType::complete(ArrayRef<Type> members, bool packed,
ArrayRef<RecordMemberKind> memberKinds) {
assert(!cir::MissingFeatures::astRecordDeclAttr());
- // mutate() bypasses the verifier, so check what get() would have checked.
- assert(
- succeeded(verifyInvariants(
+ if (failed(completeChecked(
mlir::detail::getDefaultDiagnosticEmitFn(getContext()), members,
- getName(), /*incomplete=*/false, packed, memberKinds, isClass())) &&
- "invalid struct completion");
- if (mutate(members, packed, memberKinds).failed())
- llvm_unreachable("failed to complete struct");
+ packed, memberKinds)))
+ llvm_unreachable("invalid struct completion");
}
LogicalResult
StructType::completeChecked(function_ref<mlir::InFlightDiagnostic()> emitError,
ArrayRef<Type> members, bool packed,
ArrayRef<RecordMemberKind> memberKinds) {
- assert(getName() && "anonymous records are complete when built");
- if (failed(verifyInvariants(emitError, members, getName(),
- /*incomplete=*/false, packed, memberKinds,
- isClass())))
- return failure();
- if (failed(mutate(members, packed, memberKinds)))
- return emitError() << "record '" << getName().getValue()
- << "' redefined with a different body";
- return success();
+ return completeRecord(*this, emitError, members, packed, /*padding=*/Type(),
+ memberKinds);
}
bool StructType::isLayoutIdentical(const StructType &other) {
@@ -620,27 +644,17 @@ void UnionType::complete(ArrayRef<Type> members, bool packed,
mlir::Type padding,
ArrayRef<RecordMemberKind> memberKinds) {
assert(!cir::MissingFeatures::astRecordDeclAttr());
- // mutate() bypasses the verifier, so check what get() would have checked.
- assert(succeeded(verifyInvariants(
- mlir::detail::getDefaultDiagnosticEmitFn(getContext()), members,
- getName(), /*incomplete=*/false, packed, padding, memberKinds)) &&
- "invalid union completion");
- if (mutate(members, packed, padding, memberKinds).failed())
- llvm_unreachable("failed to complete union");
+ if (failed(completeChecked(
+ mlir::detail::getDefaultDiagnosticEmitFn(getContext()), members,
+ packed, padding, memberKinds)))
+ llvm_unreachable("invalid union completion");
}
LogicalResult UnionType::completeChecked(
function_ref<mlir::InFlightDiagnostic()> emitError, ArrayRef<Type> members,
bool packed, mlir::Type padding, ArrayRef<RecordMemberKind> memberKinds) {
- assert(getName() && "anonymous records are complete when built");
- if (failed(verifyInvariants(emitError, members, getName(),
- /*incomplete=*/false, packed, padding,
- memberKinds)))
- return failure();
- if (failed(mutate(members, packed, padding, memberKinds)))
- return emitError() << "record '" << getName().getValue()
- << "' redefined with a different body";
- return success();
+ return completeRecord(*this, emitError, members, packed, padding,
+ memberKinds);
}
mlir::Type
diff --git a/clang/unittests/CIR/RecordBytecodeTest.cpp b/clang/unittests/CIR/RecordBytecodeTest.cpp
index 5d9ecd9e837a4..ddf52a7c4c738 100644
--- a/clang/unittests/CIR/RecordBytecodeTest.cpp
+++ b/clang/unittests/CIR/RecordBytecodeTest.cpp
@@ -21,32 +21,39 @@
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "llvm/Support/MemoryBufferRef.h"
+#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace mlir;
using namespace cir;
+using ::testing::HasSubstr;
namespace {
-/// Keeps the type code, the first value a generated type writer emits.
+/// Keeps the first value written, if it is a varint.
struct TypeCodeRecorder : DialectBytecodeWriter {
std::optional<uint64_t> code;
+ bool wroteFirst = false;
void writeVarInt(uint64_t value) override {
- if (!code)
+ if (!wroteFirst)
code = value;
+ wroteFirst = true;
}
- void writeAttribute(Attribute) override {}
- void writeOptionalAttribute(Attribute) override {}
- void writeType(Type) override {}
- void writeResourceHandle(const AsmDialectResourceHandle &) override {}
- void writeSignedVarInt(int64_t) override {}
- void writeAPIntWithKnownWidth(const APInt &) override {}
- void writeAPFloatWithKnownSemantics(const APFloat &) override {}
- void writeOwnedString(StringRef) override {}
- void writeOwnedBlob(ArrayRef<char>) override {}
- void writeUnownedBlob(ArrayRef<char>) override {}
- void writeOwnedBool(bool) override {}
+ void write() { wroteFirst = true; }
+ void writeAttribute(Attribute) override { write(); }
+ void writeOptionalAttribute(Attribute) override { write(); }
+ void writeType(Type) override { write(); }
+ void writeResourceHandle(const AsmDialectResourceHandle &) override {
+ write();
+ }
+ void writeSignedVarInt(int64_t) override { write(); }
+ void writeAPIntWithKnownWidth(const APInt &) override { write(); }
+ void writeAPFloatWithKnownSemantics(const APFloat &) override { write(); }
+ void writeOwnedString(StringRef) override { write(); }
+ void writeOwnedBlob(ArrayRef<char>) override { write(); }
+ void writeUnownedBlob(ArrayRef<char>) override { write(); }
+ void writeOwnedBool(bool) override { write(); }
int64_t getBytecodeVersion() const override { return 0; }
FailureOr<const DialectVersion *>
getDialectVersion(StringRef) const override {
@@ -54,11 +61,15 @@ struct TypeCodeRecorder : DialectBytecodeWriter {
}
};
+/// The generator gives no access to the type codes, so this relies on every
+/// generated type writer emitting its type code as its first value, a varint.
uint64_t getTypeCode(Type type) {
TypeCodeRecorder recorder;
auto *iface =
type.getDialect().getRegisteredInterface<BytecodeDialectInterface>();
EXPECT_TRUE(succeeded(iface->writeType(type, recorder)));
+ EXPECT_TRUE(recorder.code)
+ << "the generated type writer no longer starts with the type code";
return recorder.code.value_or(0);
}
@@ -169,9 +180,7 @@ TEST_F(RecordBytecodeTest, EmptyName) {
writeStruct(writer, StringAttr::get(&context, ""), /*incomplete=*/true,
{}, {});
}));
- EXPECT_NE(diags.find("identified records cannot have an empty name"),
- std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("identified records cannot have an empty name"));
}
TEST_F(RecordBytecodeTest, IncompleteAnonymous) {
@@ -179,17 +188,16 @@ TEST_F(RecordBytecodeTest, IncompleteAnonymous) {
read(write([](MLIRContext &, DialectBytecodeWriter &writer) {
writeStruct(writer, StringAttr(), /*incomplete=*/true, {}, {});
}));
- EXPECT_NE(diags.find("anonymous records must be complete"), std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("anonymous records must be complete"));
}
// Each part of a body: members, packing, member kinds, and union padding.
TEST_F(RecordBytecodeTest, IncompleteWithBody) {
auto expectRejected = [](EncodeFn encode, llvm::StringRef name) {
std::string diags = read(write(encode));
- EXPECT_NE(diags.find(("incomplete record '" + name + "' has a body").str()),
- std::string::npos)
- << diags;
+ EXPECT_THAT(
+ diags,
+ HasSubstr(("incomplete record '" + name + "' has a body").str()));
};
expectRejected(
[](MLIRContext &context, DialectBytecodeWriter &writer) {
@@ -223,8 +231,7 @@ TEST_F(RecordBytecodeTest, InvalidMemberKind) {
writeStruct(writer, StringAttr::get(&context, "R"),
/*incomplete=*/false, {getS32(context)}, {99});
}));
- EXPECT_NE(diags.find("invalid RecordMemberKind value 99"), std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("invalid RecordMemberKind value 99"));
}
TEST_F(RecordBytecodeTest, AnonymousMemberKindCount) {
@@ -233,8 +240,7 @@ TEST_F(RecordBytecodeTest, AnonymousMemberKindCount) {
writeStruct(writer, StringAttr(), /*incomplete=*/false,
{getS32(context)}, {});
}));
- EXPECT_NE(diags.find("expected 1 member kinds, got 0"), std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("expected 1 member kinds, got 0"));
}
TEST_F(RecordBytecodeTest, NamedVoidMember) {
@@ -243,9 +249,7 @@ TEST_F(RecordBytecodeTest, NamedVoidMember) {
writeStruct(writer, StringAttr::get(&context, "R"),
/*incomplete=*/false, {VoidType::get(&context)}, {data});
}));
- EXPECT_NE(diags.find("record member at index 0 cannot be void"),
- std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("record member at index 0 cannot be void"));
}
TEST_F(RecordBytecodeTest, NonCIRMember) {
@@ -255,9 +259,7 @@ TEST_F(RecordBytecodeTest, NonCIRMember) {
/*incomplete=*/false, {IntegerType::get(&context, 32)},
{data});
}));
- EXPECT_NE(diags.find("record member at index 0 must be a CIR type"),
- std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("record member at index 0 must be a CIR type"));
}
TEST_F(RecordBytecodeTest, UnionPadKind) {
@@ -266,9 +268,7 @@ TEST_F(RecordBytecodeTest, UnionPadKind) {
writeUnion(writer, StringAttr::get(&context, "U"), /*incomplete=*/false,
{getS32(context)}, Type(), {pad});
}));
- EXPECT_NE(diags.find("a union member cannot be marked pad"),
- std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("a union member cannot be marked pad"));
}
TEST_F(RecordBytecodeTest, UnionPadding) {
@@ -277,9 +277,8 @@ TEST_F(RecordBytecodeTest, UnionPadding) {
writeUnion(writer, StringAttr::get(&context, "U"), /*incomplete=*/false,
{getS32(context)}, getS32(context), {data});
}));
- EXPECT_NE(diags.find("union padding must be !u8i or an array of !u8i"),
- std::string::npos)
- << diags;
+ EXPECT_THAT(diags,
+ HasSubstr("union padding must be !u8i or an array of !u8i"));
}
TEST_F(RecordBytecodeTest, AnonymousUnionPadKind) {
@@ -288,9 +287,7 @@ TEST_F(RecordBytecodeTest, AnonymousUnionPadKind) {
writeUnion(writer, StringAttr(), /*incomplete=*/false,
{getS32(context)}, Type(), {pad});
}));
- EXPECT_NE(diags.find("a union member cannot be marked pad"),
- std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("a union member cannot be marked pad"));
}
// A context that already holds the record with another body.
@@ -306,9 +303,7 @@ TEST_F(RecordBytecodeTest, StructRedefined) {
existing.complete({IntType::get(&context, 8, /*isSigned=*/true)},
/*packed=*/false, {RecordMemberKind::Data});
});
- EXPECT_NE(diags.find("record 'R' redefined with a different body"),
- std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("record 'R' redefined with a different body"));
}
TEST_F(RecordBytecodeTest, UnionRedefined) {
@@ -324,9 +319,7 @@ TEST_F(RecordBytecodeTest, UnionRedefined) {
/*packed=*/false, /*padding=*/Type(),
{RecordMemberKind::Data});
});
- EXPECT_NE(diags.find("record 'U' redefined with a different body"),
- std::string::npos)
- << diags;
+ EXPECT_THAT(diags, HasSubstr("record 'U' redefined with a different body"));
}
} // namespace
More information about the cfe-commits
mailing list