16#include "mlir/IR/Builders.h"
17#include "mlir/IR/DialectImplementation.h"
18#include "mlir/IR/Matchers.h"
19#include "mlir/IR/PatternMatch.h"
20#include "llvm/ADT/SmallString.h"
31ConstantOp::inferReturnTypes(MLIRContext *
context, std::optional<Location> loc,
32 ValueRange operands, DictionaryAttr attributes,
33 PropertyRef properties, RegionRange regions,
34 SmallVectorImpl<Type> &inferredReturnTypes) {
35 inferredReturnTypes.push_back(
36 properties.as<Properties *>()->getValue().getType());
40OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) {
return getValueAttr(); }
43 if (
auto reg = dyn_cast<rtg::RegisterAttrInterface>(getValueAttr())) {
44 setNameFn(getResult(),
reg.getRegisterAssembly());
53LogicalResult SequenceOp::verifyRegions() {
54 if (TypeRange(getSequenceType().getElementTypes()) !=
55 getBody()->getArgumentTypes())
56 return emitOpError(
"sequence type does not match block argument types");
61ParseResult SequenceOp::parse(OpAsmParser &parser, OperationState &result) {
63 if (parser.parseSymbolName(
64 result.getOrAddProperties<SequenceOp::Properties>().sym_name))
68 SmallVector<OpAsmParser::Argument> arguments;
69 if (parser.parseArgumentList(arguments, OpAsmParser::Delimiter::Paren,
73 SmallVector<Type> argTypes;
74 SmallVector<Location> argLocs;
75 argTypes.reserve(arguments.size());
76 argLocs.reserve(arguments.size());
77 for (
auto &arg : arguments) {
78 argTypes.push_back(arg.type);
79 argLocs.push_back(arg.sourceLoc ? *arg.sourceLoc : result.location);
81 Type type = SequenceType::get(result.getContext(), argTypes);
82 result.getOrAddProperties<SequenceOp::Properties>().sequenceType =
85 auto loc = parser.getCurrentLocation();
86 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
88 if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() {
89 return parser.emitError(loc)
90 <<
"'" << result.name.getStringRef() <<
"' op ";
94 std::unique_ptr<Region> bodyRegionRegion = std::make_unique<Region>();
95 if (parser.parseRegion(*bodyRegionRegion, arguments))
98 if (bodyRegionRegion->empty()) {
99 bodyRegionRegion->emplaceBlock();
100 bodyRegionRegion->addArguments(argTypes, argLocs);
102 result.addRegion(std::move(bodyRegionRegion));
107void SequenceOp::print(OpAsmPrinter &p) {
109 p.printSymbolName(getSymNameAttr().getValue());
111 llvm::interleaveComma(getBody()->getArguments(), p,
112 [&](
auto arg) { p.printRegionArgument(arg); });
114 p.printOptionalAttrDictWithKeyword(
115 (*this)->getAttrs(), {getSymNameAttrName(), getSequenceTypeAttrName()});
117 p.printRegion(getBodyRegion(),
false);
120StringAttr SequenceOp::getNameAttr() {
return getSymNameAttr(); }
122void SequenceOp::setName(StringAttr name) { setSymNameAttr(name); }
124mlir::SymbolTable::Visibility SequenceOp::getVisibility() {
125 return mlir::SymbolTable::Visibility::Private;
128void SequenceOp::setVisibility(mlir::SymbolTable::Visibility visibility) {
130 assert(
false &&
"cannot change visibility of sequence");
138GetSequenceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
140 symbolTable.lookupNearestSymbolFrom<SequenceOp>(*
this, getSequenceAttr());
143 <<
"'" << getSequence()
144 <<
"' does not reference a valid 'rtg.sequence' operation";
146 if (
seq.getSequenceType() != getType())
147 return emitOpError(
"referenced 'rtg.sequence' op's type does not match");
156LogicalResult SubstituteSequenceOp::verify() {
157 if (getReplacements().
empty())
158 return emitOpError(
"must at least have one replacement value");
160 if (getReplacements().size() >
161 getSequence().getType().getElementTypes().size())
163 "must not have more replacement values than sequence arguments");
165 if (getReplacements().getTypes() !=
166 getSequence().getType().getElementTypes().take_front(
167 getReplacements().size()))
168 return emitOpError(
"replacement types must match the same number of "
169 "sequence argument types from the front");
174LogicalResult SubstituteSequenceOp::inferReturnTypes(
175 MLIRContext *
context, std::optional<Location> loc, ValueRange operands,
176 DictionaryAttr attributes, PropertyRef properties, RegionRange regions,
177 SmallVectorImpl<Type> &inferredReturnTypes) {
178 ArrayRef<Type> argTypes =
179 cast<SequenceType>(operands[0].getType()).getElementTypes();
181 SequenceType::get(
context, argTypes.drop_front(operands.size() - 1));
182 inferredReturnTypes.push_back(seqType);
186ParseResult SubstituteSequenceOp::parse(::mlir::OpAsmParser &parser,
187 ::mlir::OperationState &result) {
188 OpAsmParser::UnresolvedOperand sequenceRawOperand;
189 SmallVector<OpAsmParser::UnresolvedOperand, 4> replacementsOperands;
190 Type sequenceRawType;
192 if (parser.parseOperand(sequenceRawOperand) || parser.parseLParen())
195 auto replacementsOperandsLoc = parser.getCurrentLocation();
196 if (parser.parseOperandList(replacementsOperands) || parser.parseRParen() ||
197 parser.parseColon() || parser.parseType(sequenceRawType) ||
198 parser.parseOptionalAttrDict(result.attributes))
201 if (!isa<SequenceType>(sequenceRawType))
202 return parser.emitError(parser.getNameLoc())
203 <<
"'sequence' must be handle to a sequence or sequence family, but "
207 if (parser.resolveOperand(sequenceRawOperand, sequenceRawType,
211 if (parser.resolveOperands(replacementsOperands,
212 cast<SequenceType>(sequenceRawType)
214 .take_front(replacementsOperands.size()),
215 replacementsOperandsLoc, result.operands))
218 SmallVector<Type> inferredReturnTypes;
219 if (failed(inferReturnTypes(
220 parser.getContext(), result.location, result.operands,
221 result.attributes.getDictionary(parser.getContext()),
222 result.getRawProperties(), result.regions, inferredReturnTypes)))
225 result.addTypes(inferredReturnTypes);
229void SubstituteSequenceOp::print(OpAsmPrinter &p) {
230 p <<
' ' << getSequence() <<
"(" << getReplacements()
231 <<
") : " << getSequence().getType();
232 p.printOptionalAttrDict((*this)->getAttrs(), {});
239LogicalResult InterleaveSequencesOp::verify() {
240 if (getSequences().
empty())
241 return emitOpError(
"must have at least one sequence in the list");
246OpFoldResult InterleaveSequencesOp::fold(FoldAdaptor adaptor) {
247 if (getSequences().size() == 1)
248 return getSequences()[0];
257ParseResult SetCreateOp::parse(OpAsmParser &parser, OperationState &result) {
258 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
261 if (parser.parseOperandList(operands) ||
262 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
263 parser.parseType(elemType))
266 result.addTypes({SetType::get(result.getContext(), elemType)});
268 for (
auto operand : operands)
269 if (parser.resolveOperand(operand, elemType, result.operands))
275void SetCreateOp::print(OpAsmPrinter &p) {
277 p.printOperands(getElements());
278 p.printOptionalAttrDict((*this)->getAttrs());
279 p <<
" : " << getSet().getType().getElementType();
282LogicalResult SetCreateOp::verify() {
283 if (getElements().size() > 0) {
286 if (getElements()[0].getType() != getSet().getType().getElementType())
287 return emitOpError() <<
"operand types must match set element type";
297LogicalResult SetCartesianProductOp::inferReturnTypes(
298 MLIRContext *
context, std::optional<Location> loc, ValueRange operands,
299 DictionaryAttr attributes, PropertyRef properties, RegionRange regions,
300 SmallVectorImpl<Type> &inferredReturnTypes) {
301 if (operands.empty()) {
303 return mlir::emitError(*loc) <<
"at least one set must be provided";
307 SmallVector<Type> elementTypes;
308 for (
auto operand : operands)
309 elementTypes.push_back(cast<SetType>(operand.getType()).getElementType());
310 inferredReturnTypes.push_back(
311 SetType::get(rtg::TupleType::get(
context, elementTypes)));
319ParseResult BagCreateOp::parse(OpAsmParser &parser, OperationState &result) {
320 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> elementOperands,
324 if (!parser.parseOptionalLParen()) {
326 OpAsmParser::UnresolvedOperand elementOperand, multipleOperand;
327 if (parser.parseOperand(multipleOperand) || parser.parseKeyword(
"x") ||
328 parser.parseOperand(elementOperand))
331 elementOperands.push_back(elementOperand);
332 multipleOperands.push_back(multipleOperand);
334 if (parser.parseOptionalComma()) {
335 if (parser.parseRParen())
342 if (parser.parseColon() || parser.parseType(elemType) ||
343 parser.parseOptionalAttrDict(result.attributes))
346 result.addTypes({BagType::get(result.getContext(), elemType)});
348 for (
auto operand : elementOperands)
349 if (parser.resolveOperand(operand, elemType, result.operands))
352 for (
auto operand : multipleOperands)
353 if (parser.resolveOperand(operand, IndexType::
get(result.getContext()),
360void BagCreateOp::print(OpAsmPrinter &p) {
362 if (!getElements().
empty())
364 llvm::interleaveComma(llvm::zip(getElements(), getMultiples()), p,
365 [&](
auto elAndMultiple) {
366 auto [el, multiple] = elAndMultiple;
367 p << multiple <<
" x " << el;
369 if (!getElements().
empty())
372 p <<
" : " << getBag().getType().getElementType();
373 p.printOptionalAttrDict((*this)->getAttrs());
376LogicalResult BagCreateOp::verify() {
377 if (!llvm::all_equal(getElements().getTypes()))
378 return emitOpError() <<
"types of all elements must match";
380 if (getElements().size() > 0)
381 if (getElements()[0].getType() != getBag().getType().getElementType())
382 return emitOpError() <<
"operand types must match bag element type";
391LogicalResult TupleCreateOp::inferReturnTypes(
392 MLIRContext *
context, std::optional<Location> loc, ValueRange operands,
393 DictionaryAttr attributes, PropertyRef properties, RegionRange regions,
394 SmallVectorImpl<Type> &inferredReturnTypes) {
395 SmallVector<Type> elementTypes;
396 for (
auto operand : operands)
397 elementTypes.push_back(operand.getType());
398 inferredReturnTypes.push_back(rtg::TupleType::get(
context, elementTypes));
406LogicalResult TupleExtractOp::inferReturnTypes(
407 MLIRContext *
context, std::optional<Location> loc, ValueRange operands,
408 DictionaryAttr attributes, PropertyRef properties, RegionRange regions,
409 SmallVectorImpl<Type> &inferredReturnTypes) {
410 assert(operands.size() == 1 &&
"must have exactly one operand");
412 auto tupleTy = dyn_cast<rtg::TupleType>(operands[0].getType());
413 size_t idx = properties.as<Properties *>()->getIndex().getInt();
416 return mlir::emitError(*loc) <<
"only RTG tuples are supported";
420 if (tupleTy.getFieldTypes().size() <= idx) {
422 return mlir::emitError(*loc)
424 <<
") must be smaller than number of elements in tuple ("
425 << tupleTy.getFieldTypes().size() <<
")";
429 inferredReturnTypes.push_back(tupleTy.getFieldTypes()[idx]);
437LogicalResult ConstraintOp::canonicalize(ConstraintOp op,
438 PatternRewriter &rewriter) {
439 if (mlir::matchPattern(op.getCondition(), mlir::m_One())) {
440 rewriter.eraseOp(op);
451LogicalResult VirtualRegisterOp::inferReturnTypes(
452 MLIRContext *
context, std::optional<Location> loc, ValueRange operands,
453 DictionaryAttr attributes, PropertyRef properties, RegionRange regions,
454 SmallVectorImpl<Type> &inferredReturnTypes) {
455 auto allowedRegs = properties.as<Properties *>()->getAllowedRegs();
456 inferredReturnTypes.push_back(allowedRegs.getType());
464OpFoldResult RegisterToIndexOp::fold(FoldAdaptor adaptor) {
465 if (
auto reg = dyn_cast_or_null<rtg::RegisterAttrInterface>(adaptor.getReg()))
466 return IntegerAttr::get(IndexType::get(getContext()),
reg.getClassIndex());
468 if (
auto indexToRegOp = getReg().getDefiningOp<IndexToRegisterOp>())
469 return indexToRegOp.getIndex();
478LogicalResult IndexToRegisterOp::verify() {
481 if (matchPattern(getIndex(), m_ConstantInt(&indexValue))) {
482 if (indexValue.uge(getType().getRegisterClassSize())) {
483 SmallString<16> indexStr;
484 indexValue.toString(indexStr, 10,
false);
485 return emitOpError() <<
"index " << indexStr
486 <<
" is out of range for register class "
487 << getReg().getType();
494OpFoldResult IndexToRegisterOp::fold(FoldAdaptor adaptor) {
495 if (
auto indexAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getIndex()))
496 return getType().getRegisterAttrForClassIndex(
497 getContext(), indexAttr.getValue().getZExtValue());
506LogicalResult ContextSwitchOp::verify() {
507 auto elementTypes = getSequence().getType().getElementTypes();
508 if (elementTypes.size() != 3)
509 return emitOpError(
"sequence type must have exactly 3 element types");
511 if (getFrom().getType() != elementTypes[0])
513 "first sequence element type must match 'from' attribute type");
515 if (getTo().getType() != elementTypes[1])
517 "second sequence element type must match 'to' attribute type");
519 auto seqTy = dyn_cast<SequenceType>(elementTypes[2]);
520 if (!seqTy || !seqTy.getElementTypes().empty())
522 "third sequence element type must be a fully substituted sequence");
531LogicalResult TestOp::verifyRegions() {
532 if (!getTargetType().entryTypesMatch(getBody()->getArgumentTypes()))
533 return emitOpError(
"argument types must match dict entry types");
538LogicalResult TestOp::verify() {
539 if (getTemplateName().
empty())
540 return emitOpError(
"template name must not be empty");
545LogicalResult TestOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
546 if (!getTargetAttr())
550 symbolTable.lookupNearestSymbolFrom<TargetOp>(*
this, getTargetAttr());
553 <<
"'" << *getTarget()
554 <<
"' does not reference a valid 'rtg.target' operation";
558 size_t targetIdx = 0;
559 auto targetEntries = target.getTarget().getEntries();
560 for (
auto testEntry : getTargetType().getEntries()) {
562 while (targetIdx < targetEntries.size() &&
563 targetEntries[targetIdx].name.getValue() < testEntry.name.getValue())
567 if (targetIdx >= targetEntries.size() ||
568 targetEntries[targetIdx].name != testEntry.name ||
569 targetEntries[targetIdx].type != testEntry.type) {
570 return emitOpError(
"referenced 'rtg.target' op's type is invalid: "
571 "missing entry called '")
572 << testEntry.name.getValue() <<
"' of type " << testEntry.type;
579ParseResult TestOp::parse(OpAsmParser &parser, OperationState &result) {
581 StringAttr symNameAttr;
582 if (parser.parseSymbolName(symNameAttr))
585 result.getOrAddProperties<TestOp::Properties>().sym_name = symNameAttr;
588 SmallVector<OpAsmParser::Argument> arguments;
589 SmallVector<StringAttr> names;
591 auto parseOneArgument = [&]() -> ParseResult {
593 if (parser.parseKeywordOrString(&name) || parser.parseEqual() ||
594 parser.parseArgument(arguments.emplace_back(),
true,
598 names.push_back(StringAttr::get(result.getContext(), name));
601 if (parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
602 parseOneArgument,
" in argument list"))
605 SmallVector<Type> argTypes;
606 SmallVector<DictEntry> entries;
607 SmallVector<Location> argLocs;
608 argTypes.reserve(arguments.size());
609 argLocs.reserve(arguments.size());
610 for (
auto [name, arg] :
llvm::zip(names, arguments)) {
611 argTypes.push_back(arg.type);
612 argLocs.push_back(arg.sourceLoc ? *arg.sourceLoc : result.location);
613 entries.push_back({name, arg.type});
615 auto emitError = [&]() -> InFlightDiagnostic {
616 return parser.emitError(parser.getCurrentLocation());
618 Type type = DictType::getChecked(emitError, result.getContext(),
619 ArrayRef<DictEntry>(entries));
622 result.getOrAddProperties<TestOp::Properties>().targetType =
625 std::string templateName;
626 if (!parser.parseOptionalKeyword(
"template")) {
627 auto loc = parser.getCurrentLocation();
628 if (parser.parseString(&templateName))
631 if (templateName.empty())
632 return parser.emitError(loc,
"template name must not be empty");
635 StringAttr templateNameAttr = symNameAttr;
636 if (!templateName.empty())
637 templateNameAttr = StringAttr::get(result.getContext(), templateName);
639 StringAttr targetName;
640 if (!parser.parseOptionalKeyword(
"target"))
641 if (parser.parseSymbolName(targetName))
644 result.getOrAddProperties<TestOp::Properties>().templateName =
646 result.getOrAddProperties<TestOp::Properties>().target = targetName;
648 auto loc = parser.getCurrentLocation();
649 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
651 if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() {
652 return parser.emitError(loc)
653 <<
"'" << result.name.getStringRef() <<
"' op ";
657 std::unique_ptr<Region> bodyRegionRegion = std::make_unique<Region>();
658 if (parser.parseRegion(*bodyRegionRegion, arguments))
661 if (bodyRegionRegion->empty()) {
662 bodyRegionRegion->emplaceBlock();
663 bodyRegionRegion->addArguments(argTypes, argLocs);
665 result.addRegion(std::move(bodyRegionRegion));
670void TestOp::print(OpAsmPrinter &p) {
672 p.printSymbolName(getSymNameAttr().getValue());
674 SmallString<32> resultNameStr;
675 llvm::interleaveComma(
676 llvm::zip(getTargetType().getEntries(), getBody()->getArguments()), p,
677 [&](
auto entryAndArg) {
678 auto [entry, arg] = entryAndArg;
679 p << entry.name.getValue() <<
" = ";
680 p.printRegionArgument(arg);
684 if (getSymNameAttr() != getTemplateNameAttr())
685 p <<
" template " << getTemplateNameAttr();
687 if (getTargetAttr()) {
689 p.printSymbolName(getTargetAttr().getValue());
692 p.printOptionalAttrDictWithKeyword(
693 (*this)->getAttrs(), {getSymNameAttrName(), getTargetTypeAttrName(),
694 getTargetAttrName(), getTemplateNameAttrName()});
696 p.printRegion(getBodyRegion(),
false);
699void TestOp::getAsmBlockArgumentNames(Region ®ion,
701 for (
auto [entry, arg] :
702 llvm::zip(getTargetType().getEntries(), region.getArguments()))
703 setNameFn(arg, entry.name.getValue());
710LogicalResult TargetOp::verifyRegions() {
711 if (!getTarget().entryTypesMatch(
712 getBody()->getTerminator()->getOperandTypes()))
713 return emitOpError(
"terminator operand types must match dict entry types");
722LogicalResult ValidateOp::verify() {
723 if (!getRef().getType().isValidContentType(getValue().getType()))
725 "result type must be a valid content type for the ref value");
730bool ValidateOp::isSourceRegister(
unsigned index) {
732 return isa<RegisterTypeInterface>(getRef().getType());
736bool ValidateOp::isDestinationRegister(
unsigned index) {
return false; }
742LogicalResult ArrayCreateOp::verify() {
743 if (!getElements().
empty() &&
744 getElements()[0].getType() != getType().getElementType())
745 return emitOpError(
"operand types must match array element type, expected ")
746 << getType().getElementType() <<
" but got "
747 << getElements()[0].getType();
752ParseResult ArrayCreateOp::parse(OpAsmParser &parser, OperationState &result) {
753 SmallVector<OpAsmParser::UnresolvedOperand> operands;
756 if (parser.parseOperandList(operands) || parser.parseColon() ||
758 parser.parseOptionalAttrDict(result.attributes))
761 if (failed(parser.resolveOperands(operands,
elementType, result.operands)))
769void ArrayCreateOp::print(OpAsmPrinter &p) {
771 p.printOperands(getElements());
772 p <<
" : " << getType().getElementType();
773 p.printOptionalAttrDict((*this)->getAttrs(), {});
780LogicalResult ArrayAppendOp::canonicalize(ArrayAppendOp op,
781 PatternRewriter &rewriter) {
782 auto createOp = op.getArray().getDefiningOp<ArrayCreateOp>();
786 SmallVector<Value> newElements(createOp.getElements());
787 newElements.push_back(op.getElement());
788 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, op.getType(), newElements);
796LogicalResult MemoryBlockDeclareOp::verify() {
799 "base address width must match memory block address width");
803 "end address width must match memory block address width");
805 if (getBaseAddress().ugt(getEndAddress()))
807 "base address must be smaller than or equal to the end address");
812ParseResult MemoryBlockDeclareOp::parse(OpAsmParser &parser,
813 OperationState &result) {
814 SmallVector<OpAsmParser::UnresolvedOperand> operands;
815 MemoryBlockType memoryBlockType;
818 if (parser.parseLSquare())
821 auto startLoc = parser.getCurrentLocation();
822 if (parser.parseInteger(start))
825 if (parser.parseMinus())
828 auto endLoc = parser.getCurrentLocation();
829 if (parser.parseInteger(end) || parser.parseRSquare() ||
830 parser.parseColonType(memoryBlockType) ||
831 parser.parseOptionalAttrDict(result.attributes))
834 auto width = memoryBlockType.getAddressWidth();
835 auto adjustAPInt = [&](APInt value, llvm::SMLoc loc) -> FailureOr<APInt> {
836 if (value.getBitWidth() > width) {
837 if (!value.isIntN(width))
838 return parser.emitError(
840 "address out of range for memory block with address width ")
843 return value.trunc(width);
846 if (value.getBitWidth() < width)
847 return value.zext(width);
852 auto startRes = adjustAPInt(start, startLoc);
853 auto endRes = adjustAPInt(end, endLoc);
854 if (failed(startRes) || failed(endRes))
857 auto intType = IntegerType::get(result.getContext(), width);
858 result.addAttribute(getBaseAddressAttrName(result.name),
859 IntegerAttr::get(intType, *startRes));
860 result.addAttribute(getEndAddressAttrName(result.name),
861 IntegerAttr::get(intType, *endRes));
863 result.addTypes(memoryBlockType);
867void MemoryBlockDeclareOp::print(OpAsmPrinter &p) {
868 SmallVector<char> str;
869 getBaseAddress().toString(str, 16,
false,
false,
false);
873 getEndAddress().toString(str, 16,
false,
false,
false);
874 p << str <<
"] : " << getType();
875 p.printOptionalAttrDict((*this)->getAttrs(),
876 {getBaseAddressAttrName(), getEndAddressAttrName()});
883LogicalResult MemoryBaseAddressOp::inferReturnTypes(
884 MLIRContext *
context, std::optional<Location> loc, ValueRange operands,
885 DictionaryAttr attributes, PropertyRef properties, RegionRange regions,
886 SmallVectorImpl<Type> &inferredReturnTypes) {
887 if (operands.empty())
889 auto memTy = dyn_cast<MemoryType>(operands[0].getType());
892 inferredReturnTypes.push_back(
893 IntegerType::get(
context, memTy.getAddressWidth()));
901LogicalResult ConcatImmediateOp::inferReturnTypes(
902 MLIRContext *
context, std::optional<Location> loc, ValueRange operands,
903 DictionaryAttr attributes, PropertyRef properties, RegionRange regions,
904 SmallVectorImpl<Type> &inferredReturnTypes) {
905 if (operands.empty()) {
907 return mlir::emitError(*loc) <<
"at least one operand must be provided";
911 unsigned totalWidth = 0;
912 for (
auto operand : operands) {
913 auto immType = dyn_cast<IntegerType>(operand.getType());
916 return mlir::emitError(*loc)
917 <<
"all operands must be of immediate type";
920 totalWidth += immType.getWidth();
923 inferredReturnTypes.push_back(IntegerType::get(
context, totalWidth));
927OpFoldResult ConcatImmediateOp::fold(FoldAdaptor adaptor) {
929 if (getOperands().size() == 1)
930 return getOperands()[0];
933 if (llvm::all_of(adaptor.getOperands(), [](Attribute attr) {
934 return isa_and_nonnull<IntegerAttr>(attr);
936 auto result = APInt::getZeroWidth();
937 for (
auto attr : adaptor.getOperands())
938 result = result.concat(cast<IntegerAttr>(attr).getValue());
940 return IntegerAttr::get(
941 IntegerType::get(getContext(), result.getBitWidth()), result);
951LogicalResult SliceImmediateOp::verify() {
952 auto srcWidth = getInput().getType().getWidth();
953 auto dstWidth = getResult().getType().getWidth();
955 if (getLowBit() >= srcWidth)
956 return emitOpError(
"from bit too large for input (got ")
957 << getLowBit() <<
", but input width is " << srcWidth <<
")";
959 if (srcWidth - getLowBit() < dstWidth)
960 return emitOpError(
"slice does not fit in input (trying to extract ")
961 << dstWidth <<
" bits starting at index " << getLowBit()
962 <<
", but only " << (srcWidth - getLowBit())
963 <<
" bits are available)";
968OpFoldResult SliceImmediateOp::fold(FoldAdaptor adaptor) {
969 if (
auto inputAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getInput())) {
970 auto resultWidth = getType().getWidth();
971 APInt sliced = inputAttr.getValue().extractBits(resultWidth, getLowBit());
972 return IntegerAttr::get(
973 IntegerType::get(getContext(), sliced.getBitWidth()), sliced);
983OpFoldResult StringConcatOp::fold(FoldAdaptor adaptor) {
984 SmallString<32> result;
985 for (
auto attr : adaptor.getStrings()) {
986 auto stringAttr = dyn_cast_or_null<StringAttr>(attr);
990 result += stringAttr.getValue();
993 return StringAttr::get(result, StringType::get(getContext()));
1000OpFoldResult IntFormatOp::fold(FoldAdaptor adaptor) {
1001 auto intAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getValue());
1004 if (!intAttr.getType().isIndex())
1006 return StringAttr::get(Twine(intAttr.getValue().getZExtValue()),
1007 StringType::get(getContext()));
1014OpFoldResult ImmediateFormatOp::fold(FoldAdaptor adaptor) {
1015 auto immAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getValue());
1018 SmallString<16> strBuf(
"0x");
1019 immAttr.getValue().toString(strBuf, 16,
false);
1020 return StringAttr::get(strBuf, StringType::get(getContext()));
1027OpFoldResult RegisterFormatOp::fold(FoldAdaptor adaptor) {
1028 auto regAttr = dyn_cast_or_null<RegisterAttrInterface>(adaptor.getValue());
1031 return StringAttr::get(regAttr.getRegisterAssembly(),
1032 StringType::get(getContext()));
1039OpFoldResult StringToLabelOp::fold(FoldAdaptor adaptor) {
1040 if (
auto stringAttr = dyn_cast_or_null<StringAttr>(adaptor.getString()))
1041 return LabelAttr::get(getContext(), stringAttr.getValue());
1050LogicalResult StringToASCIIArrayOp::canonicalize(StringToASCIIArrayOp op,
1051 PatternRewriter &rewriter) {
1052 auto constOp = op.getString().getDefiningOp<ConstantOp>();
1056 auto strAttr = dyn_cast<StringAttr>(constOp.getValue());
1060 auto i8Ty = rewriter.getIntegerType(8);
1061 SmallVector<Value> bytes;
1062 bytes.reserve(strAttr.getValue().size());
1063 for (
unsigned char c : strAttr.getValue())
1064 bytes.push_back(ConstantOp::create(rewriter, op.
getLoc(),
1065 rewriter.getIntegerAttr(i8Ty, c)));
1067 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, op.getType(), bytes);
1075ParseResult WithHandlersOp::parse(OpAsmParser &parser, OperationState &result) {
1082 SmallVector<Attribute> effectSymbols;
1083 SmallVector<std::unique_ptr<Region>> handlerRegions;
1085 if (parser.parseLBrace())
1090 if (succeeded(parser.parseOptionalKeyword(
"do")))
1094 if (parser.parseKeyword(
"handle"))
1098 FlatSymbolRefAttr sym;
1099 if (parser.parseAttribute(sym))
1101 effectSymbols.push_back(sym);
1104 SmallVector<OpAsmParser::Argument> args;
1105 if (parser.parseArgumentList(args, OpAsmParser::Delimiter::Paren,
1110 auto handler = std::make_unique<Region>();
1111 if (parser.parseRegion(*handler, args))
1113 if (handler->empty())
1114 handler->emplaceBlock();
1115 handlerRegions.push_back(std::move(handler));
1119 auto &props = result.getOrAddProperties<WithHandlersOp::Properties>();
1120 props.effects = ArrayAttr::get(parser.getContext(), effectSymbols);
1123 Region *body = result.addRegion();
1124 if (parser.parseRegion(*body))
1127 body->emplaceBlock();
1130 for (
auto &h : handlerRegions) {
1131 Region *hr = result.addRegion();
1135 if (parser.parseRBrace() || parser.parseOptionalAttrDict(result.attributes))
1141void WithHandlersOp::print(OpAsmPrinter &printer) {
1143 printer.increaseIndent();
1144 for (
auto [symAttr, handlerRegion] :
1145 llvm::zip(getEffects(), getHandlerRegions())) {
1146 printer.printNewline();
1147 printer <<
"handle " << symAttr <<
"(";
1149 for (BlockArgument arg : handlerRegion.front().getArguments()) {
1153 printer.printRegionArgument(arg);
1156 printer.printRegion(handlerRegion,
false);
1158 printer.printNewline();
1160 printer.printRegion(getBody());
1161 printer.decreaseIndent();
1162 printer.printNewline();
1165 printer.printOptionalAttrDict(
1166 (*this)->getDiscardableAttrDictionary().getValue());
1169LogicalResult WithHandlersOp::verify() {
1170 auto effects = getEffects();
1171 if (effects.size() != getHandlerRegions().size())
1172 return emitOpError(
"effects.size() (")
1173 << effects.size() <<
") != handlerRegions.size() ("
1174 << getHandlerRegions().size() <<
")";
1176 llvm::SmallDenseSet<StringAttr> seen;
1177 for (
auto attr : effects) {
1178 auto sym = cast<FlatSymbolRefAttr>(attr).getAttr();
1179 if (!seen.insert(sym).second)
1180 return emitOpError(
"duplicate handler for effect '")
1181 << sym.getValue() <<
"'";
1187WithHandlersOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1188 auto moduleOp = (*this)->getParentOfType<ModuleOp>();
1190 return emitOpError(
"must be inside a module");
1192 for (
auto [idx, symAttr] :
llvm::enumerate(getEffects())) {
1193 auto ref = dyn_cast<FlatSymbolRefAttr>(symAttr);
1195 return emitOpError(
"effects[") << idx <<
"] is not a symbol reference";
1197 auto decl = symbolTable.lookupNearestSymbolFrom<EffectOp>(moduleOp, ref);
1199 return emitOpError(
"unresolved effect symbol '") << ref.getValue() <<
"'";
1202 Region &handlerRegion = getHandlerRegions()[idx];
1203 if (handlerRegion.empty())
1204 return emitOpError(
"handler region ") << idx <<
" is empty";
1206 Block &handlerBlock = handlerRegion.front();
1207 FunctionType ft = decl.getFunctionType();
1208 auto inputTypes = ft.getInputs();
1209 auto resultTypes = ft.getResults();
1213 resultTypes.empty() ? NoneType::get(getContext()) : resultTypes[0];
1214 size_t expectedArgs = inputTypes.size() + 1;
1216 if (handlerBlock.getNumArguments() != expectedArgs)
1217 return emitOpError(
"handler region ")
1218 << idx <<
" expects " << expectedArgs <<
" block args but has "
1219 << handlerBlock.getNumArguments();
1221 for (
auto [argIdx, argType] :
llvm::enumerate(inputTypes)) {
1222 if (handlerBlock.getArgument(argIdx).getType() != argType)
1223 return emitOpError(
"handler region ")
1224 << idx <<
" block arg " << argIdx <<
" has type "
1225 << handlerBlock.getArgument(argIdx).getType() <<
" but expected "
1229 auto contTy = ContinuationType::get(getContext(), resumeType);
1230 if (handlerBlock.getArgument(inputTypes.size()).getType() != contTy)
1231 return emitOpError(
"handler region ")
1232 << idx <<
" continuation arg has type "
1233 << handlerBlock.getArgument(inputTypes.size()).getType()
1234 <<
" but expected " << contTy;
1244ParseResult PerformOp::parse(OpAsmParser &parser, OperationState &result) {
1246 FlatSymbolRefAttr effectAttr;
1247 if (parser.parseAttribute(effectAttr))
1249 result.getOrAddProperties<PerformOp::Properties>().effect = effectAttr;
1251 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1252 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::Paren))
1255 if (parser.parseColon())
1258 SmallVector<Type> operandTypes;
1259 if (parser.parseLParen())
1261 if (succeeded(parser.parseOptionalRParen())) {
1264 if (parser.parseTypeList(operandTypes) || parser.parseRParen())
1268 if (parser.parseArrow())
1272 if (parser.parseType(resultType))
1275 if (parser.resolveOperands(operands, operandTypes,
1276 parser.getCurrentLocation(), result.operands))
1279 if (!isa<NoneType>(resultType))
1280 result.addTypes(resultType);
1282 if (parser.parseOptionalAttrDict(result.attributes))
1288void PerformOp::print(OpAsmPrinter &printer) {
1289 printer <<
" " << getEffectAttr() <<
"(";
1290 llvm::interleaveComma(getOperands(), printer, [&](Value v) { printer << v; });
1292 llvm::interleaveComma(getOperands(), printer,
1293 [&](Value v) { printer << v.getType(); });
1296 printer << getResult().getType();
1298 printer << NoneType::get(getContext());
1300 printer.printOptionalAttrDict(
1301 (*this)->getDiscardableAttrDictionary().getValue());
1304void PerformOp::getEffects(
1305 SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
1307 effects.emplace_back(MemoryEffects::Write::get(), MutResource::get());
1310LogicalResult PerformOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1311 auto moduleOp = (*this)->getParentOfType<ModuleOp>();
1313 return emitOpError(
"must be inside a module");
1316 symbolTable.lookupNearestSymbolFrom<EffectOp>(moduleOp, getEffectAttr());
1318 return emitOpError(
"unresolved effect symbol '") << getEffect() <<
"'";
1320 FunctionType ft = decl.getFunctionType();
1321 auto inputTypes = ft.getInputs();
1322 auto resultTypes = ft.getResults();
1324 if (getOperands().size() != inputTypes.size())
1325 return emitOpError(
"effect '")
1326 << getEffect() <<
"' expects " << inputTypes.size()
1327 <<
" inputs but got " << getOperands().size();
1329 for (
auto [idx, opType, declType] :
1330 llvm::enumerate(getOperandTypes(), inputTypes)) {
1331 if (opType != declType)
1332 return emitOpError(
"operand ") << idx <<
" has type " << opType
1333 <<
" but effect declares " << declType;
1336 if (resultTypes.empty()) {
1338 return emitOpError(
"effect '")
1339 << getEffect() <<
"' returns none but perform has a result";
1342 return emitOpError(
"effect '")
1343 << getEffect() <<
"' returns " << resultTypes[0]
1344 <<
" but perform has no result";
1345 if (getResult().getType() != resultTypes[0])
1346 return emitOpError(
"result type ")
1347 << getResult().getType() <<
" does not match effect result type "
1358void ResumeOp::getEffects(
1359 SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
1361 effects.emplace_back(MemoryEffects::Write::get(), MutResource::get());
1364LogicalResult ResumeOp::verify() {
1365 auto contTy = cast<ContinuationType>(getContinuation().getType());
1366 Type resumeType = contTy.getResumeType();
1368 if (isa<NoneType>(resumeType)) {
1371 "continuation expects none but resume provides a value");
1374 return emitOpError(
"continuation expects ")
1375 << resumeType <<
" but resume provides no value";
1376 if (getValue().getType() != resumeType)
1377 return emitOpError(
"resume value type ")
1378 << getValue().getType()
1379 <<
" does not match continuation resume type " << resumeType;
1389#define GET_OP_CLASSES
1390#include "circt/Dialect/RTG/IR/RTG.cpp.inc"
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static size_t getAddressWidth(size_t depth)
static Location getLoc(DefSlot slot)
static InstancePath empty
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
reg(value, clock, reset=None, reset_value=None, name=None, sym_name=None)