16#include "mlir/IR/Builders.h"
17#include "mlir/IR/ImplicitLocOpBuilder.h"
18#include "llvm/ADT/STLExtras.h"
28 auto *
context = parser.getContext();
29 auto loc = parser.getCurrentLocation();
31 if (parser.parseString(&rawPath))
34 return parser.emitError(loc,
"invalid base path");
43 p << elt.module.getValue() <<
'/' << elt.
instance.getValue();
50 StringAttr &module, StringAttr &ref,
53 auto *
context = parser.getContext();
54 auto loc = parser.getCurrentLocation();
56 if (parser.parseString(&rawPath))
59 return parser.emitError(loc,
"invalid path");
64 StringAttr module, StringAttr ref,
67 for (
const auto &elt : path)
68 p << elt.module.getValue() <<
'/' << elt.instance.getValue() <<
':';
69 if (!module.getValue().empty())
70 p << module.getValue();
71 if (!ref.getValue().empty())
72 p <<
'>' << ref.getValue();
73 if (!field.getValue().empty())
74 p << field.getValue();
78static ParseResult
parseFieldLocs(OpAsmParser &parser, ArrayAttr &fieldLocs) {
79 if (parser.parseOptionalKeyword(
"field_locs"))
81 if (parser.parseLParen() || parser.parseAttribute(fieldLocs) ||
82 parser.parseRParen()) {
89 ArrayAttr fieldLocs) {
90 mlir::OpPrintingFlags flags;
91 if (!flags.shouldPrintDebugInfo() || !fieldLocs)
93 printer <<
"field_locs(";
94 printer.printAttribute(fieldLocs);
102 SmallVectorImpl<Attribute> &fieldNames,
103 SmallVectorImpl<Type> &fieldTypes) {
105 llvm::StringMap<SMLoc> nameLocMap;
106 auto parseElt = [&]() -> ParseResult {
108 std::string fieldName;
109 if (parser.parseKeywordOrString(&fieldName))
111 SMLoc currLoc = parser.getCurrentLocation();
112 if (nameLocMap.count(fieldName)) {
113 parser.emitError(currLoc,
"field \"")
114 << fieldName <<
"\" is defined twice";
115 parser.emitError(nameLocMap[fieldName]) <<
"previous definition is here";
118 nameLocMap[fieldName] = currLoc;
119 fieldNames.push_back(StringAttr::get(parser.getContext(), fieldName));
122 fieldTypes.emplace_back();
123 if (parser.parseColonType(fieldTypes.back()))
129 return parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
136 if (parser.parseSymbolName(symName, mlir::SymbolTable::getSymbolAttrName(),
141 SmallVector<OpAsmParser::Argument> args;
142 if (parser.parseArgumentList(args, OpAsmParser::Delimiter::Paren,
146 SmallVector<Type> fieldTypes;
147 SmallVector<Attribute> fieldNames;
148 if (succeeded(parser.parseOptionalArrow()))
152 SmallVector<NamedAttribute> fieldTypesMap;
153 if (!fieldNames.empty()) {
154 for (
auto [name, type] : zip(fieldNames, fieldTypes))
155 fieldTypesMap.push_back(
156 NamedAttribute(cast<StringAttr>(name), TypeAttr::get(type)));
158 auto *ctx = parser.getContext();
159 state.addAttribute(
"fieldNames", mlir::ArrayAttr::get(ctx, fieldNames));
160 state.addAttribute(
"fieldTypes",
161 mlir::DictionaryAttr::get(ctx, fieldTypesMap));
164 if (failed(parser.parseOptionalAttrDictWithKeyword(state.attributes)))
168 Region *region = state.addRegion();
169 if (parser.parseRegion(*region, args))
174 region->emplaceBlock();
177 auto argNames = llvm::map_range(args, [&](OpAsmParser::Argument arg) {
178 return StringAttr::get(parser.getContext(), arg.ssaName.name.drop_front());
182 ArrayAttr::get(parser.getContext(), SmallVector<Attribute>(argNames)));
190 printer << classLike.getSymName();
193 auto argNames = SmallVector<StringRef>(
194 classLike.getFormalParamNames().getAsValueRange<StringAttr>());
195 ArrayRef<BlockArgument> args = classLike.getBodyBlock()->getArguments();
199 for (
size_t i = 0, e = args.size(); i < e; ++i) {
200 printer <<
'%' << argNames[i] <<
": " << args[i].getType();
206 ArrayRef<Attribute> fieldNames =
207 cast<ArrayAttr>(classLike->getAttr(
"fieldNames")).getValue();
209 if (!fieldNames.empty()) {
211 for (
size_t i = 0, e = fieldNames.size(); i < e; ++i) {
214 StringAttr name = cast<StringAttr>(fieldNames[i]);
215 printer.printKeywordOrString(name.getValue());
217 Type type = classLike.getFieldType(name).value();
218 printer.printType(type);
224 SmallVector<StringRef> elidedAttrs{classLike.getSymNameAttrName(),
225 classLike.getFormalParamNamesAttrName(),
226 "fieldTypes",
"fieldNames"};
227 printer.printOptionalAttrDictWithKeyword(classLike.getOperation()->getAttrs(),
231 printer.printRegion(classLike.getBody(),
false,
237 if (classLike.getFormalParamNames().size() !=
238 classLike.getBodyBlock()->getArguments().size()) {
239 auto error = classLike.emitOpError(
240 "formal parameter name list doesn't match formal parameter value list");
241 error.attachNote(classLike.getLoc())
242 <<
"formal parameter names: " << classLike.getFormalParamNames();
243 error.attachNote(classLike.getLoc())
244 <<
"formal parameter values: "
245 << classLike.getBodyBlock()->getArguments();
255 auto argNames = SmallVector<StringRef>(
256 classLike.getFormalParamNames().getAsValueRange<StringAttr>());
257 ArrayRef<BlockArgument> args = classLike.getBodyBlock()->getArguments();
260 for (
size_t i = 0, e = args.size(); i < e; ++i)
261 setNameFn(args[i], argNames[i]);
265 return NamedAttribute(name, TypeAttr::get(type));
270 return NamedAttribute(StringAttr(name),
271 mlir::IntegerAttr::get(mlir::IndexType::get(ctx), i));
276 DictionaryAttr fieldTypes = mlir::cast<DictionaryAttr>(
277 classLike.getOperation()->getAttr(
"fieldTypes"));
278 Attribute type = fieldTypes.get(name);
281 return cast<TypeAttr>(type).getValue();
285 AttrTypeReplacer &replacer) {
286 classLike->setAttr(
"fieldTypes", cast<DictionaryAttr>(replacer.replace(
287 classLike.getFieldTypes())));
294ParseResult circt::om::ClassOp::parse(OpAsmParser &parser,
295 OperationState &state) {
299circt::om::ClassOp circt::om::ClassOp::buildSimpleClassOp(
300 OpBuilder &odsBuilder, Location loc, Twine name,
301 ArrayRef<StringRef> formalParamNames, ArrayRef<StringRef> fieldNames,
302 ArrayRef<Type> fieldTypes) {
303 circt::om::ClassOp classOp = circt::om::ClassOp::create(
304 odsBuilder, loc, odsBuilder.getStringAttr(name),
305 odsBuilder.getStrArrayAttr(formalParamNames),
306 odsBuilder.getStrArrayAttr(fieldNames),
307 odsBuilder.getDictionaryAttr(llvm::map_to_vector(
308 llvm::zip(fieldNames, fieldTypes), [&](
auto field) -> NamedAttribute {
309 return NamedAttribute(odsBuilder.getStringAttr(std::get<0>(field)),
310 TypeAttr::get(std::get<1>(field)));
312 Block *body = &classOp.getRegion().emplaceBlock();
313 auto prevLoc = odsBuilder.saveInsertionPoint();
314 odsBuilder.setInsertionPointToEnd(body);
316 mlir::SmallVector<Attribute> locAttrs(fieldNames.size(), LocationAttr(loc));
318 ClassFieldsOp::create(odsBuilder, loc,
319 llvm::map_to_vector(fieldTypes,
320 [&](Type type) -> Value {
321 return body->addArgument(type,
324 odsBuilder.getArrayAttr(locAttrs));
326 odsBuilder.restoreInsertionPoint(prevLoc);
331void circt::om::ClassOp::print(OpAsmPrinter &printer) {
335LogicalResult circt::om::ClassOp::verify() {
return verifyClassLike(*
this); }
337LogicalResult circt::om::ClassOp::verifyRegions() {
338 auto fieldsOp = cast<ClassFieldsOp>(this->
getBodyBlock()->getTerminator());
341 if (fieldsOp.getNumOperands() != this->getFieldNames().size()) {
342 auto diag = this->emitOpError()
343 <<
"returns '" << this->getFieldNames().size()
344 <<
"' fields, but its terminator returned '"
345 << fieldsOp.getNumOperands() <<
"' fields";
346 return diag.attachNote(fieldsOp.getLoc()) <<
"see terminator:";
350 auto types = this->getFieldTypes();
351 for (
auto [fieldName, terminatorOperandType] :
352 llvm::zip(this->getFieldNames(), fieldsOp.getOperandTypes())) {
354 if (terminatorOperandType ==
355 cast<TypeAttr>(types.get(cast<StringAttr>(fieldName))).getValue())
358 auto diag = this->emitOpError()
359 <<
"returns different field types than its terminator";
360 return diag.attachNote(fieldsOp.getLoc()) <<
"see terminator:";
366void circt::om::ClassOp::getAsmBlockArgumentNames(
371std::optional<mlir::Type>
372circt::om::ClassOp::getFieldType(mlir::StringAttr field) {
376void circt::om::ClassOp::replaceFieldTypes(AttrTypeReplacer replacer) {
380void circt::om::ClassOp::updateFields(
381 mlir::ArrayRef<mlir::Location> newLocations,
382 mlir::ArrayRef<mlir::Value> newValues,
383 mlir::ArrayRef<mlir::Attribute> newNames) {
385 auto fieldsOp = getFieldsOp();
386 assert(fieldsOp &&
"The fields op should exist");
388 SmallVector<Attribute> names(getFieldNamesAttr().getAsRange<StringAttr>());
390 SmallVector<NamedAttribute> fieldTypes(getFieldTypesAttr().getValue());
392 SmallVector<Value> fieldVals(fieldsOp.getFields());
394 Location fieldOpLoc = fieldsOp->getLoc();
397 SmallVector<Location> locations;
398 if (
auto fl = dyn_cast<FusedLoc>(fieldOpLoc)) {
399 auto metadataArr = dyn_cast<ArrayAttr>(fl.getMetadata());
400 assert(metadataArr &&
"Expected the metadata for the fused location");
401 auto r = metadataArr.getAsRange<LocationAttr>();
402 locations.append(r.begin(), r.end());
405 locations.append(names.size(), fieldOpLoc);
409 names.append(newNames.begin(), newNames.end());
410 locations.append(newLocations.begin(), newLocations.end());
411 fieldVals.append(newValues.begin(), newValues.end());
414 for (
auto [v, n] :
llvm::zip(newValues, newNames))
415 fieldTypes.emplace_back(
416 NamedAttribute(
llvm::cast<StringAttr>(n), TypeAttr::
get(v.getType())));
419 SmallVector<Attribute> locationsAttr;
420 llvm::for_each(locations, [&](Location &l) {
421 locationsAttr.push_back(cast<Attribute>(l));
424 ImplicitLocOpBuilder builder(
getLoc(), *
this);
426 setFieldNamesAttr(builder.getArrayAttr(names));
428 setFieldTypesAttr(builder.getDictionaryAttr(fieldTypes));
429 fieldsOp.getFieldsMutable().assign(fieldVals);
431 fieldsOp->setLoc(builder.getFusedLoc(
432 locations, ArrayAttr::get(getContext(), locationsAttr)));
435void circt::om::ClassOp::addNewFieldsOp(mlir::OpBuilder &builder,
436 mlir::ArrayRef<Location> locs,
437 mlir::ArrayRef<Value> values) {
440 assert(locs.size() == values.size() &&
"Expected a location per value");
441 mlir::SmallVector<Attribute> locAttrs;
442 for (
auto loc : locs) {
443 locAttrs.push_back(cast<Attribute>(LocationAttr(loc)));
447 ClassFieldsOp::create(builder, builder.getFusedLoc(locs), values,
448 builder.getArrayAttr(locAttrs));
451mlir::Location circt::om::ClassOp::getFieldLocByIndex(
size_t i) {
452 auto fieldsOp = this->getFieldsOp();
453 auto fieldLocs = fieldsOp.getFieldLocs();
454 if (!fieldLocs.has_value())
455 return fieldsOp.getLoc();
456 assert(i < fieldLocs.value().size() &&
457 "field index too large for location array");
458 return cast<LocationAttr>(fieldLocs.value()[i]);
465ParseResult circt::om::ClassExternOp::parse(OpAsmParser &parser,
466 OperationState &state) {
470void circt::om::ClassExternOp::print(OpAsmPrinter &printer) {
474LogicalResult circt::om::ClassExternOp::verify() {
480 return this->emitOpError(
"external class body should be empty");
486void circt::om::ClassExternOp::getAsmBlockArgumentNames(
491std::optional<mlir::Type>
492circt::om::ClassExternOp::getFieldType(mlir::StringAttr field) {
496void circt::om::ClassExternOp::replaceFieldTypes(AttrTypeReplacer replacer) {
504LogicalResult circt::om::ClassFieldsOp::verify() {
505 auto fieldLocs = this->getFieldLocs();
506 if (fieldLocs.has_value()) {
507 auto fieldLocsVal = fieldLocs.value();
508 if (fieldLocsVal.size() != this->getFields().size()) {
509 auto error = this->emitOpError(
"size of field_locs (")
510 << fieldLocsVal.size()
511 <<
") does not match number of fields ("
512 << this->getFields().size() <<
")";
522void circt::om::ObjectOp::build(::mlir::OpBuilder &odsBuilder,
523 ::mlir::OperationState &odsState,
525 ::mlir::ValueRange actualParams) {
526 return build(odsBuilder, odsState,
527 om::ClassType::get(odsBuilder.getContext(),
528 mlir::FlatSymbolRefAttr::get(classOp)),
529 classOp.getNameAttr(), actualParams);
533circt::om::ObjectOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
535 StringAttr resultClassName = getResult().getType().getClassName().getAttr();
536 StringAttr className = getClassNameAttr();
537 if (resultClassName != className)
538 return emitOpError(
"result type (")
539 << resultClassName <<
") does not match referred to class ("
543 auto classDef = dyn_cast_or_null<ClassLike>(
544 symbolTable.lookupNearestSymbolFrom(*
this, className));
546 return emitOpError(
"refers to non-existant class (") << className <<
')';
548 auto actualTypes = getActualParams().getTypes();
549 auto formalTypes = classDef.getBodyBlock()->getArgumentTypes();
552 if (actualTypes.size() != formalTypes.size()) {
553 auto error = emitOpError(
554 "actual parameter list doesn't match formal parameter list");
555 error.attachNote(classDef.getLoc())
556 <<
"formal parameters: " << classDef.getBodyBlock()->getArguments();
557 error.attachNote(
getLoc()) <<
"actual parameters: " << getActualParams();
562 for (
size_t i = 0, e = actualTypes.size(); i < e; ++i) {
563 if (actualTypes[i] != formalTypes[i]) {
564 return emitOpError(
"actual parameter type (")
565 << actualTypes[i] <<
") doesn't match formal parameter type ("
566 << formalTypes[i] <<
')';
577void circt::om::ConstantOp::build(::mlir::OpBuilder &odsBuilder,
578 ::mlir::OperationState &odsState,
579 ::mlir::TypedAttr constVal) {
580 return build(odsBuilder, odsState, constVal.getType(), constVal);
583OpFoldResult circt::om::ConstantOp::fold(FoldAdaptor adaptor) {
584 assert(adaptor.getOperands().empty() &&
"constant has no operands");
585 return getValueAttr();
592void circt::om::ListCreateOp::print(OpAsmPrinter &p) {
594 p.printOperands(getInputs());
595 p.printOptionalAttrDict((*this)->getAttrs());
596 p <<
" : " << getType().getElementType();
599ParseResult circt::om::ListCreateOp::parse(OpAsmParser &parser,
600 OperationState &result) {
601 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
604 if (parser.parseOperandList(operands) ||
605 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
606 parser.parseType(elemType))
608 result.addTypes({circt::om::ListType::get(elemType)});
610 for (
auto operand : operands)
611 if (parser.resolveOperand(operand, elemType, result.operands))
621BasePathCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
622 auto hierPath = symbolTable.lookupNearestSymbolFrom<hw::HierPathOp>(
623 *
this, getTargetAttr());
625 return emitOpError(
"invalid symbol reference");
634PathCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
635 auto hierPath = symbolTable.lookupNearestSymbolFrom<hw::HierPathOp>(
636 *
this, getTargetAttr());
638 return emitOpError(
"invalid symbol reference");
646FailureOr<llvm::APSInt>
647IntegerAddOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
648 const llvm::APSInt &rhs) {
649 return success(lhs + rhs);
656FailureOr<llvm::APSInt>
657IntegerMulOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
658 const llvm::APSInt &rhs) {
659 return success(lhs * rhs);
666FailureOr<llvm::APSInt>
667IntegerShrOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
668 const llvm::APSInt &rhs) {
670 if (!rhs.isNonNegative())
671 return emitOpError(
"shift amount must be non-negative");
673 if (!rhs.isRepresentableByInt64())
674 return emitOpError(
"shift amount must be representable in 64 bits");
675 return success(lhs >> rhs.getExtValue());
682FailureOr<llvm::APSInt>
683IntegerShlOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
684 const llvm::APSInt &rhs) {
686 if (!rhs.isNonNegative())
687 return emitOpError(
"shift amount must be non-negative");
689 if (!rhs.isRepresentableByInt64())
690 return emitOpError(
"shift amount must be representable in 64 bits");
691 return success(lhs << rhs.getExtValue());
698OpFoldResult StringConcatOp::fold(FoldAdaptor adaptor) {
700 if (getStrings().size() == 1)
701 return getStrings()[0];
704 if (!llvm::all_of(adaptor.getStrings(), [](Attribute operand) {
705 return isa_and_nonnull<StringAttr>(operand);
710 SmallString<64> result;
711 for (
auto operand : adaptor.getStrings())
712 result += cast<StringAttr>(operand).getValue();
714 return StringAttr::get(result, getResult().getType());
722 using OpRewritePattern::OpRewritePattern;
725 matchAndRewrite(StringConcatOp concat,
726 mlir::PatternRewriter &rewriter)
const override {
730 bool hasNestedConcat = llvm::any_of(concat.getStrings(), [](Value operand) {
731 auto nestedConcat = operand.getDefiningOp<StringConcatOp>();
732 return nestedConcat && operand.hasOneUse();
735 if (!hasNestedConcat)
739 SmallVector<Value> flatOperands;
740 for (
auto input : concat.getStrings()) {
741 if (
auto nestedConcat = input.getDefiningOp<StringConcatOp>();
742 nestedConcat && input.hasOneUse())
743 llvm::append_range(flatOperands, nestedConcat.getStrings());
745 flatOperands.push_back(input);
748 rewriter.modifyOpInPlace(concat,
749 [&]() { concat->setOperands(flatOperands); });
756class MergeAdjacentOMStringConstants
759 using OpRewritePattern::OpRewritePattern;
762 matchAndRewrite(StringConcatOp concat,
763 mlir::PatternRewriter &rewriter)
const override {
765 SmallVector<Value> newOperands;
766 SmallString<64> accumulatedLit;
767 SmallVector<ConstantOp> accumulatedOps;
768 bool changed =
false;
770 auto flushLiterals = [&]() {
771 if (accumulatedOps.empty())
775 if (accumulatedOps.size() == 1) {
776 newOperands.push_back(accumulatedOps[0]);
779 auto newLit = rewriter.createOrFold<ConstantOp>(
781 StringAttr::get(accumulatedLit, concat.getResult().getType()));
782 newOperands.push_back(newLit);
785 accumulatedLit.clear();
786 accumulatedOps.clear();
789 for (
auto operand : concat.getStrings()) {
790 if (
auto litOp = operand.getDefiningOp<ConstantOp>()) {
791 if (
auto strAttr = dyn_cast<StringAttr>(litOp.getValue())) {
793 if (strAttr.getValue().empty()) {
797 accumulatedLit += strAttr.getValue();
798 accumulatedOps.push_back(litOp);
804 newOperands.push_back(operand);
814 if (newOperands.empty())
815 return rewriter.replaceOpWithNewOp<ConstantOp>(
816 concat, StringAttr::get(
"", concat.getResult().getType())),
820 rewriter.modifyOpInPlace(concat,
821 [&]() { concat->setOperands(newOperands); });
828void StringConcatOp::getCanonicalizationPatterns(RewritePatternSet &results,
830 results.insert<FlattenOMStringConcat, MergeAdjacentOMStringConstants>(
838LogicalResult circt::om::UnknownValueOp::verifySymbolUses(
839 SymbolTableCollection &symbolTable) {
842 auto classType = dyn_cast<ClassType>(getType());
847 auto className = classType.getClassName();
848 if (symbolTable.lookupNearestSymbolFrom<ClassLike>(*
this, className))
851 return emitOpError() <<
"refers to non-existant class (\""
852 << className.getValue() <<
"\")";
859#define GET_OP_CLASSES
860#include "circt/Dialect/OM/OM.cpp.inc"
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static Location getLoc(DefSlot slot)
static ParseResult parseClassLike(OpAsmParser &parser, OperationState &state)
LogicalResult verifyClassLike(ClassLike classLike)
std::optional< Type > getClassLikeFieldType(ClassLike classLike, StringAttr name)
void getClassLikeAsmBlockArgumentNames(ClassLike classLike, Region ®ion, OpAsmSetValueNameFn setNameFn)
static ParseResult parseBasePathString(OpAsmParser &parser, PathAttr &path)
static ParseResult parsePathString(OpAsmParser &parser, PathAttr &path, StringAttr &module, StringAttr &ref, StringAttr &field)
static void printBasePathString(OpAsmPrinter &p, Operation *op, PathAttr path)
static void printFieldLocs(OpAsmPrinter &printer, Operation *op, ArrayAttr fieldLocs)
static ParseResult parseFieldLocs(OpAsmParser &parser, ArrayAttr &fieldLocs)
static ParseResult parseClassFieldsList(OpAsmParser &parser, SmallVectorImpl< Attribute > &fieldNames, SmallVectorImpl< Type > &fieldTypes)
static void printClassLike(ClassLike classLike, OpAsmPrinter &printer)
void replaceClassLikeFieldTypes(ClassLike classLike, AttrTypeReplacer &replacer)
NamedAttribute makeFieldType(StringAttr name, Type type)
NamedAttribute makeFieldIdx(MLIRContext *ctx, mlir::StringAttr name, unsigned i)
static void printPathString(OpAsmPrinter &p, Operation *op, PathAttr path, StringAttr module, StringAttr ref, StringAttr field)
static Block * getBodyBlock(FModuleLike mod)
static InstancePath empty
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
void error(Twine message)
ParseResult parsePath(MLIRContext *context, StringRef spelling, PathAttr &path, StringAttr &module, StringAttr &ref, StringAttr &field)
Parse a target string in to a path.
ParseResult parseBasePath(MLIRContext *context, StringRef spelling, PathAttr &path)
Parse a target string of the form "Foo/bar:Bar/baz" in to a base path.
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
A module name, and the name of an instance inside that module.
mlir::StringAttr mlir::StringAttr instance