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"
34void DPIFuncOp::build(OpBuilder &odsBuilder, OperationState &odsState,
35 StringAttr symName, ArrayRef<StringAttr> argNames,
36 ArrayRef<Type> argTypes,
37 ArrayRef<DPIDirection> argDirections, ArrayAttr argLocs,
38 StringAttr verilogName) {
40 SmallVector<DPIArgument> args;
41 args.reserve(argNames.size());
42 for (
auto [name, type, dir] :
llvm::zip(argNames, argTypes, argDirections))
43 args.push_back({name, type, dir});
44 auto dpiType = DPIFunctionType::get(odsBuilder.getContext(), args);
45 build(odsBuilder, odsState, symName, dpiType, argLocs, verilogName);
48void DPIFuncOp::build(OpBuilder &odsBuilder, OperationState &odsState,
49 StringAttr symName, DPIFunctionType dpiFunctionType,
50 ArrayAttr argLocs, StringAttr verilogName) {
51 odsState.addAttribute(getSymNameAttrName(odsState.name), symName);
52 odsState.addAttribute(getDpiFunctionTypeAttrName(odsState.name),
53 TypeAttr::get(dpiFunctionType));
55 odsState.addAttribute(getArgumentLocsAttrName(odsState.name), argLocs);
57 odsState.addAttribute(getVerilogNameAttrName(odsState.name), verilogName);
61::mlir::Type DPIFuncOp::getFunctionType() {
62 return getDpiFunctionType().getFunctionType();
65void DPIFuncOp::setFunctionTypeAttr(::mlir::TypeAttr type) {
67 auto dpiType = llvm::dyn_cast<DPIFunctionType>(type.getValue());
68 assert(dpiType &&
"DPIFuncOp function type can only be set via "
69 "DPIFunctionType, not a plain FunctionType");
70 setDpiFunctionType(dpiType);
73::mlir::Type DPIFuncOp::cloneTypeWith(::mlir::TypeRange inputs,
74 ::mlir::TypeRange results) {
75 return FunctionType::get(getContext(), inputs, results);
78ParseResult DPIFuncOp::parse(OpAsmParser &parser, OperationState &result) {
79 auto builder = parser.getBuilder();
80 auto ctx = builder.getContext();
82 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
85 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
89 SmallVector<DPIArgument> args;
90 SmallVector<Attribute> argLocs;
91 auto unknownLoc = builder.getUnknownLoc();
94 auto parseOneArg = [&]() -> ParseResult {
96 auto keyLoc = parser.getCurrentLocation();
97 if (parser.parseKeyword(&dirKeyword))
101 return parser.emitError(keyLoc,
102 "expected DPI argument direction keyword");
108 OpAsmParser::UnresolvedOperand ssaName;
109 if (parser.parseOperand(ssaName,
false))
111 argName = ssaName.name.substr(1).str();
113 if (parser.parseKeywordOrString(&argName))
118 if (parser.parseColonType(argType))
120 args.push_back({StringAttr::get(ctx, argName), argType, *dir});
122 std::optional<Location> maybeLoc;
123 if (failed(parser.parseOptionalLocationSpecifier(maybeLoc)))
126 argLocs.push_back(*maybeLoc);
129 argLocs.push_back(unknownLoc);
134 if (parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren, parseOneArg,
135 " in DPI argument list"))
138 auto dpiType = DPIFunctionType::get(ctx, args);
140 result.addAttribute(DPIFuncOp::getDpiFunctionTypeAttrName(result.name),
141 TypeAttr::get(dpiType));
143 result.addAttribute(DPIFuncOp::getArgumentLocsAttrName(result.name),
144 builder.getArrayAttr(argLocs));
147 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
152void DPIFuncOp::print(OpAsmPrinter &p) {
155 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
156 if (
auto visibility = (*this)->getAttrOfType<StringAttr>(visibilityAttrName))
157 p << visibility.getValue() <<
' ';
158 p.printSymbolName(getSymName());
160 auto dpiType = getDpiFunctionType();
161 auto dpiArgs = dpiType.getArguments();
164 llvm::interleaveComma(llvm::enumerate(dpiArgs), p, [&](
auto it) {
165 auto &arg = it.value();
172 p.printKeywordOrString(arg.name.getValue());
174 p.printType(arg.type);
176 if (getArgumentLocs()) {
177 auto loc = cast<Location>(getArgumentLocsAttr()[i]);
178 if (loc != UnknownLoc::get(getContext()))
179 p.printOptionalLocationSpecifier(loc);
184 mlir::function_interface_impl::printFunctionAttributes(
186 {visibilityAttrName, getDpiFunctionTypeAttrName(),
187 getArgumentLocsAttrName()});
190LogicalResult DPIFuncOp::verify() {
191 auto dpiType = getDpiFunctionType();
194 if (failed(dpiType.verify([&]() { return emitOpError(); })))
198 for (
auto &arg : dpiType.getArguments()) {
199 if (arg.dir == DPIDirection::Ref) {
200 if (!isa<LLVM::LLVMPointerType>(arg.type))
201 return emitOpError(
"'ref' arguments must use !llvm.ptr type");
209sim::DPICallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
211 symbolTable.lookupNearestSymbolFrom(*
this, getCalleeAttr());
213 return emitError(
"cannot find function declaration '")
214 << getCallee() <<
"'";
215 if (
auto dpiFunc = dyn_cast<sim::DPIFuncOp>(referencedOp)) {
216 auto expectedFuncType = cast<FunctionType>(dpiFunc.getFunctionType());
217 auto expectedInputs = expectedFuncType.getInputs();
218 auto expectedResults = expectedFuncType.getResults();
219 if (getInputs().size() != expectedInputs.size())
220 return emitError(
"expects ")
221 << expectedInputs.size() <<
" DPI operands, but got "
222 << getInputs().size();
223 if (getResults().size() != expectedResults.size())
224 return emitError(
"expects ")
225 << expectedResults.size() <<
" DPI results, but got "
226 << getResults().size();
227 for (
auto [operand, expectedType] :
llvm::zip(getInputs(), expectedInputs))
228 if (operand.getType() != expectedType)
229 return emitError(
"operand type mismatch: expected ")
230 << expectedType <<
", but got " << operand.getType();
231 for (
auto [result, expectedType] :
llvm::zip(getResults(), expectedResults))
232 if (result.getType() != expectedType)
233 return emitError(
"result type mismatch: expected ")
234 << expectedType <<
", but got " << result.getType();
237 if (isa<func::FuncOp>(referencedOp))
239 return emitError(
"callee must be 'sim.func.dpi' or 'func.func' but got '")
240 << referencedOp->getName() <<
"'";
248 const Attribute &value,
249 bool isUpperCase,
bool isLeftAligned,
251 std::optional<int32_t> specifierWidth,
252 bool isSigned =
false) {
253 auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(value);
256 if (intAttr.getType().getIntOrFloatBitWidth() == 0)
257 return StringAttr::get(ctx,
"");
260 llvm::raw_svector_ostream os(str);
261 formatInteger(os, intAttr.getValue(), radix, isUpperCase, isLeftAligned,
262 paddingChar, specifierWidth, isSigned);
263 return StringAttr::get(ctx, str);
268 std::optional<unsigned> fieldWidth,
269 std::optional<unsigned> fracDigits,
270 std::string formatSpecifier) {
271 if (
auto floatAttr = llvm::dyn_cast_or_null<FloatAttr>(value)) {
272 std::string widthString = isLeftAligned ?
"-" :
"";
273 if (fieldWidth.has_value()) {
274 widthString += std::to_string(fieldWidth.value());
276 std::string fmtSpecifier =
"%" + widthString +
"." +
277 std::to_string(fracDigits.value()) +
282 int bufferSize = std::snprintf(
nullptr, 0, fmtSpecifier.c_str(),
283 floatAttr.getValue().convertToDouble());
284 std::string floatFmtBuffer(bufferSize,
'\0');
285 snprintf(floatFmtBuffer.data(), bufferSize + 1, fmtSpecifier.c_str(),
286 floatAttr.getValue().convertToDouble());
287 return StringAttr::get(ctx, floatFmtBuffer);
295OpFoldResult FormatLiteralOp::fold(FoldAdaptor adaptor) {
296 return getLiteralAttr();
301StringAttr FormatStringOp::formatConstant(Attribute constVal) {
302 auto strAttr = llvm::dyn_cast<StringAttr>(constVal);
306 SmallString<128> strBuf(strAttr.getValue());
307 if (getSpecifierWidth().has_value()) {
308 auto padChar =
static_cast<char>(getPaddingChar());
309 unsigned padWidth = getSpecifierWidth().value();
310 padWidth = padWidth > strBuf.size() ? padWidth - strBuf.size() : 0;
311 if (getIsLeftAligned())
312 strBuf.append(padWidth, padChar);
314 strBuf.insert(strBuf.begin(), padWidth, padChar);
316 return StringAttr::get(getContext(), strBuf);
321StringAttr FormatDecOp::formatConstant(Attribute constVal) {
322 auto intAttr = llvm::dyn_cast<IntegerAttr>(constVal);
326 llvm::raw_svector_ostream os(str);
328 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth(),
330 return StringAttr::get(getContext(), str);
333OpFoldResult FormatDecOp::fold(FoldAdaptor adaptor) {
334 if (getValue().getType().getIntOrFloatBitWidth() == 0)
335 return StringAttr::get(getContext(),
"0");
341StringAttr FormatHexOp::formatConstant(Attribute constVal) {
343 getIsHexUppercase(), getIsLeftAligned(),
344 getPaddingChar(), getSpecifierWidth());
347OpFoldResult FormatHexOp::fold(FoldAdaptor adaptor) {
348 if (getValue().getType().getIntOrFloatBitWidth() == 0)
350 getContext(), 16, IntegerAttr::get(getValue().getType(), 0),
false,
351 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth());
357StringAttr FormatOctOp::formatConstant(Attribute constVal) {
359 getIsLeftAligned(), getPaddingChar(),
360 getSpecifierWidth());
363OpFoldResult FormatOctOp::fold(FoldAdaptor adaptor) {
364 if (getValue().getType().getIntOrFloatBitWidth() == 0)
366 getContext(), 8, IntegerAttr::get(getValue().getType(), 0),
false,
367 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth());
373StringAttr FormatBinOp::formatConstant(Attribute constVal) {
375 getIsLeftAligned(), getPaddingChar(),
376 getSpecifierWidth());
379OpFoldResult FormatBinOp::fold(FoldAdaptor adaptor) {
380 if (getValue().getType().getIntOrFloatBitWidth() == 0)
382 getContext(), 2, IntegerAttr::get(getValue().getType(), 0),
false,
383 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth());
389StringAttr FormatScientificOp::formatConstant(Attribute constVal) {
391 getFieldWidth(), getFracDigits(),
"e");
396StringAttr FormatFloatOp::formatConstant(Attribute constVal) {
398 getFieldWidth(), getFracDigits(),
"f");
403StringAttr FormatGeneralOp::formatConstant(Attribute constVal) {
405 getFieldWidth(), getFracDigits(),
"g");
410StringAttr FormatCharOp::formatConstant(Attribute constVal) {
411 auto intCst = dyn_cast<IntegerAttr>(constVal);
414 if (intCst.getType().getIntOrFloatBitWidth() == 0)
415 return StringAttr::get(getContext(), Twine(
static_cast<char>(0)));
416 if (intCst.getType().getIntOrFloatBitWidth() > 8)
418 auto intValue = intCst.getValue().getZExtValue();
419 return StringAttr::get(getContext(), Twine(
static_cast<char>(intValue)));
422OpFoldResult FormatCharOp::fold(FoldAdaptor adaptor) {
423 if (getValue().getType().getIntOrFloatBitWidth() == 0)
424 return StringAttr::get(getContext(), Twine(
static_cast<char>(0)));
429 assert(!lits.empty() &&
"No literals to concatenate");
430 if (lits.size() == 1)
431 return StringAttr::get(ctxt, lits.front());
432 SmallString<64> newLit;
433 for (
auto lit : lits)
435 return StringAttr::get(ctxt, newLit);
438OpFoldResult FormatStringConcatOp::fold(FoldAdaptor adaptor) {
439 if (getNumOperands() == 0)
440 return StringAttr::get(getContext(),
"");
441 if (getNumOperands() == 1) {
443 if (getResult() == getOperand(0))
445 return getOperand(0);
449 SmallVector<StringRef> lits;
450 for (
auto attr : adaptor.getInputs()) {
451 auto lit = dyn_cast_or_null<StringAttr>(attr);
459LogicalResult FormatStringConcatOp::getFlattenedInputs(
460 llvm::SmallVectorImpl<Value> &flatOperands) {
462 bool isCyclic =
false;
466 concatStack.insert({*
this, 0});
467 while (!concatStack.empty()) {
468 auto &top = concatStack.back();
469 auto currentConcat = top.first;
470 unsigned operandIndex = top.second;
473 while (operandIndex < currentConcat.getNumOperands()) {
474 auto currentOperand = currentConcat.getOperand(operandIndex);
476 if (
auto nextConcat =
477 currentOperand.getDefiningOp<FormatStringConcatOp>()) {
479 if (!concatStack.contains(nextConcat)) {
482 top.second = operandIndex + 1;
483 concatStack.insert({nextConcat, 0});
490 flatOperands.push_back(currentOperand);
495 if (operandIndex >= currentConcat.getNumOperands())
496 concatStack.pop_back();
499 return success(!isCyclic);
502LogicalResult FormatStringConcatOp::verify() {
503 if (llvm::any_of(getOperands(),
504 [&](Value operand) {
return operand == getResult(); }))
505 return emitOpError(
"is infinitely recursive.");
509LogicalResult FormatStringConcatOp::canonicalize(FormatStringConcatOp op,
510 PatternRewriter &rewriter) {
512 rewriter.setInsertionPoint(op);
514 auto fmtStrType = FormatStringType::get(op.getContext());
517 bool hasBeenFlattened =
false;
518 SmallVector<Value, 0> flatOperands;
521 flatOperands.reserve(op.getNumOperands() + 4);
522 auto isAcyclic = op.getFlattenedInputs(flatOperands);
524 if (failed(isAcyclic)) {
527 op.emitWarning(
"Cyclic concatenation detected.");
531 hasBeenFlattened =
true;
534 if (!hasBeenFlattened && op.getNumOperands() < 2)
539 SmallVector<StringRef> litSequence;
540 SmallVector<Value> newOperands;
541 newOperands.reserve(op.getNumOperands());
542 FormatLiteralOp prevLitOp;
544 auto oldOperands = hasBeenFlattened ? flatOperands : op.getOperands();
545 for (
auto operand : oldOperands) {
546 if (
auto litOp = operand.getDefiningOp<FormatLiteralOp>()) {
547 if (!litOp.getLiteral().empty()) {
549 litSequence.push_back(litOp.getLiteral());
552 if (!litSequence.empty()) {
553 if (litSequence.size() > 1) {
555 auto newLit = rewriter.createOrFold<FormatLiteralOp>(
556 op.getLoc(), fmtStrType,
558 newOperands.push_back(newLit);
561 newOperands.push_back(prevLitOp.getResult());
565 newOperands.push_back(operand);
570 if (!litSequence.empty()) {
571 if (litSequence.size() > 1) {
573 auto newLit = rewriter.createOrFold<FormatLiteralOp>(
574 op.getLoc(), fmtStrType,
576 newOperands.push_back(newLit);
579 newOperands.push_back(prevLitOp.getResult());
583 if (!hasBeenFlattened && newOperands.size() == op.getNumOperands())
586 if (newOperands.empty())
587 rewriter.replaceOpWithNewOp<FormatLiteralOp>(op, fmtStrType,
588 rewriter.getStringAttr(
""));
589 else if (newOperands.size() == 1)
590 rewriter.replaceOp(op, newOperands);
592 rewriter.modifyOpInPlace(op, [&]() { op->setOperands(newOperands); });
597LogicalResult PrintFormattedOp::canonicalize(PrintFormattedOp op,
598 PatternRewriter &rewriter) {
600 if (
auto cstCond = op.getCondition().getDefiningOp<
hw::ConstantOp>()) {
601 if (cstCond.getValue().isZero()) {
602 rewriter.eraseOp(op);
609LogicalResult PrintFormattedProcOp::canonicalize(PrintFormattedProcOp op,
610 PatternRewriter &rewriter) {
612 if (
auto litInput = op.getInput().getDefiningOp<FormatLiteralOp>()) {
613 if (litInput.getLiteral().empty()) {
614 rewriter.eraseOp(op);
621OpFoldResult StringConstantOp::fold(FoldAdaptor adaptor) {
622 return adaptor.getLiteralAttr();
625OpFoldResult StringConcatOp::fold(FoldAdaptor adaptor) {
626 auto operands = adaptor.getInputs();
627 if (operands.empty())
628 return StringAttr::get(getContext(),
"");
630 SmallString<128> result;
631 for (
auto &operand : operands) {
632 auto strAttr = cast_if_present<StringAttr>(operand);
635 result += strAttr.getValue();
638 return StringAttr::get(getContext(), result);
641OpFoldResult StringLengthOp::fold(FoldAdaptor adaptor) {
642 auto inputAttr = adaptor.getInput();
646 if (
auto strAttr = cast<StringAttr>(inputAttr))
647 return IntegerAttr::get(getType(), strAttr.getValue().size());
652OpFoldResult IntToStringOp::fold(FoldAdaptor adaptor) {
653 auto intAttr = cast_or_null<IntegerAttr>(adaptor.getInput());
657 SmallString<128> result;
658 auto width = intAttr.getType().getIntOrFloatBitWidth();
663 for (
unsigned int i = 0; i < width; i += 8) {
665 intAttr.getValue().extractBitsAsZExtValue(std::min(width - i, 8U), i);
667 result.push_back(
static_cast<char>(
byte));
669 std::reverse(result.begin(), result.end());
670 return StringAttr::get(getContext(), result);
678OpFoldResult StringGetOp::fold(FoldAdaptor adaptor) {
679 auto strAttr = cast_or_null<StringAttr>(adaptor.getStr());
680 auto indexAttr = cast_or_null<IntegerAttr>(adaptor.getIndex());
681 if (!strAttr || !indexAttr)
684 auto str = strAttr.getValue();
685 int64_t index = indexAttr.getValue().getSExtValue();
688 if (index < 0 || index >=
static_cast<int64_t
>(str.size()))
689 return IntegerAttr::get(getType(), 0);
692 uint8_t ch =
static_cast<uint8_t
>(str[index]);
693 return IntegerAttr::get(getType(), ch);
700LogicalResult QueueResizeOp::verify() {
701 if (cast<QueueType>(getInput().getType()).getElementType() !=
702 cast<QueueType>(getResult().getType()).getElementType())
707LogicalResult QueueFromArrayOp::verify() {
708 auto queueElementType =
709 cast<QueueType>(getResult().getType()).getElementType();
711 auto arrayElementType =
712 cast<hw::ArrayType>(getInput().getType()).getElementType();
714 if (queueElementType != arrayElementType) {
715 return emitOpError() <<
"sim::Queue element type " << queueElementType
716 <<
" doesn't match hw::ArrayType element type "
723LogicalResult QueueConcatOp::verify() {
726 auto resultElType = cast<QueueType>(getResult().getType()).getElementType();
728 for (Value input : getInputs()) {
729 auto inpElType = cast<QueueType>(input.getType()).getElementType();
730 if (inpElType != resultElType) {
731 return emitOpError() <<
"sim::Queue element type " << inpElType
732 <<
" doesn't match result sim::Queue element type "
744void TriggeredOp::build(OpBuilder &builder, OperationState &odsState,
745 Value clock, Value condition) {
746 odsState.addOperands(clock);
748 odsState.addOperands(condition);
750 auto *region = odsState.addRegion();
751 region->push_back(
new Block());
754void TriggeredOp::build(OpBuilder &builder, OperationState &odsState,
755 Value clock, Value condition,
756 llvm::function_ref<
void()> bodyCtor) {
757 OpBuilder::InsertionGuard guard(builder);
759 odsState.addOperands(clock);
761 odsState.addOperands(condition);
763 builder.createBlock(odsState.addRegion());
772#include "circt/Dialect/Sim/SimOpInterfaces.cpp.inc"
775#define GET_OP_CLASSES
776#include "circt/Dialect/Sim/Sim.cpp.inc"
777#include "circt/Dialect/Sim/SimEnums.cpp.inc"
assert(baseType &&"element must be base type")
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)
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.