CIRCT 22.0.0git
Loading...
Searching...
No Matches
SimOps.cpp
Go to the documentation of this file.
1//===- SimOps.cpp - Implement the Sim operations ------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements `sim` dialect ops.
10//
11//===----------------------------------------------------------------------===//
12
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"
21
22using namespace mlir;
23using namespace circt;
24using namespace sim;
25
26ParseResult DPIFuncOp::parse(OpAsmParser &parser, OperationState &result) {
27 auto builder = parser.getBuilder();
28 // Parse visibility.
29 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
30
31 // Parse the name as a symbol.
32 StringAttr nameAttr;
33 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
34 result.attributes))
35 return failure();
36
37 SmallVector<hw::module_like_impl::PortParse> ports;
38 TypeAttr modType;
39 if (failed(
40 hw::module_like_impl::parseModuleSignature(parser, ports, modType)))
41 return failure();
42
43 result.addAttribute(DPIFuncOp::getModuleTypeAttrName(result.name), modType);
44
45 // Convert the specified array of dictionary attrs (which may have null
46 // entries) to an ArrayAttr of dictionaries.
47 auto unknownLoc = builder.getUnknownLoc();
48 SmallVector<Attribute> attrs, locs;
49 auto nonEmptyLocsFn = [unknownLoc](Attribute attr) {
50 return attr && cast<Location>(attr) != unknownLoc;
51 };
52
53 for (auto &port : ports) {
54 attrs.push_back(port.attrs ? port.attrs : builder.getDictionaryAttr({}));
55 locs.push_back(port.sourceLoc ? Location(*port.sourceLoc) : unknownLoc);
56 }
57
58 result.addAttribute(DPIFuncOp::getPerArgumentAttrsAttrName(result.name),
59 builder.getArrayAttr(attrs));
60 result.addRegion();
61
62 if (llvm::any_of(locs, nonEmptyLocsFn))
63 result.addAttribute(DPIFuncOp::getArgumentLocsAttrName(result.name),
64 builder.getArrayAttr(locs));
65
66 // Parse the attribute dict.
67 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
68 return failure();
69
70 return success();
71}
72
73LogicalResult
74sim::DPICallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
75 auto referencedOp =
76 symbolTable.lookupNearestSymbolFrom(*this, getCalleeAttr());
77 if (!referencedOp)
78 return emitError("cannot find function declaration '")
79 << getCallee() << "'";
80 if (isa<func::FuncOp, sim::DPIFuncOp>(referencedOp))
81 return success();
82 return emitError("callee must be 'sim.dpi.func' or 'func.func' but got '")
83 << referencedOp->getName() << "'";
84}
85
86void DPIFuncOp::print(OpAsmPrinter &p) {
87 DPIFuncOp op = *this;
88 // Print the operation and the function name.
89 auto funcName =
90 op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())
91 .getValue();
92 p << ' ';
93
94 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
95 if (auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName))
96 p << visibility.getValue() << ' ';
97 p.printSymbolName(funcName);
99 p, op->getRegion(0), op.getModuleType(),
100 getPerArgumentAttrsAttr()
101 ? ArrayRef<Attribute>(getPerArgumentAttrsAttr().getValue())
102 : ArrayRef<Attribute>{},
103 getArgumentLocs() ? SmallVector<Location>(
104 getArgumentLocs().value().getAsRange<Location>())
105 : ArrayRef<Location>{});
106
107 mlir::function_interface_impl::printFunctionAttributes(
108 p, op,
109 {visibilityAttrName, getModuleTypeAttrName(),
110 getPerArgumentAttrsAttrName(), getArgumentLocsAttrName()});
111}
112
113OpFoldResult FormatLiteralOp::fold(FoldAdaptor adaptor) {
114 return getLiteralAttr();
115}
116
117OpFoldResult FormatDecOp::fold(FoldAdaptor adaptor) {
118 if (getValue().getType() == IntegerType::get(getContext(), 0U))
119 return StringAttr::get(getContext(), "0");
120
121 if (auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(adaptor.getValue())) {
122 SmallVector<char, 16> strBuf;
123 intAttr.getValue().toString(strBuf, 10U, getIsSigned());
124
125 unsigned width = intAttr.getType().getIntOrFloatBitWidth();
126 unsigned padWidth = FormatDecOp::getDecimalWidth(width, getIsSigned());
127 padWidth = padWidth > strBuf.size() ? padWidth - strBuf.size() : 0;
128
129 SmallVector<char, 8> padding(padWidth, ' ');
130 return StringAttr::get(getContext(), Twine(padding) + Twine(strBuf));
131 }
132 return {};
133}
134
135OpFoldResult FormatHexOp::fold(FoldAdaptor adaptor) {
136 if (getValue().getType() == IntegerType::get(getContext(), 0U))
137 return StringAttr::get(getContext(), "");
138
139 if (auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(adaptor.getValue())) {
140 SmallVector<char, 8> strBuf;
141 intAttr.getValue().toString(strBuf, 16U, /*Signed*/ false,
142 /*formatAsCLiteral*/ false,
143 /*UpperCase*/ false);
144
145 unsigned width = intAttr.getType().getIntOrFloatBitWidth();
146 unsigned padWidth = width / 4;
147 if (width % 4 != 0)
148 padWidth++;
149 padWidth = padWidth > strBuf.size() ? padWidth - strBuf.size() : 0;
150
151 SmallVector<char, 8> padding(padWidth, '0');
152 return StringAttr::get(getContext(), Twine(padding) + Twine(strBuf));
153 }
154 return {};
155}
156
157OpFoldResult FormatBinOp::fold(FoldAdaptor adaptor) {
158 if (getValue().getType() == IntegerType::get(getContext(), 0U))
159 return StringAttr::get(getContext(), "");
160
161 if (auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(adaptor.getValue())) {
162 SmallVector<char, 32> strBuf;
163 intAttr.getValue().toString(strBuf, 2U, false);
164
165 unsigned width = intAttr.getType().getIntOrFloatBitWidth();
166 unsigned padWidth = width > strBuf.size() ? width - strBuf.size() : 0;
167
168 SmallVector<char, 32> padding(padWidth, '0');
169 return StringAttr::get(getContext(), Twine(padding) + Twine(strBuf));
170 }
171 return {};
172}
173
174OpFoldResult FormatCharOp::fold(FoldAdaptor adaptor) {
175 auto width = getValue().getType().getIntOrFloatBitWidth();
176 if (width > 8)
177 return {};
178 if (width == 0)
179 return StringAttr::get(getContext(), Twine(static_cast<char>(0)));
180
181 if (auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(adaptor.getValue())) {
182 auto intValue = intAttr.getValue().getZExtValue();
183 return StringAttr::get(getContext(), Twine(static_cast<char>(intValue)));
184 }
185
186 return {};
187}
188
189static StringAttr concatLiterals(MLIRContext *ctxt, ArrayRef<StringRef> lits) {
190 assert(!lits.empty() && "No literals to concatenate");
191 if (lits.size() == 1)
192 return StringAttr::get(ctxt, lits.front());
193 SmallString<64> newLit;
194 for (auto lit : lits)
195 newLit += lit;
196 return StringAttr::get(ctxt, newLit);
197}
198
199OpFoldResult FormatStringConcatOp::fold(FoldAdaptor adaptor) {
200 if (getNumOperands() == 0)
201 return StringAttr::get(getContext(), "");
202 if (getNumOperands() == 1) {
203 // Don't fold to our own result to avoid an infinte loop.
204 if (getResult() == getOperand(0))
205 return {};
206 return getOperand(0);
207 }
208
209 // Fold if all operands are literals.
210 SmallVector<StringRef> lits;
211 for (auto attr : adaptor.getInputs()) {
212 auto lit = dyn_cast_or_null<StringAttr>(attr);
213 if (!lit)
214 return {};
215 lits.push_back(lit);
216 }
217 return concatLiterals(getContext(), lits);
218}
219
220LogicalResult FormatStringConcatOp::getFlattenedInputs(
221 llvm::SmallVectorImpl<Value> &flatOperands) {
222 llvm::SmallMapVector<FormatStringConcatOp, unsigned, 4> concatStack;
223 bool isCyclic = false;
224
225 // Perform a DFS on this operation's concatenated operands,
226 // collect the leaf format string fragments.
227 concatStack.insert({*this, 0});
228 while (!concatStack.empty()) {
229 auto &top = concatStack.back();
230 auto currentConcat = top.first;
231 unsigned operandIndex = top.second;
232
233 // Iterate over concatenated operands
234 while (operandIndex < currentConcat.getNumOperands()) {
235 auto currentOperand = currentConcat.getOperand(operandIndex);
236
237 if (auto nextConcat =
238 currentOperand.getDefiningOp<FormatStringConcatOp>()) {
239 // Concat of a concat
240 if (!concatStack.contains(nextConcat)) {
241 // Save the next operand index to visit on the
242 // stack and put the new concat on top.
243 top.second = operandIndex + 1;
244 concatStack.insert({nextConcat, 0});
245 break;
246 }
247 // Cyclic concatenation encountered. Don't recurse.
248 isCyclic = true;
249 }
250
251 flatOperands.push_back(currentOperand);
252 operandIndex++;
253 }
254
255 // Pop the concat off of the stack if we have visited all operands.
256 if (operandIndex >= currentConcat.getNumOperands())
257 concatStack.pop_back();
258 }
259
260 return success(!isCyclic);
261}
262
263LogicalResult FormatStringConcatOp::verify() {
264 if (llvm::any_of(getOperands(),
265 [&](Value operand) { return operand == getResult(); }))
266 return emitOpError("is infinitely recursive.");
267 return success();
268}
269
270LogicalResult FormatStringConcatOp::canonicalize(FormatStringConcatOp op,
271 PatternRewriter &rewriter) {
272
273 auto fmtStrType = FormatStringType::get(op.getContext());
274
275 // Check if we can flatten concats of concats
276 bool hasBeenFlattened = false;
277 SmallVector<Value, 0> flatOperands;
278 if (!op.isFlat()) {
279 // Get a new, flattened list of operands
280 flatOperands.reserve(op.getNumOperands() + 4);
281 auto isAcyclic = op.getFlattenedInputs(flatOperands);
282
283 if (failed(isAcyclic)) {
284 // Infinite recursion, but we cannot fail compilation right here (can we?)
285 // so just emit a warning and bail out.
286 op.emitWarning("Cyclic concatenation detected.");
287 return failure();
288 }
289
290 hasBeenFlattened = true;
291 }
292
293 if (!hasBeenFlattened && op.getNumOperands() < 2)
294 return failure(); // Should be handled by the folder
295
296 // Check if there are adjacent literals we can merge or empty literals to
297 // remove
298 SmallVector<StringRef> litSequence;
299 SmallVector<Value> newOperands;
300 newOperands.reserve(op.getNumOperands());
301 FormatLiteralOp prevLitOp;
302
303 auto oldOperands = hasBeenFlattened ? flatOperands : op.getOperands();
304 for (auto operand : oldOperands) {
305 if (auto litOp = operand.getDefiningOp<FormatLiteralOp>()) {
306 if (!litOp.getLiteral().empty()) {
307 prevLitOp = litOp;
308 litSequence.push_back(litOp.getLiteral());
309 }
310 } else {
311 if (!litSequence.empty()) {
312 if (litSequence.size() > 1) {
313 // Create a fused literal.
314 auto newLit = rewriter.createOrFold<FormatLiteralOp>(
315 op.getLoc(), fmtStrType,
316 concatLiterals(op.getContext(), litSequence));
317 newOperands.push_back(newLit);
318 } else {
319 // Reuse the existing literal.
320 newOperands.push_back(prevLitOp.getResult());
321 }
322 litSequence.clear();
323 }
324 newOperands.push_back(operand);
325 }
326 }
327
328 // Push trailing literals into the new operand list
329 if (!litSequence.empty()) {
330 if (litSequence.size() > 1) {
331 // Create a fused literal.
332 auto newLit = rewriter.createOrFold<FormatLiteralOp>(
333 op.getLoc(), fmtStrType,
334 concatLiterals(op.getContext(), litSequence));
335 newOperands.push_back(newLit);
336 } else {
337 // Reuse the existing literal.
338 newOperands.push_back(prevLitOp.getResult());
339 }
340 }
341
342 if (!hasBeenFlattened && newOperands.size() == op.getNumOperands())
343 return failure(); // Nothing changed
344
345 if (newOperands.empty())
346 rewriter.replaceOpWithNewOp<FormatLiteralOp>(op, fmtStrType,
347 rewriter.getStringAttr(""));
348 else if (newOperands.size() == 1)
349 rewriter.replaceOp(op, newOperands);
350 else
351 rewriter.modifyOpInPlace(op, [&]() { op->setOperands(newOperands); });
352
353 return success();
354}
355
356LogicalResult PrintFormattedOp::canonicalize(PrintFormattedOp op,
357 PatternRewriter &rewriter) {
358 // Remove ops with constant false condition.
359 if (auto cstCond = op.getCondition().getDefiningOp<hw::ConstantOp>()) {
360 if (cstCond.getValue().isZero()) {
361 rewriter.eraseOp(op);
362 return success();
363 }
364 }
365 return failure();
366}
367
368LogicalResult PrintFormattedProcOp::verify() {
369 // Check if we know for sure that the parent is not procedural.
370 auto *parentOp = getOperation()->getParentOp();
371
372 if (!parentOp)
373 return emitOpError("must be within a procedural region.");
374
375 if (isa_and_nonnull<hw::HWDialect>(parentOp->getDialect())) {
376 if (!isa<hw::TriggeredOp>(parentOp))
377 return emitOpError("must be within a procedural region.");
378 return success();
379 }
380
381 if (isa_and_nonnull<sv::SVDialect>(parentOp->getDialect())) {
382 if (!parentOp->hasTrait<sv::ProceduralRegion>())
383 return emitOpError("must be within a procedural region.");
384 return success();
385 }
386
387 // Don't fail for dialects that are not explicitly handled.
388 return success();
389}
390
391LogicalResult PrintFormattedProcOp::canonicalize(PrintFormattedProcOp op,
392 PatternRewriter &rewriter) {
393 // Remove empty prints.
394 if (auto litInput = op.getInput().getDefiningOp<FormatLiteralOp>()) {
395 if (litInput.getLiteral().empty()) {
396 rewriter.eraseOp(op);
397 return success();
398 }
399 }
400 return failure();
401}
402
403//===----------------------------------------------------------------------===//
404// TableGen generated logic.
405//===----------------------------------------------------------------------===//
406
407// Provide the autogenerated implementation guts for the Op classes.
408#define GET_OP_CLASSES
409#include "circt/Dialect/Sim/Sim.cpp.inc"
assert(baseType &&"element must be base type")
static StringAttr concatLiterals(MLIRContext *ctxt, ArrayRef< StringRef > lits)
Definition SimOps.cpp:189
Signals that an operations regions are procedural.
Definition SVOps.h:176
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.