CIRCT 24.0.0git
Loading...
Searching...
No Matches
OMOps.cpp
Go to the documentation of this file.
1//===- OMOps.cpp - Object Model operation definitions ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the Object Model operation definitions.
10//
11//===----------------------------------------------------------------------===//
12
16#include "mlir/IR/Builders.h"
17#include "mlir/IR/ImplicitLocOpBuilder.h"
18#include "mlir/IR/SymbolTable.h"
19#include "llvm/ADT/STLExtras.h"
20
21using namespace mlir;
22using namespace circt::om;
23
24//===----------------------------------------------------------------------===//
25// Custom Printers and Parsers
26//===----------------------------------------------------------------------===//
27
28static ParseResult parseBasePathString(OpAsmParser &parser, PathAttr &path) {
29 auto *context = parser.getContext();
30 auto loc = parser.getCurrentLocation();
31 std::string rawPath;
32 if (parser.parseString(&rawPath))
33 return failure();
34 if (parseBasePath(context, rawPath, path))
35 return parser.emitError(loc, "invalid base path");
36 return success();
37}
38
39static void printBasePathString(OpAsmPrinter &p, Operation *op, PathAttr path) {
40 p << '\"';
41 llvm::interleave(
42 path, p,
43 [&](const PathElement &elt) {
44 p << elt.module.getValue() << '/' << elt.instance.getValue();
45 },
46 ":");
47 p << '\"';
48}
49
50static ParseResult parsePathString(OpAsmParser &parser, PathAttr &path,
51 StringAttr &module, StringAttr &ref,
52 StringAttr &field) {
53
54 auto *context = parser.getContext();
55 auto loc = parser.getCurrentLocation();
56 std::string rawPath;
57 if (parser.parseString(&rawPath))
58 return failure();
59 if (parsePath(context, rawPath, path, module, ref, field))
60 return parser.emitError(loc, "invalid path");
61 return success();
62}
63
64static void printPathString(OpAsmPrinter &p, Operation *op, PathAttr path,
65 StringAttr module, StringAttr ref,
66 StringAttr field) {
67 p << '\"';
68 for (const auto &elt : path)
69 p << elt.module.getValue() << '/' << elt.instance.getValue() << ':';
70 if (!module.getValue().empty())
71 p << module.getValue();
72 if (!ref.getValue().empty())
73 p << '>' << ref.getValue();
74 if (!field.getValue().empty())
75 p << field.getValue();
76 p << '\"';
77}
78
79static ParseResult parseFieldLocs(OpAsmParser &parser, ArrayAttr &fieldLocs) {
80 if (parser.parseOptionalKeyword("field_locs"))
81 return success();
82 if (parser.parseLParen() || parser.parseAttribute(fieldLocs) ||
83 parser.parseRParen()) {
84 return failure();
85 }
86 return success();
87}
88
89static void printFieldLocs(OpAsmPrinter &printer, Operation *op,
90 ArrayAttr fieldLocs) {
91 mlir::OpPrintingFlags flags;
92 if (!flags.shouldPrintDebugInfo() || !fieldLocs)
93 return;
94 printer << "field_locs(";
95 printer.printAttribute(fieldLocs);
96 printer << ")";
97}
98
99//===----------------------------------------------------------------------===//
100// Shared definitions
101//===----------------------------------------------------------------------===//
102static ParseResult parseClassFieldsList(OpAsmParser &parser,
103 SmallVectorImpl<Attribute> &fieldNames,
104 SmallVectorImpl<Type> &fieldTypes) {
105
106 llvm::StringMap<SMLoc> nameLocMap;
107 auto parseElt = [&]() -> ParseResult {
108 // Parse the field name.
109 std::string fieldName;
110 if (parser.parseKeywordOrString(&fieldName))
111 return failure();
112 SMLoc currLoc = parser.getCurrentLocation();
113 if (nameLocMap.count(fieldName)) {
114 parser.emitError(currLoc, "field \"")
115 << fieldName << "\" is defined twice";
116 parser.emitError(nameLocMap[fieldName]) << "previous definition is here";
117 return failure();
118 }
119 nameLocMap[fieldName] = currLoc;
120 fieldNames.push_back(StringAttr::get(parser.getContext(), fieldName));
121
122 // Parse the field type.
123 fieldTypes.emplace_back();
124 if (parser.parseColonType(fieldTypes.back()))
125 return failure();
126
127 return success();
128 };
129
130 return parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
131 parseElt);
132}
133
134template <typename ClassTy>
135static ParseResult parseClassLike(OpAsmParser &parser, OperationState &state) {
136 // Parse the optional symbol visibility.
137 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, state.attributes);
138
139 // Parse the Class symbol name.
140 StringAttr symName;
141 if (parser.parseSymbolName(symName, ClassTy::getSymNameAttrName(state.name),
142 state.attributes))
143 return failure();
144
145 // Parse the formal parameters.
146 SmallVector<OpAsmParser::Argument> args;
147 if (parser.parseArgumentList(args, OpAsmParser::Delimiter::Paren,
148 /*allowType=*/true, /*allowAttrs=*/false))
149 return failure();
150
151 SmallVector<Type> fieldTypes;
152 SmallVector<Attribute> fieldNames;
153 if (succeeded(parser.parseOptionalArrow()))
154 if (failed(parseClassFieldsList(parser, fieldNames, fieldTypes)))
155 return failure();
156
157 SmallVector<NamedAttribute> fieldTypesMap;
158 if (!fieldNames.empty()) {
159 for (auto [name, type] : zip(fieldNames, fieldTypes))
160 fieldTypesMap.push_back(
161 NamedAttribute(cast<StringAttr>(name), TypeAttr::get(type)));
162 }
163 auto *ctx = parser.getContext();
164 state.addAttribute("fieldNames", mlir::ArrayAttr::get(ctx, fieldNames));
165 state.addAttribute("fieldTypes",
166 mlir::DictionaryAttr::get(ctx, fieldTypesMap));
167
168 // Parse the optional attribute dictionary.
169 if (failed(parser.parseOptionalAttrDictWithKeyword(state.attributes)))
170 return failure();
171
172 // Parse the body.
173 Region *region = state.addRegion();
174 if (parser.parseRegion(*region, args))
175 return failure();
176
177 // If the region was empty, add an empty block so it's still a SizedRegion<1>.
178 if (region->empty())
179 region->emplaceBlock();
180
181 // Remember the formal parameter names in an attribute.
182 auto argNames = llvm::map_range(args, [&](OpAsmParser::Argument arg) {
183 return StringAttr::get(parser.getContext(), arg.ssaName.name.drop_front());
184 });
185 state.addAttribute(
186 "formalParamNames",
187 ArrayAttr::get(parser.getContext(), SmallVector<Attribute>(argNames)));
188
189 return success();
190}
191
192static void printClassLike(ClassLike classLike, OpAsmPrinter &printer) {
193 printer << " ";
194
195 // Print the optional symbol visibility.
196 StringRef visibilityAttrName =
197 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
198 if (auto visibility =
199 classLike->getAttrOfType<StringAttr>(visibilityAttrName))
200 printer << visibility.getValue() << ' ';
201
202 // Print the Class symbol name.
203 printer.printSymbolName(classLike.getSymName());
204
205 // Retrieve the formal parameter names and values.
206 auto argNames = SmallVector<StringRef>(
207 classLike.getFormalParamNames().getAsValueRange<StringAttr>());
208 ArrayRef<BlockArgument> args = classLike.getBodyBlock()->getArguments();
209
210 // Print the formal parameters.
211 printer << '(';
212 for (size_t i = 0, e = args.size(); i < e; ++i) {
213 printer << '%' << argNames[i] << ": " << args[i].getType();
214 if (i < e - 1)
215 printer << ", ";
216 }
217 printer << ") ";
218
219 ArrayRef<Attribute> fieldNames =
220 cast<ArrayAttr>(classLike->getAttr("fieldNames")).getValue();
221
222 if (!fieldNames.empty()) {
223 printer << " -> (";
224 for (size_t i = 0, e = fieldNames.size(); i < e; ++i) {
225 if (i != 0)
226 printer << ", ";
227 StringAttr name = cast<StringAttr>(fieldNames[i]);
228 printer.printKeywordOrString(name.getValue());
229 printer << ": ";
230 Type type = classLike.getFieldType(name).value();
231 printer.printType(type);
232 }
233 printer << ") ";
234 }
235
236 // Print the optional attribute dictionary.
237 SmallVector<StringRef> elidedAttrs{
238 classLike.getSymNameAttrName(), classLike.getFormalParamNamesAttrName(),
239 visibilityAttrName, "fieldTypes", "fieldNames"};
240 printer.printOptionalAttrDictWithKeyword(classLike.getOperation()->getAttrs(),
241 elidedAttrs);
242
243 // Print the body.
244 printer.printRegion(classLike.getBody(), /*printEntryBlockArgs=*/false,
245 /*printBlockTerminators=*/true);
246}
247
248LogicalResult verifyClassLike(ClassLike classLike) {
249 // Verify the formal parameter names match up with the values.
250 if (classLike.getFormalParamNames().size() !=
251 classLike.getBodyBlock()->getArguments().size()) {
252 auto error = classLike.emitOpError(
253 "formal parameter name list doesn't match formal parameter value list");
254 error.attachNote(classLike.getLoc())
255 << "formal parameter names: " << classLike.getFormalParamNames();
256 error.attachNote(classLike.getLoc())
257 << "formal parameter values: "
258 << classLike.getBodyBlock()->getArguments();
259 return error;
260 }
261
262 return success();
263}
264
265void getClassLikeAsmBlockArgumentNames(ClassLike classLike, Region &region,
266 OpAsmSetValueNameFn setNameFn) {
267 // Retrieve the formal parameter names and values.
268 auto argNames = SmallVector<StringRef>(
269 classLike.getFormalParamNames().getAsValueRange<StringAttr>());
270 ArrayRef<BlockArgument> args = classLike.getBodyBlock()->getArguments();
271
272 // Use the formal parameter names as the SSA value names.
273 for (size_t i = 0, e = args.size(); i < e; ++i)
274 setNameFn(args[i], argNames[i]);
275}
276
277NamedAttribute makeFieldType(StringAttr name, Type type) {
278 return NamedAttribute(name, TypeAttr::get(type));
279}
280
281NamedAttribute makeFieldIdx(MLIRContext *ctx, mlir::StringAttr name,
282 unsigned i) {
283 return NamedAttribute(StringAttr(name),
284 mlir::IntegerAttr::get(mlir::IndexType::get(ctx), i));
285}
286
287std::optional<Type> getClassLikeFieldType(ClassLike classLike,
288 StringAttr name) {
289 DictionaryAttr fieldTypes = mlir::cast<DictionaryAttr>(
290 classLike.getOperation()->getAttr("fieldTypes"));
291 Attribute type = fieldTypes.get(name);
292 if (auto field = dyn_cast_or_null<TypeAttr>(type))
293 return field.getValue();
294 return std::nullopt;
295}
296
297void replaceClassLikeFieldTypes(ClassLike classLike,
298 AttrTypeReplacer &replacer) {
299 classLike->setAttr("fieldTypes", cast<DictionaryAttr>(replacer.replace(
300 classLike.getFieldTypes())));
301}
302
303//===----------------------------------------------------------------------===//
304// ClassOp
305//===----------------------------------------------------------------------===//
306
307ParseResult circt::om::ClassOp::parse(OpAsmParser &parser,
308 OperationState &state) {
309 return parseClassLike<ClassOp>(parser, state);
310}
311
312circt::om::ClassOp circt::om::ClassOp::buildSimpleClassOp(
313 OpBuilder &odsBuilder, Location loc, Twine name,
314 ArrayRef<StringRef> formalParamNames, ArrayRef<StringRef> fieldNames,
315 ArrayRef<Type> fieldTypes) {
316 circt::om::ClassOp classOp = circt::om::ClassOp::create(
317 odsBuilder, loc, odsBuilder.getStringAttr(name), /*sym_visibility=*/{},
318 odsBuilder.getStrArrayAttr(formalParamNames),
319 odsBuilder.getStrArrayAttr(fieldNames),
320 odsBuilder.getDictionaryAttr(llvm::map_to_vector(
321 llvm::zip(fieldNames, fieldTypes), [&](auto field) -> NamedAttribute {
322 return NamedAttribute(odsBuilder.getStringAttr(std::get<0>(field)),
323 TypeAttr::get(std::get<1>(field)));
324 })));
325 Block *body = &classOp.getRegion().emplaceBlock();
326 auto prevLoc = odsBuilder.saveInsertionPoint();
327 odsBuilder.setInsertionPointToEnd(body);
328
329 mlir::SmallVector<Attribute> locAttrs(fieldNames.size(), LocationAttr(loc));
330
331 ClassFieldsOp::create(odsBuilder, loc,
332 llvm::map_to_vector(fieldTypes,
333 [&](Type type) -> Value {
334 return body->addArgument(type,
335 loc);
336 }),
337 odsBuilder.getArrayAttr(locAttrs));
338
339 odsBuilder.restoreInsertionPoint(prevLoc);
340
341 return classOp;
342}
343
344void circt::om::ClassOp::print(OpAsmPrinter &printer) {
345 printClassLike(*this, printer);
346}
347
348LogicalResult circt::om::ClassOp::verify() {
349 if (getLinkonceOdr() && !isPublic())
350 return emitOpError("linkonce_odr requires public visibility");
351 return verifyClassLike(*this);
352}
353
354LogicalResult circt::om::ClassOp::verifyRegions() {
355 auto fieldsOp =
356 dyn_cast_or_null<ClassFieldsOp>(this->getBodyBlock()->getTerminator());
357 if (!fieldsOp)
358 return this->emitOpError("expected terminator to be ClassFieldsOp");
359
360 // The number of results matches the number of terminator operands.
361 if (fieldsOp.getNumOperands() != this->getFieldNames().size()) {
362 auto diag = this->emitOpError()
363 << "returns '" << this->getFieldNames().size()
364 << "' fields, but its terminator returned '"
365 << fieldsOp.getNumOperands() << "' fields";
366 return diag.attachNote(fieldsOp.getLoc()) << "see terminator:";
367 }
368
369 // The type of each result matches the corresponding terminator operand type.
370 auto types = this->getFieldTypes();
371 for (auto [fieldName, terminatorOperandType] :
372 llvm::zip(this->getFieldNames(), fieldsOp.getOperandTypes())) {
373
374 auto fieldNameAttr = dyn_cast_or_null<StringAttr>(fieldName);
375 if (!fieldNameAttr)
376 return this->emitOpError("field name is not a StringAttr");
377
378 if (auto fieldType = types.get(fieldNameAttr))
379 if (auto typeAttr = dyn_cast<TypeAttr>(fieldType))
380 if (typeAttr.getValue() == terminatorOperandType)
381 continue;
382
383 auto diag = this->emitOpError()
384 << "returns different field types than its terminator";
385 return diag.attachNote(fieldsOp.getLoc()) << "see terminator:";
386 }
387
388 return success();
389}
390
391void circt::om::ClassOp::getAsmBlockArgumentNames(
392 Region &region, OpAsmSetValueNameFn setNameFn) {
393 getClassLikeAsmBlockArgumentNames(*this, region, setNameFn);
394}
395
396std::optional<mlir::Type>
397circt::om::ClassOp::getFieldType(mlir::StringAttr field) {
398 return getClassLikeFieldType(*this, field);
399}
400
401void circt::om::ClassOp::replaceFieldTypes(AttrTypeReplacer &replacer) {
402 replaceClassLikeFieldTypes(*this, replacer);
403}
404
405void circt::om::ClassOp::updateFields(
406 mlir::ArrayRef<mlir::Location> newLocations,
407 mlir::ArrayRef<mlir::Value> newValues,
408 mlir::ArrayRef<mlir::Attribute> newNames) {
409
410 auto fieldsOp = getFieldsOp();
411 assert(fieldsOp && "The fields op should exist");
412 // Get field names.
413 SmallVector<Attribute> names(getFieldNamesAttr().getAsRange<StringAttr>());
414 // Get the field types.
415 SmallVector<NamedAttribute> fieldTypes(getFieldTypesAttr().getValue());
416 // Get the field values.
417 SmallVector<Value> fieldVals(fieldsOp.getFields());
418 // Get the field locations.
419 Location fieldOpLoc = fieldsOp->getLoc();
420
421 // Extract the locations per field.
422 SmallVector<Location> locations;
423 if (auto fl = dyn_cast<FusedLoc>(fieldOpLoc)) {
424 if (auto metadataArr = dyn_cast_or_null<ArrayAttr>(fl.getMetadata())) {
425 if (names.size() == metadataArr.size()) {
426 auto r = metadataArr.getAsRange<LocationAttr>();
427 locations.append(r.begin(), r.end());
428 } else {
429 locations.append(names.size(), fieldOpLoc);
430 }
431 } else {
432 auto fieldLocs = fieldsOp.getFieldLocs();
433 if (fieldLocs.has_value() && names.size() == fieldLocs.value().size()) {
434 auto r = fieldLocs.value().getAsRange<LocationAttr>();
435 locations.append(r.begin(), r.end());
436 } else {
437 locations.append(names.size(), fieldOpLoc);
438 }
439 }
440 } else {
441 // Assume same loc for every field.
442 locations.append(names.size(), fieldOpLoc);
443 }
444
445 // Append the new names, locations and values.
446 names.append(newNames.begin(), newNames.end());
447 locations.append(newLocations.begin(), newLocations.end());
448 fieldVals.append(newValues.begin(), newValues.end());
449
450 // Construct the new field types from values and names.
451 for (auto [v, n] : llvm::zip(newValues, newNames))
452 fieldTypes.emplace_back(
453 NamedAttribute(llvm::cast<StringAttr>(n), TypeAttr::get(v.getType())));
454
455 // Keep the locations as array on the metadata.
456 SmallVector<Attribute> locationsAttr;
457 llvm::for_each(locations, [&](Location &l) {
458 locationsAttr.push_back(cast<Attribute>(l));
459 });
460
461 ImplicitLocOpBuilder builder(getLoc(), *this);
462 // Update the field names attribute.
463 setFieldNamesAttr(builder.getArrayAttr(names));
464 // Update the fields type attribute.
465 setFieldTypesAttr(builder.getDictionaryAttr(fieldTypes));
466 fieldsOp.getFieldsMutable().assign(fieldVals);
467 // Update the location.
468 fieldsOp->setLoc(builder.getFusedLoc(
469 locations, ArrayAttr::get(getContext(), locationsAttr)));
470}
471
472void circt::om::ClassOp::addNewFieldsOp(mlir::OpBuilder &builder,
473 mlir::ArrayRef<Location> locs,
474 mlir::ArrayRef<Value> values) {
475 // Store the original locations as a metadata array so that unique locations
476 // are preserved as a mapping from field index to location
477 assert(locs.size() == values.size() && "Expected a location per value");
478 mlir::SmallVector<Attribute> locAttrs;
479 for (auto loc : locs) {
480 locAttrs.push_back(cast<Attribute>(LocationAttr(loc)));
481 }
482 // Also store the locations incase there's some other analysis that might
483 // be able to use the default FusedLoc representation.
484 ClassFieldsOp::create(builder, builder.getFusedLoc(locs), values,
485 builder.getArrayAttr(locAttrs));
486}
487
488mlir::Location circt::om::ClassOp::getFieldLocByIndex(size_t i) {
489 auto fieldsOp = this->getFieldsOp();
490 auto fieldLocs = fieldsOp.getFieldLocs();
491 if (!fieldLocs.has_value())
492 return fieldsOp.getLoc();
493 assert(i < fieldLocs.value().size() &&
494 "field index too large for location array");
495 return cast<LocationAttr>(fieldLocs.value()[i]);
496}
497
498//===----------------------------------------------------------------------===//
499// ClassExternOp
500//===----------------------------------------------------------------------===//
501
502ParseResult circt::om::ClassExternOp::parse(OpAsmParser &parser,
503 OperationState &state) {
504 return parseClassLike<ClassExternOp>(parser, state);
505}
506
507void circt::om::ClassExternOp::print(OpAsmPrinter &printer) {
508 printClassLike(*this, printer);
509}
510
511LogicalResult circt::om::ClassExternOp::verify() {
512 if (failed(verifyClassLike(*this))) {
513 return failure();
514 }
515 // Verify body is empty
516 if (!this->getBodyBlock()->getOperations().empty()) {
517 return this->emitOpError("external class body should be empty");
518 }
519
520 return success();
521}
522
523void circt::om::ClassExternOp::getAsmBlockArgumentNames(
524 Region &region, OpAsmSetValueNameFn setNameFn) {
525 getClassLikeAsmBlockArgumentNames(*this, region, setNameFn);
526}
527
528std::optional<mlir::Type>
529circt::om::ClassExternOp::getFieldType(mlir::StringAttr field) {
530 return getClassLikeFieldType(*this, field);
531}
532
533void circt::om::ClassExternOp::replaceFieldTypes(AttrTypeReplacer &replacer) {
534 replaceClassLikeFieldTypes(*this, replacer);
535}
536
537//===----------------------------------------------------------------------===//
538// ClassFieldsOp
539//===----------------------------------------------------------------------===//
540//
541LogicalResult circt::om::ClassFieldsOp::verify() {
542 auto fieldLocs = this->getFieldLocs();
543 if (fieldLocs.has_value()) {
544 auto fieldLocsVal = fieldLocs.value();
545 if (fieldLocsVal.size() != this->getFields().size()) {
546 auto error = this->emitOpError("size of field_locs (")
547 << fieldLocsVal.size()
548 << ") does not match number of fields ("
549 << this->getFields().size() << ")";
550 }
551 }
552 return success();
553}
554
555//===----------------------------------------------------------------------===//
556// ObjectOp
557//===----------------------------------------------------------------------===//
558
559void circt::om::ObjectOp::build(::mlir::OpBuilder &odsBuilder,
560 ::mlir::OperationState &odsState,
561 om::ClassOp classOp,
562 ::mlir::ValueRange actualParams) {
563 return build(odsBuilder, odsState,
564 om::ClassType::get(odsBuilder.getContext(),
565 mlir::FlatSymbolRefAttr::get(classOp)),
566 mlir::FlatSymbolRefAttr::get(classOp.getNameAttr()),
567 actualParams);
568}
569
570static FailureOr<ClassLike>
571verifyClassLikeSymbolUser(Operation *op, SymbolTableCollection &symbolTable,
572 ClassType resultType, StringAttr className) {
573 StringAttr resultClassName = resultType.getClassName().getAttr();
574 if (resultClassName != className)
575 return op->emitOpError("result type (")
576 << resultClassName << ") does not match referred to class ("
577 << className << ')';
578
579 auto classDef = dyn_cast_or_null<ClassLike>(
580 symbolTable.lookupNearestSymbolFrom(op, className));
581 if (!classDef)
582 return op->emitOpError("refers to non-existant class (")
583 << className << ')';
584 return classDef;
585}
586
587LogicalResult
588circt::om::ObjectOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
589 auto classDef =
590 verifyClassLikeSymbolUser((*this), symbolTable, getResult().getType(),
591 getClassNameAttr().getAttr());
592 if (failed(classDef))
593 return failure();
594
595 auto actualTypes = getActualParams().getTypes();
596 auto formalTypes = classDef->getBodyBlock()->getArgumentTypes();
597
598 // Verify the actual parameter list matches the formal parameter list.
599 if (actualTypes.size() != formalTypes.size()) {
600 auto error = emitOpError(
601 "actual parameter list doesn't match formal parameter list");
602 error.attachNote(classDef->getLoc())
603 << "formal parameters: " << classDef->getBodyBlock()->getArguments();
604 error.attachNote(getLoc()) << "actual parameters: " << getActualParams();
605 return error;
606 }
607
608 // Verify the actual parameter types match the formal parameter types.
609 for (size_t i = 0, e = actualTypes.size(); i < e; ++i) {
610 if (actualTypes[i] != formalTypes[i]) {
611 return emitOpError("actual parameter type (")
612 << actualTypes[i] << ") doesn't match formal parameter type ("
613 << formalTypes[i] << ')';
614 }
615 }
616
617 return success();
618}
619
620//===----------------------------------------------------------------------===//
621// ObjectFieldOp
622//===----------------------------------------------------------------------===//
623
624LogicalResult
625circt::om::ObjectFieldOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
626 auto classType = getObject().getType();
627 auto className = classType.getClassName().getAttr();
628
629 // Verify the referred-to class exists.
630 auto classDef = dyn_cast_or_null<ClassLike>(
631 symbolTable.lookupNearestSymbolFrom(*this, className));
632 if (!classDef)
633 return emitOpError("class ") << className << " was not found";
634
635 // Verify the field exists in the class.
636 auto fieldName = getFieldAttr();
637 std::optional<Type> fieldType = classDef.getFieldType(fieldName);
638 if (!fieldType) {
639 auto diag = emitOpError("referenced non-existent field ") << fieldName;
640 diag.attachNote(classDef.getLoc()) << "class defined here";
641 return diag;
642 }
643
644 // Verify the result type matches the field type.
645 if (getResult().getType() != fieldType.value())
646 return emitOpError("expected type ")
647 << getResult().getType() << ", but accessed field has type "
648 << fieldType.value();
649 return success();
650}
651
652//===----------------------------------------------------------------------===//
653// ElaboratedObjectOp
654//===----------------------------------------------------------------------===//
655
656void circt::om::ElaboratedObjectOp::build(OpBuilder &odsBuilder,
657 OperationState &odsState,
658 om::ClassLike classOp,
659 ValueRange fieldValues) {
660 return build(odsBuilder, odsState,
661 om::ClassType::get(
662 odsBuilder.getContext(),
663 mlir::FlatSymbolRefAttr::get(classOp.getSymNameAttr())),
664 mlir::FlatSymbolRefAttr::get(classOp.getSymNameAttr()),
665 fieldValues);
666}
667
668LogicalResult circt::om::ElaboratedObjectOp::verifySymbolUses(
669 SymbolTableCollection &symbolTable) {
670 auto classDef =
671 verifyClassLikeSymbolUser((*this), symbolTable, getResult().getType(),
672 getClassNameAttr().getAttr());
673 if (failed(classDef))
674 return failure();
675
676 auto fieldNames = classDef->getFieldNames();
677 auto fieldValues = getFieldValues();
678 if (fieldValues.size() != fieldNames.size())
679 return emitOpError("field value list doesn't match class field list, "
680 "expected ")
681 << fieldNames.size() << " values but got " << fieldValues.size();
682
683 for (auto [fieldName, fieldValue] : llvm::zip(fieldNames, fieldValues)) {
684 Type expectedType =
685 classDef->getFieldType(cast<StringAttr>(fieldName)).value();
686 if (fieldValue.getType() != expectedType)
687 return emitOpError("field value type for ")
688 << cast<StringAttr>(fieldName) << " (" << fieldValue.getType()
689 << ") doesn't match class field type (" << expectedType << ')';
690 }
691
692 return success();
693}
694
695//===----------------------------------------------------------------------===//
696// ConstantOp
697//===----------------------------------------------------------------------===//
698
699void circt::om::ConstantOp::build(::mlir::OpBuilder &odsBuilder,
700 ::mlir::OperationState &odsState,
701 ::mlir::TypedAttr constVal) {
702 return build(odsBuilder, odsState, constVal.getType(), constVal);
703}
704
705OpFoldResult circt::om::ConstantOp::fold(FoldAdaptor adaptor) {
706 assert(adaptor.getOperands().empty() && "constant has no operands");
707 return getValueAttr();
708}
709
710//===----------------------------------------------------------------------===//
711// RegistryInsertOp
712//===----------------------------------------------------------------------===//
713
714LogicalResult RegistryInsertOp::canonicalize(RegistryInsertOp op,
715 PatternRewriter &rewriter) {
716 auto allocation = op.getRegistry().getDefiningOp<RegistryCreateOp>();
717 if (!allocation)
718 return failure();
719 // Collect all known insertions at once. Rewriting them individually would
720 // repeatedly put the growing allocation on the greedy driver's worklist.
721 SmallVector<RegistryInsertOp> insertions;
722 SmallVector<Value> elements;
723 for (auto &use : allocation.getResult().getUses()) {
724 auto insertion = dyn_cast<RegistryInsertOp>(use.getOwner());
725 if (!insertion || insertion.getRegistry() != allocation.getResult())
726 continue;
727 insertions.push_back(insertion);
728 elements.push_back(insertion.getElement());
729 }
730 rewriter.modifyOpInPlace(
731 allocation, [&] { allocation.getElementsMutable().append(elements); });
732 for (auto insertion : insertions)
733 rewriter.eraseOp(insertion);
734 return success();
735}
736
737//===----------------------------------------------------------------------===//
738// ListCreateOp
739//===----------------------------------------------------------------------===//
740
741OpFoldResult circt::om::ListCreateOp::fold(FoldAdaptor adaptor) {
742 auto inputs = adaptor.getInputs();
743 if (!llvm::all_of(inputs, [](Attribute attr) { return attr; }))
744 return {};
745
746 return ListAttr::get(getContext(), getType().getElementType(),
747 ArrayAttr::get(getContext(), inputs));
748}
749
750void circt::om::ListCreateOp::print(OpAsmPrinter &p) {
751 p << " ";
752 p.printOperands(getInputs());
753 p.printOptionalAttrDict((*this)->getAttrs());
754 p << " : " << getType().getElementType();
755}
756
757ParseResult circt::om::ListCreateOp::parse(OpAsmParser &parser,
758 OperationState &result) {
759 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
760 Type elemType;
761
762 if (parser.parseOperandList(operands) ||
763 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
764 parser.parseType(elemType))
765 return failure();
766 result.addTypes({circt::om::ListType::get(elemType)});
767
768 for (auto operand : operands)
769 if (parser.resolveOperand(operand, elemType, result.operands))
770 return failure();
771 return success();
772}
773
774//===----------------------------------------------------------------------===//
775// ListConcatOp
776//===----------------------------------------------------------------------===//
777
778OpFoldResult circt::om::ListConcatOp::fold(FoldAdaptor adaptor) {
779 auto subLists = adaptor.getSubLists();
780 if (subLists.size() == 1)
781 return getSubLists().front();
782
783 SmallVector<Attribute> elements;
784 for (Attribute attr : subLists) {
785 auto listAttr = dyn_cast_or_null<ListAttr>(attr);
786 if (!listAttr)
787 return {};
788 llvm::append_range(elements, listAttr.getElements());
789 }
790
791 return ListAttr::get(getContext(), getType().getElementType(),
792 ArrayAttr::get(getContext(), elements));
793}
794
795namespace {
796/// Concatenate constructed lists into a single list_create.
797struct ConcatListCreates : OpRewritePattern<ListConcatOp> {
798 using Base::Base;
799
800 LogicalResult matchAndRewrite(ListConcatOp concat,
801 PatternRewriter &rewriter) const override {
802 SmallVector<Value> inputs;
803 for (auto element : concat.getSubLists()) {
804 if (auto create = element.getDefiningOp<ListCreateOp>()) {
805 llvm::append_range(inputs, create.getInputs());
806 continue;
807 }
808
809 // Drop empty constant lists, since these may have been folded to
810 // constants. Reject any other elements.
811 ListAttr attr;
812 if (auto constant = element.getDefiningOp<ConstantOp>())
813 attr = dyn_cast<ListAttr>(constant.getValue());
814 if (!attr || !attr.getElements().empty())
815 return failure();
816 }
817
818 rewriter.replaceOpWithNewOp<ListCreateOp>(concat, concat.getType(), inputs);
819 return success();
820 }
821};
822} // namespace
823
824void ListConcatOp::getCanonicalizationPatterns(RewritePatternSet &results,
825 MLIRContext *context) {
826 results.insert<ConcatListCreates>(context);
827}
828
829//===----------------------------------------------------------------------===//
830// ListLengthOp
831//===----------------------------------------------------------------------===//
832
833OpFoldResult ListLengthOp::fold(FoldAdaptor adaptor) {
834 uint64_t length;
835 if (auto listCreate = getList().getDefiningOp<ListCreateOp>())
836 length = listCreate.getInputs().size();
837 else if (auto listAttr = dyn_cast_or_null<ListAttr>(adaptor.getList()))
838 length = listAttr.getElements().size();
839 else
840 return {};
841
842 return circt::om::IntegerAttr::get(
843 getContext(),
844 mlir::IntegerAttr::get(getContext(),
845 APSInt(APInt(64, length), /*isUnsigned=*/false)));
846}
847
848//===----------------------------------------------------------------------===//
849// OptionCreateOp
850//===----------------------------------------------------------------------===//
851
852LogicalResult OptionCreateOp::canonicalize(OptionCreateOp op,
853 PatternRewriter &rewriter) {
854 auto value = op.getValue();
855 // option_create(unknown) -> unknown
856 if (value && value.getDefiningOp<UnknownValueOp>()) {
857 rewriter.replaceOpWithNewOp<UnknownValueOp>(op, op.getType());
858 return success();
859 }
860 return failure();
861}
862
863//===----------------------------------------------------------------------===//
864// OptionGetOrElseOp
865//===----------------------------------------------------------------------===//
866
867OpFoldResult OptionGetOrElseOp::fold(FoldAdaptor adaptor) {
868 auto option = getOption().getDefiningOp<OptionCreateOp>();
869 if (!option)
870 return {};
871 return option.getValue() ? option.getValue() : getDefaultValue();
872}
873
874//===----------------------------------------------------------------------===//
875// BasePathCreateOp
876//===----------------------------------------------------------------------===//
877
878LogicalResult
879BasePathCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
880 auto hierPath = symbolTable.lookupNearestSymbolFrom<hw::HierPathOp>(
881 *this, getTargetAttr());
882 if (!hierPath)
883 return emitOpError("invalid symbol reference");
884 return success();
885}
886
887//===----------------------------------------------------------------------===//
888// PathCreateOp
889//===----------------------------------------------------------------------===//
890
891LogicalResult
892PathCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
893 auto hierPath = symbolTable.lookupNearestSymbolFrom<hw::HierPathOp>(
894 *this, getTargetAttr());
895 if (!hierPath)
896 return emitOpError("invalid symbol reference");
897 return success();
898}
899
900//===----------------------------------------------------------------------===//
901// AnyCastOp
902//===----------------------------------------------------------------------===//
903
904OpFoldResult AnyCastOp::fold(FoldAdaptor adaptor) {
905 if (getInput().getType() == getType() && getInput() != getResult())
906 return getInput();
907 return {};
908}
909
910//===----------------------------------------------------------------------===//
911// IntegerBinaryOp (arithmetic)
912//===----------------------------------------------------------------------===//
913
914static APSInt getAPSIntForOMIntegerAttr(circt::om::IntegerAttr attr) {
915 auto value = attr.getValue();
916 if (value.getType().isSignedInteger())
917 return value.getAPSInt();
918
919 // OM integers use signed semantics, but their underlying IntegerAttr may be
920 // signless. Construct an APSInt with signed interpretation explicitly instead
921 // of calling IntegerAttr::getAPSInt(), which asserts for signless integers.
922 return APSInt(value.getValue(), /*isUnsigned=*/false);
923}
924
926 llvm::function_ref<FailureOr<APSInt>(const APSInt &, const APSInt &)>;
927
928static OpFoldResult foldIntegerBinaryArithmetic(Attribute lhsAttr,
929 Attribute rhsAttr,
930 IntegerBinaryFn evaluate) {
931 auto lhs = dyn_cast_or_null<circt::om::IntegerAttr>(lhsAttr);
932 auto rhs = dyn_cast_or_null<circt::om::IntegerAttr>(rhsAttr);
933 if (!lhs || !rhs)
934 return {};
935 // Extend values if necessary to match bitwidth. Most interesting arithmetic
936 // on APSInt asserts that both operands are the same bitwidth, but the
937 // IntegerAttrs we are working with may have used the smallest necessary
938 // bitwidth to represent the number they hold, and won't necessarily match.
939 APSInt lhsVal = getAPSIntForOMIntegerAttr(lhs);
940 APSInt rhsVal = getAPSIntForOMIntegerAttr(rhs);
941 if (lhsVal.getBitWidth() > rhsVal.getBitWidth())
942 rhsVal = rhsVal.extend(lhsVal.getBitWidth());
943 else if (rhsVal.getBitWidth() > lhsVal.getBitWidth())
944 lhsVal = lhsVal.extend(rhsVal.getBitWidth());
945
946 // Perform arbitrary precision signed integer binary arithmetic.
947 auto result = evaluate(lhsVal, rhsVal);
948 if (failed(result))
949 return {};
950
951 // Return the result as a new om::IntegerAttr.
952 auto *ctx = lhsAttr.getContext();
953 return circt::om::IntegerAttr::get(
954 ctx, mlir::IntegerAttr::get(ctx, result.value()));
955}
956
957//===----------------------------------------------------------------------===//
958// IntegerAddOp
959//===----------------------------------------------------------------------===//
960
961OpFoldResult IntegerAddOp::fold(FoldAdaptor adaptor) {
963 adaptor.getLhs(), adaptor.getRhs(),
964 [](const APSInt &lhs, const APSInt &rhs) { return success(lhs + rhs); });
965}
966
967//===----------------------------------------------------------------------===//
968// IntegerMulOp
969//===----------------------------------------------------------------------===//
970
971OpFoldResult IntegerMulOp::fold(FoldAdaptor adaptor) {
973 adaptor.getLhs(), adaptor.getRhs(),
974 [](const APSInt &lhs, const APSInt &rhs) { return success(lhs * rhs); });
975}
976
977//===----------------------------------------------------------------------===//
978// IntegerShrOp
979//===----------------------------------------------------------------------===//
980
981OpFoldResult IntegerShrOp::fold(FoldAdaptor adaptor) {
983 adaptor.getLhs(), adaptor.getRhs(),
984 [&](const APSInt &lhs, const APSInt &rhs) -> FailureOr<APSInt> {
985 // Check non-negative constraint from operation semantics.
986 if (!rhs.isNonNegative())
987 return (emitOpError("shift amount must be non-negative"), failure());
988 // Check size constraint from implementation detail of using
989 // getExtValue.
990 if (!rhs.isRepresentableByInt64())
991 return (emitOpError("shift amount must be representable in 64 bits"),
992 failure());
993 return success(lhs >> rhs.getExtValue());
994 });
995}
996
997//===----------------------------------------------------------------------===//
998// IntegerShlOp
999//===----------------------------------------------------------------------===//
1000
1001OpFoldResult IntegerShlOp::fold(FoldAdaptor adaptor) {
1003 adaptor.getLhs(), adaptor.getRhs(),
1004 [&](const APSInt &lhs, const APSInt &rhs) -> FailureOr<APSInt> {
1005 // Check non-negative constraint from operation semantics.
1006 if (!rhs.isNonNegative())
1007 return (emitOpError("shift amount must be non-negative"), failure());
1008 // Check size constraint from implementation detail of using
1009 // getExtValue.
1010 if (!rhs.isRepresentableByInt64())
1011 return (emitOpError("shift amount must be representable in 64 bits"),
1012 failure());
1013 int64_t shiftAmt = rhs.getExtValue();
1014 // Extend lhs to lhsWidth + shiftAmt bits so no bits are truncated.
1015 return success(lhs.extend(lhs.getBitWidth() + shiftAmt) << shiftAmt);
1016 });
1017}
1018
1019//===----------------------------------------------------------------------===//
1020// IntegerBitAndOp
1021//===----------------------------------------------------------------------===//
1022
1023OpFoldResult IntegerBitAndOp::fold(FoldAdaptor adaptor) {
1025 adaptor.getLhs(), adaptor.getRhs(),
1026 [](const APSInt &lhs, const APSInt &rhs) { return success(lhs & rhs); });
1027}
1028
1029//===----------------------------------------------------------------------===//
1030// IntegerBitOrOp
1031//===----------------------------------------------------------------------===//
1032
1033OpFoldResult IntegerBitOrOp::fold(FoldAdaptor adaptor) {
1035 adaptor.getLhs(), adaptor.getRhs(),
1036 [](const APSInt &lhs, const APSInt &rhs) { return success(lhs | rhs); });
1037}
1038
1039//===----------------------------------------------------------------------===//
1040// IntegerBitNotOp
1041//===----------------------------------------------------------------------===//
1042
1043OpFoldResult IntegerBitNotOp::fold(FoldAdaptor adaptor) {
1044 auto input = dyn_cast_or_null<circt::om::IntegerAttr>(adaptor.getInput());
1045 if (!input)
1046 return {};
1047
1048 APSInt result = ~getAPSIntForOMIntegerAttr(input);
1049 return circt::om::IntegerAttr::get(
1050 getContext(), mlir::IntegerAttr::get(getContext(), result));
1051}
1052
1053//===----------------------------------------------------------------------===//
1054// StringConcatOp
1055//===----------------------------------------------------------------------===//
1056
1057OpFoldResult StringConcatOp::fold(FoldAdaptor adaptor) {
1058 // Fold single-operand concat to just the operand.
1059 if (getStrings().size() == 1) {
1060 if (auto strAttr = adaptor.getStrings()[0])
1061 return strAttr;
1062
1063 return getStrings()[0];
1064 }
1065
1066 // Check if all operands are constant strings before accumulating.
1067 if (!llvm::all_of(adaptor.getStrings(), [](Attribute operand) {
1068 return isa_and_nonnull<StringAttr>(operand);
1069 }))
1070 return {};
1071
1072 // All operands are constant strings, concatenate them.
1073 SmallString<64> result;
1074 for (auto operand : adaptor.getStrings())
1075 result += cast<StringAttr>(operand).getValue();
1076
1077 return StringAttr::get(result, getResult().getType());
1078}
1079
1080namespace {
1081/// Flatten nested string.concat operations into a single concat.
1082/// string.concat(a, string.concat(b, c), d) -> string.concat(a, b, c, d)
1083class FlattenOMStringConcat : public mlir::OpRewritePattern<StringConcatOp> {
1084public:
1085 using OpRewritePattern::OpRewritePattern;
1086
1087 LogicalResult
1088 matchAndRewrite(StringConcatOp concat,
1089 mlir::PatternRewriter &rewriter) const override {
1090
1091 // Check if any operands are nested concats with a single use. Only inline
1092 // single-use nested concats to avoid fighting with DCE.
1093 bool hasNestedConcat = llvm::any_of(concat.getStrings(), [](Value operand) {
1094 auto nestedConcat = operand.getDefiningOp<StringConcatOp>();
1095 return nestedConcat && operand.hasOneUse();
1096 });
1097
1098 if (!hasNestedConcat)
1099 return failure();
1100
1101 // Flatten nested concats that have a single use.
1102 SmallVector<Value> flatOperands;
1103 for (auto input : concat.getStrings()) {
1104 if (auto nestedConcat = input.getDefiningOp<StringConcatOp>();
1105 nestedConcat && input.hasOneUse())
1106 llvm::append_range(flatOperands, nestedConcat.getStrings());
1107 else
1108 flatOperands.push_back(input);
1109 }
1110
1111 rewriter.modifyOpInPlace(concat,
1112 [&]() { concat->setOperands(flatOperands); });
1113 return success();
1114 }
1115};
1116
1117/// Merge consecutive constant strings in a concat and remove empty strings.
1118/// string.concat("a", "b", x, "", "c", "d") -> string.concat("ab", x, "cd")
1119class MergeAdjacentOMStringConstants
1120 : public mlir::OpRewritePattern<StringConcatOp> {
1121public:
1122 using OpRewritePattern::OpRewritePattern;
1123
1124 LogicalResult
1125 matchAndRewrite(StringConcatOp concat,
1126 mlir::PatternRewriter &rewriter) const override {
1127
1128 SmallVector<Value> newOperands;
1129 SmallString<64> accumulatedLit;
1130 SmallVector<ConstantOp> accumulatedOps;
1131 bool changed = false;
1132
1133 auto flushLiterals = [&]() {
1134 if (accumulatedOps.empty())
1135 return;
1136
1137 // If only one literal, reuse it.
1138 if (accumulatedOps.size() == 1) {
1139 newOperands.push_back(accumulatedOps[0]);
1140 } else {
1141 // Multiple literals - merge them.
1142 auto newLit = rewriter.createOrFold<ConstantOp>(
1143 concat.getLoc(),
1144 StringAttr::get(accumulatedLit, concat.getResult().getType()));
1145 newOperands.push_back(newLit);
1146 changed = true;
1147 }
1148 accumulatedLit.clear();
1149 accumulatedOps.clear();
1150 };
1151
1152 for (auto operand : concat.getStrings()) {
1153 if (auto litOp = operand.getDefiningOp<ConstantOp>()) {
1154 if (auto strAttr = dyn_cast<StringAttr>(litOp.getValue())) {
1155 // Skip empty strings.
1156 if (strAttr.getValue().empty()) {
1157 changed = true;
1158 continue;
1159 }
1160 accumulatedLit += strAttr.getValue();
1161 accumulatedOps.push_back(litOp);
1162 continue;
1163 }
1164 }
1165
1166 flushLiterals();
1167 newOperands.push_back(operand);
1168 }
1169
1170 // Flush any remaining literals.
1171 flushLiterals();
1172
1173 if (!changed)
1174 return failure();
1175
1176 // If no operands remain, replace with empty string.
1177 if (newOperands.empty())
1178 return rewriter.replaceOpWithNewOp<ConstantOp>(
1179 concat, StringAttr::get("", concat.getResult().getType())),
1180 success();
1181
1182 // Single-operand case is handled by the folder.
1183 rewriter.modifyOpInPlace(concat,
1184 [&]() { concat->setOperands(newOperands); });
1185 return success();
1186 }
1187};
1188
1189} // namespace
1190
1191void StringConcatOp::getCanonicalizationPatterns(RewritePatternSet &results,
1192 MLIRContext *context) {
1193 results.insert<FlattenOMStringConcat, MergeAdjacentOMStringConstants>(
1194 context);
1195}
1196
1197//===----------------------------------------------------------------------===//
1198// PropEqOp
1199//===----------------------------------------------------------------------===//
1200
1201static FailureOr<mlir::Attribute>
1202evaluateBinaryEquality(mlir::Attribute lhsAttr, mlir::Attribute rhsAttr) {
1203 auto resultType = mlir::IntegerType::get(lhsAttr.getContext(), 1);
1204
1205 // String equality.
1206 if (auto lhs = dyn_cast<mlir::StringAttr>(lhsAttr))
1207 if (auto rhs = dyn_cast<mlir::StringAttr>(rhsAttr))
1208 return mlir::Attribute(
1209 mlir::IntegerAttr::get(resultType, lhs == rhs ? 1 : 0));
1210
1211 // OM integer equality (arbitrary precision).
1212 if (auto lhs = dyn_cast<circt::om::IntegerAttr>(lhsAttr))
1213 if (auto rhs = dyn_cast<circt::om::IntegerAttr>(rhsAttr)) {
1214 APSInt lhsVal = getAPSIntForOMIntegerAttr(lhs);
1215 APSInt rhsVal = getAPSIntForOMIntegerAttr(rhs);
1216 if (lhsVal.getBitWidth() > rhsVal.getBitWidth())
1217 rhsVal = rhsVal.extend(lhsVal.getBitWidth());
1218 else if (rhsVal.getBitWidth() > lhsVal.getBitWidth())
1219 lhsVal = lhsVal.extend(rhsVal.getBitWidth());
1220 return mlir::Attribute(
1221 mlir::IntegerAttr::get(resultType, lhsVal == rhsVal ? 1 : 0));
1222 }
1223
1224 // Boolean (i1) equality.
1225 if (auto lhs = dyn_cast<mlir::IntegerAttr>(lhsAttr))
1226 if (auto rhs = dyn_cast<mlir::IntegerAttr>(rhsAttr))
1227 return mlir::Attribute(
1228 mlir::IntegerAttr::get(resultType, lhs == rhs ? 1 : 0));
1229
1230 return failure();
1231}
1232
1233/// Look through identity-preserving class-to-any casts.
1234static Value getObjectReference(Value value) {
1235 if (auto cast = value.getDefiningOp<AnyCastOp>();
1236 cast && isa<ClassType>(cast.getInput().getType()))
1237 return cast.getInput();
1238 return value;
1239}
1240
1241/// Compare SSA identities, looking through class-to-any casts. Identical values
1242/// prove equality for all types; distinct elaborated allocations prove
1243/// inequality. Otherwise, return std::nullopt.
1244static std::optional<bool> evaluateIdentityEquality(Value lhs, Value rhs) {
1245 lhs = getObjectReference(lhs);
1246 rhs = getObjectReference(rhs);
1247 if (lhs == rhs)
1248 return true;
1249 if (lhs.getDefiningOp<ElaboratedObjectOp>() &&
1250 rhs.getDefiningOp<ElaboratedObjectOp>())
1251 return false;
1252 return std::nullopt;
1253}
1254
1255OpFoldResult PropEqOp::fold(FoldAdaptor adaptor) {
1256 if (isa<ClassType, AnyType>(getLhs().getType())) {
1257 if (auto equal = evaluateIdentityEquality(getLhs(), getRhs()))
1258 return mlir::IntegerAttr::get(getType(), *equal);
1259
1260 auto lhs = getObjectReference(getLhs());
1261 auto rhs = getObjectReference(getRhs());
1262
1263 // Peel class-to-any casts only if both resulting operand types match.
1264 // Peeling just one cast, or casts from different classes, is invalid.
1265 if (lhs.getType() == rhs.getType() &&
1266 (lhs != getLhs() || rhs != getRhs())) {
1267 getLhsMutable().assign(lhs);
1268 getRhsMutable().assign(rhs);
1269 return getResult();
1270 }
1271 return {};
1272 }
1273
1274 // Primitive equality is by value, not SSA identity. In particular, comparing
1275 // an unknown primitive with itself must remain unknown.
1276 auto lhsAttr = adaptor.getLhs();
1277 auto rhsAttr = adaptor.getRhs();
1278 if (!lhsAttr || !rhsAttr)
1279 return {};
1280
1281 auto result = evaluateBinaryEquality(lhsAttr, rhsAttr);
1282 if (failed(result))
1283 return {};
1284
1285 return *result;
1286}
1287
1288//===----------------------------------------------------------------------===//
1289// ListContainsOp
1290//===----------------------------------------------------------------------===//
1291
1292OpFoldResult ListContainsOp::fold(FoldAdaptor adaptor) {
1293 if (auto listCreate = getList().getDefiningOp<ListCreateOp>()) {
1294 bool allKnown = true;
1295 for (auto candidate : listCreate.getInputs()) {
1296 auto equal = evaluateIdentityEquality(candidate, getElement());
1297 if (equal && *equal)
1298 return mlir::IntegerAttr::get(getResult().getType(), 1);
1299 // Continue past unknown comparisons. A later candidate may still match.
1300 allKnown &= equal.has_value();
1301 }
1302 // This also covers empty lists, even with an unknown search value.
1303 if (allKnown)
1304 return mlir::IntegerAttr::get(getResult().getType(), 0);
1305 }
1306
1307 auto listAttr = dyn_cast_or_null<ListAttr>(adaptor.getList());
1308 if (!listAttr)
1309 return {};
1310 if (listAttr.getElements().empty())
1311 return mlir::IntegerAttr::get(getResult().getType(), 0);
1312
1313 // Both the nonempty list and element must fold to constant attributes.
1314 Attribute elementAttr = adaptor.getElement();
1315 if (!elementAttr)
1316 return {};
1317
1318 for (Attribute candidate : listAttr.getElements()) {
1319 auto equality = evaluateBinaryEquality(candidate, elementAttr);
1320 if (failed(equality))
1321 return {};
1322 if (!cast<mlir::IntegerAttr>(*equality).getValue().isZero())
1323 return mlir::IntegerAttr::get(getResult().getType(), 1);
1324 }
1325
1326 return mlir::IntegerAttr::get(getResult().getType(), 0);
1327}
1328
1329//===----------------------------------------------------------------------===//
1330// IntegerAndOp / IntegerOrOp / IntegerXorOp
1331//===----------------------------------------------------------------------===//
1332
1333static OpFoldResult foldIntegerBitwise(Attribute lhsAttr, Attribute rhsAttr,
1334 IntegerBinaryFn evaluate) {
1335 auto lhsInt = dyn_cast_or_null<mlir::IntegerAttr>(lhsAttr);
1336 auto rhsInt = dyn_cast_or_null<mlir::IntegerAttr>(rhsAttr);
1337 if (!lhsInt || !rhsInt)
1338 return {};
1339 APSInt lhsVal(lhsInt.getValue());
1340 APSInt rhsVal(rhsInt.getValue());
1341 auto result = evaluate(lhsVal, rhsVal);
1342 if (failed(result))
1343 return {};
1344 return mlir::IntegerAttr::get(
1345 lhsInt.getType(), result->extOrTrunc(lhsInt.getValue().getBitWidth()));
1346}
1347
1348// Returns true if attr is an IntegerAttr whose value is all-zeros.
1349static bool isZeroInt(Attribute a) {
1350 auto i = dyn_cast_or_null<mlir::IntegerAttr>(a);
1351 return i && i.getValue().isZero();
1352}
1353
1354// Returns true if attr is an IntegerAttr whose value is all-ones.
1355static bool isAllOnesInt(Attribute a) {
1356 auto i = dyn_cast_or_null<mlir::IntegerAttr>(a);
1357 return i && i.getValue().isAllOnes();
1358}
1359
1360OpFoldResult IntegerAndOp::fold(FoldAdaptor adaptor) {
1361 if (auto result = foldIntegerBitwise(
1362 adaptor.getLhs(), adaptor.getRhs(),
1363 [](const APSInt &lhs, const APSInt &rhs) {
1364 return success(APSInt(lhs & rhs, /*isUnsigned=*/false));
1365 }))
1366 return result;
1367 // AND with all-zeros is always zero.
1368 if (isZeroInt(adaptor.getLhs()) || isZeroInt(adaptor.getRhs()))
1369 return mlir::IntegerAttr::get(getResult().getType(),
1370 APInt::getZero(getType().getWidth()));
1371 // AND with all-ones is identity.
1372 if (isAllOnesInt(adaptor.getLhs()))
1373 return getRhs();
1374 if (isAllOnesInt(adaptor.getRhs()))
1375 return getLhs();
1376 return {};
1377}
1378
1379OpFoldResult IntegerOrOp::fold(FoldAdaptor adaptor) {
1380 if (auto result = foldIntegerBitwise(
1381 adaptor.getLhs(), adaptor.getRhs(),
1382 [](const APSInt &lhs, const APSInt &rhs) {
1383 return success(APSInt(lhs | rhs, /*isUnsigned=*/false));
1384 }))
1385 return result;
1386 // OR with all-ones is always all-ones.
1387 if (isAllOnesInt(adaptor.getLhs()) || isAllOnesInt(adaptor.getRhs()))
1388 return mlir::IntegerAttr::get(getResult().getType(),
1389 APInt::getAllOnes(getType().getWidth()));
1390 // OR with all-zeros is identity.
1391 if (isZeroInt(adaptor.getLhs()))
1392 return getRhs();
1393 if (isZeroInt(adaptor.getRhs()))
1394 return getLhs();
1395 return {};
1396}
1397
1398OpFoldResult IntegerXorOp::fold(FoldAdaptor adaptor) {
1399 if (auto result = foldIntegerBitwise(
1400 adaptor.getLhs(), adaptor.getRhs(),
1401 [](const APSInt &lhs, const APSInt &rhs) {
1402 return success(APSInt(lhs ^ rhs, /*isUnsigned=*/false));
1403 }))
1404 return result;
1405 // XOR with all-zeros is identity.
1406 if (isZeroInt(adaptor.getLhs()))
1407 return getRhs();
1408 if (isZeroInt(adaptor.getRhs()))
1409 return getLhs();
1410 return {};
1411}
1412
1413//===----------------------------------------------------------------------===//
1414// UnknownValueOp
1415//===----------------------------------------------------------------------===//
1416
1417LogicalResult circt::om::UnknownValueOp::verifySymbolUses(
1418 SymbolTableCollection &symbolTable) {
1419
1420 // Unknown values of non-class type don't need to be verified.
1421 auto classType = dyn_cast<ClassType>(getType());
1422 if (!classType)
1423 return success();
1424
1425 // Verify the referred to ClassOp exists.
1426 auto className = classType.getClassName();
1427 if (symbolTable.lookupNearestSymbolFrom<ClassLike>(*this, className))
1428 return success();
1429
1430 return emitOpError() << "refers to non-existant class (\""
1431 << className.getValue() << "\")";
1432}
1433
1434//===----------------------------------------------------------------------===//
1435// TableGen generated logic.
1436//===----------------------------------------------------------------------===//
1437
1438#define GET_OP_CLASSES
1439#include "circt/Dialect/OM/OM.cpp.inc"
assert(baseType &&"element must be base type")
static SmallVector< T > concat(const SmallVectorImpl< T > &a, const SmallVectorImpl< T > &b)
Returns a new vector containing the concatenation of vectors a and b.
Definition CalyxOps.cpp:555
static std::unique_ptr< Context > context
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:193
false return failure()
Parse an optional keyword or string and set instance into 'result'.
return success()
static OpFoldResult foldIntegerBitwise(Attribute lhsAttr, Attribute rhsAttr, IntegerBinaryFn evaluate)
Definition OMOps.cpp:1333
static Value getObjectReference(Value value)
Look through identity-preserving class-to-any casts.
Definition OMOps.cpp:1234
LogicalResult verifyClassLike(ClassLike classLike)
Definition OMOps.cpp:248
std::optional< Type > getClassLikeFieldType(ClassLike classLike, StringAttr name)
Definition OMOps.cpp:287
void getClassLikeAsmBlockArgumentNames(ClassLike classLike, Region &region, OpAsmSetValueNameFn setNameFn)
Definition OMOps.cpp:265
static ParseResult parseBasePathString(OpAsmParser &parser, PathAttr &path)
Definition OMOps.cpp:28
static ParseResult parsePathString(OpAsmParser &parser, PathAttr &path, StringAttr &module, StringAttr &ref, StringAttr &field)
Definition OMOps.cpp:50
static APSInt getAPSIntForOMIntegerAttr(circt::om::IntegerAttr attr)
Definition OMOps.cpp:914
static void printBasePathString(OpAsmPrinter &p, Operation *op, PathAttr path)
Definition OMOps.cpp:39
llvm::function_ref< FailureOr< APSInt >(const APSInt &, const APSInt &)> IntegerBinaryFn
Definition OMOps.cpp:925
static FailureOr< ClassLike > verifyClassLikeSymbolUser(Operation *op, SymbolTableCollection &symbolTable, ClassType resultType, StringAttr className)
Definition OMOps.cpp:571
static void printFieldLocs(OpAsmPrinter &printer, Operation *op, ArrayAttr fieldLocs)
Definition OMOps.cpp:89
static bool isZeroInt(Attribute a)
Definition OMOps.cpp:1349
static ParseResult parseFieldLocs(OpAsmParser &parser, ArrayAttr &fieldLocs)
Definition OMOps.cpp:79
static ParseResult parseClassFieldsList(OpAsmParser &parser, SmallVectorImpl< Attribute > &fieldNames, SmallVectorImpl< Type > &fieldTypes)
Definition OMOps.cpp:102
static FailureOr< mlir::Attribute > evaluateBinaryEquality(mlir::Attribute lhsAttr, mlir::Attribute rhsAttr)
Definition OMOps.cpp:1202
static void printClassLike(ClassLike classLike, OpAsmPrinter &printer)
Definition OMOps.cpp:192
void replaceClassLikeFieldTypes(ClassLike classLike, AttrTypeReplacer &replacer)
Definition OMOps.cpp:297
static std::optional< bool > evaluateIdentityEquality(Value lhs, Value rhs)
Compare SSA identities, looking through class-to-any casts.
Definition OMOps.cpp:1244
NamedAttribute makeFieldType(StringAttr name, Type type)
Definition OMOps.cpp:277
NamedAttribute makeFieldIdx(MLIRContext *ctx, mlir::StringAttr name, unsigned i)
Definition OMOps.cpp:281
static void printPathString(OpAsmPrinter &p, Operation *op, PathAttr path, StringAttr module, StringAttr ref, StringAttr field)
Definition OMOps.cpp:64
static ParseResult parseClassLike(OpAsmParser &parser, OperationState &state)
Definition OMOps.cpp:135
static OpFoldResult foldIntegerBinaryArithmetic(Attribute lhsAttr, Attribute rhsAttr, IntegerBinaryFn evaluate)
Definition OMOps.cpp:928
static bool isAllOnesInt(Attribute a)
Definition OMOps.cpp:1355
static Block * getBodyBlock(FModuleLike mod)
static InstancePath empty
uint64_t getWidth(Type t)
Definition ESIPasses.cpp:30
void error(Twine message)
Definition LSPUtils.cpp:16
ParseResult parsePath(MLIRContext *context, StringRef spelling, PathAttr &path, StringAttr &module, StringAttr &ref, StringAttr &field)
Parse a target string in to a path.
Definition OMUtils.cpp:182
ParseResult parseBasePath(MLIRContext *context, StringRef spelling, PathAttr &path)
Parse a target string of the form "Foo/bar:Bar/baz" in to a base path.
Definition OMUtils.cpp:177
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
Definition LLVM.h:190
A module name, and the name of an instance inside that module.
mlir::StringAttr module
mlir::StringAttr instance