CIRCT 20.0.0git
Loading...
Searching...
No Matches
Expressions.cpp
Go to the documentation of this file.
1//===- Expressions.cpp - Slang expression conversion ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "slang/ast/SystemSubroutine.h"
11#include "slang/syntax/AllSyntax.h"
12
13using namespace circt;
14using namespace ImportVerilog;
15using moore::Domain;
16
17/// Convert a Slang `SVInt` to a CIRCT `FVInt`.
18static FVInt convertSVIntToFVInt(const slang::SVInt &svint) {
19 if (svint.hasUnknown()) {
20 unsigned numWords = svint.getNumWords() / 2;
21 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), numWords);
22 auto unknown = ArrayRef<uint64_t>(svint.getRawPtr() + numWords, numWords);
23 return FVInt(APInt(svint.getBitWidth(), value),
24 APInt(svint.getBitWidth(), unknown));
25 }
26 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), svint.getNumWords());
27 return FVInt(APInt(svint.getBitWidth(), value));
28}
29
30// NOLINTBEGIN(misc-no-recursion)
31namespace {
32struct RvalueExprVisitor {
33 Context &context;
34 Location loc;
35 OpBuilder &builder;
36
37 RvalueExprVisitor(Context &context, Location loc)
38 : context(context), loc(loc), builder(context.builder) {}
39
40 // Handle references to the left-hand side of a parent assignment.
41 Value visit(const slang::ast::LValueReferenceExpression &expr) {
42 assert(!context.lvalueStack.empty() && "parent assignments push lvalue");
43 auto lvalue = context.lvalueStack.back();
44 return builder.create<moore::ReadOp>(loc, lvalue);
45 }
46
47 // Handle named values, such as references to declared variables.
48 Value visit(const slang::ast::NamedValueExpression &expr) {
49 if (auto value = context.valueSymbols.lookup(&expr.symbol)) {
50 if (isa<moore::RefType>(value.getType())) {
51 auto readOp = builder.create<moore::ReadOp>(loc, value);
52 if (context.rvalueReadCallback)
53 context.rvalueReadCallback(readOp);
54 value = readOp.getResult();
55 }
56 return value;
57 }
58
59 // Try to materialize constant values directly.
60 auto constant = context.evaluateConstant(expr);
61 if (auto value = context.materializeConstant(constant, *expr.type, loc))
62 return value;
63
64 // Otherwise some other part of ImportVerilog should have added an MLIR
65 // value for this expression's symbol to the `context.valueSymbols` table.
66 auto d = mlir::emitError(loc, "unknown name `") << expr.symbol.name << "`";
67 d.attachNote(context.convertLocation(expr.symbol.location))
68 << "no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
69 return {};
70 }
71
72 // Handle hierarchical values, such as `x = Top.sub.var`.
73 Value visit(const slang::ast::HierarchicalValueExpression &expr) {
74 auto hierLoc = context.convertLocation(expr.symbol.location);
75 if (auto value = context.valueSymbols.lookup(&expr.symbol)) {
76 if (isa<moore::RefType>(value.getType())) {
77 auto readOp = builder.create<moore::ReadOp>(hierLoc, value);
78 if (context.rvalueReadCallback)
79 context.rvalueReadCallback(readOp);
80 value = readOp.getResult();
81 }
82 return value;
83 }
84
85 // Emit an error for those hierarchical values not recorded in the
86 // `valueSymbols`.
87 auto d = mlir::emitError(loc, "unknown hierarchical name `")
88 << expr.symbol.name << "`";
89 d.attachNote(hierLoc) << "no rvalue generated for "
90 << slang::ast::toString(expr.symbol.kind);
91 return {};
92 }
93
94 // Handle type conversions (explicit and implicit).
95 Value visit(const slang::ast::ConversionExpression &expr) {
96 auto type = context.convertType(*expr.type);
97 if (!type)
98 return {};
99 return context.convertRvalueExpression(expr.operand(), type);
100 }
101
102 // Handle blocking and non-blocking assignments.
103 Value visit(const slang::ast::AssignmentExpression &expr) {
104 auto lhs = context.convertLvalueExpression(expr.left());
105 if (!lhs)
106 return {};
107
108 context.lvalueStack.push_back(lhs);
109 auto rhs = context.convertRvalueExpression(
110 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
111 context.lvalueStack.pop_back();
112 if (!rhs)
113 return {};
114
115 if (expr.timingControl) {
116 auto loc = context.convertLocation(expr.timingControl->sourceRange);
117 mlir::emitError(loc, "delayed assignments not supported");
118 return {};
119 }
120
121 if (expr.isNonBlocking())
122 builder.create<moore::NonBlockingAssignOp>(loc, lhs, rhs);
123 else
124 builder.create<moore::BlockingAssignOp>(loc, lhs, rhs);
125 return rhs;
126 }
127
128 // Helper function to convert an argument to a simple bit vector type, pass it
129 // to a reduction op, and optionally invert the result.
130 template <class ConcreteOp>
131 Value createReduction(Value arg, bool invert) {
132 arg = context.convertToSimpleBitVector(arg);
133 if (!arg)
134 return {};
135 Value result = builder.create<ConcreteOp>(loc, arg);
136 if (invert)
137 result = builder.create<moore::NotOp>(loc, result);
138 return result;
139 }
140
141 // Helper function to create pre and post increments and decrements.
142 Value createIncrement(Value arg, bool isInc, bool isPost) {
143 auto preValue = builder.create<moore::ReadOp>(loc, arg);
144 auto one = builder.create<moore::ConstantOp>(
145 loc, cast<moore::IntType>(preValue.getType()), 1);
146 auto postValue =
147 isInc ? builder.create<moore::AddOp>(loc, preValue, one).getResult()
148 : builder.create<moore::SubOp>(loc, preValue, one).getResult();
149 builder.create<moore::BlockingAssignOp>(loc, arg, postValue);
150 if (isPost)
151 return preValue;
152 return postValue;
153 }
154
155 // Handle unary operators.
156 Value visit(const slang::ast::UnaryExpression &expr) {
157 using slang::ast::UnaryOperator;
158 Value arg;
159 if (expr.op == UnaryOperator::Preincrement ||
160 expr.op == UnaryOperator::Predecrement ||
161 expr.op == UnaryOperator::Postincrement ||
162 expr.op == UnaryOperator::Postdecrement)
163 arg = context.convertLvalueExpression(expr.operand());
164 else
165 arg = context.convertRvalueExpression(expr.operand());
166 if (!arg)
167 return {};
168
169 switch (expr.op) {
170 // `+a` is simply `a`, but converted to a simple bit vector type since
171 // this is technically an arithmetic operation.
172 case UnaryOperator::Plus:
173 return context.convertToSimpleBitVector(arg);
174
175 case UnaryOperator::Minus:
176 arg = context.convertToSimpleBitVector(arg);
177 if (!arg)
178 return {};
179 return builder.create<moore::NegOp>(loc, arg);
180
181 case UnaryOperator::BitwiseNot:
182 arg = context.convertToSimpleBitVector(arg);
183 if (!arg)
184 return {};
185 return builder.create<moore::NotOp>(loc, arg);
186
187 case UnaryOperator::BitwiseAnd:
188 return createReduction<moore::ReduceAndOp>(arg, false);
189 case UnaryOperator::BitwiseOr:
190 return createReduction<moore::ReduceOrOp>(arg, false);
191 case UnaryOperator::BitwiseXor:
192 return createReduction<moore::ReduceXorOp>(arg, false);
193 case UnaryOperator::BitwiseNand:
194 return createReduction<moore::ReduceAndOp>(arg, true);
195 case UnaryOperator::BitwiseNor:
196 return createReduction<moore::ReduceOrOp>(arg, true);
197 case UnaryOperator::BitwiseXnor:
198 return createReduction<moore::ReduceXorOp>(arg, true);
199
200 case UnaryOperator::LogicalNot:
201 arg = context.convertToBool(arg);
202 if (!arg)
203 return {};
204 return builder.create<moore::NotOp>(loc, arg);
205
206 case UnaryOperator::Preincrement:
207 return createIncrement(arg, true, false);
208 case UnaryOperator::Predecrement:
209 return createIncrement(arg, false, false);
210 case UnaryOperator::Postincrement:
211 return createIncrement(arg, true, true);
212 case UnaryOperator::Postdecrement:
213 return createIncrement(arg, false, true);
214 }
215
216 mlir::emitError(loc, "unsupported unary operator");
217 return {};
218 }
219
220 // Helper function to convert two arguments to a simple bit vector type and
221 // pass them into a binary op.
222 template <class ConcreteOp>
223 Value createBinary(Value lhs, Value rhs) {
224 lhs = context.convertToSimpleBitVector(lhs);
225 if (!lhs)
226 return {};
227 rhs = context.convertToSimpleBitVector(rhs);
228 if (!rhs)
229 return {};
230 return builder.create<ConcreteOp>(loc, lhs, rhs);
231 }
232
233 // Handle binary operators.
234 Value visit(const slang::ast::BinaryExpression &expr) {
235 auto lhs = context.convertRvalueExpression(expr.left());
236 if (!lhs)
237 return {};
238 auto rhs = context.convertRvalueExpression(expr.right());
239 if (!rhs)
240 return {};
241
242 // Determine the domain of the result.
243 Domain domain = Domain::TwoValued;
244 if (expr.type->isFourState() || expr.left().type->isFourState() ||
245 expr.right().type->isFourState())
246 domain = Domain::FourValued;
247
248 using slang::ast::BinaryOperator;
249 switch (expr.op) {
250 case BinaryOperator::Add:
251 return createBinary<moore::AddOp>(lhs, rhs);
252 case BinaryOperator::Subtract:
253 return createBinary<moore::SubOp>(lhs, rhs);
254 case BinaryOperator::Multiply:
255 return createBinary<moore::MulOp>(lhs, rhs);
256 case BinaryOperator::Divide:
257 if (expr.type->isSigned())
258 return createBinary<moore::DivSOp>(lhs, rhs);
259 else
260 return createBinary<moore::DivUOp>(lhs, rhs);
261 case BinaryOperator::Mod:
262 if (expr.type->isSigned())
263 return createBinary<moore::ModSOp>(lhs, rhs);
264 else
265 return createBinary<moore::ModUOp>(lhs, rhs);
266 case BinaryOperator::Power: {
267 // Slang casts the LHS and result of the `**` operator to a four-valued
268 // type, since the operator can return X even for two-valued inputs. To
269 // maintain uniform types across operands and results, cast the RHS to
270 // that four-valued type as well.
271 auto rhsCast =
272 builder.create<moore::ConversionOp>(loc, lhs.getType(), rhs);
273 if (expr.type->isSigned())
274 return createBinary<moore::PowSOp>(lhs, rhsCast);
275 else
276 return createBinary<moore::PowUOp>(lhs, rhsCast);
277 }
278
279 case BinaryOperator::BinaryAnd:
280 return createBinary<moore::AndOp>(lhs, rhs);
281 case BinaryOperator::BinaryOr:
282 return createBinary<moore::OrOp>(lhs, rhs);
283 case BinaryOperator::BinaryXor:
284 return createBinary<moore::XorOp>(lhs, rhs);
285 case BinaryOperator::BinaryXnor: {
286 auto result = createBinary<moore::XorOp>(lhs, rhs);
287 if (!result)
288 return {};
289 return builder.create<moore::NotOp>(loc, result);
290 }
291
292 case BinaryOperator::Equality:
293 return createBinary<moore::EqOp>(lhs, rhs);
294 case BinaryOperator::Inequality:
295 return createBinary<moore::NeOp>(lhs, rhs);
296 case BinaryOperator::CaseEquality:
297 return createBinary<moore::CaseEqOp>(lhs, rhs);
298 case BinaryOperator::CaseInequality:
299 return createBinary<moore::CaseNeOp>(lhs, rhs);
300 case BinaryOperator::WildcardEquality:
301 return createBinary<moore::WildcardEqOp>(lhs, rhs);
302 case BinaryOperator::WildcardInequality:
303 return createBinary<moore::WildcardNeOp>(lhs, rhs);
304
305 case BinaryOperator::GreaterThanEqual:
306 if (expr.left().type->isSigned())
307 return createBinary<moore::SgeOp>(lhs, rhs);
308 else
309 return createBinary<moore::UgeOp>(lhs, rhs);
310 case BinaryOperator::GreaterThan:
311 if (expr.left().type->isSigned())
312 return createBinary<moore::SgtOp>(lhs, rhs);
313 else
314 return createBinary<moore::UgtOp>(lhs, rhs);
315 case BinaryOperator::LessThanEqual:
316 if (expr.left().type->isSigned())
317 return createBinary<moore::SleOp>(lhs, rhs);
318 else
319 return createBinary<moore::UleOp>(lhs, rhs);
320 case BinaryOperator::LessThan:
321 if (expr.left().type->isSigned())
322 return createBinary<moore::SltOp>(lhs, rhs);
323 else
324 return createBinary<moore::UltOp>(lhs, rhs);
325
326 // See IEEE 1800-2017 ยง 11.4.7 "Logical operators".
327 case BinaryOperator::LogicalAnd: {
328 // TODO: This should short-circuit. Put the RHS code into a separate
329 // block.
330 lhs = context.convertToBool(lhs, domain);
331 if (!lhs)
332 return {};
333 rhs = context.convertToBool(rhs, domain);
334 if (!rhs)
335 return {};
336 return builder.create<moore::AndOp>(loc, lhs, rhs);
337 }
338 case BinaryOperator::LogicalOr: {
339 // TODO: This should short-circuit. Put the RHS code into a separate
340 // block.
341 lhs = context.convertToBool(lhs, domain);
342 if (!lhs)
343 return {};
344 rhs = context.convertToBool(rhs, domain);
345 if (!rhs)
346 return {};
347 return builder.create<moore::OrOp>(loc, lhs, rhs);
348 }
349 case BinaryOperator::LogicalImplication: {
350 // `(lhs -> rhs)` equivalent to `(!lhs || rhs)`.
351 lhs = context.convertToBool(lhs, domain);
352 if (!lhs)
353 return {};
354 rhs = context.convertToBool(rhs, domain);
355 if (!rhs)
356 return {};
357 auto notLHS = builder.create<moore::NotOp>(loc, lhs);
358 return builder.create<moore::OrOp>(loc, notLHS, rhs);
359 }
360 case BinaryOperator::LogicalEquivalence: {
361 // `(lhs <-> rhs)` equivalent to `(lhs && rhs) || (!lhs && !rhs)`.
362 lhs = context.convertToBool(lhs, domain);
363 if (!lhs)
364 return {};
365 rhs = context.convertToBool(rhs, domain);
366 if (!rhs)
367 return {};
368 auto notLHS = builder.create<moore::NotOp>(loc, lhs);
369 auto notRHS = builder.create<moore::NotOp>(loc, rhs);
370 auto both = builder.create<moore::AndOp>(loc, lhs, rhs);
371 auto notBoth = builder.create<moore::AndOp>(loc, notLHS, notRHS);
372 return builder.create<moore::OrOp>(loc, both, notBoth);
373 }
374
375 case BinaryOperator::LogicalShiftLeft:
376 return createBinary<moore::ShlOp>(lhs, rhs);
377 case BinaryOperator::LogicalShiftRight:
378 return createBinary<moore::ShrOp>(lhs, rhs);
379 case BinaryOperator::ArithmeticShiftLeft:
380 return createBinary<moore::ShlOp>(lhs, rhs);
381 case BinaryOperator::ArithmeticShiftRight: {
382 // The `>>>` operator is an arithmetic right shift if the LHS operand is
383 // signed, or a logical right shift if the operand is unsigned.
384 lhs = context.convertToSimpleBitVector(lhs);
385 rhs = context.convertToSimpleBitVector(rhs);
386 if (!lhs || !rhs)
387 return {};
388 if (expr.type->isSigned())
389 return builder.create<moore::AShrOp>(loc, lhs, rhs);
390 return builder.create<moore::ShrOp>(loc, lhs, rhs);
391 }
392 }
393
394 mlir::emitError(loc, "unsupported binary operator");
395 return {};
396 }
397
398 // Handle `'0`, `'1`, `'x`, and `'z` literals.
399 Value visit(const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
400 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
401 }
402
403 // Handle integer literals.
404 Value visit(const slang::ast::IntegerLiteral &expr) {
405 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
406 }
407
408 // Handle concatenations.
409 Value visit(const slang::ast::ConcatenationExpression &expr) {
410 SmallVector<Value> operands;
411 for (auto *operand : expr.operands()) {
412 auto value = context.convertRvalueExpression(*operand);
413 if (!value)
414 continue;
415 value = context.convertToSimpleBitVector(value);
416 operands.push_back(value);
417 }
418 return builder.create<moore::ConcatOp>(loc, operands);
419 }
420
421 // Handle replications.
422 Value visit(const slang::ast::ReplicationExpression &expr) {
423 auto type = context.convertType(*expr.type);
424 if (isa<moore::VoidType>(type))
425 return {};
426
427 auto value = context.convertRvalueExpression(expr.concat());
428 if (!value)
429 return {};
430 return builder.create<moore::ReplicateOp>(loc, type, value);
431 }
432
433 Value getSelectIndex(Value index, const slang::ConstantRange &range) const {
434 auto indexType = cast<moore::UnpackedType>(index.getType());
435 auto bw = std::max(llvm::Log2_32_Ceil(std::abs(range.upper())),
436 indexType.getBitSize().value());
437 auto intType =
438 moore::IntType::get(index.getContext(), bw, indexType.getDomain());
439
440 if (range.isLittleEndian()) {
441 if (range.lower() == 0)
442 return index;
443
444 Value newIndex =
445 builder.createOrFold<moore::ConversionOp>(loc, intType, index);
446 Value offset =
447 builder.create<moore::ConstantOp>(loc, intType, range.lower());
448 return builder.createOrFold<moore::SubOp>(loc, newIndex, offset);
449 }
450
451 if (range.upper() == 0)
452 return builder.createOrFold<moore::NegOp>(loc, index);
453
454 Value newIndex =
455 builder.createOrFold<moore::ConversionOp>(loc, intType, index);
456 Value offset =
457 builder.create<moore::ConstantOp>(loc, intType, range.upper());
458 return builder.createOrFold<moore::SubOp>(loc, offset, newIndex);
459 }
460
461 // Handle single bit selections.
462 Value visit(const slang::ast::ElementSelectExpression &expr) {
463 auto type = context.convertType(*expr.type);
464 auto value = context.convertRvalueExpression(expr.value());
465 if (!type || !value)
466 return {};
467 auto range = expr.value().type->getFixedRange();
468 if (auto *constValue = expr.selector().constant) {
469 assert(!constValue->hasUnknown());
470 assert(constValue->size() <= 32);
471
472 auto lowBit = constValue->integer().as<uint32_t>().value();
473 return builder.create<moore::ExtractOp>(loc, type, value,
474 range.translateIndex(lowBit));
475 }
476 auto lowBit = context.convertRvalueExpression(expr.selector());
477 if (!lowBit)
478 return {};
479 return builder.create<moore::DynExtractOp>(loc, type, value,
480 getSelectIndex(lowBit, range));
481 }
482
483 // Handle range bits selections.
484 Value visit(const slang::ast::RangeSelectExpression &expr) {
485 auto type = context.convertType(*expr.type);
486 auto value = context.convertRvalueExpression(expr.value());
487 if (!type || !value)
488 return {};
489
490 Value dynLowBit;
491 uint32_t constLowBit;
492 auto *leftConst = expr.left().constant;
493 auto *rightConst = expr.right().constant;
494 if (leftConst) {
495 assert(!leftConst->hasUnknown());
496 assert(leftConst->size() <= 32);
497 }
498 if (rightConst) {
499 assert(!rightConst->hasUnknown());
500 assert(rightConst->size() <= 32);
501 }
502
503 if (expr.getSelectionKind() == slang::ast::RangeSelectionKind::Simple) {
504 if (leftConst && rightConst) {
505 // Estimate whether is big endian or little endian.
506 auto lhs = leftConst->integer().as<uint32_t>().value();
507 auto rhs = rightConst->integer().as<uint32_t>().value();
508 constLowBit = lhs < rhs ? lhs : rhs;
509 } else {
510 mlir::emitError(loc, "unsupported a variable as the index in the")
511 << slang::ast::toString(expr.getSelectionKind()) << "kind";
512 return {};
513 }
514 } else if (expr.getSelectionKind() ==
515 slang::ast::RangeSelectionKind::IndexedDown) {
516 // IndexedDown: arr[7-:8]. It's equivalent to arr[7:0] or arr[0:7]
517 // depending on little endian or bit endian. No matter which situation,
518 // the low bit must be "0".
519 if (leftConst) {
520 auto subtrahend = leftConst->integer().as<uint32_t>().value();
521 auto sliceWidth =
522 expr.right().constant->integer().as<uint32_t>().value();
523 constLowBit = subtrahend - sliceWidth - 1;
524 } else {
525 auto subtrahend = context.convertRvalueExpression(expr.left());
526 auto subtrahendType = cast<moore::UnpackedType>(subtrahend.getType());
527 auto intType = moore::IntType::get(context.getContext(),
528 subtrahendType.getBitSize().value(),
529 subtrahendType.getDomain());
530 auto sliceWidth =
531 expr.right().constant->integer().as<uint32_t>().value() - 1;
532 auto minuend =
533 builder.create<moore::ConstantOp>(loc, intType, sliceWidth);
534 dynLowBit = builder.create<moore::SubOp>(loc, subtrahend, minuend);
535 }
536 } else {
537 // IndexedUp: arr[0+:8]. "0" is the low bit, "8" is the bits slice width.
538 if (leftConst)
539 constLowBit = leftConst->integer().as<uint32_t>().value();
540 else
541 dynLowBit = context.convertRvalueExpression(expr.left());
542 }
543 auto range = expr.value().type->getFixedRange();
544 if (leftConst && rightConst)
545 return builder.create<moore::ExtractOp>(
546 loc, type, value, range.translateIndex(constLowBit));
547 return builder.create<moore::DynExtractOp>(
548 loc, type, value, getSelectIndex(dynLowBit, range));
549 }
550
551 Value visit(const slang::ast::MemberAccessExpression &expr) {
552 auto type = context.convertType(*expr.type);
553 auto valueType = expr.value().type;
554 auto value = context.convertRvalueExpression(expr.value());
555 if (!type || !value)
556 return {};
557 if (valueType->isStruct()) {
558 return builder.create<moore::StructExtractOp>(
559 loc, type, builder.getStringAttr(expr.member.name), value);
560 }
561 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
562 return builder.create<moore::UnionExtractOp>(
563 loc, type, builder.getStringAttr(expr.member.name), value);
564 }
565 mlir::emitError(loc, "expression of type ")
566 << value.getType() << " cannot be accessed";
567 return {};
568 }
569
570 // Handle set membership operator.
571 Value visit(const slang::ast::InsideExpression &expr) {
572 auto lhs = context.convertToSimpleBitVector(
573 context.convertRvalueExpression(expr.left()));
574 if (!lhs)
575 return {};
576 // All conditions for determining whether it is inside.
577 SmallVector<Value> conditions;
578
579 // Traverse open range list.
580 for (const auto *listExpr : expr.rangeList()) {
581 Value cond;
582 // The open range list on the right-hand side of the inside operator is a
583 // comma-separated list of expressions or ranges.
584 if (const auto *openRange =
585 listExpr->as_if<slang::ast::OpenRangeExpression>()) {
586 // Handle ranges.
587 auto lowBound = context.convertToSimpleBitVector(
588 context.convertRvalueExpression(openRange->left()));
589 auto highBound = context.convertToSimpleBitVector(
590 context.convertRvalueExpression(openRange->right()));
591 if (!lowBound || !highBound)
592 return {};
593 Value leftValue, rightValue;
594 // Determine if the expression on the left-hand side is inclusively
595 // within the range.
596 if (openRange->left().type->isSigned() ||
597 expr.left().type->isSigned()) {
598 leftValue = builder.create<moore::SgeOp>(loc, lhs, lowBound);
599 } else {
600 leftValue = builder.create<moore::UgeOp>(loc, lhs, lowBound);
601 }
602 if (openRange->right().type->isSigned() ||
603 expr.left().type->isSigned()) {
604 rightValue = builder.create<moore::SleOp>(loc, lhs, highBound);
605 } else {
606 rightValue = builder.create<moore::UleOp>(loc, lhs, highBound);
607 }
608 cond = builder.create<moore::AndOp>(loc, leftValue, rightValue);
609 } else {
610 // Handle expressions.
611 if (!listExpr->type->isSimpleBitVector()) {
612 if (listExpr->type->isUnpackedArray()) {
613 mlir::emitError(
614 loc, "unpacked arrays in 'inside' expressions not supported");
615 return {};
616 }
617 mlir::emitError(
618 loc, "only simple bit vectors supported in 'inside' expressions");
619 return {};
620 }
621 auto value = context.convertToSimpleBitVector(
622 context.convertRvalueExpression(*listExpr));
623 if (!value)
624 return {};
625 cond = builder.create<moore::WildcardEqOp>(loc, lhs, value);
626 }
627 conditions.push_back(cond);
628 }
629
630 // Calculate the final result by `or` op.
631 auto result = conditions.back();
632 conditions.pop_back();
633 while (!conditions.empty()) {
634 result = builder.create<moore::OrOp>(loc, conditions.back(), result);
635 conditions.pop_back();
636 }
637 return result;
638 }
639
640 // Handle conditional operator `?:`.
641 Value visit(const slang::ast::ConditionalExpression &expr) {
642 auto type = context.convertType(*expr.type);
643
644 // Handle condition.
645 if (expr.conditions.size() > 1) {
646 mlir::emitError(loc)
647 << "unsupported conditional expression with more than one condition";
648 return {};
649 }
650 const auto &cond = expr.conditions[0];
651 if (cond.pattern) {
652 mlir::emitError(loc) << "unsupported conditional expression with pattern";
653 return {};
654 }
655 auto value =
656 context.convertToBool(context.convertRvalueExpression(*cond.expr));
657 if (!value)
658 return {};
659 auto conditionalOp = builder.create<moore::ConditionalOp>(loc, type, value);
660
661 // Create blocks for true region and false region.
662 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
663 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
664
665 OpBuilder::InsertionGuard g(builder);
666
667 // Handle left expression.
668 builder.setInsertionPointToStart(&trueBlock);
669 auto trueValue = context.convertRvalueExpression(expr.left(), type);
670 if (!trueValue)
671 return {};
672 builder.create<moore::YieldOp>(loc, trueValue);
673
674 // Handle right expression.
675 builder.setInsertionPointToStart(&falseBlock);
676 auto falseValue = context.convertRvalueExpression(expr.right(), type);
677 if (!falseValue)
678 return {};
679 builder.create<moore::YieldOp>(loc, falseValue);
680
681 return conditionalOp.getResult();
682 }
683
684 /// Handle calls.
685 Value visit(const slang::ast::CallExpression &expr) {
686 // Class method calls are currently not supported.
687 if (expr.thisClass()) {
688 mlir::emitError(loc, "unsupported class method call");
689 return {};
690 }
691
692 // Try to materialize constant values directly.
693 auto constant = context.evaluateConstant(expr);
694 if (auto value = context.materializeConstant(constant, *expr.type, loc))
695 return value;
696
697 return std::visit(
698 [&](auto &subroutine) { return visitCall(expr, subroutine); },
699 expr.subroutine);
700 }
701
702 /// Handle subroutine calls.
703 Value visitCall(const slang::ast::CallExpression &expr,
704 const slang::ast::SubroutineSymbol *subroutine) {
705 auto *lowering = context.declareFunction(*subroutine);
706 if (!lowering)
707 return {};
708
709 // Convert the call arguments. Input arguments are converted to an rvalue.
710 // All other arguments are converted to lvalues and passed into the function
711 // by reference.
712 SmallVector<Value> arguments;
713 for (auto [callArg, declArg] :
714 llvm::zip(expr.arguments(), subroutine->getArguments())) {
715
716 // Unpack the `<expr> = EmptyArgument` pattern emitted by Slang for output
717 // and inout arguments.
718 auto *expr = callArg;
719 if (const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
720 expr = &assign->left();
721
722 Value value;
723 if (declArg->direction == slang::ast::ArgumentDirection::In)
724 value = context.convertRvalueExpression(*expr);
725 else
726 value = context.convertLvalueExpression(*expr);
727 if (!value)
728 return {};
729 arguments.push_back(value);
730 }
731
732 // Create the call.
733 auto callOp =
734 builder.create<mlir::func::CallOp>(loc, lowering->op, arguments);
735
736 // For calls to void functions we need to have a value to return from this
737 // function. Create a dummy `unrealized_conversion_cast`, which will get
738 // deleted again later on.
739 if (callOp.getNumResults() == 0)
740 return builder
741 .create<mlir::UnrealizedConversionCastOp>(
742 loc, moore::VoidType::get(context.getContext()), ValueRange{})
743 .getResult(0);
744
745 return callOp.getResult(0);
746 }
747
748 /// Handle system calls.
749 Value visitCall(const slang::ast::CallExpression &expr,
750 const slang::ast::CallExpression::SystemCallInfo &info) {
751 const auto &subroutine = *info.subroutine;
752 auto args = expr.arguments();
753
754 if (subroutine.name == "$signed" || subroutine.name == "$unsigned")
755 return context.convertRvalueExpression(*args[0]);
756
757 if (subroutine.name == "$clog2") {
758 auto value = context.convertToSimpleBitVector(
759 context.convertRvalueExpression(*args[0]));
760 if (!value)
761 return {};
762 return builder.create<moore::Clog2BIOp>(loc, value);
763 }
764
765 mlir::emitError(loc) << "unsupported system call `" << subroutine.name
766 << "`";
767 return {};
768 }
769
770 /// Handle string literals.
771 Value visit(const slang::ast::StringLiteral &expr) {
772 auto type = context.convertType(*expr.type);
773 return builder.create<moore::StringConstantOp>(loc, type, expr.getValue());
774 }
775
776 /// Handle assignment patterns.
777 Value visitAssignmentPattern(
778 const slang::ast::AssignmentPatternExpressionBase &expr,
779 unsigned replCount = 1) {
780 auto type = context.convertType(*expr.type);
781
782 // Convert the individual elements first.
783 auto elementCount = expr.elements().size();
784 SmallVector<Value> elements;
785 elements.reserve(replCount * elementCount);
786 for (auto elementExpr : expr.elements()) {
787 auto value = context.convertRvalueExpression(*elementExpr);
788 if (!value)
789 return {};
790 elements.push_back(value);
791 }
792 for (unsigned replIdx = 1; replIdx < replCount; ++replIdx)
793 for (unsigned elementIdx = 0; elementIdx < elementCount; ++elementIdx)
794 elements.push_back(elements[elementIdx]);
795
796 // Handle integers.
797 if (auto intType = dyn_cast<moore::IntType>(type)) {
798 assert(intType.getWidth() == elements.size());
799 std::reverse(elements.begin(), elements.end());
800 return builder.create<moore::ConcatOp>(loc, intType, elements);
801 }
802
803 // Handle packed structs.
804 if (auto structType = dyn_cast<moore::StructType>(type)) {
805 assert(structType.getMembers().size() == elements.size());
806 return builder.create<moore::StructCreateOp>(loc, structType, elements);
807 }
808
809 // Handle unpacked structs.
810 if (auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
811 assert(structType.getMembers().size() == elements.size());
812 return builder.create<moore::StructCreateOp>(loc, structType, elements);
813 }
814
815 // Handle packed arrays.
816 if (auto arrayType = dyn_cast<moore::ArrayType>(type)) {
817 assert(arrayType.getSize() == elements.size());
818 return builder.create<moore::ArrayCreateOp>(loc, arrayType, elements);
819 }
820
821 // Handle unpacked arrays.
822 if (auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
823 assert(arrayType.getSize() == elements.size());
824 return builder.create<moore::ArrayCreateOp>(loc, arrayType, elements);
825 }
826
827 mlir::emitError(loc) << "unsupported assignment pattern with type " << type;
828 return {};
829 }
830
831 Value visit(const slang::ast::SimpleAssignmentPatternExpression &expr) {
832 return visitAssignmentPattern(expr);
833 }
834
835 Value visit(const slang::ast::StructuredAssignmentPatternExpression &expr) {
836 return visitAssignmentPattern(expr);
837 }
838
839 Value visit(const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
840 auto count =
841 context.evaluateConstant(expr.count()).integer().as<unsigned>();
842 assert(count && "Slang guarantees constant non-zero replication count");
843 return visitAssignmentPattern(expr, *count);
844 }
845
846 Value visit(const slang::ast::StreamingConcatenationExpression &expr) {
847 SmallVector<Value> operands;
848 for (auto stream : expr.streams()) {
849 auto operandLoc = context.convertLocation(stream.operand->sourceRange);
850 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
851 mlir::emitError(operandLoc)
852 << "Moore only support streaming "
853 "concatenation with fixed size 'with expression'";
854 return {};
855 }
856 Value value;
857 if (stream.constantWithWidth.has_value()) {
858 value = context.convertRvalueExpression(*stream.withExpr);
859 auto type = cast<moore::UnpackedType>(value.getType());
860 auto intType = moore::IntType::get(
861 context.getContext(), type.getBitSize().value(), type.getDomain());
862 // Do not care if it's signed, because we will not do expansion.
863 value = context.materializeConversion(intType, value, false, loc);
864 } else {
865 value = context.convertRvalueExpression(*stream.operand);
866 }
867
868 if (!value)
869 return {};
870 value = context.convertToSimpleBitVector(value);
871 if (!value) {
872 return {};
873 }
874 operands.push_back(value);
875 }
876 Value value;
877
878 if (operands.size() == 1) {
879 // There must be at least one element, otherwise slang will report an
880 // error.
881 value = operands.front();
882 } else {
883 value = builder.create<moore::ConcatOp>(loc, operands).getResult();
884 }
885
886 if (expr.sliceSize == 0) {
887 return value;
888 }
889
890 auto type = cast<moore::IntType>(value.getType());
891 SmallVector<Value> slicedOperands;
892 auto iterMax = type.getWidth() / expr.sliceSize;
893 auto remainSize = type.getWidth() % expr.sliceSize;
894
895 for (size_t i = 0; i < iterMax; i++) {
896 auto extractResultType = moore::IntType::get(
897 context.getContext(), expr.sliceSize, type.getDomain());
898
899 auto extracted = builder.create<moore::ExtractOp>(
900 loc, extractResultType, value, i * expr.sliceSize);
901 slicedOperands.push_back(extracted);
902 }
903 // Handle other wire
904 if (remainSize) {
905 auto extractResultType = moore::IntType::get(
906 context.getContext(), remainSize, type.getDomain());
907
908 auto extracted = builder.create<moore::ExtractOp>(
909 loc, extractResultType, value, iterMax * expr.sliceSize);
910 slicedOperands.push_back(extracted);
911 }
912
913 return builder.create<moore::ConcatOp>(loc, slicedOperands);
914 }
915
916 /// Emit an error for all other expressions.
917 template <typename T>
918 Value visit(T &&node) {
919 mlir::emitError(loc, "unsupported expression: ")
920 << slang::ast::toString(node.kind);
921 return {};
922 }
923
924 Value visitInvalid(const slang::ast::Expression &expr) {
925 mlir::emitError(loc, "invalid expression");
926 return {};
927 }
928};
929} // namespace
930
931namespace {
932struct LvalueExprVisitor {
933 Context &context;
934 Location loc;
935 OpBuilder &builder;
936
937 LvalueExprVisitor(Context &context, Location loc)
938 : context(context), loc(loc), builder(context.builder) {}
939
940 // Handle named values, such as references to declared variables.
941 Value visit(const slang::ast::NamedValueExpression &expr) {
942 if (auto value = context.valueSymbols.lookup(&expr.symbol))
943 return value;
944 auto d = mlir::emitError(loc, "unknown name `") << expr.symbol.name << "`";
945 d.attachNote(context.convertLocation(expr.symbol.location))
946 << "no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
947 return {};
948 }
949
950 // Handle hierarchical values, such as `Top.sub.var = x`.
951 Value visit(const slang::ast::HierarchicalValueExpression &expr) {
952 if (auto value = context.valueSymbols.lookup(&expr.symbol))
953 return value;
954
955 // Emit an error for those hierarchical values not recorded in the
956 // `valueSymbols`.
957 auto d = mlir::emitError(loc, "unknown hierarchical name `")
958 << expr.symbol.name << "`";
959 d.attachNote(context.convertLocation(expr.symbol.location))
960 << "no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
961 return {};
962 }
963
964 // Handle concatenations.
965 Value visit(const slang::ast::ConcatenationExpression &expr) {
966 SmallVector<Value> operands;
967 for (auto *operand : expr.operands()) {
968 auto value = context.convertLvalueExpression(*operand);
969 if (!value)
970 continue;
971 operands.push_back(value);
972 }
973 return builder.create<moore::ConcatRefOp>(loc, operands);
974 }
975
976 // Handle single bit selections.
977 Value visit(const slang::ast::ElementSelectExpression &expr) {
978 auto type = context.convertType(*expr.type);
979 auto value = context.convertLvalueExpression(expr.value());
980 if (!type || !value)
981 return {};
982 if (auto *constValue = expr.selector().constant) {
983 assert(!constValue->hasUnknown());
984 assert(constValue->size() <= 32);
985
986 auto lowBit = constValue->integer().as<uint32_t>().value();
987 return builder.create<moore::ExtractRefOp>(
988 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
989 lowBit);
990 }
991 auto lowBit = context.convertRvalueExpression(expr.selector());
992 if (!lowBit)
993 return {};
994 return builder.create<moore::DynExtractRefOp>(
995 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
996 lowBit);
997 }
998
999 // Handle range bits selections.
1000 Value visit(const slang::ast::RangeSelectExpression &expr) {
1001 auto type = context.convertType(*expr.type);
1002 auto value = context.convertLvalueExpression(expr.value());
1003 if (!type || !value)
1004 return {};
1005
1006 Value dynLowBit;
1007 uint32_t constLowBit;
1008 auto *leftConst = expr.left().constant;
1009 auto *rightConst = expr.right().constant;
1010 if (leftConst) {
1011 assert(!leftConst->hasUnknown());
1012 assert(leftConst->size() <= 32);
1013 }
1014 if (rightConst) {
1015 assert(!rightConst->hasUnknown());
1016 assert(rightConst->size() <= 32);
1017 }
1018
1019 if (expr.getSelectionKind() == slang::ast::RangeSelectionKind::Simple) {
1020 if (leftConst && rightConst) {
1021 // Estimate whether is big endian or little endian.
1022 auto lhs = leftConst->integer().as<uint32_t>().value();
1023 auto rhs = rightConst->integer().as<uint32_t>().value();
1024 constLowBit = lhs < rhs ? lhs : rhs;
1025 } else {
1026 mlir::emitError(loc, "unsupported a variable as the index in the")
1027 << slang::ast::toString(expr.getSelectionKind()) << "kind";
1028 return {};
1029 }
1030 } else if (expr.getSelectionKind() ==
1031 slang::ast::RangeSelectionKind::IndexedDown) {
1032 // IndexedDown: arr[7-:8]. It's equivalent to arr[7:0] or arr[0:7]
1033 // depending on little endian or bit endian. No matter which situation,
1034 // the low bit must be "0".
1035 if (leftConst) {
1036 auto subtrahend = leftConst->integer().as<uint32_t>().value();
1037 auto sliceWidth =
1038 expr.right().constant->integer().as<uint32_t>().value();
1039 constLowBit = subtrahend - sliceWidth - 1;
1040 } else {
1041 auto subtrahend = context.convertRvalueExpression(expr.left());
1042 auto subtrahendType = cast<moore::UnpackedType>(subtrahend.getType());
1043 auto intType = moore::IntType::get(context.getContext(),
1044 subtrahendType.getBitSize().value(),
1045 subtrahendType.getDomain());
1046 auto sliceWidth =
1047 expr.right().constant->integer().as<uint32_t>().value() - 1;
1048 auto minuend =
1049 builder.create<moore::ConstantOp>(loc, intType, sliceWidth);
1050 dynLowBit = builder.create<moore::SubOp>(loc, subtrahend, minuend);
1051 }
1052 } else {
1053 // IndexedUp: arr[0+:8]. "0" is the low bit, "8" is the bits slice width.
1054 if (leftConst)
1055 constLowBit = leftConst->integer().as<uint32_t>().value();
1056 else
1057 dynLowBit = context.convertRvalueExpression(expr.left());
1058 }
1059 if (leftConst && rightConst)
1060 return builder.create<moore::ExtractRefOp>(
1061 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
1062 constLowBit);
1063 return builder.create<moore::DynExtractRefOp>(
1064 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
1065 dynLowBit);
1066 }
1067
1068 Value visit(const slang::ast::StreamingConcatenationExpression &expr) {
1069 SmallVector<Value> operands;
1070 for (auto stream : expr.streams()) {
1071 auto operandLoc = context.convertLocation(stream.operand->sourceRange);
1072 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
1073 mlir::emitError(operandLoc)
1074 << "Moore only support streaming "
1075 "concatenation with fixed size 'with expression'";
1076 return {};
1077 }
1078 Value value;
1079 if (stream.constantWithWidth.has_value()) {
1080 value = context.convertLvalueExpression(*stream.withExpr);
1081 auto type = cast<moore::UnpackedType>(
1082 cast<moore::RefType>(value.getType()).getNestedType());
1083 auto intType = moore::RefType::get(moore::IntType::get(
1084 context.getContext(), type.getBitSize().value(), type.getDomain()));
1085 // Do not care if it's signed, because we will not do expansion.
1086 value = context.materializeConversion(intType, value, false, loc);
1087 } else {
1088 value = context.convertLvalueExpression(*stream.operand);
1089 }
1090
1091 if (!value)
1092 return {};
1093 operands.push_back(value);
1094 }
1095 Value value;
1096 if (operands.size() == 1) {
1097 // There must be at least one element, otherwise slang will report an
1098 // error.
1099 value = operands.front();
1100 } else {
1101 value = builder.create<moore::ConcatRefOp>(loc, operands).getResult();
1102 }
1103
1104 if (expr.sliceSize == 0) {
1105 return value;
1106 }
1107
1108 auto type = cast<moore::IntType>(
1109 cast<moore::RefType>(value.getType()).getNestedType());
1110 SmallVector<Value> slicedOperands;
1111 auto widthSum = type.getWidth();
1112 auto domain = type.getDomain();
1113 auto iterMax = widthSum / expr.sliceSize;
1114 auto remainSize = widthSum % expr.sliceSize;
1115
1116 for (size_t i = 0; i < iterMax; i++) {
1117 auto extractResultType = moore::RefType::get(
1118 moore::IntType::get(context.getContext(), expr.sliceSize, domain));
1119
1120 auto extracted = builder.create<moore::ExtractRefOp>(
1121 loc, extractResultType, value, i * expr.sliceSize);
1122 slicedOperands.push_back(extracted);
1123 }
1124 // Handle other wire
1125 if (remainSize) {
1126 auto extractResultType = moore::RefType::get(
1127 moore::IntType::get(context.getContext(), remainSize, domain));
1128
1129 auto extracted = builder.create<moore::ExtractRefOp>(
1130 loc, extractResultType, value, iterMax * expr.sliceSize);
1131 slicedOperands.push_back(extracted);
1132 }
1133
1134 return builder.create<moore::ConcatRefOp>(loc, slicedOperands);
1135 }
1136
1137 Value visit(const slang::ast::MemberAccessExpression &expr) {
1138 auto type = context.convertType(*expr.type);
1139 auto valueType = expr.value().type;
1140 auto value = context.convertLvalueExpression(expr.value());
1141 if (!type || !value)
1142 return {};
1143 if (valueType->isStruct()) {
1144 return builder.create<moore::StructExtractRefOp>(
1145 loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
1146 builder.getStringAttr(expr.member.name), value);
1147 }
1148 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
1149 return builder.create<moore::UnionExtractRefOp>(
1150 loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
1151 builder.getStringAttr(expr.member.name), value);
1152 }
1153 mlir::emitError(loc, "expression of type ")
1154 << value.getType() << " cannot be accessed";
1155 return {};
1156 }
1157
1158 /// Emit an error for all other expressions.
1159 template <typename T>
1160 Value visit(T &&node) {
1161 return context.convertRvalueExpression(node);
1162 }
1163
1164 Value visitInvalid(const slang::ast::Expression &expr) {
1165 mlir::emitError(loc, "invalid expression");
1166 return {};
1167 }
1168};
1169} // namespace
1170
1171Value Context::convertRvalueExpression(const slang::ast::Expression &expr,
1172 Type requiredType) {
1173 auto loc = convertLocation(expr.sourceRange);
1174 auto value = expr.visit(RvalueExprVisitor(*this, loc));
1175 if (value && requiredType)
1176 value =
1177 materializeConversion(requiredType, value, expr.type->isSigned(), loc);
1178 return value;
1179}
1180
1181Value Context::convertLvalueExpression(const slang::ast::Expression &expr) {
1182 auto loc = convertLocation(expr.sourceRange);
1183 return expr.visit(LvalueExprVisitor(*this, loc));
1184}
1185// NOLINTEND(misc-no-recursion)
1186
1187/// Helper function to convert a value to its "truthy" boolean value.
1188Value Context::convertToBool(Value value) {
1189 if (!value)
1190 return {};
1191 if (auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
1192 if (type.getBitSize() == 1)
1193 return value;
1194 if (auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
1195 return builder.create<moore::BoolCastOp>(value.getLoc(), value);
1196 mlir::emitError(value.getLoc(), "expression of type ")
1197 << value.getType() << " cannot be cast to a boolean";
1198 return {};
1199}
1200
1201/// Materialize a Slang integer literal as a constant op.
1202Value Context::materializeSVInt(const slang::SVInt &svint,
1203 const slang::ast::Type &astType, Location loc) {
1204 auto type = convertType(astType);
1205 if (!type)
1206 return {};
1207
1208 bool typeIsFourValued = false;
1209 if (auto unpackedType = dyn_cast<moore::UnpackedType>(type))
1210 typeIsFourValued = unpackedType.getDomain() == moore::Domain::FourValued;
1211
1212 auto fvint = convertSVIntToFVInt(svint);
1213 auto intType = moore::IntType::get(getContext(), fvint.getBitWidth(),
1214 fvint.hasUnknown() || typeIsFourValued
1217 Value result = builder.create<moore::ConstantOp>(loc, intType, fvint);
1218 if (result.getType() != type)
1219 result = builder.create<moore::ConversionOp>(loc, type, result);
1220 return result;
1221}
1222
1223Value Context::materializeConstant(const slang::ConstantValue &constant,
1224 const slang::ast::Type &type, Location loc) {
1225 if (constant.isInteger())
1226 return materializeSVInt(constant.integer(), type, loc);
1227 return {};
1228}
1229
1230slang::ConstantValue
1231Context::evaluateConstant(const slang::ast::Expression &expr) {
1232 using slang::ast::EvalFlags;
1233 slang::ast::EvalContext evalContext(
1234 compilation, EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
1235 return expr.eval(evalContext);
1236}
1237
1238/// Helper function to convert a value to its "truthy" boolean value and
1239/// convert it to the given domain.
1240Value Context::convertToBool(Value value, Domain domain) {
1241 value = convertToBool(value);
1242 if (!value)
1243 return {};
1244 auto type = moore::IntType::get(getContext(), 1, domain);
1245 if (value.getType() == type)
1246 return value;
1247 return builder.create<moore::ConversionOp>(value.getLoc(), type, value);
1248}
1249
1251 if (!value)
1252 return {};
1253 if (isa<moore::IntType>(value.getType()))
1254 return value;
1255
1256 // Some operations in Slang's AST, for example bitwise or `|`, don't cast
1257 // packed struct/array operands to simple bit vectors but directly operate
1258 // on the struct/array. Since the corresponding IR ops operate only on
1259 // simple bit vectors, insert a conversion in this case.
1260 if (auto packed = dyn_cast<moore::PackedType>(value.getType())) {
1261 if (auto bits = packed.getBitSize()) {
1262 auto sbvType =
1263 moore::IntType::get(value.getContext(), *bits, packed.getDomain());
1264 return builder.create<moore::ConversionOp>(value.getLoc(), sbvType,
1265 value);
1266 }
1267 }
1268
1269 mlir::emitError(value.getLoc()) << "expression of type " << value.getType()
1270 << " cannot be cast to a simple bit vector";
1271 return {};
1272}
1273
1274Value Context::materializeConversion(Type type, Value value, bool isSigned,
1275 Location loc) {
1276 if (type == value.getType())
1277 return value;
1278 auto dstPacked = dyn_cast<moore::PackedType>(type);
1279 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
1280
1281 // Resize the value if needed.
1282 if (dstPacked && srcPacked && dstPacked.getBitSize() &&
1283 srcPacked.getBitSize() &&
1284 *dstPacked.getBitSize() != *srcPacked.getBitSize()) {
1285 auto dstWidth = *dstPacked.getBitSize();
1286 auto srcWidth = *srcPacked.getBitSize();
1287
1288 // Convert the value to a simple bit vector which we can extend or truncate.
1289 auto srcWidthType = moore::IntType::get(value.getContext(), srcWidth,
1290 srcPacked.getDomain());
1291 if (value.getType() != srcWidthType)
1292 value = builder.create<moore::ConversionOp>(value.getLoc(), srcWidthType,
1293 value);
1294
1295 // Create truncation or sign/zero extension ops depending on the source and
1296 // destination width.
1297 auto dstWidthType = moore::IntType::get(value.getContext(), dstWidth,
1298 srcPacked.getDomain());
1299 if (dstWidth < srcWidth) {
1300 value = builder.create<moore::TruncOp>(loc, dstWidthType, value);
1301 } else if (dstWidth > srcWidth) {
1302 if (isSigned)
1303 value = builder.create<moore::SExtOp>(loc, dstWidthType, value);
1304 else
1305 value = builder.create<moore::ZExtOp>(loc, dstWidthType, value);
1306 }
1307 }
1308
1309 if (value.getType() != type)
1310 value = builder.create<moore::ConversionOp>(loc, type, value);
1311 return value;
1312}
assert(baseType &&"element must be base type")
static FVInt convertSVIntToFVInt(const slang::SVInt &svint)
Convert a Slang SVInt to a CIRCT FVInt.
Four-valued arbitrary precision integers.
Definition FVInt.h:37
Domain
The number of values each bit of a type can assume.
Definition MooreTypes.h:47
@ FourValued
Four-valued types such as logic or integer.
@ TwoValued
Two-valued types such as bit or int.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
Value 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
OpBuilder builder
The builder used to create IR operations.
std::function< void(moore::ReadOp)> rvalueReadCallback
A listener called for every variable or net being read.
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
Definition Types.cpp:167
Value materializeSVInt(const slang::SVInt &svint, const slang::ast::Type &type, Location loc)
Helper function to materialize an SVInt as an SSA value.
Value convertToBool(Value value)
Helper function to convert a value to its "truthy" boolean value.
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.
FunctionLowering * declareFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function and its arguments to a function declaration in the IR.
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.