14#include "mlir/IR/Operation.h"
15#include "mlir/IR/Value.h"
16#include "slang/ast/EvalContext.h"
17#include "slang/ast/SystemSubroutine.h"
18#include "slang/ast/types/AllTypes.h"
19#include "slang/syntax/AllSyntax.h"
20#include "llvm/ADT/ScopeExit.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/SaveAndRestore.h"
25using namespace ImportVerilog;
30 if (svint.hasUnknown()) {
31 unsigned numWords = svint.getNumWords() / 2;
32 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), numWords);
33 auto unknown = ArrayRef<uint64_t>(svint.getRawPtr() + numWords, numWords);
34 return FVInt(APInt(svint.getBitWidth(), value),
35 APInt(svint.getBitWidth(), unknown));
37 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), svint.getNumWords());
38 return FVInt(APInt(svint.getBitWidth(), value));
43static Value
getIsUnknown(OpBuilder &builder, Location loc, Value value,
44 moore::IntType valTy, MLIRContext *ctx) {
46 if (valTy.getWidth() > 1) {
47 auto mooreI1Type = moore::IntType::get(ctx, 1, valTy.getDomain());
48 bitVal = moore::ReduceXorOp::create(builder, loc, mooreI1Type, value);
50 auto xType = moore::IntType::get(ctx, 1, moore::Domain::FourValued);
53 return moore::CaseEqOp::create(builder, loc, bitVal, xConst).getResult();
59 moore::IntType valTy) {
60 if (valTy.getDomain() == moore::Domain::FourValued)
61 value = builder.createOrFold<moore::LogicToIntOp>(loc, value);
62 return builder.createOrFold<moore::ToBuiltinIntOp>(loc, value);
66 const slang::ConstantRange &range) {
67 auto &builder =
context.builder;
68 auto indexType = cast<moore::UnpackedType>(index.getType());
71 auto lo = range.lower();
72 auto hi = range.upper();
73 auto offset = range.isDescending() ? lo : hi;
76 const bool needSigned = (lo < 0) || (hi < 0);
79 const uint64_t maxAbs = std::max<uint64_t>(std::abs(lo), std::abs(hi));
84 unsigned want = needSigned
85 ? (llvm::Log2_64_Ceil(std::max<uint64_t>(1, maxAbs)) + 1)
86 : std::max<unsigned>(1, llvm::Log2_64_Ceil(maxAbs + 1));
89 const unsigned bw = std::max<unsigned>(want, indexType.getBitSize().value());
92 moore::IntType::get(index.getContext(), bw, indexType.getDomain());
93 index =
context.materializeConversion(intType, index, needSigned, loc);
96 if (range.isDescending())
99 return moore::NegOp::create(builder, loc, index);
103 moore::ConstantOp::create(builder, loc, intType, offset, needSigned);
104 if (range.isDescending())
105 return moore::SubOp::create(builder, loc, index, offsetConst);
107 return moore::SubOp::create(builder, loc, offsetConst, index);
112 static_assert(int(slang::TimeUnit::Seconds) == 0);
113 static_assert(int(slang::TimeUnit::Milliseconds) == 1);
114 static_assert(int(slang::TimeUnit::Microseconds) == 2);
115 static_assert(int(slang::TimeUnit::Nanoseconds) == 3);
116 static_assert(int(slang::TimeUnit::Picoseconds) == 4);
117 static_assert(int(slang::TimeUnit::Femtoseconds) == 5);
119 static_assert(int(slang::TimeScaleMagnitude::One) == 1);
120 static_assert(int(slang::TimeScaleMagnitude::Ten) == 10);
121 static_assert(int(slang::TimeScaleMagnitude::Hundred) == 100);
123 auto exp =
static_cast<unsigned>(
context.timeScale.base.unit);
126 auto scale =
static_cast<uint64_t
>(
context.timeScale.base.magnitude);
135 Context &
context,
const slang::ast::HierarchicalValueExpression &expr) {
136 auto nameAttr =
context.builder.getStringAttr(expr.symbol.name);
137 for (
const auto &element : expr.ref.path) {
138 auto *inst = element.symbol->as_if<slang::ast::InstanceSymbol>();
141 auto *lowering =
context.interfaceInstances.lookup(inst);
144 if (
auto it = lowering->expandedMembers.find(&expr.symbol);
145 it != lowering->expandedMembers.end())
147 if (
auto it = lowering->expandedMembersByName.find(nameAttr);
148 it != lowering->expandedMembersByName.end())
155 const slang::ast::ClassPropertySymbol &expr) {
156 auto loc =
context.convertLocation(expr.location);
157 auto builder =
context.builder;
158 auto type =
context.convertType(expr.getType());
159 auto fieldTy = cast<moore::UnpackedType>(type);
160 auto fieldRefTy = moore::RefType::get(fieldTy);
162 if (expr.lifetime == slang::ast::VariableLifetime::Static) {
165 if (!
context.globalVariables.lookup(&expr)) {
166 if (failed(
context.convertGlobalVariable(expr))) {
171 if (
auto globalOp =
context.globalVariables.lookup(&expr))
172 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
174 mlir::emitError(loc) <<
"Failed to access static member variable "
175 << expr.name <<
" as a global variable";
180 mlir::Value instRef =
context.getImplicitThisRef();
182 mlir::emitError(loc) <<
"class property '" << expr.name
183 <<
"' referenced without an implicit 'this'";
187 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(), expr.name);
189 moore::ClassHandleType classTy =
190 cast<moore::ClassHandleType>(instRef.getType());
192 auto targetClassHandle =
193 context.getAncestorClassWithProperty(classTy, expr.name, loc);
194 if (!targetClassHandle)
197 auto upcastRef =
context.materializeConversion(targetClassHandle, instRef,
198 false, instRef.getLoc());
202 Value fieldRef = moore::ClassPropertyRefOp::create(builder, loc, fieldRefTy,
203 upcastRef, fieldSym);
221template <
typename RangeT>
223 assert(type.hasFixedRange());
224 const slang::ConstantRange &cstRange = type.getFixedRange();
225 if (cstRange.left < cstRange.right)
226 std::reverse(std::begin(range), std::end(range));
237 ExprVisitor(
Context &context, Location loc,
bool isLvalue)
238 : context(context), loc(loc), builder(context.builder),
239 isLvalue(isLvalue) {}
245 Value convertLvalueOrRvalueExpression(
const slang::ast::Expression &expr) {
253 Value materializeSymbolRvalue(
const slang::ast::ValueSymbol &sym) {
255 if (isa<moore::RefType>(value.getType())) {
256 auto readOp = moore::ReadOp::create(builder, loc, value);
259 return readOp.getResult();
265 auto ref = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
266 auto readOp = moore::ReadOp::create(builder, loc, ref);
269 return readOp.getResult();
272 if (
auto *
const property = sym.as_if<slang::ast::ClassPropertySymbol>()) {
274 auto readOp = moore::ReadOp::create(builder, loc, fieldRef);
277 return readOp.getResult();
283 Value visit(
const slang::ast::NewArrayExpression &expr) {
288 if (expr.initExpr()) {
290 <<
"unsupported expression: array `new` with initializer\n";
295 expr.sizeExpr(), context.
convertType(*expr.sizeExpr().type));
299 return moore::OpenUArrayCreateOp::create(builder, loc, type, initialSize);
303 Value visit(
const slang::ast::ElementSelectExpression &expr) {
305 auto value = convertLvalueOrRvalueExpression(expr.value());
310 auto derefType = value.getType();
312 derefType = cast<moore::RefType>(derefType).getNestedType();
314 if (!isa<moore::IntType, moore::ArrayType, moore::UnpackedArrayType,
315 moore::QueueType, moore::AssocArrayType, moore::StringType,
316 moore::OpenUnpackedArrayType, moore::StructType, moore::UnionType>(
318 mlir::emitError(loc) <<
"unsupported expression: element select into "
319 << expr.value().type->toString() <<
"\n";
323 if (!isLvalue && isa<moore::StructType, moore::UnionType>(derefType)) {
327 derefType = value.getType();
331 if (isa<moore::AssocArrayType>(derefType)) {
332 auto assocArray = cast<moore::AssocArrayType>(derefType);
333 auto expectedIndexType = assocArray.getIndexType();
339 if (givenIndex.getType() != expectedIndexType) {
341 <<
"Incorrect index type: expected index type of "
342 << expectedIndexType <<
" but was given " << givenIndex.getType();
346 return moore::AssocArrayExtractRefOp::create(
347 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
350 return moore::AssocArrayExtractOp::create(builder, loc, type, value,
355 if (isa<moore::StringType>(derefType)) {
357 mlir::emitError(loc) <<
"string index assignment not supported";
362 auto i32Type = moore::IntType::getInt(builder.getContext(), 32);
368 return moore::StringGetOp::create(builder, loc, value, index);
372 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
373 auto range = expr.value().type->getFixedRange();
374 if (
auto *constValue = expr.selector().getConstant();
375 constValue && constValue->isInteger()) {
376 assert(!constValue->hasUnknown());
377 assert(constValue->size() <= 32);
379 auto lowBit = constValue->integer().as<uint32_t>().value();
381 return llvm::TypeSwitch<Type, Value>(derefType)
382 .Case<moore::QueueType>([&](moore::QueueType) {
384 <<
"Unexpected LValue extract on Queue Type!";
388 return moore::ExtractRefOp::create(builder, loc, resultType,
390 range.translateIndex(lowBit));
393 return llvm::TypeSwitch<Type, Value>(derefType)
394 .Case<moore::QueueType>([&](moore::QueueType) {
396 <<
"Unexpected RValue extract on Queue Type!";
400 return moore::ExtractOp::create(builder, loc, resultType, value,
401 range.translateIndex(lowBit));
408 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
409 if (isa<moore::QueueType>(derefType)) {
412 if (isa<moore::RefType>(value.getType())) {
413 context.
currentQueue = moore::ReadOp::create(builder, loc, value);
424 return llvm::TypeSwitch<Type, Value>(derefType)
425 .Case<moore::QueueType>([&](moore::QueueType) {
426 return moore::DynQueueRefElementOp::create(builder, loc, resultType,
430 return moore::DynExtractRefOp::create(builder, loc, resultType,
435 return llvm::TypeSwitch<Type, Value>(derefType)
436 .Case<moore::QueueType>([&](moore::QueueType) {
437 return moore::DynQueueExtractOp::create(builder, loc, resultType,
438 value, lowBit, lowBit);
441 return moore::DynExtractOp::create(builder, loc, resultType, value,
448 Value visit(
const slang::ast::NullLiteral &expr) {
450 if (isa<moore::ClassHandleType, moore::ChandleType, moore::EventType,
451 moore::NullType>(type))
452 return moore::NullOp::create(builder, loc);
453 mlir::emitError(loc) <<
"No null value definition found for value of type "
459 Value visit(
const slang::ast::RangeSelectExpression &expr) {
461 auto value = convertLvalueOrRvalueExpression(expr.value());
465 auto derefType = value.getType();
467 derefType = cast<moore::RefType>(derefType).getNestedType();
469 if (isa<moore::QueueType>(derefType)) {
470 return handleQueueRangeSelectExpressions(expr, type, value);
472 if (!isLvalue && isa<moore::StructType, moore::UnionType>(derefType)) {
478 return handleArrayRangeSelectExpressions(expr, type, value);
483 Value handleQueueRangeSelectExpressions(
484 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
486 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
492 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
495 mlir::emitError(loc) <<
"queue lvalue range selections are not supported";
498 return moore::DynQueueExtractOp::create(builder, loc, resultType, value,
504 Value handleArrayRangeSelectExpressions(
505 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
506 std::optional<int32_t> constLeft;
507 std::optional<int32_t> constRight;
508 if (
auto *constant = expr.left().getConstant())
509 constLeft = constant->integer().as<int32_t>();
510 if (
auto *constant = expr.right().getConstant())
511 constRight = constant->integer().as<int32_t>();
517 <<
"unsupported expression: range select with non-constant bounds";
537 int32_t offsetConst = 0;
538 auto range = expr.value().type->getFixedRange();
540 using slang::ast::RangeSelectionKind;
541 if (expr.getSelectionKind() == RangeSelectionKind::Simple) {
546 assert(constRight &&
"constness checked in slang");
547 offsetConst = *constRight;
558 offsetConst = *constLeft;
569 int32_t offsetAdd = 0;
574 if (expr.getSelectionKind() == RangeSelectionKind::IndexedDown &&
575 range.isDescending()) {
576 assert(constRight &&
"constness checked in slang");
577 offsetAdd = 1 - *constRight;
583 if (expr.getSelectionKind() == RangeSelectionKind::IndexedUp &&
584 !range.isDescending()) {
585 assert(constRight &&
"constness checked in slang");
586 offsetAdd = *constRight - 1;
590 if (offsetAdd != 0) {
592 offsetDyn = moore::AddOp::create(
593 builder, loc, offsetDyn,
594 moore::ConstantOp::create(
595 builder, loc, cast<moore::IntType>(offsetDyn.getType()),
599 offsetConst += offsetAdd;
610 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
615 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
618 return moore::DynExtractOp::create(builder, loc, resultType, value,
622 offsetConst = range.translateIndex(offsetConst);
624 return moore::ExtractRefOp::create(builder, loc, resultType, value,
627 return moore::ExtractOp::create(builder, loc, resultType, value,
634 Value visit(
const slang::ast::ConcatenationExpression &expr) {
635 SmallVector<Value> operands;
636 if (expr.type->isString()) {
637 for (
auto *operand : expr.operands()) {
638 assert(!isLvalue &&
"checked by Slang");
639 auto value = convertLvalueOrRvalueExpression(*operand);
643 moore::StringType::get(context.
getContext()), value,
false,
647 operands.push_back(value);
649 return moore::StringConcatOp::create(builder, loc, operands);
651 if (expr.type->isQueue()) {
652 return handleQueueConcat(expr);
655 if (expr.type->isUnpackedArray()) {
656 assert(!isLvalue &&
"checked by Slang");
657 auto loweredType = context.
convertType(*expr.type, loc);
662 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(loweredType))
664 else if (
auto openType =
665 dyn_cast<moore::OpenUnpackedArrayType>(loweredType))
670 SmallVector<Value> operands;
671 for (
auto *operand : expr.operands()) {
672 if (operand->type->isVoid())
677 operands.push_back(value);
680 auto arrayType = moore::UnpackedArrayType::get(
682 return moore::ArrayCreateOp::create(builder, loc, arrayType, operands);
685 for (
auto *operand : expr.operands()) {
689 if (operand->type->isVoid())
691 auto value = convertLvalueOrRvalueExpression(*operand);
698 operands.push_back(value);
701 return moore::ConcatRefOp::create(builder, loc, operands);
703 return moore::ConcatOp::create(builder, loc, operands);
710 Value handleQueueConcat(
const slang::ast::ConcatenationExpression &expr) {
711 SmallVector<Value> operands;
714 cast<moore::QueueType>(context.
convertType(*expr.type, loc));
726 Value contigElements;
728 for (
auto *operand : expr.operands()) {
729 bool isSingleElement =
734 if (!isSingleElement && contigElements) {
735 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
739 assert(!isLvalue &&
"checked by Slang");
740 auto value = convertLvalueOrRvalueExpression(*operand);
748 moore::RefType::get(context.
getContext(), queueType);
750 if (!contigElements) {
752 moore::VariableOp::create(builder, loc, queueRefType, {}, {});
754 moore::QueuePushBackOp::create(builder, loc, contigElements, value);
762 if (!(isa<moore::QueueType>(value.getType()) &&
763 cast<moore::QueueType>(value.getType()).getElementType() ==
769 operands.push_back(value);
772 if (contigElements) {
773 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
776 return moore::QueueConcatOp::create(builder, loc, queueType, operands);
780 Value visit(
const slang::ast::MemberAccessExpression &expr) {
785 auto *valueType = expr.value().type.get();
786 auto memberName = builder.getStringAttr(expr.member.name);
792 if (valueType->isVirtualInterface()) {
793 auto memberType = dyn_cast<moore::UnpackedType>(type);
796 <<
"unsupported virtual interface member type: " << type;
799 auto resultRefType = moore::RefType::get(memberType);
807 auto memberRef = moore::StructExtractOp::create(
808 builder, loc, resultRefType, memberName, base);
811 return moore::ReadOp::create(builder, loc, memberRef);
815 if (valueType->isStruct()) {
817 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
819 auto value = convertLvalueOrRvalueExpression(expr.value());
824 return moore::StructExtractRefOp::create(builder, loc, resultType,
826 return moore::StructExtractOp::create(builder, loc, resultType,
831 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
833 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
835 auto value = convertLvalueOrRvalueExpression(expr.value());
840 return moore::UnionExtractRefOp::create(builder, loc, resultType,
842 return moore::UnionExtractOp::create(builder, loc, type, memberName,
847 if (valueType->isClass()) {
851 auto targetTy = cast<moore::ClassHandleType>(valTy);
863 if (expr.member.kind != slang::ast::SymbolKind::Parameter) {
869 moore::ClassHandleType upcastTargetTy =
883 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(),
885 auto fieldRefTy = moore::RefType::get(cast<moore::UnpackedType>(type));
889 Value fieldRef = moore::ClassPropertyRefOp::create(
890 builder, loc, fieldRefTy, baseVal, fieldSym);
893 return isLvalue ? fieldRef
894 : moore::ReadOp::create(builder, loc, fieldRef);
897 slang::ConstantValue constVal;
898 if (
auto param = expr.member.as_if<slang::ast::ParameterSymbol>()) {
899 constVal = param->getValue();
904 mlir::emitError(loc) <<
"Parameter " << expr.member.name
905 <<
" has no constant value";
909 mlir::emitError(loc,
"expression of type ")
910 << valueType->toString() <<
" has no member fields";
922struct RvalueExprVisitor :
public ExprVisitor {
924 : ExprVisitor(
context, loc, false) {}
925 using ExprVisitor::visit;
928 Value visit(
const slang::ast::LValueReferenceExpression &expr) {
929 assert(!
context.lvalueStack.empty() &&
"parent assignments push lvalue");
930 auto lvalue =
context.lvalueStack.back();
931 return moore::ReadOp::create(builder, loc, lvalue);
935 Value visit(
const slang::ast::NamedValueExpression &expr) {
937 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
938 if (isa<moore::RefType>(value.getType())) {
939 auto readOp = moore::ReadOp::create(builder, loc, value);
940 if (
context.rvalueReadCallback)
941 context.rvalueReadCallback(readOp);
942 value = readOp.getResult();
948 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol)) {
949 auto value = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
950 return moore::ReadOp::create(builder, loc, value);
954 if (
auto *
const property =
955 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
957 return moore::ReadOp::create(builder, loc, fieldRef).getResult();
964 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
966 auto type =
context.convertType(*expr.type);
969 auto memberType = dyn_cast<moore::UnpackedType>(type);
972 <<
"unsupported virtual interface member type: " << type;
976 Value base = materializeSymbolRvalue(*access.base);
978 auto d = mlir::emitError(loc,
"unknown name `")
979 << access.base->name <<
"`";
980 d.attachNote(
context.convertLocation(access.base->location))
981 <<
"no rvalue generated for virtual interface base";
985 auto fieldName = access.fieldName
987 : builder.getStringAttr(expr.symbol.name);
988 auto memberRefType = moore::RefType::get(memberType);
989 auto memberRef = moore::StructExtractOp::create(
990 builder, loc, memberRefType, fieldName, base);
991 auto readOp = moore::ReadOp::create(builder, loc, memberRef);
992 if (
context.rvalueReadCallback)
993 context.rvalueReadCallback(readOp);
994 return readOp.getResult();
998 auto constant =
context.evaluateConstant(expr);
999 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1004 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
1005 d.attachNote(
context.convertLocation(expr.symbol.location))
1006 <<
"no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
1011 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
1012 auto hierLoc =
context.convertLocation(expr.symbol.location);
1018 if (!expr.ref.path.empty()) {
1019 if (
auto *inst = expr.ref.path.front()
1020 .symbol->as_if<slang::ast::InstanceSymbol>()) {
1022 expr.symbol.getParentScope()->getContainingInstance();
1023 if (&inst->body == symbolBody ||
1024 (symbolBody && inst->body.getDeclaringDefinition() ==
1025 symbolBody->getDeclaringDefinition())) {
1026 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
1027 if (isa<moore::RefType>(value.getType())) {
1028 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1029 if (
context.rvalueReadCallback)
1030 context.rvalueReadCallback(readOp);
1031 value = readOp.getResult();
1041 if (
auto value =
context.resolveCapturedValue(expr.symbol)) {
1042 if (isa<moore::RefType>(value.getType())) {
1043 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1044 if (
context.rvalueReadCallback)
1045 context.rvalueReadCallback(readOp);
1046 value = readOp.getResult();
1055 if (
auto key =
context.buildHierValueKey(expr)) {
1056 if (
auto it =
context.hierValueSymbols.find(*key);
1057 it !=
context.hierValueSymbols.end()) {
1058 auto value = it->second;
1059 if (isa<moore::RefType>(value.getType())) {
1060 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1061 if (
context.rvalueReadCallback)
1062 context.rvalueReadCallback(readOp);
1063 value = readOp.getResult();
1070 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
1071 if (isa<moore::RefType>(value.getType())) {
1072 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1073 if (
context.rvalueReadCallback)
1074 context.rvalueReadCallback(readOp);
1075 value = readOp.getResult();
1081 if (isa<moore::RefType>(value.getType())) {
1082 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1083 if (
context.rvalueReadCallback)
1084 context.rvalueReadCallback(readOp);
1085 return readOp.getResult();
1093 slang::ConstantValue constant;
1094 switch (expr.symbol.kind) {
1095 case slang::ast::SymbolKind::Parameter:
1096 constant = expr.symbol.as<slang::ast::ParameterSymbol>().getValue(
1099 case slang::ast::SymbolKind::Specparam:
1100 constant = expr.symbol.as<slang::ast::SpecparamSymbol>().getValue(
1103 case slang::ast::SymbolKind::EnumValue:
1104 constant = expr.symbol.as<slang::ast::EnumValueSymbol>().getValue(
1108 constant =
context.evaluateConstant(expr);
1111 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1116 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
1117 << expr.symbol.name <<
"`";
1118 d.attachNote(hierLoc) <<
"no rvalue generated for "
1119 << slang::ast::toString(expr.symbol.kind);
1125 Value visit(
const slang::ast::ArbitrarySymbolExpression &expr) {
1126 const auto &canonTy = expr.type->getCanonicalType();
1127 if (
const auto *vi = canonTy.as_if<slang::ast::VirtualInterfaceType>()) {
1128 auto value =
context.materializeVirtualInterfaceValue(*vi, loc);
1134 mlir::emitError(loc) <<
"unsupported arbitrary symbol expression of type "
1135 << expr.type->toString();
1140 Value visit(
const slang::ast::ConversionExpression &expr) {
1141 auto type =
context.convertType(*expr.type);
1144 return context.convertRvalueExpression(expr.operand(), type);
1148 Value visit(
const slang::ast::AssignmentExpression &expr) {
1149 auto lhs =
context.convertLvalueExpression(expr.left());
1154 context.lvalueStack.push_back(lhs);
1155 auto rhs =
context.convertRvalueExpression(
1156 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
1157 context.lvalueStack.pop_back();
1164 if (!expr.isNonBlocking()) {
1165 if (expr.timingControl)
1166 if (failed(
context.convertTimingControl(*expr.timingControl)))
1168 auto assignOp = moore::BlockingAssignOp::create(builder, loc, lhs, rhs);
1169 if (
context.variableAssignCallback)
1170 context.variableAssignCallback(assignOp);
1175 if (expr.timingControl) {
1177 if (
auto *ctrl = expr.timingControl->as_if<slang::ast::DelayControl>()) {
1178 auto delay =
context.convertRvalueExpression(
1179 ctrl->expr, moore::TimeType::get(builder.getContext()));
1182 auto assignOp = moore::DelayedNonBlockingAssignOp::create(
1183 builder, loc, lhs, rhs, delay);
1184 if (
context.variableAssignCallback)
1185 context.variableAssignCallback(assignOp);
1190 auto loc =
context.convertLocation(expr.timingControl->sourceRange);
1191 mlir::emitError(loc)
1192 <<
"unsupported non-blocking assignment timing control: "
1193 << slang::ast::toString(expr.timingControl->kind);
1196 auto assignOp = moore::NonBlockingAssignOp::create(builder, loc, lhs, rhs);
1197 if (
context.variableAssignCallback)
1198 context.variableAssignCallback(assignOp);
1204 template <
class ConcreteOp>
1205 Value createReduction(Value arg,
bool invert) {
1206 arg =
context.convertToSimpleBitVector(arg);
1209 Value result = ConcreteOp::create(builder, loc, arg);
1211 result = moore::NotOp::create(builder, loc, result);
1216 Value createIncrement(Value arg,
bool isInc,
bool isPost) {
1217 auto preValue = moore::ReadOp::create(builder, loc, arg);
1223 postValue = moore::NotOp::create(builder, loc, preValue).getResult();
1226 auto one = moore::ConstantOp::create(
1227 builder, loc, cast<moore::IntType>(preValue.getType()), 1);
1229 isInc ? moore::AddOp::create(builder, loc, preValue, one).getResult()
1230 : moore::SubOp::create(builder, loc, preValue, one).getResult();
1232 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1233 if (
context.variableAssignCallback)
1234 context.variableAssignCallback(assignOp);
1243 Value createRealIncrement(Value arg,
bool isInc,
bool isPost) {
1244 Value preValue = moore::ReadOp::create(builder, loc, arg);
1247 bool isTime = isa<moore::TimeType>(preValue.getType());
1249 preValue =
context.materializeConversion(
1250 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1251 preValue,
false, loc);
1253 moore::RealType realTy =
1254 llvm::dyn_cast<moore::RealType>(preValue.getType());
1259 if (realTy.getWidth() == moore::RealWidth::f32) {
1260 oneAttr = builder.getFloatAttr(builder.getF32Type(), 1.0);
1261 }
else if (realTy.getWidth() == moore::RealWidth::f64) {
1263 oneAttr = builder.getFloatAttr(builder.getF64Type(), oneVal);
1265 mlir::emitError(loc) <<
"cannot construct increment for " << realTy;
1268 auto one = moore::ConstantRealOp::create(builder, loc, oneAttr);
1272 ? moore::AddRealOp::create(builder, loc, preValue, one).getResult()
1273 : moore::SubRealOp::create(builder, loc, preValue, one).getResult();
1276 postValue =
context.materializeConversion(
1277 moore::TimeType::get(
context.getContext()), postValue,
false, loc);
1280 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1282 if (
context.variableAssignCallback)
1283 context.variableAssignCallback(assignOp);
1290 Value visitRealUOp(
const slang::ast::UnaryExpression &expr) {
1291 Type opFTy =
context.convertType(*expr.operand().type);
1293 using slang::ast::UnaryOperator;
1295 if (expr.op == UnaryOperator::Preincrement ||
1296 expr.op == UnaryOperator::Predecrement ||
1297 expr.op == UnaryOperator::Postincrement ||
1298 expr.op == UnaryOperator::Postdecrement)
1299 arg =
context.convertLvalueExpression(expr.operand());
1301 arg =
context.convertRvalueExpression(expr.operand(), opFTy);
1306 if (isa<moore::TimeType>(arg.getType()))
1307 arg =
context.materializeConversion(
1308 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1313 case UnaryOperator::Plus:
1315 case UnaryOperator::Minus:
1316 return moore::NegRealOp::create(builder, loc, arg);
1318 case UnaryOperator::Preincrement:
1319 return createRealIncrement(arg,
true,
false);
1320 case UnaryOperator::Predecrement:
1321 return createRealIncrement(arg,
false,
false);
1322 case UnaryOperator::Postincrement:
1323 return createRealIncrement(arg,
true,
true);
1324 case UnaryOperator::Postdecrement:
1325 return createRealIncrement(arg,
false,
true);
1327 case UnaryOperator::LogicalNot:
1328 arg =
context.convertToBool(arg);
1331 return moore::NotOp::create(builder, loc, arg);
1334 mlir::emitError(loc) <<
"Unary operator " << slang::ast::toString(expr.op)
1335 <<
" not supported with real values!\n";
1341 Value visit(
const slang::ast::UnaryExpression &expr) {
1343 const auto *floatType =
1344 expr.operand().type->as_if<slang::ast::FloatingType>();
1347 return visitRealUOp(expr);
1349 using slang::ast::UnaryOperator;
1351 if (expr.op == UnaryOperator::Preincrement ||
1352 expr.op == UnaryOperator::Predecrement ||
1353 expr.op == UnaryOperator::Postincrement ||
1354 expr.op == UnaryOperator::Postdecrement)
1355 arg =
context.convertLvalueExpression(expr.operand());
1357 arg =
context.convertRvalueExpression(expr.operand());
1364 case UnaryOperator::Plus:
1365 return context.convertToSimpleBitVector(arg);
1367 case UnaryOperator::Minus:
1368 arg =
context.convertToSimpleBitVector(arg);
1371 return moore::NegOp::create(builder, loc, arg);
1373 case UnaryOperator::BitwiseNot:
1374 arg =
context.convertToSimpleBitVector(arg);
1377 return moore::NotOp::create(builder, loc, arg);
1379 case UnaryOperator::BitwiseAnd:
1380 return createReduction<moore::ReduceAndOp>(arg,
false);
1381 case UnaryOperator::BitwiseOr:
1382 return createReduction<moore::ReduceOrOp>(arg,
false);
1383 case UnaryOperator::BitwiseXor:
1384 return createReduction<moore::ReduceXorOp>(arg,
false);
1385 case UnaryOperator::BitwiseNand:
1386 return createReduction<moore::ReduceAndOp>(arg,
true);
1387 case UnaryOperator::BitwiseNor:
1388 return createReduction<moore::ReduceOrOp>(arg,
true);
1389 case UnaryOperator::BitwiseXnor:
1390 return createReduction<moore::ReduceXorOp>(arg,
true);
1392 case UnaryOperator::LogicalNot:
1393 arg =
context.convertToBool(arg);
1396 return moore::NotOp::create(builder, loc, arg);
1398 case UnaryOperator::Preincrement:
1399 return createIncrement(arg,
true,
false);
1400 case UnaryOperator::Predecrement:
1401 return createIncrement(arg,
false,
false);
1402 case UnaryOperator::Postincrement:
1403 return createIncrement(arg,
true,
true);
1404 case UnaryOperator::Postdecrement:
1405 return createIncrement(arg,
false,
true);
1408 mlir::emitError(loc,
"unsupported unary operator");
1413 Value buildLogicalBOp(slang::ast::BinaryOperator op, Value lhs, Value rhs,
1414 std::optional<Domain> domain = std::nullopt) {
1415 using slang::ast::BinaryOperator;
1419 lhs =
context.convertToBool(lhs, domain.value());
1420 rhs =
context.convertToBool(rhs, domain.value());
1422 lhs =
context.convertToBool(lhs);
1423 rhs =
context.convertToBool(rhs);
1430 case BinaryOperator::LogicalAnd:
1431 return moore::AndOp::create(builder, loc, lhs, rhs);
1433 case BinaryOperator::LogicalOr:
1434 return moore::OrOp::create(builder, loc, lhs, rhs);
1436 case BinaryOperator::LogicalImplication: {
1438 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1439 return moore::OrOp::create(builder, loc, notLHS, rhs);
1442 case BinaryOperator::LogicalEquivalence: {
1444 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1445 auto notRHS = moore::NotOp::create(builder, loc, rhs);
1446 auto both = moore::AndOp::create(builder, loc, lhs, rhs);
1447 auto notBoth = moore::AndOp::create(builder, loc, notLHS, notRHS);
1448 return moore::OrOp::create(builder, loc, both, notBoth);
1452 llvm_unreachable(
"not a logical BinaryOperator");
1456 Value visitHandleBOp(
const slang::ast::BinaryExpression &expr) {
1458 auto lhs =
context.convertRvalueExpression(expr.left());
1461 auto rhs =
context.convertRvalueExpression(expr.right());
1465 using slang::ast::BinaryOperator;
1468 case BinaryOperator::Equality:
1469 return moore::HandleEqOp::create(builder, loc, lhs, rhs);
1470 case BinaryOperator::Inequality:
1471 return moore::HandleNeOp::create(builder, loc, lhs, rhs);
1472 case BinaryOperator::CaseEquality:
1473 return moore::HandleCaseEqOp::create(builder, loc, lhs, rhs);
1474 case BinaryOperator::CaseInequality:
1475 return moore::HandleCaseNeOp::create(builder, loc, lhs, rhs);
1478 mlir::emitError(loc)
1479 <<
"Binary operator " << slang::ast::toString(expr.op)
1480 <<
" not supported with class handle valued operands!\n";
1485 Value visitRealBOp(
const slang::ast::BinaryExpression &expr) {
1487 auto lhs =
context.convertRvalueExpression(expr.left());
1490 auto rhs =
context.convertRvalueExpression(expr.right());
1494 if (isa<moore::TimeType>(lhs.getType()) ||
1495 isa<moore::TimeType>(rhs.getType())) {
1496 lhs =
context.materializeConversion(
1497 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1499 rhs =
context.materializeConversion(
1500 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1504 using slang::ast::BinaryOperator;
1506 case BinaryOperator::Add:
1507 return moore::AddRealOp::create(builder, loc, lhs, rhs);
1508 case BinaryOperator::Subtract:
1509 return moore::SubRealOp::create(builder, loc, lhs, rhs);
1510 case BinaryOperator::Multiply:
1511 return moore::MulRealOp::create(builder, loc, lhs, rhs);
1512 case BinaryOperator::Divide:
1513 return moore::DivRealOp::create(builder, loc, lhs, rhs);
1514 case BinaryOperator::Power:
1515 return moore::PowRealOp::create(builder, loc, lhs, rhs);
1517 case BinaryOperator::Equality:
1518 return moore::EqRealOp::create(builder, loc, lhs, rhs);
1519 case BinaryOperator::Inequality:
1520 return moore::NeRealOp::create(builder, loc, lhs, rhs);
1522 case BinaryOperator::GreaterThan:
1523 return moore::FgtOp::create(builder, loc, lhs, rhs);
1524 case BinaryOperator::LessThan:
1525 return moore::FltOp::create(builder, loc, lhs, rhs);
1526 case BinaryOperator::GreaterThanEqual:
1527 return moore::FgeOp::create(builder, loc, lhs, rhs);
1528 case BinaryOperator::LessThanEqual:
1529 return moore::FleOp::create(builder, loc, lhs, rhs);
1531 case BinaryOperator::LogicalAnd:
1532 case BinaryOperator::LogicalOr:
1533 case BinaryOperator::LogicalImplication:
1534 case BinaryOperator::LogicalEquivalence: {
1535 Domain domain = Domain::TwoValued;
1536 if (expr.left().type->isFourState() || expr.right().type->isFourState())
1537 domain = Domain::FourValued;
1538 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1542 mlir::emitError(loc) <<
"Binary operator "
1543 << slang::ast::toString(expr.op)
1544 <<
" not supported with real valued operands!\n";
1551 template <
class ConcreteOp>
1552 Value createBinary(Value lhs, Value rhs) {
1553 lhs =
context.convertToSimpleBitVector(lhs);
1556 rhs =
context.convertToSimpleBitVector(rhs);
1559 return ConcreteOp::create(builder, loc, lhs, rhs);
1563 Value visit(
const slang::ast::BinaryExpression &expr) {
1564 if (expr.left().kind == slang::ast::ExpressionKind::TypeReference &&
1565 expr.right().kind == slang::ast::ExpressionKind::TypeReference) {
1567 expr.left().as<slang::ast::TypeReferenceExpression>().targetType;
1569 expr.right().as<slang::ast::TypeReferenceExpression>().targetType;
1570 bool value = lhsType.isMatching(rhsType);
1572 using slang::ast::BinaryOperator;
1574 case BinaryOperator::Equality:
1575 case BinaryOperator::CaseEquality:
1577 case BinaryOperator::Inequality:
1578 case BinaryOperator::CaseInequality:
1582 mlir::emitError(loc,
"unsupported type reference binary operator");
1586 auto type = moore::IntType::get(
context.getContext(), 1,
1587 moore::Domain::TwoValued);
1588 return moore::ConstantOp::create(builder, loc, type, value,
1593 const auto *rhsFloatType =
1594 expr.right().type->as_if<slang::ast::FloatingType>();
1595 const auto *lhsFloatType =
1596 expr.left().type->as_if<slang::ast::FloatingType>();
1599 if (rhsFloatType || lhsFloatType)
1600 return visitRealBOp(expr);
1603 const auto rhsIsClass = expr.right().type->isClass();
1604 const auto lhsIsClass = expr.left().type->isClass();
1605 const auto rhsIsChandle = expr.right().type->isCHandle();
1606 const auto lhsIsChandle = expr.left().type->isCHandle();
1608 if (rhsIsClass || lhsIsClass || rhsIsChandle || lhsIsChandle)
1609 return visitHandleBOp(expr);
1611 auto lhs =
context.convertRvalueExpression(expr.left());
1614 auto rhs =
context.convertRvalueExpression(expr.right());
1619 Domain domain = Domain::TwoValued;
1620 if (expr.type->isFourState() || expr.left().type->isFourState() ||
1621 expr.right().type->isFourState())
1622 domain = Domain::FourValued;
1624 using slang::ast::BinaryOperator;
1626 case BinaryOperator::Add:
1627 return createBinary<moore::AddOp>(lhs, rhs);
1628 case BinaryOperator::Subtract:
1629 return createBinary<moore::SubOp>(lhs, rhs);
1630 case BinaryOperator::Multiply:
1631 return createBinary<moore::MulOp>(lhs, rhs);
1632 case BinaryOperator::Divide:
1633 if (expr.type->isSigned())
1634 return createBinary<moore::DivSOp>(lhs, rhs);
1636 return createBinary<moore::DivUOp>(lhs, rhs);
1637 case BinaryOperator::Mod:
1638 if (expr.type->isSigned())
1639 return createBinary<moore::ModSOp>(lhs, rhs);
1641 return createBinary<moore::ModUOp>(lhs, rhs);
1642 case BinaryOperator::Power: {
1647 auto rhsCast =
context.materializeConversion(
1648 lhs.getType(), rhs, expr.right().type->isSigned(), rhs.getLoc());
1649 if (expr.type->isSigned())
1650 return createBinary<moore::PowSOp>(lhs, rhsCast);
1652 return createBinary<moore::PowUOp>(lhs, rhsCast);
1655 case BinaryOperator::BinaryAnd:
1656 return createBinary<moore::AndOp>(lhs, rhs);
1657 case BinaryOperator::BinaryOr:
1658 return createBinary<moore::OrOp>(lhs, rhs);
1659 case BinaryOperator::BinaryXor:
1660 return createBinary<moore::XorOp>(lhs, rhs);
1661 case BinaryOperator::BinaryXnor: {
1662 auto result = createBinary<moore::XorOp>(lhs, rhs);
1665 return moore::NotOp::create(builder, loc, result);
1668 case BinaryOperator::Equality:
1669 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1670 return moore::UArrayCmpOp::create(
1671 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1672 else if (isa<moore::StringType>(lhs.getType()))
1673 return moore::StringCmpOp::create(
1674 builder, loc, moore::StringCmpPredicate::eq, lhs, rhs);
1675 else if (isa<moore::QueueType>(lhs.getType()))
1676 return moore::QueueCmpOp::create(
1677 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1679 return createBinary<moore::EqOp>(lhs, rhs);
1680 case BinaryOperator::Inequality:
1681 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1682 return moore::UArrayCmpOp::create(
1683 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1684 else if (isa<moore::StringType>(lhs.getType()))
1685 return moore::StringCmpOp::create(
1686 builder, loc, moore::StringCmpPredicate::ne, lhs, rhs);
1687 else if (isa<moore::QueueType>(lhs.getType()))
1688 return moore::QueueCmpOp::create(
1689 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1691 return createBinary<moore::NeOp>(lhs, rhs);
1692 case BinaryOperator::CaseEquality:
1693 return createBinary<moore::CaseEqOp>(lhs, rhs);
1694 case BinaryOperator::CaseInequality:
1695 return createBinary<moore::CaseNeOp>(lhs, rhs);
1696 case BinaryOperator::WildcardEquality:
1697 return createBinary<moore::WildcardEqOp>(lhs, rhs);
1698 case BinaryOperator::WildcardInequality:
1699 return createBinary<moore::WildcardNeOp>(lhs, rhs);
1701 case BinaryOperator::GreaterThanEqual:
1702 if (expr.left().type->isSigned())
1703 return createBinary<moore::SgeOp>(lhs, rhs);
1704 else if (isa<moore::StringType>(lhs.getType()))
1705 return moore::StringCmpOp::create(
1706 builder, loc, moore::StringCmpPredicate::ge, lhs, rhs);
1708 return createBinary<moore::UgeOp>(lhs, rhs);
1709 case BinaryOperator::GreaterThan:
1710 if (expr.left().type->isSigned())
1711 return createBinary<moore::SgtOp>(lhs, rhs);
1712 else if (isa<moore::StringType>(lhs.getType()))
1713 return moore::StringCmpOp::create(
1714 builder, loc, moore::StringCmpPredicate::gt, lhs, rhs);
1716 return createBinary<moore::UgtOp>(lhs, rhs);
1717 case BinaryOperator::LessThanEqual:
1718 if (expr.left().type->isSigned())
1719 return createBinary<moore::SleOp>(lhs, rhs);
1720 else if (isa<moore::StringType>(lhs.getType()))
1721 return moore::StringCmpOp::create(
1722 builder, loc, moore::StringCmpPredicate::le, lhs, rhs);
1724 return createBinary<moore::UleOp>(lhs, rhs);
1725 case BinaryOperator::LessThan:
1726 if (expr.left().type->isSigned())
1727 return createBinary<moore::SltOp>(lhs, rhs);
1728 else if (isa<moore::StringType>(lhs.getType()))
1729 return moore::StringCmpOp::create(
1730 builder, loc, moore::StringCmpPredicate::lt, lhs, rhs);
1732 return createBinary<moore::UltOp>(lhs, rhs);
1734 case BinaryOperator::LogicalAnd:
1735 case BinaryOperator::LogicalOr:
1736 case BinaryOperator::LogicalImplication:
1737 case BinaryOperator::LogicalEquivalence:
1738 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1740 case BinaryOperator::LogicalShiftLeft:
1741 return createBinary<moore::ShlOp>(lhs, rhs);
1742 case BinaryOperator::LogicalShiftRight:
1743 return createBinary<moore::ShrOp>(lhs, rhs);
1744 case BinaryOperator::ArithmeticShiftLeft:
1745 return createBinary<moore::ShlOp>(lhs, rhs);
1746 case BinaryOperator::ArithmeticShiftRight: {
1749 lhs =
context.convertToSimpleBitVector(lhs);
1750 rhs =
context.convertToSimpleBitVector(rhs);
1753 if (expr.type->isSigned())
1754 return moore::AShrOp::create(builder, loc, lhs, rhs);
1755 return moore::ShrOp::create(builder, loc, lhs, rhs);
1759 mlir::emitError(loc,
"unsupported binary operator");
1764 Value visit(
const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
1765 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1769 Value visit(
const slang::ast::IntegerLiteral &expr) {
1770 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1774 Value visit(
const slang::ast::TimeLiteral &expr) {
1779 double value = std::round(expr.getValue() * scale);
1789 static constexpr uint64_t limit =
1790 (std::numeric_limits<uint64_t>::max() >> 11) << 11;
1791 if (value > limit) {
1792 mlir::emitError(loc) <<
"time value is larger than " << limit <<
" fs";
1796 return moore::ConstantTimeOp::create(builder, loc,
1797 static_cast<uint64_t
>(value));
1801 Value visit(
const slang::ast::ReplicationExpression &expr) {
1802 auto type =
context.convertType(*expr.type);
1803 auto value =
context.convertRvalueExpression(expr.concat());
1806 return moore::ReplicateOp::create(builder, loc, type, value);
1810 Value visit(
const slang::ast::InsideExpression &expr) {
1811 auto lhs =
context.convertToSimpleBitVector(
1812 context.convertRvalueExpression(expr.left()));
1817 SmallVector<Value> conditions;
1820 for (
const auto *listExpr : expr.rangeList()) {
1821 auto cond =
context.convertInsideCheck(lhs, loc, *listExpr);
1825 conditions.push_back(cond);
1829 auto result = conditions.back();
1830 conditions.pop_back();
1831 while (!conditions.empty()) {
1832 result = moore::OrOp::create(builder, loc, conditions.back(), result);
1833 conditions.pop_back();
1839 Value visit(
const slang::ast::ConditionalExpression &expr) {
1840 auto type =
context.convertType(*expr.type);
1843 if (expr.conditions.size() > 1) {
1844 mlir::emitError(loc)
1845 <<
"unsupported conditional expression with more than one condition";
1848 const auto &cond = expr.conditions[0];
1850 mlir::emitError(loc) <<
"unsupported conditional expression with pattern";
1854 context.convertToBool(
context.convertRvalueExpression(*cond.expr));
1857 auto conditionalOp =
1858 moore::ConditionalOp::create(builder, loc, type, value);
1861 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
1862 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
1864 OpBuilder::InsertionGuard g(builder);
1867 builder.setInsertionPointToStart(&trueBlock);
1868 auto trueValue =
context.convertRvalueExpression(expr.left(), type);
1871 moore::YieldOp::create(builder, loc, trueValue);
1874 builder.setInsertionPointToStart(&falseBlock);
1875 auto falseValue =
context.convertRvalueExpression(expr.right(), type);
1878 moore::YieldOp::create(builder, loc, falseValue);
1880 return conditionalOp.getResult();
1884 Value visit(
const slang::ast::CallExpression &expr) {
1886 auto constant =
context.evaluateConstant(expr);
1887 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1891 [&](
auto &subroutine) {
return visitCall(expr, subroutine); },
1897 std::pair<Value, moore::ClassHandleType>
1898 getMethodReceiverTypeHandle(
const slang::ast::CallExpression &expr) {
1900 moore::ClassHandleType handleTy;
1904 if (
const slang::ast::Expression *recvExpr = expr.thisClass()) {
1905 thisRef =
context.convertRvalueExpression(*recvExpr);
1910 thisRef =
context.getImplicitThisRef();
1912 mlir::emitError(loc) <<
"method '" << expr.getSubroutineName()
1913 <<
"' called without an object";
1917 handleTy = cast<moore::ClassHandleType>(thisRef.getType());
1918 return {thisRef, handleTy};
1922 mlir::CallOpInterface
1923 buildMethodCall(
const slang::ast::SubroutineSymbol *subroutine,
1925 moore::ClassHandleType actualHandleTy, Value actualThisRef,
1926 SmallVector<Value> &arguments,
1927 SmallVector<Type> &resultTypes) {
1930 auto funcTy = cast<FunctionType>(lowering->
op.getFunctionType());
1931 auto expected0 = funcTy.getInput(0);
1932 auto expectedHdlTy = cast<moore::ClassHandleType>(expected0);
1935 auto implicitThisRef =
context.materializeConversion(
1936 expectedHdlTy, actualThisRef,
false, actualThisRef.getLoc());
1939 SmallVector<Value> explicitArguments;
1940 explicitArguments.reserve(arguments.size() + 1);
1941 explicitArguments.push_back(implicitThisRef);
1942 explicitArguments.append(arguments.begin(), arguments.end());
1945 const bool isVirtual =
1946 (subroutine->flags & slang::ast::MethodFlags::Virtual) != 0;
1949 auto calleeSym = lowering->
op.getNameAttr().getValue();
1950 if (isa<moore::CoroutineOp>(lowering->
op.getOperation()))
1951 return moore::CallCoroutineOp::create(builder, loc, resultTypes,
1952 calleeSym, explicitArguments);
1953 return mlir::func::CallOp::create(builder, loc, resultTypes, calleeSym,
1957 auto funcName = subroutine->name;
1958 auto method = moore::VTableLoadMethodOp::create(
1959 builder, loc, funcTy, actualThisRef,
1960 SymbolRefAttr::get(
context.getContext(), funcName));
1961 return mlir::func::CallIndirectOp::create(builder, loc, method,
1966 Value visitCall(
const slang::ast::CallExpression &expr,
1967 const slang::ast::SubroutineSymbol *subroutine) {
1969 const bool isMethod = (subroutine->thisVar !=
nullptr);
1971 auto *lowering =
context.declareFunction(*subroutine);
1975 if (isa<moore::DPIFuncOp>(lowering->
op.getOperation())) {
1976 SmallVector<Value> operands;
1977 SmallVector<Value> resultTargets;
1979 for (
auto [callArg, declArg] :
1980 llvm::zip(expr.arguments(), subroutine->getArguments())) {
1981 auto *actual = callArg;
1982 if (
const auto *assign =
1983 actual->as_if<slang::ast::AssignmentExpression>())
1984 actual = &assign->left();
1986 auto argType =
context.convertType(declArg->getType());
1990 switch (declArg->direction) {
1991 case slang::ast::ArgumentDirection::In: {
1992 auto value =
context.convertRvalueExpression(*actual, argType);
1995 operands.push_back(value);
1998 case slang::ast::ArgumentDirection::Out: {
1999 auto lvalue =
context.convertLvalueExpression(*actual);
2002 resultTargets.push_back(lvalue);
2005 case slang::ast::ArgumentDirection::InOut:
2006 case slang::ast::ArgumentDirection::Ref: {
2007 auto lvalue =
context.convertLvalueExpression(*actual);
2010 auto value =
context.convertRvalueExpression(*actual, argType);
2013 operands.push_back(value);
2014 resultTargets.push_back(lvalue);
2020 SmallVector<Type> resultTypes(
2021 cast<FunctionType>(lowering->
op.getFunctionType()).getResults());
2022 auto callOp = moore::FuncDPICallOp::create(
2023 builder, loc, resultTypes,
2024 SymbolRefAttr::get(lowering->
op.getNameAttr()), operands);
2026 unsigned resultIndex = 0;
2027 unsigned targetIndex = 0;
2028 for (
const auto *declArg : subroutine->getArguments()) {
2029 auto argType =
context.convertType(declArg->getType());
2033 switch (declArg->direction) {
2034 case slang::ast::ArgumentDirection::Out:
2035 case slang::ast::ArgumentDirection::InOut:
2036 case slang::ast::ArgumentDirection::Ref: {
2037 auto lvalue = resultTargets[targetIndex++];
2038 auto refTy = dyn_cast<moore::RefType>(lvalue.getType());
2040 lowering->
op->emitError(
2041 "expected DPI output target to be moore::RefType");
2044 auto converted =
context.materializeConversion(
2045 refTy.getNestedType(), callOp->getResult(resultIndex++),
2046 declArg->getType().isSigned(), loc);
2049 moore::BlockingAssignOp::create(builder, loc, lvalue, converted);
2057 if (!subroutine->getReturnType().isVoid())
2058 return callOp->getResult(resultIndex);
2060 return mlir::UnrealizedConversionCastOp::create(
2061 builder, loc, moore::VoidType::get(
context.getContext()),
2069 SmallVector<Value> arguments;
2070 for (
auto [callArg, declArg] :
2071 llvm::zip(expr.arguments(), subroutine->getArguments())) {
2075 auto *expr = callArg;
2076 if (
const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
2077 expr = &assign->left();
2080 auto type =
context.convertType(declArg->getType());
2081 if (declArg->direction == slang::ast::ArgumentDirection::In) {
2082 value =
context.convertRvalueExpression(*expr, type);
2084 Value lvalue =
context.convertLvalueExpression(*expr);
2085 auto unpackedType = dyn_cast<moore::UnpackedType>(type);
2089 context.materializeConversion(moore::RefType::get(unpackedType),
2090 lvalue, expr->type->isSigned(), loc);
2094 arguments.push_back(value);
2101 for (
auto *sym : lowering->capturedSymbols) {
2102 Value val =
context.valueSymbols.lookup(sym);
2104 mlir::emitError(loc) <<
"failed to resolve captured variable `"
2105 << sym->name <<
"` at call site";
2108 arguments.push_back(val);
2112 SmallVector<Type> resultTypes(
2113 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().begin(),
2114 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().end());
2116 mlir::CallOpInterface callOp;
2120 auto [thisRef, tyHandle] = getMethodReceiverTypeHandle(expr);
2121 callOp = buildMethodCall(subroutine, lowering, tyHandle, thisRef,
2122 arguments, resultTypes);
2123 }
else if (isa<moore::CoroutineOp>(lowering->
op.getOperation())) {
2125 auto coroutine = cast<moore::CoroutineOp>(lowering->
op.getOperation());
2127 moore::CallCoroutineOp::create(builder, loc, coroutine, arguments);
2130 auto funcOp = cast<mlir::func::FuncOp>(lowering->
op.getOperation());
2131 callOp = mlir::func::CallOp::create(builder, loc, funcOp, arguments);
2134 auto result = resultTypes.size() > 0 ? callOp->getOpResult(0) : Value{};
2138 if (resultTypes.size() == 0)
2139 return mlir::UnrealizedConversionCastOp::create(
2140 builder, loc, moore::VoidType::get(
context.getContext()),
2148 Value visitCall(
const slang::ast::CallExpression &expr,
2149 const slang::ast::CallExpression::SystemCallInfo &info) {
2150 using ksn = slang::parsing::KnownSystemName;
2151 const auto &subroutine = *
info.subroutine;
2152 auto nameId = subroutine.knownNameId;
2163 return context.convertSampledValueCallExpression(expr, info, loc);
2168 auto args = expr.arguments();
2176 if (nameId == ksn::SFormatF) {
2178 auto fmtValue =
context.convertFormatString(
2179 expr.arguments(), loc, moore::IntFormat::Decimal,
false);
2180 if (failed(fmtValue))
2182 return fmtValue.value();
2186 auto result =
context.convertSystemCall(subroutine, loc, args);
2190 auto ty =
context.convertType(*expr.type);
2194 bool isSigned = expr.type->isSigned();
2195 if (nameId == ksn::CountOnes || nameId == ksn::IsUnknown ||
2196 nameId == ksn::OneHot || nameId == ksn::OneHot0)
2198 return context.materializeConversion(ty, result, isSigned, loc);
2202 Value visit(
const slang::ast::StringLiteral &expr) {
2203 auto type =
context.convertType(*expr.type);
2204 return moore::ConstantStringOp::create(builder, loc, type, expr.getValue());
2208 Value visit(
const slang::ast::RealLiteral &expr) {
2209 auto fTy = mlir::Float64Type::get(
context.getContext());
2210 auto attr = mlir::FloatAttr::get(fTy, expr.getValue());
2211 return moore::ConstantRealOp::create(builder, loc, attr).getResult();
2216 FailureOr<SmallVector<Value>>
2217 convertElements(
const slang::ast::AssignmentPatternExpressionBase &expr,
2218 std::variant<Type, ArrayRef<Type>> expectedTypes,
2219 unsigned replCount) {
2220 const auto &elts = expr.elements();
2221 const size_t elementCount = elts.size();
2224 const bool hasBroadcast =
2225 std::holds_alternative<Type>(expectedTypes) &&
2226 static_cast<bool>(std::get<Type>(expectedTypes));
2228 const bool hasPerElem =
2229 std::holds_alternative<ArrayRef<Type>>(expectedTypes) &&
2230 !std::get<ArrayRef<Type>>(expectedTypes).empty();
2234 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2235 if (types.size() != elementCount) {
2236 mlir::emitError(loc)
2237 <<
"assignment pattern arity mismatch: expected " << types.size()
2238 <<
" elements, got " << elementCount;
2243 SmallVector<Value> converted;
2244 converted.reserve(elementCount * std::max(1u, replCount));
2247 if (!hasBroadcast && !hasPerElem) {
2249 for (
const auto *elementExpr : elts) {
2250 Value v =
context.convertRvalueExpression(*elementExpr);
2253 converted.push_back(v);
2255 }
else if (hasBroadcast) {
2257 Type want = std::get<Type>(expectedTypes);
2258 for (
const auto *elementExpr : elts) {
2259 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2260 :
context.convertRvalueExpression(*elementExpr);
2263 converted.push_back(v);
2266 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2267 for (
size_t i = 0; i < elementCount; ++i) {
2268 Type want = types[i];
2269 const auto *elementExpr = elts[i];
2270 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2271 :
context.convertRvalueExpression(*elementExpr);
2274 converted.push_back(v);
2278 for (
unsigned i = 1; i < replCount; ++i)
2279 converted.append(converted.begin(), converted.begin() + elementCount);
2285 Value visitAssignmentPattern(
2286 const slang::ast::AssignmentPatternExpressionBase &expr,
2287 unsigned replCount = 1) {
2288 auto type =
context.convertType(*expr.type);
2289 const auto &elts = expr.elements();
2292 if (
auto intType = dyn_cast<moore::IntType>(type)) {
2293 auto elements = convertElements(expr, {}, replCount);
2295 if (failed(elements))
2298 assert(intType.getWidth() == elements->size());
2300 return moore::ConcatOp::create(builder, loc, intType, *elements);
2304 if (
auto structType = dyn_cast<moore::StructType>(type)) {
2305 SmallVector<Type> expectedTy;
2306 expectedTy.reserve(structType.getMembers().size());
2307 for (
auto member : structType.getMembers())
2308 expectedTy.push_back(member.type);
2310 FailureOr<SmallVector<Value>> elements;
2311 if (expectedTy.size() == elts.size())
2312 elements = convertElements(expr, expectedTy, replCount);
2314 elements = convertElements(expr, {}, replCount);
2316 if (failed(elements))
2319 assert(structType.getMembers().size() == elements->size());
2320 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2324 if (
auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
2325 SmallVector<Type> expectedTy;
2326 expectedTy.reserve(structType.getMembers().size());
2327 for (
auto member : structType.getMembers())
2328 expectedTy.push_back(member.type);
2330 FailureOr<SmallVector<Value>> elements;
2331 if (expectedTy.size() == elts.size())
2332 elements = convertElements(expr, expectedTy, replCount);
2334 elements = convertElements(expr, {}, replCount);
2336 if (failed(elements))
2339 assert(structType.getMembers().size() == elements->size());
2341 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2345 if (
auto arrayType = dyn_cast<moore::ArrayType>(type)) {
2347 convertElements(expr, arrayType.getElementType(), replCount);
2349 if (failed(elements))
2352 assert(arrayType.getSize() == elements->size());
2354 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2358 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
2360 convertElements(expr, arrayType.getElementType(), replCount);
2362 if (failed(elements))
2365 assert(arrayType.getSize() == elements->size());
2366 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2370 if (
auto openType = dyn_cast<moore::OpenUnpackedArrayType>(type)) {
2372 convertElements(expr, openType.getElementType(), replCount);
2374 if (failed(elements))
2377 auto arrayType = moore::UnpackedArrayType::get(
2378 context.getContext(), elements->size(), openType.getElementType());
2379 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2382 mlir::emitError(loc) <<
"unsupported assignment pattern with type " << type;
2386 Value visit(
const slang::ast::SimpleAssignmentPatternExpression &expr) {
2387 return visitAssignmentPattern(expr);
2390 Value visit(
const slang::ast::StructuredAssignmentPatternExpression &expr) {
2391 return visitAssignmentPattern(expr);
2394 Value visit(
const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
2396 context.evaluateConstant(expr.count()).integer().as<
unsigned>();
2397 assert(count &&
"Slang guarantees constant non-zero replication count");
2398 return visitAssignmentPattern(expr, *count);
2401 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2402 SmallVector<Value> operands;
2403 for (
auto stream : expr.streams()) {
2404 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2405 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2406 mlir::emitError(operandLoc)
2407 <<
"Moore only support streaming "
2408 "concatenation with fixed size 'with expression'";
2412 if (stream.constantWithWidth.has_value()) {
2413 value =
context.convertRvalueExpression(*stream.withExpr);
2414 auto type = cast<moore::UnpackedType>(value.getType());
2415 auto intType = moore::IntType::get(
2416 context.getContext(), type.getBitSize().value(), type.getDomain());
2418 value =
context.materializeConversion(intType, value,
false, loc);
2420 value =
context.convertRvalueExpression(*stream.operand);
2423 value =
context.convertToSimpleBitVector(value);
2426 operands.push_back(value);
2430 if (operands.size() == 1) {
2433 value = operands.front();
2435 value = moore::ConcatOp::create(builder, loc, operands).getResult();
2438 if (expr.getSliceSize() == 0) {
2442 auto type = cast<moore::IntType>(value.getType());
2443 SmallVector<Value> slicedOperands;
2444 auto iterMax = type.getWidth() / expr.getSliceSize();
2445 auto remainSize = type.getWidth() % expr.getSliceSize();
2447 for (
size_t i = 0; i < iterMax; i++) {
2448 auto extractResultType = moore::IntType::get(
2449 context.getContext(), expr.getSliceSize(), type.getDomain());
2451 auto extracted = moore::ExtractOp::create(builder, loc, extractResultType,
2452 value, i * expr.getSliceSize());
2453 slicedOperands.push_back(extracted);
2457 auto extractResultType = moore::IntType::get(
2458 context.getContext(), remainSize, type.getDomain());
2461 moore::ExtractOp::create(builder, loc, extractResultType, value,
2462 iterMax * expr.getSliceSize());
2463 slicedOperands.push_back(extracted);
2466 return moore::ConcatOp::create(builder, loc, slicedOperands);
2469 Value visit(
const slang::ast::AssertionInstanceExpression &expr) {
2470 return context.convertAssertionExpression(expr.body, loc);
2473 Value visit(
const slang::ast::UnboundedLiteral &expr) {
2475 "slang checks $ only used within queue index expression");
2479 moore::QueueSizeBIOp::create(builder, loc,
context.getIndexedQueue());
2480 auto one = moore::ConstantOp::create(builder, loc, queueSize.getType(), 1);
2481 auto lastElement = moore::SubOp::create(builder, loc, queueSize, one);
2498 Value visit(
const slang::ast::NewClassExpression &expr) {
2499 auto type =
context.convertType(*expr.type);
2500 auto classTy = dyn_cast<moore::ClassHandleType>(type);
2506 if (!classTy && expr.isSuperClass) {
2507 newObj =
context.getImplicitThisRef();
2508 if (!newObj || !newObj.getType() ||
2509 !isa<moore::ClassHandleType>(newObj.getType())) {
2510 mlir::emitError(loc) <<
"implicit this ref was not set while "
2511 "converting new class function";
2514 auto thisType = cast<moore::ClassHandleType>(newObj.getType());
2516 cast<moore::ClassDeclOp>(*
context.symbolTable.lookupNearestSymbolFrom(
2517 context.intoModuleOp, thisType.getClassSym()));
2518 auto baseClassSym = classDecl.getBase();
2519 classTy = circt::moore::ClassHandleType::get(
context.getContext(),
2520 baseClassSym.value());
2523 newObj = moore::ClassNewOp::create(builder, loc, classTy, {});
2526 const auto *constructor = expr.constructorCall();
2531 if (
const auto *callConstructor =
2532 constructor->as_if<slang::ast::CallExpression>())
2533 if (
const auto *subroutine =
2534 std::get_if<const slang::ast::SubroutineSymbol *>(
2535 &callConstructor->subroutine)) {
2536 if (!(*subroutine)->thisVar) {
2537 mlir::emitError(loc)
2538 <<
"unsupported constructor call without `this` argument";
2542 llvm::SaveAndRestore saveThis(
context.currentThisRef, newObj);
2543 if (!visitCall(*callConstructor, *subroutine))
2551 template <
typename T>
2552 Value visit(T &&node) {
2553 mlir::emitError(loc,
"unsupported expression: ")
2554 << slang::ast::toString(node.kind);
2558 Value visitInvalid(
const slang::ast::Expression &expr) {
2559 mlir::emitError(loc,
"invalid expression");
2570struct LvalueExprVisitor :
public ExprVisitor {
2572 : ExprVisitor(
context, loc, true) {}
2573 using ExprVisitor::visit;
2576 Value visit(
const slang::ast::NamedValueExpression &expr) {
2578 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2582 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2583 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2585 if (
auto *
const property =
2586 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
2590 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
2592 auto type =
context.convertType(*expr.type);
2595 auto memberType = dyn_cast<moore::UnpackedType>(type);
2597 mlir::emitError(loc)
2598 <<
"unsupported virtual interface member type: " << type;
2602 Value base = materializeSymbolRvalue(*access.base);
2604 auto d = mlir::emitError(loc,
"unknown name `")
2605 << access.base->name <<
"`";
2606 d.attachNote(
context.convertLocation(access.base->location))
2607 <<
"no rvalue generated for virtual interface base";
2611 auto fieldName = access.fieldName
2613 : builder.getStringAttr(expr.symbol.name);
2614 auto memberRefType = moore::RefType::get(memberType);
2615 return moore::StructExtractOp::create(builder, loc, memberRefType,
2619 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
2620 d.attachNote(
context.convertLocation(expr.symbol.location))
2621 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2626 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
2629 if (!expr.ref.path.empty()) {
2630 if (
auto *inst = expr.ref.path.front()
2631 .symbol->as_if<slang::ast::InstanceSymbol>()) {
2633 expr.symbol.getParentScope()->getContainingInstance();
2634 if (&inst->body == symbolBody ||
2635 (symbolBody && inst->body.getDeclaringDefinition() ==
2636 symbolBody->getDeclaringDefinition())) {
2637 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2644 if (
auto value =
context.resolveCapturedValue(expr.symbol))
2650 if (
auto key =
context.buildHierValueKey(expr)) {
2651 if (
auto it =
context.hierValueSymbols.find(*key);
2652 it !=
context.hierValueSymbols.end())
2657 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2664 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2665 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2669 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
2670 << expr.symbol.name <<
"`";
2671 d.attachNote(
context.convertLocation(expr.symbol.location))
2672 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2676 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2677 SmallVector<Value> operands;
2678 for (
auto stream : expr.streams()) {
2679 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2680 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2681 mlir::emitError(operandLoc)
2682 <<
"Moore only support streaming "
2683 "concatenation with fixed size 'with expression'";
2687 if (stream.constantWithWidth.has_value()) {
2688 value =
context.convertLvalueExpression(*stream.withExpr);
2689 auto type = cast<moore::UnpackedType>(
2690 cast<moore::RefType>(value.getType()).getNestedType());
2691 auto intType = moore::RefType::get(moore::IntType::get(
2692 context.getContext(), type.getBitSize().value(), type.getDomain()));
2694 value =
context.materializeConversion(intType, value,
false, loc);
2696 value =
context.convertLvalueExpression(*stream.operand);
2701 operands.push_back(value);
2704 if (operands.size() == 1) {
2707 value = operands.front();
2709 value = moore::ConcatRefOp::create(builder, loc, operands).getResult();
2712 if (expr.getSliceSize() == 0) {
2716 auto type = cast<moore::IntType>(
2717 cast<moore::RefType>(value.getType()).getNestedType());
2718 SmallVector<Value> slicedOperands;
2719 auto widthSum = type.getWidth();
2720 auto domain = type.getDomain();
2721 auto iterMax = widthSum / expr.getSliceSize();
2722 auto remainSize = widthSum % expr.getSliceSize();
2724 for (
size_t i = 0; i < iterMax; i++) {
2725 auto extractResultType = moore::RefType::get(moore::IntType::get(
2726 context.getContext(), expr.getSliceSize(), domain));
2728 auto extracted = moore::ExtractRefOp::create(
2729 builder, loc, extractResultType, value, i * expr.getSliceSize());
2730 slicedOperands.push_back(extracted);
2734 auto extractResultType = moore::RefType::get(
2735 moore::IntType::get(
context.getContext(), remainSize, domain));
2738 moore::ExtractRefOp::create(builder, loc, extractResultType, value,
2739 iterMax * expr.getSliceSize());
2740 slicedOperands.push_back(extracted);
2743 return moore::ConcatRefOp::create(builder, loc, slicedOperands);
2747 template <
typename T>
2748 Value visit(T &&node) {
2749 return context.convertRvalueExpression(node);
2752 Value visitInvalid(
const slang::ast::Expression &expr) {
2753 mlir::emitError(loc,
"invalid expression");
2763Value Context::resolveCapturedValue(
const slang::ast::ValueSymbol &sym) {
2771std::optional<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>>
2773 const slang::ast::HierarchicalValueExpression &expr) {
2774 if (expr.ref.path.empty())
2775 return std::nullopt;
2777 const slang::ast::InstanceSymbol *firstInst =
nullptr;
2778 SmallVector<StringRef, 4> names;
2779 for (
auto &elem : expr.ref.path) {
2780 if (
auto *inst = elem.symbol->as_if<slang::ast::InstanceSymbol>()) {
2784 names.push_back(inst->name);
2788 names.push_back(expr.symbol.name);
2789 std::string hierName = llvm::join(names,
".");
2792 return std::nullopt;
2793 return std::make_pair(firstInst,
builder.getStringAttr(hierName));
2801 Type requiredType) {
2803 auto value = expr.visit(RvalueExprVisitor(*
this, loc));
2804 if (value && requiredType)
2812 return expr.visit(LvalueExprVisitor(*
this, loc));
2820 if (
auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
2821 if (type.getBitSize() == 1)
2823 if (
auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
2824 return moore::BoolCastOp::create(
builder, value.getLoc(), value);
2825 mlir::emitError(value.getLoc(),
"expression of type ")
2826 << value.getType() <<
" cannot be cast to a boolean";
2832 const slang::ast::Type &astType,
2834 const auto *floatType = astType.as_if<slang::ast::FloatingType>();
2838 if (svreal.isShortReal() &&
2839 floatType->floatKind == slang::ast::FloatingType::ShortReal) {
2840 attr = FloatAttr::get(
builder.getF32Type(), svreal.shortReal().v);
2841 }
else if (svreal.isReal() &&
2842 floatType->floatKind == slang::ast::FloatingType::Real) {
2843 attr = FloatAttr::get(
builder.getF64Type(), svreal.real().v);
2845 mlir::emitError(loc) <<
"invalid real constant";
2849 return moore::ConstantRealOp::create(
builder, loc, attr);
2854 const slang::ast::Type &astType,
2856 if (!astType.isString())
2858 const std::string &str = stringLiteral.str();
2859 auto intTy = moore::IntType::getInt(
getContext(),
2860 static_cast<unsigned>(str.size() * 8));
2862 moore::ConstantStringOp::create(
builder, loc, intTy, str).getResult();
2863 return moore::IntToStringOp::create(
builder, loc, immInt).getResult();
2868 const slang::ast::Type &astType, Location loc) {
2873 bool typeIsFourValued =
false;
2874 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2878 auto intType = moore::IntType::get(
getContext(), fvint.getBitWidth(),
2879 fvint.hasUnknown() || typeIsFourValued
2882 auto result = moore::ConstantOp::create(
builder, loc, intType, fvint);
2887 const slang::ConstantValue &constant,
2888 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc) {
2895 if (astType.elementType.isString()) {
2896 auto arrayType = dyn_cast<moore::UnpackedArrayType>(type);
2900 SmallVector<Value> elemVals;
2901 for (
const auto &elem : constant.elements()) {
2902 if (!elem.isString())
2907 elemVals.push_back(value);
2909 if (elemVals.size() != arrayType.getSize())
2911 return moore::ArrayCreateOp::create(
builder, loc, arrayType, elemVals);
2916 if (astType.elementType.isIntegral())
2917 bitWidth = astType.elementType.getBitWidth();
2921 bool typeIsFourValued =
false;
2924 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2935 auto intType = moore::IntType::get(
getContext(), bitWidth, domain);
2937 auto arrType = moore::UnpackedArrayType::get(
2938 getContext(), constant.elements().size(), intType);
2940 llvm::SmallVector<mlir::Value> elemVals;
2941 moore::ConstantOp constOp;
2943 mlir::OpBuilder::InsertionGuard guard(
builder);
2946 for (
auto elem : constant.elements()) {
2948 constOp = moore::ConstantOp::create(
builder, loc, intType, fvInt);
2949 elemVals.push_back(constOp.getResult());
2954 auto arrayOp = moore::ArrayCreateOp::create(
builder, loc, arrType, elemVals);
2956 return arrayOp.getResult();
2960 const slang::ast::Type &type, Location loc) {
2962 if (
auto *arr = type.as_if<slang::ast::FixedSizeUnpackedArrayType>())
2964 if (constant.isInteger())
2966 if (constant.isReal() || constant.isShortReal())
2968 if (constant.isString())
2976 using slang::ast::EvalFlags;
2977 slang::ast::EvalContext evalContext(
2979 slang::ast::LookupLocation::max),
2980 EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
2981 return expr.eval(evalContext);
2990 auto type = moore::IntType::get(
getContext(), 1, domain);
2997 if (isa<moore::IntType>(value.getType()))
3004 if (
auto packed = dyn_cast<moore::PackedType>(value.getType()))
3005 if (
auto sbvType = packed.getSimpleBitVector())
3008 mlir::emitError(value.getLoc()) <<
"expression of type " << value.getType()
3009 <<
" cannot be cast to a simple bit vector";
3015 if (isa<moore::IntType>(value.getType()))
3018 auto packedType = cast<moore::PackedType>(value.getType());
3019 auto intType = packedType.getSimpleBitVector();
3024 if (isa<moore::TimeType>(packedType) &&
3026 value =
builder.createOrFold<moore::TimeToLogicOp>(loc, value);
3027 auto scale = moore::ConstantOp::create(
builder, loc, intType,
3029 return builder.createOrFold<moore::DivUOp>(loc, value, scale);
3035 if (packedType.containsTimeType()) {
3037 mlir::emitError(loc) <<
"unsupported conversion: " << packedType
3038 <<
" cannot be converted to " << intType
3039 <<
"; contains a time type";
3044 return builder.createOrFold<moore::PackedToSBVOp>(loc, value);
3052 Value value, Location loc,
3054 if (value.getType() == packedType)
3057 auto &builder =
context.builder;
3058 auto intType = cast<moore::IntType>(value.getType());
3063 if (isa<moore::TimeType>(packedType) &&
3065 auto scale = moore::ConstantOp::create(builder, loc, intType,
3067 value = builder.createOrFold<moore::MulOp>(loc, value, scale);
3068 return builder.createOrFold<moore::LogicToTimeOp>(loc, value);
3076 mlir::emitError(loc) <<
"unsupported conversion: " << intType
3077 <<
" cannot be converted to " << packedType
3078 <<
"; contains a time type";
3083 return builder.createOrFold<moore::SBVToPackedOp>(loc, packedType, value);
3089 moore::ClassHandleType expectedHandleTy) {
3090 auto loc = actualHandle.getLoc();
3092 auto actualTy = actualHandle.getType();
3093 auto actualHandleTy = dyn_cast<moore::ClassHandleType>(actualTy);
3094 if (!actualHandleTy) {
3095 mlir::emitError(loc) <<
"expected a !moore.class<...> value, got "
3101 if (actualHandleTy == expectedHandleTy)
3102 return actualHandle;
3104 if (!
context.isClassDerivedFrom(actualHandleTy, expectedHandleTy)) {
3105 mlir::emitError(loc)
3106 <<
"receiver class " << actualHandleTy.getClassSym()
3107 <<
" is not the same as, or derived from, expected base class "
3108 << expectedHandleTy.getClassSym().getRootReference();
3113 auto casted = moore::ClassUpcastOp::create(
context.builder, loc,
3114 expectedHandleTy, actualHandle)
3120 Location loc,
bool fallible) {
3122 if (type == value.getType())
3127 auto dstPacked = dyn_cast<moore::PackedType>(type);
3128 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
3129 auto dstInt = dstPacked ? dstPacked.getSimpleBitVector() : moore::IntType();
3130 auto srcInt = srcPacked ? srcPacked.getSimpleBitVector() : moore::IntType();
3132 if (dstInt && srcInt) {
3140 auto resizedType = moore::IntType::get(
3141 value.getContext(), dstInt.getWidth(), srcPacked.getDomain());
3142 if (dstInt.getWidth() < srcInt.getWidth()) {
3143 value =
builder.createOrFold<moore::TruncOp>(loc, resizedType, value);
3144 }
else if (dstInt.getWidth() > srcInt.getWidth()) {
3146 value =
builder.createOrFold<moore::SExtOp>(loc, resizedType, value);
3148 value =
builder.createOrFold<moore::ZExtOp>(loc, resizedType, value);
3152 if (dstInt.getDomain() != srcInt.getDomain()) {
3154 value =
builder.createOrFold<moore::LogicToIntOp>(loc, value);
3156 value =
builder.createOrFold<moore::IntToLogicOp>(loc, value);
3165 assert(value.getType() == type);
3170 if (isa<moore::StringType>(type) &&
3171 isa<moore::FormatStringType>(value.getType())) {
3172 return builder.createOrFold<moore::FormatStringToStringOp>(loc, value);
3176 if (isa<moore::FormatStringType>(type) &&
3177 isa<moore::StringType>(value.getType())) {
3178 return builder.createOrFold<moore::FormatStringOp>(loc, value);
3183 if (isa<moore::QueueType>(type) && isa<moore::QueueType>(value.getType()) &&
3184 cast<moore::QueueType>(type).getElementType() ==
3185 cast<moore::QueueType>(value.getType()).getElementType())
3186 return builder.createOrFold<moore::QueueResizeOp>(loc, type, value);
3189 if (isa<moore::QueueType>(type) &&
3190 isa<moore::UnpackedArrayType>(value.getType())) {
3191 auto queueElType = dyn_cast<moore::QueueType>(type).getElementType();
3192 auto unpackedArrayElType =
3193 dyn_cast<moore::UnpackedArrayType>(value.getType()).getElementType();
3195 if (queueElType == unpackedArrayElType) {
3196 return builder.createOrFold<moore::QueueFromUnpackedArrayOp>(loc, type,
3202 if (dstInt && isa<moore::RealType>(value.getType())) {
3203 auto twoValInt =
builder.createOrFold<moore::RealToIntOp>(
3204 loc, dstInt.getTwoValued(), value);
3209 if (isa<moore::RealType>(type) && isa<moore::IntType>(value.getType())) {
3212 if (dyn_cast<moore::IntType>(value.getType()).getDomain() ==
3217 dyn_cast<moore::IntType>(value.getType()).getTwoValued(), value,
true,
3221 return builder.createOrFold<moore::SIntToRealOp>(loc, type, twoValInt);
3222 return builder.createOrFold<moore::UIntToRealOp>(loc, type, twoValInt);
3225 auto getBuiltinFloatType = [&](moore::RealType type) -> Type {
3227 return mlir::Float32Type::get(
builder.getContext());
3229 return mlir::Float64Type::get(
builder.getContext());
3233 if (isa<moore::TimeType>(type) && isa<moore::RealType>(value.getType())) {
3235 moore::IntType::get(
builder.getContext(), 64, Domain::TwoValued);
3237 getBuiltinFloatType(cast<moore::RealType>(value.getType()));
3238 auto scale = moore::ConstantRealOp::create(
3239 builder, loc, value.getType(),
3241 auto scaled =
builder.createOrFold<moore::MulRealOp>(loc, value, scale);
3242 auto asInt = moore::RealToIntOp::create(
builder, loc, intType, scaled);
3243 auto asLogic = moore::IntToLogicOp::create(
builder, loc, asInt);
3244 return moore::LogicToTimeOp::create(
builder, loc, asLogic);
3248 if (isa<moore::RealType>(type) && isa<moore::TimeType>(value.getType())) {
3249 auto asLogic = moore::TimeToLogicOp::create(
builder, loc, value);
3250 auto asInt = moore::LogicToIntOp::create(
builder, loc, asLogic);
3251 auto asReal = moore::UIntToRealOp::create(
builder, loc, type, asInt);
3252 Type floatType = getBuiltinFloatType(cast<moore::RealType>(type));
3253 auto scale = moore::ConstantRealOp::create(
3256 return moore::DivRealOp::create(
builder, loc, asReal, scale);
3260 if (isa<moore::StringType>(type)) {
3261 if (
auto intType = dyn_cast<moore::IntType>(value.getType())) {
3263 value = moore::LogicToIntOp::create(
builder, loc, value);
3264 return moore::IntToStringOp::create(
builder, loc, value);
3269 if (
auto intType = dyn_cast<moore::IntType>(type)) {
3270 if (isa<moore::StringType>(value.getType())) {
3271 value = moore::StringToIntOp::create(
builder, loc, intType.getTwoValued(),
3275 return moore::IntToLogicOp::create(
builder, loc, value);
3282 if (isa<moore::FormatStringType>(type)) {
3284 value, isSigned, loc);
3287 return moore::FormatStringOp::create(
builder, loc, asStr, {}, {}, {});
3290 if (isa<moore::RealType>(type) && isa<moore::RealType>(value.getType()))
3291 return builder.createOrFold<moore::ConvertRealOp>(loc, type, value);
3293 if (isa<moore::ClassHandleType>(type) &&
3294 isa<moore::ClassHandleType>(value.getType()))
3298 if (fallible && value.getType() != type)
3300 if (value.getType() != type)
3301 value = moore::ConversionOp::create(
builder, loc, type, value);
3307template <
typename OpTy>
3310 std::span<const slang::ast::Expression *const> args) {
3312 assert(args.size() == 1 &&
"real math builtin expects 1 argument");
3313 auto value =
context.convertRvalueExpression(*args[0]);
3316 return OpTy::create(
context.builder, loc, value);
3321template <
typename OpTy>
3324 std::span<const slang::ast::Expression *const> args) {
3326 assert(args.size() == 2 &&
"real math builtin expects 2 arguments");
3329 auto lhs =
context.convertRvalueExpression(*args[0], realType);
3330 auto rhs =
context.convertRvalueExpression(*args[1], realType);
3333 return OpTy::create(
context.builder, loc, lhs, rhs);
3339 auto &builder =
context.builder;
3340 auto newBlockAfter = [&](Block *after) -> Block * {
3341 auto block = std::make_unique<Block>();
3342 block->insertAfter(after);
3343 return block.release();
3346 for (
auto [destExpr, value, matched] : result.assignments) {
3347 auto lhs =
context.convertLvalueExpression(*destExpr);
3350 auto cond = moore::ToBuiltinIntOp::create(builder, loc, matched);
3352 auto *assignBlock = newBlockAfter(builder.getInsertionBlock());
3353 auto *continuedBlock = newBlockAfter(assignBlock);
3354 mlir::cf::CondBranchOp::create(builder, loc, cond, assignBlock,
3357 builder.setInsertionPointToEnd(assignBlock);
3358 moore::BlockingAssignOp::create(builder, loc, lhs, value);
3359 mlir::cf::BranchOp::create(builder, loc, continuedBlock);
3361 builder.setInsertionPointToEnd(continuedBlock);
3367 const slang::ast::SystemSubroutine &subroutine, Location loc,
3368 std::span<const slang::ast::Expression *const> args) {
3369 using ksn = slang::parsing::KnownSystemName;
3370 StringRef name = subroutine.name;
3371 auto nameId = subroutine.knownNameId;
3372 size_t numArgs = args.size();
3380 if (nameId == ksn::URandom || nameId == ksn::Random) {
3381 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3382 auto minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3384 moore::ConstantOp::create(
builder, loc, i32Ty, APInt::getAllOnes(32));
3391 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval, seed);
3394 if (nameId == ksn::URandomRange) {
3395 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3405 minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3407 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval,
3415 if (nameId == ksn::Time || nameId == ksn::STime || nameId == ksn::RealTime) {
3417 assert(numArgs == 0 &&
"time functions take no arguments");
3418 return moore::TimeBIOp::create(
builder, loc);
3425 if (nameId == ksn::Clog2) {
3427 assert(numArgs == 1 &&
"`$clog2` takes 1 argument");
3434 return moore::Clog2BIOp::create(
builder, loc, value);
3441 if (nameId == ksn::IsUnknown) {
3442 assert(numArgs == 1 &&
"`$isunknown` takes 1 argument");
3447 if (!isa<moore::IntType>(value.getType())) {
3448 if (!isa<moore::PackedType>(value.getType())) {
3449 mlir::emitError(loc) <<
"expected integer argument for `$isunknown`";
3457 auto valTy = dyn_cast<moore::IntType>(value.getType());
3461 if (nameId == ksn::OneHot0 || nameId == ksn::OneHot) {
3462 assert(numArgs == 1 &&
"`$onehot`/`$onehot0` takes 1 argument");
3466 if (!isa<moore::IntType>(value.getType())) {
3467 if (!isa<moore::PackedType>(value.getType())) {
3468 mlir::emitError(loc)
3469 <<
"expected integer argument for `$onehot`/`$onehot0`";
3477 auto valTy = dyn_cast<moore::IntType>(value.getType());
3479 mlir::emitError(loc) <<
"expected integer argument for `"
3480 << subroutine.name <<
"`";
3487 if (valTy.getDomain() == Domain::FourValued) {
3488 Value isUnknownMoore =
3491 builder.createOrFold<moore::ToBuiltinIntOp>(loc, isUnknownMoore);
3499 auto minusOne = comb::SubOp::create(
builder, loc, intVal, one);
3500 auto anded = comb::AndOp::create(
builder, loc, intVal, minusOne);
3502 Value result = comb::ICmpOp::create(
builder, loc, comb::ICmpPredicate::eq,
3503 anded, zero,
false);
3506 if (nameId == ksn::OneHot) {
3507 auto isNotZero = comb::ICmpOp::create(
3508 builder, loc, comb::ICmpPredicate::ne, intVal, zero,
false);
3509 result = comb::AndOp::create(
builder, loc, result, isNotZero);
3516 result = comb::MuxOp::create(
builder, loc, isUnknown, zeroI1, result);
3517 Value resultMoore = moore::FromBuiltinIntOp::create(
builder, loc, result);
3518 return moore::IntToLogicOp::create(
builder, loc, resultMoore).getResult();
3520 return moore::FromBuiltinIntOp::create(
builder, loc, result);
3523 if (nameId == ksn::CountOnes) {
3524 assert(numArgs == 1 &&
"`$countones` takes 1 argument");
3528 if (!isa<moore::IntType>(value.getType())) {
3529 if (!isa<moore::PackedType>(value.getType())) {
3530 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3538 auto valTy = dyn_cast<moore::IntType>(value.getType());
3540 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3548 auto builtinIntTy = cast<IntegerType>(intVal.getType());
3549 unsigned width = builtinIntTy.getWidth();
3550 unsigned resultWidth = llvm::Log2_32_Ceil(width + 1);
3551 auto i1Ty =
builder.getI1Type();
3552 unsigned padWidth = resultWidth - 1;
3554 builder.getIntegerType(padWidth), 0);
3558 Value sum = comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit0});
3560 for (
unsigned i = 1; i < width; ++i) {
3563 comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit});
3564 sum = comb::AddOp::create(
builder, loc, sum, extended);
3568 return moore::FromBuiltinIntOp::create(
builder, loc, sum);
3572 if (nameId == ksn::Ln)
3573 return convertRealMathBI<moore::LnBIOp>(*
this, loc, name, args);
3574 if (nameId == ksn::Log10)
3575 return convertRealMathBI<moore::Log10BIOp>(*
this, loc, name, args);
3576 if (nameId == ksn::Exp)
3577 return convertRealMathBI<moore::ExpBIOp>(*
this, loc, name, args);
3578 if (nameId == ksn::Sqrt)
3579 return convertRealMathBI<moore::SqrtBIOp>(*
this, loc, name, args);
3580 if (nameId == ksn::Floor)
3581 return convertRealMathBI<moore::FloorBIOp>(*
this, loc, name, args);
3582 if (nameId == ksn::Ceil)
3583 return convertRealMathBI<moore::CeilBIOp>(*
this, loc, name, args);
3584 if (nameId == ksn::Sin)
3585 return convertRealMathBI<moore::SinBIOp>(*
this, loc, name, args);
3586 if (nameId == ksn::Cos)
3587 return convertRealMathBI<moore::CosBIOp>(*
this, loc, name, args);
3588 if (nameId == ksn::Tan)
3589 return convertRealMathBI<moore::TanBIOp>(*
this, loc, name, args);
3590 if (nameId == ksn::Asin)
3591 return convertRealMathBI<moore::AsinBIOp>(*
this, loc, name, args);
3592 if (nameId == ksn::Acos)
3593 return convertRealMathBI<moore::AcosBIOp>(*
this, loc, name, args);
3594 if (nameId == ksn::Atan)
3595 return convertRealMathBI<moore::AtanBIOp>(*
this, loc, name, args);
3596 if (nameId == ksn::Sinh)
3597 return convertRealMathBI<moore::SinhBIOp>(*
this, loc, name, args);
3598 if (nameId == ksn::Cosh)
3599 return convertRealMathBI<moore::CoshBIOp>(*
this, loc, name, args);
3600 if (nameId == ksn::Tanh)
3601 return convertRealMathBI<moore::TanhBIOp>(*
this, loc, name, args);
3602 if (nameId == ksn::Asinh)
3603 return convertRealMathBI<moore::AsinhBIOp>(*
this, loc, name, args);
3604 if (nameId == ksn::Acosh)
3605 return convertRealMathBI<moore::AcoshBIOp>(*
this, loc, name, args);
3606 if (nameId == ksn::Atanh)
3607 return convertRealMathBI<moore::AtanhBIOp>(*
this, loc, name, args);
3609 if (nameId == ksn::Pow)
3610 return convertRealMathTwoBI<moore::PowRealOp>(*
this, loc, name, args);
3611 if (nameId == ksn::Atan2)
3612 return convertRealMathTwoBI<moore::Atan2BIOp>(*
this, loc, name, args);
3613 if (nameId == ksn::Hypot)
3614 return convertRealMathTwoBI<moore::HypotBIOp>(*
this, loc, name, args);
3620 if (nameId == ksn::Itor) {
3621 assert(numArgs == 1 &&
"`$itor` takes 1 argument");
3626 if (nameId == ksn::Rtoi) {
3627 assert(numArgs == 1 &&
"`$rtoi` takes 1 argument");
3628 auto intType = moore::IntType::get(
getContext(), 32, Domain::TwoValued);
3632 if (nameId == ksn::Signed || nameId == ksn::Unsigned) {
3634 assert(numArgs == 1 &&
"`$signed`/`$unsigned` take 1 argument");
3640 if (nameId == ksn::RealToBits)
3641 return convertRealMathBI<moore::RealtobitsBIOp>(*
this, loc, name, args);
3642 if (nameId == ksn::BitsToReal)
3643 return convertRealMathBI<moore::BitstorealBIOp>(*
this, loc, name, args);
3644 if (nameId == ksn::ShortrealToBits)
3645 return convertRealMathBI<moore::ShortrealtobitsBIOp>(*
this, loc, name,
3647 if (nameId == ksn::BitsToShortreal)
3648 return convertRealMathBI<moore::BitstoshortrealBIOp>(*
this, loc, name,
3651 if (nameId == ksn::Cast) {
3652 assert(numArgs == 2 &&
"`cast` takes 2 arguments");
3653 auto *dstExpr = args[0];
3658 if (
auto *assign = dstExpr->as_if<slang::ast::AssignmentExpression>())
3659 dstExpr = &assign->left();
3668 if (isa<moore::ClassHandleType>(dstType) ||
3669 isa<moore::ClassHandleType>(src.getType())) {
3670 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3671 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3675 dstType, src, args[1]->type->isSigned(), loc,
true);
3676 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3678 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3680 moore::BlockingAssignOp::create(
builder, loc, dst, converted);
3681 return moore::ConstantOp::create(
builder, loc, i1Ty, 1,
3689 if (nameId == ksn::Len) {
3691 assert(numArgs == 1 &&
"`len` takes 1 argument");
3692 auto stringType = moore::StringType::get(
getContext());
3696 return moore::StringLenOp::create(
builder, loc, value);
3699 if (nameId == ksn::Getc) {
3701 assert(numArgs == 2 &&
"`getc` takes 2 arguments");
3702 auto stringType = moore::StringType::get(
getContext());
3707 return moore::StringGetOp::create(
builder, loc, str, index);
3710 if (nameId == ksn::ToUpper) {
3712 assert(numArgs == 1 &&
"`toupper` takes 1 argument");
3713 auto stringType = moore::StringType::get(
getContext());
3717 return moore::StringToUpperOp::create(
builder, loc, value);
3720 if (nameId == ksn::ToLower) {
3722 assert(numArgs == 1 &&
"`tolower` takes 1 argument");
3723 auto stringType = moore::StringType::get(
getContext());
3727 return moore::StringToLowerOp::create(
builder, loc, value);
3730 if (nameId == ksn::Compare || nameId == ksn::ICompare) {
3733 auto stringType = moore::StringType::get(
getContext());
3738 if (nameId == ksn::Compare)
3739 return moore::StringCompareOp::create(
builder, loc, lhs, rhs);
3740 return moore::StringICompareOp::create(
builder, loc, lhs, rhs);
3743 if (nameId == ksn::Substr) {
3745 assert(numArgs == 3 &&
"`substr` takes 3 arguments");
3746 auto stringType = moore::StringType::get(
getContext());
3750 if (!str || !start || !end)
3752 return moore::StringSubstrOp::create(
builder, loc, str, start, end);
3755 if (nameId == ksn::AToI || nameId == ksn::AToHex || nameId == ksn::AToOct ||
3756 nameId == ksn::AToBin) {
3758 assert(numArgs == 1 &&
"`atoi/hex/oct/bin` takes 1 argument");
3759 auto stringType = moore::StringType::get(
getContext());
3763 auto integerType = moore::IntType::getLogic(
builder.getContext(), 32);
3766 return moore::StringAtoiOp::create(
builder, loc, integerType, str);
3768 return moore::StringAtohexOp::create(
builder, loc, integerType, str);
3770 return moore::StringAtooctOp::create(
builder, loc, integerType, str);
3772 return moore::StringAtobinOp::create(
builder, loc, integerType, str);
3774 llvm_unreachable(
"unexpected string to integer conversion");
3778 if (nameId == ksn::AToReal) {
3780 assert(numArgs == 1 &&
"`atoreal` takes 1 argument");
3781 auto stringType = moore::StringType::get(
getContext());
3786 return moore::StringAtorealOp::create(
builder, loc, realType, str);
3793 if (nameId == ksn::ArraySize) {
3795 assert(numArgs == 1 &&
"`size` takes 1 argument");
3796 if (args[0]->type->isQueue()) {
3800 return moore::QueueSizeBIOp::create(
builder, loc, value);
3802 if (args[0]->type->getCanonicalType().kind ==
3803 slang::ast::SymbolKind::DynamicArrayType) {
3807 return moore::OpenUArraySizeOp::create(
builder, loc, value);
3809 if (args[0]->type->isAssociativeArray()) {
3813 return moore::AssocArraySizeOp::create(
builder, loc, value);
3815 emitError(loc) <<
"unsupported member function `size` on type `"
3816 << args[0]->type->toString() <<
"`";
3820 if (nameId == ksn::Delete) {
3822 assert(numArgs == 1 &&
"`delete` takes 1 argument");
3823 if (args[0]->type->getCanonicalType().kind ==
3824 slang::ast::SymbolKind::DynamicArrayType) {
3828 return moore::OpenUArrayDeleteOp::create(
builder, loc, value);
3830 emitError(loc) <<
"unsupported member function `delete` on type `"
3831 << args[0]->type->toString() <<
"`";
3835 if (nameId == ksn::PopBack) {
3837 assert(numArgs == 1 &&
"`pop_back` takes 1 argument");
3838 assert(args[0]->type->isQueue() &&
"`pop_back` is only valid on queues");
3842 return moore::QueuePopBackOp::create(
builder, loc, value);
3845 if (nameId == ksn::PopFront) {
3847 assert(numArgs == 1 &&
"`pop_front` takes 1 argument");
3848 assert(args[0]->type->isQueue() &&
"`pop_front` is only valid on queues");
3852 return moore::QueuePopFrontOp::create(
builder, loc, value);
3859 if (nameId == ksn::Num) {
3860 if (args[0]->type->isAssociativeArray()) {
3861 assert(numArgs == 1 &&
"`num` takes 1 argument");
3865 return moore::AssocArraySizeOp::create(
builder, loc, value);
3867 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3871 if (nameId == ksn::Exists) {
3873 assert(numArgs == 2 &&
"`exists` takes 2 arguments");
3874 assert(args[0]->type->isAssociativeArray() &&
3875 "`exists` is only valid on associative arrays");
3880 return moore::AssocArrayExistsOp::create(
builder, loc, array, key);
3887 if (nameId == ksn::First || nameId == ksn::Last || nameId == ksn::Next ||
3888 nameId == ksn::Prev) {
3889 if (args[0]->type->isAssociativeArray()) {
3890 assert(numArgs == 2 &&
"traversal methods take 2 arguments");
3895 if (nameId == ksn::First)
3896 return moore::AssocArrayFirstOp::create(
builder, loc, array, key);
3897 if (nameId == ksn::Last)
3898 return moore::AssocArrayLastOp::create(
builder, loc, array, key);
3899 if (nameId == ksn::Next)
3900 return moore::AssocArrayNextOp::create(
builder, loc, array, key);
3901 if (nameId == ksn::Prev)
3902 return moore::AssocArrayPrevOp::create(
builder, loc, array, key);
3903 llvm_unreachable(
"all traversal cases handled above");
3905 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3913 if (nameId == ksn::FOpen) {
3914 assert(numArgs >= 1 && numArgs <= 2 &&
"`$fopen` takes 1 or 2 arguments");
3919 moore::FOpenModeAttr modeAttr;
3921 auto *strLit = args[1]
3922 ->unwrapImplicitConversions()
3923 .as_if<slang::ast::StringLiteral>();
3925 return emitError(loc) <<
"$fopen mode must be a string literal",
3929 llvm::StringSwitch<std::optional<moore::FOpenMode>>(
3931 .Cases({
"r",
"rb"}, moore::FOpenMode::Read)
3932 .Cases({
"w",
"wb"}, moore::FOpenMode::Write)
3933 .Cases({
"a",
"ab"}, moore::FOpenMode::Append)
3934 .Cases({
"r+",
"r+b",
"rb+"}, moore::FOpenMode::ReadUpdate)
3935 .Cases({
"w+",
"w+b",
"wb+"}, moore::FOpenMode::WriteUpdate)
3936 .Cases({
"a+",
"a+b",
"ab+"}, moore::FOpenMode::AppendUpdate)
3937 .Default(std::nullopt);
3940 return emitError(loc)
3941 <<
"invalid $fopen mode '" << strLit->getValue() <<
"'",
3943 modeAttr = moore::FOpenModeAttr::get(
getContext(), *mode);
3945 return moore::FOpenBIOp::create(
builder, loc, filename, modeAttr);
3952 if (nameId == ksn::TestPlusArgs) {
3954 assert(numArgs == 1 &&
"`$test$plusargs` takes 1 argument");
3956 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3958 return emitError(loc) <<
"`$test$plusargs` argument must be a string "
3961 auto foundTy = moore::IntType::getInt(
getContext(), 1);
3962 return moore::PlusArgsTestBIOp::create(
3963 builder, loc, foundTy,
builder.getStringAttr(strLit->getValue()));
3966 if (nameId == ksn::ValuePlusArgs) {
3970 assert(numArgs == 2 &&
"`$value$plusargs` takes 2 arguments");
3972 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3974 return emitError(loc) <<
"`$value$plusargs` format must be a string "
3979 const auto *valueArg = args[1];
3980 if (
const auto *assign =
3981 valueArg->as_if<slang::ast::AssignmentExpression>())
3982 valueArg = &assign->left();
3986 auto resultType = cast<moore::RefType>(lvalue.getType()).getNestedType();
3987 auto foundTy = moore::IntType::getInt(
getContext(), 1);
3988 auto op = moore::PlusArgsValueBIOp::create(
3989 builder, loc, foundTy, resultType,
3990 builder.getStringAttr(strLit->getValue()));
3991 moore::BlockingAssignOp::create(
builder, loc, lvalue, op.getResult());
3992 return op.getFound();
3995 if (nameId == ksn::FScanf) {
3997 *args[0], moore::IntType::getInt(
builder.getContext(), 32));
4001 args[1]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
4003 return (mlir::emitError(loc)
4004 <<
"$fscanf requires a string literal format string"),
4007 moore::ScanBeginFScanFOp::create(
builder, loc, fd).getCursor();
4014 return moore::ScanEndOp::create(
builder, loc, result->finalCursor)
4018 if (nameId == ksn::SScanf) {
4024 args[1]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
4026 return (mlir::emitError(loc)
4027 <<
"$sscanf requires a string literal format string"),
4030 moore::ScanBeginSScanFOp::create(
builder, loc, str).getCursor();
4037 return moore::ScanEndOp::create(
builder, loc, result->finalCursor)
4042 emitError(loc) <<
"unsupported system call `" << name <<
"`";
4048 return context.symbolTable.lookupNearestSymbolFrom(
context.intoModuleOp, sym);
4052 const moore::ClassHandleType &baseTy) {
4053 if (!actualTy || !baseTy)
4056 mlir::SymbolRefAttr actualSym = actualTy.getClassSym();
4057 mlir::SymbolRefAttr baseSym = baseTy.getClassSym();
4059 if (actualSym == baseSym)
4062 auto *op =
resolve(*
this, actualSym);
4063 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
4066 mlir::SymbolRefAttr curBase = decl.getBaseAttr();
4069 if (curBase == baseSym)
4071 decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(
resolve(*
this, curBase));
4076moore::ClassHandleType
4078 llvm::StringRef fieldName, Location loc) {
4080 mlir::SymbolRefAttr classSym = actualTy.getClassSym();
4084 auto *op =
resolve(*
this, classSym);
4085 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
4090 for (
auto &block : decl.getBody()) {
4091 for (
auto &opInBlock : block) {
4093 llvm::dyn_cast<moore::ClassPropertyDeclOp>(&opInBlock)) {
4094 if (prop.getSymName() == fieldName) {
4096 return moore::ClassHandleType::get(actualTy.getContext(), classSym);
4103 classSym = decl.getBaseAttr();
4107 mlir::emitError(loc) <<
"unknown property `" << fieldName <<
"`";
4116 const slang::ast::Expression &expr) {
4119 if (
const auto *valueRange = expr.as_if<slang::ast::ValueRangeExpression>()) {
4124 if (!insideLhs || !lowBound || !highBound)
4127 Value rangeLhs, rangeRhs;
4130 if (valueRange->left().type->isSigned() ||
4131 insideLhs.getType().isSignedInteger()) {
4132 rangeLhs = moore::SgeOp::create(
builder, loc, insideLhs, lowBound);
4134 rangeLhs = moore::UgeOp::create(
builder, loc, insideLhs, lowBound);
4137 if (valueRange->right().type->isSigned() ||
4138 insideLhs.getType().isSignedInteger()) {
4139 rangeRhs = moore::SleOp::create(
builder, loc, insideLhs, highBound);
4141 rangeRhs = moore::UleOp::create(
builder, loc, insideLhs, highBound);
4144 return moore::AndOp::create(
builder, loc, rangeLhs, rangeRhs);
4148 if (!expr.type->isIntegral()) {
4149 if (expr.type->isUnpackedArray()) {
4150 mlir::emitError(loc,
4151 "unpacked arrays in 'inside' expressions not supported");
4155 loc,
"only simple bit vectors supported in 'inside' expressions");
4162 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 Value convertRealMathTwoBI(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 two arguments.
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 void ensureDescendingOrder(RangeT &range, const slang::ast::Type &type)
Ensures that the given range is in "descending" order.
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 LogicalResult emitScanAssignments(Context &context, const Context::ScanStringResult &result, Location loc)
static Value getIsUnknown(OpBuilder &builder, Location loc, Value value, moore::IntType valTy, MLIRContext *ctx)
Check if a Moore integer value contains any unknown (x/z) bits.
static uint64_t getTimeScaleInFemtoseconds(Context &context)
Get the currently active timescale as an integer number of femtoseconds.
static Value coerceToBuiltinInt(OpBuilder &builder, Location loc, Value value, moore::IntType valTy)
Coerce a Moore integer value to a builtin integer, handling four-valued inputs by first mapping x/z t...
static FVInt convertSVIntToFVInt(const slang::SVInt &svint)
Convert a Slang SVInt to a CIRCT FVInt.
Four-valued arbitrary precision integers.
static FVInt getAllX(unsigned numBits)
Construct an FVInt with all bits set to X.
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.
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.
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")
@ f64
A 64-bit double-precision floation point number ("double")
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
FailureOr< ScanStringResult > convertScanString(StringRef formatStr, Value initialCursor, std::span< const slang::ast::Expression *const > destinations, Location loc)
Convert a scan format string into a consuming chain of moore.scan.
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 materializePackedToSBVConversion(Value value, Location loc, bool fallible)
Helper function to convert a PackedType value to its simple bit vector representation,...
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.
FunctionLowering * currentFunctionLowering
The function currently being converted, if any.
std::optional< std::pair< const slang::ast::InstanceSymbol *, mlir::StringAttr > > buildHierValueKey(const slang::ast::HierarchicalValueExpression &expr)
Build a composite key for hierValueSymbols from a hierarchical value expression.
MLIRContext * getContext()
Return the MLIR context.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.
Function lowering information.
SmallVector< const slang::ast::ValueSymbol *, 4 > capturedSymbols
The AST symbols captured by this function, determined by the capture analysis pre-pass.
mlir::FunctionOpInterface op