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 FormatLitOp::fold(FoldAdaptor adaptor) { return getLiteralAttr(); }
114
115OpFoldResult FormatDecOp::fold(FoldAdaptor adaptor) {
116 if (getValue().getType() == IntegerType::get(getContext(), 0U))
117 return StringAttr::get(getContext(), "0");
118
119 if (auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(adaptor.getValue())) {
120 SmallVector<char, 16> strBuf;
121 intAttr.getValue().toString(strBuf, 10U, getIsSigned());
122
123 unsigned width = intAttr.getType().getIntOrFloatBitWidth();
124 unsigned padWidth = FormatDecOp::getDecimalWidth(width, getIsSigned());
125 padWidth = padWidth > strBuf.size() ? padWidth - strBuf.size() : 0;
126
127 SmallVector<char, 8> padding(padWidth, ' ');
128 return StringAttr::get(getContext(), Twine(padding) + Twine(strBuf));
129 }
130 return {};
131}
132
133OpFoldResult FormatHexOp::fold(FoldAdaptor adaptor) {
134 if (getValue().getType() == IntegerType::get(getContext(), 0U))
135 return StringAttr::get(getContext(), "");
136
137 if (auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(adaptor.getValue())) {
138 SmallVector<char, 8> strBuf;
139 intAttr.getValue().toString(strBuf, 16U, /*Signed*/ false,
140 /*formatAsCLiteral*/ false,
141 /*UpperCase*/ false);
142
143 unsigned width = intAttr.getType().getIntOrFloatBitWidth();
144 unsigned padWidth = width / 4;
145 if (width % 4 != 0)
146 padWidth++;
147 padWidth = padWidth > strBuf.size() ? padWidth - strBuf.size() : 0;
148
149 SmallVector<char, 8> padding(padWidth, '0');
150 return StringAttr::get(getContext(), Twine(padding) + Twine(strBuf));
151 }
152 return {};
153}
154
155OpFoldResult FormatBinOp::fold(FoldAdaptor adaptor) {
156 if (getValue().getType() == IntegerType::get(getContext(), 0U))
157 return StringAttr::get(getContext(), "");
158
159 if (auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(adaptor.getValue())) {
160 SmallVector<char, 32> strBuf;
161 intAttr.getValue().toString(strBuf, 2U, false);
162
163 unsigned width = intAttr.getType().getIntOrFloatBitWidth();
164 unsigned padWidth = width > strBuf.size() ? width - strBuf.size() : 0;
165
166 SmallVector<char, 32> padding(padWidth, '0');
167 return StringAttr::get(getContext(), Twine(padding) + Twine(strBuf));
168 }
169 return {};
170}
171
172OpFoldResult FormatCharOp::fold(FoldAdaptor adaptor) {
173 auto width = getValue().getType().getIntOrFloatBitWidth();
174 if (width > 8)
175 return {};
176 if (width == 0)
177 return StringAttr::get(getContext(), Twine(static_cast<char>(0)));
178
179 if (auto intAttr = llvm::dyn_cast_or_null<IntegerAttr>(adaptor.getValue())) {
180 auto intValue = intAttr.getValue().getZExtValue();
181 return StringAttr::get(getContext(), Twine(static_cast<char>(intValue)));
182 }
183
184 return {};
185}
186
187static StringAttr concatLiterals(MLIRContext *ctxt, ArrayRef<StringRef> lits) {
188 assert(!lits.empty() && "No literals to concatenate");
189 if (lits.size() == 1)
190 return StringAttr::get(ctxt, lits.front());
191 SmallString<64> newLit;
192 for (auto lit : lits)
193 newLit += lit;
194 return StringAttr::get(ctxt, newLit);
195}
196
197OpFoldResult FormatStringConcatOp::fold(FoldAdaptor adaptor) {
198 if (getNumOperands() == 0)
199 return StringAttr::get(getContext(), "");
200 if (getNumOperands() == 1) {
201 // Don't fold to our own result to avoid an infinte loop.
202 if (getResult() == getOperand(0))
203 return {};
204 return getOperand(0);
205 }
206
207 // Fold if all operands are literals.
208 SmallVector<StringRef> lits;
209 for (auto attr : adaptor.getInputs()) {
210 auto lit = dyn_cast_or_null<StringAttr>(attr);
211 if (!lit)
212 return {};
213 lits.push_back(lit);
214 }
215 return concatLiterals(getContext(), lits);
216}
217
218LogicalResult FormatStringConcatOp::getFlattenedInputs(
219 llvm::SmallVectorImpl<Value> &flatOperands) {
220 llvm::SmallMapVector<FormatStringConcatOp, unsigned, 4> concatStack;
221 bool isCyclic = false;
222
223 // Perform a DFS on this operation's concatenated operands,
224 // collect the leaf format string fragments.
225 concatStack.insert({*this, 0});
226 while (!concatStack.empty()) {
227 auto &top = concatStack.back();
228 auto currentConcat = top.first;
229 unsigned operandIndex = top.second;
230
231 // Iterate over concatenated operands
232 while (operandIndex < currentConcat.getNumOperands()) {
233 auto currentOperand = currentConcat.getOperand(operandIndex);
234
235 if (auto nextConcat =
236 currentOperand.getDefiningOp<FormatStringConcatOp>()) {
237 // Concat of a concat
238 if (!concatStack.contains(nextConcat)) {
239 // Save the next operand index to visit on the
240 // stack and put the new concat on top.
241 top.second = operandIndex + 1;
242 concatStack.insert({nextConcat, 0});
243 break;
244 }
245 // Cyclic concatenation encountered. Don't recurse.
246 isCyclic = true;
247 }
248
249 flatOperands.push_back(currentOperand);
250 operandIndex++;
251 }
252
253 // Pop the concat off of the stack if we have visited all operands.
254 if (operandIndex >= currentConcat.getNumOperands())
255 concatStack.pop_back();
256 }
257
258 return success(!isCyclic);
259}
260
261LogicalResult FormatStringConcatOp::verify() {
262 if (llvm::any_of(getOperands(),
263 [&](Value operand) { return operand == getResult(); }))
264 return emitOpError("is infinitely recursive.");
265 return success();
266}
267
268LogicalResult FormatStringConcatOp::canonicalize(FormatStringConcatOp op,
269 PatternRewriter &rewriter) {
270
271 auto fmtStrType = FormatStringType::get(op.getContext());
272
273 // Check if we can flatten concats of concats
274 bool hasBeenFlattened = false;
275 SmallVector<Value, 0> flatOperands;
276 if (!op.isFlat()) {
277 // Get a new, flattened list of operands
278 flatOperands.reserve(op.getNumOperands() + 4);
279 auto isAcyclic = op.getFlattenedInputs(flatOperands);
280
281 if (failed(isAcyclic)) {
282 // Infinite recursion, but we cannot fail compilation right here (can we?)
283 // so just emit a warning and bail out.
284 op.emitWarning("Cyclic concatenation detected.");
285 return failure();
286 }
287
288 hasBeenFlattened = true;
289 }
290
291 if (!hasBeenFlattened && op.getNumOperands() < 2)
292 return failure(); // Should be handled by the folder
293
294 // Check if there are adjacent literals we can merge or empty literals to
295 // remove
296 SmallVector<StringRef> litSequence;
297 SmallVector<Value> newOperands;
298 newOperands.reserve(op.getNumOperands());
299 FormatLitOp prevLitOp;
300
301 auto oldOperands = hasBeenFlattened ? flatOperands : op.getOperands();
302 for (auto operand : oldOperands) {
303 if (auto litOp = operand.getDefiningOp<FormatLitOp>()) {
304 if (!litOp.getLiteral().empty()) {
305 prevLitOp = litOp;
306 litSequence.push_back(litOp.getLiteral());
307 }
308 } else {
309 if (!litSequence.empty()) {
310 if (litSequence.size() > 1) {
311 // Create a fused literal.
312 auto newLit = rewriter.createOrFold<FormatLitOp>(
313 op.getLoc(), fmtStrType,
314 concatLiterals(op.getContext(), litSequence));
315 newOperands.push_back(newLit);
316 } else {
317 // Reuse the existing literal.
318 newOperands.push_back(prevLitOp.getResult());
319 }
320 litSequence.clear();
321 }
322 newOperands.push_back(operand);
323 }
324 }
325
326 // Push trailing literals into the new operand list
327 if (!litSequence.empty()) {
328 if (litSequence.size() > 1) {
329 // Create a fused literal.
330 auto newLit = rewriter.createOrFold<FormatLitOp>(
331 op.getLoc(), fmtStrType,
332 concatLiterals(op.getContext(), litSequence));
333 newOperands.push_back(newLit);
334 } else {
335 // Reuse the existing literal.
336 newOperands.push_back(prevLitOp.getResult());
337 }
338 }
339
340 if (!hasBeenFlattened && newOperands.size() == op.getNumOperands())
341 return failure(); // Nothing changed
342
343 if (newOperands.empty())
344 rewriter.replaceOpWithNewOp<FormatLitOp>(op, fmtStrType,
345 rewriter.getStringAttr(""));
346 else if (newOperands.size() == 1)
347 rewriter.replaceOp(op, newOperands);
348 else
349 rewriter.modifyOpInPlace(op, [&]() { op->setOperands(newOperands); });
350
351 return success();
352}
353
354LogicalResult PrintFormattedOp::canonicalize(PrintFormattedOp op,
355 PatternRewriter &rewriter) {
356 // Remove ops with constant false condition.
357 if (auto cstCond = op.getCondition().getDefiningOp<hw::ConstantOp>()) {
358 if (cstCond.getValue().isZero()) {
359 rewriter.eraseOp(op);
360 return success();
361 }
362 }
363 return failure();
364}
365
366LogicalResult PrintFormattedProcOp::verify() {
367 // Check if we know for sure that the parent is not procedural.
368 auto *parentOp = getOperation()->getParentOp();
369
370 if (!parentOp)
371 return emitOpError("must be within a procedural region.");
372
373 if (isa_and_nonnull<hw::HWDialect>(parentOp->getDialect())) {
374 if (!isa<hw::TriggeredOp>(parentOp))
375 return emitOpError("must be within a procedural region.");
376 return success();
377 }
378
379 if (isa_and_nonnull<sv::SVDialect>(parentOp->getDialect())) {
380 if (!parentOp->hasTrait<sv::ProceduralRegion>())
381 return emitOpError("must be within a procedural region.");
382 return success();
383 }
384
385 // Don't fail for dialects that are not explicitly handled.
386 return success();
387}
388
389LogicalResult PrintFormattedProcOp::canonicalize(PrintFormattedProcOp op,
390 PatternRewriter &rewriter) {
391 // Remove empty prints.
392 if (auto litInput = op.getInput().getDefiningOp<FormatLitOp>()) {
393 if (litInput.getLiteral().empty()) {
394 rewriter.eraseOp(op);
395 return success();
396 }
397 }
398 return failure();
399}
400
401//===----------------------------------------------------------------------===//
402// TableGen generated logic.
403//===----------------------------------------------------------------------===//
404
405// Provide the autogenerated implementation guts for the Op classes.
406#define GET_OP_CLASSES
407#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:187
Signals that an operations regions are procedural.
Definition SVOps.h:161
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.