11#include "mlir/Dialect/Func/IR/FuncOps.h"
12#include "mlir/IR/Builders.h"
13#include "mlir/IR/OpImplementation.h"
14#include "mlir/IR/PatternMatch.h"
15#include "mlir/IR/SymbolTable.h"
16#include "mlir/Interfaces/FunctionImplementation.h"
17#include "mlir/Interfaces/SideEffectInterfaces.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/TypeSwitch.h"
30 TypeRange expectedTypeList,
31 TypeRange actualTypeList,
32 StringRef elementName) {
33 if (expectedTypeList.size() != actualTypeList.size())
34 return op->emitOpError(
"incorrect number of ")
35 << elementName <<
"s: expected " << expectedTypeList.size()
36 <<
", but got " << actualTypeList.size();
38 for (
unsigned i = 0, e = expectedTypeList.size(); i != e; ++i) {
39 if (expectedTypeList[i] != actualTypeList[i]) {
40 auto diag = op->emitOpError(elementName)
41 <<
" type mismatch: " << elementName <<
" #" << i;
42 diag.attachNote() <<
"expected type: " << expectedTypeList[i];
43 diag.attachNote() <<
" actual type: " << actualTypeList[i];
53 SymbolTableCollection &symbolTable) {
55 auto arcName = op->getAttrOfType<FlatSymbolRefAttr>(
"arc");
58 assert(arcName &&
"FlatSymbolRefAttr called 'arc' missing");
59 DefineOp
arc = symbolTable.lookupNearestSymbolFrom<DefineOp>(op, arcName);
61 return op->emitOpError() <<
"`" << arcName.getValue()
62 <<
"` does not reference a valid `arc.define`";
65 auto type =
arc.getFunctionType();
78 return llvm::isa<arc::ModelOp, hw::HWModuleLike>(moduleOp);
84 Operation *pointing, StringAttr symbol) {
85 Operation *moduleOp = symbolTable.lookupNearestSymbolFrom(pointing, symbol);
87 pointing->emitOpError(
"model not found");
92 pointing->emitOpError(
"model symbol does not point to a supported model "
93 "operation, points to ")
94 << moduleOp->getName() <<
" instead";
102 StringRef portName) {
103 auto findRightPort = [&](
auto ports) -> std::optional<hw::ModulePort> {
106 if (port == ports.end())
111 return TypeSwitch<Operation *, std::optional<hw::ModulePort>>(moduleOp)
113 [&](arc::ModelOp modelOp) -> std::optional<hw::ModulePort> {
114 return findRightPort(modelOp.getIo().getPorts());
116 .Case<hw::HWModuleLike>(
117 [&](hw::HWModuleLike moduleLike) -> std::optional<hw::ModulePort> {
118 return findRightPort(moduleLike.getPortList());
120 .Default([](Operation *) {
return std::nullopt; });
127ParseResult DefineOp::parse(OpAsmParser &parser, OperationState &result) {
129 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
130 function_interface_impl::VariadicFlag,
131 std::string &) {
return builder.getFunctionType(argTypes, results); };
133 return function_interface_impl::parseFunctionOp(
134 parser, result,
false,
135 getFunctionTypeAttrName(result.name), buildFuncType,
136 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
139void DefineOp::print(OpAsmPrinter &p) {
140 function_interface_impl::printFunctionOp(
141 p, *
this,
false,
"function_type", getArgAttrsAttrName(),
142 getResAttrsAttrName());
145LogicalResult DefineOp::verifyRegions() {
152 if (isMemoryEffectFree(&op))
161 auto diag = mlir::emitError(
getLoc(),
"body contains non-pure operation");
162 diag.attachNote(op.getLoc()).append(
"first non-pure operation here: ");
168bool DefineOp::isPassthrough() {
169 if (getNumArguments() != getNumResults())
173 llvm::zip(getArguments(),
getBodyBlock().getTerminator()->getOperands()),
174 [](
const auto &argAndRes) {
175 return std::get<0>(argAndRes) == std::get<1>(argAndRes);
183LogicalResult OutputOp::verify() {
184 auto *parent = (*this)->getParentOp();
185 TypeRange expectedTypes = parent->getResultTypes();
186 if (
auto defOp = dyn_cast<DefineOp>(parent))
187 expectedTypes = defOp.getResultTypes();
189 TypeRange actualTypes = getOperands().getTypes();
197LogicalResult StateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
199 getResults().getTypes(), symbolTable);
202LogicalResult StateOp::verify() {
203 if (getLatency() < 1)
204 return emitOpError(
"latency must be a positive integer");
206 if (!getOperation()->getParentOfType<ClockDomainOp>() && !getClock())
207 return emitOpError(
"outside a clock domain requires a clock");
209 if (getOperation()->getParentOfType<ClockDomainOp>() && getClock())
210 return emitOpError(
"inside a clock domain cannot have a clock");
220StateWriteOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
221 if (!getTraceTapModel().has_value())
224 auto modelOp = symbolTable.lookupNearestSymbolFrom<ModelOp>(
225 getOperation(), getTraceTapModelAttr());
227 return emitOpError() <<
"`" << getTraceTapModelAttr()
228 <<
"` does not reference a valid `arc.model`";
229 if (!modelOp.getTraceTaps())
230 return emitOpError() <<
"referenced model has no trace metadata";
231 if (modelOp.getTraceTapsAttr().size() <= *getTraceTapIndex())
232 return emitOpError() <<
"tap index exceeds model's tap array";
234 cast<TraceTapAttr>(modelOp.getTraceTapsAttr()[*getTraceTapIndex()]);
235 if (tapAttr.getSigType().getValue() != getValue().getType())
236 return emitOpError() <<
"incorrect signal type in referenced tap attribute";
241LogicalResult StateWriteOp::verify() {
242 if (getTraceTapIndex().has_value() == getTraceTapModel().has_value())
244 return emitOpError() <<
"must specify both a trace tap model and index";
251LogicalResult CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
253 getResults().getTypes(), symbolTable);
256bool CallOp::isClocked() {
return false; }
258Value CallOp::getClock() {
return Value{}; }
260void CallOp::eraseClock() {}
262uint32_t CallOp::getLatency() {
return 0; }
268SmallVector<Type> MemoryWritePortOp::getArcResultTypes() {
269 auto memType = cast<MemoryType>(getMemory().getType());
270 SmallVector<Type> resultTypes{memType.getAddressType(),
271 memType.getWordType()};
273 resultTypes.push_back(IntegerType::get(getContext(), 1));
275 resultTypes.push_back(memType.getWordType());
280MemoryWritePortOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
285LogicalResult MemoryWritePortOp::verify() {
286 if (getLatency() < 1)
287 return emitOpError(
"latency must be at least 1");
289 if (!getOperation()->getParentOfType<ClockDomainOp>() && !getClock())
290 return emitOpError(
"outside a clock domain requires a clock");
292 if (getOperation()->getParentOfType<ClockDomainOp>() && getClock())
293 return emitOpError(
"inside a clock domain cannot have a clock");
302LogicalResult ClockDomainOp::verifyRegions() {
304 getInputs().getTypes(),
"input");
312 SmallString<32> buf(
"in_");
314 setNameFn(getState(), buf);
322 SmallString<32> buf(
"out_");
324 setNameFn(getState(), buf);
331LogicalResult ModelOp::verify() {
333 return emitOpError(
"must have exactly one argument");
334 if (
auto type =
getBodyBlock().getArgument(0).getType();
335 !isa<StorageType>(type))
336 return emitOpError(
"argument must be of storage type");
339 return emitOpError(
"inout ports are not supported");
343LogicalResult ModelOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
344 auto fnAttrs = std::array{getInitialFnAttr(), getFinalFnAttr()};
345 auto nouns = std::array{
"initializer",
"finalizer"};
346 for (
auto [fnAttr, noun] :
llvm::zip(fnAttrs, nouns)) {
349 auto fn = symbolTable.lookupNearestSymbolFrom<func::FuncOp>(*
this, fnAttr);
351 return emitOpError() << noun <<
" '" << fnAttr.getValue()
352 <<
"' does not reference a valid function";
353 if (!llvm::equal(fn.getArgumentTypes(), getBody().getArgumentTypes())) {
354 auto diag = emitError() << noun <<
" '" << fnAttr.getValue()
355 <<
"' arguments must match arguments of model";
356 diag.attachNote(fn.getLoc()) << noun <<
" declared here:";
367LogicalResult LutOp::verify() {
368 Location firstSideEffectOpLoc = UnknownLoc::get(getContext());
369 const WalkResult result = getBody().walk([&](Operation *op) {
370 if (
auto memOp = dyn_cast<MemoryEffectOpInterface>(op)) {
371 SmallVector<SideEffects::EffectInstance<MemoryEffects::Effect>> effects;
372 memOp.getEffects(effects);
374 if (!effects.empty()) {
375 firstSideEffectOpLoc = memOp->getLoc();
376 return WalkResult::interrupt();
380 return WalkResult::advance();
383 if (result.wasInterrupted())
384 return emitOpError(
"no operations with side-effects allowed inside a LUT")
385 .attachNote(firstSideEffectOpLoc)
386 <<
"first operation with side-effects here";
395LogicalResult VectorizeOp::verify() {
396 if (getInputs().
empty())
397 return emitOpError(
"there has to be at least one input vector");
399 if (!llvm::all_equal(llvm::map_range(
400 getInputs(), [](OperandRange range) {
return range.size(); })))
401 return emitOpError(
"all input vectors must have the same size");
403 for (OperandRange range : getInputs()) {
404 if (!llvm::all_equal(range.getTypes()))
405 return emitOpError(
"all input vector lane types must match");
408 return emitOpError(
"input vector must have at least one element");
411 if (getResults().
empty())
412 return emitOpError(
"must have at least one result");
414 if (!llvm::all_equal(getResults().getTypes()))
415 return emitOpError(
"all result types must match");
417 if (getResults().size() != getInputs().front().size())
418 return emitOpError(
"number results must match input vector size");
424 if (isa<VectorType>(base))
427 if (
auto vectorTy = dyn_cast<VectorType>(vectorized)) {
428 if (vectorTy.getElementType() != base)
431 return vectorTy.getDimSize(0);
434 if (vectorized.getIntOrFloatBitWidth() < base.getIntOrFloatBitWidth())
437 if (vectorized.getIntOrFloatBitWidth() % base.getIntOrFloatBitWidth() == 0)
438 return vectorized.getIntOrFloatBitWidth() / base.getIntOrFloatBitWidth();
443LogicalResult VectorizeOp::verifyRegions() {
444 auto returnOp = cast<VectorizeReturnOp>(getBody().front().getTerminator());
445 TypeRange bodyArgTypes = getBody().front().getArgumentTypes();
447 if (bodyArgTypes.size() != getInputs().size())
449 "number of block arguments must match number of input vectors");
452 if (returnOp.getValue().getType() == getResultTypes().front()) {
453 for (
auto [i, argTy] :
llvm::enumerate(bodyArgTypes))
454 if (argTy != getInputs()[i].getTypes().front())
455 return emitOpError(
"if terminator type matches result type the "
456 "argument types must match the input types");
463 getResultTypes().front());
465 for (
auto [i, argTy] :
llvm::enumerate(bodyArgTypes)) {
466 Type inputTy = getInputs()[i].getTypes().front();
468 if (failed(argWidth))
469 return emitOpError(
"block argument must be a scalar variant of the "
470 "vectorized operand");
472 if (*argWidth != width)
473 return emitOpError(
"input and output vector width must match");
481 returnOp.getValue().getType());
483 for (
auto [i, argTy] :
llvm::enumerate(bodyArgTypes)) {
484 Type inputTy = getInputs()[i].getTypes().front();
486 if (failed(argWidth))
488 "block argument must be a vectorized variant of the operand");
490 if (*argWidth != width)
491 return emitOpError(
"input and output vector width must match");
493 if (getInputs()[i].size() > 1 && argWidth != getInputs()[i].size())
495 "when boundary not vectorized the number of vector element "
496 "operands must match the width of the vectorized body");
502 return returnOp.emitOpError(
503 "operand type must match parent op's result value or be a vectorized or "
504 "non-vectorized variant of it");
507bool VectorizeOp::isBoundaryVectorized() {
508 return getInputs().front().size() == 1;
510bool VectorizeOp::isBodyVectorized() {
511 auto returnOp = cast<VectorizeReturnOp>(getBody().front().getTerminator());
512 if (isBoundaryVectorized() &&
513 returnOp.getValue().getType() == getResultTypes().front())
517 returnOp.getValue().getType());
528void SimInstantiateOp::print(OpAsmPrinter &p) {
529 BlockArgument modelArg = getBody().getArgument(0);
530 auto modelType = cast<SimModelInstanceType>(modelArg.getType());
532 p <<
" " << modelType.getModel() <<
" as ";
533 p.printRegionArgument(modelArg, {},
true);
535 if (getRuntimeModel() || getRuntimeArgs()) {
537 if (getRuntimeModel())
538 p << getRuntimeModelAttr();
540 if (getRuntimeArgs())
541 p << getRuntimeArgsAttr();
545 p.printOptionalAttrDictWithKeyword(
546 getOperation()->getAttrs(),
547 {getRuntimeModelAttrName(), getRuntimeArgsAttrName()});
551 p.printRegion(getBody(),
false);
554ParseResult SimInstantiateOp::parse(OpAsmParser &parser,
555 OperationState &result) {
556 StringAttr modelName;
557 if (failed(parser.parseSymbolName(modelName)))
560 if (failed(parser.parseKeyword(
"as")))
563 OpAsmParser::Argument modelArg;
564 if (failed(parser.parseArgument(modelArg,
false,
false)))
567 if (succeeded(parser.parseOptionalKeyword(
"runtime"))) {
568 StringAttr runtimeSym;
569 StringAttr runtimeArgs;
570 auto symOpt = parser.parseOptionalSymbolName(runtimeSym);
571 if (parser.parseLParen())
573 auto nameOpt = parser.parseOptionalAttribute(runtimeArgs);
574 if (parser.parseRParen())
576 if (succeeded(symOpt))
578 SimInstantiateOp::getRuntimeModelAttrName(result.name),
579 FlatSymbolRefAttr::get(runtimeSym));
580 if (nameOpt.has_value())
581 result.addAttribute(SimInstantiateOp::getRuntimeArgsAttrName(result.name),
585 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
588 MLIRContext *ctxt = result.getContext();
590 SimModelInstanceType::get(ctxt, FlatSymbolRefAttr::get(ctxt, modelName));
592 std::unique_ptr<Region> body = std::make_unique<Region>();
593 if (failed(parser.parseRegion(*body, {modelArg})))
596 result.addRegion(std::move(body));
600LogicalResult SimInstantiateOp::verifyRegions() {
601 Region &body = getBody();
602 if (body.getNumArguments() != 1)
603 return emitError(
"entry block of body region must have the model instance "
604 "as a single argument");
605 if (!llvm::isa<SimModelInstanceType>(body.getArgument(0).getType()))
606 return emitError(
"entry block argument type is not a model instance");
611SimInstantiateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
614 symbolTable, getOperation(),
615 llvm::cast<SimModelInstanceType>(getBody().getArgument(0).getType())
621 if (getRuntimeModel().has_value()) {
622 Operation *runtimeModelOp = symbolTable.lookupNearestSymbolFrom(
623 getOperation(), getRuntimeModelAttr());
624 if (!runtimeModelOp) {
625 emitOpError(
"runtime model not found");
627 }
else if (!isa<RuntimeModelOp>(runtimeModelOp)) {
628 emitOpError(
"referenced runtime model is not a RuntimeModelOp");
633 return success(!failed);
641SimSetInputOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
643 symbolTable, getOperation(),
644 llvm::cast<SimModelInstanceType>(getInstance().getType())
650 std::optional<hw::ModulePort> port =
getModulePort(moduleOp, getInput());
652 return emitOpError(
"port not found on model");
654 if (port->dir != hw::ModulePort::Direction::Input &&
655 port->dir != hw::ModulePort::Direction::InOut)
656 return emitOpError(
"port is not an input port");
658 if (port->type != getValue().getType())
660 "mismatched types between value and model port, port expects ")
671SimGetPortOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
673 symbolTable, getOperation(),
674 llvm::cast<SimModelInstanceType>(getInstance().getType())
682 return emitOpError(
"port not found on model");
684 if (port->type != getValue().getType())
686 "mismatched types between value and model port, port expects ")
696LogicalResult SimStepOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
698 symbolTable, getOperation(),
699 llvm::cast<SimModelInstanceType>(getInstance().getType())
712LogicalResult ExecuteOp::verifyRegions() {
714 getBody().getArgumentTypes(),
"input");
717#include "circt/Dialect/Arc/ArcInterfaces.cpp.inc"
719#define GET_OP_CLASSES
720#include "circt/Dialect/Arc/Arc.cpp.inc"
static FailureOr< unsigned > getVectorWidth(Type base, Type vectorized)
static std::optional< hw::ModulePort > getModulePort(Operation *moduleOp, StringRef portName)
static bool isSupportedModuleOp(Operation *moduleOp)
static LogicalResult verifyArcSymbolUse(Operation *op, TypeRange inputs, TypeRange results, SymbolTableCollection &symbolTable)
static LogicalResult verifyTypeListEquivalence(Operation *op, TypeRange expectedTypeList, TypeRange actualTypeList, StringRef elementName)
static Operation * getSupportedModuleOp(SymbolTableCollection &symbolTable, Operation *pointing, StringAttr symbol)
Fetches the operation pointed to by pointing with name symbol, checking that it is a supported model ...
assert(baseType &&"element must be base type")
static PortInfo getPort(ModuleTy &mod, size_t idx)
static Location getLoc(DefSlot slot)
static Block * getBodyBlock(FModuleLike mod)
static InstancePath empty
Direction
The direction of a Component or Cell port.
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn