20#include "mlir/Dialect/Func/IR/FuncOps.h"
21#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
22#include "mlir/IR/PatternMatch.h"
23#include "mlir/Interfaces/FunctionImplementation.h"
24#include "llvm/ADT/MapVector.h"
36void DPIFuncOp::build(OpBuilder &odsBuilder, OperationState &odsState,
37 StringAttr symName, ArrayRef<StringAttr> argNames,
38 ArrayRef<Type> argTypes,
39 ArrayRef<DPIDirection> argDirections, ArrayAttr argLocs,
40 StringAttr verilogName) {
42 SmallVector<DPIArgument> args;
43 args.reserve(argNames.size());
44 for (
auto [name, type, dir] : llvm::zip(argNames, argTypes, argDirections))
45 args.push_back({name, type, dir});
46 auto dpiType = DPIFunctionType::get(odsBuilder.getContext(), args);
47 build(odsBuilder, odsState, symName, dpiType, argLocs, verilogName);
50void DPIFuncOp::build(OpBuilder &odsBuilder, OperationState &odsState,
51 StringAttr symName, DPIFunctionType dpiFunctionType,
52 ArrayAttr argLocs, StringAttr verilogName) {
53 odsState.addAttribute(getSymNameAttrName(odsState.name), symName);
54 odsState.addAttribute(getDpiFunctionTypeAttrName(odsState.name),
55 TypeAttr::get(dpiFunctionType));
57 odsState.addAttribute(getArgumentLocsAttrName(odsState.name), argLocs);
59 odsState.addAttribute(getVerilogNameAttrName(odsState.name), verilogName);
63::mlir::Type DPIFuncOp::getFunctionType() {
64 return getDpiFunctionType().getFunctionType();
67void DPIFuncOp::setFunctionTypeAttr(::mlir::TypeAttr type) {
69 auto dpiType = llvm::dyn_cast<DPIFunctionType>(type.getValue());
70 assert(dpiType &&
"DPIFuncOp function type can only be set via "
71 "DPIFunctionType, not a plain FunctionType");
72 setDpiFunctionType(dpiType);
75::mlir::Type DPIFuncOp::cloneTypeWith(::mlir::TypeRange inputs,
76 ::mlir::TypeRange results) {
77 return FunctionType::get(getContext(), inputs, results);
80ParseResult DPIFuncOp::parse(OpAsmParser &parser, OperationState &result) {
81 auto builder = parser.getBuilder();
82 auto *ctx = builder.getContext();
84 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
87 if (parser.parseSymbolName(nameAttr,
88 DPIFuncOp::getSymNameAttrName(result.name),
92 SmallVector<DPIArgument> args;
93 SmallVector<Attribute> argLocs;
94 auto unknownLoc = builder.getUnknownLoc();
97 auto parseOneArg = [&]() -> ParseResult {
99 auto keyLoc = parser.getCurrentLocation();
100 if (parser.parseKeyword(&dirKeyword))
104 return parser.emitError(keyLoc,
105 "expected DPI argument direction keyword");
111 OpAsmParser::UnresolvedOperand ssaName;
112 if (parser.parseOperand(ssaName,
false))
114 argName = ssaName.name.substr(1).str();
116 if (parser.parseKeywordOrString(&argName))
121 if (parser.parseColonType(argType))
123 args.push_back({StringAttr::get(ctx, argName), argType, *dir});
125 std::optional<Location> maybeLoc;
126 if (failed(parser.parseOptionalLocationSpecifier(maybeLoc)))
129 argLocs.push_back(*maybeLoc);
132 argLocs.push_back(unknownLoc);
137 if (parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren, parseOneArg,
138 " in DPI argument list"))
141 auto dpiType = DPIFunctionType::get(ctx, args);
143 result.addAttribute(DPIFuncOp::getDpiFunctionTypeAttrName(result.name),
144 TypeAttr::get(dpiType));
146 result.addAttribute(DPIFuncOp::getArgumentLocsAttrName(result.name),
147 builder.getArrayAttr(argLocs));
150 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
155void DPIFuncOp::print(OpAsmPrinter &p) {
158 StringRef visibilityAttrName =
159 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
160 if (
auto visibility = (*this)->getAttrOfType<StringAttr>(visibilityAttrName))
161 p << visibility.getValue() <<
' ';
162 p.printSymbolName(getSymName());
164 auto dpiType = getDpiFunctionType();
165 auto dpiArgs = dpiType.getArguments();
168 llvm::interleaveComma(llvm::enumerate(dpiArgs), p, [&](
auto it) {
169 auto &arg = it.value();
176 p.printKeywordOrString(arg.name.getValue());
178 p.printType(arg.type);
180 if (getArgumentLocs()) {
181 auto loc = cast<Location>(getArgumentLocsAttr()[i]);
182 if (loc != UnknownLoc::get(getContext()))
183 p.printOptionalLocationSpecifier(loc);
188 mlir::function_interface_impl::printFunctionAttributes(
190 {visibilityAttrName, getDpiFunctionTypeAttrName(),
191 getArgumentLocsAttrName()});
194LogicalResult DPIFuncOp::verify() {
195 auto dpiType = getDpiFunctionType();
198 if (failed(dpiType.verify([&]() { return emitOpError(); })))
202 for (
auto &arg : dpiType.getArguments()) {
203 if (arg.dir == DPIDirection::Ref) {
204 if (!isa<LLVM::LLVMPointerType>(arg.type))
205 return emitOpError(
"'ref' arguments must use !llvm.ptr type");
213sim::DPICallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
215 symbolTable.lookupNearestSymbolFrom(*
this, getCalleeAttr());
217 return emitError(
"cannot find function declaration '")
218 << getCallee() <<
"'";
219 if (
auto dpiFunc = dyn_cast<sim::DPIFuncOp>(referencedOp)) {
220 auto expectedFuncType = cast<FunctionType>(dpiFunc.getFunctionType());
221 auto expectedInputs = expectedFuncType.getInputs();
222 auto expectedResults = expectedFuncType.getResults();
223 if (getInputs().size() != expectedInputs.size())
224 return emitError(
"expects ")
225 << expectedInputs.size() <<
" DPI operands, but got "
226 << getInputs().size();
227 if (getResults().size() != expectedResults.size())
228 return emitError(
"expects ")
229 << expectedResults.size() <<
" DPI results, but got "
230 << getResults().size();
231 for (
auto [operand, expectedType] : llvm::zip(getInputs(), expectedInputs))
232 if (operand.getType() != expectedType)
233 return emitError(
"operand type mismatch: expected ")
234 << expectedType <<
", but got " << operand.getType();
235 for (
auto [result, expectedType] : llvm::zip(getResults(), expectedResults))
236 if (result.getType() != expectedType)
237 return emitError(
"result type mismatch: expected ")
238 << expectedType <<
", but got " << result.getType();
241 if (isa<func::FuncOp>(referencedOp))
243 return emitError(
"callee must be 'sim.func.dpi' or 'func.func' but got '")
244 << referencedOp->getName() <<
"'";
252 const Attribute &value,
253 bool isUpperCase,
bool isLeftAligned,
255 std::optional<int32_t> specifierWidth,
256 bool isSigned =
false) {
257 auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(value);
260 if (intAttr.getType().getIntOrFloatBitWidth() == 0)
261 return StringAttr::get(ctx,
"");
264 llvm::raw_svector_ostream os(str);
265 formatInteger(os, intAttr.getValue(), radix, isUpperCase, isLeftAligned,
266 paddingChar, specifierWidth, isSigned);
267 return StringAttr::get(ctx, str);
272 std::optional<unsigned> fieldWidth,
273 std::optional<unsigned> fracDigits,
274 std::string formatSpecifier) {
275 if (
auto floatAttr = llvm::dyn_cast_or_null<FloatAttr>(value)) {
276 std::string widthString = isLeftAligned ?
"-" :
"";
277 if (fieldWidth.has_value()) {
278 widthString += std::to_string(fieldWidth.value());
280 std::string fmtSpecifier =
"%" + widthString +
"." +
281 std::to_string(fracDigits.value()) +
286 int bufferSize = std::snprintf(
nullptr, 0, fmtSpecifier.c_str(),
287 floatAttr.getValue().convertToDouble());
288 std::string floatFmtBuffer(bufferSize,
'\0');
289 snprintf(floatFmtBuffer.data(), bufferSize + 1, fmtSpecifier.c_str(),
290 floatAttr.getValue().convertToDouble());
291 return StringAttr::get(ctx, floatFmtBuffer);
299OpFoldResult FormatLiteralOp::fold(FoldAdaptor adaptor) {
300 return getLiteralAttr();
305StringAttr FormatStringOp::formatConstant(Attribute constVal) {
306 auto strAttr = llvm::dyn_cast<StringAttr>(constVal);
310 SmallString<128> strBuf(strAttr.getValue());
311 if (getSpecifierWidth().has_value()) {
312 auto padChar =
static_cast<char>(getPaddingChar());
313 unsigned padWidth = getSpecifierWidth().value();
314 padWidth = padWidth > strBuf.size() ? padWidth - strBuf.size() : 0;
315 if (getIsLeftAligned())
316 strBuf.append(padWidth, padChar);
318 strBuf.insert(strBuf.begin(), padWidth, padChar);
320 return StringAttr::get(getContext(), strBuf);
325StringAttr FormatDecOp::formatConstant(Attribute constVal) {
326 auto intAttr = llvm::dyn_cast<IntegerAttr>(constVal);
330 llvm::raw_svector_ostream os(str);
332 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth(),
334 return StringAttr::get(getContext(), str);
337OpFoldResult FormatDecOp::fold(FoldAdaptor adaptor) {
338 if (getValue().getType().getIntOrFloatBitWidth() == 0)
339 return StringAttr::get(getContext(),
"0");
345StringAttr FormatHexOp::formatConstant(Attribute constVal) {
347 getIsHexUppercase(), getIsLeftAligned(),
348 getPaddingChar(), getSpecifierWidth());
351OpFoldResult FormatHexOp::fold(FoldAdaptor adaptor) {
352 if (getValue().getType().getIntOrFloatBitWidth() == 0)
354 getContext(), 16, IntegerAttr::get(getValue().getType(), 0),
false,
355 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth());
361StringAttr FormatOctOp::formatConstant(Attribute constVal) {
363 getIsLeftAligned(), getPaddingChar(),
364 getSpecifierWidth());
367OpFoldResult FormatOctOp::fold(FoldAdaptor adaptor) {
368 if (getValue().getType().getIntOrFloatBitWidth() == 0)
370 getContext(), 8, IntegerAttr::get(getValue().getType(), 0),
false,
371 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth());
377StringAttr FormatBinOp::formatConstant(Attribute constVal) {
379 getIsLeftAligned(), getPaddingChar(),
380 getSpecifierWidth());
383OpFoldResult FormatBinOp::fold(FoldAdaptor adaptor) {
384 if (getValue().getType().getIntOrFloatBitWidth() == 0)
386 getContext(), 2, IntegerAttr::get(getValue().getType(), 0),
false,
387 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth());
393StringAttr FormatScientificOp::formatConstant(Attribute constVal) {
395 getFieldWidth(), getFracDigits(),
"e");
400StringAttr FormatFloatOp::formatConstant(Attribute constVal) {
402 getFieldWidth(), getFracDigits(),
"f");
407StringAttr FormatGeneralOp::formatConstant(Attribute constVal) {
409 getFieldWidth(), getFracDigits(),
"g");
414StringAttr FormatCharOp::formatConstant(Attribute constVal) {
415 auto intCst = dyn_cast<IntegerAttr>(constVal);
418 if (intCst.getType().getIntOrFloatBitWidth() == 0)
419 return StringAttr::get(getContext(), Twine(
static_cast<char>(0)));
420 if (intCst.getType().getIntOrFloatBitWidth() > 8)
422 auto intValue = intCst.getValue().getZExtValue();
423 return StringAttr::get(getContext(), Twine(
static_cast<char>(intValue)));
426OpFoldResult FormatCharOp::fold(FoldAdaptor adaptor) {
427 if (getValue().getType().getIntOrFloatBitWidth() == 0)
428 return StringAttr::get(getContext(), Twine(
static_cast<char>(0)));
433 assert(!lits.empty() &&
"No literals to concatenate");
434 if (lits.size() == 1)
435 return StringAttr::get(ctxt, lits.front());
436 SmallString<64> newLit;
437 for (
auto lit : lits)
439 return StringAttr::get(ctxt, newLit);
442OpFoldResult FormatStringConcatOp::fold(FoldAdaptor adaptor) {
443 if (getNumOperands() == 0)
444 return StringAttr::get(getContext(),
"");
445 if (getNumOperands() == 1) {
447 if (getResult() == getOperand(0))
449 return getOperand(0);
453 SmallVector<StringRef> lits;
454 for (
auto attr : adaptor.getInputs()) {
455 auto lit = dyn_cast_or_null<StringAttr>(attr);
463LogicalResult FormatStringConcatOp::getFlattenedInputs(
464 llvm::SmallVectorImpl<Value> &flatOperands) {
466 bool isCyclic =
false;
470 concatStack.insert({*
this, 0});
471 while (!concatStack.empty()) {
472 auto &top = concatStack.back();
473 auto currentConcat = top.first;
474 unsigned operandIndex = top.second;
477 while (operandIndex < currentConcat.getNumOperands()) {
478 auto currentOperand = currentConcat.getOperand(operandIndex);
480 if (
auto nextConcat =
481 currentOperand.getDefiningOp<FormatStringConcatOp>()) {
483 if (!concatStack.contains(nextConcat)) {
486 top.second = operandIndex + 1;
487 concatStack.insert({nextConcat, 0});
494 flatOperands.push_back(currentOperand);
499 if (operandIndex >= currentConcat.getNumOperands())
500 concatStack.pop_back();
506LogicalResult FormatStringConcatOp::verify() {
507 if (llvm::any_of(getOperands(),
508 [&](Value operand) {
return operand == getResult(); }))
509 return emitOpError(
"is infinitely recursive.");
513LogicalResult FormatStringConcatOp::canonicalize(FormatStringConcatOp op,
514 PatternRewriter &rewriter) {
516 rewriter.setInsertionPoint(op);
518 auto fmtStrType = FormatStringType::get(op.getContext());
521 bool hasBeenFlattened =
false;
522 SmallVector<Value, 0> flatOperands;
525 flatOperands.reserve(op.getNumOperands() + 4);
526 auto isAcyclic = op.getFlattenedInputs(flatOperands);
528 if (failed(isAcyclic)) {
531 op.emitWarning(
"Cyclic concatenation detected.");
535 hasBeenFlattened =
true;
538 if (!hasBeenFlattened && op.getNumOperands() < 2)
543 SmallVector<StringRef> litSequence;
544 SmallVector<Value> newOperands;
545 newOperands.reserve(op.getNumOperands());
546 FormatLiteralOp prevLitOp;
548 auto oldOperands = hasBeenFlattened ? flatOperands : op.getOperands();
549 for (
auto operand : oldOperands) {
550 if (
auto litOp = operand.getDefiningOp<FormatLiteralOp>()) {
551 if (!litOp.getLiteral().empty()) {
553 litSequence.push_back(litOp.getLiteral());
556 if (!litSequence.empty()) {
557 if (litSequence.size() > 1) {
559 auto newLit = rewriter.createOrFold<FormatLiteralOp>(
560 op.getLoc(), fmtStrType,
562 newOperands.push_back(newLit);
565 newOperands.push_back(prevLitOp.getResult());
569 newOperands.push_back(operand);
574 if (!litSequence.empty()) {
575 if (litSequence.size() > 1) {
577 auto newLit = rewriter.createOrFold<FormatLiteralOp>(
578 op.getLoc(), fmtStrType,
580 newOperands.push_back(newLit);
583 newOperands.push_back(prevLitOp.getResult());
587 if (!hasBeenFlattened && newOperands.size() == op.getNumOperands())
590 if (newOperands.empty())
591 rewriter.replaceOpWithNewOp<FormatLiteralOp>(op, fmtStrType,
592 rewriter.getStringAttr(
""));
593 else if (newOperands.size() == 1)
594 rewriter.replaceOp(op, newOperands);
596 rewriter.modifyOpInPlace(op, [&]() { op->setOperands(newOperands); });
601LogicalResult PrintFormattedOp::canonicalize(PrintFormattedOp op,
602 PatternRewriter &rewriter) {
604 if (
auto cstCond = op.getCondition().getDefiningOp<
hw::ConstantOp>()) {
605 if (cstCond.getValue().isZero()) {
606 rewriter.eraseOp(op);
613LogicalResult PrintFormattedProcOp::canonicalize(PrintFormattedProcOp op,
614 PatternRewriter &rewriter) {
616 if (
auto litInput = op.getInput().getDefiningOp<FormatLiteralOp>()) {
617 if (litInput.getLiteral().empty()) {
618 rewriter.eraseOp(op);
625OpFoldResult StringConstantOp::fold(FoldAdaptor adaptor) {
626 return adaptor.getLiteralAttr();
629OpFoldResult StringConcatOp::fold(FoldAdaptor adaptor) {
630 auto operands = adaptor.getInputs();
631 if (operands.empty())
632 return StringAttr::get(getContext(),
"");
634 SmallString<128> result;
635 for (
auto &operand : operands) {
636 auto strAttr = cast_if_present<StringAttr>(operand);
639 result += strAttr.getValue();
642 return StringAttr::get(getContext(), result);
645OpFoldResult StringLengthOp::fold(FoldAdaptor adaptor) {
646 auto inputAttr = adaptor.getInput();
650 if (
auto strAttr = cast<StringAttr>(inputAttr))
651 return IntegerAttr::get(getType(), strAttr.getValue().size());
656OpFoldResult IntToStringOp::fold(FoldAdaptor adaptor) {
657 auto intAttr = cast_or_null<IntegerAttr>(adaptor.getInput());
661 SmallString<128> result;
662 auto width = intAttr.getType().getIntOrFloatBitWidth();
667 for (
unsigned int i = 0; i < width; i += 8) {
669 intAttr.getValue().extractBitsAsZExtValue(std::min(width - i, 8U), i);
671 result.push_back(
static_cast<char>(
byte));
673 std::reverse(result.begin(), result.end());
674 return StringAttr::get(getContext(), result);
682OpFoldResult StringGetOp::fold(FoldAdaptor adaptor) {
683 auto strAttr = cast_or_null<StringAttr>(adaptor.getStr());
684 auto indexAttr = cast_or_null<IntegerAttr>(adaptor.getIndex());
685 if (!strAttr || !indexAttr)
688 auto str = strAttr.getValue();
689 int64_t index = indexAttr.getValue().getSExtValue();
692 if (index < 0 || index >=
static_cast<int64_t
>(str.size()))
693 return IntegerAttr::get(getType(), 0);
696 uint8_t ch =
static_cast<uint8_t
>(str[index]);
697 return IntegerAttr::get(getType(), ch);
704OpFoldResult StringSubstrOp::fold(FoldAdaptor adaptor) {
705 auto strAttr = cast_if_present<StringAttr>(adaptor.getStr());
706 auto startAttr = cast_if_present<IntegerAttr>(adaptor.getStart());
707 if (!strAttr || !startAttr)
710 auto str = strAttr.getValue();
711 auto start = std::max(int64_t(0), startAttr.getValue().getSExtValue());
714 return StringAttr::get(getContext(), str.substr(start));
716 auto endAttr = cast_if_present<IntegerAttr>(adaptor.getEnd());
720 auto end = endAttr.getValue().getSExtValue();
724 return StringAttr::get(getContext(),
725 str.substr(start, std::max(int64_t(0), end - start)));
732LogicalResult QueueResizeOp::verify() {
733 if (cast<QueueType>(getInput().getType()).getElementType() !=
734 cast<QueueType>(getResult().getType()).getElementType())
739LogicalResult QueueFromArrayOp::verify() {
740 auto queueElementType =
741 cast<QueueType>(getResult().getType()).getElementType();
743 auto arrayElementType =
744 cast<hw::ArrayType>(getInput().getType()).getElementType();
746 if (queueElementType != arrayElementType) {
747 return emitOpError() <<
"sim::Queue element type " << queueElementType
748 <<
" doesn't match hw::ArrayType element type "
755LogicalResult QueueConcatOp::verify() {
758 auto resultElType = cast<QueueType>(getResult().getType()).getElementType();
760 for (Value input : getInputs()) {
761 auto inpElType = cast<QueueType>(input.getType()).getElementType();
762 if (inpElType != resultElType) {
763 return emitOpError() <<
"sim::Queue element type " << inpElType
764 <<
" doesn't match result sim::Queue element type "
776void TriggeredOp::build(OpBuilder &builder, OperationState &odsState,
777 Value clock, Value condition) {
778 odsState.addOperands(clock);
780 odsState.addOperands(condition);
782 auto *region = odsState.addRegion();
783 region->push_back(
new Block());
786void TriggeredOp::build(OpBuilder &builder, OperationState &odsState,
787 Value clock, Value condition,
788 llvm::function_ref<
void()> bodyCtor) {
789 OpBuilder::InsertionGuard guard(builder);
791 odsState.addOperands(clock);
793 odsState.addOperands(condition);
795 builder.createBlock(odsState.addRegion());
804LogicalResult SVReadMemOp::verify() {
805 if (getFinishAddr() && !getStartAddr())
806 return emitOpError(
"'finishAddr' requires 'startAddr' to be present");
807 if (getSliceLeft() && !getSliceRight())
808 return emitOpError(
"'sliceLeft' requires 'sliceRight' to be present");
809 if (getSliceRight() && !getSliceLeft())
810 return emitOpError(
"'sliceRight' requires 'sliceLeft' to be present");
811 if (getDimLows().
empty() || getDimLows().size() != getDimDescending().size())
812 return emitOpError(
"'dimLows' and 'dimDescending' must have one entry per "
813 "unpacked dimension");
821#include "circt/Dialect/Sim/SimOpInterfaces.cpp.inc"
824#define GET_OP_CLASSES
825#include "circt/Dialect/Sim/Sim.cpp.inc"
826#include "circt/Dialect/Sim/SimEnums.cpp.inc"
assert(baseType &&"element must be base type")
false return failure()
Parse an optional keyword or string and set instance into 'result'.
static StringAttr formatFloatsBySpecifier(MLIRContext *ctx, Attribute value, bool isLeftAligned, std::optional< unsigned > fieldWidth, std::optional< unsigned > fracDigits, std::string formatSpecifier)
static StringAttr formatIntegersByRadix(MLIRContext *ctx, unsigned radix, const Attribute &value, bool isUpperCase, bool isLeftAligned, char paddingChar, std::optional< int32_t > specifierWidth, bool isSigned=false)
static StringAttr concatLiterals(MLIRContext *ctxt, ArrayRef< StringRef > lits)
static InstancePath empty
llvm::StringRef stringifyDPIDirectionKeyword(DPIDirection dir)
Return the keyword string for a DPIDirection (e.g. "in", "return").
std::optional< DPIDirection > parseDPIDirectionKeyword(llvm::StringRef keyword)
Parse a keyword string to a DPIDirection. Returns std::nullopt on failure.
bool isCallOperandDir(DPIDirection dir)
True if an argument with this direction is a call operand (input/inout/ref).
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
void formatInteger(llvm::raw_ostream &os, const llvm::APInt &value, unsigned radix, bool isUpperCase, bool isLeftAligned, char paddingChar, std::optional< int32_t > specifierWidth, bool isSigned)
Format value in the given radix and emit it to os, padded to a field width.