17#include "mlir/Dialect/Func/IR/FuncOps.h"
18#include "mlir/IR/PatternMatch.h"
19#include "mlir/Interfaces/FunctionImplementation.h"
20#include "llvm/ADT/MapVector.h"
27 const Attribute &value,
28 bool isUpperCase,
bool isLeftAligned,
30 std::optional<unsigned> specifierWidth,
31 bool isSigned =
false) {
32 auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(value);
35 if (intAttr.getType().getIntOrFloatBitWidth() == 0)
36 return StringAttr::get(ctx,
"");
38 SmallVector<char, 32> strBuf;
39 intAttr.getValue().toString(strBuf, radix, isSigned,
false, isUpperCase);
40 unsigned width = intAttr.getType().getIntOrFloatBitWidth();
48 padWidth = (width + 2) / 3;
51 padWidth = (width + 3) / 4;
58 unsigned numSpaces = 0;
59 if (specifierWidth.has_value() &&
60 (specifierWidth.value() >
61 std::max(padWidth,
static_cast<unsigned>(strBuf.size())))) {
63 0U, specifierWidth.value() -
64 std::max(padWidth,
static_cast<unsigned>(strBuf.size())));
67 SmallVector<char, 1> spacePadding(numSpaces,
' ');
69 padWidth = padWidth > strBuf.size() ? padWidth - strBuf.size() : 0;
71 SmallVector<char, 32> padding(padWidth, paddingChar);
73 return StringAttr::get(ctx, Twine(padding) + Twine(strBuf) +
76 return StringAttr::get(ctx,
77 Twine(spacePadding) + Twine(padding) + Twine(strBuf));
82 std::optional<unsigned> fieldWidth,
83 std::optional<unsigned> fracDigits,
84 std::string formatSpecifier) {
85 if (
auto floatAttr = llvm::dyn_cast_or_null<FloatAttr>(value)) {
86 std::string widthString = isLeftAligned ?
"-" :
"";
87 if (fieldWidth.has_value()) {
88 widthString += std::to_string(fieldWidth.value());
90 std::string fmtSpecifier =
"%" + widthString +
"." +
91 std::to_string(fracDigits.value()) +
96 int bufferSize = std::snprintf(
nullptr, 0, fmtSpecifier.c_str(),
97 floatAttr.getValue().convertToDouble());
98 std::string floatFmtBuffer(bufferSize,
'\0');
99 snprintf(floatFmtBuffer.data(), bufferSize + 1, fmtSpecifier.c_str(),
100 floatAttr.getValue().convertToDouble());
101 return StringAttr::get(ctx, floatFmtBuffer);
106ParseResult DPIFuncOp::parse(OpAsmParser &parser, OperationState &result) {
107 auto builder = parser.getBuilder();
109 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
113 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
117 SmallVector<hw::module_like_impl::PortParse> ports;
123 result.addAttribute(DPIFuncOp::getModuleTypeAttrName(result.name), modType);
127 auto unknownLoc = builder.getUnknownLoc();
128 SmallVector<Attribute> attrs, locs;
129 auto nonEmptyLocsFn = [unknownLoc](Attribute attr) {
130 return attr && cast<Location>(attr) != unknownLoc;
133 for (
auto &port : ports) {
134 attrs.push_back(port.attrs ? port.attrs : builder.getDictionaryAttr({}));
135 locs.push_back(port.sourceLoc ? Location(*port.sourceLoc) : unknownLoc);
138 result.addAttribute(DPIFuncOp::getPerArgumentAttrsAttrName(result.name),
139 builder.getArrayAttr(attrs));
142 if (llvm::any_of(locs, nonEmptyLocsFn))
143 result.addAttribute(DPIFuncOp::getArgumentLocsAttrName(result.name),
144 builder.getArrayAttr(locs));
147 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
154sim::DPICallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
156 symbolTable.lookupNearestSymbolFrom(*
this, getCalleeAttr());
158 return emitError(
"cannot find function declaration '")
159 << getCallee() <<
"'";
160 if (isa<func::FuncOp, sim::DPIFuncOp>(referencedOp))
162 return emitError(
"callee must be 'sim.dpi.func' or 'func.func' but got '")
163 << referencedOp->getName() <<
"'";
166void DPIFuncOp::print(OpAsmPrinter &p) {
167 DPIFuncOp op = *
this;
170 op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())
174 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
175 if (
auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName))
176 p << visibility.getValue() <<
' ';
177 p.printSymbolName(funcName);
179 p, op->getRegion(0), op.getModuleType(),
180 getPerArgumentAttrsAttr()
181 ? ArrayRef<Attribute>(getPerArgumentAttrsAttr().getValue())
182 : ArrayRef<Attribute>{},
183 getArgumentLocs() ? SmallVector<Location>(
184 getArgumentLocs().value().getAsRange<Location>())
185 : ArrayRef<Location>{});
187 mlir::function_interface_impl::printFunctionAttributes(
189 {visibilityAttrName, getModuleTypeAttrName(),
190 getPerArgumentAttrsAttrName(), getArgumentLocsAttrName()});
193OpFoldResult FormatLiteralOp::fold(FoldAdaptor adaptor) {
194 return getLiteralAttr();
199StringAttr FormatDecOp::formatConstant(Attribute constVal) {
200 auto intAttr = llvm::dyn_cast<IntegerAttr>(constVal);
203 SmallVector<char, 16> strBuf;
204 intAttr.getValue().toString(strBuf, 10, getIsSigned());
206 if (getSpecifierWidth().has_value()) {
207 padWidth = getSpecifierWidth().value();
209 unsigned width = intAttr.getType().getIntOrFloatBitWidth();
210 padWidth = FormatDecOp::getDecimalWidth(width, getIsSigned());
213 padWidth = padWidth > strBuf.size() ? padWidth - strBuf.size() : 0;
215 SmallVector<char, 10> padding(padWidth, getPaddingChar());
216 if (getIsLeftAligned())
217 return StringAttr::get(getContext(), Twine(strBuf) + Twine(padding));
218 return StringAttr::get(getContext(), Twine(padding) + Twine(strBuf));
221OpFoldResult FormatDecOp::fold(FoldAdaptor adaptor) {
222 if (getValue().getType().getIntOrFloatBitWidth() == 0)
223 return StringAttr::get(getContext(),
"0");
229StringAttr FormatHexOp::formatConstant(Attribute constVal) {
231 getIsHexUppercase(), getIsLeftAligned(),
232 getPaddingChar(), getSpecifierWidth());
235OpFoldResult FormatHexOp::fold(FoldAdaptor adaptor) {
236 if (getValue().getType().getIntOrFloatBitWidth() == 0)
238 getContext(), 16, IntegerAttr::get(getValue().getType(), 0),
false,
239 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth());
245StringAttr FormatOctOp::formatConstant(Attribute constVal) {
247 getIsLeftAligned(), getPaddingChar(),
248 getSpecifierWidth());
251OpFoldResult FormatOctOp::fold(FoldAdaptor adaptor) {
252 if (getValue().getType().getIntOrFloatBitWidth() == 0)
254 getContext(), 8, IntegerAttr::get(getValue().getType(), 0),
false,
255 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth());
261StringAttr FormatBinOp::formatConstant(Attribute constVal) {
263 getIsLeftAligned(), getPaddingChar(),
264 getSpecifierWidth());
267OpFoldResult FormatBinOp::fold(FoldAdaptor adaptor) {
268 if (getValue().getType().getIntOrFloatBitWidth() == 0)
270 getContext(), 2, IntegerAttr::get(getValue().getType(), 0),
false,
271 getIsLeftAligned(), getPaddingChar(), getSpecifierWidth());
277StringAttr FormatScientificOp::formatConstant(Attribute constVal) {
279 getFieldWidth(), getFracDigits(),
"e");
284StringAttr FormatFloatOp::formatConstant(Attribute constVal) {
286 getFieldWidth(), getFracDigits(),
"f");
291StringAttr FormatGeneralOp::formatConstant(Attribute constVal) {
293 getFieldWidth(), getFracDigits(),
"g");
298StringAttr FormatCharOp::formatConstant(Attribute constVal) {
299 auto intCst = dyn_cast<IntegerAttr>(constVal);
302 if (intCst.getType().getIntOrFloatBitWidth() == 0)
303 return StringAttr::get(getContext(), Twine(
static_cast<char>(0)));
304 if (intCst.getType().getIntOrFloatBitWidth() > 8)
306 auto intValue = intCst.getValue().getZExtValue();
307 return StringAttr::get(getContext(), Twine(
static_cast<char>(intValue)));
310OpFoldResult FormatCharOp::fold(FoldAdaptor adaptor) {
311 if (getValue().getType().getIntOrFloatBitWidth() == 0)
312 return StringAttr::get(getContext(), Twine(
static_cast<char>(0)));
317 assert(!lits.empty() &&
"No literals to concatenate");
318 if (lits.size() == 1)
319 return StringAttr::get(ctxt, lits.front());
320 SmallString<64> newLit;
321 for (
auto lit : lits)
323 return StringAttr::get(ctxt, newLit);
326OpFoldResult FormatStringConcatOp::fold(FoldAdaptor adaptor) {
327 if (getNumOperands() == 0)
328 return StringAttr::get(getContext(),
"");
329 if (getNumOperands() == 1) {
331 if (getResult() == getOperand(0))
333 return getOperand(0);
337 SmallVector<StringRef> lits;
338 for (
auto attr : adaptor.getInputs()) {
339 auto lit = dyn_cast_or_null<StringAttr>(attr);
347LogicalResult FormatStringConcatOp::getFlattenedInputs(
348 llvm::SmallVectorImpl<Value> &flatOperands) {
349 llvm::SmallMapVector<FormatStringConcatOp, unsigned, 4> concatStack;
350 bool isCyclic =
false;
354 concatStack.insert({*
this, 0});
355 while (!concatStack.empty()) {
356 auto &top = concatStack.back();
357 auto currentConcat = top.first;
358 unsigned operandIndex = top.second;
361 while (operandIndex < currentConcat.getNumOperands()) {
362 auto currentOperand = currentConcat.getOperand(operandIndex);
364 if (
auto nextConcat =
365 currentOperand.getDefiningOp<FormatStringConcatOp>()) {
367 if (!concatStack.contains(nextConcat)) {
370 top.second = operandIndex + 1;
371 concatStack.insert({nextConcat, 0});
378 flatOperands.push_back(currentOperand);
383 if (operandIndex >= currentConcat.getNumOperands())
384 concatStack.pop_back();
387 return success(!isCyclic);
390LogicalResult FormatStringConcatOp::verify() {
391 if (llvm::any_of(getOperands(),
392 [&](Value operand) {
return operand == getResult(); }))
393 return emitOpError(
"is infinitely recursive.");
397LogicalResult FormatStringConcatOp::canonicalize(FormatStringConcatOp op,
398 PatternRewriter &rewriter) {
400 auto fmtStrType = FormatStringType::get(op.getContext());
403 bool hasBeenFlattened =
false;
404 SmallVector<Value, 0> flatOperands;
407 flatOperands.reserve(op.getNumOperands() + 4);
408 auto isAcyclic = op.getFlattenedInputs(flatOperands);
410 if (failed(isAcyclic)) {
413 op.emitWarning(
"Cyclic concatenation detected.");
417 hasBeenFlattened =
true;
420 if (!hasBeenFlattened && op.getNumOperands() < 2)
425 SmallVector<StringRef> litSequence;
426 SmallVector<Value> newOperands;
427 newOperands.reserve(op.getNumOperands());
428 FormatLiteralOp prevLitOp;
430 auto oldOperands = hasBeenFlattened ? flatOperands : op.getOperands();
431 for (
auto operand : oldOperands) {
432 if (
auto litOp = operand.getDefiningOp<FormatLiteralOp>()) {
433 if (!litOp.getLiteral().empty()) {
435 litSequence.push_back(litOp.getLiteral());
438 if (!litSequence.empty()) {
439 if (litSequence.size() > 1) {
441 auto newLit = rewriter.createOrFold<FormatLiteralOp>(
442 op.getLoc(), fmtStrType,
444 newOperands.push_back(newLit);
447 newOperands.push_back(prevLitOp.getResult());
451 newOperands.push_back(operand);
456 if (!litSequence.empty()) {
457 if (litSequence.size() > 1) {
459 auto newLit = rewriter.createOrFold<FormatLiteralOp>(
460 op.getLoc(), fmtStrType,
462 newOperands.push_back(newLit);
465 newOperands.push_back(prevLitOp.getResult());
469 if (!hasBeenFlattened && newOperands.size() == op.getNumOperands())
472 if (newOperands.empty())
473 rewriter.replaceOpWithNewOp<FormatLiteralOp>(op, fmtStrType,
474 rewriter.getStringAttr(
""));
475 else if (newOperands.size() == 1)
476 rewriter.replaceOp(op, newOperands);
478 rewriter.modifyOpInPlace(op, [&]() { op->setOperands(newOperands); });
483LogicalResult PrintFormattedOp::canonicalize(PrintFormattedOp op,
484 PatternRewriter &rewriter) {
486 if (
auto cstCond = op.getCondition().getDefiningOp<
hw::ConstantOp>()) {
487 if (cstCond.getValue().isZero()) {
488 rewriter.eraseOp(op);
495LogicalResult PrintFormattedProcOp::verify() {
497 auto *parentOp = getOperation()->getParentOp();
500 return emitOpError(
"must be within a procedural region.");
502 if (isa_and_nonnull<hw::HWDialect>(parentOp->getDialect())) {
503 if (!isa<hw::TriggeredOp>(parentOp))
504 return emitOpError(
"must be within a procedural region.");
508 if (isa_and_nonnull<sv::SVDialect>(parentOp->getDialect())) {
510 return emitOpError(
"must be within a procedural region.");
518LogicalResult PrintFormattedProcOp::canonicalize(PrintFormattedProcOp op,
519 PatternRewriter &rewriter) {
521 if (
auto litInput = op.getInput().getDefiningOp<FormatLiteralOp>()) {
522 if (litInput.getLiteral().empty()) {
523 rewriter.eraseOp(op);
530OpFoldResult StringConstantOp::fold(FoldAdaptor adaptor) {
531 return adaptor.getLiteralAttr();
534OpFoldResult StringConcatOp::fold(FoldAdaptor adaptor) {
535 auto operands = adaptor.getInputs();
536 if (operands.empty())
537 return StringAttr::get(getContext(),
"");
539 SmallString<128> result;
540 for (
auto &operand : operands) {
541 if (
auto strAttr = cast<StringAttr>(operand))
542 result += strAttr.getValue();
547 return StringAttr::get(getContext(), result);
550OpFoldResult StringLengthOp::fold(FoldAdaptor adaptor) {
551 auto inputAttr = adaptor.getInput();
555 if (
auto strAttr = cast<StringAttr>(inputAttr))
556 return IntegerAttr::get(getType(), strAttr.getValue().size());
561OpFoldResult IntToStringOp::fold(FoldAdaptor adaptor) {
562 auto intAttr = cast_or_null<IntegerAttr>(adaptor.getInput());
566 SmallString<128> result;
567 auto width = intAttr.getType().getIntOrFloatBitWidth();
572 for (
unsigned int i = 0; i < width; i += 8) {
574 intAttr.getValue().extractBitsAsZExtValue(std::min(width - i, 8U), i);
576 result.push_back(
static_cast<char>(
byte));
578 std::reverse(result.begin(), result.end());
579 return StringAttr::get(getContext(), result);
587#include "circt/Dialect/Sim/SimOpInterfaces.cpp.inc"
590#define GET_OP_CLASSES
591#include "circt/Dialect/Sim/Sim.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< unsigned > specifierWidth, bool isSigned=false)
static StringAttr concatLiterals(MLIRContext *ctxt, ArrayRef< StringRef > lits)
Signals that an operations regions are procedural.
ParseResult parseModuleSignature(OpAsmParser &parser, SmallVectorImpl< PortParse > &args, TypeAttr &modType)
New Style parsing.
void printModuleSignatureNew(OpAsmPrinter &p, Region &body, hw::ModuleType modType, ArrayRef< Attribute > portAttrs, ArrayRef< Location > locAttrs)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.