-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathOps.cpp
More file actions
728 lines (658 loc) · 27.9 KB
/
Ops.cpp
File metadata and controls
728 lines (658 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//===-- Ops.cpp - Struct op implementations ---------------------*- C++ -*-===//
//
// Part of the LLZK Project, under the Apache License v2.0.
// See LICENSE.txt for license information.
// Copyright 2025 Veridise Inc.
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#include "llzk/Dialect/Array/IR/Types.h"
#include "llzk/Dialect/Function/IR/Ops.h"
#include "llzk/Dialect/LLZK/IR/AttributeHelper.h"
#include "llzk/Dialect/Struct/IR/Ops.h"
#include "llzk/Util/AffineHelper.h"
#include "llzk/Util/Constants.h"
#include "llzk/Util/StreamHelper.h"
#include "llzk/Util/SymbolHelper.h"
#include <mlir/IR/IRMapping.h>
#include <mlir/IR/OpImplementation.h>
#include <llvm/ADT/MapVector.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/ADT/StringSet.h>
#include <optional>
// TableGen'd implementation files
#include "llzk/Dialect/Struct/IR/OpInterfaces.cpp.inc"
// TableGen'd implementation files
#define GET_OP_CLASSES
#include "llzk/Dialect/Struct/IR/Ops.cpp.inc"
using namespace mlir;
using namespace llzk::array;
using namespace llzk::function;
namespace llzk::component {
bool isInStruct(Operation *op) { return succeeded(getParentOfType<StructDefOp>(op)); }
FailureOr<StructDefOp> verifyInStruct(Operation *op) {
FailureOr<StructDefOp> res = getParentOfType<StructDefOp>(op);
if (failed(res)) {
return op->emitOpError() << "only valid within a '" << StructDefOp::getOperationName()
<< "' ancestor";
}
return res;
}
bool isInStructFunctionNamed(Operation *op, char const *funcName) {
FailureOr<FuncDefOp> parentFuncOpt = getParentOfType<FuncDefOp>(op);
if (succeeded(parentFuncOpt)) {
FuncDefOp parentFunc = parentFuncOpt.value();
if (isInStruct(parentFunc.getOperation())) {
if (parentFunc.getSymName().compare(funcName) == 0) {
return true;
}
}
}
return false;
}
// Again, only valid/implemented for StructDefOp
template <> LogicalResult SetFuncAllowAttrs<StructDefOp>::verifyTrait(Operation *structOp) {
assert(llvm::isa<StructDefOp>(structOp));
Region &bodyRegion = llvm::cast<StructDefOp>(structOp).getBodyRegion();
if (!bodyRegion.empty()) {
bodyRegion.front().walk([](FuncDefOp funcDef) {
if (funcDef.nameIsConstrain()) {
funcDef.setAllowConstraintAttr();
funcDef.setAllowWitnessAttr(false);
} else if (funcDef.nameIsCompute()) {
funcDef.setAllowConstraintAttr(false);
funcDef.setAllowWitnessAttr();
} else if (funcDef.nameIsProduct()) {
funcDef.setAllowConstraintAttr();
funcDef.setAllowWitnessAttr();
}
});
}
return success();
}
InFlightDiagnostic genCompareErr(StructDefOp expected, Operation *origin, const char *aspect) {
std::string prefix = std::string();
if (SymbolOpInterface symbol = llvm::dyn_cast<SymbolOpInterface>(origin)) {
prefix += "\"@";
prefix += symbol.getName();
prefix += "\" ";
}
return origin->emitOpError().append(
prefix, "must use type of its ancestor '", StructDefOp::getOperationName(), "' \"",
expected.getHeaderString(), "\" as ", aspect, " type"
);
}
static inline InFlightDiagnostic structFuncDefError(Operation *origin) {
return origin->emitError() << '\'' << StructDefOp::getOperationName() << "' op "
<< "must define either only a \"@" << FUNC_NAME_PRODUCT
<< "\" function, or both \"@" << FUNC_NAME_COMPUTE << "\" and \"@"
<< FUNC_NAME_CONSTRAIN << "\" functions; ";
}
/// Verifies that the given `actualType` matches the `StructDefOp` given (i.e., for the "self" type
/// parameter and return of the struct functions).
LogicalResult checkSelfType(
SymbolTableCollection &tables, StructDefOp expectedStruct, Type actualType, Operation *origin,
const char *aspect
) {
if (StructType actualStructType = llvm::dyn_cast<StructType>(actualType)) {
auto actualStructOpt =
lookupTopLevelSymbol<StructDefOp>(tables, actualStructType.getNameRef(), origin);
if (failed(actualStructOpt)) {
return origin->emitError().append(
"could not find '", StructDefOp::getOperationName(), "' named \"",
actualStructType.getNameRef(), '"'
);
}
StructDefOp actualStruct = actualStructOpt.value().get();
if (actualStruct != expectedStruct) {
return genCompareErr(expectedStruct, origin, aspect)
.attachNote(actualStruct.getLoc())
.append("uses this type instead");
}
// Check for an EXACT match in the parameter list since it must reference the "self" type.
if (expectedStruct.getConstParamsAttr() != actualStructType.getParams()) {
// To make error messages more consistent and meaningful, if the parameters don't match
// because the actual type uses symbols that are not defined, generate an error about the
// undefined symbol(s).
if (ArrayAttr tyParams = actualStructType.getParams()) {
if (failed(verifyParamsOfType(tables, tyParams.getValue(), actualStructType, origin))) {
return failure();
}
}
// Otherwise, generate an error stating the parent struct type must be used.
return genCompareErr(expectedStruct, origin, aspect)
.attachNote(actualStruct.getLoc())
.append("should be type of this '", StructDefOp::getOperationName(), '\'');
}
} else {
return genCompareErr(expectedStruct, origin, aspect);
}
return success();
}
//===------------------------------------------------------------------===//
// StructDefOp
//===------------------------------------------------------------------===//
StructType StructDefOp::getType(std::optional<ArrayAttr> constParams) {
auto pathRes = getPathFromRoot(*this);
assert(succeeded(pathRes)); // consistent with StructType::get() with invalid args
return StructType::get(pathRes.value(), constParams.value_or(getConstParamsAttr()));
}
std::string StructDefOp::getHeaderString() {
return buildStringViaCallback([this](llvm::raw_ostream &ss) {
FailureOr<SymbolRefAttr> pathToExpected = getPathFromRoot(*this);
if (succeeded(pathToExpected)) {
ss << pathToExpected.value();
} else {
// When there is a failure trying to get the resolved name of the struct,
// just print its symbol name directly.
ss << '@' << this->getSymName();
}
if (auto attr = this->getConstParamsAttr()) {
ss << '<' << attr << '>';
}
});
}
bool StructDefOp::hasParamNamed(StringAttr find) {
if (ArrayAttr params = this->getConstParamsAttr()) {
for (Attribute attr : params) {
assert(llvm::isa<FlatSymbolRefAttr>(attr)); // per ODS
if (llvm::cast<FlatSymbolRefAttr>(attr).getRootReference() == find) {
return true;
}
}
}
return false;
}
SymbolRefAttr StructDefOp::getFullyQualifiedName() {
auto res = getPathFromRoot(*this);
assert(succeeded(res));
return res.value();
}
LogicalResult StructDefOp::verifySymbolUses(SymbolTableCollection &tables) {
if (ArrayAttr params = this->getConstParamsAttr()) {
// Ensure struct parameter names are unique
llvm::StringSet<> uniqNames;
for (Attribute attr : params) {
assert(llvm::isa<FlatSymbolRefAttr>(attr)); // per ODS
StringRef name = llvm::cast<FlatSymbolRefAttr>(attr).getValue();
if (!uniqNames.insert(name).second) {
return this->emitOpError().append("has more than one parameter named \"@", name, '"');
}
}
// Ensure they do not conflict with existing symbols
for (Attribute attr : params) {
auto res = lookupTopLevelSymbol(tables, llvm::cast<FlatSymbolRefAttr>(attr), *this, false);
if (succeeded(res)) {
return this->emitOpError()
.append("parameter name \"@")
.append(llvm::cast<FlatSymbolRefAttr>(attr).getValue())
.append("\" conflicts with an existing symbol")
.attachNote(res->get()->getLoc())
.append("symbol already defined here");
}
}
}
return success();
}
namespace {
inline LogicalResult
checkMainFuncParamType(Type pType, FuncDefOp inFunc, std::optional<StructType> appendSelfType) {
if (isSignalType(pType)) {
return success();
} else if (auto arrayParamTy = llvm::dyn_cast<ArrayType>(pType)) {
if (isSignalType(arrayParamTy.getElementType())) {
return success();
}
}
std::string message = buildStringViaCallback([&inFunc, appendSelfType](llvm::raw_ostream &ss) {
ss << "main entry component \"@" << inFunc.getSymName()
<< "\" function parameters must be one of: {";
if (appendSelfType.has_value()) {
ss << appendSelfType.value() << ", ";
}
ss << "!" << StructType::name << "<@" << COMPONENT_NAME_SIGNAL << ">, ";
ss << "!" << ArrayType::name << "<.. x !" << StructType::name << "<@" << COMPONENT_NAME_SIGNAL
<< ">>}";
});
return inFunc.emitError(message);
}
inline LogicalResult verifyStructComputeConstrain(
StructDefOp structDef, FuncDefOp computeFunc, FuncDefOp constrainFunc
) {
// ASSERT: The `SetFuncAllowAttrs` trait on StructDefOp set the attributes correctly.
assert(constrainFunc.hasAllowConstraintAttr());
assert(!computeFunc.hasAllowConstraintAttr());
assert(!constrainFunc.hasAllowWitnessAttr());
assert(computeFunc.hasAllowWitnessAttr());
// Verify parameter types are valid. Skip the first parameter of the "constrain" function; it is
// already checked via verifyFuncTypeConstrain() in Function/IR/Ops.cpp.
ArrayRef<Type> computeParams = computeFunc.getFunctionType().getInputs();
ArrayRef<Type> constrainParams = constrainFunc.getFunctionType().getInputs().drop_front();
if (structDef.isMainComponent()) {
// Verify the input parameter types are legal. The error message is explicit about what types
// are allowed so there is no benefit to report multiple errors if more than one parameter in
// the referenced function has an illegal type.
for (Type t : computeParams) {
if (failed(checkMainFuncParamType(t, computeFunc, std::nullopt))) {
return failure(); // checkMainFuncParamType() already emits a sufficient error message
}
}
auto appendSelf = std::make_optional(structDef.getType());
for (Type t : constrainParams) {
if (failed(checkMainFuncParamType(t, constrainFunc, appendSelf))) {
return failure(); // checkMainFuncParamType() already emits a sufficient error message
}
}
}
if (!typeListsUnify(computeParams, constrainParams)) {
return constrainFunc.emitError()
.append(
"expected \"@", FUNC_NAME_CONSTRAIN,
"\" function argument types (sans the first one) to match \"@", FUNC_NAME_COMPUTE,
"\" function argument types"
)
.attachNote(computeFunc.getLoc())
.append("\"@", FUNC_NAME_COMPUTE, "\" function defined here");
}
return success();
}
inline LogicalResult verifyStructProduct(StructDefOp structDef, FuncDefOp productFunc) {
// ASSERT: The `SetFuncAllowAttrs` trait on StructDefOp set the attributes correctly
assert(productFunc.hasAllowConstraintAttr());
assert(productFunc.hasAllowWitnessAttr());
// Verify parameter types are valid
if (structDef.isMainComponent()) {
ArrayRef<Type> productParams = productFunc.getFunctionType().getInputs();
// Verify the input parameter types are legal. The error message is explicit about what types
// are allowed so there is no benefit to report multiple errors if more than one parameter in
// the referenced function has an illegal type.
for (Type t : productParams) {
if (failed(checkMainFuncParamType(t, productFunc, std::nullopt))) {
return failure(); // checkMainFuncParamType() already emits a sufficient error message
}
}
}
return success();
}
} // namespace
LogicalResult StructDefOp::verifyRegions() {
std::optional<FuncDefOp> foundCompute = std::nullopt;
std::optional<FuncDefOp> foundConstrain = std::nullopt;
std::optional<FuncDefOp> foundProduct = std::nullopt;
{
// Verify the following:
// 1. The only ops within the body are field and function definitions
// 2. The only functions defined in the struct are `@compute()` and `@constrain()`, or
// `@product()`
OwningEmitErrorFn emitError = getEmitOpErrFn(this);
Region &bodyRegion = getBodyRegion();
if (!bodyRegion.empty()) {
for (Operation &op : bodyRegion.front()) {
if (!llvm::isa<FieldDefOp>(op)) {
if (FuncDefOp funcDef = llvm::dyn_cast<FuncDefOp>(op)) {
if (funcDef.nameIsCompute()) {
if (foundProduct) {
return structFuncDefError(funcDef.getOperation())
<< "found both \"@" << FUNC_NAME_COMPUTE << "\" and \"@" << FUNC_NAME_PRODUCT
<< "\" functions";
}
if (foundCompute) {
return structFuncDefError(funcDef.getOperation())
<< "found multiple \"@" << FUNC_NAME_COMPUTE << "\" functions";
}
foundCompute = std::make_optional(funcDef);
} else if (funcDef.nameIsConstrain()) {
if (foundProduct) {
return structFuncDefError(funcDef.getOperation())
<< "found both \"@" << FUNC_NAME_CONSTRAIN << "\" and \"@"
<< FUNC_NAME_PRODUCT << "\" functions";
}
if (foundConstrain) {
return structFuncDefError(funcDef.getOperation())
<< "found multiple \"@" << FUNC_NAME_CONSTRAIN << "\" functions";
}
foundConstrain = std::make_optional(funcDef);
} else if (funcDef.nameIsProduct()) {
if (foundCompute) {
return structFuncDefError(funcDef.getOperation())
<< "found both \"@" << FUNC_NAME_COMPUTE << "\" and \"@" << FUNC_NAME_PRODUCT
<< "\" functions";
}
if (foundConstrain) {
return structFuncDefError(funcDef.getOperation())
<< "found both \"@" << FUNC_NAME_CONSTRAIN << "\" and \"@"
<< FUNC_NAME_PRODUCT << "\" functions";
}
if (foundProduct) {
return structFuncDefError(funcDef.getOperation())
<< "found multiple \"@" << FUNC_NAME_PRODUCT << "\" functions";
}
foundProduct = std::make_optional(funcDef);
} else {
// Must do a little more than a simple call to '?.emitOpError()' to
// tag the error with correct location and correct op name.
return structFuncDefError(funcDef.getOperation())
<< "found \"@" << funcDef.getSymName() << '"';
}
} else {
return op.emitOpError()
<< "invalid operation in '" << StructDefOp::getOperationName() << "'; only '"
<< FieldDefOp::getOperationName() << '\'' << " and '"
<< FuncDefOp::getOperationName() << "' operations are permitted";
}
}
}
}
if (!foundCompute.has_value() && foundConstrain.has_value()) {
return structFuncDefError(getOperation()) << "found \"@" << FUNC_NAME_CONSTRAIN
<< "\", missing \"@" << FUNC_NAME_COMPUTE << "\"";
}
if (!foundConstrain.has_value() && foundCompute.has_value()) {
return structFuncDefError(getOperation()) << "found \"@" << FUNC_NAME_COMPUTE
<< "\", missing \"@" << FUNC_NAME_CONSTRAIN << "\"";
}
}
if (!foundCompute.has_value() && !foundConstrain.has_value() && !foundProduct.has_value()) {
return structFuncDefError(getOperation())
<< "could not find \"@" << FUNC_NAME_PRODUCT << "\", \"@" << FUNC_NAME_COMPUTE
<< "\", or \"@" << FUNC_NAME_CONSTRAIN << "\"";
}
if (foundCompute && foundConstrain) {
return verifyStructComputeConstrain(*this, *foundCompute, *foundConstrain);
}
return verifyStructProduct(*this, *foundProduct);
}
FieldDefOp StructDefOp::getFieldDef(StringAttr fieldName) {
for (Operation &op : *getBody()) {
if (FieldDefOp fieldDef = llvm::dyn_cast_if_present<FieldDefOp>(op)) {
if (fieldName.compare(fieldDef.getSymNameAttr()) == 0) {
return fieldDef;
}
}
}
return nullptr;
}
std::vector<FieldDefOp> StructDefOp::getFieldDefs() {
std::vector<FieldDefOp> res;
for (Operation &op : *getBody()) {
if (FieldDefOp fieldDef = llvm::dyn_cast_if_present<FieldDefOp>(op)) {
res.push_back(fieldDef);
}
}
return res;
}
FuncDefOp StructDefOp::getComputeFuncOp() {
return llvm::dyn_cast_if_present<FuncDefOp>(lookupSymbol(FUNC_NAME_COMPUTE));
}
FuncDefOp StructDefOp::getConstrainFuncOp() {
return llvm::dyn_cast_if_present<FuncDefOp>(lookupSymbol(FUNC_NAME_CONSTRAIN));
}
FuncDefOp StructDefOp::getComputeOrProductFuncOp() {
if (auto *computeFunc = lookupSymbol(FUNC_NAME_COMPUTE)) {
return llvm::dyn_cast<FuncDefOp>(computeFunc);
}
return llvm::dyn_cast_if_present<FuncDefOp>(lookupSymbol(FUNC_NAME_PRODUCT));
}
FuncDefOp StructDefOp::getConstrainOrProductFuncOp() {
if (auto *constrainFunc = lookupSymbol(FUNC_NAME_CONSTRAIN)) {
return llvm::dyn_cast<FuncDefOp>(constrainFunc);
}
return llvm::dyn_cast_if_present<FuncDefOp>(lookupSymbol(FUNC_NAME_PRODUCT));
}
bool StructDefOp::isMainComponent() {
FailureOr<StructType> mainTypeOpt = getMainInstanceType(this->getOperation());
if (succeeded(mainTypeOpt)) {
if (StructType mainType = mainTypeOpt.value()) {
return structTypesUnify(mainType, this->getType());
}
}
return false;
}
//===------------------------------------------------------------------===//
// FieldDefOp
//===------------------------------------------------------------------===//
void FieldDefOp::build(
OpBuilder &odsBuilder, OperationState &odsState, StringAttr sym_name, TypeAttr type,
bool isColumn
) {
Properties &props = odsState.getOrAddProperties<Properties>();
props.setSymName(sym_name);
props.setType(type);
if (isColumn) {
props.column = odsBuilder.getUnitAttr();
}
}
void FieldDefOp::build(
OpBuilder &odsBuilder, OperationState &odsState, StringRef sym_name, Type type, bool isColumn
) {
build(odsBuilder, odsState, odsBuilder.getStringAttr(sym_name), TypeAttr::get(type), isColumn);
}
void FieldDefOp::build(
OpBuilder &odsBuilder, OperationState &odsState, TypeRange resultTypes, ValueRange operands,
ArrayRef<NamedAttribute> attributes, bool isColumn
) {
assert(operands.size() == 0u && "mismatched number of parameters");
odsState.addOperands(operands);
odsState.addAttributes(attributes);
assert(resultTypes.size() == 0u && "mismatched number of return types");
odsState.addTypes(resultTypes);
if (isColumn) {
odsState.getOrAddProperties<Properties>().column = odsBuilder.getUnitAttr();
}
}
void FieldDefOp::setPublicAttr(bool newValue) {
if (newValue) {
getOperation()->setAttr(PublicAttr::name, UnitAttr::get(getContext()));
} else {
getOperation()->removeAttr(PublicAttr::name);
}
}
static LogicalResult
verifyFieldDefTypeImpl(Type fieldType, SymbolTableCollection &tables, Operation *origin) {
if (StructType fieldStructType = llvm::dyn_cast<StructType>(fieldType)) {
// Special case for StructType verifies that the field type can resolve and that it is NOT the
// parent struct (i.e., struct fields cannot create circular references).
auto fieldTypeRes = verifyStructTypeResolution(tables, fieldStructType, origin);
if (failed(fieldTypeRes)) {
return failure(); // above already emits a sufficient error message
}
FailureOr<StructDefOp> parentRes = getParentOfType<StructDefOp>(origin);
assert(succeeded(parentRes) && "FieldDefOp parent is always StructDefOp"); // per ODS def
if (fieldTypeRes.value() == parentRes.value()) {
return origin->emitOpError()
.append("type is circular")
.attachNote(parentRes.value().getLoc())
.append("references parent component defined here");
}
return success();
} else {
return verifyTypeResolution(tables, origin, fieldType);
}
}
LogicalResult FieldDefOp::verifySymbolUses(SymbolTableCollection &tables) {
Type fieldType = this->getType();
if (failed(verifyFieldDefTypeImpl(fieldType, tables, *this))) {
return failure();
}
if (!getColumn()) {
return success();
}
// If the field is marked as a column only a small subset of types are allowed.
if (!isValidColumnType(getType(), tables, *this)) {
return emitOpError() << "marked as column can only contain felts, arrays of column types, or "
"structs with columns, but has type "
<< getType();
}
return success();
}
//===------------------------------------------------------------------===//
// FieldRefOp implementations
//===------------------------------------------------------------------===//
namespace {
FailureOr<SymbolLookupResult<FieldDefOp>>
getFieldDefOpImpl(FieldRefOpInterface refOp, SymbolTableCollection &tables, StructType tyStruct) {
Operation *op = refOp.getOperation();
auto structDefRes = tyStruct.getDefinition(tables, op);
if (failed(structDefRes)) {
return failure(); // getDefinition() already emits a sufficient error message
}
auto res = llzk::lookupSymbolIn<FieldDefOp>(
tables, SymbolRefAttr::get(refOp->getContext(), refOp.getFieldName()),
std::move(*structDefRes), op
);
if (failed(res)) {
return refOp->emitError() << "could not find '" << FieldDefOp::getOperationName()
<< "' named \"@" << refOp.getFieldName() << "\" in \""
<< tyStruct.getNameRef() << '"';
}
return std::move(res.value());
}
static FailureOr<SymbolLookupResult<FieldDefOp>>
findField(FieldRefOpInterface refOp, SymbolTableCollection &tables) {
// Ensure the base component/struct type reference can be resolved.
StructType tyStruct = refOp.getStructType();
if (failed(tyStruct.verifySymbolRef(tables, refOp.getOperation()))) {
return failure();
}
// Ensure the field name can be resolved in that struct.
return getFieldDefOpImpl(refOp, tables, tyStruct);
}
static LogicalResult verifySymbolUsesImpl(
FieldRefOpInterface refOp, SymbolTableCollection &tables, SymbolLookupResult<FieldDefOp> &field
) {
// Ensure the type of the referenced field declaration matches the type used in this op.
Type actualType = refOp.getVal().getType();
Type fieldType = field.get().getType();
if (!typesUnify(actualType, fieldType, field.getIncludeSymNames())) {
return refOp->emitOpError() << "has wrong type; expected " << fieldType << ", got "
<< actualType;
}
// Ensure any SymbolRef used in the type are valid
return verifyTypeResolution(tables, refOp.getOperation(), actualType);
}
LogicalResult verifySymbolUsesImpl(FieldRefOpInterface refOp, SymbolTableCollection &tables) {
// Ensure the field name can be resolved in that struct.
auto field = findField(refOp, tables);
if (failed(field)) {
return field; // getFieldDefOp() already emits a sufficient error message
}
return verifySymbolUsesImpl(refOp, tables, *field);
}
} // namespace
FailureOr<SymbolLookupResult<FieldDefOp>>
FieldRefOpInterface::getFieldDefOp(SymbolTableCollection &tables) {
return getFieldDefOpImpl(*this, tables, getStructType());
}
LogicalResult FieldReadOp::verifySymbolUses(SymbolTableCollection &tables) {
auto field = findField(*this, tables);
if (failed(field)) {
return failure();
}
if (failed(verifySymbolUsesImpl(*this, tables, *field))) {
return failure();
}
// If the field is not a column and an offset was specified then fail to validate
if (!field->get().getColumn() && getTableOffset().has_value()) {
return emitOpError("cannot read with table offset from a field that is not a column")
.attachNote(field->get().getLoc())
.append("field defined here");
}
// If the member is private and this read is outside the struct, then fail to validate.
// The current op may be inside a struct or a free function, but the
// member op (the member definition) is always inside a struct.
FailureOr<StructDefOp> parentRes = getParentOfType<StructDefOp>(*this);
FailureOr<StructDefOp> memberParentRes = verifyInStruct(field->get());
if (failed(memberParentRes)) {
return failure(); // verifyInStruct() already emits a sufficient error message
}
StructDefOp memberParentStruct = memberParentRes.value();
if (!field->get().hasPublicAttr() &&
(failed(parentRes) || parentRes.value() != memberParentStruct)) {
return emitOpError()
.append(
"cannot read from private member of struct \"", memberParentStruct.getHeaderString(),
"\""
)
.attachNote(field->get().getLoc())
.append("member defined here");
}
return success();
}
LogicalResult FieldWriteOp::verifySymbolUses(SymbolTableCollection &tables) {
// Ensure the write op only targets fields in the current struct.
FailureOr<StructDefOp> getParentRes = verifyInStruct(*this);
if (failed(getParentRes)) {
return failure(); // verifyInStruct() already emits a sufficient error message
}
if (failed(checkSelfType(tables, *getParentRes, getComponent().getType(), *this, "base value"))) {
return failure(); // checkSelfType() already emits a sufficient error message
}
// Perform the standard field ref checks.
return verifySymbolUsesImpl(*this, tables);
}
//===------------------------------------------------------------------===//
// FieldReadOp
//===------------------------------------------------------------------===//
void FieldReadOp::build(
OpBuilder &builder, OperationState &state, Type resultType, Value component, StringAttr field
) {
Properties &props = state.getOrAddProperties<Properties>();
props.setFieldName(FlatSymbolRefAttr::get(field));
state.addTypes(resultType);
state.addOperands(component);
affineMapHelpers::buildInstantiationAttrsEmptyNoSegments<FieldReadOp>(builder, state);
}
void FieldReadOp::build(
OpBuilder &builder, OperationState &state, Type resultType, Value component, StringAttr field,
Attribute dist, ValueRange mapOperands, std::optional<int32_t> numDims
) {
// '!mapOperands.empty()' implies 'numDims.has_value()'
assert(mapOperands.empty() || numDims.has_value());
state.addOperands(component);
state.addTypes(resultType);
if (numDims.has_value()) {
affineMapHelpers::buildInstantiationAttrsNoSegments<FieldReadOp>(
builder, state, ArrayRef({mapOperands}), builder.getDenseI32ArrayAttr({*numDims})
);
} else {
affineMapHelpers::buildInstantiationAttrsEmptyNoSegments<FieldReadOp>(builder, state);
}
Properties &props = state.getOrAddProperties<Properties>();
props.setFieldName(FlatSymbolRefAttr::get(field));
props.setTableOffset(dist);
}
void FieldReadOp::build(
OpBuilder & /*odsBuilder*/, OperationState &odsState, TypeRange resultTypes,
ValueRange operands, ArrayRef<NamedAttribute> attrs
) {
odsState.addTypes(resultTypes);
odsState.addOperands(operands);
odsState.addAttributes(attrs);
}
LogicalResult FieldReadOp::verify() {
SmallVector<AffineMapAttr, 1> mapAttrs;
if (AffineMapAttr map =
llvm::dyn_cast_if_present<AffineMapAttr>(getTableOffset().value_or(nullptr))) {
mapAttrs.push_back(map);
}
return affineMapHelpers::verifyAffineMapInstantiations(
getMapOperands(), getNumDimsPerMap(), mapAttrs, *this
);
}
//===------------------------------------------------------------------===//
// CreateStructOp
//===------------------------------------------------------------------===//
void CreateStructOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
setNameFn(getResult(), "self");
}
LogicalResult CreateStructOp::verifySymbolUses(SymbolTableCollection &tables) {
FailureOr<StructDefOp> getParentRes = verifyInStruct(*this);
if (failed(getParentRes)) {
return failure(); // verifyInStruct() already emits a sufficient error message
}
if (failed(checkSelfType(tables, *getParentRes, this->getType(), *this, "result"))) {
return failure();
}
return success();
}
} // namespace llzk::component