CIRCT 24.0.0git
Loading...
Searching...
No Matches
ArcOps.cpp
Go to the documentation of this file.
1//===- ArcOps.cpp ---------------------------------------------------------===//
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
13#include "mlir/Dialect/Func/IR/FuncOps.h"
14#include "mlir/IR/Builders.h"
15#include "mlir/IR/OpImplementation.h"
16#include "mlir/IR/PatternMatch.h"
17#include "mlir/IR/SymbolTable.h"
18#include "mlir/Interfaces/FunctionImplementation.h"
19#include "mlir/Interfaces/SideEffectInterfaces.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/TypeSwitch.h"
22
23using namespace circt;
24using namespace arc;
25using namespace mlir;
26
27//===----------------------------------------------------------------------===//
28// Helpers
29//===----------------------------------------------------------------------===//
30
31static LogicalResult verifyTypeListEquivalence(Operation *op,
32 TypeRange expectedTypeList,
33 TypeRange actualTypeList,
34 StringRef elementName) {
35 if (expectedTypeList.size() != actualTypeList.size())
36 return op->emitOpError("incorrect number of ")
37 << elementName << "s: expected " << expectedTypeList.size()
38 << ", but got " << actualTypeList.size();
39
40 for (unsigned i = 0, e = expectedTypeList.size(); i != e; ++i) {
41 if (expectedTypeList[i] != actualTypeList[i]) {
42 auto diag = op->emitOpError(elementName)
43 << " type mismatch: " << elementName << " #" << i;
44 diag.attachNote() << "expected type: " << expectedTypeList[i];
45 diag.attachNote() << " actual type: " << actualTypeList[i];
46 return diag;
47 }
48 }
49
50 return success();
51}
52
53static LogicalResult verifyArcSymbolUse(Operation *op, TypeRange inputs,
54 TypeRange results,
55 SymbolTableCollection &symbolTable) {
56 // Check that the arc attribute was specified.
57 auto arcName = op->getAttrOfType<FlatSymbolRefAttr>("arc");
58 // The arc attribute is verified by the tablegen generated verifier as it is
59 // an ODS defined attribute.
60 assert(arcName && "FlatSymbolRefAttr called 'arc' missing");
61 DefineOp arc = symbolTable.lookupNearestSymbolFrom<DefineOp>(op, arcName);
62 if (!arc)
63 return op->emitOpError() << "`" << arcName.getValue()
64 << "` does not reference a valid `arc.define`";
65
66 // Verify that the operand and result types match the arc.
67 auto type = arc.getFunctionType();
68 if (failed(
69 verifyTypeListEquivalence(op, type.getInputs(), inputs, "operand")))
70 return failure();
71
72 if (failed(
73 verifyTypeListEquivalence(op, type.getResults(), results, "result")))
74 return failure();
75
76 return success();
77}
78
79static bool isSupportedModuleOp(Operation *moduleOp) {
80 return llvm::isa<arc::ModelOp, hw::HWModuleLike>(moduleOp);
81}
82
83/// Fetches the operation pointed to by `pointing` with name `symbol`, checking
84/// that it is a supported model operation for simulation.
85static Operation *getSupportedModuleOp(SymbolTableCollection &symbolTable,
86 Operation *pointing, StringAttr symbol) {
87 Operation *moduleOp = symbolTable.lookupNearestSymbolFrom(pointing, symbol);
88 if (!moduleOp) {
89 pointing->emitOpError("model not found");
90 return nullptr;
91 }
92
93 if (!isSupportedModuleOp(moduleOp)) {
94 pointing->emitOpError("model symbol does not point to a supported model "
95 "operation, points to ")
96 << moduleOp->getName() << " instead";
97 return nullptr;
98 }
99
100 return moduleOp;
101}
102
103static std::optional<hw::ModulePort> getModulePort(Operation *moduleOp,
104 StringRef portName) {
105 auto findRightPort = [&](auto ports) -> std::optional<hw::ModulePort> {
106 const hw::ModulePort *port = llvm::find_if(
107 ports, [&](hw::ModulePort port) { return port.name == portName; });
108 if (port == ports.end())
109 return std::nullopt;
110 return *port;
111 };
112
113 return TypeSwitch<Operation *, std::optional<hw::ModulePort>>(moduleOp)
114 .Case<arc::ModelOp>(
115 [&](arc::ModelOp modelOp) -> std::optional<hw::ModulePort> {
116 return findRightPort(modelOp.getIo().getPorts());
117 })
118 .Case<hw::HWModuleLike>(
119 [&](hw::HWModuleLike moduleLike) -> std::optional<hw::ModulePort> {
120 return findRightPort(moduleLike.getPortList());
121 })
122 .Default([](Operation *) { return std::nullopt; });
123}
124
125//===----------------------------------------------------------------------===//
126// DefineOp
127//===----------------------------------------------------------------------===//
128
129ParseResult DefineOp::parse(OpAsmParser &parser, OperationState &result) {
130 auto buildFuncType =
131 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
132 function_interface_impl::VariadicFlag,
133 std::string &) { return builder.getFunctionType(argTypes, results); };
134
135 return function_interface_impl::parseFunctionOp(
136 parser, result, /*allowVariadic=*/false,
137 getFunctionTypeAttrName(result.name), buildFuncType,
138 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
139}
140
141void DefineOp::print(OpAsmPrinter &p) {
142 function_interface_impl::printFunctionOp(
143 p, *this, /*isVariadic=*/false, "function_type", getArgAttrsAttrName(),
144 getResAttrsAttrName());
145}
146
147LogicalResult DefineOp::verifyRegions() {
148 // Check that the body does not contain any side-effecting operations. We can
149 // simply iterate over the ops directly within the body; operations with
150 // regions, like scf::IfOp, implement the `HasRecursiveMemoryEffects` trait
151 // which causes the `isMemoryEffectFree` check to already recur into their
152 // regions.
153 for (auto &op : getBodyBlock()) {
154 if (isMemoryEffectFree(&op))
155 continue;
156
157 // We don't use a op-error here because that leads to the whole arc being
158 // printed. This can be switched of when creating the context, but one
159 // might not want to switch that off for other error messages. Here it's
160 // definitely not desirable as arcs can be very big and would fill up the
161 // error log, making it hard to read. Currently, only the signature (first
162 // line) of the arc is printed.
163 auto diag = mlir::emitError(getLoc(), "body contains non-pure operation");
164 diag.attachNote(op.getLoc()).append("first non-pure operation here: ");
165 return diag;
166 }
167 return success();
168}
169
170bool DefineOp::isPassthrough() {
171 if (getNumArguments() != getNumResults())
172 return false;
173
174 return llvm::all_of(
175 llvm::zip(getArguments(), getBodyBlock().getTerminator()->getOperands()),
176 [](const auto &argAndRes) {
177 return std::get<0>(argAndRes) == std::get<1>(argAndRes);
178 });
179}
180
181//===----------------------------------------------------------------------===//
182// OutputOp
183//===----------------------------------------------------------------------===//
184
185LogicalResult OutputOp::verify() {
186 auto *parent = (*this)->getParentOp();
187 TypeRange expectedTypes = parent->getResultTypes();
188 if (auto defOp = dyn_cast<DefineOp>(parent))
189 expectedTypes = defOp.getResultTypes();
190
191 TypeRange actualTypes = getOperands().getTypes();
192 return verifyTypeListEquivalence(*this, expectedTypes, actualTypes, "output");
193}
194
195//===----------------------------------------------------------------------===//
196// StateOp
197//===----------------------------------------------------------------------===//
198
199LogicalResult StateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
200 return verifyArcSymbolUse(*this, getInputs().getTypes(),
201 getResults().getTypes(), symbolTable);
202}
203
204LogicalResult StateOp::verify() {
205 if (getLatency() < 1)
206 return emitOpError("latency must be a positive integer");
207
208 if (!getClock())
209 return emitOpError("requires a clock");
210
211 return success();
212}
213
214//===----------------------------------------------------------------------===//
215// StateWriteOp
216//===----------------------------------------------------------------------===//
217
218LogicalResult
219StateWriteOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
220 if (!getTraceTapModel().has_value())
221 return success();
222
223 auto modelOp = symbolTable.lookupNearestSymbolFrom<ModelOp>(
224 getOperation(), getTraceTapModelAttr());
225 if (!modelOp)
226 return emitOpError() << "`" << getTraceTapModelAttr()
227 << "` does not reference a valid `arc.model`";
228 if (!modelOp.getTraceTaps())
229 return emitOpError() << "referenced model has no trace metadata";
230 if (modelOp.getTraceTapsAttr().size() <= *getTraceTapIndex())
231 return emitOpError() << "tap index exceeds model's tap array";
232 auto tapAttr =
233 cast<TraceTapAttr>(modelOp.getTraceTapsAttr()[*getTraceTapIndex()]);
234 if (tapAttr.getSigType().getValue() != getValue().getType())
235 return emitOpError() << "incorrect signal type in referenced tap attribute";
236
237 return success();
238}
239
240LogicalResult StateWriteOp::verify() {
241 if (getTraceTapIndex().has_value() == getTraceTapModel().has_value())
242 return success();
243 return emitOpError() << "must specify both a trace tap model and index";
244}
245
246//===----------------------------------------------------------------------===//
247// CallOp
248//===----------------------------------------------------------------------===//
249
250LogicalResult CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
251 return verifyArcSymbolUse(*this, getInputs().getTypes(),
252 getResults().getTypes(), symbolTable);
253}
254
255bool CallOp::isClocked() { return false; }
256
257Value CallOp::getClock() { return Value{}; }
258
259void CallOp::eraseClock() {}
260
261uint32_t CallOp::getLatency() { return 0; }
262
263//===----------------------------------------------------------------------===//
264// MemoryWritePortOp
265//===----------------------------------------------------------------------===//
266
267SmallVector<Type> MemoryWritePortOp::getArcResultTypes() {
268 auto memType = cast<MemoryType>(getMemory().getType());
269 SmallVector<Type> resultTypes{memType.getAddressType(),
270 memType.getWordType()};
271 if (getEnable())
272 resultTypes.push_back(IntegerType::get(getContext(), 1));
273 if (getMask())
274 resultTypes.push_back(memType.getWordType());
275 return resultTypes;
276}
277
278LogicalResult
279MemoryWritePortOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
280 return verifyArcSymbolUse(*this, getInputs().getTypes(), getArcResultTypes(),
281 symbolTable);
282}
283
284LogicalResult MemoryWritePortOp::verify() {
285 if (getLatency() < 1)
286 return emitOpError("latency must be at least 1");
287
288 if (!getClock())
289 return emitOpError("requires a clock");
290
291 return success();
292}
293
294//===----------------------------------------------------------------------===//
295// RootInputOp
296//===----------------------------------------------------------------------===//
297
298void RootInputOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
299 SmallString<32> buf("in_");
300 buf += getName();
301 setNameFn(getState(), buf);
302}
303
304//===----------------------------------------------------------------------===//
305// RootOutputOp
306//===----------------------------------------------------------------------===//
307
308void RootOutputOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
309 SmallString<32> buf("out_");
310 buf += getName();
311 setNameFn(getState(), buf);
312}
313
314//===----------------------------------------------------------------------===//
315// ModelOp
316//===----------------------------------------------------------------------===//
317
318LogicalResult ModelOp::verify() {
319 if (getBodyBlock().getArguments().size() != 1)
320 return emitOpError("must have exactly one argument");
321 if (auto type = getBodyBlock().getArgument(0).getType();
322 !isa<StorageType>(type))
323 return emitOpError("argument must be of storage type");
324 return success();
325}
326
327LogicalResult ModelOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
328 auto fnAttrs = std::array{getInitialFnAttr(), getFinalFnAttr()};
329 auto nouns = std::array{"initializer", "finalizer"};
330 for (auto [fnAttr, noun] : llvm::zip(fnAttrs, nouns)) {
331 if (!fnAttr)
332 continue;
333 auto fn = symbolTable.lookupNearestSymbolFrom<func::FuncOp>(*this, fnAttr);
334 if (!fn)
335 return emitOpError() << noun << " '" << fnAttr.getValue()
336 << "' does not reference a valid function";
337 if (!llvm::equal(fn.getArgumentTypes(), getBody().getArgumentTypes())) {
338 auto diag = emitError() << noun << " '" << fnAttr.getValue()
339 << "' arguments must match arguments of model";
340 diag.attachNote(fn.getLoc()) << noun << " declared here:";
341 return diag;
342 }
343 }
344 return success();
345}
346
347//===----------------------------------------------------------------------===//
348// LutOp
349//===----------------------------------------------------------------------===//
350
351LogicalResult LutOp::verify() {
352 Location firstSideEffectOpLoc = UnknownLoc::get(getContext());
353 const WalkResult result = getBody().walk([&](Operation *op) {
354 if (auto memOp = dyn_cast<MemoryEffectOpInterface>(op)) {
355 SmallVector<SideEffects::EffectInstance<MemoryEffects::Effect>> effects;
356 memOp.getEffects(effects);
357
358 if (!effects.empty()) {
359 firstSideEffectOpLoc = memOp->getLoc();
360 return WalkResult::interrupt();
361 }
362 }
363
364 return WalkResult::advance();
365 });
366
367 if (result.wasInterrupted())
368 return emitOpError("no operations with side-effects allowed inside a LUT")
369 .attachNote(firstSideEffectOpLoc)
370 << "first operation with side-effects here";
371
372 return success();
373}
374
375//===----------------------------------------------------------------------===//
376// VectorizeOp
377//===----------------------------------------------------------------------===//
378
379LogicalResult VectorizeOp::verify() {
380 if (getInputs().empty())
381 return emitOpError("there has to be at least one input vector");
382
383 if (!llvm::all_equal(llvm::map_range(
384 getInputs(), [](OperandRange range) { return range.size(); })))
385 return emitOpError("all input vectors must have the same size");
386
387 for (OperandRange range : getInputs()) {
388 if (!llvm::all_equal(range.getTypes()))
389 return emitOpError("all input vector lane types must match");
390
391 if (range.empty())
392 return emitOpError("input vector must have at least one element");
393 }
394
395 if (getResults().empty())
396 return emitOpError("must have at least one result");
397
398 if (!llvm::all_equal(getResults().getTypes()))
399 return emitOpError("all result types must match");
400
401 if (getResults().size() != getInputs().front().size())
402 return emitOpError("number results must match input vector size");
403
404 return success();
405}
406
407static FailureOr<unsigned> getVectorWidth(Type base, Type vectorized) {
408 if (isa<VectorType>(base))
409 return failure();
410
411 if (auto vectorTy = dyn_cast<VectorType>(vectorized)) {
412 if (vectorTy.getElementType() != base)
413 return failure();
414
415 return vectorTy.getDimSize(0);
416 }
417
418 if (vectorized.getIntOrFloatBitWidth() < base.getIntOrFloatBitWidth())
419 return failure();
420
421 if (vectorized.getIntOrFloatBitWidth() % base.getIntOrFloatBitWidth() == 0)
422 return vectorized.getIntOrFloatBitWidth() / base.getIntOrFloatBitWidth();
423
424 return failure();
425}
426
427LogicalResult VectorizeOp::verifyRegions() {
428 auto returnOp = cast<VectorizeReturnOp>(getBody().front().getTerminator());
429 TypeRange bodyArgTypes = getBody().front().getArgumentTypes();
430
431 if (bodyArgTypes.size() != getInputs().size())
432 return emitOpError(
433 "number of block arguments must match number of input vectors");
434
435 // Boundary and body are vectorized, or both are not vectorized
436 if (returnOp.getValue().getType() == getResultTypes().front()) {
437 for (auto [i, argTy] : llvm::enumerate(bodyArgTypes))
438 if (argTy != getInputs()[i].getTypes().front())
439 return emitOpError("if terminator type matches result type the "
440 "argument types must match the input types");
441
442 return success();
443 }
444
445 // Boundary is vectorized, body is not
446 if (auto width = getVectorWidth(returnOp.getValue().getType(),
447 getResultTypes().front());
448 succeeded(width)) {
449 for (auto [i, argTy] : llvm::enumerate(bodyArgTypes)) {
450 Type inputTy = getInputs()[i].getTypes().front();
451 FailureOr<unsigned> argWidth = getVectorWidth(argTy, inputTy);
452 if (failed(argWidth))
453 return emitOpError("block argument must be a scalar variant of the "
454 "vectorized operand");
455
456 if (*argWidth != width)
457 return emitOpError("input and output vector width must match");
458 }
459
460 return success();
461 }
462
463 // Body is vectorized, boundary is not
464 if (auto width = getVectorWidth(getResultTypes().front(),
465 returnOp.getValue().getType());
466 succeeded(width)) {
467 for (auto [i, argTy] : llvm::enumerate(bodyArgTypes)) {
468 Type inputTy = getInputs()[i].getTypes().front();
469 FailureOr<unsigned> argWidth = getVectorWidth(inputTy, argTy);
470 if (failed(argWidth))
471 return emitOpError(
472 "block argument must be a vectorized variant of the operand");
473
474 if (*argWidth != width)
475 return emitOpError("input and output vector width must match");
476
477 if (getInputs()[i].size() > 1 && argWidth != getInputs()[i].size())
478 return emitOpError(
479 "when boundary not vectorized the number of vector element "
480 "operands must match the width of the vectorized body");
481 }
482
483 return success();
484 }
485
486 return returnOp.emitOpError(
487 "operand type must match parent op's result value or be a vectorized or "
488 "non-vectorized variant of it");
489}
490
491bool VectorizeOp::isBoundaryVectorized() {
492 return getInputs().front().size() == 1;
493}
494bool VectorizeOp::isBodyVectorized() {
495 auto returnOp = cast<VectorizeReturnOp>(getBody().front().getTerminator());
496 if (isBoundaryVectorized() &&
497 returnOp.getValue().getType() == getResultTypes().front())
498 return true;
499
500 if (auto width = getVectorWidth(getResultTypes().front(),
501 returnOp.getValue().getType());
502 succeeded(width))
503 return *width > 1;
504
505 return false;
506}
507
508//===----------------------------------------------------------------------===//
509// SimInstantiateOp
510//===----------------------------------------------------------------------===//
511
512void SimInstantiateOp::print(OpAsmPrinter &p) {
513 BlockArgument modelArg = getBody().getArgument(0);
514 auto modelType = cast<SimModelInstanceType>(modelArg.getType());
515
516 p << " " << modelType.getModel() << " as ";
517 p.printRegionArgument(modelArg, {}, true);
518
519 if (getRuntimeModel() || getRuntimeArgs()) {
520 p << " runtime ";
521 if (getRuntimeModel())
522 p << getRuntimeModelAttr();
523 p << "(";
524 if (getRuntimeArgs())
525 p << getRuntimeArgsAttr();
526 p << ")";
527 }
528
529 p.printOptionalAttrDictWithKeyword(
530 getOperation()->getAttrs(),
531 {getRuntimeModelAttrName(), getRuntimeArgsAttrName()});
532
533 p << " ";
534
535 p.printRegion(getBody(), false);
536}
537
538ParseResult SimInstantiateOp::parse(OpAsmParser &parser,
539 OperationState &result) {
540 StringAttr modelName;
541 if (failed(parser.parseSymbolName(modelName)))
542 return failure();
543
544 if (failed(parser.parseKeyword("as")))
545 return failure();
546
547 OpAsmParser::Argument modelArg;
548 if (failed(parser.parseArgument(modelArg, false, false)))
549 return failure();
550
551 if (succeeded(parser.parseOptionalKeyword("runtime"))) {
552 StringAttr runtimeSym;
553 StringAttr runtimeArgs;
554 auto symOpt = parser.parseOptionalSymbolName(runtimeSym);
555 if (parser.parseLParen())
556 return failure();
557 auto nameOpt = parser.parseOptionalAttribute(runtimeArgs);
558 if (parser.parseRParen())
559 return failure();
560 if (succeeded(symOpt))
561 result.addAttribute(
562 SimInstantiateOp::getRuntimeModelAttrName(result.name),
563 FlatSymbolRefAttr::get(runtimeSym));
564 if (nameOpt.has_value())
565 result.addAttribute(SimInstantiateOp::getRuntimeArgsAttrName(result.name),
566 runtimeArgs);
567 }
568
569 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
570 return failure();
571
572 MLIRContext *ctxt = result.getContext();
573 modelArg.type =
574 SimModelInstanceType::get(ctxt, FlatSymbolRefAttr::get(ctxt, modelName));
575
576 std::unique_ptr<Region> body = std::make_unique<Region>();
577 if (failed(parser.parseRegion(*body, {modelArg})))
578 return failure();
579
580 result.addRegion(std::move(body));
581 return success();
582}
583
584LogicalResult SimInstantiateOp::verifyRegions() {
585 Region &body = getBody();
586 if (body.getNumArguments() != 1)
587 return emitError("entry block of body region must have the model instance "
588 "as a single argument");
589 if (!llvm::isa<SimModelInstanceType>(body.getArgument(0).getType()))
590 return emitError("entry block argument type is not a model instance");
591 return success();
592}
593
594LogicalResult
595SimInstantiateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
596 bool failed = false;
597 Operation *moduleOp = getSupportedModuleOp(
598 symbolTable, getOperation(),
599 llvm::cast<SimModelInstanceType>(getBody().getArgument(0).getType())
600 .getModel()
601 .getAttr());
602 if (!moduleOp)
603 failed = true;
604
605 if (getRuntimeModel().has_value()) {
606 Operation *runtimeModelOp = symbolTable.lookupNearestSymbolFrom(
607 getOperation(), getRuntimeModelAttr());
608 if (!runtimeModelOp) {
609 emitOpError("runtime model not found");
610 failed = true;
611 } else if (!isa<RuntimeModelOp>(runtimeModelOp)) {
612 emitOpError("referenced runtime model is not a RuntimeModelOp");
613 failed = true;
614 }
615 }
616
617 return success(!failed);
618}
619
620//===----------------------------------------------------------------------===//
621// SimSetInputOp
622//===----------------------------------------------------------------------===//
623
624LogicalResult
625SimSetInputOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
626 Operation *moduleOp = getSupportedModuleOp(
627 symbolTable, getOperation(),
628 llvm::cast<SimModelInstanceType>(getInstance().getType())
629 .getModel()
630 .getAttr());
631 if (!moduleOp)
632 return failure();
633
634 std::optional<hw::ModulePort> port = getModulePort(moduleOp, getInput());
635 if (!port)
636 return emitOpError("port not found on model");
637
638 if (port->dir != hw::ModulePort::Direction::Input)
639 return emitOpError("port is not an input port");
640
641 auto portType = port->type;
642 if (auto inoutType = dyn_cast<hw::InOutType>(portType))
643 portType = inoutType.getElementType();
644
645 if (portType != getValue().getType())
646 return emitOpError(
647 "mismatched types between value and model port, port expects ")
648 << port->type;
649
650 return success();
651}
652
653//===----------------------------------------------------------------------===//
654// SimGetPortOp
655//===----------------------------------------------------------------------===//
656
657LogicalResult
658SimGetPortOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
659 Operation *moduleOp = getSupportedModuleOp(
660 symbolTable, getOperation(),
661 llvm::cast<SimModelInstanceType>(getInstance().getType())
662 .getModel()
663 .getAttr());
664 if (!moduleOp)
665 return failure();
666
667 std::optional<hw::ModulePort> port = getModulePort(moduleOp, getPort());
668 if (!port)
669 return emitOpError("port not found on model");
670
671 if (port->type != getValue().getType())
672 return emitOpError(
673 "mismatched types between value and model port, port expects ")
674 << port->type;
675
676 return success();
677}
678
679//===----------------------------------------------------------------------===//
680// SimStepOp
681//===----------------------------------------------------------------------===//
682
683LogicalResult SimStepOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
684 Operation *moduleOp = getSupportedModuleOp(
685 symbolTable, getOperation(),
686 llvm::cast<SimModelInstanceType>(getInstance().getType())
687 .getModel()
688 .getAttr());
689 if (!moduleOp)
690 return failure();
691
692 return success();
693}
694
695//===----------------------------------------------------------------------===//
696// SimSetTimeOp
697//===----------------------------------------------------------------------===//
698
699LogicalResult
700SimSetTimeOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
701 Operation *moduleOp = getSupportedModuleOp(
702 symbolTable, getOperation(),
703 llvm::cast<SimModelInstanceType>(getInstance().getType())
704 .getModel()
705 .getAttr());
706 if (!moduleOp)
707 return failure();
708
709 return success();
710}
711
712//===----------------------------------------------------------------------===//
713// CoroutineDefineOp
714//===----------------------------------------------------------------------===//
715
716/// Resolve the callee symbol to a `CoroutineDefineOp` and verify that the
717/// given operand and result types match its function type.
718static LogicalResult verifyCoroutineCallTypes(Operation *op,
719 FlatSymbolRefAttr callee,
720 TypeRange operands,
721 TypeRange results,
722 SymbolTableCollection &symTable) {
723 auto defineOp =
724 symTable.lookupNearestSymbolFrom<CoroutineDefineOp>(op, callee);
725 if (!defineOp)
726 return op->emitOpError() << "`" << callee.getValue()
727 << "` does not reference a valid "
728 "`arc.coroutine.define`";
729
730 auto fnType = defineOp.getFunctionType();
731 if (failed(verifyTypeListEquivalence(op, fnType.getInputs(), operands,
732 "operand")))
733 return failure();
734 if (failed(verifyTypeListEquivalence(op, fnType.getResults(), results,
735 "result")))
736 return failure();
737 return success();
738}
739
740ParseResult CoroutineDefineOp::parse(OpAsmParser &parser,
741 OperationState &result) {
742 auto buildFuncType =
743 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
744 function_interface_impl::VariadicFlag,
745 std::string &) { return builder.getFunctionType(argTypes, results); };
746
747 return function_interface_impl::parseFunctionOp(
748 parser, result, /*allowVariadic=*/false,
749 getFunctionTypeAttrName(result.name), buildFuncType,
750 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
751}
752
753void CoroutineDefineOp::print(OpAsmPrinter &p) {
754 function_interface_impl::printFunctionOp(
755 p, *this, /*isVariadic=*/false, "function_type", getArgAttrsAttrName(),
756 getResAttrsAttrName());
757}
758
759//===----------------------------------------------------------------------===//
760// CoroutineCallOp
761//===----------------------------------------------------------------------===//
762
763LogicalResult
764CoroutineCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
765 // The `state`/`pc` and `resumeState`/`resumePC` types are constrained to
766 // wrap the callee symbol by the `CoroutineCalleeWrappedType` traits on the
767 // op. All that remains is to resolve the callee and check that the trailing
768 // arg/result types match its signature.
769 auto callee = (*this)->getAttrOfType<FlatSymbolRefAttr>("callee");
770 return verifyCoroutineCallTypes(*this, callee, getArgs().getTypes(),
771 getResults().getTypes(), symbolTable);
772}
773
774//===----------------------------------------------------------------------===//
775// CoroutineInstanceOp
776//===----------------------------------------------------------------------===//
777
778// An instance hides the coroutine's trailing observe bitmask and wakeup time.
779// Verify that the callee declares a bitmask and wakeup as its last two results
780// and that the instance's args and results match the callee's signature with
781// those two results removed.
782LogicalResult
783CoroutineInstanceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
784 auto callee = (*this)->getAttrOfType<FlatSymbolRefAttr>("callee");
785 auto defineOp =
786 symbolTable.lookupNearestSymbolFrom<CoroutineDefineOp>(*this, callee);
787 if (!defineOp)
788 return emitOpError() << "`" << callee.getValue()
789 << "` does not reference a valid "
790 "`arc.coroutine.define`";
791
792 auto fnType = defineOp.getFunctionType();
793 auto fnResults = fnType.getResults();
794 if (fnResults.size() < 2 || !fnResults.back().isInteger(64))
795 return emitOpError() << "referenced coroutine `" << callee.getValue()
796 << "` must produce an `i64` wakeup time as its "
797 "last result";
798
799 // The observe bitmask carries one bit per coroutine argument.
800 auto maskType = dyn_cast<IntegerType>(fnResults[fnResults.size() - 2]);
801 if (!maskType || maskType.getWidth() != fnType.getNumInputs())
802 return emitOpError()
803 << "referenced coroutine `" << callee.getValue()
804 << "` must produce an observe bitmask with one bit per "
805 "argument (`i"
806 << fnType.getNumInputs() << "`) as its second-to-last result";
807
808 if (failed(verifyTypeListEquivalence(*this, fnType.getInputs(),
809 getArgs().getTypes(), "operand")))
810 return failure();
811 if (failed(verifyTypeListEquivalence(*this, fnResults.drop_back(2),
812 getResults().getTypes(), "result")))
813 return failure();
814 return success();
815}
816
817//===----------------------------------------------------------------------===//
818// Coroutine Terminators
819//===----------------------------------------------------------------------===//
820
821// The three terminators all yield values back through the enclosing
822// `arc.coroutine.define`'s result types. The helper below extracts the
823// expected types from the parent and checks them against the given operand
824// types.
825static LogicalResult verifyCoroutineTerminator(Operation *op,
826 TypeRange yieldOperands) {
827 auto parent = op->getParentOfType<CoroutineDefineOp>();
828 return verifyTypeListEquivalence(op, parent.getResultTypes(), yieldOperands,
829 "yielded value");
830}
831
832LogicalResult CoroutineYieldOp::verify() {
833 if (failed(verifyCoroutineTerminator(*this, getYieldOperands().getTypes())))
834 return failure();
835
836 // The `BranchOpInterface` already verifies that the destination block has
837 // the right number of arguments and that the trailing arguments match the
838 // yield's destination operands. Additionally verify that the leading
839 // arguments, which are supplied fresh by the caller upon resumption, match
840 // the coroutine's function type.
841 auto parent = (*this)->getParentOfType<CoroutineDefineOp>();
842 TypeRange coroutineArgTypes = parent.getArgumentTypes();
843 TypeRange destArgTypes = getDest()->getArgumentTypes();
844 if (destArgTypes.size() >= coroutineArgTypes.size())
845 if (failed(verifyTypeListEquivalence(
846 *this, coroutineArgTypes,
847 destArgTypes.take_front(coroutineArgTypes.size()),
848 "destination resume argument")))
849 return failure();
850
851 return success();
852}
853
854// The destination block's leading arguments match the coroutine's function
855// type and are supplied fresh by the caller upon resumption. They are
856// therefore "produced" operands from the branch's point of view. The
857// remaining destination block arguments map to the yield's destination
858// operands.
859SuccessorOperands CoroutineYieldOp::getSuccessorOperands(unsigned index) {
860 assert(index == 0 && "invalid successor index");
861 auto parent = (*this)->getParentOfType<CoroutineDefineOp>();
862 return SuccessorOperands(parent.getArgumentTypes().size(),
863 getDestOperandsMutable());
864}
865
866LogicalResult CoroutineReturnOp::verify() {
867 return verifyCoroutineTerminator(*this, getYieldOperands().getTypes());
868}
869
870LogicalResult CoroutineHaltOp::verify() {
871 return verifyCoroutineTerminator(*this, getYieldOperands().getTypes());
872}
873
874//===----------------------------------------------------------------------===//
875// ExecuteOp
876//===----------------------------------------------------------------------===//
877
878LogicalResult ExecuteOp::verifyRegions() {
879 return verifyTypeListEquivalence(*this, getInputs().getTypes(),
880 getBody().getArgumentTypes(), "input");
881}
882
883//===----------------------------------------------------------------------===//
884// ArrayRefAllocOp
885//===----------------------------------------------------------------------===//
886
887LogicalResult ArrayRefAllocOp::verify() {
888 if (auto init = getInit()) {
889 if (init->size() != getType().getNumElements()) {
890 return emitOpError("init size does not match array size; init had size ")
891 << init->size() << " but array has size "
892 << getType().getNumElements();
893 }
894
895 if (auto intTy = dyn_cast<IntegerType>(getType().getElementType())) {
896 unsigned elemBitwidth = intTy.getWidth();
897 for (Attribute attr : *init) {
898 auto intAttr = dyn_cast<IntegerAttr>(attr);
899 if (!intAttr || intAttr.getValue().getBitWidth() != elemBitwidth) {
900 return emitOpError("expected element to be of type ")
901 << getType().getElementType();
902 }
903 }
904 }
905 }
906 return success();
907}
908
909#include "circt/Dialect/Arc/ArcInterfaces.cpp.inc"
910
911#define GET_OP_CLASSES
912#include "circt/Dialect/Arc/Arc.cpp.inc"
static FailureOr< unsigned > getVectorWidth(Type base, Type vectorized)
Definition ArcOps.cpp:407
static std::optional< hw::ModulePort > getModulePort(Operation *moduleOp, StringRef portName)
Definition ArcOps.cpp:103
static bool isSupportedModuleOp(Operation *moduleOp)
Definition ArcOps.cpp:79
static LogicalResult verifyArcSymbolUse(Operation *op, TypeRange inputs, TypeRange results, SymbolTableCollection &symbolTable)
Definition ArcOps.cpp:53
static LogicalResult verifyTypeListEquivalence(Operation *op, TypeRange expectedTypeList, TypeRange actualTypeList, StringRef elementName)
Definition ArcOps.cpp:31
static LogicalResult verifyCoroutineCallTypes(Operation *op, FlatSymbolRefAttr callee, TypeRange operands, TypeRange results, SymbolTableCollection &symTable)
Resolve the callee symbol to a CoroutineDefineOp and verify that the given operand and result types m...
Definition ArcOps.cpp:718
static LogicalResult verifyCoroutineTerminator(Operation *op, TypeRange yieldOperands)
Definition ArcOps.cpp:825
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 ...
Definition ArcOps.cpp:85
assert(baseType &&"element must be base type")
static PortInfo getPort(ModuleTy &mod, size_t idx)
Definition HWOps.cpp:1508
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:193
false return failure()
Parse an optional keyword or string and set instance into 'result'.
return success()
static Block * getBodyBlock(FModuleLike mod)
static InstancePath empty
Definition arc.py:1
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
Definition LLVM.h:190
mlir::StringAttr name
Definition HWTypes.h:33