10#include "slang/ast/EvalContext.h"
11#include "slang/ast/SystemSubroutine.h"
12#include "slang/syntax/AllSyntax.h"
13#include "llvm/ADT/ScopeExit.h"
16using namespace ImportVerilog;
21 if (svint.hasUnknown()) {
22 unsigned numWords = svint.getNumWords() / 2;
23 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), numWords);
24 auto unknown = ArrayRef<uint64_t>(svint.getRawPtr() + numWords, numWords);
25 return FVInt(APInt(svint.getBitWidth(), value),
26 APInt(svint.getBitWidth(), unknown));
28 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), svint.getNumWords());
29 return FVInt(APInt(svint.getBitWidth(), value));
36 const slang::ConstantRange &range) {
37 auto &builder = context.
builder;
38 auto indexType = cast<moore::UnpackedType>(index.getType());
41 auto lo = range.lower();
42 auto hi = range.upper();
43 auto offset = range.isLittleEndian() ? lo : hi;
46 const bool needSigned = (lo < 0) || (hi < 0);
49 const uint64_t maxAbs = std::max<uint64_t>(std::abs(lo), std::abs(hi));
54 unsigned want = needSigned
55 ? (llvm::Log2_64_Ceil(std::max<uint64_t>(1, maxAbs)) + 1)
56 : std::max<unsigned>(1, llvm::Log2_64_Ceil(maxAbs + 1));
59 const unsigned bw = std::max<unsigned>(want, indexType.getBitSize().value());
62 moore::IntType::get(index.getContext(), bw, indexType.getDomain());
66 if (range.isLittleEndian())
69 return moore::NegOp::create(builder, loc, index);
73 moore::ConstantOp::create(builder, loc, intType, offset, needSigned);
74 if (range.isLittleEndian())
75 return moore::SubOp::create(builder, loc, index, offsetConst);
77 return moore::SubOp::create(builder, loc, offsetConst, index);
82 static_assert(int(slang::TimeUnit::Seconds) == 0);
83 static_assert(int(slang::TimeUnit::Milliseconds) == 1);
84 static_assert(int(slang::TimeUnit::Microseconds) == 2);
85 static_assert(int(slang::TimeUnit::Nanoseconds) == 3);
86 static_assert(int(slang::TimeUnit::Picoseconds) == 4);
87 static_assert(int(slang::TimeUnit::Femtoseconds) == 5);
89 static_assert(int(slang::TimeScaleMagnitude::One) == 1);
90 static_assert(int(slang::TimeScaleMagnitude::Ten) == 10);
91 static_assert(int(slang::TimeScaleMagnitude::Hundred) == 100);
93 auto exp =
static_cast<unsigned>(context.
timeScale.base.unit);
96 auto scale =
static_cast<uint64_t
>(context.
timeScale.base.magnitude);
110 ExprVisitor(
Context &context, Location loc,
bool isLvalue)
111 : context(context), loc(loc), builder(context.builder),
112 isLvalue(isLvalue) {}
118 Value convertLvalueOrRvalueExpression(
const slang::ast::Expression &expr) {
125 Value visit(
const slang::ast::ElementSelectExpression &expr) {
127 auto value = convertLvalueOrRvalueExpression(expr.value());
132 auto derefType = value.getType();
134 derefType = cast<moore::RefType>(derefType).getNestedType();
135 if (!isa<moore::IntType, moore::ArrayType, moore::UnpackedArrayType>(
137 mlir::emitError(loc) <<
"unsupported expression: element select into "
138 << expr.value().type->toString() <<
"\n";
143 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
144 auto range = expr.value().type->getFixedRange();
145 if (
auto *constValue = expr.selector().getConstant();
146 constValue && constValue->isInteger()) {
147 assert(!constValue->hasUnknown());
148 assert(constValue->size() <= 32);
150 auto lowBit = constValue->integer().as<uint32_t>().value();
152 return moore::ExtractRefOp::create(builder, loc, resultType, value,
153 range.translateIndex(lowBit));
155 return moore::ExtractOp::create(builder, loc, resultType, value,
156 range.translateIndex(lowBit));
164 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
167 return moore::DynExtractOp::create(builder, loc, resultType, value,
172 Value visit(
const slang::ast::RangeSelectExpression &expr) {
174 auto value = convertLvalueOrRvalueExpression(expr.value());
178 std::optional<int32_t> constLeft;
179 std::optional<int32_t> constRight;
180 if (
auto *constant = expr.left().getConstant())
181 constLeft = constant->integer().as<int32_t>();
182 if (
auto *constant = expr.right().getConstant())
183 constRight = constant->integer().as<int32_t>();
189 <<
"unsupported expression: range select with non-constant bounds";
209 int32_t offsetConst = 0;
210 auto range = expr.value().type->getFixedRange();
212 using slang::ast::RangeSelectionKind;
213 if (expr.getSelectionKind() == RangeSelectionKind::Simple) {
218 assert(constRight &&
"constness checked in slang");
219 offsetConst = *constRight;
230 offsetConst = *constLeft;
241 int32_t offsetAdd = 0;
246 if (expr.getSelectionKind() == RangeSelectionKind::IndexedDown &&
247 range.isLittleEndian()) {
248 assert(constRight &&
"constness checked in slang");
249 offsetAdd = 1 - *constRight;
255 if (expr.getSelectionKind() == RangeSelectionKind::IndexedUp &&
256 !range.isLittleEndian()) {
257 assert(constRight &&
"constness checked in slang");
258 offsetAdd = *constRight - 1;
262 if (offsetAdd != 0) {
264 offsetDyn = moore::AddOp::create(
265 builder, loc, offsetDyn,
266 moore::ConstantOp::create(
267 builder, loc, cast<moore::IntType>(offsetDyn.getType()),
271 offsetConst += offsetAdd;
282 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
287 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
290 return moore::DynExtractOp::create(builder, loc, resultType, value,
294 offsetConst = range.translateIndex(offsetConst);
296 return moore::ExtractRefOp::create(builder, loc, resultType, value,
299 return moore::ExtractOp::create(builder, loc, resultType, value,
306 Value visit(
const slang::ast::ConcatenationExpression &expr) {
307 SmallVector<Value> operands;
308 for (
auto *operand : expr.operands()) {
312 if (operand->type->isVoid())
314 auto value = convertLvalueOrRvalueExpression(*operand);
321 operands.push_back(value);
324 return moore::ConcatRefOp::create(builder, loc, operands);
326 return moore::ConcatOp::create(builder, loc, operands);
330 Value visit(
const slang::ast::MemberAccessExpression &expr) {
335 auto *valueType = expr.value().type.get();
336 auto memberName = builder.getStringAttr(expr.member.name);
339 if (valueType->isStruct()) {
341 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
343 auto value = convertLvalueOrRvalueExpression(expr.value());
348 return moore::StructExtractRefOp::create(builder, loc, resultType,
350 return moore::StructExtractOp::create(builder, loc, resultType,
355 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
357 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
359 auto value = convertLvalueOrRvalueExpression(expr.value());
364 return moore::UnionExtractRefOp::create(builder, loc, resultType,
366 return moore::UnionExtractOp::create(builder, loc, type, memberName,
371 if (valueType->isClass()) {
376 auto targetTy = dyn_cast<moore::ClassHandleType>(valTy);
381 auto upcastTargetTy =
393 mlir::FlatSymbolRefAttr::get(builder.getContext(), expr.member.name);
394 auto fieldRefTy = moore::RefType::get(cast<moore::UnpackedType>(type));
397 Value fieldRef = moore::ClassPropertyRefOp::create(
398 builder, loc, fieldRefTy, baseVal, fieldSym);
401 return isLvalue ? fieldRef
402 : moore::ReadOp::create(builder, loc, fieldRef);
405 mlir::emitError(loc,
"expression of type ")
406 << valueType->toString() <<
" has no member fields";
418struct RvalueExprVisitor :
public ExprVisitor {
419 RvalueExprVisitor(
Context &context, Location loc)
420 : ExprVisitor(context, loc, false) {}
421 using ExprVisitor::visit;
424 Value visit(
const slang::ast::LValueReferenceExpression &expr) {
427 return moore::ReadOp::create(builder, loc, lvalue);
431 Value visit(
const slang::ast::NamedValueExpression &expr) {
432 if (
auto value = context.
valueSymbols.lookup(&expr.symbol)) {
433 if (isa<moore::RefType>(value.getType())) {
434 auto readOp = moore::ReadOp::create(builder, loc, value);
437 value = readOp.getResult();
443 if (
auto *
const property =
444 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
450 mlir::emitError(loc) <<
"class property '" <<
property->name
451 <<
"' referenced without an implicit 'this'";
456 mlir::FlatSymbolRefAttr::get(builder.getContext(), property->name);
457 auto fieldTy = cast<moore::UnpackedType>(type);
458 auto fieldRefTy = moore::RefType::get(fieldTy);
460 moore::ClassHandleType classTy =
461 cast<moore::ClassHandleType>(instRef.getType());
463 auto targetClassHandle =
466 false, instRef.getLoc());
468 Value fieldRef = moore::ClassPropertyRefOp::create(
469 builder, loc, fieldRefTy, upcastRef, fieldSym);
470 return moore::ReadOp::create(builder, loc, fieldRef).getResult();
480 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
482 <<
"no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
487 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
489 if (
auto value = context.
valueSymbols.lookup(&expr.symbol)) {
490 if (isa<moore::RefType>(value.getType())) {
491 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
494 value = readOp.getResult();
501 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
502 << expr.symbol.name <<
"`";
503 d.attachNote(hierLoc) <<
"no rvalue generated for "
504 << slang::ast::toString(expr.symbol.kind);
509 Value visit(
const slang::ast::ConversionExpression &expr) {
517 Value visit(
const slang::ast::AssignmentExpression &expr) {
525 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
533 if (!expr.isNonBlocking()) {
534 if (expr.timingControl)
537 auto assignOp = moore::BlockingAssignOp::create(builder, loc, lhs, rhs);
544 if (expr.timingControl) {
546 if (
auto *ctrl = expr.timingControl->as_if<slang::ast::DelayControl>()) {
548 ctrl->expr, moore::TimeType::get(builder.getContext()));
551 auto assignOp = moore::DelayedNonBlockingAssignOp::create(
552 builder, loc, lhs, rhs, delay);
561 <<
"unsupported non-blocking assignment timing control: "
562 << slang::ast::toString(expr.timingControl->kind);
565 auto assignOp = moore::NonBlockingAssignOp::create(builder, loc, lhs, rhs);
573 template <
class ConcreteOp>
574 Value createReduction(Value arg,
bool invert) {
578 Value result = ConcreteOp::create(builder, loc, arg);
580 result = moore::NotOp::create(builder, loc, result);
585 Value createIncrement(Value arg,
bool isInc,
bool isPost) {
586 auto preValue = moore::ReadOp::create(builder, loc, arg);
592 postValue = moore::NotOp::create(builder, loc, preValue).getResult();
595 auto one = moore::ConstantOp::create(
596 builder, loc, cast<moore::IntType>(preValue.getType()), 1);
598 isInc ? moore::AddOp::create(builder, loc, preValue, one).getResult()
599 : moore::SubOp::create(builder, loc, preValue, one).getResult();
601 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
612 Value createRealIncrement(Value arg,
bool isInc,
bool isPost) {
613 auto preValue = moore::ReadOp::create(builder, loc, arg);
616 auto ty = preValue.getType();
617 moore::RealType realTy = llvm::dyn_cast<moore::RealType>(ty);
622 if (realTy.getWidth() == moore::RealWidth::f32) {
623 oneAttr = builder.getFloatAttr(builder.getF32Type(), 1.0);
624 }
else if (realTy.getWidth() == moore::RealWidth::f64) {
625 oneAttr = builder.getFloatAttr(builder.getF64Type(), 1.0);
627 mlir::emitError(loc) <<
"cannot construct increment for " << realTy;
630 auto one = moore::ConstantRealOp::create(builder, loc, oneAttr);
634 ? moore::AddRealOp::create(builder, loc, preValue, one).getResult()
635 : moore::SubRealOp::create(builder, loc, preValue, one).getResult();
637 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
647 Value visitRealUOp(
const slang::ast::UnaryExpression &expr) {
648 Type opFTy = context.
convertType(*expr.operand().type);
650 using slang::ast::UnaryOperator;
652 if (expr.op == UnaryOperator::Preincrement ||
653 expr.op == UnaryOperator::Predecrement ||
654 expr.op == UnaryOperator::Postincrement ||
655 expr.op == UnaryOperator::Postdecrement)
664 case UnaryOperator::Plus:
666 case UnaryOperator::Minus:
667 return moore::NegRealOp::create(builder, loc, arg);
669 case UnaryOperator::Preincrement:
670 return createRealIncrement(arg,
true,
false);
671 case UnaryOperator::Predecrement:
672 return createRealIncrement(arg,
false,
false);
673 case UnaryOperator::Postincrement:
674 return createRealIncrement(arg,
true,
true);
675 case UnaryOperator::Postdecrement:
676 return createRealIncrement(arg,
false,
true);
678 case UnaryOperator::LogicalNot:
682 return moore::NotOp::create(builder, loc, arg);
685 mlir::emitError(loc) <<
"Unary operator " << slang::ast::toString(expr.op)
686 <<
" not supported with real values!\n";
692 Value visit(
const slang::ast::UnaryExpression &expr) {
694 const auto *floatType =
695 expr.operand().type->as_if<slang::ast::FloatingType>();
698 return visitRealUOp(expr);
700 using slang::ast::UnaryOperator;
702 if (expr.op == UnaryOperator::Preincrement ||
703 expr.op == UnaryOperator::Predecrement ||
704 expr.op == UnaryOperator::Postincrement ||
705 expr.op == UnaryOperator::Postdecrement)
715 case UnaryOperator::Plus:
718 case UnaryOperator::Minus:
722 return moore::NegOp::create(builder, loc, arg);
724 case UnaryOperator::BitwiseNot:
728 return moore::NotOp::create(builder, loc, arg);
730 case UnaryOperator::BitwiseAnd:
731 return createReduction<moore::ReduceAndOp>(arg,
false);
732 case UnaryOperator::BitwiseOr:
733 return createReduction<moore::ReduceOrOp>(arg,
false);
734 case UnaryOperator::BitwiseXor:
735 return createReduction<moore::ReduceXorOp>(arg,
false);
736 case UnaryOperator::BitwiseNand:
737 return createReduction<moore::ReduceAndOp>(arg,
true);
738 case UnaryOperator::BitwiseNor:
739 return createReduction<moore::ReduceOrOp>(arg,
true);
740 case UnaryOperator::BitwiseXnor:
741 return createReduction<moore::ReduceXorOp>(arg,
true);
743 case UnaryOperator::LogicalNot:
747 return moore::NotOp::create(builder, loc, arg);
749 case UnaryOperator::Preincrement:
750 return createIncrement(arg,
true,
false);
751 case UnaryOperator::Predecrement:
752 return createIncrement(arg,
false,
false);
753 case UnaryOperator::Postincrement:
754 return createIncrement(arg,
true,
true);
755 case UnaryOperator::Postdecrement:
756 return createIncrement(arg,
false,
true);
759 mlir::emitError(loc,
"unsupported unary operator");
764 Value buildLogicalBOp(slang::ast::BinaryOperator op, Value lhs, Value rhs,
765 std::optional<Domain> domain = std::nullopt) {
766 using slang::ast::BinaryOperator;
781 case BinaryOperator::LogicalAnd:
782 return moore::AndOp::create(builder, loc, lhs, rhs);
784 case BinaryOperator::LogicalOr:
785 return moore::OrOp::create(builder, loc, lhs, rhs);
787 case BinaryOperator::LogicalImplication: {
789 auto notLHS = moore::NotOp::create(builder, loc, lhs);
790 return moore::OrOp::create(builder, loc, notLHS, rhs);
793 case BinaryOperator::LogicalEquivalence: {
795 auto notLHS = moore::NotOp::create(builder, loc, lhs);
796 auto notRHS = moore::NotOp::create(builder, loc, rhs);
797 auto both = moore::AndOp::create(builder, loc, lhs, rhs);
798 auto notBoth = moore::AndOp::create(builder, loc, notLHS, notRHS);
799 return moore::OrOp::create(builder, loc, both, notBoth);
803 llvm_unreachable(
"not a logical BinaryOperator");
807 Value visitRealBOp(
const slang::ast::BinaryExpression &expr) {
816 using slang::ast::BinaryOperator;
818 case BinaryOperator::Add:
819 return moore::AddRealOp::create(builder, loc, lhs, rhs);
820 case BinaryOperator::Subtract:
821 return moore::SubRealOp::create(builder, loc, lhs, rhs);
822 case BinaryOperator::Multiply:
823 return moore::MulRealOp::create(builder, loc, lhs, rhs);
824 case BinaryOperator::Divide:
825 return moore::DivRealOp::create(builder, loc, lhs, rhs);
826 case BinaryOperator::Power:
827 return moore::PowRealOp::create(builder, loc, lhs, rhs);
829 case BinaryOperator::Equality:
830 return moore::EqRealOp::create(builder, loc, lhs, rhs);
831 case BinaryOperator::Inequality:
832 return moore::NeRealOp::create(builder, loc, lhs, rhs);
834 case BinaryOperator::GreaterThan:
835 return moore::FgtOp::create(builder, loc, lhs, rhs);
836 case BinaryOperator::LessThan:
837 return moore::FltOp::create(builder, loc, lhs, rhs);
838 case BinaryOperator::GreaterThanEqual:
839 return moore::FgeOp::create(builder, loc, lhs, rhs);
840 case BinaryOperator::LessThanEqual:
841 return moore::FleOp::create(builder, loc, lhs, rhs);
843 case BinaryOperator::LogicalAnd:
844 case BinaryOperator::LogicalOr:
845 case BinaryOperator::LogicalImplication:
846 case BinaryOperator::LogicalEquivalence:
847 return buildLogicalBOp(expr.op, lhs, rhs);
850 mlir::emitError(loc) <<
"Binary operator "
851 << slang::ast::toString(expr.op)
852 <<
" not supported with real valued operands!\n";
859 template <
class ConcreteOp>
860 Value createBinary(Value lhs, Value rhs) {
867 return ConcreteOp::create(builder, loc, lhs, rhs);
871 Value visit(
const slang::ast::BinaryExpression &expr) {
873 const auto *rhsFloatType =
874 expr.right().type->as_if<slang::ast::FloatingType>();
875 const auto *lhsFloatType =
876 expr.left().type->as_if<slang::ast::FloatingType>();
879 if (rhsFloatType || lhsFloatType)
880 return visitRealBOp(expr);
890 Domain domain = Domain::TwoValued;
891 if (expr.type->isFourState() || expr.left().type->isFourState() ||
892 expr.right().type->isFourState())
893 domain = Domain::FourValued;
895 using slang::ast::BinaryOperator;
897 case BinaryOperator::Add:
898 return createBinary<moore::AddOp>(lhs, rhs);
899 case BinaryOperator::Subtract:
900 return createBinary<moore::SubOp>(lhs, rhs);
901 case BinaryOperator::Multiply:
902 return createBinary<moore::MulOp>(lhs, rhs);
903 case BinaryOperator::Divide:
904 if (expr.type->isSigned())
905 return createBinary<moore::DivSOp>(lhs, rhs);
907 return createBinary<moore::DivUOp>(lhs, rhs);
908 case BinaryOperator::Mod:
909 if (expr.type->isSigned())
910 return createBinary<moore::ModSOp>(lhs, rhs);
912 return createBinary<moore::ModUOp>(lhs, rhs);
913 case BinaryOperator::Power: {
919 lhs.getType(), rhs, expr.right().type->isSigned(), rhs.getLoc());
920 if (expr.type->isSigned())
921 return createBinary<moore::PowSOp>(lhs, rhsCast);
923 return createBinary<moore::PowUOp>(lhs, rhsCast);
926 case BinaryOperator::BinaryAnd:
927 return createBinary<moore::AndOp>(lhs, rhs);
928 case BinaryOperator::BinaryOr:
929 return createBinary<moore::OrOp>(lhs, rhs);
930 case BinaryOperator::BinaryXor:
931 return createBinary<moore::XorOp>(lhs, rhs);
932 case BinaryOperator::BinaryXnor: {
933 auto result = createBinary<moore::XorOp>(lhs, rhs);
936 return moore::NotOp::create(builder, loc, result);
939 case BinaryOperator::Equality:
940 if (isa<moore::UnpackedArrayType>(lhs.getType()))
941 return moore::UArrayCmpOp::create(
942 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
943 else if (isa<moore::StringType>(lhs.getType()))
944 return moore::StringCmpOp::create(
945 builder, loc, moore::StringCmpPredicate::eq, lhs, rhs);
947 return createBinary<moore::EqOp>(lhs, rhs);
948 case BinaryOperator::Inequality:
949 if (isa<moore::UnpackedArrayType>(lhs.getType()))
950 return moore::UArrayCmpOp::create(
951 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
952 else if (isa<moore::StringType>(lhs.getType()))
953 return moore::StringCmpOp::create(
954 builder, loc, moore::StringCmpPredicate::ne, lhs, rhs);
956 return createBinary<moore::NeOp>(lhs, rhs);
957 case BinaryOperator::CaseEquality:
958 return createBinary<moore::CaseEqOp>(lhs, rhs);
959 case BinaryOperator::CaseInequality:
960 return createBinary<moore::CaseNeOp>(lhs, rhs);
961 case BinaryOperator::WildcardEquality:
962 return createBinary<moore::WildcardEqOp>(lhs, rhs);
963 case BinaryOperator::WildcardInequality:
964 return createBinary<moore::WildcardNeOp>(lhs, rhs);
966 case BinaryOperator::GreaterThanEqual:
967 if (expr.left().type->isSigned())
968 return createBinary<moore::SgeOp>(lhs, rhs);
969 else if (isa<moore::StringType>(lhs.getType()))
970 return moore::StringCmpOp::create(
971 builder, loc, moore::StringCmpPredicate::ge, lhs, rhs);
973 return createBinary<moore::UgeOp>(lhs, rhs);
974 case BinaryOperator::GreaterThan:
975 if (expr.left().type->isSigned())
976 return createBinary<moore::SgtOp>(lhs, rhs);
977 else if (isa<moore::StringType>(lhs.getType()))
978 return moore::StringCmpOp::create(
979 builder, loc, moore::StringCmpPredicate::gt, lhs, rhs);
981 return createBinary<moore::UgtOp>(lhs, rhs);
982 case BinaryOperator::LessThanEqual:
983 if (expr.left().type->isSigned())
984 return createBinary<moore::SleOp>(lhs, rhs);
985 else if (isa<moore::StringType>(lhs.getType()))
986 return moore::StringCmpOp::create(
987 builder, loc, moore::StringCmpPredicate::le, lhs, rhs);
989 return createBinary<moore::UleOp>(lhs, rhs);
990 case BinaryOperator::LessThan:
991 if (expr.left().type->isSigned())
992 return createBinary<moore::SltOp>(lhs, rhs);
993 else if (isa<moore::StringType>(lhs.getType()))
994 return moore::StringCmpOp::create(
995 builder, loc, moore::StringCmpPredicate::lt, lhs, rhs);
997 return createBinary<moore::UltOp>(lhs, rhs);
999 case BinaryOperator::LogicalAnd:
1000 case BinaryOperator::LogicalOr:
1001 case BinaryOperator::LogicalImplication:
1002 case BinaryOperator::LogicalEquivalence:
1003 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1005 case BinaryOperator::LogicalShiftLeft:
1006 return createBinary<moore::ShlOp>(lhs, rhs);
1007 case BinaryOperator::LogicalShiftRight:
1008 return createBinary<moore::ShrOp>(lhs, rhs);
1009 case BinaryOperator::ArithmeticShiftLeft:
1010 return createBinary<moore::ShlOp>(lhs, rhs);
1011 case BinaryOperator::ArithmeticShiftRight: {
1018 if (expr.type->isSigned())
1019 return moore::AShrOp::create(builder, loc, lhs, rhs);
1020 return moore::ShrOp::create(builder, loc, lhs, rhs);
1024 mlir::emitError(loc,
"unsupported binary operator");
1029 Value visit(
const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
1034 Value visit(
const slang::ast::IntegerLiteral &expr) {
1039 Value visit(
const slang::ast::TimeLiteral &expr) {
1044 double value = std::round(expr.getValue() * scale);
1054 static constexpr uint64_t limit =
1055 (std::numeric_limits<uint64_t>::max() >> 11) << 11;
1056 if (value > limit) {
1057 mlir::emitError(loc) <<
"time value is larger than " << limit <<
" fs";
1061 return moore::ConstantTimeOp::create(builder, loc,
1062 static_cast<uint64_t
>(value));
1066 Value visit(
const slang::ast::ReplicationExpression &expr) {
1071 return moore::ReplicateOp::create(builder, loc, type, value);
1075 Value visit(
const slang::ast::InsideExpression &expr) {
1081 SmallVector<Value> conditions;
1084 for (
const auto *listExpr : expr.rangeList()) {
1088 if (
const auto *openRange =
1089 listExpr->as_if<slang::ast::ValueRangeExpression>()) {
1095 if (!lowBound || !highBound)
1097 Value leftValue, rightValue;
1100 if (openRange->left().type->isSigned() ||
1101 expr.left().type->isSigned()) {
1102 leftValue = moore::SgeOp::create(builder, loc, lhs, lowBound);
1104 leftValue = moore::UgeOp::create(builder, loc, lhs, lowBound);
1106 if (openRange->right().type->isSigned() ||
1107 expr.left().type->isSigned()) {
1108 rightValue = moore::SleOp::create(builder, loc, lhs, highBound);
1110 rightValue = moore::UleOp::create(builder, loc, lhs, highBound);
1112 cond = moore::AndOp::create(builder, loc, leftValue, rightValue);
1115 if (!listExpr->type->isIntegral()) {
1116 if (listExpr->type->isUnpackedArray()) {
1118 loc,
"unpacked arrays in 'inside' expressions not supported");
1122 loc,
"only simple bit vectors supported in 'inside' expressions");
1130 cond = moore::WildcardEqOp::create(builder, loc, lhs, value);
1132 conditions.push_back(cond);
1136 auto result = conditions.back();
1137 conditions.pop_back();
1138 while (!conditions.empty()) {
1139 result = moore::OrOp::create(builder, loc, conditions.back(), result);
1140 conditions.pop_back();
1146 Value visit(
const slang::ast::ConditionalExpression &expr) {
1150 if (expr.conditions.size() > 1) {
1151 mlir::emitError(loc)
1152 <<
"unsupported conditional expression with more than one condition";
1155 const auto &cond = expr.conditions[0];
1157 mlir::emitError(loc) <<
"unsupported conditional expression with pattern";
1164 auto conditionalOp =
1165 moore::ConditionalOp::create(builder, loc, type, value);
1168 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
1169 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
1171 OpBuilder::InsertionGuard g(builder);
1174 builder.setInsertionPointToStart(&trueBlock);
1178 moore::YieldOp::create(builder, loc, trueValue);
1181 builder.setInsertionPointToStart(&falseBlock);
1185 moore::YieldOp::create(builder, loc, falseValue);
1187 return conditionalOp.getResult();
1191 Value visit(
const slang::ast::CallExpression &expr) {
1198 [&](
auto &subroutine) {
return visitCall(expr, subroutine); },
1204 std::pair<Value, moore::ClassHandleType>
1205 getMethodReceiverTypeHandle(
const slang::ast::CallExpression &expr) {
1207 moore::ClassHandleType handleTy;
1211 if (
const slang::ast::Expression *recvExpr = expr.thisClass()) {
1219 mlir::emitError(loc) <<
"method '" << expr.getSubroutineName()
1220 <<
"' called without an object";
1224 handleTy = cast<moore::ClassHandleType>(thisRef.getType());
1225 return {thisRef, handleTy};
1230 buildMethodCall(
const slang::ast::SubroutineSymbol *subroutine,
1232 moore::ClassHandleType actualHandleTy, Value actualThisRef,
1233 SmallVector<Value> &arguments,
1234 SmallVector<Type> &resultTypes) {
1237 auto funcTy = lowering->
op.getFunctionType();
1238 auto expected0 = funcTy.getInput(0);
1239 auto expectedHdlTy = cast<moore::ClassHandleType>(expected0);
1243 expectedHdlTy, actualThisRef,
false, actualThisRef.getLoc());
1246 SmallVector<Value> explicitArguments;
1247 explicitArguments.reserve(arguments.size() + 1);
1248 explicitArguments.push_back(implicitThisRef);
1249 explicitArguments.append(arguments.begin(), arguments.end());
1252 const bool isVirtual =
1253 (subroutine->flags & slang::ast::MethodFlags::Virtual) != 0;
1258 SymbolRefAttr::get(context.
getContext(), lowering->
op.getSymName());
1259 return mlir::func::CallOp::create(builder, loc, resultTypes, calleeSym,
1263 mlir::emitError(loc) <<
"virtual method calls not supported";
1268 Value visitCall(
const slang::ast::CallExpression &expr,
1269 const slang::ast::SubroutineSymbol *subroutine) {
1271 const bool isMethod = (subroutine->thisVar !=
nullptr);
1278 if (failed(convertedFunction))
1284 SmallVector<Value> arguments;
1285 for (
auto [callArg, declArg] :
1286 llvm::zip(expr.arguments(), subroutine->getArguments())) {
1290 auto *expr = callArg;
1291 if (
const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
1292 expr = &assign->left();
1295 if (declArg->direction == slang::ast::ArgumentDirection::In)
1301 arguments.push_back(value);
1305 auto materializeCaptureAtCall = [&](Value cap) -> Value {
1307 auto refTy = dyn_cast<moore::RefType>(cap.getType());
1309 lowering->
op.emitError(
1310 "expected captured value to be moore::RefType");
1317 Region *capRegion = [&]() -> Region * {
1318 if (
auto ba = dyn_cast<BlockArgument>(cap))
1319 return ba.getOwner()->getParent();
1320 if (
auto *def = cap.getDefiningOp())
1321 return def->getParentRegion();
1325 Region *callRegion =
1326 builder.getBlock() ? builder.getBlock()->getParent() :
nullptr;
1328 for (Region *r = callRegion; r; r = r->getParentRegion()) {
1329 if (r == capRegion) {
1336 lowering->
op.emitError()
1337 <<
"cannot materialize captured ref at call site; non-symbol "
1339 << (cap.getDefiningOp()
1340 ? cap.getDefiningOp()->getName().getStringRef()
1345 for (Value cap : lowering->captures) {
1346 Value mat = materializeCaptureAtCall(cap);
1349 arguments.push_back(mat);
1354 SmallVector<Type> resultTypes(
1355 lowering->
op.getFunctionType().getResults().begin(),
1356 lowering->
op.getFunctionType().getResults().end());
1358 mlir::func::CallOp callOp;
1361 auto [thisRef, tyHandle] = getMethodReceiverTypeHandle(expr);
1362 callOp = buildMethodCall(subroutine, lowering, tyHandle, thisRef,
1363 arguments, resultTypes);
1367 mlir::func::CallOp::create(builder, loc, lowering->
op, arguments);
1370 auto result = resultTypes.size() > 0 ? callOp.getResult(0) : Value{};
1374 if (resultTypes.size() == 0)
1375 return mlir::UnrealizedConversionCastOp::create(
1376 builder, loc, moore::VoidType::get(context.
getContext()),
1384 Value visitCall(
const slang::ast::CallExpression &expr,
1385 const slang::ast::CallExpression::SystemCallInfo &info) {
1386 const auto &subroutine = *
info.subroutine;
1391 bool isAssertionCall =
1392 llvm::StringSwitch<bool>(subroutine.name)
1393 .Cases({
"$rose",
"$fell",
"$stable",
"$past"},
true)
1396 if (isAssertionCall)
1399 auto args = expr.arguments();
1401 FailureOr<Value> result;
1410 if (!subroutine.name.compare(
"$sformatf")) {
1413 expr.arguments(), loc, moore::IntFormat::Decimal,
false);
1414 if (failed(fmtValue))
1416 return fmtValue.value();
1425 switch (args.size()) {
1453 mlir::emitError(loc) <<
"unsupported system call `" << subroutine.name
1459 Value visit(
const slang::ast::StringLiteral &expr) {
1461 return moore::ConstantStringOp::create(builder, loc, type, expr.getValue());
1465 Value visit(
const slang::ast::RealLiteral &expr) {
1466 auto fTy = mlir::Float64Type::get(context.
getContext());
1467 auto attr = mlir::FloatAttr::get(fTy, expr.getValue());
1468 return moore::ConstantRealOp::create(builder, loc, attr).getResult();
1473 FailureOr<SmallVector<Value>>
1474 convertElements(
const slang::ast::AssignmentPatternExpressionBase &expr,
1475 std::variant<Type, ArrayRef<Type>> expectedTypes,
1476 unsigned replCount) {
1477 const auto &elts = expr.elements();
1478 const size_t elementCount = elts.size();
1481 const bool hasBroadcast =
1482 std::holds_alternative<Type>(expectedTypes) &&
1483 static_cast<bool>(std::get<Type>(expectedTypes));
1485 const bool hasPerElem =
1486 std::holds_alternative<ArrayRef<Type>>(expectedTypes) &&
1487 !std::get<ArrayRef<Type>>(expectedTypes).empty();
1491 auto types = std::get<ArrayRef<Type>>(expectedTypes);
1492 if (types.size() != elementCount) {
1493 mlir::emitError(loc)
1494 <<
"assignment pattern arity mismatch: expected " << types.size()
1495 <<
" elements, got " << elementCount;
1500 SmallVector<Value> converted;
1501 converted.reserve(elementCount * std::max(1u, replCount));
1504 if (!hasBroadcast && !hasPerElem) {
1506 for (
const auto *elementExpr : elts) {
1510 converted.push_back(v);
1512 }
else if (hasBroadcast) {
1514 Type want = std::get<Type>(expectedTypes);
1515 for (
const auto *elementExpr : elts) {
1520 converted.push_back(v);
1523 auto types = std::get<ArrayRef<Type>>(expectedTypes);
1524 for (
size_t i = 0; i < elementCount; ++i) {
1525 Type want = types[i];
1526 const auto *elementExpr = elts[i];
1531 converted.push_back(v);
1535 for (
unsigned i = 1; i < replCount; ++i)
1536 converted.append(converted.begin(), converted.begin() + elementCount);
1542 Value visitAssignmentPattern(
1543 const slang::ast::AssignmentPatternExpressionBase &expr,
1544 unsigned replCount = 1) {
1546 const auto &elts = expr.elements();
1549 if (
auto intType = dyn_cast<moore::IntType>(type)) {
1550 auto elements = convertElements(expr, {}, replCount);
1552 if (failed(elements))
1555 assert(intType.getWidth() == elements->size());
1556 std::reverse(elements->begin(), elements->end());
1557 return moore::ConcatOp::create(builder, loc, intType, *elements);
1561 if (
auto structType = dyn_cast<moore::StructType>(type)) {
1562 SmallVector<Type> expectedTy;
1563 expectedTy.reserve(structType.getMembers().size());
1564 for (
auto member : structType.getMembers())
1565 expectedTy.push_back(member.type);
1567 FailureOr<SmallVector<Value>> elements;
1568 if (expectedTy.size() == elts.size())
1569 elements = convertElements(expr, expectedTy, replCount);
1571 elements = convertElements(expr, {}, replCount);
1573 if (failed(elements))
1576 assert(structType.getMembers().size() == elements->size());
1577 return moore::StructCreateOp::create(builder, loc, structType, *elements);
1581 if (
auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
1582 SmallVector<Type> expectedTy;
1583 expectedTy.reserve(structType.getMembers().size());
1584 for (
auto member : structType.getMembers())
1585 expectedTy.push_back(member.type);
1587 FailureOr<SmallVector<Value>> elements;
1588 if (expectedTy.size() == elts.size())
1589 elements = convertElements(expr, expectedTy, replCount);
1591 elements = convertElements(expr, {}, replCount);
1593 if (failed(elements))
1596 assert(structType.getMembers().size() == elements->size());
1598 return moore::StructCreateOp::create(builder, loc, structType, *elements);
1602 if (
auto arrayType = dyn_cast<moore::ArrayType>(type)) {
1604 convertElements(expr, arrayType.getElementType(), replCount);
1606 if (failed(elements))
1609 assert(arrayType.getSize() == elements->size());
1610 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
1614 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
1616 convertElements(expr, arrayType.getElementType(), replCount);
1618 if (failed(elements))
1621 assert(arrayType.getSize() == elements->size());
1622 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
1625 mlir::emitError(loc) <<
"unsupported assignment pattern with type " << type;
1629 Value visit(
const slang::ast::SimpleAssignmentPatternExpression &expr) {
1630 return visitAssignmentPattern(expr);
1633 Value visit(
const slang::ast::StructuredAssignmentPatternExpression &expr) {
1634 return visitAssignmentPattern(expr);
1637 Value visit(
const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
1640 assert(count &&
"Slang guarantees constant non-zero replication count");
1641 return visitAssignmentPattern(expr, *count);
1644 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
1645 SmallVector<Value> operands;
1646 for (
auto stream : expr.streams()) {
1647 auto operandLoc = context.
convertLocation(stream.operand->sourceRange);
1648 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
1649 mlir::emitError(operandLoc)
1650 <<
"Moore only support streaming "
1651 "concatenation with fixed size 'with expression'";
1655 if (stream.constantWithWidth.has_value()) {
1657 auto type = cast<moore::UnpackedType>(value.getType());
1658 auto intType = moore::IntType::get(
1659 context.
getContext(), type.getBitSize().value(), type.getDomain());
1669 operands.push_back(value);
1673 if (operands.size() == 1) {
1676 value = operands.front();
1678 value = moore::ConcatOp::create(builder, loc, operands).getResult();
1681 if (expr.getSliceSize() == 0) {
1685 auto type = cast<moore::IntType>(value.getType());
1686 SmallVector<Value> slicedOperands;
1687 auto iterMax = type.getWidth() / expr.getSliceSize();
1688 auto remainSize = type.getWidth() % expr.getSliceSize();
1690 for (
size_t i = 0; i < iterMax; i++) {
1691 auto extractResultType = moore::IntType::get(
1692 context.
getContext(), expr.getSliceSize(), type.getDomain());
1694 auto extracted = moore::ExtractOp::create(builder, loc, extractResultType,
1695 value, i * expr.getSliceSize());
1696 slicedOperands.push_back(extracted);
1700 auto extractResultType = moore::IntType::get(
1701 context.
getContext(), remainSize, type.getDomain());
1704 moore::ExtractOp::create(builder, loc, extractResultType, value,
1705 iterMax * expr.getSliceSize());
1706 slicedOperands.push_back(extracted);
1709 return moore::ConcatOp::create(builder, loc, slicedOperands);
1712 Value visit(
const slang::ast::AssertionInstanceExpression &expr) {
1728 Value visit(
const slang::ast::NewClassExpression &expr) {
1730 auto classTy = dyn_cast<moore::ClassHandleType>(type);
1736 if (!classTy && expr.isSuperClass) {
1738 if (!newObj || !newObj.getType() ||
1739 !isa<moore::ClassHandleType>(newObj.getType())) {
1740 mlir::emitError(loc) <<
"implicit this ref was not set while "
1741 "converting new class function";
1744 auto thisType = cast<moore::ClassHandleType>(newObj.getType());
1746 cast<moore::ClassDeclOp>(*context.
symbolTable.lookupNearestSymbolFrom(
1748 auto baseClassSym = classDecl.getBase();
1749 classTy = circt::moore::ClassHandleType::get(context.
getContext(),
1750 baseClassSym.value());
1753 newObj = moore::ClassNewOp::create(builder, loc, classTy, {});
1756 const auto *constructor = expr.constructorCall();
1761 if (
const auto *callConstructor =
1762 constructor->as_if<slang::ast::CallExpression>())
1763 if (
const auto *subroutine =
1764 std::get_if<const slang::ast::SubroutineSymbol *>(
1765 &callConstructor->subroutine)) {
1768 if (!(*subroutine)->thisVar) {
1769 mlir::emitError(loc) <<
"Expected subroutine called by new to use an "
1770 "implicit this reference";
1779 llvm::make_scope_exit([&] { context.
currentThisRef = savedThis; });
1781 if (!visitCall(*callConstructor, *subroutine))
1790 template <
typename T>
1791 Value visit(T &&node) {
1792 mlir::emitError(loc,
"unsupported expression: ")
1793 << slang::ast::toString(node.kind);
1797 Value visitInvalid(
const slang::ast::Expression &expr) {
1798 mlir::emitError(loc,
"invalid expression");
1809struct LvalueExprVisitor :
public ExprVisitor {
1810 LvalueExprVisitor(
Context &context, Location loc)
1811 : ExprVisitor(context, loc, true) {}
1812 using ExprVisitor::visit;
1815 Value visit(
const slang::ast::NamedValueExpression &expr) {
1816 if (
auto value = context.
valueSymbols.lookup(&expr.symbol))
1818 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
1820 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
1825 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
1826 if (
auto value = context.
valueSymbols.lookup(&expr.symbol))
1831 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
1832 << expr.symbol.name <<
"`";
1834 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
1838 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
1839 SmallVector<Value> operands;
1840 for (
auto stream : expr.streams()) {
1841 auto operandLoc = context.
convertLocation(stream.operand->sourceRange);
1842 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
1843 mlir::emitError(operandLoc)
1844 <<
"Moore only support streaming "
1845 "concatenation with fixed size 'with expression'";
1849 if (stream.constantWithWidth.has_value()) {
1851 auto type = cast<moore::UnpackedType>(
1852 cast<moore::RefType>(value.getType()).getNestedType());
1853 auto intType = moore::RefType::get(moore::IntType::get(
1854 context.
getContext(), type.getBitSize().value(), type.getDomain()));
1863 operands.push_back(value);
1866 if (operands.size() == 1) {
1869 value = operands.front();
1871 value = moore::ConcatRefOp::create(builder, loc, operands).getResult();
1874 if (expr.getSliceSize() == 0) {
1878 auto type = cast<moore::IntType>(
1879 cast<moore::RefType>(value.getType()).getNestedType());
1880 SmallVector<Value> slicedOperands;
1881 auto widthSum = type.getWidth();
1882 auto domain = type.getDomain();
1883 auto iterMax = widthSum / expr.getSliceSize();
1884 auto remainSize = widthSum % expr.getSliceSize();
1886 for (
size_t i = 0; i < iterMax; i++) {
1887 auto extractResultType = moore::RefType::get(moore::IntType::get(
1888 context.
getContext(), expr.getSliceSize(), domain));
1890 auto extracted = moore::ExtractRefOp::create(
1891 builder, loc, extractResultType, value, i * expr.getSliceSize());
1892 slicedOperands.push_back(extracted);
1896 auto extractResultType = moore::RefType::get(
1897 moore::IntType::get(context.
getContext(), remainSize, domain));
1900 moore::ExtractRefOp::create(builder, loc, extractResultType, value,
1901 iterMax * expr.getSliceSize());
1902 slicedOperands.push_back(extracted);
1905 return moore::ConcatRefOp::create(builder, loc, slicedOperands);
1909 template <
typename T>
1910 Value visit(T &&node) {
1914 Value visitInvalid(
const slang::ast::Expression &expr) {
1915 mlir::emitError(loc,
"invalid expression");
1925Value Context::convertRvalueExpression(
const slang::ast::Expression &expr,
1926 Type requiredType) {
1928 auto value = expr.visit(RvalueExprVisitor(*
this, loc));
1929 if (value && requiredType)
1937 return expr.visit(LvalueExprVisitor(*
this, loc));
1945 if (
auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
1946 if (type.getBitSize() == 1)
1948 if (
auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
1949 return moore::BoolCastOp::create(
builder, value.getLoc(), value);
1950 mlir::emitError(value.getLoc(),
"expression of type ")
1951 << value.getType() <<
" cannot be cast to a boolean";
1957 const slang::ast::Type &astType,
1959 const auto *floatType = astType.as_if<slang::ast::FloatingType>();
1963 if (svreal.isShortReal() &&
1964 floatType->floatKind == slang::ast::FloatingType::ShortReal) {
1965 attr = FloatAttr::get(
builder.getF32Type(), svreal.shortReal().v);
1966 }
else if (svreal.isReal() &&
1967 floatType->floatKind == slang::ast::FloatingType::Real) {
1968 attr = FloatAttr::get(
builder.getF64Type(), svreal.real().v);
1970 mlir::emitError(loc) <<
"invalid real constant";
1974 return moore::ConstantRealOp::create(
builder, loc, attr);
1979 const slang::ast::Type &astType,
1981 slang::ConstantValue intVal = stringLiteral.convertToInt();
1982 auto effectiveWidth = intVal.getEffectiveWidth();
1983 if (!effectiveWidth)
1986 auto intTy = moore::IntType::getInt(
getContext(), effectiveWidth.value());
1988 if (astType.isString()) {
1989 auto immInt = moore::ConstantStringOp::create(
builder, loc, intTy,
1990 stringLiteral.toString())
1992 return moore::IntToStringOp::create(
builder, loc, immInt).getResult();
1999 const slang::ast::Type &astType, Location loc) {
2004 bool typeIsFourValued =
false;
2005 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2009 auto intType = moore::IntType::get(
getContext(), fvint.getBitWidth(),
2010 fvint.hasUnknown() || typeIsFourValued
2013 auto result = moore::ConstantOp::create(
builder, loc, intType, fvint);
2018 const slang::ConstantValue &constant,
2019 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc) {
2027 if (astType.elementType.isIntegral())
2028 bitWidth = astType.elementType.getBitWidth();
2032 bool typeIsFourValued =
false;
2035 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2046 auto intType = moore::IntType::get(
getContext(), bitWidth, domain);
2048 auto arrType = moore::UnpackedArrayType::get(
2049 getContext(), constant.elements().size(), intType);
2051 llvm::SmallVector<mlir::Value> elemVals;
2052 moore::ConstantOp constOp;
2054 mlir::OpBuilder::InsertionGuard guard(
builder);
2057 for (
auto elem : constant.elements()) {
2059 constOp = moore::ConstantOp::create(
builder, loc, intType, fvInt);
2060 elemVals.push_back(constOp.getResult());
2065 auto arrayOp = moore::ArrayCreateOp::create(
builder, loc, arrType, elemVals);
2067 return arrayOp.getResult();
2071 const slang::ast::Type &type, Location loc) {
2073 if (
auto *arr = type.as_if<slang::ast::FixedSizeUnpackedArrayType>())
2075 if (constant.isInteger())
2077 if (constant.isReal() || constant.isShortReal())
2079 if (constant.isString())
2087 using slang::ast::EvalFlags;
2088 slang::ast::EvalContext evalContext(
2090 slang::ast::LookupLocation::max),
2091 EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
2092 return expr.eval(evalContext);
2101 auto type = moore::IntType::get(
getContext(), 1, domain);
2108 if (isa<moore::IntType>(value.getType()))
2115 if (
auto packed = dyn_cast<moore::PackedType>(value.getType()))
2116 if (
auto sbvType = packed.getSimpleBitVector())
2119 mlir::emitError(value.getLoc()) <<
"expression of type " << value.getType()
2120 <<
" cannot be cast to a simple bit vector";
2129 if (isa<moore::IntType>(value.getType()))
2132 auto &builder = context.
builder;
2133 auto packedType = cast<moore::PackedType>(value.getType());
2134 auto intType = packedType.getSimpleBitVector();
2139 if (isa<moore::TimeType>(packedType) &&
2141 value = builder.createOrFold<moore::TimeToLogicOp>(loc, value);
2142 auto scale = moore::ConstantOp::create(builder, loc, intType,
2144 return builder.createOrFold<moore::DivUOp>(loc, value, scale);
2150 if (packedType.containsTimeType()) {
2151 mlir::emitError(loc) <<
"unsupported conversion: " << packedType
2152 <<
" cannot be converted to " << intType
2153 <<
"; contains a time type";
2158 return builder.createOrFold<moore::PackedToSBVOp>(loc, value);
2166 Value value, Location loc) {
2167 if (value.getType() == packedType)
2170 auto &builder = context.
builder;
2171 auto intType = cast<moore::IntType>(value.getType());
2176 if (isa<moore::TimeType>(packedType) &&
2178 auto scale = moore::ConstantOp::create(builder, loc, intType,
2180 value = builder.createOrFold<moore::MulOp>(loc, value, scale);
2181 return builder.createOrFold<moore::LogicToTimeOp>(loc, value);
2188 mlir::emitError(loc) <<
"unsupported conversion: " << intType
2189 <<
" cannot be converted to " << packedType
2190 <<
"; contains a time type";
2195 return builder.createOrFold<moore::SBVToPackedOp>(loc, packedType, value);
2201 moore::ClassHandleType expectedHandleTy) {
2202 auto loc = actualHandle.getLoc();
2204 auto actualTy = actualHandle.getType();
2205 auto actualHandleTy = dyn_cast<moore::ClassHandleType>(actualTy);
2206 if (!actualHandleTy) {
2207 mlir::emitError(loc) <<
"expected a !moore.class<...> value, got "
2213 if (actualHandleTy == expectedHandleTy)
2214 return actualHandle;
2217 mlir::emitError(loc)
2218 <<
"receiver class " << actualHandleTy.getClassSym()
2219 <<
" is not the same as, or derived from, expected base class "
2220 << expectedHandleTy.getClassSym().getRootReference();
2225 auto casted = moore::ClassUpcastOp::create(context.
builder, loc,
2226 expectedHandleTy, actualHandle)
2234 if (type == value.getType())
2239 auto dstPacked = dyn_cast<moore::PackedType>(type);
2240 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
2241 auto dstInt = dstPacked ? dstPacked.getSimpleBitVector() : moore::IntType();
2242 auto srcInt = srcPacked ? srcPacked.getSimpleBitVector() : moore::IntType();
2244 if (dstInt && srcInt) {
2252 auto resizedType = moore::IntType::get(
2253 value.getContext(), dstInt.getWidth(), srcPacked.getDomain());
2254 if (dstInt.getWidth() < srcInt.getWidth()) {
2255 value =
builder.createOrFold<moore::TruncOp>(loc, resizedType, value);
2256 }
else if (dstInt.getWidth() > srcInt.getWidth()) {
2258 value =
builder.createOrFold<moore::SExtOp>(loc, resizedType, value);
2260 value =
builder.createOrFold<moore::ZExtOp>(loc, resizedType, value);
2264 if (dstInt.getDomain() != srcInt.getDomain()) {
2266 value =
builder.createOrFold<moore::LogicToIntOp>(loc, value);
2268 value =
builder.createOrFold<moore::IntToLogicOp>(loc, value);
2276 assert(value.getType() == type);
2281 if (isa<moore::StringType>(type) &&
2282 isa<moore::FormatStringType>(value.getType())) {
2283 return builder.createOrFold<moore::FormatStringToStringOp>(loc, value);
2287 if (isa<moore::FormatStringType>(type) &&
2288 isa<moore::StringType>(value.getType())) {
2289 return builder.createOrFold<moore::FormatStringOp>(loc, value);
2293 if (isa<moore::IntType>(type) && isa<moore::RealType>(value.getType())) {
2294 auto twoValInt =
builder.createOrFold<moore::RealToIntOp>(
2295 loc, dyn_cast<moore::IntType>(type).getTwoValued(), value);
2303 if (isa<moore::RealType>(type) && isa<moore::IntType>(value.getType())) {
2306 if (dyn_cast<moore::IntType>(value.getType()).getDomain() ==
2311 dyn_cast<moore::IntType>(value.getType()).getTwoValued(), value,
true,
2314 return builder.createOrFold<moore::IntToRealOp>(loc, type, twoValInt);
2317 if (isa<moore::ClassHandleType>(type) &&
2318 isa<moore::ClassHandleType>(value.getType()))
2322 if (value.getType() != type)
2323 value = moore::ConversionOp::create(
builder, loc, type, value);
2331 auto systemCallRes =
2332 llvm::StringSwitch<std::function<FailureOr<Value>()>>(subroutine.name)
2335 return moore::UrandomBIOp::create(
builder, loc,
nullptr);
2339 return moore::RandomBIOp::create(
builder, loc,
nullptr);
2343 [&]() -> Value {
return moore::TimeBIOp::create(
builder, loc); })
2346 [&]() -> Value {
return moore::TimeBIOp::create(
builder, loc); })
2349 [&]() -> Value {
return moore::TimeBIOp::create(
builder, loc); })
2350 .Default([&]() -> Value {
return {}; });
2351 return systemCallRes();
2356 Location loc, Value value) {
2357 auto systemCallRes =
2358 llvm::StringSwitch<std::function<FailureOr<Value>()>>(subroutine.name)
2360 .Case(
"$signed", [&]() {
return value; })
2361 .Case(
"$unsigned", [&]() {
return value; })
2365 [&]() -> FailureOr<Value> {
2369 return (Value)moore::Clog2BIOp::create(
builder, loc, value);
2373 return moore::LnBIOp::create(
builder, loc, value);
2377 return moore::Log10BIOp::create(
builder, loc, value);
2381 return moore::SinBIOp::create(
builder, loc, value);
2385 return moore::CosBIOp::create(
builder, loc, value);
2389 return moore::TanBIOp::create(
builder, loc, value);
2393 return moore::ExpBIOp::create(
builder, loc, value);
2397 return moore::SqrtBIOp::create(
builder, loc, value);
2401 return moore::FloorBIOp::create(
builder, loc, value);
2405 return moore::CeilBIOp::create(
builder, loc, value);
2409 return moore::AsinBIOp::create(
builder, loc, value);
2413 return moore::AcosBIOp::create(
builder, loc, value);
2417 return moore::AtanBIOp::create(
builder, loc, value);
2421 return moore::SinhBIOp::create(
builder, loc, value);
2425 return moore::CoshBIOp::create(
builder, loc, value);
2429 return moore::TanhBIOp::create(
builder, loc, value);
2433 return moore::AsinhBIOp::create(
builder, loc, value);
2437 return moore::AcoshBIOp::create(
builder, loc, value);
2441 return moore::AtanhBIOp::create(
builder, loc, value);
2445 return moore::UrandomBIOp::create(
builder, loc, value);
2449 return moore::RandomBIOp::create(
builder, loc, value);
2451 .Case(
"$realtobits",
2453 return moore::RealtobitsBIOp::create(
builder, loc, value);
2455 .Case(
"$bitstoreal",
2457 return moore::BitstorealBIOp::create(
builder, loc, value);
2459 .Case(
"$shortrealtobits",
2461 return moore::ShortrealtobitsBIOp::create(
builder, loc,
2464 .Case(
"$bitstoshortreal",
2466 return moore::BitstoshortrealBIOp::create(
builder, loc,
2471 if (isa<moore::StringType>(value.getType()))
2472 return moore::StringLenOp::create(
builder, loc, value);
2475 .Default([&]() -> Value {
return {}; });
2476 return systemCallRes();
2485 const moore::ClassHandleType &baseTy) {
2486 if (!actualTy || !baseTy)
2489 mlir::SymbolRefAttr actualSym = actualTy.getClassSym();
2490 mlir::SymbolRefAttr baseSym = baseTy.getClassSym();
2492 if (actualSym == baseSym)
2495 auto *op =
resolve(*
this, actualSym);
2496 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
2499 mlir::SymbolRefAttr curBase = decl.getBaseAttr();
2502 if (curBase == baseSym)
2504 decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(
resolve(*
this, curBase));
2509moore::ClassHandleType
2511 llvm::StringRef fieldName) {
2512 if (!actualTy || fieldName.empty())
2516 mlir::SymbolRefAttr classSym = actualTy.getClassSym();
2520 auto *op =
resolve(*
this, classSym);
2521 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
2526 for (
auto &block : decl.getBody()) {
2527 for (
auto &opInBlock : block) {
2529 llvm::dyn_cast<moore::ClassPropertyDeclOp>(&opInBlock)) {
2530 if (prop.getSymName() == fieldName) {
2532 return moore::ClassHandleType::get(actualTy.getContext(), classSym);
2539 classSym = decl.getBaseAttr();
assert(baseType &&"element must be base type")
static Value materializeSBVToPackedConversion(Context &context, moore::PackedType packedType, Value value, Location loc)
Create the necessary operations to convert from a simple bit vector IntType to an equivalent PackedTy...
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 uint64_t getTimeScaleInFemtoseconds(Context &context)
Get the currently active timescale as an integer number of femtoseconds.
static Value materializePackedToSBVConversion(Context &context, Value value, Location loc)
Create the necessary operations to convert from a PackedType to the corresponding simple bit vector I...
static Value getSelectIndex(Context &context, Location loc, Value index, const slang::ConstantRange &range)
Map an index into an array, with bounds range, to a bit offset of the underlying bit storage.
static FVInt convertSVIntToFVInt(const slang::SVInt &svint)
Convert a Slang SVInt to a CIRCT FVInt.
Four-valued arbitrary precision integers.
A packed SystemVerilog type.
bool containsTimeType() const
Check if this is a TimeType, or an aggregate that contains a nested TimeType.
IntType getSimpleBitVector() const
Get the simple bit vector type equivalent to this packed type.
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.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
LogicalResult convertFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function.
Value materializeConversion(Type type, Value value, bool isSigned, Location loc)
Helper function to insert the necessary operations to cast a value from one type to another.
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.
slang::ast::Compilation & compilation
LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl)
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.
Value convertAssertionCallExpression(const slang::ast::CallExpression &expr, const slang::ast::CallExpression::SystemCallInfo &info, Location loc)
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).
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.
slang::TimeScale timeScale
The time scale currently in effect.
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
std::function< void(mlir::Operation *)> variableAssignCallback
A listener called for every variable or net being assigned.
FailureOr< Value > convertFormatString(std::span< const slang::ast::Expression *const > arguments, Location loc, moore::IntFormat defaultFormat=moore::IntFormat::Decimal, bool appendNewline=false)
Convert a list of string literal arguments with formatting specifiers and arguments to be interpolate...
Value getImplicitThisRef() const
Value convertRvalueExpression(const slang::ast::Expression &expr, Type requiredType={})
FailureOr< Value > convertSystemCallArity0(const slang::ast::SystemSubroutine &subroutine, Location loc)
Convert system function calls only have arity-0.
Value convertToSimpleBitVector(Value value)
Helper function to convert a value to its simple bit vector representation, if it has one.
moore::ClassHandleType getAncestorClassWithProperty(const moore::ClassHandleType &actualTy, StringRef fieldName)
Tries to find the closest base class of actualTy that carries a property with name fieldName.
Value materializeString(const slang::ConstantValue &string, const slang::ast::Type &astType, Location loc)
Helper function to materialize a string as an SSA value.
Value currentThisRef
Variable to track the value of the current function's implicit this reference.
FailureOr< Value > convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value)
Convert system function calls only have arity-1.
mlir::ModuleOp intoModuleOp
SymbolTable symbolTable
A symbol table of the MLIR module we are emitting into.
FunctionLowering * declareFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function and its arguments to a function declaration in the IR.
Value convertAssertionExpression(const slang::ast::AssertionExpr &expr, Location loc)
MLIRContext * getContext()
Return the MLIR context.
SmallVector< Value > lvalueStack
A stack of assignment left-hand side values.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.
Function lowering information.
llvm::SmallVector< Value, 4 > captures