LLZK 0.1.0
Veridise's ZK Language IR
Loading...
Searching...
No Matches
Ops.td
Go to the documentation of this file.
1//===-- Ops.td ---------------------------------------------*- tablegen -*-===//
2//
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
7//
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
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLZK_STRUCT_OPS
16#define LLZK_STRUCT_OPS
17
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"
23
24include "mlir/IR/OpAsmInterface.td"
25include "mlir/IR/RegionKindInterface.td"
26include "mlir/IR/SymbolInterfaces.td"
27
28class StructDialectOp<string mnemonic, list<Trait> traits = []>
29 : Op<StructDialect, mnemonic, traits>;
30
31/// Only valid/implemented for StructDefOp. Sets the proper
32/// `AllowConstraintAttr` and `AllowWitnessAttr` on the functions defined within
33/// the StructDefOp.
34def SetFuncAllowAttrs : NativeOpTrait<"SetFuncAllowAttrs">, StructuralOpTrait {
35 string cppNamespace = "::llzk::component";
36}
37
38//===------------------------------------------------------------------===//
39// Struct Operations
40//===------------------------------------------------------------------===//
41
42def LLZK_StructDefOp
43 : StructDialectOp<
44 "def", [HasParent<"::mlir::ModuleOp">, Symbol, SymbolTable,
45 IsolatedFromAbove, GraphRegionNoTerminator, SetFuncAllowAttrs,
46 DeclareOpInterfaceMethods<SymbolUserOpInterface>]> {
47 let summary = "circuit component definition";
48 let description = [{
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.
54
55 Example:
56
57 ```llzk
58 struct.def @ComponentA {
59 field @f1 : !array.type<5 x index>
60 field @f2 : !felt.type {llzk.pub}
61
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>
66 }
67
68 function.def @constrain(%self: !struct.type<@ComponentA>, %p: !felt.type) {
69 // emit constraints here
70 return
71 }
72 }
73 ```
74 }];
75
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);
81
82 let regions = (region SizedRegion<1>:$body);
83
84 let assemblyFormat = [{
85 $sym_name (`<` $const_params^ `>`)? $body attr-dict
86 }];
87
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 = {});
92
93 /// Gets the FieldDefOp that defines the field in this
94 /// structure with the given name, if present.
95 FieldDefOp getFieldDef(::mlir::StringAttr fieldName);
96
97 /// Get all FieldDefOp in this structure.
98 ::std::vector<FieldDefOp> getFieldDefs();
99
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();
104 }));
105 }
106
107 /// Gets the FuncDefOp that defines the compute function in this structure, if present.
108 ::llzk::function::FuncDefOp getComputeFuncOp();
109
110 /// Gets the FuncDefOp that defines the constrain function in this structure, if present.
111 ::llzk::function::FuncDefOp getConstrainFuncOp();
112
113 /// Generate header string, in the same format as the assemblyFormat
114 ::std::string getHeaderString();
115
116 /// Return `false` iff `getConstParamsAttr()` returns `nullptr`
117 bool hasConstParamsAttr() { return getProperties().const_params != nullptr; };
118
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());
123 }
124
125 //===------------------------------------------------------------------===//
126 // Utility Methods
127 //===------------------------------------------------------------------===//
128
129 /// Return the full name for this struct from the root module, including
130 /// any surrounding module scopes.
131 ::mlir::SymbolRefAttr getFullyQualifiedName();
132
133 /// Return `true` iff this StructDefOp is named "Main".
134 bool isMainComponent();
135 }];
136
137 let hasRegionVerifier = 1;
138}
139
140def LLZK_FieldDefOp
141 : StructDialectOp<
142 "field", [HasParent<"::llzk::component::StructDefOp">,
143 DeclareOpInterfaceMethods<SymbolUserOpInterface>, Symbol]> {
144 let summary = "struct field definition";
145 let description = [{
146 This operation describes a field in a struct/component.
147
148 Example:
149
150 ```llzk
151 struct.field @f1 : !felt.type
152 struct.field @f2 : !felt.type {llzk.pub}
153 ```
154 }];
155
156 let arguments = (ins SymbolNameAttr:$sym_name, TypeAttrOf<AnyLLZKType>:$type,
157 UnitAttr:$column);
158
159 // Define builders manually to avoid the default ones that have extra
160 // TypeRange parameters that must always be empty.
161 let skipDefaultBuilders = 1;
162 let builders =
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
172 OpBuilder<
173 (ins "::llvm::ArrayRef<::mlir::NamedAttribute>":$attributes,
174 CArg<"bool", "false">:$isColumn),
175 [{ build($_builder, $_state, {}, {}, attributes, isColumn); }]>];
176
177 let assemblyFormat = [{ $sym_name `:` $type attr-dict }];
178
179 let extraClassDeclaration = [{
180 inline bool hasPublicAttr() { return getOperation()->hasAttr(llzk::PublicAttr::name); }
181 void setPublicAttr(bool newValue = true);
182 }];
183}
184
185class FieldRefOpBase<string mnemonic, list<Trait> traits = []>
186 : StructDialectOp<
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);
194 }
195 }];
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")#[{;
200 }
201 }];
202}
203
204def LLZK_FieldReadOp
205 : FieldRefOpBase<"readf", [VerifySizesForMultiAffineOps<1>]> {
206 let summary = "read value of a struct field";
207 let description = [{
208 This operation reads the value of a named field in a struct/component.
209
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.
214 }];
215 let isRead = 1;
216
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);
225
226 // Define builders manually so inference of operand layout attributes is not
227 // circumvented.
228 let skipDefaultBuilders = 1;
229 let builders =
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),
239 [{
240 build($_builder, $_state, resultType, component, field, dist, ::mlir::ValueRange(), std::nullopt);
241 }]>,
242 OpBuilder<(ins "::mlir::Type":$resultType, "::mlir::Value":$component,
243 "::mlir::StringAttr":$field, "::mlir::IntegerAttr":$dist),
244 [{
245 build($_builder, $_state, resultType, component, field, dist, ::mlir::ValueRange(), std::nullopt);
246 }]>,
247 OpBuilder<(ins "::mlir::TypeRange":$resultTypes,
248 "::mlir::ValueRange":$operands,
249 "::mlir::ArrayRef<::mlir::NamedAttribute>":$attrs)>];
250
251 let assemblyFormat = [{
252 $component `[` $field_name `]`
253 ( `{` custom<MultiDimAndSymbolList>($mapOperands, $numDimsPerMap)^ `}` )?
254 `:` type($component) `,` type($val)
255 attr-dict
256 }];
257
258 let hasVerifier = 1;
259}
260
261def LLZK_FieldWriteOp : FieldRefOpBase<"writef", [WitnessGen]> {
262 let summary = "write value to a struct field";
263 let description = [{
264 This operation writes a value to a named field in a struct/component.
265 }];
266 let isRead = 0;
267
268 let arguments = (ins LLZK_StructType:$component,
269 FlatSymbolRefAttr:$field_name, AnyLLZKType:$val);
270
271 let assemblyFormat = [{
272 $component `[` $field_name `]` `=` $val `:` type($component) `,` type($val) attr-dict
273 }];
274}
275
276def LLZK_CreateStructOp
277 : StructDialectOp<"new", [DeclareOpInterfaceMethods<
278 OpAsmOpInterface, ["getAsmResultNames"]>,
279 DeclareOpInterfaceMethods<SymbolUserOpInterface>,
280 WitnessGen,
281]> {
282 let summary = "create a new struct";
283 let description = [{
284 This operation creates a new, uninitialized instance of a struct.
285
286 Example:
287
288 ```llzk
289 %self = struct.new : !struct.type<@Reg>
290 ```
291 }];
292
293 let results = (outs LLZK_StructType:$result);
294
295 let assemblyFormat = [{ `:` type($result) attr-dict }];
296}
297
298#endif // LLZK_STRUCT_OPS