1//===-- Ops.td ---------------------------------------------*- tablegen -*-===//
3// Part of the LLZK Project, under the Apache License v2.0.
4// See LICENSE.txt for license information.
5// Copyright 2025 Veridise Inc.
6// SPDX-License-Identifier: Apache-2.0
8// Adapted from mlir/include/mlir/Dialect/Func/IR/FuncOps.td
9// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
10// See https://llvm.org/LICENSE.txt for license information.
11// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
13//===----------------------------------------------------------------------===//
15#ifndef LLZK_STRUCT_OPS
16#define LLZK_STRUCT_OPS
18include "llzk/Dialect/Function/IR/OpTraits.td"
19include "llzk/Dialect/Struct/IR/Dialect.td"
20include "llzk/Dialect/Struct/IR/OpInterfaces.td"
21include "llzk/Dialect/Struct/IR/Types.td"
22include "llzk/Dialect/Shared/OpTraits.td"
24include "mlir/IR/OpAsmInterface.td"
25include "mlir/IR/RegionKindInterface.td"
26include "mlir/IR/SymbolInterfaces.td"
28class StructDialectOp<string mnemonic, list<Trait> traits = []>
29 : Op<StructDialect, mnemonic, traits>;
31/// Only valid/implemented for StructDefOp. Sets the proper
32/// `AllowConstraintAttr` and `AllowWitnessAttr` on the functions defined within
34def SetFuncAllowAttrs : NativeOpTrait<"SetFuncAllowAttrs">, StructuralOpTrait {
35 string cppNamespace = "::llzk::component";
38//===------------------------------------------------------------------===//
40//===------------------------------------------------------------------===//
44 "def", [HasParent<"::mlir::ModuleOp">, Symbol, SymbolTable,
45 IsolatedFromAbove, GraphRegionNoTerminator, SetFuncAllowAttrs,
46 DeclareOpInterfaceMethods<SymbolUserOpInterface>]> {
47 let summary = "circuit component definition";
49 This operation describes a component in a circuit. It can contain any number
50 of fields that hold inputs, outputs, intermediate values, and subcomponents
51 of the defined component. It also contains a `compute()` function that holds
52 the witness generation code for the component and a `constrain()` function
53 that holds that constraint generation code for the component.
58 struct.def @ComponentA {
59 field @f1 : !array.type<5 x index>
60 field @f2 : !felt.type {llzk.pub}
62 function.def @compute(%p: !felt.type) -> !struct.type<@ComponentA> {
63 %self = struct.new : !struct.type<@ComponentA>
64 // initialize all fields of `%self` here
65 return %self : !struct.type<@ComponentA>
68 function.def @constrain(%self: !struct.type<@ComponentA>, %p: !felt.type) {
69 // emit constraints here
76 // Note: `$const_params` contains symbol definitions that do not use the
77 // standard SymbolTable mechanism. Instead hasParamNamed() can be used to
78 // check if a certain FlatSymbolRefAttr is a parameter in the function.
79 let arguments = (ins SymbolNameAttr:$sym_name,
80 OptionalAttr<FlatSymbolRefArrayAttr>:$const_params);
82 let regions = (region SizedRegion<1>:$body);
84 let assemblyFormat = [{
85 $sym_name (`<` $const_params^ `>`)? $body attr-dict
88 let extraClassDeclaration = [{
89 /// Gets the StructType representing this struct. If the `constParams` to use in
90 /// the type are not given, the StructType will use `this->getConstParamsAttr()`.
91 StructType getType(::std::optional<::mlir::ArrayAttr> constParams = {});
93 /// Gets the FieldDefOp that defines the field in this
94 /// structure with the given name, if present.
95 FieldDefOp getFieldDef(::mlir::StringAttr fieldName);
97 /// Get all FieldDefOp in this structure.
98 ::std::vector<FieldDefOp> getFieldDefs();
100 /// Returns wether the struct defines fields marked as columns.
101 ::mlir::LogicalResult hasColumns() {
102 return ::mlir::success(::llvm::any_of(getFieldDefs(), [](FieldDefOp fdOp) {
103 return fdOp.getColumn();
107 /// Gets the FuncDefOp that defines the compute function in this structure, if present.
108 ::llzk::function::FuncDefOp getComputeFuncOp();
110 /// Gets the FuncDefOp that defines the constrain function in this structure, if present.
111 ::llzk::function::FuncDefOp getConstrainFuncOp();
113 /// Generate header string, in the same format as the assemblyFormat
114 ::std::string getHeaderString();
116 /// Return `false` iff `getConstParamsAttr()` returns `nullptr`
117 bool hasConstParamsAttr() { return getProperties().const_params != nullptr; };
119 /// Return `true` iff this StructDefOp has a parameter with the given name
120 bool hasParamNamed(::mlir::StringAttr find);
121 inline bool hasParamNamed(::mlir::FlatSymbolRefAttr find) {
122 return hasParamNamed(find.getRootReference());
125 //===------------------------------------------------------------------===//
127 //===------------------------------------------------------------------===//
129 /// Return the full name for this struct from the root module, including
130 /// any surrounding module scopes.
131 ::mlir::SymbolRefAttr getFullyQualifiedName();
133 /// Return `true` iff this StructDefOp is named "Main".
134 bool isMainComponent();
137 let hasRegionVerifier = 1;
142 "field", [HasParent<"::llzk::component::StructDefOp">,
143 DeclareOpInterfaceMethods<SymbolUserOpInterface>, Symbol]> {
144 let summary = "struct field definition";
146 This operation describes a field in a struct/component.
151 struct.field @f1 : !felt.type
152 struct.field @f2 : !felt.type {llzk.pub}
156 let arguments = (ins SymbolNameAttr:$sym_name, TypeAttrOf<AnyLLZKType>:$type,
159 // Define builders manually to avoid the default ones that have extra
160 // TypeRange parameters that must always be empty.
161 let skipDefaultBuilders = 1;
163 [OpBuilder<(ins "::mlir::StringAttr":$sym_name, "::mlir::TypeAttr":$type,
164 CArg<"bool", "false">:$isColumn)>,
165 OpBuilder<(ins "::llvm::StringRef":$sym_name, "::mlir::Type":$type,
166 CArg<"bool", "false">:$isColumn)>,
167 OpBuilder<(ins "::mlir::TypeRange":$resultTypes,
168 "::mlir::ValueRange":$operands,
169 "::llvm::ArrayRef<::mlir::NamedAttribute>":$attributes,
170 CArg<"bool", "false">:$isColumn)>,
171 // Simpler version since 'resultTypes' and 'operands' must be empty
173 (ins "::llvm::ArrayRef<::mlir::NamedAttribute>":$attributes,
174 CArg<"bool", "false">:$isColumn),
175 [{ build($_builder, $_state, {}, {}, attributes, isColumn); }]>];
177 let assemblyFormat = [{ $sym_name `:` $type attr-dict }];
179 let extraClassDeclaration = [{
180 inline bool hasPublicAttr() { return getOperation()->hasAttr(llzk::PublicAttr::name); }
181 void setPublicAttr(bool newValue = true);
185class FieldRefOpBase<string mnemonic, list<Trait> traits = []>
187 mnemonic, traits#[DeclareOpInterfaceMethods<FieldRefOpInterface>,
188 DeclareOpInterfaceMethods<SymbolUserOpInterface>]> {
189 bit isRead = ?; // read(1) vs write(0) ops
190 let extraClassDeclaration = [{
191 /// Gets the definition for the `field` referenced in this op.
192 inline ::mlir::FailureOr<SymbolLookupResult<FieldDefOp>> getFieldDefOp(::mlir::SymbolTableCollection &tables) {
193 return ::llvm::cast<FieldRefOpInterface>(getOperation()).getFieldDefOp(tables);
196 let extraClassDefinition = [{
197 /// Return `true` if the op is a read, `false` if it's a write.
198 bool $cppClass::isRead() {
199 return }]#!if(isRead, "true", "false")#[{;
205 : FieldRefOpBase<"readf", [VerifySizesForMultiAffineOps<1>]> {
206 let summary = "read value of a struct field";
208 This operation reads the value of a named field in a struct/component.
210 The value can be read from the signals table, in which case it can be
211 offset by a constant value. A negative value represents reading a value
212 backwards and a positive value represents reading a value forward.
213 Only fields marked as columns can be read in this manner.
217 let arguments = (ins LLZK_StructType:$component,
218 FlatSymbolRefAttr:$field_name,
219 OptionalAttr<AnyAttrOf<[SymbolRefAttr, IndexAttr,
220 AffineMapAttr]>>:$tableOffset,
221 VariadicOfVariadic<Index, "mapOpGroupSizes">:$mapOperands,
222 DefaultValuedAttr<DenseI32ArrayAttr, "{}">:$numDimsPerMap,
223 DenseI32ArrayAttr:$mapOpGroupSizes);
224 let results = (outs AnyLLZKType:$val);
226 // Define builders manually so inference of operand layout attributes is not
228 let skipDefaultBuilders = 1;
230 [OpBuilder<(ins "::mlir::Type":$resultType, "::mlir::Value":$component,
231 "::mlir::StringAttr":$field)>,
232 OpBuilder<(ins "::mlir::Type":$resultType, "::mlir::Value":$component,
233 "::mlir::StringAttr":$field, "::mlir::Attribute":$dist,
234 "::mlir::ValueRange":$mapOperands,
235 "std::optional<int32_t>":$numDims)>,
236 OpBuilder<(ins "::mlir::Type":$resultType, "::mlir::Value":$component,
237 "::mlir::StringAttr":$field,
238 "::mlir::SymbolRefAttr":$dist),
240 build($_builder, $_state, resultType, component, field, dist, ::mlir::ValueRange(), std::nullopt);
242 OpBuilder<(ins "::mlir::Type":$resultType, "::mlir::Value":$component,
243 "::mlir::StringAttr":$field, "::mlir::IntegerAttr":$dist),
245 build($_builder, $_state, resultType, component, field, dist, ::mlir::ValueRange(), std::nullopt);
247 OpBuilder<(ins "::mlir::TypeRange":$resultTypes,
248 "::mlir::ValueRange":$operands,
249 "::mlir::ArrayRef<::mlir::NamedAttribute>":$attrs)>];
251 let assemblyFormat = [{
252 $component `[` $field_name `]`
253 ( `{` custom<MultiDimAndSymbolList>($mapOperands, $numDimsPerMap)^ `}` )?
254 `:` type($component) `,` type($val)
261def LLZK_FieldWriteOp : FieldRefOpBase<"writef", [WitnessGen]> {
262 let summary = "write value to a struct field";
264 This operation writes a value to a named field in a struct/component.
268 let arguments = (ins LLZK_StructType:$component,
269 FlatSymbolRefAttr:$field_name, AnyLLZKType:$val);
271 let assemblyFormat = [{
272 $component `[` $field_name `]` `=` $val `:` type($component) `,` type($val) attr-dict
276def LLZK_CreateStructOp
277 : StructDialectOp<"new", [DeclareOpInterfaceMethods<
278 OpAsmOpInterface, ["getAsmResultNames"]>,
279 DeclareOpInterfaceMethods<SymbolUserOpInterface>,
282 let summary = "create a new struct";
284 This operation creates a new, uninitialized instance of a struct.
289 %self = struct.new : !struct.type<@Reg>
293 let results = (outs LLZK_StructType:$result);
295 let assemblyFormat = [{ `:` type($result) attr-dict }];
298#endif // LLZK_STRUCT_OPS