[clang] [CIR] Add bytecode encodings for struct and union types (PR #247883)
Bruno Cardoso Lopes via cfe-commits
cfe-commits at lists.llvm.org
Tue Dec 1 17:58:47 PST 2026
https://github.com/bcardosolopes created https://github.com/llvm/llvm-project/pull/247883
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. 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 reference, their -O3 LLVM bitcode is 1.4 MB and 0.5 MB.
>From 8d9a2fb62201f72c15d93f8ab61785bc5ff7e738 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] [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 | 290 ++++++++++++++++++
8 files changed, 534 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 326d7f4910bd6c..7f160a5b7536fb 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 c576204f1058fe..d44342f1f7054d 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 56df18b630dc8e..341e9cbe3b1ec3 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 cdb649056365c4..4fcea76a466e30 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 00000000000000..6289d4f9d3e27b
--- /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 0abb17897d9e52..2781c6e53b8540 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 929eefc4d061bf..ebb5506d2bcb97 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 00000000000000..d5372c9f023546
--- /dev/null
+++ b/clang/unittests/CIR/RecordBytecodeTest.cpp
@@ -0,0 +1,290 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 {
+
+// Positions of the records in the append-only CIRDialectTypes list.
+constexpr uint64_t structCode = 27;
+constexpr uint64_t unionCode = 28;
+
+using EncodeFn =
+ llvm::function_ref<void(MLIRContext &, DialectBytecodeWriter &)>;
+
+class RecordBytecodeTest : public ::testing::Test {
+protected:
+ /// 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
More information about the cfe-commits
mailing list