12#include "mlir/IR/Operation.h"
13#include "mlir/IR/Value.h"
14#include "slang/ast/EvalContext.h"
15#include "slang/ast/SystemSubroutine.h"
16#include "slang/ast/types/AllTypes.h"
17#include "slang/syntax/AllSyntax.h"
18#include "llvm/ADT/ScopeExit.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/Support/SaveAndRestore.h"
23using namespace ImportVerilog;
28 if (svint.hasUnknown()) {
29 unsigned numWords = svint.getNumWords() / 2;
30 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), numWords);
31 auto unknown = ArrayRef<uint64_t>(svint.getRawPtr() + numWords, numWords);
32 return FVInt(APInt(svint.getBitWidth(), value),
33 APInt(svint.getBitWidth(), unknown));
35 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), svint.getNumWords());
36 return FVInt(APInt(svint.getBitWidth(), value));
43 const slang::ConstantRange &range) {
44 auto &builder =
context.builder;
45 auto indexType = cast<moore::UnpackedType>(index.getType());
48 auto lo = range.lower();
49 auto hi = range.upper();
50 auto offset = range.isLittleEndian() ? lo : hi;
53 const bool needSigned = (lo < 0) || (hi < 0);
56 const uint64_t maxAbs = std::max<uint64_t>(std::abs(lo), std::abs(hi));
61 unsigned want = needSigned
62 ? (llvm::Log2_64_Ceil(std::max<uint64_t>(1, maxAbs)) + 1)
63 : std::max<unsigned>(1, llvm::Log2_64_Ceil(maxAbs + 1));
66 const unsigned bw = std::max<unsigned>(want, indexType.getBitSize().value());
69 moore::IntType::get(index.getContext(), bw, indexType.getDomain());
70 index =
context.materializeConversion(intType, index, needSigned, loc);
73 if (range.isLittleEndian())
76 return moore::NegOp::create(builder, loc, index);
80 moore::ConstantOp::create(builder, loc, intType, offset, needSigned);
81 if (range.isLittleEndian())
82 return moore::SubOp::create(builder, loc, index, offsetConst);
84 return moore::SubOp::create(builder, loc, offsetConst, index);
89 static_assert(int(slang::TimeUnit::Seconds) == 0);
90 static_assert(int(slang::TimeUnit::Milliseconds) == 1);
91 static_assert(int(slang::TimeUnit::Microseconds) == 2);
92 static_assert(int(slang::TimeUnit::Nanoseconds) == 3);
93 static_assert(int(slang::TimeUnit::Picoseconds) == 4);
94 static_assert(int(slang::TimeUnit::Femtoseconds) == 5);
96 static_assert(int(slang::TimeScaleMagnitude::One) == 1);
97 static_assert(int(slang::TimeScaleMagnitude::Ten) == 10);
98 static_assert(int(slang::TimeScaleMagnitude::Hundred) == 100);
100 auto exp =
static_cast<unsigned>(
context.timeScale.base.unit);
103 auto scale =
static_cast<uint64_t
>(
context.timeScale.base.magnitude);
112 Context &
context,
const slang::ast::HierarchicalValueExpression &expr) {
113 auto nameAttr =
context.builder.getStringAttr(expr.symbol.name);
114 for (
const auto &element : expr.ref.path) {
115 auto *inst = element.symbol->as_if<slang::ast::InstanceSymbol>();
118 auto *lowering =
context.interfaceInstances.lookup(inst);
121 if (
auto it = lowering->expandedMembers.find(&expr.symbol);
122 it != lowering->expandedMembers.end())
124 if (
auto it = lowering->expandedMembersByName.find(nameAttr);
125 it != lowering->expandedMembersByName.end())
132 const slang::ast::ClassPropertySymbol &expr) {
133 auto loc =
context.convertLocation(expr.location);
134 auto builder =
context.builder;
135 auto type =
context.convertType(expr.getType());
136 auto fieldTy = cast<moore::UnpackedType>(type);
137 auto fieldRefTy = moore::RefType::get(fieldTy);
139 if (expr.lifetime == slang::ast::VariableLifetime::Static) {
142 if (!
context.globalVariables.lookup(&expr)) {
143 if (failed(
context.convertGlobalVariable(expr))) {
148 if (
auto globalOp =
context.globalVariables.lookup(&expr))
149 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
151 mlir::emitError(loc) <<
"Failed to access static member variable "
152 << expr.name <<
" as a global variable";
157 mlir::Value instRef =
context.getImplicitThisRef();
159 mlir::emitError(loc) <<
"class property '" << expr.name
160 <<
"' referenced without an implicit 'this'";
164 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(), expr.name);
166 moore::ClassHandleType classTy =
167 cast<moore::ClassHandleType>(instRef.getType());
169 auto targetClassHandle =
170 context.getAncestorClassWithProperty(classTy, expr.name, loc);
171 if (!targetClassHandle)
174 auto upcastRef =
context.materializeConversion(targetClassHandle, instRef,
175 false, instRef.getLoc());
179 Value fieldRef = moore::ClassPropertyRefOp::create(builder, loc, fieldRefTy,
180 upcastRef, fieldSym);
192 ExprVisitor(
Context &context, Location loc,
bool isLvalue)
193 : context(context), loc(loc), builder(context.builder),
194 isLvalue(isLvalue) {}
200 Value convertLvalueOrRvalueExpression(
const slang::ast::Expression &expr) {
208 Value materializeSymbolRvalue(
const slang::ast::ValueSymbol &sym) {
210 if (isa<moore::RefType>(value.getType())) {
211 auto readOp = moore::ReadOp::create(builder, loc, value);
214 return readOp.getResult();
220 auto ref = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
221 auto readOp = moore::ReadOp::create(builder, loc, ref);
224 return readOp.getResult();
227 if (
auto *
const property = sym.as_if<slang::ast::ClassPropertySymbol>()) {
229 auto readOp = moore::ReadOp::create(builder, loc, fieldRef);
232 return readOp.getResult();
238 Value visit(
const slang::ast::NewArrayExpression &expr) {
243 if (expr.initExpr()) {
245 <<
"unsupported expression: array `new` with initializer\n";
250 expr.sizeExpr(), context.
convertType(*expr.sizeExpr().type));
254 return moore::OpenUArrayCreateOp::create(builder, loc, type, initialSize);
258 Value visit(
const slang::ast::ElementSelectExpression &expr) {
260 auto value = convertLvalueOrRvalueExpression(expr.value());
265 auto derefType = value.getType();
267 derefType = cast<moore::RefType>(derefType).getNestedType();
269 if (!isa<moore::IntType, moore::ArrayType, moore::UnpackedArrayType,
270 moore::QueueType, moore::AssocArrayType, moore::StringType,
271 moore::OpenUnpackedArrayType>(derefType)) {
272 mlir::emitError(loc) <<
"unsupported expression: element select into "
273 << expr.value().type->toString() <<
"\n";
278 if (isa<moore::AssocArrayType>(derefType)) {
279 auto assocArray = cast<moore::AssocArrayType>(derefType);
280 auto expectedIndexType = assocArray.getIndexType();
286 if (givenIndex.getType() != expectedIndexType) {
288 <<
"Incorrect index type: expected index type of "
289 << expectedIndexType <<
" but was given " << givenIndex.getType();
293 return moore::AssocArrayExtractRefOp::create(
294 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
297 return moore::AssocArrayExtractOp::create(builder, loc, type, value,
302 if (isa<moore::StringType>(derefType)) {
304 mlir::emitError(loc) <<
"string index assignment not supported";
309 auto i32Type = moore::IntType::getInt(builder.getContext(), 32);
315 return moore::StringGetOp::create(builder, loc, value, index);
319 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
320 auto range = expr.value().type->getFixedRange();
321 if (
auto *constValue = expr.selector().getConstant();
322 constValue && constValue->isInteger()) {
323 assert(!constValue->hasUnknown());
324 assert(constValue->size() <= 32);
326 auto lowBit = constValue->integer().as<uint32_t>().value();
328 return llvm::TypeSwitch<Type, Value>(derefType)
329 .Case<moore::QueueType>([&](moore::QueueType) {
331 <<
"Unexpected LValue extract on Queue Type!";
335 return moore::ExtractRefOp::create(builder, loc, resultType,
337 range.translateIndex(lowBit));
340 return llvm::TypeSwitch<Type, Value>(derefType)
341 .Case<moore::QueueType>([&](moore::QueueType) {
343 <<
"Unexpected RValue extract on Queue Type!";
347 return moore::ExtractOp::create(builder, loc, resultType, value,
348 range.translateIndex(lowBit));
355 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
356 if (isa<moore::QueueType>(derefType)) {
359 if (isa<moore::RefType>(value.getType())) {
360 context.
currentQueue = moore::ReadOp::create(builder, loc, value);
371 return llvm::TypeSwitch<Type, Value>(derefType)
372 .Case<moore::QueueType>([&](moore::QueueType) {
373 return moore::DynQueueRefElementOp::create(builder, loc, resultType,
377 return moore::DynExtractRefOp::create(builder, loc, resultType,
382 return llvm::TypeSwitch<Type, Value>(derefType)
383 .Case<moore::QueueType>([&](moore::QueueType) {
384 return moore::DynQueueExtractOp::create(builder, loc, resultType,
385 value, lowBit, lowBit);
388 return moore::DynExtractOp::create(builder, loc, resultType, value,
395 Value visit(
const slang::ast::NullLiteral &expr) {
397 if (isa<moore::ClassHandleType, moore::ChandleType, moore::EventType,
398 moore::NullType>(type))
399 return moore::NullOp::create(builder, loc);
400 mlir::emitError(loc) <<
"No null value definition found for value of type "
406 Value visit(
const slang::ast::RangeSelectExpression &expr) {
408 auto value = convertLvalueOrRvalueExpression(expr.value());
412 auto derefType = value.getType();
414 derefType = cast<moore::RefType>(derefType).getNestedType();
416 if (isa<moore::QueueType>(derefType)) {
417 return handleQueueRangeSelectExpressions(expr, type, value);
419 return handleArrayRangeSelectExpressions(expr, type, value);
424 Value handleQueueRangeSelectExpressions(
425 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
427 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
433 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
436 mlir::emitError(loc) <<
"queue lvalue range selections are not supported";
439 return moore::DynQueueExtractOp::create(builder, loc, resultType, value,
445 Value handleArrayRangeSelectExpressions(
446 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
447 std::optional<int32_t> constLeft;
448 std::optional<int32_t> constRight;
449 if (
auto *constant = expr.left().getConstant())
450 constLeft = constant->integer().as<int32_t>();
451 if (
auto *constant = expr.right().getConstant())
452 constRight = constant->integer().as<int32_t>();
458 <<
"unsupported expression: range select with non-constant bounds";
478 int32_t offsetConst = 0;
479 auto range = expr.value().type->getFixedRange();
481 using slang::ast::RangeSelectionKind;
482 if (expr.getSelectionKind() == RangeSelectionKind::Simple) {
487 assert(constRight &&
"constness checked in slang");
488 offsetConst = *constRight;
499 offsetConst = *constLeft;
510 int32_t offsetAdd = 0;
515 if (expr.getSelectionKind() == RangeSelectionKind::IndexedDown &&
516 range.isLittleEndian()) {
517 assert(constRight &&
"constness checked in slang");
518 offsetAdd = 1 - *constRight;
524 if (expr.getSelectionKind() == RangeSelectionKind::IndexedUp &&
525 !range.isLittleEndian()) {
526 assert(constRight &&
"constness checked in slang");
527 offsetAdd = *constRight - 1;
531 if (offsetAdd != 0) {
533 offsetDyn = moore::AddOp::create(
534 builder, loc, offsetDyn,
535 moore::ConstantOp::create(
536 builder, loc, cast<moore::IntType>(offsetDyn.getType()),
540 offsetConst += offsetAdd;
551 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
556 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
559 return moore::DynExtractOp::create(builder, loc, resultType, value,
563 offsetConst = range.translateIndex(offsetConst);
565 return moore::ExtractRefOp::create(builder, loc, resultType, value,
568 return moore::ExtractOp::create(builder, loc, resultType, value,
575 Value visit(
const slang::ast::ConcatenationExpression &expr) {
576 SmallVector<Value> operands;
577 if (expr.type->isString()) {
578 for (
auto *operand : expr.operands()) {
579 assert(!isLvalue &&
"checked by Slang");
580 auto value = convertLvalueOrRvalueExpression(*operand);
584 moore::StringType::get(context.
getContext()), value,
false,
588 operands.push_back(value);
590 return moore::StringConcatOp::create(builder, loc, operands);
592 if (expr.type->isQueue()) {
593 return handleQueueConcat(expr);
596 if (expr.type->isUnpackedArray()) {
597 assert(!isLvalue &&
"checked by Slang");
598 auto loweredType = context.
convertType(*expr.type, loc);
603 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(loweredType))
605 else if (
auto openType =
606 dyn_cast<moore::OpenUnpackedArrayType>(loweredType))
611 SmallVector<Value> operands;
612 for (
auto *operand : expr.operands()) {
613 if (operand->type->isVoid())
618 operands.push_back(value);
621 auto arrayType = moore::UnpackedArrayType::get(
623 return moore::ArrayCreateOp::create(builder, loc, arrayType, operands);
626 for (
auto *operand : expr.operands()) {
630 if (operand->type->isVoid())
632 auto value = convertLvalueOrRvalueExpression(*operand);
639 operands.push_back(value);
642 return moore::ConcatRefOp::create(builder, loc, operands);
644 return moore::ConcatOp::create(builder, loc, operands);
651 Value handleQueueConcat(
const slang::ast::ConcatenationExpression &expr) {
652 SmallVector<Value> operands;
655 cast<moore::QueueType>(context.
convertType(*expr.type, loc));
667 Value contigElements;
669 for (
auto *operand : expr.operands()) {
670 bool isSingleElement =
675 if (!isSingleElement && contigElements) {
676 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
680 assert(!isLvalue &&
"checked by Slang");
681 auto value = convertLvalueOrRvalueExpression(*operand);
689 moore::RefType::get(context.
getContext(), queueType);
691 if (!contigElements) {
693 moore::VariableOp::create(builder, loc, queueRefType, {}, {});
695 moore::QueuePushBackOp::create(builder, loc, contigElements, value);
703 if (!(isa<moore::QueueType>(value.getType()) &&
704 cast<moore::QueueType>(value.getType()).getElementType() ==
710 operands.push_back(value);
713 if (contigElements) {
714 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
717 return moore::QueueConcatOp::create(builder, loc, queueType, operands);
721 Value visit(
const slang::ast::MemberAccessExpression &expr) {
726 auto *valueType = expr.value().type.get();
727 auto memberName = builder.getStringAttr(expr.member.name);
733 if (valueType->isVirtualInterface()) {
734 auto memberType = dyn_cast<moore::UnpackedType>(type);
737 <<
"unsupported virtual interface member type: " << type;
740 auto resultRefType = moore::RefType::get(memberType);
748 auto memberRef = moore::StructExtractOp::create(
749 builder, loc, resultRefType, memberName, base);
752 return moore::ReadOp::create(builder, loc, memberRef);
756 if (valueType->isStruct()) {
758 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
760 auto value = convertLvalueOrRvalueExpression(expr.value());
765 return moore::StructExtractRefOp::create(builder, loc, resultType,
767 return moore::StructExtractOp::create(builder, loc, resultType,
772 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
774 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
776 auto value = convertLvalueOrRvalueExpression(expr.value());
781 return moore::UnionExtractRefOp::create(builder, loc, resultType,
783 return moore::UnionExtractOp::create(builder, loc, type, memberName,
788 if (valueType->isClass()) {
792 auto targetTy = cast<moore::ClassHandleType>(valTy);
804 if (expr.member.kind != slang::ast::SymbolKind::Parameter) {
810 moore::ClassHandleType upcastTargetTy =
824 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(),
826 auto fieldRefTy = moore::RefType::get(cast<moore::UnpackedType>(type));
830 Value fieldRef = moore::ClassPropertyRefOp::create(
831 builder, loc, fieldRefTy, baseVal, fieldSym);
834 return isLvalue ? fieldRef
835 : moore::ReadOp::create(builder, loc, fieldRef);
838 slang::ConstantValue constVal;
839 if (
auto param = expr.member.as_if<slang::ast::ParameterSymbol>()) {
840 constVal = param->getValue();
845 mlir::emitError(loc) <<
"Parameter " << expr.member.name
846 <<
" has no constant value";
850 mlir::emitError(loc,
"expression of type ")
851 << valueType->toString() <<
" has no member fields";
863struct RvalueExprVisitor :
public ExprVisitor {
865 : ExprVisitor(
context, loc, false) {}
866 using ExprVisitor::visit;
869 Value visit(
const slang::ast::LValueReferenceExpression &expr) {
870 assert(!
context.lvalueStack.empty() &&
"parent assignments push lvalue");
871 auto lvalue =
context.lvalueStack.back();
872 return moore::ReadOp::create(builder, loc, lvalue);
876 Value visit(
const slang::ast::NamedValueExpression &expr) {
878 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
879 if (isa<moore::RefType>(value.getType())) {
880 auto readOp = moore::ReadOp::create(builder, loc, value);
881 if (
context.rvalueReadCallback)
882 context.rvalueReadCallback(readOp);
883 value = readOp.getResult();
889 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol)) {
890 auto value = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
891 return moore::ReadOp::create(builder, loc, value);
895 if (
auto *
const property =
896 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
898 return moore::ReadOp::create(builder, loc, fieldRef).getResult();
905 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
907 auto type =
context.convertType(*expr.type);
910 auto memberType = dyn_cast<moore::UnpackedType>(type);
913 <<
"unsupported virtual interface member type: " << type;
917 Value base = materializeSymbolRvalue(*access.base);
919 auto d = mlir::emitError(loc,
"unknown name `")
920 << access.base->name <<
"`";
921 d.attachNote(
context.convertLocation(access.base->location))
922 <<
"no rvalue generated for virtual interface base";
926 auto fieldName = access.fieldName
928 : builder.getStringAttr(expr.symbol.name);
929 auto memberRefType = moore::RefType::get(memberType);
930 auto memberRef = moore::StructExtractOp::create(
931 builder, loc, memberRefType, fieldName, base);
932 auto readOp = moore::ReadOp::create(builder, loc, memberRef);
933 if (
context.rvalueReadCallback)
934 context.rvalueReadCallback(readOp);
935 return readOp.getResult();
939 auto constant =
context.evaluateConstant(expr);
940 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
945 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
946 d.attachNote(
context.convertLocation(expr.symbol.location))
947 <<
"no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
952 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
953 auto hierLoc =
context.convertLocation(expr.symbol.location);
959 if (!expr.ref.path.empty()) {
960 if (
auto *inst = expr.ref.path.front()
961 .symbol->as_if<slang::ast::InstanceSymbol>()) {
963 expr.symbol.getParentScope()->getContainingInstance();
964 if (&inst->body == symbolBody ||
965 (symbolBody && inst->body.getDeclaringDefinition() ==
966 symbolBody->getDeclaringDefinition())) {
967 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
968 if (isa<moore::RefType>(value.getType())) {
969 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
970 if (
context.rvalueReadCallback)
971 context.rvalueReadCallback(readOp);
972 value = readOp.getResult();
986 if (
auto key =
context.buildHierValueKey(expr)) {
987 if (
auto it =
context.hierValueSymbols.find(*key);
988 it !=
context.hierValueSymbols.end()) {
989 auto value = it->second;
990 if (isa<moore::RefType>(value.getType())) {
991 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
992 if (
context.rvalueReadCallback)
993 context.rvalueReadCallback(readOp);
994 value = readOp.getResult();
1001 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
1002 if (isa<moore::RefType>(value.getType())) {
1003 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1004 if (
context.rvalueReadCallback)
1005 context.rvalueReadCallback(readOp);
1006 value = readOp.getResult();
1012 if (isa<moore::RefType>(value.getType())) {
1013 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1014 if (
context.rvalueReadCallback)
1015 context.rvalueReadCallback(readOp);
1016 return readOp.getResult();
1022 auto constant =
context.evaluateConstant(expr);
1023 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1028 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
1029 << expr.symbol.name <<
"`";
1030 d.attachNote(hierLoc) <<
"no rvalue generated for "
1031 << slang::ast::toString(expr.symbol.kind);
1037 Value visit(
const slang::ast::ArbitrarySymbolExpression &expr) {
1038 const auto &canonTy = expr.type->getCanonicalType();
1039 if (
const auto *vi = canonTy.as_if<slang::ast::VirtualInterfaceType>()) {
1040 auto value =
context.materializeVirtualInterfaceValue(*vi, loc);
1046 mlir::emitError(loc) <<
"unsupported arbitrary symbol expression of type "
1047 << expr.type->toString();
1052 Value visit(
const slang::ast::ConversionExpression &expr) {
1053 auto type =
context.convertType(*expr.type);
1056 return context.convertRvalueExpression(expr.operand(), type);
1060 Value visit(
const slang::ast::AssignmentExpression &expr) {
1061 auto lhs =
context.convertLvalueExpression(expr.left());
1066 context.lvalueStack.push_back(lhs);
1067 auto rhs =
context.convertRvalueExpression(
1068 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
1069 context.lvalueStack.pop_back();
1076 if (!expr.isNonBlocking()) {
1077 if (expr.timingControl)
1078 if (failed(
context.convertTimingControl(*expr.timingControl)))
1080 auto assignOp = moore::BlockingAssignOp::create(builder, loc, lhs, rhs);
1081 if (
context.variableAssignCallback)
1082 context.variableAssignCallback(assignOp);
1087 if (expr.timingControl) {
1089 if (
auto *ctrl = expr.timingControl->as_if<slang::ast::DelayControl>()) {
1090 auto delay =
context.convertRvalueExpression(
1091 ctrl->expr, moore::TimeType::get(builder.getContext()));
1094 auto assignOp = moore::DelayedNonBlockingAssignOp::create(
1095 builder, loc, lhs, rhs, delay);
1096 if (
context.variableAssignCallback)
1097 context.variableAssignCallback(assignOp);
1102 auto loc =
context.convertLocation(expr.timingControl->sourceRange);
1103 mlir::emitError(loc)
1104 <<
"unsupported non-blocking assignment timing control: "
1105 << slang::ast::toString(expr.timingControl->kind);
1108 auto assignOp = moore::NonBlockingAssignOp::create(builder, loc, lhs, rhs);
1109 if (
context.variableAssignCallback)
1110 context.variableAssignCallback(assignOp);
1116 template <
class ConcreteOp>
1117 Value createReduction(Value arg,
bool invert) {
1118 arg =
context.convertToSimpleBitVector(arg);
1121 Value result = ConcreteOp::create(builder, loc, arg);
1123 result = moore::NotOp::create(builder, loc, result);
1128 Value createIncrement(Value arg,
bool isInc,
bool isPost) {
1129 auto preValue = moore::ReadOp::create(builder, loc, arg);
1135 postValue = moore::NotOp::create(builder, loc, preValue).getResult();
1138 auto one = moore::ConstantOp::create(
1139 builder, loc, cast<moore::IntType>(preValue.getType()), 1);
1141 isInc ? moore::AddOp::create(builder, loc, preValue, one).getResult()
1142 : moore::SubOp::create(builder, loc, preValue, one).getResult();
1144 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1145 if (
context.variableAssignCallback)
1146 context.variableAssignCallback(assignOp);
1155 Value createRealIncrement(Value arg,
bool isInc,
bool isPost) {
1156 Value preValue = moore::ReadOp::create(builder, loc, arg);
1159 bool isTime = isa<moore::TimeType>(preValue.getType());
1161 preValue =
context.materializeConversion(
1162 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1163 preValue,
false, loc);
1165 moore::RealType realTy =
1166 llvm::dyn_cast<moore::RealType>(preValue.getType());
1171 if (realTy.getWidth() == moore::RealWidth::f32) {
1172 oneAttr = builder.getFloatAttr(builder.getF32Type(), 1.0);
1173 }
else if (realTy.getWidth() == moore::RealWidth::f64) {
1175 oneAttr = builder.getFloatAttr(builder.getF64Type(), oneVal);
1177 mlir::emitError(loc) <<
"cannot construct increment for " << realTy;
1180 auto one = moore::ConstantRealOp::create(builder, loc, oneAttr);
1184 ? moore::AddRealOp::create(builder, loc, preValue, one).getResult()
1185 : moore::SubRealOp::create(builder, loc, preValue, one).getResult();
1188 postValue =
context.materializeConversion(
1189 moore::TimeType::get(
context.getContext()), postValue,
false, loc);
1192 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1194 if (
context.variableAssignCallback)
1195 context.variableAssignCallback(assignOp);
1202 Value visitRealUOp(
const slang::ast::UnaryExpression &expr) {
1203 Type opFTy =
context.convertType(*expr.operand().type);
1205 using slang::ast::UnaryOperator;
1207 if (expr.op == UnaryOperator::Preincrement ||
1208 expr.op == UnaryOperator::Predecrement ||
1209 expr.op == UnaryOperator::Postincrement ||
1210 expr.op == UnaryOperator::Postdecrement)
1211 arg =
context.convertLvalueExpression(expr.operand());
1213 arg =
context.convertRvalueExpression(expr.operand(), opFTy);
1218 if (isa<moore::TimeType>(arg.getType()))
1219 arg =
context.materializeConversion(
1220 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1225 case UnaryOperator::Plus:
1227 case UnaryOperator::Minus:
1228 return moore::NegRealOp::create(builder, loc, arg);
1230 case UnaryOperator::Preincrement:
1231 return createRealIncrement(arg,
true,
false);
1232 case UnaryOperator::Predecrement:
1233 return createRealIncrement(arg,
false,
false);
1234 case UnaryOperator::Postincrement:
1235 return createRealIncrement(arg,
true,
true);
1236 case UnaryOperator::Postdecrement:
1237 return createRealIncrement(arg,
false,
true);
1239 case UnaryOperator::LogicalNot:
1240 arg =
context.convertToBool(arg);
1243 return moore::NotOp::create(builder, loc, arg);
1246 mlir::emitError(loc) <<
"Unary operator " << slang::ast::toString(expr.op)
1247 <<
" not supported with real values!\n";
1253 Value visit(
const slang::ast::UnaryExpression &expr) {
1255 const auto *floatType =
1256 expr.operand().type->as_if<slang::ast::FloatingType>();
1259 return visitRealUOp(expr);
1261 using slang::ast::UnaryOperator;
1263 if (expr.op == UnaryOperator::Preincrement ||
1264 expr.op == UnaryOperator::Predecrement ||
1265 expr.op == UnaryOperator::Postincrement ||
1266 expr.op == UnaryOperator::Postdecrement)
1267 arg =
context.convertLvalueExpression(expr.operand());
1269 arg =
context.convertRvalueExpression(expr.operand());
1276 case UnaryOperator::Plus:
1277 return context.convertToSimpleBitVector(arg);
1279 case UnaryOperator::Minus:
1280 arg =
context.convertToSimpleBitVector(arg);
1283 return moore::NegOp::create(builder, loc, arg);
1285 case UnaryOperator::BitwiseNot:
1286 arg =
context.convertToSimpleBitVector(arg);
1289 return moore::NotOp::create(builder, loc, arg);
1291 case UnaryOperator::BitwiseAnd:
1292 return createReduction<moore::ReduceAndOp>(arg,
false);
1293 case UnaryOperator::BitwiseOr:
1294 return createReduction<moore::ReduceOrOp>(arg,
false);
1295 case UnaryOperator::BitwiseXor:
1296 return createReduction<moore::ReduceXorOp>(arg,
false);
1297 case UnaryOperator::BitwiseNand:
1298 return createReduction<moore::ReduceAndOp>(arg,
true);
1299 case UnaryOperator::BitwiseNor:
1300 return createReduction<moore::ReduceOrOp>(arg,
true);
1301 case UnaryOperator::BitwiseXnor:
1302 return createReduction<moore::ReduceXorOp>(arg,
true);
1304 case UnaryOperator::LogicalNot:
1305 arg =
context.convertToBool(arg);
1308 return moore::NotOp::create(builder, loc, arg);
1310 case UnaryOperator::Preincrement:
1311 return createIncrement(arg,
true,
false);
1312 case UnaryOperator::Predecrement:
1313 return createIncrement(arg,
false,
false);
1314 case UnaryOperator::Postincrement:
1315 return createIncrement(arg,
true,
true);
1316 case UnaryOperator::Postdecrement:
1317 return createIncrement(arg,
false,
true);
1320 mlir::emitError(loc,
"unsupported unary operator");
1325 Value buildLogicalBOp(slang::ast::BinaryOperator op, Value lhs, Value rhs,
1326 std::optional<Domain> domain = std::nullopt) {
1327 using slang::ast::BinaryOperator;
1331 lhs =
context.convertToBool(lhs, domain.value());
1332 rhs =
context.convertToBool(rhs, domain.value());
1334 lhs =
context.convertToBool(lhs);
1335 rhs =
context.convertToBool(rhs);
1342 case BinaryOperator::LogicalAnd:
1343 return moore::AndOp::create(builder, loc, lhs, rhs);
1345 case BinaryOperator::LogicalOr:
1346 return moore::OrOp::create(builder, loc, lhs, rhs);
1348 case BinaryOperator::LogicalImplication: {
1350 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1351 return moore::OrOp::create(builder, loc, notLHS, rhs);
1354 case BinaryOperator::LogicalEquivalence: {
1356 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1357 auto notRHS = moore::NotOp::create(builder, loc, rhs);
1358 auto both = moore::AndOp::create(builder, loc, lhs, rhs);
1359 auto notBoth = moore::AndOp::create(builder, loc, notLHS, notRHS);
1360 return moore::OrOp::create(builder, loc, both, notBoth);
1364 llvm_unreachable(
"not a logical BinaryOperator");
1368 Value visitHandleBOp(
const slang::ast::BinaryExpression &expr) {
1370 auto lhs =
context.convertRvalueExpression(expr.left());
1373 auto rhs =
context.convertRvalueExpression(expr.right());
1377 using slang::ast::BinaryOperator;
1380 case BinaryOperator::Equality:
1381 return moore::HandleEqOp::create(builder, loc, lhs, rhs);
1382 case BinaryOperator::Inequality:
1383 return moore::HandleNeOp::create(builder, loc, lhs, rhs);
1384 case BinaryOperator::CaseEquality:
1385 return moore::HandleCaseEqOp::create(builder, loc, lhs, rhs);
1386 case BinaryOperator::CaseInequality:
1387 return moore::HandleCaseNeOp::create(builder, loc, lhs, rhs);
1390 mlir::emitError(loc)
1391 <<
"Binary operator " << slang::ast::toString(expr.op)
1392 <<
" not supported with class handle valued operands!\n";
1397 Value visitRealBOp(
const slang::ast::BinaryExpression &expr) {
1399 auto lhs =
context.convertRvalueExpression(expr.left());
1402 auto rhs =
context.convertRvalueExpression(expr.right());
1406 if (isa<moore::TimeType>(lhs.getType()) ||
1407 isa<moore::TimeType>(rhs.getType())) {
1408 lhs =
context.materializeConversion(
1409 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1411 rhs =
context.materializeConversion(
1412 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1416 using slang::ast::BinaryOperator;
1418 case BinaryOperator::Add:
1419 return moore::AddRealOp::create(builder, loc, lhs, rhs);
1420 case BinaryOperator::Subtract:
1421 return moore::SubRealOp::create(builder, loc, lhs, rhs);
1422 case BinaryOperator::Multiply:
1423 return moore::MulRealOp::create(builder, loc, lhs, rhs);
1424 case BinaryOperator::Divide:
1425 return moore::DivRealOp::create(builder, loc, lhs, rhs);
1426 case BinaryOperator::Power:
1427 return moore::PowRealOp::create(builder, loc, lhs, rhs);
1429 case BinaryOperator::Equality:
1430 return moore::EqRealOp::create(builder, loc, lhs, rhs);
1431 case BinaryOperator::Inequality:
1432 return moore::NeRealOp::create(builder, loc, lhs, rhs);
1434 case BinaryOperator::GreaterThan:
1435 return moore::FgtOp::create(builder, loc, lhs, rhs);
1436 case BinaryOperator::LessThan:
1437 return moore::FltOp::create(builder, loc, lhs, rhs);
1438 case BinaryOperator::GreaterThanEqual:
1439 return moore::FgeOp::create(builder, loc, lhs, rhs);
1440 case BinaryOperator::LessThanEqual:
1441 return moore::FleOp::create(builder, loc, lhs, rhs);
1443 case BinaryOperator::LogicalAnd:
1444 case BinaryOperator::LogicalOr:
1445 case BinaryOperator::LogicalImplication:
1446 case BinaryOperator::LogicalEquivalence:
1447 return buildLogicalBOp(expr.op, lhs, rhs);
1450 mlir::emitError(loc) <<
"Binary operator "
1451 << slang::ast::toString(expr.op)
1452 <<
" not supported with real valued operands!\n";
1459 template <
class ConcreteOp>
1460 Value createBinary(Value lhs, Value rhs) {
1461 lhs =
context.convertToSimpleBitVector(lhs);
1464 rhs =
context.convertToSimpleBitVector(rhs);
1467 return ConcreteOp::create(builder, loc, lhs, rhs);
1471 Value visit(
const slang::ast::BinaryExpression &expr) {
1473 const auto *rhsFloatType =
1474 expr.right().type->as_if<slang::ast::FloatingType>();
1475 const auto *lhsFloatType =
1476 expr.left().type->as_if<slang::ast::FloatingType>();
1479 if (rhsFloatType || lhsFloatType)
1480 return visitRealBOp(expr);
1483 const auto rhsIsClass = expr.right().type->isClass();
1484 const auto lhsIsClass = expr.left().type->isClass();
1485 const auto rhsIsChandle = expr.right().type->isCHandle();
1486 const auto lhsIsChandle = expr.left().type->isCHandle();
1488 if (rhsIsClass || lhsIsClass || rhsIsChandle || lhsIsChandle)
1489 return visitHandleBOp(expr);
1491 auto lhs =
context.convertRvalueExpression(expr.left());
1494 auto rhs =
context.convertRvalueExpression(expr.right());
1499 Domain domain = Domain::TwoValued;
1500 if (expr.type->isFourState() || expr.left().type->isFourState() ||
1501 expr.right().type->isFourState())
1502 domain = Domain::FourValued;
1504 using slang::ast::BinaryOperator;
1506 case BinaryOperator::Add:
1507 return createBinary<moore::AddOp>(lhs, rhs);
1508 case BinaryOperator::Subtract:
1509 return createBinary<moore::SubOp>(lhs, rhs);
1510 case BinaryOperator::Multiply:
1511 return createBinary<moore::MulOp>(lhs, rhs);
1512 case BinaryOperator::Divide:
1513 if (expr.type->isSigned())
1514 return createBinary<moore::DivSOp>(lhs, rhs);
1516 return createBinary<moore::DivUOp>(lhs, rhs);
1517 case BinaryOperator::Mod:
1518 if (expr.type->isSigned())
1519 return createBinary<moore::ModSOp>(lhs, rhs);
1521 return createBinary<moore::ModUOp>(lhs, rhs);
1522 case BinaryOperator::Power: {
1527 auto rhsCast =
context.materializeConversion(
1528 lhs.getType(), rhs, expr.right().type->isSigned(), rhs.getLoc());
1529 if (expr.type->isSigned())
1530 return createBinary<moore::PowSOp>(lhs, rhsCast);
1532 return createBinary<moore::PowUOp>(lhs, rhsCast);
1535 case BinaryOperator::BinaryAnd:
1536 return createBinary<moore::AndOp>(lhs, rhs);
1537 case BinaryOperator::BinaryOr:
1538 return createBinary<moore::OrOp>(lhs, rhs);
1539 case BinaryOperator::BinaryXor:
1540 return createBinary<moore::XorOp>(lhs, rhs);
1541 case BinaryOperator::BinaryXnor: {
1542 auto result = createBinary<moore::XorOp>(lhs, rhs);
1545 return moore::NotOp::create(builder, loc, result);
1548 case BinaryOperator::Equality:
1549 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1550 return moore::UArrayCmpOp::create(
1551 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1552 else if (isa<moore::StringType>(lhs.getType()))
1553 return moore::StringCmpOp::create(
1554 builder, loc, moore::StringCmpPredicate::eq, lhs, rhs);
1555 else if (isa<moore::QueueType>(lhs.getType()))
1556 return moore::QueueCmpOp::create(
1557 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1559 return createBinary<moore::EqOp>(lhs, rhs);
1560 case BinaryOperator::Inequality:
1561 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1562 return moore::UArrayCmpOp::create(
1563 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1564 else if (isa<moore::StringType>(lhs.getType()))
1565 return moore::StringCmpOp::create(
1566 builder, loc, moore::StringCmpPredicate::ne, lhs, rhs);
1567 else if (isa<moore::QueueType>(lhs.getType()))
1568 return moore::QueueCmpOp::create(
1569 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1571 return createBinary<moore::NeOp>(lhs, rhs);
1572 case BinaryOperator::CaseEquality:
1573 return createBinary<moore::CaseEqOp>(lhs, rhs);
1574 case BinaryOperator::CaseInequality:
1575 return createBinary<moore::CaseNeOp>(lhs, rhs);
1576 case BinaryOperator::WildcardEquality:
1577 return createBinary<moore::WildcardEqOp>(lhs, rhs);
1578 case BinaryOperator::WildcardInequality:
1579 return createBinary<moore::WildcardNeOp>(lhs, rhs);
1581 case BinaryOperator::GreaterThanEqual:
1582 if (expr.left().type->isSigned())
1583 return createBinary<moore::SgeOp>(lhs, rhs);
1584 else if (isa<moore::StringType>(lhs.getType()))
1585 return moore::StringCmpOp::create(
1586 builder, loc, moore::StringCmpPredicate::ge, lhs, rhs);
1588 return createBinary<moore::UgeOp>(lhs, rhs);
1589 case BinaryOperator::GreaterThan:
1590 if (expr.left().type->isSigned())
1591 return createBinary<moore::SgtOp>(lhs, rhs);
1592 else if (isa<moore::StringType>(lhs.getType()))
1593 return moore::StringCmpOp::create(
1594 builder, loc, moore::StringCmpPredicate::gt, lhs, rhs);
1596 return createBinary<moore::UgtOp>(lhs, rhs);
1597 case BinaryOperator::LessThanEqual:
1598 if (expr.left().type->isSigned())
1599 return createBinary<moore::SleOp>(lhs, rhs);
1600 else if (isa<moore::StringType>(lhs.getType()))
1601 return moore::StringCmpOp::create(
1602 builder, loc, moore::StringCmpPredicate::le, lhs, rhs);
1604 return createBinary<moore::UleOp>(lhs, rhs);
1605 case BinaryOperator::LessThan:
1606 if (expr.left().type->isSigned())
1607 return createBinary<moore::SltOp>(lhs, rhs);
1608 else if (isa<moore::StringType>(lhs.getType()))
1609 return moore::StringCmpOp::create(
1610 builder, loc, moore::StringCmpPredicate::lt, lhs, rhs);
1612 return createBinary<moore::UltOp>(lhs, rhs);
1614 case BinaryOperator::LogicalAnd:
1615 case BinaryOperator::LogicalOr:
1616 case BinaryOperator::LogicalImplication:
1617 case BinaryOperator::LogicalEquivalence:
1618 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1620 case BinaryOperator::LogicalShiftLeft:
1621 return createBinary<moore::ShlOp>(lhs, rhs);
1622 case BinaryOperator::LogicalShiftRight:
1623 return createBinary<moore::ShrOp>(lhs, rhs);
1624 case BinaryOperator::ArithmeticShiftLeft:
1625 return createBinary<moore::ShlOp>(lhs, rhs);
1626 case BinaryOperator::ArithmeticShiftRight: {
1629 lhs =
context.convertToSimpleBitVector(lhs);
1630 rhs =
context.convertToSimpleBitVector(rhs);
1633 if (expr.type->isSigned())
1634 return moore::AShrOp::create(builder, loc, lhs, rhs);
1635 return moore::ShrOp::create(builder, loc, lhs, rhs);
1639 mlir::emitError(loc,
"unsupported binary operator");
1644 Value visit(
const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
1645 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1649 Value visit(
const slang::ast::IntegerLiteral &expr) {
1650 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1654 Value visit(
const slang::ast::TimeLiteral &expr) {
1659 double value = std::round(expr.getValue() * scale);
1669 static constexpr uint64_t limit =
1670 (std::numeric_limits<uint64_t>::max() >> 11) << 11;
1671 if (value > limit) {
1672 mlir::emitError(loc) <<
"time value is larger than " << limit <<
" fs";
1676 return moore::ConstantTimeOp::create(builder, loc,
1677 static_cast<uint64_t
>(value));
1681 Value visit(
const slang::ast::ReplicationExpression &expr) {
1682 auto type =
context.convertType(*expr.type);
1683 auto value =
context.convertRvalueExpression(expr.concat());
1686 return moore::ReplicateOp::create(builder, loc, type, value);
1690 Value visit(
const slang::ast::InsideExpression &expr) {
1691 auto lhs =
context.convertToSimpleBitVector(
1692 context.convertRvalueExpression(expr.left()));
1697 SmallVector<Value> conditions;
1700 for (
const auto *listExpr : expr.rangeList()) {
1701 auto cond =
context.convertInsideCheck(lhs, loc, *listExpr);
1705 conditions.push_back(cond);
1709 auto result = conditions.back();
1710 conditions.pop_back();
1711 while (!conditions.empty()) {
1712 result = moore::OrOp::create(builder, loc, conditions.back(), result);
1713 conditions.pop_back();
1719 Value visit(
const slang::ast::ConditionalExpression &expr) {
1720 auto type =
context.convertType(*expr.type);
1723 if (expr.conditions.size() > 1) {
1724 mlir::emitError(loc)
1725 <<
"unsupported conditional expression with more than one condition";
1728 const auto &cond = expr.conditions[0];
1730 mlir::emitError(loc) <<
"unsupported conditional expression with pattern";
1734 context.convertToBool(
context.convertRvalueExpression(*cond.expr));
1737 auto conditionalOp =
1738 moore::ConditionalOp::create(builder, loc, type, value);
1741 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
1742 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
1744 OpBuilder::InsertionGuard g(builder);
1747 builder.setInsertionPointToStart(&trueBlock);
1748 auto trueValue =
context.convertRvalueExpression(expr.left(), type);
1751 moore::YieldOp::create(builder, loc, trueValue);
1754 builder.setInsertionPointToStart(&falseBlock);
1755 auto falseValue =
context.convertRvalueExpression(expr.right(), type);
1758 moore::YieldOp::create(builder, loc, falseValue);
1760 return conditionalOp.getResult();
1764 Value visit(
const slang::ast::CallExpression &expr) {
1766 auto constant =
context.evaluateConstant(expr);
1767 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1771 [&](
auto &subroutine) {
return visitCall(expr, subroutine); },
1777 std::pair<Value, moore::ClassHandleType>
1778 getMethodReceiverTypeHandle(
const slang::ast::CallExpression &expr) {
1780 moore::ClassHandleType handleTy;
1784 if (
const slang::ast::Expression *recvExpr = expr.thisClass()) {
1785 thisRef =
context.convertRvalueExpression(*recvExpr);
1790 thisRef =
context.getImplicitThisRef();
1792 mlir::emitError(loc) <<
"method '" << expr.getSubroutineName()
1793 <<
"' called without an object";
1797 handleTy = cast<moore::ClassHandleType>(thisRef.getType());
1798 return {thisRef, handleTy};
1802 mlir::CallOpInterface
1803 buildMethodCall(
const slang::ast::SubroutineSymbol *subroutine,
1805 moore::ClassHandleType actualHandleTy, Value actualThisRef,
1806 SmallVector<Value> &arguments,
1807 SmallVector<Type> &resultTypes) {
1810 auto funcTy = cast<FunctionType>(lowering->
op.getFunctionType());
1811 auto expected0 = funcTy.getInput(0);
1812 auto expectedHdlTy = cast<moore::ClassHandleType>(expected0);
1815 auto implicitThisRef =
context.materializeConversion(
1816 expectedHdlTy, actualThisRef,
false, actualThisRef.getLoc());
1819 SmallVector<Value> explicitArguments;
1820 explicitArguments.reserve(arguments.size() + 1);
1821 explicitArguments.push_back(implicitThisRef);
1822 explicitArguments.append(arguments.begin(), arguments.end());
1825 const bool isVirtual =
1826 (subroutine->flags & slang::ast::MethodFlags::Virtual) != 0;
1829 auto calleeSym = lowering->
op.getNameAttr().getValue();
1830 if (isa<moore::CoroutineOp>(lowering->
op.getOperation()))
1831 return moore::CallCoroutineOp::create(builder, loc, resultTypes,
1832 calleeSym, explicitArguments);
1833 return mlir::func::CallOp::create(builder, loc, resultTypes, calleeSym,
1837 auto funcName = subroutine->name;
1838 auto method = moore::VTableLoadMethodOp::create(
1839 builder, loc, funcTy, actualThisRef,
1840 SymbolRefAttr::get(
context.getContext(), funcName));
1841 return mlir::func::CallIndirectOp::create(builder, loc, method,
1846 Value visitCall(
const slang::ast::CallExpression &expr,
1847 const slang::ast::SubroutineSymbol *subroutine) {
1849 const bool isMethod = (subroutine->thisVar !=
nullptr);
1851 auto *lowering =
context.declareFunction(*subroutine);
1855 if (isa<moore::DPIFuncOp>(lowering->
op.getOperation())) {
1856 SmallVector<Value> operands;
1857 SmallVector<Value> resultTargets;
1859 for (
auto [callArg, declArg] :
1860 llvm::zip(expr.arguments(), subroutine->getArguments())) {
1861 auto *actual = callArg;
1862 if (
const auto *assign =
1863 actual->as_if<slang::ast::AssignmentExpression>())
1864 actual = &assign->left();
1866 auto argType =
context.convertType(declArg->getType());
1870 switch (declArg->direction) {
1871 case slang::ast::ArgumentDirection::In: {
1872 auto value =
context.convertRvalueExpression(*actual, argType);
1875 operands.push_back(value);
1878 case slang::ast::ArgumentDirection::Out: {
1879 auto lvalue =
context.convertLvalueExpression(*actual);
1882 resultTargets.push_back(lvalue);
1885 case slang::ast::ArgumentDirection::InOut:
1886 case slang::ast::ArgumentDirection::Ref: {
1887 auto lvalue =
context.convertLvalueExpression(*actual);
1890 auto value =
context.convertRvalueExpression(*actual, argType);
1893 operands.push_back(value);
1894 resultTargets.push_back(lvalue);
1900 SmallVector<Type> resultTypes(
1901 cast<FunctionType>(lowering->
op.getFunctionType()).getResults());
1902 auto callOp = moore::FuncDPICallOp::create(
1903 builder, loc, resultTypes,
1904 SymbolRefAttr::get(lowering->
op.getNameAttr()), operands);
1906 unsigned resultIndex = 0;
1907 unsigned targetIndex = 0;
1908 for (
const auto *declArg : subroutine->getArguments()) {
1909 auto argType =
context.convertType(declArg->getType());
1913 switch (declArg->direction) {
1914 case slang::ast::ArgumentDirection::Out:
1915 case slang::ast::ArgumentDirection::InOut:
1916 case slang::ast::ArgumentDirection::Ref: {
1917 auto lvalue = resultTargets[targetIndex++];
1918 auto refTy = dyn_cast<moore::RefType>(lvalue.getType());
1920 lowering->
op->emitError(
1921 "expected DPI output target to be moore::RefType");
1924 auto converted =
context.materializeConversion(
1925 refTy.getNestedType(), callOp->getResult(resultIndex++),
1926 declArg->getType().isSigned(), loc);
1929 moore::BlockingAssignOp::create(builder, loc, lvalue, converted);
1937 if (!subroutine->getReturnType().isVoid())
1938 return callOp->getResult(resultIndex);
1940 return mlir::UnrealizedConversionCastOp::create(
1941 builder, loc, moore::VoidType::get(
context.getContext()),
1949 SmallVector<Value> arguments;
1950 for (
auto [callArg, declArg] :
1951 llvm::zip(expr.arguments(), subroutine->getArguments())) {
1955 auto *expr = callArg;
1956 if (
const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
1957 expr = &assign->left();
1960 auto type =
context.convertType(declArg->getType());
1961 if (declArg->direction == slang::ast::ArgumentDirection::In) {
1962 value =
context.convertRvalueExpression(*expr, type);
1964 Value lvalue =
context.convertLvalueExpression(*expr);
1965 auto unpackedType = dyn_cast<moore::UnpackedType>(type);
1969 context.materializeConversion(moore::RefType::get(unpackedType),
1970 lvalue, expr->type->isSigned(), loc);
1974 arguments.push_back(value);
1981 for (
auto *sym : lowering->capturedSymbols) {
1982 Value val =
context.valueSymbols.lookup(sym);
1984 mlir::emitError(loc) <<
"failed to resolve captured variable `"
1985 << sym->name <<
"` at call site";
1988 arguments.push_back(val);
1992 SmallVector<Type> resultTypes(
1993 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().begin(),
1994 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().end());
1996 mlir::CallOpInterface callOp;
2000 auto [thisRef, tyHandle] = getMethodReceiverTypeHandle(expr);
2001 callOp = buildMethodCall(subroutine, lowering, tyHandle, thisRef,
2002 arguments, resultTypes);
2003 }
else if (isa<moore::CoroutineOp>(lowering->
op.getOperation())) {
2005 auto coroutine = cast<moore::CoroutineOp>(lowering->
op.getOperation());
2007 moore::CallCoroutineOp::create(builder, loc, coroutine, arguments);
2010 auto funcOp = cast<mlir::func::FuncOp>(lowering->
op.getOperation());
2011 callOp = mlir::func::CallOp::create(builder, loc, funcOp, arguments);
2014 auto result = resultTypes.size() > 0 ? callOp->getOpResult(0) : Value{};
2018 if (resultTypes.size() == 0)
2019 return mlir::UnrealizedConversionCastOp::create(
2020 builder, loc, moore::VoidType::get(
context.getContext()),
2028 Value visitCall(
const slang::ast::CallExpression &expr,
2029 const slang::ast::CallExpression::SystemCallInfo &info) {
2030 using ksn = slang::parsing::KnownSystemName;
2031 const auto &subroutine = *
info.subroutine;
2032 auto nameId = subroutine.knownNameId;
2044 case ksn::IsUnknown:
2047 return context.convertAssertionCallExpression(expr, info, loc);
2052 auto args = expr.arguments();
2060 if (nameId == ksn::SFormatF) {
2062 auto fmtValue =
context.convertFormatString(
2063 expr.arguments(), loc, moore::IntFormat::Decimal,
false);
2064 if (failed(fmtValue))
2066 return fmtValue.value();
2070 auto result =
context.convertSystemCall(subroutine, loc, args);
2074 auto ty =
context.convertType(*expr.type);
2075 return context.materializeConversion(ty, result, expr.type->isSigned(),
2080 Value visit(
const slang::ast::StringLiteral &expr) {
2081 auto type =
context.convertType(*expr.type);
2082 return moore::ConstantStringOp::create(builder, loc, type, expr.getValue());
2086 Value visit(
const slang::ast::RealLiteral &expr) {
2087 auto fTy = mlir::Float64Type::get(
context.getContext());
2088 auto attr = mlir::FloatAttr::get(fTy, expr.getValue());
2089 return moore::ConstantRealOp::create(builder, loc, attr).getResult();
2094 FailureOr<SmallVector<Value>>
2095 convertElements(
const slang::ast::AssignmentPatternExpressionBase &expr,
2096 std::variant<Type, ArrayRef<Type>> expectedTypes,
2097 unsigned replCount) {
2098 const auto &elts = expr.elements();
2099 const size_t elementCount = elts.size();
2102 const bool hasBroadcast =
2103 std::holds_alternative<Type>(expectedTypes) &&
2104 static_cast<bool>(std::get<Type>(expectedTypes));
2106 const bool hasPerElem =
2107 std::holds_alternative<ArrayRef<Type>>(expectedTypes) &&
2108 !std::get<ArrayRef<Type>>(expectedTypes).empty();
2112 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2113 if (types.size() != elementCount) {
2114 mlir::emitError(loc)
2115 <<
"assignment pattern arity mismatch: expected " << types.size()
2116 <<
" elements, got " << elementCount;
2121 SmallVector<Value> converted;
2122 converted.reserve(elementCount * std::max(1u, replCount));
2125 if (!hasBroadcast && !hasPerElem) {
2127 for (
const auto *elementExpr : elts) {
2128 Value v =
context.convertRvalueExpression(*elementExpr);
2131 converted.push_back(v);
2133 }
else if (hasBroadcast) {
2135 Type want = std::get<Type>(expectedTypes);
2136 for (
const auto *elementExpr : elts) {
2137 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2138 :
context.convertRvalueExpression(*elementExpr);
2141 converted.push_back(v);
2144 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2145 for (
size_t i = 0; i < elementCount; ++i) {
2146 Type want = types[i];
2147 const auto *elementExpr = elts[i];
2148 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2149 :
context.convertRvalueExpression(*elementExpr);
2152 converted.push_back(v);
2156 for (
unsigned i = 1; i < replCount; ++i)
2157 converted.append(converted.begin(), converted.begin() + elementCount);
2163 Value visitAssignmentPattern(
2164 const slang::ast::AssignmentPatternExpressionBase &expr,
2165 unsigned replCount = 1) {
2166 auto type =
context.convertType(*expr.type);
2167 const auto &elts = expr.elements();
2170 if (
auto intType = dyn_cast<moore::IntType>(type)) {
2171 auto elements = convertElements(expr, {}, replCount);
2173 if (failed(elements))
2176 assert(intType.getWidth() == elements->size());
2177 std::reverse(elements->begin(), elements->end());
2178 return moore::ConcatOp::create(builder, loc, intType, *elements);
2182 if (
auto structType = dyn_cast<moore::StructType>(type)) {
2183 SmallVector<Type> expectedTy;
2184 expectedTy.reserve(structType.getMembers().size());
2185 for (
auto member : structType.getMembers())
2186 expectedTy.push_back(member.type);
2188 FailureOr<SmallVector<Value>> elements;
2189 if (expectedTy.size() == elts.size())
2190 elements = convertElements(expr, expectedTy, replCount);
2192 elements = convertElements(expr, {}, replCount);
2194 if (failed(elements))
2197 assert(structType.getMembers().size() == elements->size());
2198 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2202 if (
auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
2203 SmallVector<Type> expectedTy;
2204 expectedTy.reserve(structType.getMembers().size());
2205 for (
auto member : structType.getMembers())
2206 expectedTy.push_back(member.type);
2208 FailureOr<SmallVector<Value>> elements;
2209 if (expectedTy.size() == elts.size())
2210 elements = convertElements(expr, expectedTy, replCount);
2212 elements = convertElements(expr, {}, replCount);
2214 if (failed(elements))
2217 assert(structType.getMembers().size() == elements->size());
2219 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2223 if (
auto arrayType = dyn_cast<moore::ArrayType>(type)) {
2225 convertElements(expr, arrayType.getElementType(), replCount);
2227 if (failed(elements))
2230 assert(arrayType.getSize() == elements->size());
2231 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2235 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
2237 convertElements(expr, arrayType.getElementType(), replCount);
2239 if (failed(elements))
2242 assert(arrayType.getSize() == elements->size());
2243 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2247 if (
auto openType = dyn_cast<moore::OpenUnpackedArrayType>(type)) {
2249 convertElements(expr, openType.getElementType(), replCount);
2251 if (failed(elements))
2254 auto arrayType = moore::UnpackedArrayType::get(
2255 context.getContext(), elements->size(), openType.getElementType());
2256 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2259 mlir::emitError(loc) <<
"unsupported assignment pattern with type " << type;
2263 Value visit(
const slang::ast::SimpleAssignmentPatternExpression &expr) {
2264 return visitAssignmentPattern(expr);
2267 Value visit(
const slang::ast::StructuredAssignmentPatternExpression &expr) {
2268 return visitAssignmentPattern(expr);
2271 Value visit(
const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
2273 context.evaluateConstant(expr.count()).integer().as<
unsigned>();
2274 assert(count &&
"Slang guarantees constant non-zero replication count");
2275 return visitAssignmentPattern(expr, *count);
2278 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2279 SmallVector<Value> operands;
2280 for (
auto stream : expr.streams()) {
2281 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2282 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2283 mlir::emitError(operandLoc)
2284 <<
"Moore only support streaming "
2285 "concatenation with fixed size 'with expression'";
2289 if (stream.constantWithWidth.has_value()) {
2290 value =
context.convertRvalueExpression(*stream.withExpr);
2291 auto type = cast<moore::UnpackedType>(value.getType());
2292 auto intType = moore::IntType::get(
2293 context.getContext(), type.getBitSize().value(), type.getDomain());
2295 value =
context.materializeConversion(intType, value,
false, loc);
2297 value =
context.convertRvalueExpression(*stream.operand);
2300 value =
context.convertToSimpleBitVector(value);
2303 operands.push_back(value);
2307 if (operands.size() == 1) {
2310 value = operands.front();
2312 value = moore::ConcatOp::create(builder, loc, operands).getResult();
2315 if (expr.getSliceSize() == 0) {
2319 auto type = cast<moore::IntType>(value.getType());
2320 SmallVector<Value> slicedOperands;
2321 auto iterMax = type.getWidth() / expr.getSliceSize();
2322 auto remainSize = type.getWidth() % expr.getSliceSize();
2324 for (
size_t i = 0; i < iterMax; i++) {
2325 auto extractResultType = moore::IntType::get(
2326 context.getContext(), expr.getSliceSize(), type.getDomain());
2328 auto extracted = moore::ExtractOp::create(builder, loc, extractResultType,
2329 value, i * expr.getSliceSize());
2330 slicedOperands.push_back(extracted);
2334 auto extractResultType = moore::IntType::get(
2335 context.getContext(), remainSize, type.getDomain());
2338 moore::ExtractOp::create(builder, loc, extractResultType, value,
2339 iterMax * expr.getSliceSize());
2340 slicedOperands.push_back(extracted);
2343 return moore::ConcatOp::create(builder, loc, slicedOperands);
2346 Value visit(
const slang::ast::AssertionInstanceExpression &expr) {
2347 return context.convertAssertionExpression(expr.body, loc);
2350 Value visit(
const slang::ast::UnboundedLiteral &expr) {
2352 "slang checks $ only used within queue index expression");
2356 moore::QueueSizeBIOp::create(builder, loc,
context.getIndexedQueue());
2357 auto one = moore::ConstantOp::create(builder, loc, queueSize.getType(), 1);
2358 auto lastElement = moore::SubOp::create(builder, loc, queueSize, one);
2375 Value visit(
const slang::ast::NewClassExpression &expr) {
2376 auto type =
context.convertType(*expr.type);
2377 auto classTy = dyn_cast<moore::ClassHandleType>(type);
2383 if (!classTy && expr.isSuperClass) {
2384 newObj =
context.getImplicitThisRef();
2385 if (!newObj || !newObj.getType() ||
2386 !isa<moore::ClassHandleType>(newObj.getType())) {
2387 mlir::emitError(loc) <<
"implicit this ref was not set while "
2388 "converting new class function";
2391 auto thisType = cast<moore::ClassHandleType>(newObj.getType());
2393 cast<moore::ClassDeclOp>(*
context.symbolTable.lookupNearestSymbolFrom(
2394 context.intoModuleOp, thisType.getClassSym()));
2395 auto baseClassSym = classDecl.getBase();
2396 classTy = circt::moore::ClassHandleType::get(
context.getContext(),
2397 baseClassSym.value());
2400 newObj = moore::ClassNewOp::create(builder, loc, classTy, {});
2403 const auto *constructor = expr.constructorCall();
2408 if (
const auto *callConstructor =
2409 constructor->as_if<slang::ast::CallExpression>())
2410 if (
const auto *subroutine =
2411 std::get_if<const slang::ast::SubroutineSymbol *>(
2412 &callConstructor->subroutine)) {
2413 if (!(*subroutine)->thisVar) {
2414 mlir::emitError(loc)
2415 <<
"unsupported constructor call without `this` argument";
2419 llvm::SaveAndRestore saveThis(
context.currentThisRef, newObj);
2420 if (!visitCall(*callConstructor, *subroutine))
2428 template <
typename T>
2429 Value visit(T &&node) {
2430 mlir::emitError(loc,
"unsupported expression: ")
2431 << slang::ast::toString(node.kind);
2435 Value visitInvalid(
const slang::ast::Expression &expr) {
2436 mlir::emitError(loc,
"invalid expression");
2447struct LvalueExprVisitor :
public ExprVisitor {
2449 : ExprVisitor(
context, loc, true) {}
2450 using ExprVisitor::visit;
2453 Value visit(
const slang::ast::NamedValueExpression &expr) {
2455 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2459 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2460 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2462 if (
auto *
const property =
2463 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
2467 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
2469 auto type =
context.convertType(*expr.type);
2472 auto memberType = dyn_cast<moore::UnpackedType>(type);
2474 mlir::emitError(loc)
2475 <<
"unsupported virtual interface member type: " << type;
2479 Value base = materializeSymbolRvalue(*access.base);
2481 auto d = mlir::emitError(loc,
"unknown name `")
2482 << access.base->name <<
"`";
2483 d.attachNote(
context.convertLocation(access.base->location))
2484 <<
"no rvalue generated for virtual interface base";
2488 auto fieldName = access.fieldName
2490 : builder.getStringAttr(expr.symbol.name);
2491 auto memberRefType = moore::RefType::get(memberType);
2492 return moore::StructExtractOp::create(builder, loc, memberRefType,
2496 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
2497 d.attachNote(
context.convertLocation(expr.symbol.location))
2498 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2503 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
2506 if (!expr.ref.path.empty()) {
2507 if (
auto *inst = expr.ref.path.front()
2508 .symbol->as_if<slang::ast::InstanceSymbol>()) {
2510 expr.symbol.getParentScope()->getContainingInstance();
2511 if (&inst->body == symbolBody ||
2512 (symbolBody && inst->body.getDeclaringDefinition() ==
2513 symbolBody->getDeclaringDefinition())) {
2514 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2523 if (
auto key =
context.buildHierValueKey(expr)) {
2524 if (
auto it =
context.hierValueSymbols.find(*key);
2525 it !=
context.hierValueSymbols.end())
2530 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2537 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2538 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2542 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
2543 << expr.symbol.name <<
"`";
2544 d.attachNote(
context.convertLocation(expr.symbol.location))
2545 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2549 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2550 SmallVector<Value> operands;
2551 for (
auto stream : expr.streams()) {
2552 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2553 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2554 mlir::emitError(operandLoc)
2555 <<
"Moore only support streaming "
2556 "concatenation with fixed size 'with expression'";
2560 if (stream.constantWithWidth.has_value()) {
2561 value =
context.convertLvalueExpression(*stream.withExpr);
2562 auto type = cast<moore::UnpackedType>(
2563 cast<moore::RefType>(value.getType()).getNestedType());
2564 auto intType = moore::RefType::get(moore::IntType::get(
2565 context.getContext(), type.getBitSize().value(), type.getDomain()));
2567 value =
context.materializeConversion(intType, value,
false, loc);
2569 value =
context.convertLvalueExpression(*stream.operand);
2574 operands.push_back(value);
2577 if (operands.size() == 1) {
2580 value = operands.front();
2582 value = moore::ConcatRefOp::create(builder, loc, operands).getResult();
2585 if (expr.getSliceSize() == 0) {
2589 auto type = cast<moore::IntType>(
2590 cast<moore::RefType>(value.getType()).getNestedType());
2591 SmallVector<Value> slicedOperands;
2592 auto widthSum = type.getWidth();
2593 auto domain = type.getDomain();
2594 auto iterMax = widthSum / expr.getSliceSize();
2595 auto remainSize = widthSum % expr.getSliceSize();
2597 for (
size_t i = 0; i < iterMax; i++) {
2598 auto extractResultType = moore::RefType::get(moore::IntType::get(
2599 context.getContext(), expr.getSliceSize(), domain));
2601 auto extracted = moore::ExtractRefOp::create(
2602 builder, loc, extractResultType, value, i * expr.getSliceSize());
2603 slicedOperands.push_back(extracted);
2607 auto extractResultType = moore::RefType::get(
2608 moore::IntType::get(
context.getContext(), remainSize, domain));
2611 moore::ExtractRefOp::create(builder, loc, extractResultType, value,
2612 iterMax * expr.getSliceSize());
2613 slicedOperands.push_back(extracted);
2616 return moore::ConcatRefOp::create(builder, loc, slicedOperands);
2620 template <
typename T>
2621 Value visit(T &&node) {
2622 return context.convertRvalueExpression(node);
2625 Value visitInvalid(
const slang::ast::Expression &expr) {
2626 mlir::emitError(loc,
"invalid expression");
2636std::optional<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>>
2637Context::buildHierValueKey(
2638 const slang::ast::HierarchicalValueExpression &expr) {
2639 if (expr.ref.path.empty())
2640 return std::nullopt;
2642 const slang::ast::InstanceSymbol *firstInst =
nullptr;
2643 SmallVector<StringRef, 4> names;
2644 for (
auto &elem : expr.ref.path) {
2645 if (
auto *inst = elem.symbol->as_if<slang::ast::InstanceSymbol>()) {
2649 names.push_back(inst->name);
2653 names.push_back(expr.symbol.name);
2654 std::string hierName = llvm::join(names,
".");
2657 return std::nullopt;
2658 return std::make_pair(firstInst,
builder.getStringAttr(hierName));
2666 Type requiredType) {
2668 auto value = expr.visit(RvalueExprVisitor(*
this, loc));
2669 if (value && requiredType)
2677 return expr.visit(LvalueExprVisitor(*
this, loc));
2685 if (
auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
2686 if (type.getBitSize() == 1)
2688 if (
auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
2689 return moore::BoolCastOp::create(
builder, value.getLoc(), value);
2690 mlir::emitError(value.getLoc(),
"expression of type ")
2691 << value.getType() <<
" cannot be cast to a boolean";
2697 const slang::ast::Type &astType,
2699 const auto *floatType = astType.as_if<slang::ast::FloatingType>();
2703 if (svreal.isShortReal() &&
2704 floatType->floatKind == slang::ast::FloatingType::ShortReal) {
2705 attr = FloatAttr::get(
builder.getF32Type(), svreal.shortReal().v);
2706 }
else if (svreal.isReal() &&
2707 floatType->floatKind == slang::ast::FloatingType::Real) {
2708 attr = FloatAttr::get(
builder.getF64Type(), svreal.real().v);
2710 mlir::emitError(loc) <<
"invalid real constant";
2714 return moore::ConstantRealOp::create(
builder, loc, attr);
2719 const slang::ast::Type &astType,
2721 slang::ConstantValue intVal = stringLiteral.convertToInt();
2722 auto effectiveWidth = intVal.getEffectiveWidth();
2723 if (!effectiveWidth)
2726 auto intTy = moore::IntType::getInt(
getContext(), effectiveWidth.value());
2728 if (astType.isString()) {
2729 auto immInt = moore::ConstantStringOp::create(
builder, loc, intTy,
2730 stringLiteral.toString())
2732 return moore::IntToStringOp::create(
builder, loc, immInt).getResult();
2739 const slang::ast::Type &astType, Location loc) {
2744 bool typeIsFourValued =
false;
2745 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2749 auto intType = moore::IntType::get(
getContext(), fvint.getBitWidth(),
2750 fvint.hasUnknown() || typeIsFourValued
2753 auto result = moore::ConstantOp::create(
builder, loc, intType, fvint);
2758 const slang::ConstantValue &constant,
2759 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc) {
2766 if (astType.elementType.isString()) {
2767 auto arrayType = dyn_cast<moore::UnpackedArrayType>(type);
2771 SmallVector<Value> elemVals;
2772 for (
const auto &elem : constant.elements()) {
2773 if (!elem.isString())
2778 elemVals.push_back(value);
2780 if (elemVals.size() != arrayType.getSize())
2782 return moore::ArrayCreateOp::create(
builder, loc, arrayType, elemVals);
2787 if (astType.elementType.isIntegral())
2788 bitWidth = astType.elementType.getBitWidth();
2792 bool typeIsFourValued =
false;
2795 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2806 auto intType = moore::IntType::get(
getContext(), bitWidth, domain);
2808 auto arrType = moore::UnpackedArrayType::get(
2809 getContext(), constant.elements().size(), intType);
2811 llvm::SmallVector<mlir::Value> elemVals;
2812 moore::ConstantOp constOp;
2814 mlir::OpBuilder::InsertionGuard guard(
builder);
2817 for (
auto elem : constant.elements()) {
2819 constOp = moore::ConstantOp::create(
builder, loc, intType, fvInt);
2820 elemVals.push_back(constOp.getResult());
2825 auto arrayOp = moore::ArrayCreateOp::create(
builder, loc, arrType, elemVals);
2827 return arrayOp.getResult();
2831 const slang::ast::Type &type, Location loc) {
2833 if (
auto *arr = type.as_if<slang::ast::FixedSizeUnpackedArrayType>())
2835 if (constant.isInteger())
2837 if (constant.isReal() || constant.isShortReal())
2839 if (constant.isString())
2847 using slang::ast::EvalFlags;
2848 slang::ast::EvalContext evalContext(
2850 slang::ast::LookupLocation::max),
2851 EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
2852 return expr.eval(evalContext);
2861 auto type = moore::IntType::get(
getContext(), 1, domain);
2868 if (isa<moore::IntType>(value.getType()))
2875 if (
auto packed = dyn_cast<moore::PackedType>(value.getType()))
2876 if (
auto sbvType = packed.getSimpleBitVector())
2879 mlir::emitError(value.getLoc()) <<
"expression of type " << value.getType()
2880 <<
" cannot be cast to a simple bit vector";
2888 Location loc,
bool fallible) {
2889 if (isa<moore::IntType>(value.getType()))
2892 auto &builder =
context.builder;
2893 auto packedType = cast<moore::PackedType>(value.getType());
2894 auto intType = packedType.getSimpleBitVector();
2899 if (isa<moore::TimeType>(packedType) &&
2901 value = builder.createOrFold<moore::TimeToLogicOp>(loc, value);
2902 auto scale = moore::ConstantOp::create(builder, loc, intType,
2904 return builder.createOrFold<moore::DivUOp>(loc, value, scale);
2910 if (packedType.containsTimeType()) {
2912 mlir::emitError(loc) <<
"unsupported conversion: " << packedType
2913 <<
" cannot be converted to " << intType
2914 <<
"; contains a time type";
2919 return builder.createOrFold<moore::PackedToSBVOp>(loc, value);
2927 Value value, Location loc,
2929 if (value.getType() == packedType)
2932 auto &builder =
context.builder;
2933 auto intType = cast<moore::IntType>(value.getType());
2938 if (isa<moore::TimeType>(packedType) &&
2940 auto scale = moore::ConstantOp::create(builder, loc, intType,
2942 value = builder.createOrFold<moore::MulOp>(loc, value, scale);
2943 return builder.createOrFold<moore::LogicToTimeOp>(loc, value);
2951 mlir::emitError(loc) <<
"unsupported conversion: " << intType
2952 <<
" cannot be converted to " << packedType
2953 <<
"; contains a time type";
2958 return builder.createOrFold<moore::SBVToPackedOp>(loc, packedType, value);
2964 moore::ClassHandleType expectedHandleTy) {
2965 auto loc = actualHandle.getLoc();
2967 auto actualTy = actualHandle.getType();
2968 auto actualHandleTy = dyn_cast<moore::ClassHandleType>(actualTy);
2969 if (!actualHandleTy) {
2970 mlir::emitError(loc) <<
"expected a !moore.class<...> value, got "
2976 if (actualHandleTy == expectedHandleTy)
2977 return actualHandle;
2979 if (!
context.isClassDerivedFrom(actualHandleTy, expectedHandleTy)) {
2980 mlir::emitError(loc)
2981 <<
"receiver class " << actualHandleTy.getClassSym()
2982 <<
" is not the same as, or derived from, expected base class "
2983 << expectedHandleTy.getClassSym().getRootReference();
2988 auto casted = moore::ClassUpcastOp::create(
context.builder, loc,
2989 expectedHandleTy, actualHandle)
2995 Location loc,
bool fallible) {
2997 if (type == value.getType())
3002 auto dstPacked = dyn_cast<moore::PackedType>(type);
3003 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
3004 auto dstInt = dstPacked ? dstPacked.getSimpleBitVector() : moore::IntType();
3005 auto srcInt = srcPacked ? srcPacked.getSimpleBitVector() : moore::IntType();
3007 if (dstInt && srcInt) {
3015 auto resizedType = moore::IntType::get(
3016 value.getContext(), dstInt.getWidth(), srcPacked.getDomain());
3017 if (dstInt.getWidth() < srcInt.getWidth()) {
3018 value =
builder.createOrFold<moore::TruncOp>(loc, resizedType, value);
3019 }
else if (dstInt.getWidth() > srcInt.getWidth()) {
3021 value =
builder.createOrFold<moore::SExtOp>(loc, resizedType, value);
3023 value =
builder.createOrFold<moore::ZExtOp>(loc, resizedType, value);
3027 if (dstInt.getDomain() != srcInt.getDomain()) {
3029 value =
builder.createOrFold<moore::LogicToIntOp>(loc, value);
3031 value =
builder.createOrFold<moore::IntToLogicOp>(loc, value);
3040 assert(value.getType() == type);
3045 if (isa<moore::StringType>(type) &&
3046 isa<moore::FormatStringType>(value.getType())) {
3047 return builder.createOrFold<moore::FormatStringToStringOp>(loc, value);
3051 if (isa<moore::FormatStringType>(type) &&
3052 isa<moore::StringType>(value.getType())) {
3053 return builder.createOrFold<moore::FormatStringOp>(loc, value);
3058 if (isa<moore::QueueType>(type) && isa<moore::QueueType>(value.getType()) &&
3059 cast<moore::QueueType>(type).getElementType() ==
3060 cast<moore::QueueType>(value.getType()).getElementType())
3061 return builder.createOrFold<moore::QueueResizeOp>(loc, type, value);
3064 if (isa<moore::QueueType>(type) &&
3065 isa<moore::UnpackedArrayType>(value.getType())) {
3066 auto queueElType = dyn_cast<moore::QueueType>(type).getElementType();
3067 auto unpackedArrayElType =
3068 dyn_cast<moore::UnpackedArrayType>(value.getType()).getElementType();
3070 if (queueElType == unpackedArrayElType) {
3071 return builder.createOrFold<moore::QueueFromUnpackedArrayOp>(loc, type,
3077 if (dstInt && isa<moore::RealType>(value.getType())) {
3078 auto twoValInt =
builder.createOrFold<moore::RealToIntOp>(
3079 loc, dstInt.getTwoValued(), value);
3084 if (isa<moore::RealType>(type) && isa<moore::IntType>(value.getType())) {
3087 if (dyn_cast<moore::IntType>(value.getType()).getDomain() ==
3092 dyn_cast<moore::IntType>(value.getType()).getTwoValued(), value,
true,
3096 return builder.createOrFold<moore::SIntToRealOp>(loc, type, twoValInt);
3097 return builder.createOrFold<moore::UIntToRealOp>(loc, type, twoValInt);
3100 auto getBuiltinFloatType = [&](moore::RealType type) -> Type {
3102 return mlir::Float32Type::get(
builder.getContext());
3104 return mlir::Float64Type::get(
builder.getContext());
3108 if (isa<moore::TimeType>(type) && isa<moore::RealType>(value.getType())) {
3110 moore::IntType::get(
builder.getContext(), 64, Domain::TwoValued);
3112 getBuiltinFloatType(cast<moore::RealType>(value.getType()));
3113 auto scale = moore::ConstantRealOp::create(
3114 builder, loc, value.getType(),
3116 auto scaled =
builder.createOrFold<moore::MulRealOp>(loc, value, scale);
3117 auto asInt = moore::RealToIntOp::create(
builder, loc, intType, scaled);
3118 auto asLogic = moore::IntToLogicOp::create(
builder, loc, asInt);
3119 return moore::LogicToTimeOp::create(
builder, loc, asLogic);
3123 if (isa<moore::RealType>(type) && isa<moore::TimeType>(value.getType())) {
3124 auto asLogic = moore::TimeToLogicOp::create(
builder, loc, value);
3125 auto asInt = moore::LogicToIntOp::create(
builder, loc, asLogic);
3126 auto asReal = moore::UIntToRealOp::create(
builder, loc, type, asInt);
3127 Type floatType = getBuiltinFloatType(cast<moore::RealType>(type));
3128 auto scale = moore::ConstantRealOp::create(
3131 return moore::DivRealOp::create(
builder, loc, asReal, scale);
3135 if (isa<moore::StringType>(type)) {
3136 if (
auto intType = dyn_cast<moore::IntType>(value.getType())) {
3138 value = moore::LogicToIntOp::create(
builder, loc, value);
3139 return moore::IntToStringOp::create(
builder, loc, value);
3144 if (
auto intType = dyn_cast<moore::IntType>(type)) {
3145 if (isa<moore::StringType>(value.getType())) {
3146 value = moore::StringToIntOp::create(
builder, loc, intType.getTwoValued(),
3150 return moore::IntToLogicOp::create(
builder, loc, value);
3157 if (isa<moore::FormatStringType>(type)) {
3159 value, isSigned, loc);
3162 return moore::FormatStringOp::create(
builder, loc, asStr, {}, {}, {});
3165 if (isa<moore::RealType>(type) && isa<moore::RealType>(value.getType()))
3166 return builder.createOrFold<moore::ConvertRealOp>(loc, type, value);
3168 if (isa<moore::ClassHandleType>(type) &&
3169 isa<moore::ClassHandleType>(value.getType()))
3173 if (fallible && value.getType() != type)
3175 if (value.getType() != type)
3176 value = moore::ConversionOp::create(
builder, loc, type, value);
3182template <
typename OpTy>
3185 std::span<const slang::ast::Expression *const> args) {
3187 assert(args.size() == 1 &&
"real math builtin expects 1 argument");
3188 auto value =
context.convertRvalueExpression(*args[0]);
3191 return OpTy::create(
context.builder, loc, value);
3195 const slang::ast::SystemSubroutine &subroutine, Location loc,
3196 std::span<const slang::ast::Expression *const> args) {
3197 using ksn = slang::parsing::KnownSystemName;
3198 StringRef name = subroutine.name;
3199 auto nameId = subroutine.knownNameId;
3200 size_t numArgs = args.size();
3208 if (nameId == ksn::URandom || nameId == ksn::Random) {
3209 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3210 auto minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3212 moore::ConstantOp::create(
builder, loc, i32Ty, APInt::getAllOnes(32));
3219 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval, seed);
3222 if (nameId == ksn::URandomRange) {
3223 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3233 minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3235 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval,
3243 if (nameId == ksn::Time || nameId == ksn::STime || nameId == ksn::RealTime) {
3245 assert(numArgs == 0 &&
"time functions take no arguments");
3246 return moore::TimeBIOp::create(
builder, loc);
3253 if (nameId == ksn::Clog2) {
3255 assert(numArgs == 1 &&
"`$clog2` takes 1 argument");
3262 return moore::Clog2BIOp::create(
builder, loc, value);
3266 if (nameId == ksn::Ln)
3267 return convertRealMathBI<moore::LnBIOp>(*
this, loc, name, args);
3268 if (nameId == ksn::Log10)
3269 return convertRealMathBI<moore::Log10BIOp>(*
this, loc, name, args);
3270 if (nameId == ksn::Exp)
3271 return convertRealMathBI<moore::ExpBIOp>(*
this, loc, name, args);
3272 if (nameId == ksn::Sqrt)
3273 return convertRealMathBI<moore::SqrtBIOp>(*
this, loc, name, args);
3274 if (nameId == ksn::Floor)
3275 return convertRealMathBI<moore::FloorBIOp>(*
this, loc, name, args);
3276 if (nameId == ksn::Ceil)
3277 return convertRealMathBI<moore::CeilBIOp>(*
this, loc, name, args);
3278 if (nameId == ksn::Sin)
3279 return convertRealMathBI<moore::SinBIOp>(*
this, loc, name, args);
3280 if (nameId == ksn::Cos)
3281 return convertRealMathBI<moore::CosBIOp>(*
this, loc, name, args);
3282 if (nameId == ksn::Tan)
3283 return convertRealMathBI<moore::TanBIOp>(*
this, loc, name, args);
3284 if (nameId == ksn::Asin)
3285 return convertRealMathBI<moore::AsinBIOp>(*
this, loc, name, args);
3286 if (nameId == ksn::Acos)
3287 return convertRealMathBI<moore::AcosBIOp>(*
this, loc, name, args);
3288 if (nameId == ksn::Atan)
3289 return convertRealMathBI<moore::AtanBIOp>(*
this, loc, name, args);
3290 if (nameId == ksn::Sinh)
3291 return convertRealMathBI<moore::SinhBIOp>(*
this, loc, name, args);
3292 if (nameId == ksn::Cosh)
3293 return convertRealMathBI<moore::CoshBIOp>(*
this, loc, name, args);
3294 if (nameId == ksn::Tanh)
3295 return convertRealMathBI<moore::TanhBIOp>(*
this, loc, name, args);
3296 if (nameId == ksn::Asinh)
3297 return convertRealMathBI<moore::AsinhBIOp>(*
this, loc, name, args);
3298 if (nameId == ksn::Acosh)
3299 return convertRealMathBI<moore::AcoshBIOp>(*
this, loc, name, args);
3300 if (nameId == ksn::Atanh)
3301 return convertRealMathBI<moore::AtanhBIOp>(*
this, loc, name, args);
3307 if (nameId == ksn::Signed || nameId == ksn::Unsigned) {
3309 assert(numArgs == 1 &&
"`$signed`/`$unsigned` take 1 argument");
3315 if (nameId == ksn::RealToBits)
3316 return convertRealMathBI<moore::RealtobitsBIOp>(*
this, loc, name, args);
3317 if (nameId == ksn::BitsToReal)
3318 return convertRealMathBI<moore::BitstorealBIOp>(*
this, loc, name, args);
3319 if (nameId == ksn::ShortrealToBits)
3320 return convertRealMathBI<moore::ShortrealtobitsBIOp>(*
this, loc, name,
3322 if (nameId == ksn::BitsToShortreal)
3323 return convertRealMathBI<moore::BitstoshortrealBIOp>(*
this, loc, name,
3326 if (nameId == ksn::Cast) {
3327 assert(numArgs == 2 &&
"`cast` takes 2 arguments");
3328 auto *dstExpr = args[0];
3333 if (
auto *assign = dstExpr->as_if<slang::ast::AssignmentExpression>())
3334 dstExpr = &assign->left();
3343 if (isa<moore::ClassHandleType>(dstType) ||
3344 isa<moore::ClassHandleType>(src.getType())) {
3345 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3346 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3350 dstType, src, args[1]->type->isSigned(), loc,
true);
3351 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3353 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3355 moore::BlockingAssignOp::create(
builder, loc, dst, converted);
3356 return moore::ConstantOp::create(
builder, loc, i1Ty, 1,
3364 if (nameId == ksn::Len) {
3366 assert(numArgs == 1 &&
"`len` takes 1 argument");
3367 auto stringType = moore::StringType::get(
getContext());
3371 return moore::StringLenOp::create(
builder, loc, value);
3374 if (nameId == ksn::ToUpper) {
3376 assert(numArgs == 1 &&
"`toupper` takes 1 argument");
3377 auto stringType = moore::StringType::get(
getContext());
3381 return moore::StringToUpperOp::create(
builder, loc, value);
3384 if (nameId == ksn::ToLower) {
3386 assert(numArgs == 1 &&
"`tolower` takes 1 argument");
3387 auto stringType = moore::StringType::get(
getContext());
3391 return moore::StringToLowerOp::create(
builder, loc, value);
3394 if (nameId == ksn::Getc) {
3396 assert(numArgs == 2 &&
"`getc` takes 2 arguments");
3397 auto stringType = moore::StringType::get(
getContext());
3402 return moore::StringGetOp::create(
builder, loc, str, index);
3409 if (nameId == ksn::ArraySize) {
3411 assert(numArgs == 1 &&
"`size` takes 1 argument");
3412 if (args[0]->type->isQueue()) {
3416 return moore::QueueSizeBIOp::create(
builder, loc, value);
3418 if (args[0]->type->getCanonicalType().kind ==
3419 slang::ast::SymbolKind::DynamicArrayType) {
3423 return moore::OpenUArraySizeOp::create(
builder, loc, value);
3425 if (args[0]->type->isAssociativeArray()) {
3429 return moore::AssocArraySizeOp::create(
builder, loc, value);
3431 emitError(loc) <<
"unsupported member function `size` on type `"
3432 << args[0]->type->toString() <<
"`";
3436 if (nameId == ksn::Delete) {
3438 assert(numArgs == 1 &&
"`delete` takes 1 argument");
3439 if (args[0]->type->getCanonicalType().kind ==
3440 slang::ast::SymbolKind::DynamicArrayType) {
3444 return moore::OpenUArrayDeleteOp::create(
builder, loc, value);
3446 emitError(loc) <<
"unsupported member function `delete` on type `"
3447 << args[0]->type->toString() <<
"`";
3451 if (nameId == ksn::PopBack) {
3453 assert(numArgs == 1 &&
"`pop_back` takes 1 argument");
3454 assert(args[0]->type->isQueue() &&
"`pop_back` is only valid on queues");
3458 return moore::QueuePopBackOp::create(
builder, loc, value);
3461 if (nameId == ksn::PopFront) {
3463 assert(numArgs == 1 &&
"`pop_front` takes 1 argument");
3464 assert(args[0]->type->isQueue() &&
"`pop_front` is only valid on queues");
3468 return moore::QueuePopFrontOp::create(
builder, loc, value);
3475 if (nameId == ksn::Num) {
3476 if (args[0]->type->isAssociativeArray()) {
3477 assert(numArgs == 1 &&
"`num` takes 1 argument");
3481 return moore::AssocArraySizeOp::create(
builder, loc, value);
3483 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3487 if (nameId == ksn::Exists) {
3489 assert(numArgs == 2 &&
"`exists` takes 2 arguments");
3490 assert(args[0]->type->isAssociativeArray() &&
3491 "`exists` is only valid on associative arrays");
3496 return moore::AssocArrayExistsOp::create(
builder, loc, array, key);
3503 if (nameId == ksn::First || nameId == ksn::Last || nameId == ksn::Next ||
3504 nameId == ksn::Prev) {
3505 if (args[0]->type->isAssociativeArray()) {
3506 assert(numArgs == 2 &&
"traversal methods take 2 arguments");
3511 if (nameId == ksn::First)
3512 return moore::AssocArrayFirstOp::create(
builder, loc, array, key);
3513 if (nameId == ksn::Last)
3514 return moore::AssocArrayLastOp::create(
builder, loc, array, key);
3515 if (nameId == ksn::Next)
3516 return moore::AssocArrayNextOp::create(
builder, loc, array, key);
3517 if (nameId == ksn::Prev)
3518 return moore::AssocArrayPrevOp::create(
builder, loc, array, key);
3519 llvm_unreachable(
"all traversal cases handled above");
3521 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3529 if (nameId == ksn::FOpen) {
3530 assert(numArgs >= 1 && numArgs <= 2 &&
"`$fopen` takes 1 or 2 arguments");
3535 moore::FOpenModeAttr modeAttr;
3537 auto *strLit = args[1]
3538 ->unwrapImplicitConversions()
3539 .as_if<slang::ast::StringLiteral>();
3541 return emitError(loc) <<
"$fopen mode must be a string literal",
3545 llvm::StringSwitch<std::optional<moore::FOpenMode>>(
3547 .Cases({
"r",
"rb"}, moore::FOpenMode::Read)
3548 .Cases({
"w",
"wb"}, moore::FOpenMode::Write)
3549 .Cases({
"a",
"ab"}, moore::FOpenMode::Append)
3550 .Cases({
"r+",
"r+b",
"rb+"}, moore::FOpenMode::ReadUpdate)
3551 .Cases({
"w+",
"w+b",
"wb+"}, moore::FOpenMode::WriteUpdate)
3552 .Cases({
"a+",
"a+b",
"ab+"}, moore::FOpenMode::AppendUpdate)
3553 .Default(std::nullopt);
3556 return emitError(loc)
3557 <<
"invalid $fopen mode '" << strLit->getValue() <<
"'",
3559 modeAttr = moore::FOpenModeAttr::get(
getContext(), *mode);
3561 return moore::FOpenBIOp::create(
builder, loc, filename, modeAttr);
3565 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3571 return context.symbolTable.lookupNearestSymbolFrom(
context.intoModuleOp, sym);
3575 const moore::ClassHandleType &baseTy) {
3576 if (!actualTy || !baseTy)
3579 mlir::SymbolRefAttr actualSym = actualTy.getClassSym();
3580 mlir::SymbolRefAttr baseSym = baseTy.getClassSym();
3582 if (actualSym == baseSym)
3585 auto *op =
resolve(*
this, actualSym);
3586 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
3589 mlir::SymbolRefAttr curBase = decl.getBaseAttr();
3592 if (curBase == baseSym)
3594 decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(
resolve(*
this, curBase));
3599moore::ClassHandleType
3601 llvm::StringRef fieldName, Location loc) {
3603 mlir::SymbolRefAttr classSym = actualTy.getClassSym();
3607 auto *op =
resolve(*
this, classSym);
3608 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
3613 for (
auto &block : decl.getBody()) {
3614 for (
auto &opInBlock : block) {
3616 llvm::dyn_cast<moore::ClassPropertyDeclOp>(&opInBlock)) {
3617 if (prop.getSymName() == fieldName) {
3619 return moore::ClassHandleType::get(actualTy.getContext(), classSym);
3626 classSym = decl.getBaseAttr();
3630 mlir::emitError(loc) <<
"unknown property `" << fieldName <<
"`";
3639 const slang::ast::Expression &expr) {
3642 if (
const auto *valueRange = expr.as_if<slang::ast::ValueRangeExpression>()) {
3647 if (!insideLhs || !lowBound || !highBound)
3650 Value rangeLhs, rangeRhs;
3653 if (valueRange->left().type->isSigned() ||
3654 insideLhs.getType().isSignedInteger()) {
3655 rangeLhs = moore::SgeOp::create(
builder, loc, insideLhs, lowBound);
3657 rangeLhs = moore::UgeOp::create(
builder, loc, insideLhs, lowBound);
3660 if (valueRange->right().type->isSigned() ||
3661 insideLhs.getType().isSignedInteger()) {
3662 rangeRhs = moore::SleOp::create(
builder, loc, insideLhs, highBound);
3664 rangeRhs = moore::UleOp::create(
builder, loc, insideLhs, highBound);
3667 return moore::AndOp::create(
builder, loc, rangeLhs, rangeRhs);
3671 if (!expr.type->isIntegral()) {
3672 if (expr.type->isUnpackedArray()) {
3673 mlir::emitError(loc,
3674 "unpacked arrays in 'inside' expressions not supported");
3678 loc,
"only simple bit vectors supported in 'inside' expressions");
3685 return moore::WildcardEqOp::create(
builder, loc, insideLhs, value);
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static Value convertRealMathBI(Context &context, Location loc, StringRef name, std::span< const slang::ast::Expression *const > args)
Helper function to convert real math builtin functions that take exactly one argument.
static mlir::Value maybeUpcastHandle(Context &context, mlir::Value actualHandle, moore::ClassHandleType expectedHandleTy)
Check whether the actual handle is a subclass of another handle type and return a properly upcast ver...
static mlir::Operation * resolve(Context &context, mlir::SymbolRefAttr sym)
static Value lookupExpandedInterfaceMember(Context &context, const slang::ast::HierarchicalValueExpression &expr)
Resolve a hierarchical value that refers to a member of an expanded interface instance.
static Value visitClassProperty(Context &context, const slang::ast::ClassPropertySymbol &expr)
static Value materializeSBVToPackedConversion(Context &context, moore::PackedType packedType, Value value, Location loc, bool fallible)
Create the necessary operations to convert from a simple bit vector IntType to an equivalent PackedTy...
static Value materializePackedToSBVConversion(Context &context, Value value, Location loc, bool fallible)
Create the necessary operations to convert from a PackedType to the corresponding simple bit vector I...
static uint64_t getTimeScaleInFemtoseconds(Context &context)
Get the currently active timescale as an integer number of femtoseconds.
static Value getSelectIndex(Context &context, Location loc, Value index, const slang::ConstantRange &range)
Map an index into an array, with bounds range, to a bit offset of the underlying bit storage.
static FVInt convertSVIntToFVInt(const slang::SVInt &svint)
Convert a Slang SVInt to a CIRCT FVInt.
Four-valued arbitrary precision integers.
A packed SystemVerilog type.
bool containsTimeType() const
Check if this is a TimeType, or an aggregate that contains a nested TimeType.
IntType getSimpleBitVector() const
Get the simple bit vector type equivalent to this packed type.
An unpacked SystemVerilog type.
Domain
The number of values each bit of a type can assume.
@ FourValued
Four-valued types such as logic or integer.
@ TwoValued
Two-valued types such as bit or int.
bool isIntType(Type type, unsigned width)
Check if a type is an IntType type of the given width.
@ f32
A standard 32-Bit floating point number ("float")
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
Value convertLvalueExpression(const slang::ast::Expression &expr)
Value materializeConstant(const slang::ConstantValue &constant, const slang::ast::Type &type, Location loc)
Helper function to materialize a ConstantValue as an SSA value.
slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr)
Evaluate the constant value of an expression.
Value convertInsideCheck(Value insideLhs, Location loc, const slang::ast::Expression &expr)
Convert the inside/set-membership expression.
DenseMap< const slang::ast::ValueSymbol *, moore::GlobalVariableOp > globalVariables
A table of defined global variables that may be referred to by name in expressions.
slang::ast::Compilation & compilation
OpBuilder builder
The builder used to create IR operations.
Value materializeFixedSizeUnpackedArrayType(const slang::ConstantValue &constant, const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc)
Helper function to materialize an unpacked array of SVInts as an SSA value.
std::function< void(moore::ReadOp)> rvalueReadCallback
A listener called for every variable or net being read.
bool isClassDerivedFrom(const moore::ClassHandleType &actualTy, const moore::ClassHandleType &baseTy)
Checks whether one class (actualTy) is derived from another class (baseTy).
Value convertSystemCall(const slang::ast::SystemSubroutine &subroutine, Location loc, std::span< const slang::ast::Expression *const > args)
Convert system function calls.
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
Value materializeSVInt(const slang::SVInt &svint, const slang::ast::Type &type, Location loc)
Helper function to materialize an SVInt as an SSA value.
Value materializeSVReal(const slang::ConstantValue &svreal, const slang::ast::Type &type, Location loc)
Helper function to materialize a real value as an SSA value.
Value convertToBool(Value value)
Helper function to convert a value to its "truthy" boolean value.
ValueSymbols valueSymbols
moore::ClassHandleType getAncestorClassWithProperty(const moore::ClassHandleType &actualTy, StringRef fieldName, Location loc)
Tries to find the closest base class of actualTy that carries a property with name fieldName.
Value convertRvalueExpression(const slang::ast::Expression &expr, Type requiredType={})
Value convertToSimpleBitVector(Value value)
Helper function to convert a value to its simple bit vector representation, if it has one.
Value materializeString(const slang::ConstantValue &string, const slang::ast::Type &astType, Location loc)
Helper function to materialize a string as an SSA value.
Value materializeConversion(Type type, Value value, bool isSigned, Location loc, bool fallible=false)
Helper function to insert the necessary operations to cast a value from one type to another.
Value currentQueue
Variable that tracks the queue which we are currently converting the index expression for.
MLIRContext * getContext()
Return the MLIR context.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.
Function lowering information.
mlir::FunctionOpInterface op