CIRCT 24.0.0git
Loading...
Searching...
No Matches
ExportVerilog.cpp
Go to the documentation of this file.
1//===- ExportVerilog.cpp - Verilog Emitter --------------------------------===//
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//
9// This is the main Verilog emitter implementation.
10//
11// CAREFUL: This file covers the emission phase of `ExportVerilog` which mainly
12// walks the IR and produces output. Do NOT modify the IR during this walk, as
13// emission occurs in a highly parallel fashion. If you need to modify the IR,
14// do so during the preparation phase which lives in `PrepareForEmission.cpp`.
15//
16//===----------------------------------------------------------------------===//
17
35#include "circt/Support/LLVM.h"
37#include "circt/Support/Path.h"
42#include "mlir/IR/BuiltinOps.h"
43#include "mlir/IR/ImplicitLocOpBuilder.h"
44#include "mlir/IR/Location.h"
45#include "mlir/IR/Threading.h"
46#include "mlir/Interfaces/FunctionImplementation.h"
47#include "mlir/Pass/PassManager.h"
48#include "mlir/Support/FileUtilities.h"
49#include "llvm/ADT/MapVector.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/StringSet.h"
52#include "llvm/ADT/TypeSwitch.h"
53#include "llvm/Support/FileSystem.h"
54#include "llvm/Support/FormattedStream.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/SaveAndRestore.h"
57#include "llvm/Support/ToolOutputFile.h"
58#include "llvm/Support/raw_ostream.h"
59
60namespace circt {
61#define GEN_PASS_DEF_EXPORTSPLITVERILOG
62#define GEN_PASS_DEF_EXPORTVERILOG
63#include "circt/Conversion/Passes.h.inc"
64} // namespace circt
65
66using namespace circt;
67using namespace comb;
68using namespace hw;
69using namespace sv;
70using namespace ExportVerilog;
71
72using namespace pretty;
73
74#define DEBUG_TYPE "export-verilog"
75
76StringRef circtHeader = "circt_header.svh";
77StringRef circtHeaderInclude = "`include \"circt_header.svh\"\n";
78
79namespace {
80/// This enum keeps track of the precedence level of various binary operators,
81/// where a lower number binds tighter.
82enum VerilogPrecedence {
83 // Normal precedence levels.
84 Symbol, // Atomic symbol like "foo" and {a,b}
85 Selection, // () , [] , :: , ., $signed()
86 Unary, // Unary operators like ~foo
87 Multiply, // * , / , %
88 Addition, // + , -
89 Shift, // << , >>, <<<, >>>
90 Comparison, // > , >= , < , <=
91 Equality, // == , !=
92 And, // &
93 Xor, // ^ , ^~
94 Or, // |
95 AndShortCircuit, // &&
96 Conditional, // ? :
97
98 LowestPrecedence, // Sentinel which is always the lowest precedence.
99};
100
101/// This enum keeps track of whether the emitted subexpression is signed or
102/// unsigned as seen from the Verilog language perspective.
103enum SubExprSignResult { IsSigned, IsUnsigned };
104
105/// This is information precomputed about each subexpression in the tree we
106/// are emitting as a unit.
107struct SubExprInfo {
108 /// The precedence of this expression.
109 VerilogPrecedence precedence;
110
111 /// The signedness of the expression.
112 SubExprSignResult signedness;
113
114 SubExprInfo(VerilogPrecedence precedence, SubExprSignResult signedness)
115 : precedence(precedence), signedness(signedness) {}
116};
117
118} // end anonymous namespace
119
120//===----------------------------------------------------------------------===//
121// Helper routines
122//===----------------------------------------------------------------------===//
123
124static TypedAttr getInt32Attr(MLIRContext *ctx, uint32_t value) {
125 return Builder(ctx).getI32IntegerAttr(value);
126}
127
128static TypedAttr getIntAttr(MLIRContext *ctx, Type t, const APInt &value) {
129 return Builder(ctx).getIntegerAttr(t, value);
130}
131
132/// Return true for nullary operations that are better emitted multiple
133/// times as inline expression (when they have multiple uses) rather than having
134/// a temporary wire.
135///
136/// This can only handle nullary expressions, because we don't want to replicate
137/// subtrees arbitrarily.
138static bool isDuplicatableNullaryExpression(Operation *op) {
139 // We don't want wires that are just constants aesthetically.
140 if (isConstantExpression(op))
141 return true;
142
143 // If this is a small verbatim expression with no side effects, duplicate it
144 // inline.
145 if (isa<VerbatimExprOp>(op)) {
146 if (op->getNumOperands() == 0 &&
147 op->getAttrOfType<StringAttr>("format_string").getValue().size() <= 32)
148 return true;
149 }
150
151 // Always duplicate XMRs into their use site.
152 if (isa<XMRRefOp>(op))
153 return true;
154
155 // If this is a macro reference without side effects, allow duplication.
156 if (isa<MacroRefExprOp>(op))
157 return true;
158
159 return false;
160}
161
162// Return true if the expression can be inlined even when the op has multiple
163// uses. Be careful to add operations here since it might cause exponential
164// emission without proper restrictions.
165static bool isDuplicatableExpression(Operation *op) {
166 if (op->getNumOperands() == 0)
168
169 // It is cheap to inline extract op.
170 if (isa<comb::ExtractOp, hw::StructExtractOp, hw::UnionExtractOp>(op))
171 return true;
172
173 // We only inline array_get with a constant, port or wire index.
174 if (auto array = dyn_cast<hw::ArrayGetOp>(op)) {
175 auto *indexOp = array.getIndex().getDefiningOp();
176 if (!indexOp || isa<ConstantOp>(indexOp))
177 return true;
178 if (auto read = dyn_cast<ReadInOutOp>(indexOp)) {
179 auto *readSrc = read.getInput().getDefiningOp();
180 // A port or wire is ok to duplicate reads.
181 return !readSrc || isa<sv::WireOp, LogicOp, sv::VarOp>(readSrc);
182 }
183
184 return false;
185 }
186
187 return false;
188}
189
190/// Return the verilog name of the operations that can define a symbol.
191/// Legalized names are added to "hw.verilogName" so look up it when the
192/// attribute already exists.
193StringRef ExportVerilog::getSymOpName(Operation *symOp) {
194 // Typeswitch of operation types which can define a symbol.
195 // If legalizeNames has renamed it, then the attribute must be set.
196 if (auto attr = symOp->getAttrOfType<StringAttr>("hw.verilogName"))
197 return attr.getValue();
198 return TypeSwitch<Operation *, StringRef>(symOp)
199 .Case<HWModuleOp, HWModuleExternOp, HWModuleGeneratedOp,
200 sv::SVVerbatimModuleOp, FuncOp>(
201 [](Operation *op) { return getVerilogModuleName(op); })
202 .Case<SVVerbatimSourceOp>([](SVVerbatimSourceOp op) {
203 return op.getVerilogNameAttr().getValue();
204 })
205 .Case<PackageExternOp>([](PackageExternOp op) {
206 return op.getVerilogName().value_or(op.getSymName());
207 })
208 .Case<InterfaceOp>([&](InterfaceOp op) {
209 return getVerilogModuleNameAttr(op).getValue();
210 })
211 .Case<InterfaceSignalOp>(
212 [&](InterfaceSignalOp op) { return op.getSymName(); })
213 .Case<InterfaceModportOp>(
214 [&](InterfaceModportOp op) { return op.getSymName(); })
215 .Case<GenerateOp>([](GenerateOp op) { return op.getSymName(); })
216 .Default([&](Operation *op) {
217 if (auto attr = op->getAttrOfType<StringAttr>("name"))
218 return attr.getValue();
219 if (auto attr = op->getAttrOfType<StringAttr>("instanceName"))
220 return attr.getValue();
221 if (auto attr = op->getAttrOfType<StringAttr>("sv.namehint"))
222 return attr.getValue();
223 if (auto symbol = dyn_cast<mlir::SymbolOpInterface>(op))
224 return symbol.getName();
225 return StringRef("");
226 });
227}
228
229/// Emits a known-safe token that is legal when indexing into singleton arrays.
230template <typename PPS>
231static void emitZeroWidthIndexingValue(PPS &os) {
232 os << "/*Zero width*/ 1\'b0";
233}
234
235/// Return the verilog name of the port for the module.
236static StringRef getPortVerilogName(Operation *module, size_t portArgNum) {
237 auto hml = cast<HWModuleLike>(module);
238 return hml.getPort(portArgNum).getVerilogName();
239}
240
241/// Return the verilog name of the port for the module.
242static StringRef getInputPortVerilogName(Operation *module, size_t portArgNum) {
243 auto hml = cast<HWModuleLike>(module);
244 auto pId = hml.getHWModuleType().getPortIdForInputId(portArgNum);
245 if (auto attrs = dyn_cast_or_null<DictionaryAttr>(hml.getPortAttrs(pId)))
246 if (auto updatedName = attrs.getAs<StringAttr>("hw.verilogName"))
247 return updatedName.getValue();
248 return hml.getHWModuleType().getPortName(pId);
249}
250
251/// This predicate returns true if the specified operation is considered a
252/// potentially inlinable Verilog expression. These nodes always have a single
253/// result, but may have side effects (e.g. `sv.verbatim.expr.se`).
254/// MemoryEffects should be checked if a client cares.
256 // These are SV dialect expressions.
257 if (isa<ReadInOutOp, AggregateConstantOp, ArrayIndexInOutOp,
258 IndexedPartSelectInOutOp, StructFieldInOutOp, IndexedPartSelectOp,
259 ParamValueOp, XMROp, XMRRefOp, SampledOp, EnumConstantOp, SFormatFOp,
260 SystemFunctionOp, STimeOp, TimeOp, UnpackedArrayCreateOp,
261 UnpackedOpenArrayCastOp, ConcatStrOp>(op))
262 return true;
263
264 // These are Verif dialect expressions.
265 if (isa<verif::ContractOp>(op))
266 return true;
267
268 // All HW combinational logic ops and SV expression ops are Verilog
269 // expressions.
270 return isCombinational(op) || isExpression(op);
271}
272
273// NOLINTBEGIN(misc-no-recursion)
274/// Push this type's dimension into a vector.
275static void getTypeDims(
276 SmallVectorImpl<Attribute> &dims, Type type, Location loc,
277 llvm::function_ref<mlir::InFlightDiagnostic(Location)> errorHandler) {
278 if (auto integer = hw::type_dyn_cast<IntegerType>(type)) {
279 if (integer.getWidth() != 1)
280 dims.push_back(getInt32Attr(type.getContext(), integer.getWidth()));
281 return;
282 }
283 if (auto array = hw::type_dyn_cast<ArrayType>(type)) {
284 dims.push_back(getInt32Attr(type.getContext(), array.getNumElements()));
285 getTypeDims(dims, array.getElementType(), loc, errorHandler);
286
287 return;
288 }
289 if (auto intType = hw::type_dyn_cast<IntType>(type)) {
290 dims.push_back(intType.getWidth());
291 return;
292 }
293
294 if (auto inout = hw::type_dyn_cast<InOutType>(type))
295 return getTypeDims(dims, inout.getElementType(), loc, errorHandler);
296 if (auto net = dyn_cast<sv::NetType>(type))
297 return getTypeDims(dims, net.getElementType(), loc, errorHandler);
298 if (auto var = dyn_cast<sv::VarType>(type))
299 return getTypeDims(dims, var.getElementType(), loc, errorHandler);
300 if (auto uarray = hw::type_dyn_cast<hw::UnpackedArrayType>(type))
301 return getTypeDims(dims, uarray.getElementType(), loc, errorHandler);
302 if (auto uarray = hw::type_dyn_cast<sv::UnpackedOpenArrayType>(type))
303 return getTypeDims(dims, uarray.getElementType(), loc, errorHandler);
304 if (hw::type_isa<InterfaceType, StructType, EnumType, UnionType>(type))
305 return;
306
307 errorHandler(loc) << "value has an unsupported verilog type " << type;
308}
309// NOLINTEND(misc-no-recursion)
310
311/// True iff 'a' and 'b' have the same wire dims.
313 Type a, Type b, Location loc,
314 llvm::function_ref<mlir::InFlightDiagnostic(Location)> errorHandler) {
315 SmallVector<Attribute, 4> aDims;
316 getTypeDims(aDims, a, loc, errorHandler);
317
318 SmallVector<Attribute, 4> bDims;
319 getTypeDims(bDims, b, loc, errorHandler);
320
321 return aDims == bDims;
322}
323
324// NOLINTBEGIN(misc-no-recursion)
326 type = getCanonicalType(type);
327 if (auto intType = dyn_cast<IntegerType>(type))
328 return intType.getWidth() == 0;
329 if (auto inout = dyn_cast<hw::InOutType>(type))
330 return isZeroBitType(inout.getElementType());
331 if (auto net = dyn_cast<sv::NetType>(type))
332 return isZeroBitType(net.getElementType());
333 if (auto var = dyn_cast<sv::VarType>(type))
334 return isZeroBitType(var.getElementType());
335 if (auto uarray = dyn_cast<hw::UnpackedArrayType>(type))
336 return uarray.getNumElements() == 0 ||
337 isZeroBitType(uarray.getElementType());
338 if (auto array = dyn_cast<hw::ArrayType>(type))
339 return array.getNumElements() == 0 || isZeroBitType(array.getElementType());
340 if (auto structType = dyn_cast<hw::StructType>(type))
341 return llvm::all_of(structType.getElements(),
342 [](auto elem) { return isZeroBitType(elem.type); });
343 if (auto enumType = dyn_cast<hw::EnumType>(type))
344 return enumType.getFields().empty();
345 if (auto unionType = dyn_cast<hw::UnionType>(type))
346 return hw::getBitWidth(unionType) == 0;
347
348 // We have an open type system, so assume it is ok.
349 return false;
350}
351// NOLINTEND(misc-no-recursion)
352
353/// Given a set of known nested types (those supported by this pass), strip off
354/// leading unpacked types. This strips off portions of the type that are
355/// printed to the right of the name in verilog.
356// NOLINTBEGIN(misc-no-recursion)
357static Type stripUnpackedTypes(Type type) {
358 return TypeSwitch<Type, Type>(type)
359 .Case<InOutType, NetType, VarType>([](auto valueType) {
360 return stripUnpackedTypes(valueType.getElementType());
361 })
362 .Case<UnpackedArrayType, sv::UnpackedOpenArrayType>([](auto arrayType) {
363 return stripUnpackedTypes(arrayType.getElementType());
364 })
365 .Default([](Type type) { return type; });
366}
367
368/// Return true if the type has a leading unpacked type.
369static bool hasLeadingUnpackedType(Type type) {
370 auto elementType = sv::getHandleElementType(type);
371 assert(elementType && "inout or SV handle type is expected");
373}
374
375/// Return true if the element type is emitted as a type name or a keyword
376/// (struct, union, enum or typedef), so that no "logic" prefix is allowed.
377static bool hasStructType(Type type) {
378 return TypeSwitch<Type, bool>(type)
379 .Case<InOutType, NetType, VarType, UnpackedArrayType, ArrayType>(
380 [](auto parentType) {
381 return hasStructType(parentType.getElementType());
382 })
383 .Case<StructType, UnionType, EnumType, TypeAliasType>(
384 [](auto) { return true; })
385 .Default([](auto) { return false; });
386}
387// NOLINTEND(misc-no-recursion)
388
389//===----------------------------------------------------------------------===//
390// Location comparison
391//===----------------------------------------------------------------------===//
392
393// NOLINTBEGIN(misc-no-recursion)
394
395static int compareLocs(Location lhs, Location rhs);
396
397// NameLoc comparator - compare names, then child locations.
398static int compareLocsImpl(mlir::NameLoc lhs, mlir::NameLoc rhs) {
399 if (auto name = lhs.getName().compare(rhs.getName()))
400 return name;
401 return compareLocs(lhs.getChildLoc(), rhs.getChildLoc());
402}
403
404// FileLineColLoc comparator.
405static int compareLocsImpl(mlir::FileLineColLoc lhs, mlir::FileLineColLoc rhs) {
406 if (auto fn = lhs.getFilename().compare(rhs.getFilename()))
407 return fn;
408 if (lhs.getLine() != rhs.getLine())
409 return lhs.getLine() < rhs.getLine() ? -1 : 1;
410 return lhs.getColumn() < rhs.getColumn() ? -1 : 1;
411}
412
413// CallSiteLoc comparator. Compare first on the callee, then on the caller.
414static int compareLocsImpl(mlir::CallSiteLoc lhs, mlir::CallSiteLoc rhs) {
415 Location lhsCallee = lhs.getCallee();
416 Location rhsCallee = rhs.getCallee();
417 if (auto res = compareLocs(lhsCallee, rhsCallee))
418 return res;
419
420 Location lhsCaller = lhs.getCaller();
421 Location rhsCaller = rhs.getCaller();
422 return compareLocs(lhsCaller, rhsCaller);
423}
424
425template <typename TTargetLoc>
426FailureOr<int> dispatchCompareLocations(Location lhs, Location rhs) {
427 auto lhsT = dyn_cast<TTargetLoc>(lhs);
428 auto rhsT = dyn_cast<TTargetLoc>(rhs);
429 if (lhsT && rhsT) {
430 // Both are of the target location type, compare them directly.
431 return compareLocsImpl(lhsT, rhsT);
432 }
433 if (lhsT) {
434 // lhs is TTargetLoc => it comes before rhs.
435 return -1;
436 }
437 if (rhsT) {
438 // rhs is TTargetLoc => it comes before lhs.
439 return 1;
440 }
441
442 return failure();
443}
444
445// Top-level comparator for two arbitrarily typed locations.
446// First order comparison by location type:
447// 1. FileLineColLoc
448// 2. NameLoc
449// 3. CallSiteLoc
450// 4. Anything else...
451// Intra-location type comparison is delegated to the corresponding
452// compareLocsImpl() function.
453static int compareLocs(Location lhs, Location rhs) {
454 // FileLineColLoc
455 if (auto res = dispatchCompareLocations<mlir::FileLineColLoc>(lhs, rhs);
456 succeeded(res))
457 return *res;
458
459 // NameLoc
460 if (auto res = dispatchCompareLocations<mlir::NameLoc>(lhs, rhs);
461 succeeded(res))
462 return *res;
463
464 // CallSiteLoc
465 if (auto res = dispatchCompareLocations<mlir::CallSiteLoc>(lhs, rhs);
466 succeeded(res))
467 return *res;
468
469 // Anything else...
470 return 0;
471}
472
473// NOLINTEND(misc-no-recursion)
474
475//===----------------------------------------------------------------------===//
476// Location printing
477//===----------------------------------------------------------------------===//
478
479/// Pull apart any fused locations into the location set, such that they are
480/// uniqued. Any other location type will be added as-is.
481static void collectAndUniqueLocations(Location loc,
482 SmallPtrSetImpl<Attribute> &locationSet) {
483 llvm::TypeSwitch<Location, void>(loc)
484 .Case<FusedLoc>([&](auto fusedLoc) {
485 for (auto subLoc : fusedLoc.getLocations())
486 collectAndUniqueLocations(subLoc, locationSet);
487 })
488 .Default([&](auto loc) { locationSet.insert(loc); });
489}
490
491// Sorts a vector of locations in-place.
492template <typename TVector>
493static void sortLocationVector(TVector &vec) {
494 llvm::array_pod_sort(
495 vec.begin(), vec.end(), [](const auto *lhs, const auto *rhs) -> int {
496 return compareLocs(cast<Location>(*lhs), cast<Location>(*rhs));
497 });
498}
499
501public:
502 // Generates location info for a single location in the specified style.
504 SmallPtrSet<Attribute, 8> locationSet;
505 locationSet.insert(loc);
506 llvm::raw_string_ostream os(output);
507 emitLocationSetInfo(os, style, locationSet);
508 }
509
510 // Generates location info for a set of operations in the specified style.
512 const SmallPtrSetImpl<Operation *> &ops) {
513 // Multiple operations may come from the same location or may not have
514 // useful
515 // location info. Unique it now.
516 SmallPtrSet<Attribute, 8> locationSet;
517 for (auto *op : ops)
518 collectAndUniqueLocations(op->getLoc(), locationSet);
519 llvm::raw_string_ostream os(output);
520 emitLocationSetInfo(os, style, locationSet);
521 }
522
523 StringRef strref() { return output; }
524
525private:
526 void emitLocationSetInfo(llvm::raw_string_ostream &os,
528 const SmallPtrSetImpl<Attribute> &locationSet) {
530 return;
531 std::string resstr;
532 llvm::raw_string_ostream sstr(resstr);
533 LocationEmitter::Impl(sstr, style, locationSet);
534 if (resstr.empty() || style == LoweringOptions::LocationInfoStyle::Plain) {
535 os << resstr;
536 return;
537 }
539 "other styles must be already handled");
540 os << "@[" << resstr << "]";
541 }
542
543 std::string output;
544
545 struct Impl {
546
547 // NOLINTBEGIN(misc-no-recursion)
549 const SmallPtrSetImpl<Attribute> &locationSet)
550 : os(os), style(style) {
551 emitLocationSetInfoImpl(locationSet);
552 }
553
554 // Emit CallSiteLocs.
555 void emitLocationInfo(mlir::CallSiteLoc loc) {
556 os << "{";
557 emitLocationInfo(loc.getCallee());
558 os << " <- ";
559 emitLocationInfo(loc.getCaller());
560 os << "}";
561 }
562
563 // Emit NameLocs.
564 void emitLocationInfo(mlir::NameLoc loc) {
565 bool withName = !loc.getName().empty();
566 if (withName)
567 os << "'" << loc.getName().strref() << "'(";
568 emitLocationInfo(loc.getChildLoc());
569
570 if (withName)
571 os << ")";
572 }
573
574 // Emit FileLineColLocs.
575 void emitLocationInfo(FileLineColLoc loc) {
576 os << loc.getFilename().getValue();
577 if (auto line = loc.getLine()) {
578 os << ':' << line;
579 if (auto col = loc.getColumn())
580 os << ':' << col;
581 }
582 }
583
584 // Generates a string representation of a set of FileLineColLocs.
585 // The entries are sorted by filename, line, col. Try to merge together
586 // entries to reduce verbosity on the column info.
587 void
588 printFileLineColSetInfo(llvm::SmallVector<FileLineColLoc, 8> locVector) {
589 // The entries are sorted by filename, line, col. Try to merge together
590 // entries to reduce verbosity on the column info.
591 StringRef lastFileName;
592 for (size_t i = 0, e = locVector.size(); i != e;) {
593 if (i != 0)
594 os << ", ";
595
596 // Print the filename if it changed.
597 auto first = locVector[i];
598 if (first.getFilename() != lastFileName) {
599 lastFileName = first.getFilename();
600 os << lastFileName;
601 }
602
603 // Scan for entries with the same file/line.
604 size_t end = i + 1;
605 while (end != e &&
606 first.getFilename() == locVector[end].getFilename() &&
607 first.getLine() == locVector[end].getLine())
608 ++end;
609
610 // If we have one entry, print it normally.
611 if (end == i + 1) {
612 if (auto line = first.getLine()) {
613 os << ':' << line;
614 if (auto col = first.getColumn())
615 os << ':' << col;
616 }
617 ++i;
618 continue;
619 }
620
621 // Otherwise print a brace enclosed list.
622 os << ':' << first.getLine() << ":{";
623 while (i != end) {
624 os << locVector[i++].getColumn();
625
626 if (i != end)
627 os << ',';
628 }
629 os << '}';
630 }
631 }
632
633 /// Return the location information in the specified style. This is the main
634 /// dispatch function for calling the location-specific routines.
635 void emitLocationInfo(Location loc) {
636 llvm::TypeSwitch<Location, void>(loc)
637 .Case<mlir::CallSiteLoc, mlir::NameLoc, mlir::FileLineColLoc>(
638 [&](auto loc) { emitLocationInfo(loc); })
639 .Case<mlir::FusedLoc>([&](auto loc) {
640 SmallPtrSet<Attribute, 8> locationSet;
641 collectAndUniqueLocations(loc, locationSet);
642 emitLocationSetInfoImpl(locationSet);
643 })
644 .Default([&](auto loc) {
645 // Don't print anything for unhandled locations.
646 });
647 }
648
649 /// Emit the location information of `locationSet` to `sstr`. The emitted
650 /// string
651 /// may potentially be an empty string given the contents of the
652 /// `locationSet`.
653 void
654 emitLocationSetInfoImpl(const SmallPtrSetImpl<Attribute> &locationSet) {
655 // Fast pass some common cases.
656 switch (locationSet.size()) {
657 case 1:
658 emitLocationInfo(cast<LocationAttr>(*locationSet.begin()));
659 [[fallthrough]];
660 case 0:
661 return;
662 default:
663 break;
664 }
665
666 // Sort the entries into distinct location printing kinds.
667 SmallVector<FileLineColLoc, 8> flcLocs;
668 SmallVector<Attribute, 8> otherLocs;
669 flcLocs.reserve(locationSet.size());
670 otherLocs.reserve(locationSet.size());
671 for (Attribute loc : locationSet) {
672 if (auto flcLoc = dyn_cast<FileLineColLoc>(loc))
673 flcLocs.push_back(flcLoc);
674 else
675 otherLocs.push_back(loc);
676 }
677
678 // SmallPtrSet iteration is non-deterministic, so sort the location
679 // vectors to ensure deterministic output.
680 sortLocationVector(otherLocs);
681 sortLocationVector(flcLocs);
682
683 // To detect whether something actually got emitted, we inspect the stream
684 // for size changes. This is due to the possiblity of locations which are
685 // not supposed to be emitted (e.g. `loc("")`).
686 size_t sstrSize = os.tell();
687 bool emittedAnything = false;
688 auto recheckEmittedSomething = [&]() {
689 size_t currSize = os.tell();
690 bool emittedSomethingSinceLastCheck = currSize != sstrSize;
691 emittedAnything |= emittedSomethingSinceLastCheck;
692 sstrSize = currSize;
693 return emittedSomethingSinceLastCheck;
694 };
695
696 // First, emit the other locations through the generic location dispatch
697 // function.
698 llvm::interleave(
699 otherLocs,
700 [&](Attribute loc) { emitLocationInfo(cast<LocationAttr>(loc)); },
701 [&] {
702 if (recheckEmittedSomething()) {
703 os << ", ";
704 recheckEmittedSomething(); // reset detector to reflect the comma.
705 }
706 });
707
708 // If we emitted anything, and we have FileLineColLocs, then emit a
709 // location-separating comma.
710 if (emittedAnything && !flcLocs.empty())
711 os << ", ";
712 // Then, emit the FileLineColLocs.
714 }
715 llvm::raw_string_ostream &os;
717
718 // NOLINTEND(misc-no-recursion)
719 };
720};
721
722/// Most expressions are invalid to bit-select from in Verilog, but some
723/// things are ok. Return true if it is ok to inline bitselect from the
724/// result of this expression. It is conservatively correct to return false.
725static bool isOkToBitSelectFrom(Value v) {
726 // Module ports are always ok to bit select from.
727 if (isa<BlockArgument>(v))
728 return true;
729
730 // Read_inout is valid to inline for bit-select. See `select` syntax on
731 // SV spec A.8.4 (P1174).
732 if (auto read = v.getDefiningOp<ReadInOutOp>())
733 return true;
734
735 // Aggregate access can be inlined.
736 if (isa_and_nonnull<StructExtractOp, UnionExtractOp, ArrayGetOp>(
737 v.getDefiningOp()))
738 return true;
739
740 // Interface signal can be inlined.
741 if (v.getDefiningOp<ReadInterfaceSignalOp>())
742 return true;
743
744 // TODO: We could handle concat and other operators here.
745 return false;
746}
747
748/// Return true if we are unable to ever inline the specified operation. This
749/// happens because not all Verilog expressions are composable, notably you
750/// can only use bit selects like x[4:6] on simple expressions, you cannot use
751/// expressions in the sensitivity list of always blocks, etc.
752static bool isExpressionUnableToInline(Operation *op,
753 const LoweringOptions &options) {
754 if (auto cast = dyn_cast<BitcastOp>(op))
755 if (!haveMatchingDims(cast.getInput().getType(), cast.getResult().getType(),
756 op->getLoc(),
757 [&](Location loc) { return emitError(loc); })) {
758 // Even if dimentions don't match, we can inline when its user doesn't
759 // rely on the type.
760 if (op->hasOneUse() &&
761 isa<comb::ConcatOp, hw::ArrayConcatOp>(*op->getUsers().begin()))
762 return false;
763 // Bitcasts rely on the type being assigned to, so we cannot inline.
764 return true;
765 }
766
767 // StructCreateOp needs to be assigning to a named temporary so that types
768 // are inferred properly by verilog
769 if (isa<StructCreateOp, UnionCreateOp, UnpackedArrayCreateOp, ArrayInjectOp>(
770 op))
771 return true;
772
773 // Aggregate literal syntax only works in an assignment expression, where
774 // the Verilog expression's type is determined by the LHS.
775 if (auto aggConstantOp = dyn_cast<AggregateConstantOp>(op))
776 return true;
777
778 // Verbatim with a long string should be emitted as an out-of-line declration.
779 if (auto verbatim = dyn_cast<VerbatimExprOp>(op))
780 if (verbatim.getFormatString().size() > 32)
781 return true;
782
783 // Scan the users of the operation to see if any of them need this to be
784 // emitted out-of-line.
785 for (auto &use : op->getUses()) {
786 auto *user = use.getOwner();
787
788 // Verilog bit selection is required by the standard to be:
789 // "a vector, packed array, packed structure, parameter or concatenation".
790 //
791 // It cannot be an arbitrary expression, e.g. this is invalid:
792 // assign bar = {{a}, {b}, {c}, {d}}[idx];
793 //
794 // To handle these, we push the subexpression into a temporary.
795 if (isa<ExtractOp, ArraySliceOp, ArrayGetOp, ArrayInjectOp, StructExtractOp,
796 StructInjectOp, StructExplodeOp, UnionExtractOp,
797 IndexedPartSelectOp>(user))
798 if (use.getOperandNumber() == 0 && // ignore index operands.
799 !isOkToBitSelectFrom(use.get()))
800 return true;
801
802 // Handle option disallowing expressions in event control.
803 if (!options.allowExprInEventControl) {
804 // Check operations used for event control, anything other than
805 // a read of a wire must be out of line.
806
807 // Helper to determine if the use will be part of "event control",
808 // based on what the operation using it is and as which operand.
809 auto usedInExprControl = [user, &use]() {
810 return TypeSwitch<Operation *, bool>(user)
811 .Case<ltl::ClockOp>([&](auto clockOp) {
812 // LTL Clock op's clock operand must be a name.
813 return clockOp.getClock() == use.get();
814 })
815 .Case<sv::AssertConcurrentOp, sv::AssumeConcurrentOp,
816 sv::CoverConcurrentOp>(
817 [&](auto op) { return op.getClock() == use.get(); })
818 .Case<sv::AssertPropertyOp, sv::AssumePropertyOp,
819 sv::CoverPropertyOp>([&](auto op) {
820 return op.getDisable() == use.get() || op.getClock() == use.get();
821 })
822 .Case<AlwaysOp, AlwaysFFOp>([](auto) {
823 // Always blocks must have a name in their sensitivity list.
824 // (all operands)
825 return true;
826 })
827 .Default([](auto) { return false; });
828 };
829
830 if (!usedInExprControl())
831 continue;
832
833 // Otherwise, this can only be inlined if is (already) a read of a wire.
834 auto read = dyn_cast<ReadInOutOp>(op);
835 if (!read)
836 return true;
837 if (!isa_and_nonnull<sv::WireOp, RegOp, sv::VarOp>(
838 read.getInput().getDefiningOp()))
839 return true;
840 }
841 }
842 return false;
843}
844
846
847/// Compute how many statements are within this block, for begin/end markers.
849 unsigned numStatements = 0;
850 block.walk([&](Operation *op) {
851 if (isVerilogExpression(op) ||
852 isa_and_nonnull<ltl::LTLDialect>(op->getDialect()))
853 return WalkResult::advance();
854 numStatements +=
855 TypeSwitch<Operation *, unsigned>(op)
856 .Case<VerbatimOp>([&](auto) {
857 // We don't know how many statements we emitted, so assume
858 // conservatively that a lot got put out. This will make sure we
859 // get a begin/end block around this.
860 return 3;
861 })
862 .Case<IfOp>([&](auto) {
863 // We count if as multiple statements to make sure it is always
864 // surrounded by a begin/end so we don't get if/else confusion in
865 // cases like this:
866 // if (cond)
867 // if (otherCond) // This should force a begin!
868 // stmt
869 // else // Goes with the outer if!
870 // thing;
871 return 2;
872 })
873 .Case<IfDefOp, IfDefProceduralOp>([&](auto) { return 3; })
874 .Case<OutputOp>([&](OutputOp oop) {
875 // Skip single-use instance outputs, they don't get statements.
876 // Keep this synchronized with visitStmt(InstanceOp,OutputOp).
877 return llvm::count_if(oop->getOperands(), [&](auto operand) {
878 Operation *op = operand.getDefiningOp();
879 return !operand.hasOneUse() || !op || !isa<HWInstanceLike>(op);
880 });
881 })
882 .Default([](auto) { return 1; });
883 if (numStatements > 1)
884 return WalkResult::interrupt();
885 return WalkResult::advance();
886 });
887 if (numStatements == 0)
889 if (numStatements == 1)
892}
893
894/// Return true if this expression should be emitted inline into any statement
895/// that uses it.
897 const LoweringOptions &options) {
898 // Never create a temporary for a dead expression.
899 if (op->getResult(0).use_empty())
900 return true;
901
902 // Never create a temporary which is only going to be assigned to an output
903 // port, wire, or reg.
904 if (op->hasOneUse() &&
905 isa<hw::OutputOp, sv::AssignOp, sv::BPAssignOp, sv::PAssignOp>(
906 *op->getUsers().begin()))
907 return true;
908
909 // If mux inlining is dissallowed, we cannot inline muxes.
910 if (options.disallowMuxInlining && isa<MuxOp>(op))
911 return false;
912
913 // If this operation has multiple uses, we can't generally inline it unless
914 // the op is duplicatable.
915 if (!op->getResult(0).hasOneUse() && !isDuplicatableExpression(op))
916 return false;
917
918 // If it isn't structurally possible to inline this expression, emit it out
919 // of line.
920 return !isExpressionUnableToInline(op, options);
921}
922
923/// Find a nested IfOp in an else block that can be printed as `else if`
924/// instead of nesting it into a new `begin` - `end` block. The block must
925/// contain a single IfOp and optionally expressions which can be hoisted out.
926static IfOp findNestedElseIf(Block *elseBlock) {
927 IfOp ifOp;
928 for (auto &op : *elseBlock) {
929 if (auto opIf = dyn_cast<IfOp>(op)) {
930 if (ifOp)
931 return {};
932 ifOp = opIf;
933 continue;
934 }
935 if (!isVerilogExpression(&op))
936 return {};
937 }
938 // SV attributes cannot be attached to `else if` so reject when ifOp has SV
939 // attributes.
940 if (ifOp && hasSVAttributes(ifOp))
941 return {};
942 return ifOp;
943}
944
945/// Emit SystemVerilog attributes.
946template <typename PPS>
947static void emitSVAttributesImpl(PPS &ps, ArrayAttr attrs, bool mayBreak) {
948 enum Container { NoContainer, InComment, InAttr };
949 Container currentContainer = NoContainer;
950
951 auto closeContainer = [&] {
952 if (currentContainer == NoContainer)
953 return;
954 if (currentContainer == InComment)
955 ps << " */";
956 else if (currentContainer == InAttr)
957 ps << " *)";
958 ps << PP::end << PP::end;
959
960 currentContainer = NoContainer;
961 };
962
963 bool isFirstContainer = true;
964 auto openContainer = [&](Container newContainer) {
965 assert(newContainer != NoContainer);
966 if (currentContainer == newContainer)
967 return false;
968 closeContainer();
969 // If not first container, insert break point but no space.
970 if (!isFirstContainer)
971 ps << (mayBreak ? PP::space : PP::nbsp);
972 isFirstContainer = false;
973 // fit container on one line if possible, break if needed.
974 ps << PP::ibox0;
975 if (newContainer == InComment)
976 ps << "/* ";
977 else if (newContainer == InAttr)
978 ps << "(* ";
979 currentContainer = newContainer;
980 // Pack attributes within to fit, align to current column when breaking.
981 ps << PP::ibox0;
982 return true;
983 };
984
985 // Break containers to starting column (0), put all on same line OR
986 // put each on their own line (cbox).
987 ps.scopedBox(PP::cbox0, [&]() {
988 for (auto attr : attrs.getAsRange<SVAttributeAttr>()) {
989 if (!openContainer(attr.getEmitAsComment().getValue() ? InComment
990 : InAttr))
991 ps << "," << (mayBreak ? PP::space : PP::nbsp);
992 ps << PPExtString(attr.getName().getValue());
993 if (attr.getExpression())
994 ps << " = " << PPExtString(attr.getExpression().getValue());
995 }
996 closeContainer();
997 });
998}
999
1000/// Retrieve value's verilog name from IR. The name must already have been
1001/// added in pre-pass and passed through "hw.verilogName" attr.
1002StringRef getVerilogValueName(Value val) {
1003 if (auto *op = val.getDefiningOp())
1004 return getSymOpName(op);
1005
1006 if (auto port = dyn_cast<BlockArgument>(val)) {
1007 // If the value is defined by for op, use its associated verilog name.
1008 auto *parent = port.getParentBlock()->getParentOp();
1009 if (isa<ForOp, GenerateForOp>(parent))
1010 return parent->getAttrOfType<StringAttr>("hw.verilogName");
1011 return getInputPortVerilogName(port.getParentBlock()->getParentOp(),
1012 port.getArgNumber());
1013 }
1014 assert(false && "unhandled value");
1015 return {};
1016}
1017
1018//===----------------------------------------------------------------------===//
1019// VerilogEmitterState
1020//===----------------------------------------------------------------------===//
1021
1022namespace {
1023
1024/// This class maintains the mutable state that cross-cuts and is shared by the
1025/// various emitters.
1026class VerilogEmitterState {
1027public:
1028 explicit VerilogEmitterState(ModuleOp designOp,
1029 const SharedEmitterState &shared,
1030 const LoweringOptions &options,
1031 const HWSymbolCache &symbolCache,
1032 const GlobalNameTable &globalNames,
1033 const FileMapping &fileMapping,
1034 llvm::formatted_raw_ostream &os,
1035 StringAttr fileName, OpLocMap &verilogLocMap)
1036 : designOp(designOp), shared(shared), options(options),
1037 symbolCache(symbolCache), globalNames(globalNames),
1038 fileMapping(fileMapping), os(os), verilogLocMap(verilogLocMap),
1039 pp(os, options.getEmittedLineLength().value_or(0)), fileName(fileName) {
1040 pp.setListener(&saver);
1041 }
1042 /// This is the root mlir::ModuleOp that holds the whole design being emitted.
1043 ModuleOp designOp;
1044
1045 const SharedEmitterState &shared;
1046
1047 /// The emitter options which control verilog emission.
1048 const LoweringOptions &options;
1049
1050 /// This is a cache of various information about the IR, in frozen state.
1051 const HWSymbolCache &symbolCache;
1052
1053 /// This tracks global names where the Verilog name needs to be different than
1054 /// the IR name.
1055 const GlobalNameTable &globalNames;
1056
1057 /// Tracks the referenceable files through their symbol.
1058 const FileMapping &fileMapping;
1059
1060 /// The stream to emit to. Use a formatted_raw_ostream, to easily get the
1061 /// current location(line,column) on the stream. This is required to record
1062 /// the verilog output location information corresponding to any op.
1063 llvm::formatted_raw_ostream &os;
1064
1065 bool encounteredError = false;
1066
1067 /// Pretty printing:
1068
1069 /// Whether a newline is expected, emitted late to provide opportunity to
1070 /// open/close boxes we don't know we need at level of individual statement.
1071 /// Every statement should set this instead of directly emitting (last)
1072 /// newline. Most statements end with emitLocationInfoAndNewLine which handles
1073 /// this.
1074 bool pendingNewline = false;
1075
1076 /// Used to record the verilog output file location of an op.
1077 OpLocMap &verilogLocMap;
1078 /// String storage backing Tokens built from temporary strings.
1079 /// PrettyPrinter will clear this as appropriate.
1080 PrintEventAndStorageListener<OpLocMap, std::pair<Operation *, bool>> saver =
1081 PrintEventAndStorageListener<OpLocMap, std::pair<Operation *, bool>>(
1082 verilogLocMap);
1083
1084 /// Pretty printer.
1085 PrettyPrinter pp;
1086
1087 /// Name of the output file, used for debug information.
1088 StringAttr fileName;
1089
1090 /// Update the location attribute of the ops with the verilog locations
1091 /// recorded in `verilogLocMap` and clear the map. `lineOffset` is added to
1092 /// all the line numbers, this is required when the modules are exported in
1093 /// parallel.
1094 void addVerilogLocToOps(unsigned int lineOffset, StringAttr fileName) {
1095 verilogLocMap.updateIRWithLoc(lineOffset, fileName,
1096 shared.designOp->getContext());
1097 verilogLocMap.clear();
1098 }
1099
1100private:
1101 VerilogEmitterState(const VerilogEmitterState &) = delete;
1102 void operator=(const VerilogEmitterState &) = delete;
1103};
1104} // namespace
1105
1106//===----------------------------------------------------------------------===//
1107// EmitterBase
1108//===----------------------------------------------------------------------===//
1109
1110namespace {
1111
1112/// The data that is unique to each callback. The operation and a flag to
1113/// indicate if the callback is for begin or end of the operation print
1114/// location.
1115using CallbackDataTy = std::pair<Operation *, bool>;
1116class EmitterBase {
1117public:
1118 // All of the mutable state we are maintaining.
1119 VerilogEmitterState &state;
1120
1121 /// Stream helper (pp, saver).
1122 TokenStreamWithCallback<OpLocMap, CallbackDataTy> ps;
1123
1124 explicit EmitterBase(VerilogEmitterState &state)
1125 : state(state),
1126 ps(state.pp, state.saver, state.options.emitVerilogLocations) {}
1127
1128 InFlightDiagnostic emitError(Operation *op, const Twine &message) {
1129 state.encounteredError = true;
1130 return op->emitError(message);
1131 }
1132
1133 InFlightDiagnostic emitOpError(Operation *op, const Twine &message) {
1134 state.encounteredError = true;
1135 return op->emitOpError(message);
1136 }
1137
1138 InFlightDiagnostic emitError(Location loc, const Twine &message = "") {
1139 state.encounteredError = true;
1140 return mlir::emitError(loc, message);
1141 }
1142
1143 void emitLocationImpl(llvm::StringRef location) {
1144 // Break so previous content is not impacted by following,
1145 // but use a 'neverbreak' so it always fits.
1146 ps << PP::neverbreak;
1147 if (!location.empty())
1148 ps << "\t// " << location; // (don't use tabs in normal pretty-printing)
1149 }
1150
1151 void emitLocationInfo(Location loc) {
1152 emitLocationImpl(
1153 LocationEmitter(state.options.locationInfoStyle, loc).strref());
1154 }
1155
1156 /// If we have location information for any of the specified operations,
1157 /// aggregate it together and print a pretty comment specifying where the
1158 /// operations came from. In any case, print a newline.
1159 void emitLocationInfoAndNewLine(const SmallPtrSetImpl<Operation *> &ops) {
1160 emitLocationImpl(
1161 LocationEmitter(state.options.locationInfoStyle, ops).strref());
1162 setPendingNewline();
1163 }
1164
1165 template <typename PPS>
1166 void emitTextWithSubstitutions(PPS &ps, StringRef string, Operation *op,
1167 llvm::function_ref<void(Value)> operandEmitter,
1168 ArrayAttr symAttrs);
1169
1170 /// Emit the value of a StringAttr as one or more Verilog "one-line" comments
1171 /// ("//"). Break the comment to respect the emittedLineLength and trim
1172 /// whitespace after a line break. Do nothing if the StringAttr is null or
1173 /// the value is empty.
1174 void emitComment(StringAttr comment);
1175
1176 /// If previous emission requires a newline, emit it now.
1177 /// This gives us opportunity to open/close boxes before linebreak.
1178 void emitPendingNewlineIfNeeded() {
1179 if (state.pendingNewline) {
1180 state.pendingNewline = false;
1181 ps << PP::newline;
1182 }
1183 }
1184 void setPendingNewline() {
1185 assert(!state.pendingNewline);
1186 state.pendingNewline = true;
1187 }
1188
1189 void startStatement() { emitPendingNewlineIfNeeded(); }
1190
1191private:
1192 void operator=(const EmitterBase &) = delete;
1193 EmitterBase(const EmitterBase &) = delete;
1194};
1195} // end anonymous namespace
1196
1197template <typename PPS>
1198void EmitterBase::emitTextWithSubstitutions(
1199 PPS &ps, StringRef string, Operation *op,
1200 llvm::function_ref<void(Value)> operandEmitter, ArrayAttr symAttrs) {
1201
1202 // Perform operand substitions as we emit the line string. We turn {{42}}
1203 // into the value of operand 42.
1204 auto namify = [&](Attribute sym, HWSymbolCache::Item item) {
1205 // CAVEAT: These accesses can reach into other modules through inner name
1206 // references, which are currently being processed. Do not add those remote
1207 // operations to this module's `names`, which is reserved for things named
1208 // *within* this module. Instead, you have to rely on those remote
1209 // operations to have been named inside the global names table. If they
1210 // haven't, take a look at name legalization first.
1211 if (auto *itemOp = item.getOp()) {
1212 if (item.hasPort()) {
1213 return getPortVerilogName(itemOp, item.getPort());
1214 }
1215 StringRef symOpName = getSymOpName(itemOp);
1216 if (!symOpName.empty())
1217 return symOpName;
1218 emitError(itemOp, "cannot get name for symbol ") << sym;
1219 } else {
1220 emitError(op, "cannot get name for symbol ") << sym;
1221 }
1222 return StringRef("<INVALID>");
1223 };
1224
1225 // Scan 'line' for a substitution, emitting any non-substitution prefix,
1226 // then the mentioned operand, chopping the relevant text off 'line' and
1227 // returning true. This returns false if no substitution is found.
1228 unsigned numSymOps = symAttrs.size();
1229 auto emitUntilSubstitution = [&](size_t next = 0) -> bool {
1230 size_t start = 0;
1231 while (true) {
1232 next = string.find("{{", next);
1233 if (next == StringRef::npos)
1234 return false;
1235
1236 // Check to make sure we have a number followed by }}. If not, we
1237 // ignore the {{ sequence as something that could happen in Verilog.
1238 next += 2;
1239 start = next;
1240 while (next < string.size() && isdigit(string[next]))
1241 ++next;
1242 // We need at least one digit.
1243 if (start == next) {
1244 next--;
1245 continue;
1246 }
1247 size_t operandNoLength = next - start;
1248
1249 // Format string options follow a ':'.
1250 StringRef fmtOptsStr;
1251 if (string[next] == ':') {
1252 size_t startFmtOpts = next + 1;
1253 while (next < string.size() && string[next] != '}')
1254 ++next;
1255 fmtOptsStr = string.substr(startFmtOpts, next - startFmtOpts);
1256 }
1257
1258 // We must have a }} right after the digits.
1259 if (!string.substr(next).starts_with("}}"))
1260 continue;
1261
1262 // We must be able to decode the integer into an unsigned.
1263 unsigned operandNo = 0;
1264 if (string.drop_front(start)
1265 .take_front(operandNoLength)
1266 .getAsInteger(10, operandNo)) {
1267 emitError(op, "operand substitution too large");
1268 continue;
1269 }
1270 next += 2;
1271
1272 // Emit any text before the substitution.
1273 auto before = string.take_front(start - 2);
1274 if (!before.empty())
1275 ps << PPExtString(before);
1276
1277 // operandNo can either refer to Operands or symOps. symOps are
1278 // numbered after the operands.
1279 if (operandNo < op->getNumOperands())
1280 // Emit the operand.
1281 operandEmitter(op->getOperand(operandNo));
1282 else if ((operandNo - op->getNumOperands()) < numSymOps) {
1283 unsigned symOpNum = operandNo - op->getNumOperands();
1284 auto sym = symAttrs[symOpNum];
1285 StringRef symVerilogName;
1286 if (auto fsym = dyn_cast<FlatSymbolRefAttr>(sym)) {
1287 if (auto *symOp = state.symbolCache.getDefinition(fsym)) {
1288 if (auto globalRef = dyn_cast<HierPathOp>(symOp)) {
1289 auto namepath = globalRef.getNamepathAttr().getValue();
1290 for (auto [index, sym] : llvm::enumerate(namepath)) {
1291 // Emit the seperator string.
1292 if (index > 0)
1293 ps << (fmtOptsStr.empty() ? "." : fmtOptsStr);
1294
1295 auto innerRef = cast<InnerRefAttr>(sym);
1296 auto ref = state.symbolCache.getInnerDefinition(
1297 innerRef.getModule(), innerRef.getName());
1298 ps << namify(innerRef, ref);
1299 }
1300 } else {
1301 symVerilogName = namify(sym, symOp);
1302 }
1303 }
1304 } else if (auto isym = dyn_cast<InnerRefAttr>(sym)) {
1305 auto symOp = state.symbolCache.getInnerDefinition(isym.getModule(),
1306 isym.getName());
1307 symVerilogName = namify(sym, symOp);
1308 }
1309 if (!symVerilogName.empty())
1310 ps << PPExtString(symVerilogName);
1311 } else {
1312 emitError(op, "operand " + llvm::utostr(operandNo) + " isn't valid");
1313 continue;
1314 }
1315 // Forget about the part we emitted.
1316 string = string.drop_front(next);
1317 return true;
1318 }
1319 };
1320
1321 // Emit all the substitutions.
1322 while (emitUntilSubstitution())
1323 ;
1324
1325 // Emit any text after the last substitution.
1326 if (!string.empty())
1327 ps << PPExtString(string);
1328}
1329
1330void EmitterBase::emitComment(StringAttr comment) {
1331 if (!comment)
1332 return;
1333
1334 // Set a line length for the comment. Subtract off the leading comment and
1335 // space ("// ") as well as the current indent level to simplify later
1336 // arithmetic. Ensure that this line length doesn't go below zero.
1337 std::optional<size_t> lineLength = state.options.getEmittedLineLength();
1338 if (lineLength)
1339 lineLength = std::max<size_t>(*lineLength, 3) - 3;
1340
1341 // Process the comment in line chunks extracted from manually specified line
1342 // breaks. This is done to preserve user-specified line breaking if used.
1343 auto ref = comment.getValue();
1344 StringRef line;
1345 while (!ref.empty()) {
1346 std::tie(line, ref) = ref.split("\n");
1347 // Emit each comment line breaking it if it exceeds the emittedLineLength.
1348 for (;;) {
1349 startStatement();
1350 ps << "// ";
1351
1352 // Base case 1: the entire comment fits on one line.
1353 if (!lineLength || line.size() <= lineLength) {
1354 ps << PPExtString(line);
1355 setPendingNewline();
1356 break;
1357 }
1358
1359 // The comment does NOT fit on one line. Use a simple algorithm to find
1360 // a position to break the line:
1361 // 1) Search backwards for whitespace and break there if you find it.
1362 // 2) If no whitespace exists in (1), search forward for whitespace
1363 // and break there.
1364 // This algorithm violates the emittedLineLength if (2) ever occurrs,
1365 // but it's dead simple.
1366 auto breakPos = line.rfind(' ', *lineLength);
1367 // No whitespace exists looking backwards.
1368 if (breakPos == StringRef::npos) {
1369 breakPos = line.find(' ', *lineLength);
1370 // No whitespace exists looking forward (you hit the end of the
1371 // string).
1372 if (breakPos == StringRef::npos)
1373 breakPos = line.size();
1374 }
1375
1376 // Emit up to the break position. Trim any whitespace after the break
1377 // position. Exit if nothing is left to emit. Otherwise, update the
1378 // comment ref and continue;
1379 ps << PPExtString(line.take_front(breakPos));
1380 setPendingNewline();
1381 breakPos = line.find_first_not_of(' ', breakPos);
1382 // Base Case 2: nothing left except whitespace.
1383 if (breakPos == StringRef::npos)
1384 break;
1385
1386 line = line.drop_front(breakPos);
1387 }
1388 }
1389}
1390
1391/// Given an expression that is spilled into a temporary wire, try to synthesize
1392/// a better name than "_T_42" based on the structure of the expression.
1393// NOLINTBEGIN(misc-no-recursion)
1395 StringAttr result;
1396 bool addPrefixUnderScore = true;
1397
1398 // Look through read_inout.
1399 if (auto read = expr.getDefiningOp<ReadInOutOp>())
1400 return inferStructuralNameForTemporary(read.getInput());
1401
1402 // Module ports carry names!
1403 if (auto blockArg = dyn_cast<BlockArgument>(expr)) {
1404 auto moduleOp =
1405 cast<HWEmittableModuleLike>(blockArg.getOwner()->getParentOp());
1406 StringRef name = getPortVerilogName(moduleOp, blockArg.getArgNumber());
1407 result = StringAttr::get(expr.getContext(), name);
1408
1409 } else if (auto *op = expr.getDefiningOp()) {
1410 // Uses of a wire, register or logic can be done inline.
1411 if (isa<sv::WireOp, RegOp, LogicOp, sv::VarOp>(op)) {
1412 StringRef name = getSymOpName(op);
1413 result = StringAttr::get(expr.getContext(), name);
1414
1415 } else if (auto nameHint = op->getAttrOfType<StringAttr>("sv.namehint")) {
1416 // Use a dialect (sv) attribute to get a hint for the name if the op
1417 // doesn't explicitly specify it. Do this last
1418 result = nameHint;
1419
1420 // If there is a namehint, don't add underscores to the name.
1421 addPrefixUnderScore = false;
1422 } else {
1423 TypeSwitch<Operation *>(op)
1424 // Generate a pretty name for VerbatimExpr's that look macro-like
1425 // using the same logic that generates the MLIR syntax name.
1426 .Case([&result](VerbatimExprOp verbatim) {
1427 verbatim.getAsmResultNames([&](Value, StringRef name) {
1428 result = StringAttr::get(verbatim.getContext(), name);
1429 });
1430 })
1431 .Case([&result](VerbatimExprSEOp verbatim) {
1432 verbatim.getAsmResultNames([&](Value, StringRef name) {
1433 result = StringAttr::get(verbatim.getContext(), name);
1434 });
1435 })
1436
1437 // If this is an extract from a namable object, derive a name from it.
1438 .Case([&result](ExtractOp extract) {
1439 if (auto operandName =
1440 inferStructuralNameForTemporary(extract.getInput())) {
1441 unsigned numBits =
1442 cast<IntegerType>(extract.getType()).getWidth();
1443 if (numBits == 1)
1444 result = StringAttr::get(extract.getContext(),
1445 operandName.strref() + "_" +
1446 Twine(extract.getLowBit()));
1447 else
1448 result = StringAttr::get(
1449 extract.getContext(),
1450 operandName.strref() + "_" +
1451 Twine(extract.getLowBit() + numBits - 1) + "to" +
1452 Twine(extract.getLowBit()));
1453 }
1454 });
1455 // TODO: handle other common patterns.
1456 }
1457 }
1458
1459 // Make sure any synthesized name starts with an _.
1460 if (!result || result.strref().empty())
1461 return {};
1462
1463 // Make sure that all temporary names start with an underscore.
1464 if (addPrefixUnderScore && result.strref().front() != '_')
1465 result = StringAttr::get(expr.getContext(), "_" + result.strref());
1466
1467 return result;
1468}
1469// NOLINTEND(misc-no-recursion)
1470
1471//===----------------------------------------------------------------------===//
1472// ModuleEmitter
1473//===----------------------------------------------------------------------===//
1474
1475namespace {
1476
1477class ModuleEmitter : public EmitterBase {
1478public:
1479 explicit ModuleEmitter(VerilogEmitterState &state)
1480 : EmitterBase(state), currentModuleOp(nullptr),
1481 fieldNameResolver(FieldNameResolver(state.globalNames, state.options)) {
1482 }
1483 ~ModuleEmitter() {
1484 emitPendingNewlineIfNeeded();
1485 ps.eof();
1486 };
1487
1488 void emitParameters(Operation *module, ArrayAttr params);
1489 void emitPortList(Operation *module, const ModulePortInfo &portInfo,
1490 bool emitAsTwoStateType = false);
1491
1492 void emitHWModule(HWModuleOp module);
1493 void emitHWGeneratedModule(HWModuleGeneratedOp module);
1494 void emitFunc(FuncOp);
1495
1496 // Statements.
1497 void emitStatement(Operation *op);
1498 void emitBind(BindOp op);
1499 void emitBindInterface(BindInterfaceOp op);
1500
1501 void emitSVAttributes(Operation *op);
1502
1503 /// Legalize the given field name if it is an invalid verilog name.
1504 StringRef getVerilogStructFieldName(StringAttr field) {
1505 return fieldNameResolver.getRenamedFieldName(field).getValue();
1506 }
1507
1508 //===--------------------------------------------------------------------===//
1509 // Methods for formatting types.
1510
1511 /// Emit a type's packed dimensions.
1512 void emitTypeDims(Type type, Location loc, raw_ostream &os);
1513
1514 /// Print the specified packed portion of the type to the specified stream,
1515 ///
1516 /// * 'optionalAliasType' can be provided to perform any alias-aware printing
1517 /// of the inner type.
1518 /// * When `implicitIntType` is false, a "logic" is printed. This is used in
1519 /// struct fields and typedefs.
1520 /// * When `singleBitDefaultType` is false, single bit values are printed as
1521 /// `[0:0]`. This is used in parameter lists.
1522 ///
1523 /// This returns true if anything was printed.
1524 bool printPackedType(Type type, raw_ostream &os, Location loc,
1525 Type optionalAliasType = {}, bool implicitIntType = true,
1526 bool singleBitDefaultType = true,
1527 bool emitAsTwoStateType = false);
1528
1529 /// Output the unpacked array dimensions. This is the part of the type that
1530 /// is to the right of the name.
1531 void printUnpackedTypePostfix(Type type, raw_ostream &os);
1532
1533 //===--------------------------------------------------------------------===//
1534 // Methods for formatting parameters.
1535
1536 /// Prints a parameter attribute expression in a Verilog compatible way to the
1537 /// specified stream. This returns the precedence of the generated string.
1538 SubExprInfo printParamValue(Attribute value, raw_ostream &os,
1539 function_ref<InFlightDiagnostic()> emitError);
1540
1541 SubExprInfo printParamValue(Attribute value, raw_ostream &os,
1542 VerilogPrecedence parenthesizeIfLooserThan,
1543 function_ref<InFlightDiagnostic()> emitError);
1544
1545 //===--------------------------------------------------------------------===//
1546 // Mutable state while emitting a module body.
1547
1548 /// This is the current module being emitted for a HWModuleOp.
1549 Operation *currentModuleOp;
1550 Operation *currentPackage = nullptr;
1551
1552 /// This set keeps track of expressions that were emitted into their
1553 /// 'automatic logic' or 'localparam' declaration. This is only used for
1554 /// expressions in a procedural region, because we otherwise just emit wires
1555 /// on demand.
1556 SmallPtrSet<Operation *, 16> expressionsEmittedIntoDecl;
1557
1558 /// This class keeps track of field name renamings in the module scope.
1559 FieldNameResolver fieldNameResolver;
1560
1561 /// This keeps track of assignments folded into wire emissions
1562 SmallPtrSet<Operation *, 16> assignsInlined;
1563};
1564
1565} // end anonymous namespace
1566
1567/// Returns true if `type` prints its own SystemVerilog `data_type`, so
1568/// its declaration must not be prefixed with `logic` or `reg`. Integer types
1569/// are the exception: they print only a packed range like `[3:0]`, so the
1570/// declaration must supply `logic` or `reg`. Packed and unpacked arrays
1571/// inherit this property from their elememt type. See SV Spec 6.8.
1572static bool hasExplicitDataType(Type type) {
1573 return TypeSwitch<Type, bool>(type)
1574 .Case<UnpackedArrayType, ArrayType>(
1575 [](auto t) { return hasExplicitDataType(t.getElementType()); })
1576 .Case<IntegerType>([](auto) { return false; })
1577 .Default([](auto) { return true; });
1578}
1579
1580/// Return the word (e.g. "reg") in Verilog to declare the specified thing.
1581/// If `stripAutomatic` is true, "automatic" is not used even for a declaration
1582/// in a non-procedural region.
1583static StringRef getVerilogDeclWord(Operation *op,
1584 const ModuleEmitter &emitter) {
1585 if (isa<RegOp>(op)) {
1586 // Check if the type stored in this register is a struct or array of
1587 // structs. In this case, according to spec section 6.8, the "reg" prefix
1588 // should be left off.
1589 auto elementType =
1590 cast<InOutType>(op->getResult(0).getType()).getElementType();
1591 // Unwrap arrays. Since packed arrays cannot contain unpacked arrays, we can
1592 // unpack unpacked arrays first.
1593 while (auto arrayType = hw::type_dyn_cast<UnpackedArrayType>(elementType))
1594 elementType = arrayType.getElementType();
1595 while (auto arrayType = hw::type_dyn_cast<ArrayType>(elementType))
1596 elementType = arrayType.getElementType();
1597
1598 if (isa<StructType, UnionType, EnumType, TypeAliasType>(elementType))
1599 return "";
1600
1601 return "reg";
1602 }
1603
1604 if (isa<sv::WireOp>(op))
1605 return "wire";
1606 if (isa<ConstantOp, AggregateConstantOp, LocalParamOp, ParamValueOp>(op))
1607 return "localparam";
1608
1609 // Interfaces instances use the name of the declared interface.
1610 if (auto interface = dyn_cast<InterfaceInstanceOp>(op))
1611 return interface.getInterfaceType().getInterface().getValue();
1612
1613 // If 'op' is in a module, output 'wire'. If 'op' is in a procedural block,
1614 // fall through to default.
1615 bool isProcedural = op->getParentOp()->hasTrait<ProceduralRegion>();
1616
1617 // If this decl is within a function, "automatic" is not needed because
1618 // "automatic" is added to its definition.
1619 bool stripAutomatic = isa_and_nonnull<FuncOp>(emitter.currentModuleOp);
1620
1621 if (auto var = dyn_cast<VarOp>(op)) {
1622 bool hasExplicitType = hasExplicitDataType(var.getElementType());
1623 // A var defined in a procedural region is emitted as 'automatic'. If the
1624 // type has a struct, 'logic' is already emitted within the struct type
1625 // definition (e.g. struct packed {logic foo;}), so don't emit it again.
1626 // A var carrying `sv.no_automatic` (i.e. one that used to be an `sv.reg`)
1627 // keeps the regular declaration style even in a procedural region.
1628 if (isProcedural && !stripAutomatic && !var->hasAttr("sv.no_automatic"))
1629 return hasStructType(var.getElementType()) ? "automatic"
1630 : "automatic logic";
1631
1632 switch (emitter.state.options.varOpDeclStyle) {
1634 return hasExplicitType ? "var" : "var logic";
1636 return hasExplicitType ? "" : "logic";
1638 return hasExplicitType ? "" : "reg";
1639 }
1640 }
1641
1642 if (isa<LogicOp>(op)) {
1643 // If the logic op is defined in a procedural region, add 'automatic'
1644 // keyword. If the op has a struct type, 'logic' keyword is already emitted
1645 // within a struct type definition (e.g. struct packed {logic foo;}). So we
1646 // should not emit extra 'logic'.
1647 bool hasStruct = hasStructType(op->getResult(0).getType());
1648 if (isProcedural && !stripAutomatic)
1649 return hasStruct ? "automatic" : "automatic logic";
1650 return hasStruct ? "" : "logic";
1651 }
1652
1653 if (!isProcedural)
1654 return "wire";
1655
1656 if (stripAutomatic)
1657 return hasStructType(op->getResult(0).getType()) ? "" : "logic";
1658
1659 // "automatic" values aren't allowed in disallowLocalVariables mode.
1660 assert(!emitter.state.options.disallowLocalVariables &&
1661 "automatic variables not allowed");
1662
1663 // If the type contains a struct type, we have to use only "automatic" because
1664 // "automatic struct" is syntactically correct.
1665 return hasStructType(op->getResult(0).getType()) ? "automatic"
1666 : "automatic logic";
1667}
1668
1669//===----------------------------------------------------------------------===//
1670// Methods for formatting types.
1671
1672/// Emit a single dimension.
1673static void emitDim(Attribute width, raw_ostream &os, Location loc,
1674 ModuleEmitter &emitter, bool downTo) {
1675 if (!width) {
1676 os << "<<invalid type>>";
1677 return;
1678 }
1679 if (auto intAttr = dyn_cast<IntegerAttr>(width)) {
1680 if (intAttr.getValue().isZero()) {
1681 os << "/*Zero Width*/";
1682 } else {
1683 os << '[';
1684 if (!downTo)
1685 os << "0:";
1686 os << (intAttr.getValue().getZExtValue() - 1);
1687 if (downTo)
1688 os << ":0";
1689 os << ']';
1690 }
1691 return;
1692 }
1693
1694 // Otherwise it must be a parameterized dimension. Shove the "-1" into the
1695 // attribute so it gets printed in canonical form.
1696 auto typedAttr = dyn_cast<TypedAttr>(width);
1697 if (!typedAttr) {
1698 emitter.emitError(loc, "untyped dimension attribute ") << width;
1699 return;
1700 }
1701 auto negOne =
1702 getIntAttr(loc.getContext(), typedAttr.getType(),
1703 APInt(typedAttr.getType().getIntOrFloatBitWidth(), -1L, true));
1704 width = ParamExprAttr::get(PEO::Add, typedAttr, negOne);
1705 os << '[';
1706 if (!downTo)
1707 os << "0:";
1708 emitter.printParamValue(width, os, [loc, &emitter]() {
1709 return emitter.emitError(loc, "invalid parameter in type");
1710 });
1711 if (downTo)
1712 os << ":0";
1713 os << ']';
1714}
1715
1716/// Emit a list of packed dimensions.
1717static void emitDims(ArrayRef<Attribute> dims, raw_ostream &os, Location loc,
1718 ModuleEmitter &emitter) {
1719 for (Attribute width : dims) {
1720 emitDim(width, os, loc, emitter, /*downTo=*/true);
1721 }
1722}
1723
1724/// Emit a type's packed dimensions.
1725void ModuleEmitter::emitTypeDims(Type type, Location loc, raw_ostream &os) {
1726 SmallVector<Attribute, 4> dims;
1727 getTypeDims(dims, type, loc,
1728 [&](Location loc) { return this->emitError(loc); });
1729 emitDims(dims, os, loc, *this);
1730}
1731
1732/// Return a 2-state integer atom type name if the width matches. See Spec 6.8
1733/// Variable declarations.
1734static StringRef getTwoStateIntegerAtomType(size_t width) {
1735 switch (width) {
1736 case 8:
1737 return "byte";
1738 case 16:
1739 return "shortint";
1740 case 32:
1741 return "int";
1742 case 64:
1743 return "longint";
1744 default:
1745 return "";
1746 }
1747}
1748
1749/// Output the basic type that consists of packed and primitive types. This is
1750/// those to the left of the name in verilog. implicitIntType controls whether
1751/// to print a base type for (logic) for inteters or whether the caller will
1752/// have handled this (with logic, wire, reg, etc).
1753/// optionalAliasType can be provided to perform any necessary alias-aware
1754/// printing of 'type'.
1755///
1756/// Returns true when anything was printed out.
1757// NOLINTBEGIN(misc-no-recursion)
1758static bool printPackedTypeImpl(Type type, raw_ostream &os, Location loc,
1759 SmallVectorImpl<Attribute> &dims,
1760 bool implicitIntType, bool singleBitDefaultType,
1761 ModuleEmitter &emitter,
1762 Type optionalAliasType = {},
1763 bool emitAsTwoStateType = false) {
1764 return TypeSwitch<Type, bool>(type)
1765 .Case<IntegerType>([&](IntegerType integerType) -> bool {
1766 if (emitAsTwoStateType && dims.empty()) {
1767 auto typeName = getTwoStateIntegerAtomType(integerType.getWidth());
1768 if (!typeName.empty()) {
1769 os << typeName;
1770 return true;
1771 }
1772 }
1773 if (integerType.getWidth() != 1 || !singleBitDefaultType)
1774 dims.push_back(
1775 getInt32Attr(type.getContext(), integerType.getWidth()));
1776
1777 StringRef typeName =
1778 (emitAsTwoStateType ? "bit" : (implicitIntType ? "" : "logic"));
1779 if (!typeName.empty()) {
1780 os << typeName;
1781 if (!dims.empty())
1782 os << ' ';
1783 }
1784
1785 emitDims(dims, os, loc, emitter);
1786 return !dims.empty() || !implicitIntType;
1787 })
1788 .Case<IntType>([&](IntType intType) {
1789 if (!implicitIntType)
1790 os << "logic ";
1791 dims.push_back(intType.getWidth());
1792 emitDims(dims, os, loc, emitter);
1793 return true;
1794 })
1795 .Case<ArrayType>([&](ArrayType arrayType) {
1796 dims.push_back(arrayType.getSizeAttr());
1797 return printPackedTypeImpl(arrayType.getElementType(), os, loc, dims,
1798 implicitIntType, singleBitDefaultType,
1799 emitter, /*optionalAliasType=*/{},
1800 emitAsTwoStateType);
1801 })
1802 .Case<InOutType, sv::NetType, sv::VarType>([&](auto handleType) {
1803 return printPackedTypeImpl(handleType.getElementType(), os, loc, dims,
1804 implicitIntType, singleBitDefaultType,
1805 emitter, /*optionalAliasType=*/{},
1806 emitAsTwoStateType);
1807 })
1808 .Case<EnumType>([&](EnumType enumType) {
1809 assert(enumType.getBitWidth().has_value() &&
1810 "enum type must have bitwidth");
1811 os << "enum ";
1812 if (enumType.getBitWidth() != 32)
1813 os << "bit [" << *enumType.getBitWidth() - 1 << ":0] ";
1814 os << "{";
1815 Type enumPrefixType = optionalAliasType ? optionalAliasType : enumType;
1816 llvm::interleaveComma(
1817 enumType.getFields().getAsRange<StringAttr>(), os,
1818 [&](auto enumerator) {
1819 os << emitter.fieldNameResolver.getEnumFieldName(
1820 hw::EnumFieldAttr::get(loc, enumerator, enumPrefixType),
1821 emitter.currentPackage);
1822 });
1823 os << "}";
1824 return true;
1825 })
1826 .Case<StructType>([&](StructType structType) {
1827 if (structType.getElements().empty() || isZeroBitType(structType)) {
1828 os << "/*Zero Width*/";
1829 return true;
1830 }
1831 os << "struct packed {";
1832 for (auto &element : structType.getElements()) {
1833 if (isZeroBitType(element.type)) {
1834 os << "/*" << emitter.getVerilogStructFieldName(element.name)
1835 << ": Zero Width;*/ ";
1836 continue;
1837 }
1838 SmallVector<Attribute, 8> structDims;
1839 printPackedTypeImpl(stripUnpackedTypes(element.type), os, loc,
1840 structDims,
1841 /*implicitIntType=*/false,
1842 /*singleBitDefaultType=*/true, emitter,
1843 /*optionalAliasType=*/{}, emitAsTwoStateType);
1844 os << ' ' << emitter.getVerilogStructFieldName(element.name);
1845 emitter.printUnpackedTypePostfix(element.type, os);
1846 os << "; ";
1847 }
1848 os << '}';
1849 emitDims(dims, os, loc, emitter);
1850 return true;
1851 })
1852 .Case<UnionType>([&](UnionType unionType) {
1853 if (unionType.getElements().empty() || isZeroBitType(unionType)) {
1854 os << "/*Zero Width*/";
1855 return true;
1856 }
1857
1858 int64_t unionWidth = hw::getBitWidth(unionType);
1859 assert(unionWidth > 0 &&
1860 "SV packed union must have known positive bitwidth");
1861 os << "union packed {";
1862 for (auto &element : unionType.getElements()) {
1863 if (isZeroBitType(element.type)) {
1864 os << "/*" << emitter.getVerilogStructFieldName(element.name)
1865 << ": Zero Width;*/ ";
1866 continue;
1867 }
1868 int64_t elementWidth = hw::getBitWidth(element.type);
1869 // Members share the LSB of the union and are moved towards the MSB
1870 // by their offset.
1871 auto elementOffset = static_cast<int64_t>(element.offset);
1872 bool needsPadding = elementWidth < unionWidth || elementOffset > 0;
1873 int64_t prePadding = unionWidth - (elementWidth + elementOffset);
1874 if (needsPadding) {
1875 os << " struct packed {";
1876 if (prePadding > 0) {
1877 os << (emitAsTwoStateType ? "bit" : "logic") << " ["
1878 << prePadding - 1 << ":0] "
1879 << "__pre_padding_" << element.name.getValue() << "; ";
1880 }
1881 }
1882
1883 SmallVector<Attribute, 8> structDims;
1885 stripUnpackedTypes(element.type), os, loc, structDims,
1886 /*implicitIntType=*/false,
1887 /*singleBitDefaultType=*/true, emitter, {}, emitAsTwoStateType);
1888 os << ' ' << emitter.getVerilogStructFieldName(element.name);
1889 emitter.printUnpackedTypePostfix(element.type, os);
1890 os << ";";
1891
1892 if (needsPadding) {
1893 if (elementOffset > 0) {
1894 os << " " << (emitAsTwoStateType ? "bit" : "logic") << " ["
1895 << elementOffset - 1 << ":0] "
1896 << "__post_padding_" << element.name.getValue() << ";";
1897 }
1898 os << "} " << emitter.getVerilogStructFieldName(element.name)
1899 << ";";
1900 }
1901 }
1902 os << '}';
1903 emitDims(dims, os, loc, emitter);
1904 return true;
1905 })
1906
1907 .Case<InterfaceType>([](InterfaceType ifaceType) { return false; })
1908 .Case<ModportType>([&](ModportType modportType) {
1909 auto modportAttr = modportType.getModport();
1910 os << modportAttr.getRootReference().getValue() << "."
1911 << modportAttr.getNestedReferences().front().getValue();
1912 return true;
1913 })
1914 .Case<UnpackedArrayType>([&](UnpackedArrayType arrayType) {
1915 os << "<<unexpected unpacked array>>";
1916 emitter.emitError(loc, "Unexpected unpacked array in packed type ")
1917 << arrayType;
1918 return true;
1919 })
1920 .Case<TypeAliasType>([&](TypeAliasType typeRef) {
1921 auto typedecl = typeRef.getTypeDecl(emitter.state.symbolCache);
1922 if (!typedecl) {
1923 emitter.emitError(loc, "unresolvable type reference");
1924 return false;
1925 }
1926 if (typedecl.getType() != typeRef.getInnerType()) {
1927 emitter.emitError(loc, "declared type did not match aliased type");
1928 return false;
1929 }
1930
1931 if (auto *package = typedecl->getParentOp();
1932 isa<PackageOp, PackageExternOp>(package)) {
1933 if (package != emitter.currentPackage)
1934 os << getSymOpName(package) << "::";
1935 }
1936 os << typedecl.getPreferredName();
1937 emitDims(dims, os, typedecl->getLoc(), emitter);
1938 return true;
1939 })
1940 .Default([&](Type type) {
1941 os << "<<invalid type '" << type << "'>>";
1942 emitter.emitError(loc, "value has an unsupported verilog type ")
1943 << type;
1944 return true;
1945 });
1946}
1947// NOLINTEND(misc-no-recursion)
1948
1949/// Print the specified packed portion of the type to the specified stream,
1950///
1951/// * When `implicitIntType` is false, a "logic" is printed. This is used in
1952/// struct fields and typedefs.
1953/// * When `singleBitDefaultType` is false, single bit values are printed as
1954/// `[0:0]`. This is used in parameter lists.
1955/// * When `emitAsTwoStateType` is true, a "bit" is printed. This is used in
1956/// DPI function import statement.
1957///
1958/// This returns true if anything was printed.
1959bool ModuleEmitter::printPackedType(Type type, raw_ostream &os, Location loc,
1960 Type optionalAliasType,
1961 bool implicitIntType,
1962 bool singleBitDefaultType,
1963 bool emitAsTwoStateType) {
1964 SmallVector<Attribute, 8> packedDimensions;
1965 return printPackedTypeImpl(type, os, loc, packedDimensions, implicitIntType,
1966 singleBitDefaultType, *this, optionalAliasType,
1967 emitAsTwoStateType);
1968}
1969
1970/// Output the unpacked array dimensions. This is the part of the type that is
1971/// to the right of the name.
1972// NOLINTBEGIN(misc-no-recursion)
1973void ModuleEmitter::printUnpackedTypePostfix(Type type, raw_ostream &os) {
1974 TypeSwitch<Type, void>(type)
1975 .Case<InOutType, NetType, VarType>([&](auto valueType) {
1976 printUnpackedTypePostfix(valueType.getElementType(), os);
1977 })
1978 .Case<UnpackedArrayType>([&](UnpackedArrayType arrayType) {
1979 auto loc = currentModuleOp ? currentModuleOp->getLoc()
1980 : state.designOp->getLoc();
1981 emitDim(arrayType.getSizeAttr(), os, loc, *this,
1982 /*downTo=*/false);
1983 printUnpackedTypePostfix(arrayType.getElementType(), os);
1984 })
1985 .Case<sv::UnpackedOpenArrayType>([&](auto arrayType) {
1986 os << "[]";
1987 printUnpackedTypePostfix(arrayType.getElementType(), os);
1988 })
1989 .Case<InterfaceType>([&](auto) {
1990 // Interface instantiations have parentheses like a module with no
1991 // ports.
1992 os << "()";
1993 });
1994}
1995// NOLINTEND(misc-no-recursion)
1996
1997//===----------------------------------------------------------------------===//
1998// Methods for formatting parameters.
1999
2000/// Prints a parameter attribute expression in a Verilog compatible way to the
2001/// specified stream. This returns the precedence of the generated string.
2002SubExprInfo
2003ModuleEmitter::printParamValue(Attribute value, raw_ostream &os,
2004 function_ref<InFlightDiagnostic()> emitError) {
2005 return printParamValue(value, os, VerilogPrecedence::LowestPrecedence,
2006 emitError);
2007}
2008
2009/// Helper that prints a parameter constant value in a Verilog compatible way.
2010/// This returns the precedence of the generated string.
2011// NOLINTBEGIN(misc-no-recursion)
2012SubExprInfo
2013ModuleEmitter::printParamValue(Attribute value, raw_ostream &os,
2014 VerilogPrecedence parenthesizeIfLooserThan,
2015 function_ref<InFlightDiagnostic()> emitError) {
2016 if (auto intAttr = dyn_cast<IntegerAttr>(value)) {
2017 IntegerType intTy = cast<IntegerType>(intAttr.getType());
2018 APInt value = intAttr.getValue();
2019
2020 // We omit the width specifier if the value is <= 32-bits in size, which
2021 // makes this more compatible with unknown width extmodules.
2022 if (intTy.getWidth() > 32) {
2023 // Sign comes out before any width specifier.
2024 if (value.isNegative() && (intTy.isSigned() || intTy.isSignless())) {
2025 os << '-';
2026 value = -value;
2027 }
2028 if (intTy.isSigned())
2029 os << intTy.getWidth() << "'sd";
2030 else
2031 os << intTy.getWidth() << "'d";
2032 }
2033 value.print(os, intTy.isSigned());
2034 return {Symbol, intTy.isSigned() ? IsSigned : IsUnsigned};
2035 }
2036 if (auto strAttr = dyn_cast<StringAttr>(value)) {
2037 os << '"';
2038 os.write_escaped(strAttr.getValue());
2039 os << '"';
2040 return {Symbol, IsUnsigned};
2041 }
2042 if (auto fpAttr = dyn_cast<FloatAttr>(value)) {
2043 // TODO: relying on float printing to be precise is not a good idea.
2044 os << fpAttr.getValueAsDouble();
2045 return {Symbol, IsUnsigned};
2046 }
2047 if (auto verbatimParam = dyn_cast<ParamVerbatimAttr>(value)) {
2048 os << verbatimParam.getValue().getValue();
2049 return {Symbol, IsUnsigned};
2050 }
2051 if (auto parameterRef = dyn_cast<ParamDeclRefAttr>(value)) {
2052 // Get the name of this parameter (in case it got renamed).
2053 os << state.globalNames.getParameterVerilogName(currentModuleOp,
2054 parameterRef.getName());
2055
2056 // TODO: Should we support signed parameters?
2057 return {Symbol, IsUnsigned};
2058 }
2059
2060 // Handle nested expressions.
2061 auto expr = dyn_cast<ParamExprAttr>(value);
2062 if (!expr) {
2063 os << "<<UNKNOWN MLIRATTR: " << value << ">>";
2064 emitError() << " = " << value;
2065 return {LowestPrecedence, IsUnsigned};
2066 }
2067
2068 StringRef operatorStr;
2069 StringRef openStr, closeStr;
2070 VerilogPrecedence subprecedence = LowestPrecedence;
2071 VerilogPrecedence prec; // precedence of the emitted expression.
2072 std::optional<SubExprSignResult> operandSign;
2073 bool isUnary = false;
2074 bool hasOpenClose = false;
2075
2076 switch (expr.getOpcode()) {
2077 case PEO::Add:
2078 operatorStr = " + ";
2079 subprecedence = Addition;
2080 break;
2081 case PEO::Mul:
2082 operatorStr = " * ";
2083 subprecedence = Multiply;
2084 break;
2085 case PEO::And:
2086 operatorStr = " & ";
2087 subprecedence = And;
2088 break;
2089 case PEO::Or:
2090 operatorStr = " | ";
2091 subprecedence = Or;
2092 break;
2093 case PEO::Xor:
2094 operatorStr = " ^ ";
2095 subprecedence = Xor;
2096 break;
2097 case PEO::Shl:
2098 operatorStr = " << ";
2099 subprecedence = Shift;
2100 break;
2101 case PEO::ShrU:
2102 // >> in verilog is always a logical shift even if operands are signed.
2103 operatorStr = " >> ";
2104 subprecedence = Shift;
2105 break;
2106 case PEO::ShrS:
2107 // >>> in verilog is an arithmetic shift if both operands are signed.
2108 operatorStr = " >>> ";
2109 subprecedence = Shift;
2110 operandSign = IsSigned;
2111 break;
2112 case PEO::DivU:
2113 operatorStr = " / ";
2114 subprecedence = Multiply;
2115 operandSign = IsUnsigned;
2116 break;
2117 case PEO::DivS:
2118 operatorStr = " / ";
2119 subprecedence = Multiply;
2120 operandSign = IsSigned;
2121 break;
2122 case PEO::ModU:
2123 operatorStr = " % ";
2124 subprecedence = Multiply;
2125 operandSign = IsUnsigned;
2126 break;
2127 case PEO::ModS:
2128 operatorStr = " % ";
2129 subprecedence = Multiply;
2130 operandSign = IsSigned;
2131 break;
2132 case PEO::CLog2:
2133 openStr = "$clog2(";
2134 closeStr = ")";
2135 operandSign = IsUnsigned;
2136 hasOpenClose = true;
2137 prec = Symbol;
2138 break;
2139 case PEO::StrConcat:
2140 openStr = "{";
2141 closeStr = "}";
2142 hasOpenClose = true;
2143 operatorStr = ", ";
2144 // We don't have Concat precedence, but it's lowest anyway. (SV Table 11-2).
2145 subprecedence = LowestPrecedence;
2146 prec = Symbol;
2147 break;
2148 }
2149 if (!hasOpenClose)
2150 prec = subprecedence;
2151
2152 // unary -> one element.
2153 assert(!isUnary || llvm::hasSingleElement(expr.getOperands()));
2154 // one element -> {unary || open/close}.
2155 assert(isUnary || hasOpenClose ||
2156 !llvm::hasSingleElement(expr.getOperands()));
2157
2158 // Emit the specified operand with a $signed() or $unsigned() wrapper around
2159 // it if context requires a specific signedness to compute the right value.
2160 // This returns true if the operand is signed.
2161 // TODO: This could try harder to omit redundant casts like the mainline
2162 // expression emitter.
2163 auto emitOperand = [&](Attribute operand) -> bool {
2164 // If surrounding with signed/unsigned, inner expr doesn't need parens.
2165 auto subprec = operandSign.has_value() ? LowestPrecedence : subprecedence;
2166 if (operandSign.has_value())
2167 os << (*operandSign == IsSigned ? "$signed(" : "$unsigned(");
2168 auto signedness =
2169 printParamValue(operand, os, subprec, emitError).signedness;
2170 if (operandSign.has_value()) {
2171 os << ')';
2172 signedness = *operandSign;
2173 }
2174 return signedness == IsSigned;
2175 };
2176
2177 // Check outer precedence, wrap in parentheses if needed.
2178 if (prec > parenthesizeIfLooserThan)
2179 os << '(';
2180
2181 // Emit opening portion of the operation.
2182 if (hasOpenClose)
2183 os << openStr;
2184 else if (isUnary)
2185 os << operatorStr;
2186
2187 bool allOperandsSigned = emitOperand(expr.getOperands()[0]);
2188 for (auto op : expr.getOperands().drop_front()) {
2189 // Handle the special case of (a + b + -42) as (a + b - 42).
2190 // TODO: Also handle (a + b + x*-1).
2191 if (expr.getOpcode() == PEO::Add) {
2192 if (auto integer = dyn_cast<IntegerAttr>(op)) {
2193 const APInt &value = integer.getValue();
2194 if (value.isNegative() && !value.isMinSignedValue()) {
2195 os << " - ";
2196 allOperandsSigned &=
2197 emitOperand(IntegerAttr::get(op.getType(), -value));
2198 continue;
2199 }
2200 }
2201 }
2202
2203 os << operatorStr;
2204 allOperandsSigned &= emitOperand(op);
2205 }
2206 if (hasOpenClose)
2207 os << closeStr;
2208 if (prec > parenthesizeIfLooserThan) {
2209 os << ')';
2210 prec = Selection;
2211 }
2212 return {prec, allOperandsSigned ? IsSigned : IsUnsigned};
2213}
2214// NOLINTEND(misc-no-recursion)
2215
2216//===----------------------------------------------------------------------===//
2217// Expression Emission
2218//===----------------------------------------------------------------------===//
2219
2220namespace {
2221/// This builds a recursively nested expression from an SSA use-def graph. This
2222/// uses a post-order walk, but it needs to obey precedence and signedness
2223/// constraints that depend on the behavior of the child nodes.
2224/// To handle this, we must buffer all output so we can insert parentheses
2225/// and other things if we find out that it was needed later.
2226// NOLINTBEGIN(misc-no-recursion)
2227class ExprEmitter : public EmitterBase,
2228 public TypeOpVisitor<ExprEmitter, SubExprInfo>,
2229 public CombinationalVisitor<ExprEmitter, SubExprInfo>,
2230 public sv::Visitor<ExprEmitter, SubExprInfo> {
2231public:
2232 /// Create an ExprEmitter for the specified module emitter, and keeping track
2233 /// of any emitted expressions in the specified set.
2234 ExprEmitter(ModuleEmitter &emitter,
2235 SmallPtrSetImpl<Operation *> &emittedExprs)
2236 : ExprEmitter(emitter, emittedExprs, localTokens) {}
2237
2238 ExprEmitter(ModuleEmitter &emitter,
2239 SmallPtrSetImpl<Operation *> &emittedExprs,
2240 BufferingPP::BufferVec &tokens)
2241 : EmitterBase(emitter.state), emitter(emitter),
2242 emittedExprs(emittedExprs), buffer(tokens),
2243 ps(buffer, state.saver, state.options.emitVerilogLocations) {
2244 assert(state.pp.getListener() == &state.saver);
2245 }
2246
2247 /// Emit the specified value as an expression. If this is an inline-emitted
2248 /// expression, we emit that expression, otherwise we emit a reference to the
2249 /// already computed name.
2250 ///
2251 void emitExpression(Value exp, VerilogPrecedence parenthesizeIfLooserThan,
2252 bool isAssignmentLikeContext) {
2253 assert(localTokens.empty());
2254 // Wrap to this column.
2255 ps.scopedBox(PP::ibox0, [&]() {
2256 // Require unsigned in an assignment context since every wire is
2257 // declared as unsigned.
2258 emitSubExpr(exp, parenthesizeIfLooserThan,
2259 /*signRequirement*/
2260 isAssignmentLikeContext ? RequireUnsigned : NoRequirement,
2261 /*isSelfDeterminedUnsignedValue*/ false,
2262 isAssignmentLikeContext);
2263 });
2264 // If we are not using an external token buffer provided through the
2265 // constructor, but we're using the default `ExprEmitter`-scoped buffer,
2266 // flush it.
2267 if (&buffer.tokens == &localTokens)
2268 buffer.flush(state.pp);
2269 }
2270
2271private:
2272 friend class TypeOpVisitor<ExprEmitter, SubExprInfo>;
2273 friend class CombinationalVisitor<ExprEmitter, SubExprInfo>;
2274 friend class sv::Visitor<ExprEmitter, SubExprInfo>;
2275
2276 enum SubExprSignRequirement { NoRequirement, RequireSigned, RequireUnsigned };
2277
2278 /// Emit the specified value `exp` as a subexpression to the stream. The
2279 /// `parenthesizeIfLooserThan` parameter indicates when parentheses should be
2280 /// added aroun the subexpression. The `signReq` flag can cause emitSubExpr
2281 /// to emit a subexpression that is guaranteed to be signed or unsigned, and
2282 /// the `isSelfDeterminedUnsignedValue` flag indicates whether the value is
2283 /// known to be have "self determined" width, allowing us to omit extensions.
2284 SubExprInfo emitSubExpr(Value exp, VerilogPrecedence parenthesizeIfLooserThan,
2285 SubExprSignRequirement signReq = NoRequirement,
2286 bool isSelfDeterminedUnsignedValue = false,
2287 bool isAssignmentLikeContext = false);
2288
2289 /// Emit SystemVerilog attributes attached to the expression op as dialect
2290 /// attributes.
2291 void emitSVAttributes(Operation *op);
2292
2293 SubExprInfo visitUnhandledExpr(Operation *op);
2294 SubExprInfo visitInvalidComb(Operation *op) {
2295 return dispatchTypeOpVisitor(op);
2296 }
2297 SubExprInfo visitUnhandledComb(Operation *op) {
2298 return visitUnhandledExpr(op);
2299 }
2300 SubExprInfo visitInvalidTypeOp(Operation *op) {
2301 return dispatchSVVisitor(op);
2302 }
2303 SubExprInfo visitUnhandledTypeOp(Operation *op) {
2304 return visitUnhandledExpr(op);
2305 }
2306 SubExprInfo visitUnhandledSV(Operation *op) { return visitUnhandledExpr(op); }
2307
2308 /// These are flags that control `emitBinary`.
2309 enum EmitBinaryFlags {
2310 EB_RequireSignedOperands = RequireSigned, /* 0x1*/
2311 EB_RequireUnsignedOperands = RequireUnsigned, /* 0x2*/
2312 EB_OperandSignRequirementMask = 0x3,
2313
2314 /// This flag indicates that the RHS operand is an unsigned value that has
2315 /// "self determined" width. This means that we can omit explicit zero
2316 /// extensions from it, and don't impose a sign on it.
2317 EB_RHS_UnsignedWithSelfDeterminedWidth = 0x4,
2318
2319 /// This flag indicates that the result should be wrapped in a $signed(x)
2320 /// expression to force the result to signed.
2321 EB_ForceResultSigned = 0x8,
2322 };
2323
2324 /// Emit a binary expression. The "emitBinaryFlags" are a bitset from
2325 /// EmitBinaryFlags.
2326 SubExprInfo emitBinary(Operation *op, VerilogPrecedence prec,
2327 const char *syntax, unsigned emitBinaryFlags = 0);
2328
2329 SubExprInfo emitUnary(Operation *op, const char *syntax,
2330 bool resultAlwaysUnsigned = false);
2331
2332 /// Emit the specified value as a subexpression, wrapping in an ibox2.
2333 void emitSubExprIBox2(
2334 Value v, VerilogPrecedence parenthesizeIfLooserThan = LowestPrecedence) {
2335 ps.scopedBox(PP::ibox2,
2336 [&]() { emitSubExpr(v, parenthesizeIfLooserThan); });
2337 }
2338
2339 /// Emit a range of values separated by commas and a breakable space.
2340 /// Each value is emitted by invoking `eachFn`.
2341 template <typename Container, typename EachFn>
2342 void interleaveComma(const Container &c, EachFn eachFn) {
2343 llvm::interleave(c, eachFn, [&]() { ps << "," << PP::space; });
2344 }
2345
2346 /// Emit a range of values separated by commas and a breakable space.
2347 /// Each value is emitted in an ibox2.
2348 void interleaveComma(ValueRange ops) {
2349 return interleaveComma(ops, [&](Value v) { emitSubExprIBox2(v); });
2350 }
2351
2352 /// Emit an array-literal-like structure, separated by commas.
2353 /// Use callbacks to emit open tokens, closing tokens, and handle each value.
2354 /// If it fits, will be emitted on a single line with no space between
2355 /// list and surrounding open and close.
2356 /// Otherwise, each item is placed on its own line.
2357 /// This has property that if any element requires breaking, all elements
2358 /// are emitted on separate lines (with open/close attached to first/last).
2359 /// `{a + b, x + y, c}`
2360 /// OR
2361 /// ```
2362 /// {a + b,
2363 /// x + y,
2364 /// c}
2365 /// ```
2366 template <typename Container, typename OpenFunc, typename CloseFunc,
2367 typename EachFunc>
2368 void emitBracedList(const Container &c, OpenFunc openFn, EachFunc eachFn,
2369 CloseFunc closeFn) {
2370 openFn();
2371 ps.scopedBox(PP::cbox0, [&]() {
2372 interleaveComma(c, eachFn);
2373 closeFn();
2374 });
2375 }
2376
2377 /// Emit braced list of values surrounded by specified open/close.
2378 template <typename OpenFunc, typename CloseFunc>
2379 void emitBracedList(ValueRange ops, OpenFunc openFn, CloseFunc closeFn) {
2380 return emitBracedList(
2381 ops, openFn, [&](Value v) { emitSubExprIBox2(v); }, closeFn);
2382 }
2383
2384 /// Emit braced list of values surrounded by `{` and `}`.
2385 void emitBracedList(ValueRange ops) {
2386 return emitBracedList(
2387 ops, [&]() { ps << "{"; }, [&]() { ps << "}"; });
2388 }
2389
2390 /// Print an APInt constant.
2391 SubExprInfo printConstantScalar(APInt &value, IntegerType type);
2392
2393 /// Print a constant array.
2394 void printConstantArray(ArrayAttr elementValues, Type elementType,
2395 bool printAsPattern, Operation *op);
2396 /// Print a constant struct.
2397 void printConstantStruct(ArrayRef<hw::detail::FieldInfo> fieldInfos,
2398 ArrayAttr fieldValues, bool printAsPattern,
2399 Operation *op);
2400 /// Print an aggregate array or struct constant as the given type.
2401 void printConstantAggregate(Attribute attr, Type type, Operation *op);
2402
2403 using sv::Visitor<ExprEmitter, SubExprInfo>::visitSV;
2404 SubExprInfo visitSV(GetModportOp op);
2405 SubExprInfo visitSV(SystemFunctionOp op);
2406 SubExprInfo visitSV(ReadInterfaceSignalOp op);
2407 SubExprInfo visitSV(XMROp op);
2408 SubExprInfo visitSV(SFormatFOp op);
2409 SubExprInfo visitSV(XMRRefOp op);
2410 SubExprInfo visitVerbatimExprOp(Operation *op, ArrayAttr symbols);
2411 SubExprInfo visitSV(VerbatimExprOp op) {
2412 return visitVerbatimExprOp(op, op.getSymbols());
2413 }
2414 SubExprInfo visitSV(VerbatimExprSEOp op) {
2415 return visitVerbatimExprOp(op, op.getSymbols());
2416 }
2417 SubExprInfo visitSV(MacroRefExprOp op);
2418 SubExprInfo visitSV(MacroRefExprSEOp op);
2419 template <typename MacroTy>
2420 SubExprInfo emitMacroCall(MacroTy op);
2421
2422 SubExprInfo visitSV(ConstantXOp op);
2423 SubExprInfo visitSV(ConstantZOp op);
2424 SubExprInfo visitSV(ConstantStrOp op);
2425 SubExprInfo visitSV(ConcatStrOp op);
2426
2427 SubExprInfo visitSV(sv::UnpackedArrayCreateOp op);
2428 SubExprInfo visitSV(sv::UnpackedOpenArrayCastOp op) {
2429 // Cast op is noop.
2430 return emitSubExpr(op->getOperand(0), LowestPrecedence);
2431 }
2432
2433 // Noop cast operators.
2434 SubExprInfo visitSV(ReadInOutOp op) {
2435 auto result = emitSubExpr(op->getOperand(0), LowestPrecedence);
2436 emitSVAttributes(op);
2437 return result;
2438 }
2439 SubExprInfo visitSV(ArrayIndexInOutOp op);
2440 SubExprInfo visitSV(IndexedPartSelectInOutOp op);
2441 SubExprInfo visitSV(IndexedPartSelectOp op);
2442 SubExprInfo visitSV(StructFieldInOutOp op);
2443
2444 // Sampled value functions
2445 SubExprInfo visitSV(SampledOp op);
2446
2447 // Time system functions
2448 SubExprInfo visitSV(TimeOp op);
2449 SubExprInfo visitSV(STimeOp op);
2450
2451 // Other
2452 using TypeOpVisitor::visitTypeOp;
2453 SubExprInfo visitTypeOp(ConstantOp op);
2454 SubExprInfo visitTypeOp(AggregateConstantOp op);
2455 SubExprInfo visitTypeOp(BitcastOp op);
2456 SubExprInfo visitTypeOp(ParamValueOp op);
2457 SubExprInfo visitTypeOp(ArraySliceOp op);
2458 SubExprInfo visitTypeOp(ArrayGetOp op);
2459 SubExprInfo visitTypeOp(ArrayCreateOp op);
2460 SubExprInfo visitTypeOp(ArrayConcatOp op);
2461 SubExprInfo visitTypeOp(StructCreateOp op);
2462 SubExprInfo visitTypeOp(StructExtractOp op);
2463 SubExprInfo visitTypeOp(StructInjectOp op);
2464 SubExprInfo visitTypeOp(UnionCreateOp op);
2465 SubExprInfo visitTypeOp(UnionExtractOp op);
2466 SubExprInfo visitTypeOp(EnumCmpOp op);
2467 SubExprInfo visitTypeOp(EnumConstantOp op);
2468
2469 // Comb Dialect Operations
2470 using CombinationalVisitor::visitComb;
2471 SubExprInfo visitComb(MuxOp op);
2472 SubExprInfo visitComb(ReverseOp op);
2473 SubExprInfo visitComb(AddOp op) {
2474 assert(op.getNumOperands() == 2 && "prelowering should handle variadics");
2475 return emitBinary(op, Addition, "+");
2476 }
2477 SubExprInfo visitComb(SubOp op) { return emitBinary(op, Addition, "-"); }
2478 SubExprInfo visitComb(MulOp op) {
2479 assert(op.getNumOperands() == 2 && "prelowering should handle variadics");
2480 return emitBinary(op, Multiply, "*");
2481 }
2482 SubExprInfo visitComb(DivUOp op) {
2483 return emitBinary(op, Multiply, "/", EB_RequireUnsignedOperands);
2484 }
2485 SubExprInfo visitComb(DivSOp op) {
2486 return emitBinary(op, Multiply, "/",
2487 EB_RequireSignedOperands | EB_ForceResultSigned);
2488 }
2489 SubExprInfo visitComb(ModUOp op) {
2490 return emitBinary(op, Multiply, "%", EB_RequireUnsignedOperands);
2491 }
2492 SubExprInfo visitComb(ModSOp op) {
2493 return emitBinary(op, Multiply, "%",
2494 EB_RequireSignedOperands | EB_ForceResultSigned);
2495 }
2496 SubExprInfo visitComb(ShlOp op) {
2497 return emitBinary(op, Shift, "<<", EB_RHS_UnsignedWithSelfDeterminedWidth);
2498 }
2499 SubExprInfo visitComb(ShrUOp op) {
2500 // >> in Verilog is always an unsigned right shift.
2501 return emitBinary(op, Shift, ">>", EB_RHS_UnsignedWithSelfDeterminedWidth);
2502 }
2503 SubExprInfo visitComb(ShrSOp op) {
2504 // >>> is only an arithmetic shift right when both operands are signed.
2505 // Otherwise it does a logical shift.
2506 return emitBinary(op, Shift, ">>>",
2507 EB_RequireSignedOperands | EB_ForceResultSigned |
2508 EB_RHS_UnsignedWithSelfDeterminedWidth);
2509 }
2510 SubExprInfo visitComb(AndOp op) {
2511 assert(op.getNumOperands() == 2 && "prelowering should handle variadics");
2512 return emitBinary(op, And, "&");
2513 }
2514 SubExprInfo visitComb(OrOp op) {
2515 assert(op.getNumOperands() == 2 && "prelowering should handle variadics");
2516 return emitBinary(op, Or, "|");
2517 }
2518 SubExprInfo visitComb(XorOp op) {
2519 if (op.isBinaryNot())
2520 return emitUnary(op, "~");
2521 assert(op.getNumOperands() == 2 && "prelowering should handle variadics");
2522 return emitBinary(op, Xor, "^");
2523 }
2524
2525 // SystemVerilog spec 11.8.1: "Reduction operator results are unsigned,
2526 // regardless of the operands."
2527 SubExprInfo visitComb(ParityOp op) { return emitUnary(op, "^", true); }
2528
2529 SubExprInfo visitComb(ReplicateOp op);
2530 SubExprInfo visitComb(ConcatOp op);
2531 SubExprInfo visitComb(ExtractOp op);
2532 SubExprInfo visitComb(ICmpOp op);
2533
2534 InFlightDiagnostic emitAssignmentPatternContextError(Operation *op) {
2535 auto d = emitOpError(op, "must be printed as assignment pattern, but is "
2536 "not printed within an assignment-like context");
2537 d.attachNote() << "this is likely a bug in PrepareForEmission, which is "
2538 "supposed to spill such expressions";
2539 return d;
2540 }
2541
2542 SubExprInfo printStructCreate(
2543 ArrayRef<hw::detail::FieldInfo> fieldInfos,
2544 llvm::function_ref<void(const hw::detail::FieldInfo &, unsigned)> fieldFn,
2545 bool printAsPattern, Operation *op);
2546
2547public:
2548 ModuleEmitter &emitter;
2549
2550private:
2551 /// This is set (before a visit method is called) if emitSubExpr would
2552 /// prefer to get an output of a specific sign. This is a hint to cause the
2553 /// visitor to change its emission strategy, but the visit method can ignore
2554 /// it without a correctness problem.
2555 SubExprSignRequirement signPreference = NoRequirement;
2556
2557 /// Keep track of all operations emitted within this subexpression for
2558 /// location information tracking.
2559 SmallPtrSetImpl<Operation *> &emittedExprs;
2560
2561 /// Tokens buffered for inserting casts/parens after emitting children.
2562 SmallVector<Token> localTokens;
2563
2564 /// Stores tokens until told to flush. Uses provided buffer (tokens).
2565 BufferingPP buffer;
2566
2567 /// Stream to emit expressions into, will add to buffer.
2568 TokenStreamWithCallback<OpLocMap, CallbackDataTy, BufferingPP> ps;
2569
2570 /// Tracks whether the expression being emitted is currently within an
2571 /// assignment-like context. Certain constructs such as `'{...}` assignment
2572 /// patterns are restricted to only appear in assignment-like contexts.
2573 /// Others, like packed struct and array constants, can be printed as either
2574 /// `{...}` concatenation or `'{...}` assignment pattern, depending on whether
2575 /// they appear within an assignment-like context or not.
2576 bool isAssignmentLikeContext = false;
2577};
2578} // end anonymous namespace
2579
2580SubExprInfo ExprEmitter::emitBinary(Operation *op, VerilogPrecedence prec,
2581 const char *syntax,
2582 unsigned emitBinaryFlags) {
2583 if (hasSVAttributes(op))
2584 emitError(op, "SV attributes emission is unimplemented for the op");
2585
2586 // It's tempting to wrap expressions in groups as we emit them,
2587 // but that can cause bad wrapping as-is:
2588 // add(a, add(b, add(c, add(d, e))))
2589 // ->
2590 // group(a + (group(b + group(c + group(d + e)))))
2591 // Which will break after 'a +' first.
2592 // TODO: Build tree capturing precedence/fixity at same level, group those!
2593 // Maybe like: https://www.tweag.io/blog/2022-02-10-ormolu-and-operators/ .
2594 // For now, only group within punctuation, such as parens + braces.
2595 if (emitBinaryFlags & EB_ForceResultSigned)
2596 ps << "$signed(" << PP::ibox0;
2597 auto operandSignReq =
2598 SubExprSignRequirement(emitBinaryFlags & EB_OperandSignRequirementMask);
2599 auto lhsInfo = emitSubExpr(op->getOperand(0), prec, operandSignReq);
2600 // Bit of a kludge: if this is a comparison or equality, don't break on either
2601 // side.
2602 auto lhsSpace = (prec == VerilogPrecedence::Comparison ||
2603 prec == VerilogPrecedence::Equality)
2604 ? PP::nbsp
2605 : PP::space;
2606 // Use non-breaking space between op and RHS so breaking is consistent.
2607 ps << lhsSpace << syntax << PP::nbsp; // PP::space;
2608
2609 // Right associative operators are already generally variadic, we need to
2610 // handle things like: (a<4> == b<4>) == (c<3> == d<3>). When processing the
2611 // top operation of the tree, the rhs needs parens. When processing
2612 // known-reassociative operators like +, ^, etc we don't need parens.
2613 // TODO: MLIR should have general "Associative" trait.
2614 auto rhsPrec = prec;
2615 if (!isa<AddOp, MulOp, AndOp, OrOp, XorOp>(op))
2616 rhsPrec = VerilogPrecedence(prec - 1);
2617
2618 // If the RHS operand has self-determined width and always treated as
2619 // unsigned, inform emitSubExpr of this. This is true for the shift amount in
2620 // a shift operation.
2621 bool rhsIsUnsignedValueWithSelfDeterminedWidth = false;
2622 if (emitBinaryFlags & EB_RHS_UnsignedWithSelfDeterminedWidth) {
2623 rhsIsUnsignedValueWithSelfDeterminedWidth = true;
2624 operandSignReq = NoRequirement;
2625 }
2626
2627 auto rhsInfo = emitSubExpr(op->getOperand(1), rhsPrec, operandSignReq,
2628 rhsIsUnsignedValueWithSelfDeterminedWidth);
2629
2630 // SystemVerilog 11.8.1 says that the result of a binary expression is signed
2631 // only if both operands are signed.
2632 SubExprSignResult signedness = IsUnsigned;
2633 if (lhsInfo.signedness == IsSigned && rhsInfo.signedness == IsSigned)
2634 signedness = IsSigned;
2635
2636 if (emitBinaryFlags & EB_ForceResultSigned) {
2637 ps << PP::end << ")";
2638 signedness = IsSigned;
2639 prec = Selection;
2640 }
2641
2642 return {prec, signedness};
2643}
2644
2645SubExprInfo ExprEmitter::emitUnary(Operation *op, const char *syntax,
2646 bool resultAlwaysUnsigned) {
2647 if (hasSVAttributes(op))
2648 emitError(op, "SV attributes emission is unimplemented for the op");
2649
2650 ps << syntax;
2651 auto signedness = emitSubExpr(op->getOperand(0), Selection).signedness;
2652 // For reduction operators "&" and "|", make precedence lowest to avoid
2653 // emitting an expression like `a & &b`, which is syntactically valid but some
2654 // tools produce LINT warnings.
2655 return {isa<ICmpOp>(op) ? LowestPrecedence : Unary,
2656 resultAlwaysUnsigned ? IsUnsigned : signedness};
2657}
2658
2659/// Emit SystemVerilog attributes attached to the expression op as dialect
2660/// attributes.
2661void ExprEmitter::emitSVAttributes(Operation *op) {
2662 // SystemVerilog 2017 Section 5.12.
2663 auto svAttrs = getSVAttributes(op);
2664 if (!svAttrs)
2665 return;
2666
2667 // For now, no breaks for attributes.
2668 ps << PP::nbsp;
2669 emitSVAttributesImpl(ps, svAttrs, /*mayBreak=*/false);
2670}
2671
2672/// If the specified extension is a zero extended version of another value,
2673/// return the shorter value, otherwise return null.
2674static Value isZeroExtension(Value value) {
2675 auto concat = value.getDefiningOp<ConcatOp>();
2676 if (!concat || concat.getNumOperands() != 2)
2677 return {};
2678
2679 auto constant = concat.getOperand(0).getDefiningOp<ConstantOp>();
2680 if (constant && constant.getValue().isZero())
2681 return concat.getOperand(1);
2682 return {};
2683}
2684
2685/// Emit the specified value `exp` as a subexpression to the stream. The
2686/// `parenthesizeIfLooserThan` parameter indicates when parentheses should be
2687/// added aroun the subexpression. The `signReq` flag can cause emitSubExpr
2688/// to emit a subexpression that is guaranteed to be signed or unsigned, and
2689/// the `isSelfDeterminedUnsignedValue` flag indicates whether the value is
2690/// known to be have "self determined" width, allowing us to omit extensions.
2691SubExprInfo ExprEmitter::emitSubExpr(Value exp,
2692 VerilogPrecedence parenthesizeIfLooserThan,
2693 SubExprSignRequirement signRequirement,
2694 bool isSelfDeterminedUnsignedValue,
2695 bool isAssignmentLikeContext) {
2696 // `verif.contract` ops act as no-ops.
2697 if (auto result = dyn_cast<OpResult>(exp))
2698 if (auto contract = dyn_cast<verif::ContractOp>(result.getOwner()))
2699 return emitSubExpr(contract.getInputs()[result.getResultNumber()],
2700 parenthesizeIfLooserThan, signRequirement,
2701 isSelfDeterminedUnsignedValue,
2702 isAssignmentLikeContext);
2703
2704 // If this is a self-determined unsigned value, look through any inline zero
2705 // extensions. This occurs on the RHS of a shift operation for example.
2706 if (isSelfDeterminedUnsignedValue && exp.hasOneUse()) {
2707 if (auto smaller = isZeroExtension(exp))
2708 exp = smaller;
2709 }
2710
2711 auto *op = exp.getDefiningOp();
2712 bool shouldEmitInlineExpr = op && isVerilogExpression(op);
2713
2714 // If this is a non-expr or shouldn't be done inline, just refer to its name.
2715 if (!shouldEmitInlineExpr) {
2716 // All wires are declared as unsigned, so if the client needed it signed,
2717 // emit a conversion.
2718 if (signRequirement == RequireSigned) {
2719 ps << "$signed(" << PPExtString(getVerilogValueName(exp)) << ")";
2720 return {Symbol, IsSigned};
2721 }
2722
2723 ps << PPExtString(getVerilogValueName(exp));
2724 return {Symbol, IsUnsigned};
2725 }
2726
2727 unsigned subExprStartIndex = buffer.tokens.size();
2728 if (op)
2729 ps.addCallback({op, true});
2730 llvm::scope_exit done([&]() {
2731 if (op)
2732 ps.addCallback({op, false});
2733 });
2734
2735 // Inform the visit method about the preferred sign we want from the result.
2736 // It may choose to ignore this, but some emitters can change behavior based
2737 // on contextual desired sign.
2738 signPreference = signRequirement;
2739
2740 bool bitCastAdded = false;
2741 if (state.options.explicitBitcast && isa<AddOp, MulOp, SubOp>(op))
2742 if (auto inType =
2743 dyn_cast_or_null<IntegerType>(op->getResult(0).getType())) {
2744 ps.addAsString(inType.getWidth());
2745 ps << "'(" << PP::ibox0;
2746 bitCastAdded = true;
2747 }
2748 // Okay, this is an expression we should emit inline. Do this through our
2749 // visitor.
2750 llvm::SaveAndRestore restoreALC(this->isAssignmentLikeContext,
2751 isAssignmentLikeContext);
2752 auto expInfo = dispatchCombinationalVisitor(exp.getDefiningOp());
2753
2754 // Check cases where we have to insert things before the expression now that
2755 // we know things about it.
2756 auto addPrefix = [&](StringToken &&t) {
2757 // insert {Prefix, ibox0}.
2758 buffer.tokens.insert(buffer.tokens.begin() + subExprStartIndex,
2759 BeginToken(0));
2760 buffer.tokens.insert(buffer.tokens.begin() + subExprStartIndex, t);
2761 };
2762 auto closeBoxAndParen = [&]() { ps << PP::end << ")"; };
2763 if (signRequirement == RequireSigned && expInfo.signedness == IsUnsigned) {
2764 addPrefix(StringToken("$signed("));
2765 closeBoxAndParen();
2766 expInfo.signedness = IsSigned;
2767 expInfo.precedence = Selection;
2768 } else if (signRequirement == RequireUnsigned &&
2769 expInfo.signedness == IsSigned) {
2770 addPrefix(StringToken("$unsigned("));
2771 closeBoxAndParen();
2772 expInfo.signedness = IsUnsigned;
2773 expInfo.precedence = Selection;
2774 } else if (expInfo.precedence > parenthesizeIfLooserThan) {
2775 // If this subexpression would bind looser than the expression it is bound
2776 // into, then we need to parenthesize it. Insert the parentheses
2777 // retroactively.
2778 addPrefix(StringToken("("));
2779 closeBoxAndParen();
2780 // Reset the precedence to the () level.
2781 expInfo.precedence = Selection;
2782 }
2783 if (bitCastAdded) {
2784 closeBoxAndParen();
2785 }
2786
2787 // Remember that we emitted this.
2788 emittedExprs.insert(exp.getDefiningOp());
2789 return expInfo;
2790}
2791
2792SubExprInfo ExprEmitter::visitComb(ReplicateOp op) {
2793 // The replication operator is unsupported in some tools, so expand it
2794 // into an explicit concatenation when requested.
2795 if (state.options.disallowReplicate) {
2796 emitBracedList(SmallVector<Value>(op.getMultiple(), op.getOperand()));
2797 return {Symbol, IsUnsigned};
2798 }
2799
2800 auto openFn = [&]() {
2801 ps << "{";
2802 ps.addAsString(op.getMultiple());
2803 ps << "{";
2804 };
2805 auto closeFn = [&]() { ps << "}}"; };
2806
2807 // If the subexpression is an inline concat, we can emit it as part of the
2808 // replicate.
2809 if (auto concatOp = op.getOperand().getDefiningOp<ConcatOp>()) {
2810 if (op.getOperand().hasOneUse()) {
2811 emitBracedList(concatOp.getOperands(), openFn, closeFn);
2812 return {Symbol, IsUnsigned};
2813 }
2814 }
2815 emitBracedList(op.getOperand(), openFn, closeFn);
2816 return {Symbol, IsUnsigned};
2817}
2818
2819SubExprInfo ExprEmitter::visitComb(ConcatOp op) {
2820 emitBracedList(op.getOperands());
2821 return {Symbol, IsUnsigned};
2822}
2823
2824SubExprInfo ExprEmitter::visitTypeOp(BitcastOp op) {
2825 // NOTE: Bitcasts are emitted out-of-line with their own wire declaration when
2826 // their dimensions don't match. SystemVerilog uses the wire declaration to
2827 // know what type this value is being casted to.
2828 Type toType = op.getType();
2829 if (!haveMatchingDims(
2830 toType, op.getInput().getType(), op.getLoc(),
2831 [&](Location loc) { return emitter.emitError(loc, ""); })) {
2832 ps << "/*cast(bit";
2833 ps.invokeWithStringOS(
2834 [&](auto &os) { emitter.emitTypeDims(toType, op.getLoc(), os); });
2835 ps << ")*/";
2836 }
2837 return emitSubExpr(op.getInput(), LowestPrecedence);
2838}
2839
2840SubExprInfo ExprEmitter::visitComb(ICmpOp op) {
2841 const char *symop[] = {"==", "!=", "<", "<=", ">", ">=", "<",
2842 "<=", ">", ">=", "===", "!==", "==?", "!=?"};
2843 SubExprSignRequirement signop[] = {
2844 // Equality
2845 NoRequirement, NoRequirement,
2846 // Signed Comparisons
2847 RequireSigned, RequireSigned, RequireSigned, RequireSigned,
2848 // Unsigned Comparisons
2849 RequireUnsigned, RequireUnsigned, RequireUnsigned, RequireUnsigned,
2850 // Weird Comparisons
2851 NoRequirement, NoRequirement, NoRequirement, NoRequirement};
2852
2853 auto pred = static_cast<uint64_t>(op.getPredicate());
2854 assert(pred < sizeof(symop) / sizeof(symop[0]));
2855
2856 // Lower "== -1" to Reduction And.
2857 if (op.isEqualAllOnes())
2858 return emitUnary(op, "&", true);
2859
2860 // Lower "!= 0" to Reduction Or.
2861 if (op.isNotEqualZero())
2862 return emitUnary(op, "|", true);
2863
2864 VerilogPrecedence precedence = Comparison;
2865 switch (op.getPredicate()) {
2866 case ICmpPredicate::eq:
2867 case ICmpPredicate::ne:
2868 case ICmpPredicate::ceq:
2869 case ICmpPredicate::cne:
2870 case ICmpPredicate::weq:
2871 case ICmpPredicate::wne:
2872 precedence = Equality;
2873 break;
2874 default:
2875 precedence = Comparison;
2876 break;
2877 }
2878 auto result = emitBinary(op, precedence, symop[pred], signop[pred]);
2879
2880 // SystemVerilog 11.8.1: "Comparison... operator results are unsigned,
2881 // regardless of the operands".
2882 result.signedness = IsUnsigned;
2883 return result;
2884}
2885
2886SubExprInfo ExprEmitter::visitComb(ExtractOp op) {
2887 if (hasSVAttributes(op))
2888 emitError(op, "SV attributes emission is unimplemented for the op");
2889
2890 unsigned loBit = op.getLowBit();
2891 unsigned hiBit = loBit + cast<IntegerType>(op.getType()).getWidth() - 1;
2892
2893 auto x = emitSubExpr(op.getInput(), LowestPrecedence);
2894 assert((x.precedence == Symbol ||
2895 (x.precedence == Selection && isOkToBitSelectFrom(op.getInput()))) &&
2896 "should be handled by isExpressionUnableToInline");
2897
2898 // If we're extracting the whole input, just return it. This is valid but
2899 // non-canonical IR, and we don't want to generate invalid Verilog.
2900 if (loBit == 0 &&
2901 op.getInput().getType().getIntOrFloatBitWidth() == hiBit + 1)
2902 return x;
2903
2904 ps << "[";
2905 ps.addAsString(hiBit);
2906 if (hiBit != loBit) { // Emit x[4] instead of x[4:4].
2907 ps << ":";
2908 ps.addAsString(loBit);
2909 }
2910 ps << "]";
2911 return {Unary, IsUnsigned};
2912}
2913
2914SubExprInfo ExprEmitter::visitSV(GetModportOp op) {
2915 if (hasSVAttributes(op))
2916 emitError(op, "SV attributes emission is unimplemented for the op");
2917
2918 auto decl = op.getReferencedDecl(state.symbolCache);
2919 ps << PPExtString(getVerilogValueName(op.getIface())) << "."
2920 << PPExtString(getSymOpName(decl));
2921 return {Selection, IsUnsigned};
2922}
2923
2924SubExprInfo ExprEmitter::visitSV(SystemFunctionOp op) {
2925 if (hasSVAttributes(op))
2926 emitError(op, "SV attributes emission is unimplemented for the op");
2927
2928 ps << "$" << PPExtString(op.getFnName()) << "(";
2929 ps.scopedBox(PP::ibox0, [&]() {
2930 llvm::interleave(
2931 op.getOperands(), [&](Value v) { emitSubExpr(v, LowestPrecedence); },
2932 [&]() { ps << "," << PP::space; });
2933 ps << ")";
2934 });
2935 return {Symbol, IsUnsigned};
2936}
2937
2938SubExprInfo ExprEmitter::visitSV(ReadInterfaceSignalOp op) {
2939 if (hasSVAttributes(op))
2940 emitError(op, "SV attributes emission is unimplemented for the op");
2941
2942 auto decl = op.getReferencedDecl(state.symbolCache);
2943
2944 ps << PPExtString(getVerilogValueName(op.getIface())) << "."
2945 << PPExtString(getSymOpName(decl));
2946 return {Selection, IsUnsigned};
2947}
2948
2949SubExprInfo ExprEmitter::visitSV(XMROp op) {
2950 if (hasSVAttributes(op))
2951 emitError(op, "SV attributes emission is unimplemented for the op");
2952
2953 if (op.getIsRooted())
2954 ps << "$root.";
2955 for (auto s : op.getPath())
2956 ps << PPExtString(cast<StringAttr>(s).getValue()) << ".";
2957 ps << PPExtString(op.getTerminal());
2958 return {Selection, IsUnsigned};
2959}
2960
2961// TODO: This shares a lot of code with the getNameRemotely mtehod. Combine
2962// these to share logic.
2963SubExprInfo ExprEmitter::visitSV(XMRRefOp op) {
2964 if (hasSVAttributes(op))
2965 emitError(op, "SV attributes emission is unimplemented for the op");
2966
2967 // The XMR is pointing at a GlobalRef.
2968 auto globalRef = op.getReferencedPath(&state.symbolCache);
2969 auto namepath = globalRef.getNamepathAttr().getValue();
2970 auto *module = state.symbolCache.getDefinition(
2971 cast<InnerRefAttr>(namepath.front()).getModule());
2972 ps << PPExtString(getSymOpName(module));
2973 for (auto sym : namepath) {
2974 ps << ".";
2975 auto innerRef = cast<InnerRefAttr>(sym);
2976 auto ref = state.symbolCache.getInnerDefinition(innerRef.getModule(),
2977 innerRef.getName());
2978 if (ref.hasPort()) {
2979 ps << PPExtString(getPortVerilogName(ref.getOp(), ref.getPort()));
2980 continue;
2981 }
2982 ps << PPExtString(getSymOpName(ref.getOp()));
2983 }
2984 auto leaf = op.getVerbatimSuffixAttr();
2985 if (leaf && leaf.size())
2986 ps << PPExtString(leaf);
2987 return {Selection, IsUnsigned};
2988}
2989
2990SubExprInfo ExprEmitter::visitVerbatimExprOp(Operation *op, ArrayAttr symbols) {
2991 if (hasSVAttributes(op))
2992 emitError(op, "SV attributes emission is unimplemented for the op");
2993
2994 emitTextWithSubstitutions(
2995 ps, op->getAttrOfType<StringAttr>("format_string").getValue(), op,
2996 [&](Value operand) { emitSubExpr(operand, LowestPrecedence); }, symbols);
2997
2998 return {Unary, IsUnsigned};
2999}
3000
3001template <typename MacroTy>
3002SubExprInfo ExprEmitter::emitMacroCall(MacroTy op) {
3003 if (hasSVAttributes(op))
3004 emitError(op, "SV attributes emission is unimplemented for the op");
3005
3006 // Use the specified name or the symbol name as appropriate.
3007 auto macroOp = op.getReferencedMacro(&state.symbolCache);
3008 assert(macroOp && "Invalid IR");
3009 StringRef name =
3010 macroOp.getVerilogName() ? *macroOp.getVerilogName() : macroOp.getName();
3011 ps << "`" << PPExtString(name);
3012 if (!op.getInputs().empty()) {
3013 ps << "(";
3014 llvm::interleaveComma(op.getInputs(), ps, [&](Value val) {
3015 emitExpression(val, LowestPrecedence, /*isAssignmentLikeContext=*/false);
3016 });
3017 ps << ")";
3018 }
3019 return {LowestPrecedence, IsUnsigned};
3020}
3021
3022SubExprInfo ExprEmitter::visitSV(MacroRefExprOp op) {
3023 return emitMacroCall(op);
3024}
3025
3026SubExprInfo ExprEmitter::visitSV(MacroRefExprSEOp op) {
3027 return emitMacroCall(op);
3028}
3029
3030SubExprInfo ExprEmitter::visitSV(ConstantXOp op) {
3031 if (hasSVAttributes(op))
3032 emitError(op, "SV attributes emission is unimplemented for the op");
3033
3034 ps.addAsString(op.getWidth());
3035 ps << "'bx";
3036 return {Unary, IsUnsigned};
3037}
3038
3039SubExprInfo ExprEmitter::visitSV(ConstantStrOp op) {
3040 if (hasSVAttributes(op))
3041 emitError(op, "SV attributes emission is unimplemented for the op");
3042
3043 ps.writeQuotedEscaped(op.getStr());
3044 return {Symbol, IsUnsigned}; // is a string unsigned? Yes! SV 5.9
3045}
3046
3047SubExprInfo ExprEmitter::visitSV(ConcatStrOp op) {
3048 if (hasSVAttributes(op))
3049 emitError(op, "SV attributes emission is unimplemented for the op");
3050
3051 // Emits the SystemVerilog concatenation `{a, b, ...}`. Strings are unsigned
3052 // (SV 5.9) and braces bind at the primary/Symbol level.
3053 emitBracedList(op.getInputs());
3054 return {Symbol, IsUnsigned};
3055}
3056
3057SubExprInfo ExprEmitter::visitSV(ConstantZOp op) {
3058 if (hasSVAttributes(op))
3059 emitError(op, "SV attributes emission is unimplemented for the op");
3060
3061 ps.addAsString(op.getWidth());
3062 ps << "'bz";
3063 return {Unary, IsUnsigned};
3064}
3065
3066SubExprInfo ExprEmitter::printConstantScalar(APInt &value, IntegerType type) {
3067 bool isNegated = false;
3068 // If this is a negative signed number and not MININT (e.g. -128), then print
3069 // it as a negated positive number.
3070 if (signPreference == RequireSigned && value.isNegative() &&
3071 !value.isMinSignedValue()) {
3072 ps << "-";
3073 isNegated = true;
3074 }
3075
3076 ps.addAsString(type.getWidth());
3077 ps << "'";
3078
3079 // Emit this as a signed constant if the caller would prefer that.
3080 if (signPreference == RequireSigned)
3081 ps << "sh";
3082 else
3083 ps << "h";
3084
3085 // Print negated if required.
3086 SmallString<32> valueStr;
3087 if (isNegated) {
3088 (-value).toStringUnsigned(valueStr, 16);
3089 } else {
3090 value.toStringUnsigned(valueStr, 16);
3091 }
3092 ps << valueStr;
3093 return {Unary, signPreference == RequireSigned ? IsSigned : IsUnsigned};
3094}
3095
3096SubExprInfo ExprEmitter::visitTypeOp(ConstantOp op) {
3097 if (hasSVAttributes(op))
3098 emitError(op, "SV attributes emission is unimplemented for the op");
3099
3100 auto value = op.getValue();
3101 // We currently only allow zero width values to be handled as special cases in
3102 // the various operations that may come across them. If we reached this point
3103 // in the emitter, the value should be considered illegal to emit.
3104 if (value.getBitWidth() == 0) {
3105 emitOpError(op, "will not emit zero width constants in the general case");
3106 ps << "<<unsupported zero width constant: "
3107 << PPExtString(op->getName().getStringRef()) << ">>";
3108 return {Unary, IsUnsigned};
3109 }
3110
3111 return printConstantScalar(value, hw::type_cast<IntegerType>(op.getType()));
3112}
3113
3114void ExprEmitter::printConstantArray(ArrayAttr elementValues, Type elementType,
3115 bool printAsPattern, Operation *op) {
3116 if (printAsPattern && !isAssignmentLikeContext)
3117 emitAssignmentPatternContextError(op);
3118 StringRef openDelim = printAsPattern ? "'{" : "{";
3119
3120 emitBracedList(
3121 elementValues, [&]() { ps << openDelim; },
3122 [&](Attribute elementValue) {
3123 printConstantAggregate(elementValue, elementType, op);
3124 },
3125 [&]() { ps << "}"; });
3126}
3127
3128void ExprEmitter::printConstantStruct(
3129 ArrayRef<hw::detail::FieldInfo> fieldInfos, ArrayAttr fieldValues,
3130 bool printAsPattern, Operation *op) {
3131 if (printAsPattern && !isAssignmentLikeContext)
3132 emitAssignmentPatternContextError(op);
3133
3134 // Only emit elements with non-zero bit width.
3135 // TODO: Ideally we should emit zero bit values as comments, e.g. `{/*a:
3136 // ZeroBit,*/ b: foo, /* c: ZeroBit*/ d: bar}`. However it's tedious to
3137 // nicely emit all edge cases hence currently we just elide zero bit
3138 // values.
3139 auto fieldRange = llvm::make_filter_range(
3140 llvm::zip(fieldInfos, fieldValues), [](const auto &fieldAndValue) {
3141 // Elide zero bit elements.
3142 return !isZeroBitType(std::get<0>(fieldAndValue).type);
3143 });
3144
3145 if (printAsPattern) {
3146 emitBracedList(
3147 fieldRange, [&]() { ps << "'{"; },
3148 [&](const auto &fieldAndValue) {
3149 ps.scopedBox(PP::ibox2, [&]() {
3150 const auto &[field, value] = fieldAndValue;
3151 ps << PPExtString(emitter.getVerilogStructFieldName(field.name))
3152 << ":" << PP::space;
3153 printConstantAggregate(value, field.type, op);
3154 });
3155 },
3156 [&]() { ps << "}"; });
3157 } else {
3158 emitBracedList(
3159 fieldRange, [&]() { ps << "{"; },
3160 [&](const auto &fieldAndValue) {
3161 ps.scopedBox(PP::ibox2, [&]() {
3162 const auto &[field, value] = fieldAndValue;
3163 printConstantAggregate(value, field.type, op);
3164 });
3165 },
3166 [&]() { ps << "}"; });
3167 }
3168}
3169
3170void ExprEmitter::printConstantAggregate(Attribute attr, Type type,
3171 Operation *op) {
3172 // Packed arrays can be printed as concatenation or pattern.
3173 if (auto arrayType = hw::type_dyn_cast<ArrayType>(type))
3174 return printConstantArray(cast<ArrayAttr>(attr), arrayType.getElementType(),
3175 isAssignmentLikeContext, op);
3176
3177 // Unpacked arrays must be printed as pattern.
3178 if (auto arrayType = hw::type_dyn_cast<UnpackedArrayType>(type))
3179 return printConstantArray(cast<ArrayAttr>(attr), arrayType.getElementType(),
3180 true, op);
3181
3182 // Packed structs can be printed as concatenation or pattern.
3183 if (auto structType = hw::type_dyn_cast<StructType>(type))
3184 return printConstantStruct(structType.getElements(), cast<ArrayAttr>(attr),
3185 isAssignmentLikeContext, op);
3186
3187 if (auto intType = hw::type_dyn_cast<IntegerType>(type)) {
3188 auto value = cast<IntegerAttr>(attr).getValue();
3189 printConstantScalar(value, intType);
3190 return;
3191 }
3192
3193 emitOpError(op, "contains constant of type ")
3194 << type << " which cannot be emitted as Verilog";
3195}
3196
3197SubExprInfo ExprEmitter::visitTypeOp(AggregateConstantOp op) {
3198 if (hasSVAttributes(op))
3199 emitError(op, "SV attributes emission is unimplemented for the op");
3200
3201 // If the constant op as a whole is zero-width, it is an error.
3202 assert(!isZeroBitType(op.getType()) &&
3203 "zero-bit types not allowed at this point");
3204
3205 printConstantAggregate(op.getFields(), op.getType(), op);
3206 return {Symbol, IsUnsigned};
3207}
3208
3209SubExprInfo ExprEmitter::visitTypeOp(ParamValueOp op) {
3210 if (hasSVAttributes(op))
3211 emitError(op, "SV attributes emission is unimplemented for the op");
3212
3213 return ps.invokeWithStringOS([&](auto &os) {
3214 return emitter.printParamValue(op.getValue(), os, [&]() {
3215 return op->emitOpError("invalid parameter use");
3216 });
3217 });
3218}
3219
3220// 11.5.1 "Vector bit-select and part-select addressing" allows a '+:' syntax
3221// for slicing operations.
3222SubExprInfo ExprEmitter::visitTypeOp(ArraySliceOp op) {
3223 if (hasSVAttributes(op))
3224 emitError(op, "SV attributes emission is unimplemented for the op");
3225
3226 auto arrayPrec = emitSubExpr(op.getInput(), Selection);
3227
3228 unsigned dstWidth = type_cast<ArrayType>(op.getType()).getNumElements();
3229 ps << "[";
3230 emitSubExpr(op.getLowIndex(), LowestPrecedence);
3231 ps << " +: ";
3232 ps.addAsString(dstWidth);
3233 ps << "]";
3234 return {Selection, arrayPrec.signedness};
3235}
3236
3237SubExprInfo ExprEmitter::visitTypeOp(ArrayGetOp op) {
3238 emitSubExpr(op.getInput(), Selection);
3239 ps << "[";
3240 if (isZeroBitType(op.getIndex().getType()))
3242 else
3243 emitSubExpr(op.getIndex(), LowestPrecedence);
3244 ps << "]";
3245 emitSVAttributes(op);
3246 return {Selection, IsUnsigned};
3247}
3248
3249// Syntax from: section 5.11 "Array literals".
3250SubExprInfo ExprEmitter::visitTypeOp(ArrayCreateOp op) {
3251 if (hasSVAttributes(op))
3252 emitError(op, "SV attributes emission is unimplemented for the op");
3253
3254 if (op.isUniform()) {
3255 ps << "{";
3256 ps.addAsString(op.getInputs().size());
3257 ps << "{";
3258 emitSubExpr(op.getUniformElement(), LowestPrecedence);
3259 ps << "}}";
3260 } else {
3261 emitBracedList(
3262 op.getInputs(), [&]() { ps << "{"; },
3263 [&](Value v) {
3264 ps << "{";
3265 emitSubExprIBox2(v);
3266 ps << "}";
3267 },
3268 [&]() { ps << "}"; });
3269 }
3270 return {Unary, IsUnsigned};
3271}
3272
3273SubExprInfo ExprEmitter::visitSV(UnpackedArrayCreateOp op) {
3274 if (hasSVAttributes(op))
3275 emitError(op, "SV attributes emission is unimplemented for the op");
3276
3277 emitBracedList(
3278 llvm::reverse(op.getInputs()), [&]() { ps << "'{"; },
3279 [&](Value v) { emitSubExprIBox2(v); }, [&]() { ps << "}"; });
3280 return {Unary, IsUnsigned};
3281}
3282
3283SubExprInfo ExprEmitter::visitTypeOp(ArrayConcatOp op) {
3284 if (hasSVAttributes(op))
3285 emitError(op, "SV attributes emission is unimplemented for the op");
3286
3287 emitBracedList(op.getOperands());
3288 return {Unary, IsUnsigned};
3289}
3290
3291SubExprInfo ExprEmitter::visitSV(ArrayIndexInOutOp op) {
3292 if (hasSVAttributes(op))
3293 emitError(op, "SV attributes emission is unimplemented for the op");
3294
3295 auto index = op.getIndex();
3296 auto arrayPrec = emitSubExpr(op.getInput(), Selection);
3297 ps << "[";
3298 if (isZeroBitType(index.getType()))
3300 else
3301 emitSubExpr(index, LowestPrecedence);
3302 ps << "]";
3303 return {Selection, arrayPrec.signedness};
3304}
3305
3306SubExprInfo ExprEmitter::visitSV(IndexedPartSelectInOutOp op) {
3307 if (hasSVAttributes(op))
3308 emitError(op, "SV attributes emission is unimplemented for the op");
3309
3310 auto prec = emitSubExpr(op.getInput(), Selection);
3311 ps << "[";
3312 emitSubExpr(op.getBase(), LowestPrecedence);
3313 if (op.getDecrement())
3314 ps << " -: ";
3315 else
3316 ps << " +: ";
3317 ps.addAsString(op.getWidth());
3318 ps << "]";
3319 return {Selection, prec.signedness};
3320}
3321
3322SubExprInfo ExprEmitter::visitSV(IndexedPartSelectOp op) {
3323 if (hasSVAttributes(op))
3324 emitError(op, "SV attributes emission is unimplemented for the op");
3325
3326 auto info = emitSubExpr(op.getInput(), LowestPrecedence);
3327 ps << "[";
3328 emitSubExpr(op.getBase(), LowestPrecedence);
3329 if (op.getDecrement())
3330 ps << " -: ";
3331 else
3332 ps << " +: ";
3333 ps.addAsString(op.getWidth());
3334 ps << "]";
3335 return info;
3336}
3337
3338SubExprInfo ExprEmitter::visitSV(StructFieldInOutOp op) {
3339 if (hasSVAttributes(op))
3340 emitError(op, "SV attributes emission is unimplemented for the op");
3341
3342 auto prec = emitSubExpr(op.getInput(), Selection);
3343 ps << "."
3344 << PPExtString(emitter.getVerilogStructFieldName(op.getFieldAttr()));
3345 return {Selection, prec.signedness};
3346}
3347
3348SubExprInfo ExprEmitter::visitSV(SampledOp op) {
3349 if (hasSVAttributes(op))
3350 emitError(op, "SV attributes emission is unimplemented for the op");
3351
3352 ps << "$sampled(";
3353 auto info = emitSubExpr(op.getExpression(), LowestPrecedence);
3354 ps << ")";
3355 return info;
3356}
3357
3358SubExprInfo ExprEmitter::visitSV(SFormatFOp op) {
3359 if (hasSVAttributes(op))
3360 emitError(op, "SV attributes emission is unimplemented for the op");
3361
3362 ps << "$sformatf(";
3363 ps.scopedBox(PP::ibox0, [&]() {
3364 ps.writeQuotedEscaped(op.getFormatString());
3365 // TODO: if any of these breaks, it'd be "nice" to break
3366 // after the comma, instead of:
3367 // $sformatf("...", a + b,
3368 // longexpr_goes
3369 // + here, c);
3370 // (without forcing breaking between all elements, like braced list)
3371 for (auto operand : op.getSubstitutions()) {
3372 ps << "," << PP::space;
3373 emitSubExpr(operand, LowestPrecedence);
3374 }
3375 });
3376 ps << ")";
3377 return {Symbol, IsUnsigned};
3378}
3379
3380SubExprInfo ExprEmitter::visitSV(TimeOp op) {
3381 if (hasSVAttributes(op))
3382 emitError(op, "SV attributes emission is unimplemented for the op");
3383
3384 ps << "$time";
3385 return {Symbol, IsUnsigned};
3386}
3387
3388SubExprInfo ExprEmitter::visitSV(STimeOp op) {
3389 if (hasSVAttributes(op))
3390 emitError(op, "SV attributes emission is unimplemented for the op");
3391
3392 ps << "$stime";
3393 return {Symbol, IsUnsigned};
3394}
3395
3396SubExprInfo ExprEmitter::visitComb(MuxOp op) {
3397 // The ?: operator is right associative.
3398
3399 // Layout:
3400 // cond ? a : b
3401 // (long
3402 // + cond) ? a : b
3403 // long
3404 // + cond
3405 // ? a : b
3406 // long
3407 // + cond
3408 // ? a
3409 // : b
3410 return ps.scopedBox(PP::cbox0, [&]() -> SubExprInfo {
3411 ps.scopedBox(PP::ibox0, [&]() {
3412 emitSubExpr(op.getCond(), VerilogPrecedence(Conditional - 1));
3413 });
3414 ps << BreakToken(1, 2);
3415 ps << "?";
3416 emitSVAttributes(op);
3417 ps << " ";
3418 auto lhsInfo = ps.scopedBox(PP::ibox0, [&]() {
3419 return emitSubExpr(op.getTrueValue(), VerilogPrecedence(Conditional - 1));
3420 });
3421 ps << BreakToken(1, 2) << ": ";
3422
3423 auto rhsInfo = ps.scopedBox(PP::ibox0, [&]() {
3424 return emitSubExpr(op.getFalseValue(), Conditional);
3425 });
3426
3427 SubExprSignResult signedness = IsUnsigned;
3428 if (lhsInfo.signedness == IsSigned && rhsInfo.signedness == IsSigned)
3429 signedness = IsSigned;
3430
3431 return {Conditional, signedness};
3432 });
3433}
3434
3435SubExprInfo ExprEmitter::visitComb(ReverseOp op) {
3436 if (hasSVAttributes(op))
3437 emitError(op, "SV attributes emission is unimplemented for the op");
3438
3439 ps << "{<<{";
3440 emitSubExpr(op.getInput(), LowestPrecedence);
3441 ps << "}}";
3442
3443 return {Symbol, IsUnsigned};
3444}
3445
3446SubExprInfo ExprEmitter::printStructCreate(
3447 ArrayRef<hw::detail::FieldInfo> fieldInfos,
3448 llvm::function_ref<void(const hw::detail::FieldInfo &, unsigned)> fieldFn,
3449 bool printAsPattern, Operation *op) {
3450 if (printAsPattern && !isAssignmentLikeContext)
3451 emitAssignmentPatternContextError(op);
3452
3453 // Elide zero bit elements.
3454 auto filteredFields = llvm::make_filter_range(
3455 llvm::enumerate(fieldInfos),
3456 [](const auto &field) { return !isZeroBitType(field.value().type); });
3457
3458 if (printAsPattern) {
3459 emitBracedList(
3460 filteredFields, [&]() { ps << "'{"; },
3461 [&](const auto &field) {
3462 ps.scopedBox(PP::ibox2, [&]() {
3463 ps << PPExtString(
3464 emitter.getVerilogStructFieldName(field.value().name))
3465 << ":" << PP::space;
3466 fieldFn(field.value(), field.index());
3467 });
3468 },
3469 [&]() { ps << "}"; });
3470 } else {
3471 emitBracedList(
3472 filteredFields, [&]() { ps << "{"; },
3473 [&](const auto &field) {
3474 ps.scopedBox(PP::ibox2,
3475 [&]() { fieldFn(field.value(), field.index()); });
3476 },
3477 [&]() { ps << "}"; });
3478 }
3479
3480 return {Selection, IsUnsigned};
3481}
3482
3483SubExprInfo ExprEmitter::visitTypeOp(StructCreateOp op) {
3484 if (hasSVAttributes(op))
3485 emitError(op, "SV attributes emission is unimplemented for the op");
3486
3487 // TODO: For unpacked structs, once we have support for them, `printAsPattern`
3488 // should be set to true.
3489 bool printAsPattern = isAssignmentLikeContext;
3490 StructType structType = op.getType();
3491 return printStructCreate(
3492 structType.getElements(),
3493 [&](const auto &field, auto index) {
3494 emitSubExpr(op.getOperand(index), Selection, NoRequirement,
3495 /*isSelfDeterminedUnsignedValue=*/false,
3496 /*isAssignmentLikeContext=*/isAssignmentLikeContext);
3497 },
3498 printAsPattern, op);
3499}
3500
3501SubExprInfo ExprEmitter::visitTypeOp(StructExtractOp op) {
3502 if (hasSVAttributes(op))
3503 emitError(op, "SV attributes emission is unimplemented for the op");
3504
3505 emitSubExpr(op.getInput(), Selection);
3506 ps << "."
3507 << PPExtString(emitter.getVerilogStructFieldName(op.getFieldNameAttr()));
3508 return {Selection, IsUnsigned};
3509}
3510
3511SubExprInfo ExprEmitter::visitTypeOp(StructInjectOp op) {
3512 if (hasSVAttributes(op))
3513 emitError(op, "SV attributes emission is unimplemented for the op");
3514
3515 // TODO: For unpacked structs, once we have support for them, `printAsPattern`
3516 // should be set to true.
3517 bool printAsPattern = isAssignmentLikeContext;
3518 StructType structType = op.getType();
3519 return printStructCreate(
3520 structType.getElements(),
3521 [&](const auto &field, auto index) {
3522 if (field.name == op.getFieldNameAttr()) {
3523 emitSubExpr(op.getNewValue(), Selection);
3524 } else {
3525 emitSubExpr(op.getInput(), Selection);
3526 ps << "."
3527 << PPExtString(emitter.getVerilogStructFieldName(field.name));
3528 }
3529 },
3530 printAsPattern, op);
3531}
3532
3533SubExprInfo ExprEmitter::visitTypeOp(EnumConstantOp op) {
3534 ps << PPSaveString(emitter.fieldNameResolver.getEnumFieldName(op.getField()));
3535 return {Selection, IsUnsigned};
3536}
3537
3538SubExprInfo ExprEmitter::visitTypeOp(EnumCmpOp op) {
3539 if (hasSVAttributes(op))
3540 emitError(op, "SV attributes emission is unimplemented for the op");
3541 auto result = emitBinary(op, Comparison, "==", NoRequirement);
3542 // SystemVerilog 11.8.1: "Comparison... operator results are unsigned,
3543 // regardless of the operands".
3544 result.signedness = IsUnsigned;
3545 return result;
3546}
3547
3548SubExprInfo ExprEmitter::visitTypeOp(UnionCreateOp op) {
3549 if (hasSVAttributes(op))
3550 emitError(op, "SV attributes emission is unimplemented for the op");
3551
3552 // Check if this union type has been padded.
3553 auto unionType = cast<UnionType>(getCanonicalType(op.getType()));
3554 auto unionWidth = hw::getBitWidth(unionType);
3555 auto &element = unionType.getElements()[op.getFieldIndex()];
3556 auto elementWidth = hw::getBitWidth(element.type);
3557
3558 // If the element is 0 width, just fill the union with 0s.
3559 if (!elementWidth) {
3560 ps.addAsString(unionWidth);
3561 ps << "'h0";
3562 return {Unary, IsUnsigned};
3563 }
3564
3565 // If the element has no padding, emit it directly.
3566 if (elementWidth == unionWidth) {
3567 emitSubExpr(op.getInput(), LowestPrecedence);
3568 return {Unary, IsUnsigned};
3569 }
3570
3571 // Emit the value as a bitconcat, supplying 0 for the padding bits. The
3572 // member shares the LSB of the union, moved towards the MSB by its offset.
3573 auto elementOffset = static_cast<int64_t>(element.offset);
3574 int64_t prePadding = unionWidth - elementWidth - elementOffset;
3575 ps << "{";
3576 ps.scopedBox(PP::ibox0, [&]() {
3577 if (prePadding > 0) {
3578 ps.addAsString(prePadding);
3579 ps << "'h0," << PP::space;
3580 }
3581 emitSubExpr(op.getInput(), Selection);
3582 if (elementOffset > 0) {
3583 ps << "," << PP::space;
3584 ps.addAsString(elementOffset);
3585 ps << "'h0";
3586 }
3587 ps << "}";
3588 });
3589
3590 return {Unary, IsUnsigned};
3591}
3592
3593SubExprInfo ExprEmitter::visitTypeOp(UnionExtractOp op) {
3594 if (hasSVAttributes(op))
3595 emitError(op, "SV attributes emission is unimplemented for the op");
3596 emitSubExpr(op.getInput(), Selection);
3597
3598 // Check if this union type has been padded.
3599 auto unionType = cast<UnionType>(getCanonicalType(op.getInput().getType()));
3600 auto unionWidth = hw::getBitWidth(unionType);
3601 auto &element = unionType.getElements()[op.getFieldIndex()];
3602 auto elementWidth = hw::getBitWidth(element.type);
3603 bool needsPadding = elementWidth < unionWidth || element.offset > 0;
3604 auto verilogFieldName = emitter.getVerilogStructFieldName(element.name);
3605
3606 // If the element needs padding then we need to get the actual element out
3607 // of an anonymous structure.
3608 if (needsPadding)
3609 ps << "." << PPExtString(verilogFieldName);
3610
3611 // Get the correct member from the union.
3612 ps << "." << PPExtString(verilogFieldName);
3613 return {Selection, IsUnsigned};
3614}
3615
3616SubExprInfo ExprEmitter::visitUnhandledExpr(Operation *op) {
3617 emitOpError(op, "cannot emit this expression to Verilog");
3618 ps << "<<unsupported expr: " << PPExtString(op->getName().getStringRef())
3619 << ">>";
3620 return {Symbol, IsUnsigned};
3621}
3622// NOLINTEND(misc-no-recursion)
3623
3624//===----------------------------------------------------------------------===//
3625// Property Emission
3626//===----------------------------------------------------------------------===//
3627
3628// NOLINTBEGIN(misc-no-recursion)
3629
3630namespace {
3631/// Precedence level of various property and sequence expressions. Lower numbers
3632/// bind tighter.
3633///
3634/// See IEEE 1800-2017 section 16.12 "Declaring properties", specifically table
3635/// 16-3 on "Sequence and property operator precedence and associativity".
3636enum class PropertyPrecedence {
3637 Symbol, // Atomic symbol like `foo` and regular boolean expressions
3638 Repeat, // Sequence `[*]`, `[=]`, `[->]`
3639 Concat, // Sequence `##`
3640 Throughout, // Sequence `throughout`
3641 Within, // Sequence `within`
3642 Intersect, // Sequence `intersect`
3643 Unary, // Property `not`, `nexttime`-like
3644 And, // Sequence and property `and`
3645 Or, // Sequence and property `or`
3646 Iff, // Property `iff`
3647 Until, // Property `until`-like, `implies`
3648 Implication, // Property `|->`, `|=>`, `#-#`, `#=#`
3649 Qualifier, // Property `always`-like, `eventually`-like, `if`, `case`,
3650 // `accept`-like, `reject`-like
3651 Clocking, // `@(...)`, `disable iff` (not specified in the standard)
3652 Lowest, // Sentinel which is always the lowest precedence.
3653};
3654
3655/// Additional information on emitted property and sequence expressions.
3656struct EmittedProperty {
3657 /// The precedence of this expression.
3658 PropertyPrecedence precedence;
3659};
3660
3661/// A helper to emit recursively nested property and sequence expressions for
3662/// SystemVerilog assertions.
3663class PropertyEmitter : public EmitterBase,
3664 public ltl::Visitor<PropertyEmitter, EmittedProperty> {
3665public:
3666 /// Create a PropertyEmitter for the specified module emitter, and keeping
3667 /// track of any emitted expressions in the specified set.
3668 PropertyEmitter(ModuleEmitter &emitter,
3669 SmallPtrSetImpl<Operation *> &emittedOps)
3670 : PropertyEmitter(emitter, emittedOps, localTokens) {}
3671 PropertyEmitter(ModuleEmitter &emitter,
3672 SmallPtrSetImpl<Operation *> &emittedOps,
3673 BufferingPP::BufferVec &tokens)
3674 : EmitterBase(emitter.state), emitter(emitter), emittedOps(emittedOps),
3675 buffer(tokens),
3676 ps(buffer, state.saver, state.options.emitVerilogLocations) {
3677 assert(state.pp.getListener() == &state.saver);
3678 }
3679
3680 void emitAssertPropertyDisable(
3681 Value property, Value disable,
3682 PropertyPrecedence parenthesizeIfLooserThan = PropertyPrecedence::Lowest);
3683
3684 void emitAssertPropertyBody(
3685 Value property, Value disable,
3686 PropertyPrecedence parenthesizeIfLooserThan = PropertyPrecedence::Lowest);
3687
3688 void emitAssertPropertyBody(
3689 Value property, sv::EventControl event, Value clock, Value disable,
3690 PropertyPrecedence parenthesizeIfLooserThan = PropertyPrecedence::Lowest);
3691
3692private:
3693 /// Emit the specified value as an SVA property or sequence.
3694 EmittedProperty
3695 emitNestedProperty(Value property,
3696 PropertyPrecedence parenthesizeIfLooserThan);
3697 using ltl::Visitor<PropertyEmitter, EmittedProperty>::visitLTL;
3698 friend class ltl::Visitor<PropertyEmitter, EmittedProperty>;
3699
3700 EmittedProperty visitUnhandledLTL(Operation *op);
3701 EmittedProperty visitLTL(ltl::BooleanConstantOp op);
3702 EmittedProperty visitLTL(ltl::AndOp op);
3703 EmittedProperty visitLTL(ltl::OrOp op);
3704 EmittedProperty visitLTL(ltl::IntersectOp op);
3705 EmittedProperty visitLTL(ltl::DelayOp op);
3706 EmittedProperty visitLTL(ltl::ClockedDelayOp op);
3707 EmittedProperty visitLTL(ltl::ConcatOp op);
3708 EmittedProperty visitLTL(ltl::RepeatOp op);
3709 EmittedProperty visitLTL(ltl::GoToRepeatOp op);
3710 EmittedProperty visitLTL(ltl::NonConsecutiveRepeatOp op);
3711 EmittedProperty visitLTL(ltl::NotOp op);
3712 EmittedProperty visitLTL(ltl::ImplicationOp op);
3713 EmittedProperty visitLTL(ltl::UntilOp op);
3714 EmittedProperty visitLTL(ltl::EventuallyOp op);
3715 EmittedProperty visitLTL(ltl::AcceptOnOp op);
3716 EmittedProperty emitAcceptRejectOn(StringRef mnemonic, Value condition,
3717 Value input);
3718 EmittedProperty visitLTL(ltl::ClockOp op);
3719 EmittedProperty visitLTL(ltl::WeakOp op);
3720 EmittedProperty visitLTL(ltl::StrongOp op);
3721
3722 EmittedProperty emitWeakStrongOp(StringRef mnemonic, Value input);
3723 void emitLTLDelay(int64_t delay, std::optional<int64_t> length);
3724 void emitLTLClockingEvent(ltl::ClockEdge edge, Value clock);
3725 void emitLTLConcat(ValueRange inputs);
3726
3727public:
3728 ModuleEmitter &emitter;
3729
3730private:
3731 /// Keep track of all operations emitted within this subexpression for
3732 /// location information tracking.
3733 SmallPtrSetImpl<Operation *> &emittedOps;
3734
3735 /// Tokens buffered for inserting casts/parens after emitting children.
3736 SmallVector<Token> localTokens;
3737
3738 /// Stores tokens until told to flush. Uses provided buffer (tokens).
3739 BufferingPP buffer;
3740
3741 /// Stream to emit expressions into, will add to buffer.
3742 TokenStreamWithCallback<OpLocMap, CallbackDataTy, BufferingPP> ps;
3743};
3744} // end anonymous namespace
3745
3746// Emits a disable signal and its containing property.
3747// This function can be called from withing another emission process in which
3748// case we don't need to check that the local tokens are empty.
3749void PropertyEmitter::emitAssertPropertyDisable(
3750 Value property, Value disable,
3751 PropertyPrecedence parenthesizeIfLooserThan) {
3752 // If the property is tied to a disable, emit that.
3753 if (disable) {
3754 ps << "disable iff" << PP::nbsp << "(";
3755 ps.scopedBox(PP::ibox2, [&] {
3756 emitNestedProperty(disable, PropertyPrecedence::Unary);
3757 ps << ")";
3758 });
3759 ps << PP::space;
3760 }
3761
3762 ps.scopedBox(PP::ibox0,
3763 [&] { emitNestedProperty(property, parenthesizeIfLooserThan); });
3764}
3765
3766// Emits a disable signal and its containing property.
3767// This function can be called from withing another emission process in which
3768// case we don't need to check that the local tokens are empty.
3769void PropertyEmitter::emitAssertPropertyBody(
3770 Value property, Value disable,
3771 PropertyPrecedence parenthesizeIfLooserThan) {
3772 assert(localTokens.empty());
3773
3774 emitAssertPropertyDisable(property, disable, parenthesizeIfLooserThan);
3775
3776 // If we are not using an external token buffer provided through the
3777 // constructor, but we're using the default `PropertyEmitter`-scoped buffer,
3778 // flush it.
3779 if (&buffer.tokens == &localTokens)
3780 buffer.flush(state.pp);
3781}
3782
3783void PropertyEmitter::emitAssertPropertyBody(
3784 Value property, sv::EventControl event, Value clock, Value disable,
3785 PropertyPrecedence parenthesizeIfLooserThan) {
3786 assert(localTokens.empty());
3787 // Wrap to this column.
3788 ps << "@(";
3789 ps.scopedBox(PP::ibox2, [&] {
3790 ps << PPExtString(stringifyEventControl(event)) << PP::space;
3791 emitNestedProperty(clock, PropertyPrecedence::Lowest);
3792 ps << ")";
3793 });
3794 ps << PP::space;
3795
3796 // Emit the rest of the body
3797 emitAssertPropertyDisable(property, disable, parenthesizeIfLooserThan);
3798
3799 // If we are not using an external token buffer provided through the
3800 // constructor, but we're using the default `PropertyEmitter`-scoped buffer,
3801 // flush it.
3802 if (&buffer.tokens == &localTokens)
3803 buffer.flush(state.pp);
3804}
3805
3806EmittedProperty PropertyEmitter::emitNestedProperty(
3807 Value property, PropertyPrecedence parenthesizeIfLooserThan) {
3808 // Emit the property as a plain expression if it doesn't have a property or
3809 // sequence type, in which case it is just a boolean expression.
3810 //
3811 // We use the `LowestPrecedence` for the boolean expression such that it never
3812 // gets parenthesized. According to IEEE 1800-2017, "the operators described
3813 // in Table 11-2 have higher precedence than the sequence and property
3814 // operators". Therefore any boolean expression behaves just like a
3815 // `PropertyPrecedence::Symbol` and needs no parantheses, which is equivalent
3816 // to `VerilogPrecedence::LowestPrecedence`.
3817 if (!isa<ltl::SequenceType, ltl::PropertyType>(property.getType())) {
3818 ExprEmitter(emitter, emittedOps, buffer.tokens)
3819 .emitExpression(property, LowestPrecedence,
3820 /*isAssignmentLikeContext=*/false);
3821 return {PropertyPrecedence::Symbol};
3822 }
3823
3824 unsigned startIndex = buffer.tokens.size();
3825 auto info = dispatchLTLVisitor(property.getDefiningOp());
3826
3827 // If this subexpression would bind looser than the expression it is bound
3828 // into, then we need to parenthesize it. Insert the parentheses
3829 // retroactively.
3830 if (info.precedence > parenthesizeIfLooserThan) {
3831 // Insert {"(", ibox0} before the subexpression.
3832 buffer.tokens.insert(buffer.tokens.begin() + startIndex, BeginToken(0));
3833 buffer.tokens.insert(buffer.tokens.begin() + startIndex, StringToken("("));
3834 // Insert {end, ")" } after the subexpression.
3835 ps << PP::end << ")";
3836 // Reset the precedence level.
3837 info.precedence = PropertyPrecedence::Symbol;
3838 }
3839
3840 // Remember that we emitted this.
3841 emittedOps.insert(property.getDefiningOp());
3842 return info;
3843}
3844
3845EmittedProperty PropertyEmitter::visitUnhandledLTL(Operation *op) {
3846 emitOpError(op, "emission as Verilog property or sequence not supported");
3847 ps << "<<unsupported: " << PPExtString(op->getName().getStringRef()) << ">>";
3848 return {PropertyPrecedence::Symbol};
3849}
3850
3851EmittedProperty PropertyEmitter::visitLTL(ltl::BooleanConstantOp op) {
3852 // Emit the boolean constant value as a literal.
3853 ps << (op.getValueAttr().getValue() ? "1'h1" : "1'h0");
3854 return {PropertyPrecedence::Symbol};
3855}
3856
3857EmittedProperty PropertyEmitter::visitLTL(ltl::AndOp op) {
3858 llvm::interleave(
3859 op.getInputs(),
3860 [&](auto input) { emitNestedProperty(input, PropertyPrecedence::And); },
3861 [&]() { ps << PP::space << "and" << PP::nbsp; });
3862 return {PropertyPrecedence::And};
3863}
3864
3865EmittedProperty PropertyEmitter::visitLTL(ltl::OrOp op) {
3866 llvm::interleave(
3867 op.getInputs(),
3868 [&](auto input) { emitNestedProperty(input, PropertyPrecedence::Or); },
3869 [&]() { ps << PP::space << "or" << PP::nbsp; });
3870 return {PropertyPrecedence::Or};
3871}
3872
3873EmittedProperty PropertyEmitter::visitLTL(ltl::IntersectOp op) {
3874 llvm::interleave(
3875 op.getInputs(),
3876 [&](auto input) {
3877 emitNestedProperty(input, PropertyPrecedence::Intersect);
3878 },
3879 [&]() { ps << PP::space << "intersect" << PP::nbsp; });
3880 return {PropertyPrecedence::Intersect};
3881}
3882
3883void PropertyEmitter::emitLTLDelay(int64_t delay,
3884 std::optional<int64_t> length) {
3885 ps << "##";
3886 if (length) {
3887 if (*length == 0) {
3888 ps.addAsString(delay);
3889 } else {
3890 ps << "[";
3891 ps.addAsString(delay);
3892 ps << ":";
3893 ps.addAsString(delay + *length);
3894 ps << "]";
3895 }
3896 } else {
3897 if (delay == 0) {
3898 ps << "[*]";
3899 } else if (delay == 1) {
3900 ps << "[+]";
3901 } else {
3902 ps << "[";
3903 ps.addAsString(delay);
3904 ps << ":$]";
3905 }
3906 }
3907}
3908
3909void PropertyEmitter::emitLTLClockingEvent(ltl::ClockEdge edge, Value clock) {
3910 ps << "@(";
3911 ps.scopedBox(PP::ibox2, [&] {
3912 ps << PPExtString(stringifyClockEdge(edge)) << PP::space;
3913 emitNestedProperty(clock, PropertyPrecedence::Lowest);
3914 ps << ")";
3915 });
3916}
3917
3918EmittedProperty PropertyEmitter::visitLTL(ltl::DelayOp op) {
3919 emitLTLDelay(op.getDelay(), op.getLength());
3920 ps << PP::space;
3921 emitNestedProperty(op.getInput(), PropertyPrecedence::Concat);
3922 return {PropertyPrecedence::Concat};
3923}
3924
3925EmittedProperty PropertyEmitter::visitLTL(ltl::ClockedDelayOp op) {
3926 emitLTLClockingEvent(op.getEdge(), op.getClock());
3927 ps << PP::space;
3928 emitLTLDelay(op.getDelay(), op.getLength());
3929 ps << PP::space;
3930 emitNestedProperty(op.getInput(), PropertyPrecedence::Concat);
3931 return {PropertyPrecedence::Clocking};
3932}
3933
3934void PropertyEmitter::emitLTLConcat(ValueRange inputs) {
3935 bool addSeparator = false;
3936 for (auto input : inputs) {
3937 if (addSeparator) {
3938 ps << PP::space;
3939 if (!input.getDefiningOp<ltl::DelayOp>())
3940 ps << "##0" << PP::space;
3941 }
3942 addSeparator = true;
3943 emitNestedProperty(input, PropertyPrecedence::Concat);
3944 }
3945}
3946
3947EmittedProperty PropertyEmitter::visitLTL(ltl::ConcatOp op) {
3948 emitLTLConcat(op.getInputs());
3949 return {PropertyPrecedence::Concat};
3950}
3951
3952EmittedProperty PropertyEmitter::visitLTL(ltl::RepeatOp op) {
3953 emitNestedProperty(op.getInput(), PropertyPrecedence::Repeat);
3954 if (auto more = op.getMore()) {
3955 ps << "[*";
3956 ps.addAsString(op.getBase());
3957 if (*more != 0) {
3958 ps << ":";
3959 ps.addAsString(op.getBase() + *more);
3960 }
3961 ps << "]";
3962 } else {
3963 if (op.getBase() == 0) {
3964 ps << "[*]";
3965 } else if (op.getBase() == 1) {
3966 ps << "[+]";
3967 } else {
3968 ps << "[*";
3969 ps.addAsString(op.getBase());
3970 ps << ":$]";
3971 }
3972 }
3973 return {PropertyPrecedence::Repeat};
3974}
3975
3976EmittedProperty PropertyEmitter::visitLTL(ltl::GoToRepeatOp op) {
3977 emitNestedProperty(op.getInput(), PropertyPrecedence::Repeat);
3978 // More always exists
3979 auto more = op.getMore();
3980 ps << "[->";
3981 ps.addAsString(op.getBase());
3982 if (more != 0) {
3983 ps << ":";
3984 ps.addAsString(op.getBase() + more);
3985 }
3986 ps << "]";
3987
3988 return {PropertyPrecedence::Repeat};
3989}
3990
3991EmittedProperty PropertyEmitter::visitLTL(ltl::NonConsecutiveRepeatOp op) {
3992 emitNestedProperty(op.getInput(), PropertyPrecedence::Repeat);
3993 // More always exists
3994 auto more = op.getMore();
3995 ps << "[=";
3996 ps.addAsString(op.getBase());
3997 if (more != 0) {
3998 ps << ":";
3999 ps.addAsString(op.getBase() + more);
4000 }
4001 ps << "]";
4002
4003 return {PropertyPrecedence::Repeat};
4004}
4005
4006EmittedProperty PropertyEmitter::visitLTL(ltl::NotOp op) {
4007 // Emit `not(accept_on(not(X), c))` as `reject_on (c) X` by duality, and
4008 // likewise for the `sync` variants.
4009 if (auto accept = op.getInput().getDefiningOp<ltl::AcceptOnOp>())
4010 if (auto innerNot = accept.getInput().getDefiningOp<ltl::NotOp>())
4011 return emitAcceptRejectOn(accept.getSync() ? "sync_reject_on"
4012 : "reject_on",
4013 accept.getCondition(), innerNot.getInput());
4014 // Emit `not (s_eventually X)` as `always ...` by duality, pulling the
4015 // quantifier to the top and cancelling any inner negation.
4016 if (auto ev = op.getInput().getDefiningOp<ltl::EventuallyOp>()) {
4017 ps << "always" << PP::space;
4018 if (auto innerNot = ev.getInput().getDefiningOp<ltl::NotOp>()) {
4019 // `not(strong_eventually(not(X)))` -> `always X`.
4020 emitNestedProperty(innerNot.getInput(), PropertyPrecedence::Qualifier);
4021 } else {
4022 // `not(strong_eventually(X))` -> `always (not X)`.
4023 ps << "not" << PP::space;
4024 emitNestedProperty(ev.getInput(), PropertyPrecedence::Unary);
4025 }
4026 return {PropertyPrecedence::Qualifier};
4027 }
4028 ps << "not" << PP::space;
4029 emitNestedProperty(op.getInput(), PropertyPrecedence::Unary);
4030 return {PropertyPrecedence::Unary};
4031}
4032
4033/// For a value `concat(..., delay(const(true), 1, 0))`, return `...`. This is
4034/// useful for emitting `(seq ##1 true) |-> prop` as `seq |=> prop`.
4035static ValueRange getNonOverlappingConcatSubrange(Value value) {
4036 auto concatOp = value.getDefiningOp<ltl::ConcatOp>();
4037 if (!concatOp || concatOp.getInputs().size() < 2)
4038 return {};
4039 auto delayOp = concatOp.getInputs().back().getDefiningOp<ltl::DelayOp>();
4040 if (!delayOp || delayOp.getDelay() != 1 || delayOp.getLength() != 0)
4041 return {};
4042 auto constOp = delayOp.getInput().getDefiningOp<ConstantOp>();
4043 if (!constOp || !constOp.getValue().isOne())
4044 return {};
4045 return concatOp.getInputs().drop_back();
4046}
4047
4048EmittedProperty PropertyEmitter::visitLTL(ltl::ImplicationOp op) {
4049 // Emit `(seq ##1 true) |-> prop` as `seq |=> prop`.
4050 if (auto range = getNonOverlappingConcatSubrange(op.getAntecedent());
4051 !range.empty()) {
4052 emitLTLConcat(range);
4053 ps << PP::space << "|=>" << PP::nbsp;
4054 } else {
4055 emitNestedProperty(op.getAntecedent(), PropertyPrecedence::Implication);
4056 ps << PP::space << "|->" << PP::nbsp;
4057 }
4058 emitNestedProperty(op.getConsequent(), PropertyPrecedence::Implication);
4059 return {PropertyPrecedence::Implication};
4060}
4061
4062EmittedProperty PropertyEmitter::visitLTL(ltl::UntilOp op) {
4063 emitNestedProperty(op.getInput(), PropertyPrecedence::Until);
4064 ps << PP::space << "until" << PP::space;
4065 emitNestedProperty(op.getCondition(), PropertyPrecedence::Until);
4066 return {PropertyPrecedence::Until};
4067}
4068
4069EmittedProperty PropertyEmitter::visitLTL(ltl::EventuallyOp op) {
4070 ps << "s_eventually" << PP::space;
4071 emitNestedProperty(op.getInput(), PropertyPrecedence::Qualifier);
4072 return {PropertyPrecedence::Qualifier};
4073}
4074
4075EmittedProperty PropertyEmitter::emitAcceptRejectOn(StringRef mnemonic,
4076 Value condition,
4077 Value input) {
4078 ps << mnemonic << PP::nbsp << "(";
4079 ps.scopedBox(PP::ibox0, [&] {
4080 emitNestedProperty(condition, PropertyPrecedence::Lowest);
4081 ps << ")";
4082 });
4083 ps << PP::space;
4084 emitNestedProperty(input, PropertyPrecedence::Qualifier);
4085 return {PropertyPrecedence::Qualifier};
4086}
4087
4088EmittedProperty PropertyEmitter::visitLTL(ltl::AcceptOnOp op) {
4089 return emitAcceptRejectOn(op.getSync() ? "sync_accept_on" : "accept_on",
4090 op.getCondition(), op.getInput());
4091}
4092
4093EmittedProperty PropertyEmitter::visitLTL(ltl::ClockOp op) {
4094 emitLTLClockingEvent(op.getEdge(), op.getClock());
4095 ps << PP::space;
4096 emitNestedProperty(op.getInput(), PropertyPrecedence::Clocking);
4097 return {PropertyPrecedence::Clocking};
4098}
4099
4100// Weak and strong are emitted identically
4101EmittedProperty PropertyEmitter::emitWeakStrongOp(StringRef mnemonic,
4102 Value input) {
4103 ps << mnemonic << PP::space << "(";
4104 ps.scopedBox(PP::ibox2, [&] {
4105 emitNestedProperty(input, PropertyPrecedence::Unary);
4106 ps << ")";
4107 });
4108 return {PropertyPrecedence::Lowest};
4109}
4110
4111EmittedProperty PropertyEmitter::visitLTL(ltl::WeakOp op) {
4112 return emitWeakStrongOp("weak", op.getInput());
4113}
4114
4115EmittedProperty PropertyEmitter::visitLTL(ltl::StrongOp op) {
4116 return emitWeakStrongOp("strong", op.getInput());
4117}
4118
4119// NOLINTEND(misc-no-recursion)
4120
4121//===----------------------------------------------------------------------===//
4122// NameCollector
4123//===----------------------------------------------------------------------===//
4124
4125namespace {
4126class NameCollector {
4127public:
4128 NameCollector(ModuleEmitter &moduleEmitter) : moduleEmitter(moduleEmitter) {}
4129
4130 // Scan operations in the specified block, collecting information about
4131 // those that need to be emitted as declarations.
4132 void collectNames(Block &block);
4133
4134 size_t getMaxDeclNameWidth() const { return maxDeclNameWidth; }
4135 size_t getMaxTypeWidth() const { return maxTypeWidth; }
4136
4137private:
4138 size_t maxDeclNameWidth = 0, maxTypeWidth = 0;
4139 ModuleEmitter &moduleEmitter;
4140
4141 /// Types that are longer than `maxTypeWidthBound` are not added to the
4142 /// `maxTypeWidth` to prevent one single huge type from messing up the
4143 /// alignment of all other declarations.
4144 static constexpr size_t maxTypeWidthBound = 32;
4145};
4146} // namespace
4147
4148// NOLINTNEXTLINE(misc-no-recursion)
4149void NameCollector::collectNames(Block &block) {
4150 // Loop over all of the results of all of the ops. Anything that defines a
4151 // value needs to be noticed.
4152 for (auto &op : block) {
4153 // Instances have an instance name to recognize but we don't need to look
4154 // at the result values since wires used by instances should be traversed
4155 // anyway.
4156 if (isa<InstanceOp, InterfaceInstanceOp, FuncCallProceduralOp, FuncCallOp>(
4157 op))
4158 continue;
4159 if (isa<ltl::LTLDialect, debug::DebugDialect>(op.getDialect()))
4160 continue;
4161
4162 if (!isVerilogExpression(&op)) {
4163 for (auto result : op.getResults()) {
4164 StringRef declName = getVerilogDeclWord(&op, moduleEmitter);
4165 maxDeclNameWidth = std::max(declName.size(), maxDeclNameWidth);
4166 SmallString<16> typeString;
4167
4168 // Convert the port's type to a string and measure it.
4169 {
4170 llvm::raw_svector_ostream stringStream(typeString);
4171 moduleEmitter.printPackedType(stripUnpackedTypes(result.getType()),
4172 stringStream, op.getLoc());
4173 }
4174 if (typeString.size() <= maxTypeWidthBound)
4175 maxTypeWidth = std::max(typeString.size(), maxTypeWidth);
4176 }
4177 }
4178
4179 // Recursively process any regions under the op iff this is a procedural
4180 // #ifdef region: we need to emit automatic logic values at the top of the
4181 // enclosing region.
4182 if (isa<IfDefProceduralOp, OrderedOutputOp>(op)) {
4183 for (auto &region : op.getRegions()) {
4184 if (!region.empty())
4185 collectNames(region.front());
4186 }
4187 continue;
4188 }
4189 }
4190}
4191
4192//===----------------------------------------------------------------------===//
4193// StmtEmitter
4194//===----------------------------------------------------------------------===//
4195
4196namespace {
4197/// This emits statement-related operations.
4198// NOLINTBEGIN(misc-no-recursion)
4199class StmtEmitter : public EmitterBase,
4200 public hw::StmtVisitor<StmtEmitter, LogicalResult>,
4201 public sv::Visitor<StmtEmitter, LogicalResult>,
4202 public verif::Visitor<StmtEmitter, LogicalResult> {
4203public:
4204 /// Create an ExprEmitter for the specified module emitter, and keeping track
4205 /// of any emitted expressions in the specified set.
4206 StmtEmitter(ModuleEmitter &emitter, const LoweringOptions &options)
4207 : EmitterBase(emitter.state), emitter(emitter), options(options) {}
4208
4209 void emitStatement(Operation *op);
4210 void emitStatementBlock(Block &body);
4211
4212 /// Emit a declaration.
4213 LogicalResult emitDeclaration(Operation *op);
4214
4215private:
4216 void collectNamesAndCalculateDeclarationWidths(Block &block);
4217
4218 void
4219 emitExpression(Value exp, SmallPtrSetImpl<Operation *> &emittedExprs,
4220 VerilogPrecedence parenthesizeIfLooserThan = LowestPrecedence,
4221 bool isAssignmentLikeContext = false);
4222 void emitSVAttributes(Operation *op);
4223
4224 using hw::StmtVisitor<StmtEmitter, LogicalResult>::visitStmt;
4225 using sv::Visitor<StmtEmitter, LogicalResult>::visitSV;
4226 using verif::Visitor<StmtEmitter, LogicalResult>::visitVerif;
4227 friend class hw::StmtVisitor<StmtEmitter, LogicalResult>;
4228 friend class sv::Visitor<StmtEmitter, LogicalResult>;
4229 friend class verif::Visitor<StmtEmitter, LogicalResult>;
4230
4231 // Visitor methods.
4232 LogicalResult visitUnhandledStmt(Operation *op) { return failure(); }
4233 LogicalResult visitInvalidStmt(Operation *op) { return failure(); }
4234 LogicalResult visitUnhandledSV(Operation *op) { return failure(); }
4235 LogicalResult visitInvalidSV(Operation *op) { return failure(); }
4236 LogicalResult visitUnhandledVerif(Operation *op) { return failure(); }
4237 LogicalResult visitInvalidVerif(Operation *op) { return failure(); }
4238
4239 LogicalResult visitSV(sv::WireOp op) { return emitDeclaration(op); }
4240 LogicalResult visitSV(VarOp op) { return emitDeclaration(op); }
4241 LogicalResult visitSV(RegOp op) { return emitDeclaration(op); }
4242 LogicalResult visitSV(LogicOp op) { return emitDeclaration(op); }
4243 LogicalResult visitSV(LocalParamOp op) { return emitDeclaration(op); }
4244 template <typename Op>
4245 LogicalResult
4246 emitAssignLike(Op op, PPExtString syntax,
4247 std::optional<PPExtString> wordBeforeLHS = std::nullopt);
4248 void emitAssignLike(llvm::function_ref<void()> emitLHS,
4249 llvm::function_ref<void()> emitRHS, PPExtString syntax,
4250 PPExtString postSyntax = PPExtString(";"),
4251 std::optional<PPExtString> wordBeforeLHS = std::nullopt);
4252 LogicalResult visitSV(AssignOp op);
4253 LogicalResult visitSV(VarAssignOp op);
4254 LogicalResult visitSV(BPAssignOp op);
4255 LogicalResult visitSV(PAssignOp op);
4256 LogicalResult visitSV(ForceOp op);
4257 LogicalResult visitSV(ReleaseOp op);
4258 LogicalResult visitSV(AliasOp op);
4259 LogicalResult visitSV(InterfaceInstanceOp op);
4260 LogicalResult emitOutputLikeOp(Operation *op, const ModulePortInfo &ports);
4261 LogicalResult visitStmt(OutputOp op);
4262
4263 LogicalResult visitStmt(InstanceOp op);
4264 void emitInstancePortList(Operation *op, ModulePortInfo &modPortInfo,
4265 ArrayRef<Value> instPortValues);
4266
4267 LogicalResult visitStmt(TypeScopeOp op);
4268 LogicalResult visitStmt(TypedeclOp op);
4269 LogicalResult visitSV(PackageOp op);
4270
4271 LogicalResult emitIfDef(Operation *op, MacroIdentAttr cond);
4272 LogicalResult visitSV(OrderedOutputOp op);
4273 LogicalResult visitSV(IfDefOp op) { return emitIfDef(op, op.getCond()); }
4274 LogicalResult visitSV(IfDefProceduralOp op) {
4275 return emitIfDef(op, op.getCond());
4276 }
4277 LogicalResult visitSV(IfOp op);
4278 LogicalResult visitSV(AlwaysOp op);
4279 LogicalResult visitSV(AlwaysCombOp op);
4280 LogicalResult visitSV(AlwaysFFOp op);
4281 LogicalResult visitSV(InitialOp op);
4282 LogicalResult visitSV(CaseOp op);
4283 template <typename OpTy, typename EmitPrefixFn>
4284 LogicalResult
4285 emitFormattedWriteLikeOp(OpTy op, StringRef callee, StringRef formatString,
4286 ValueRange substitutions, EmitPrefixFn emitPrefix);
4287 LogicalResult visitSV(WriteOp op);
4288 LogicalResult visitSV(FWriteOp op);
4289 LogicalResult visitSV(FFlushOp op);
4290 LogicalResult visitSV(FCloseOp op);
4291 LogicalResult visitSV(VerbatimOp op);
4292 LogicalResult visitSV(MacroRefOp op);
4293
4294 LogicalResult emitSimulationControlTask(Operation *op, PPExtString taskName,
4295 std::optional<unsigned> verbosity);
4296 LogicalResult visitSV(StopOp op);
4297 LogicalResult visitSV(FinishOp op);
4298 LogicalResult visitSV(ExitOp op);
4299
4300 LogicalResult emitSeverityMessageTask(Operation *op, PPExtString taskName,
4301 std::optional<unsigned> verbosity,
4302 StringAttr message,
4303 ValueRange operands);
4304
4305 // Helper template for nonfatal message operations
4306 template <typename OpTy>
4307 LogicalResult emitNonfatalMessageOp(OpTy op, const char *taskName) {
4308 return emitSeverityMessageTask(op, PPExtString(taskName), {},
4309 op.getMessageAttr(), op.getSubstitutions());
4310 }
4311
4312 // Helper template for fatal message operations
4313 template <typename OpTy>
4314 LogicalResult emitFatalMessageOp(OpTy op) {
4315 return emitSeverityMessageTask(op, PPExtString("$fatal"), op.getVerbosity(),
4316 op.getMessageAttr(), op.getSubstitutions());
4317 }
4318
4319 LogicalResult visitSV(FatalProceduralOp op);
4320 LogicalResult visitSV(FatalOp op);
4321 LogicalResult visitSV(ErrorProceduralOp op);
4322 LogicalResult visitSV(WarningProceduralOp op);
4323 LogicalResult visitSV(InfoProceduralOp op);
4324 LogicalResult visitSV(ErrorOp op);
4325 LogicalResult visitSV(WarningOp op);
4326 LogicalResult visitSV(InfoOp op);
4327
4328 LogicalResult visitSV(ReadMemOp op);
4329
4330 LogicalResult visitSV(GenerateOp op);
4331 LogicalResult visitSV(GenerateCaseOp op);
4332 LogicalResult visitSV(GenerateForOp op);
4333
4334 LogicalResult visitSV(ForOp op);
4335
4336 void emitAssertionLabel(Operation *op);
4337 void emitAssertionMessage(StringAttr message, ValueRange args,
4338 SmallPtrSetImpl<Operation *> &ops,
4339 bool isConcurrent);
4340 template <typename Op>
4341 LogicalResult emitImmediateAssertion(Op op, PPExtString opName);
4342 LogicalResult visitSV(AssertOp op);
4343 LogicalResult visitSV(AssumeOp op);
4344 LogicalResult visitSV(CoverOp op);
4345 template <typename Op>
4346 LogicalResult emitConcurrentAssertion(Op op, PPExtString opName);
4347 LogicalResult visitSV(AssertConcurrentOp op);
4348 LogicalResult visitSV(AssumeConcurrentOp op);
4349 LogicalResult visitSV(CoverConcurrentOp op);
4350 template <typename Op>
4351 LogicalResult emitPropertyAssertion(Op op, PPExtString opName);
4352 LogicalResult visitSV(AssertPropertyOp op);
4353 LogicalResult visitSV(AssumePropertyOp op);
4354 LogicalResult visitSV(CoverPropertyOp op);
4355
4356 LogicalResult visitSV(BindOp op);
4357 LogicalResult visitSV(InterfaceOp op);
4358 LogicalResult visitSV(sv::SVVerbatimSourceOp op);
4359 LogicalResult visitSV(InterfaceSignalOp op);
4360 LogicalResult visitSV(InterfaceModportOp op);
4361 LogicalResult visitSV(AssignInterfaceSignalOp op);
4362 LogicalResult visitSV(MacroErrorOp op);
4363 LogicalResult visitSV(MacroDefOp op);
4364
4365 void emitBlockAsStatement(Block *block,
4366 const SmallPtrSetImpl<Operation *> &locationOps,
4367 StringRef multiLineComment = StringRef());
4368
4369 LogicalResult visitSV(FuncDPIImportOp op);
4370 template <typename CallOp>
4371 LogicalResult emitFunctionCall(CallOp callOp);
4372 LogicalResult visitSV(FuncCallProceduralOp op);
4373 LogicalResult visitSV(FuncCallOp op);
4374 LogicalResult visitSV(ReturnOp op);
4375 LogicalResult visitSV(IncludeOp op);
4376
4377public:
4378 ModuleEmitter &emitter;
4379
4380private:
4381 /// These keep track of the maximum length of name width and type width in the
4382 /// current statement scope.
4383 size_t maxDeclNameWidth = 0;
4384 size_t maxTypeWidth = 0;
4385
4386 const LoweringOptions &options;
4387};
4388
4389} // end anonymous namespace
4390
4391/// Emit the specified value as an expression. If this is an inline-emitted
4392/// expression, we emit that expression, otherwise we emit a reference to the
4393/// already computed name.
4394///
4395void StmtEmitter::emitExpression(Value exp,
4396 SmallPtrSetImpl<Operation *> &emittedExprs,
4397 VerilogPrecedence parenthesizeIfLooserThan,
4398 bool isAssignmentLikeContext) {
4399 ExprEmitter(emitter, emittedExprs)
4400 .emitExpression(exp, parenthesizeIfLooserThan, isAssignmentLikeContext);
4401}
4402
4403/// Emit SystemVerilog attributes attached to the statement op as dialect
4404/// attributes.
4405void StmtEmitter::emitSVAttributes(Operation *op) {
4406 // SystemVerilog 2017 Section 5.12.
4407 auto svAttrs = getSVAttributes(op);
4408 if (!svAttrs)
4409 return;
4410
4411 startStatement(); // For attributes.
4412 emitSVAttributesImpl(ps, svAttrs, /*mayBreak=*/true);
4413 setPendingNewline();
4414}
4415
4416void StmtEmitter::emitAssignLike(llvm::function_ref<void()> emitLHS,
4417 llvm::function_ref<void()> emitRHS,
4418 PPExtString syntax, PPExtString postSyntax,
4419 std::optional<PPExtString> wordBeforeLHS) {
4420 // If wraps, indent.
4421 ps.scopedBox(PP::ibox2, [&]() {
4422 if (wordBeforeLHS) {
4423 ps << *wordBeforeLHS << PP::space;
4424 }
4425 emitLHS();
4426 // Allow breaking before 'syntax' (e.g., '=') if long assignment.
4427 ps << PP::space << syntax << PP::space;
4428 // RHS is boxed to right of the syntax.
4429 ps.scopedBox(PP::ibox0, [&]() {
4430 emitRHS();
4431 ps << postSyntax;
4432 });
4433 });
4434}
4435
4436template <typename Op>
4437LogicalResult
4438StmtEmitter::emitAssignLike(Op op, PPExtString syntax,
4439 std::optional<PPExtString> wordBeforeLHS) {
4440 SmallPtrSet<Operation *, 8> ops;
4441 ops.insert(op);
4442
4443 startStatement();
4444 ps.addCallback({op, true});
4445 emitAssignLike([&]() { emitExpression(op.getDest(), ops); },
4446 [&]() {
4447 emitExpression(op.getSrc(), ops, LowestPrecedence,
4448 /*isAssignmentLikeContext=*/true);
4449 },
4450 syntax, PPExtString(";"), wordBeforeLHS);
4451
4452 ps.addCallback({op, false});
4453 emitLocationInfoAndNewLine(ops);
4454 return success();
4455}
4456
4457LogicalResult StmtEmitter::visitSV(AssignOp op) {
4458 // prepare assigns wires to instance outputs and function results, but these
4459 // are logically handled in the port binding list when outputing an instance.
4460 if (isa_and_nonnull<HWInstanceLike, FuncCallOp>(op.getSrc().getDefiningOp()))
4461 return success();
4462
4463 if (emitter.assignsInlined.count(op))
4464 return success();
4465
4466 // Emit SV attributes. See Spec 12.3.
4467 emitSVAttributes(op);
4468
4469 return emitAssignLike(op, PPExtString("="), PPExtString("assign"));
4470}
4471
4472LogicalResult StmtEmitter::visitSV(VarAssignOp op) {
4473 // Emit SV attributes. See Spec 12.3.
4474 emitSVAttributes(op);
4475
4476 return emitAssignLike(op, PPExtString("="), PPExtString("assign"));
4477}
4478
4479LogicalResult StmtEmitter::visitSV(BPAssignOp op) {
4480 if (op.getSrc().getDefiningOp<FuncCallProceduralOp>())
4481 return success();
4482
4483 // If the assign is emitted into logic declaration, we must not emit again.
4484 if (emitter.assignsInlined.count(op))
4485 return success();
4486
4487 // Emit SV attributes. See Spec 12.3.
4488 emitSVAttributes(op);
4489
4490 return emitAssignLike(op, PPExtString("="));
4491}
4492
4493LogicalResult StmtEmitter::visitSV(PAssignOp op) {
4494 // Emit SV attributes. See Spec 12.3.
4495 emitSVAttributes(op);
4496
4497 return emitAssignLike(op, PPExtString("<="));
4498}
4499
4500LogicalResult StmtEmitter::visitSV(ForceOp op) {
4501 if (hasSVAttributes(op))
4502 emitError(op, "SV attributes emission is unimplemented for the op");
4503
4504 return emitAssignLike(op, PPExtString("="), PPExtString("force"));
4505}
4506
4507LogicalResult StmtEmitter::visitSV(ReleaseOp op) {
4508 if (hasSVAttributes(op))
4509 emitError(op, "SV attributes emission is unimplemented for the op");
4510
4511 startStatement();
4512 SmallPtrSet<Operation *, 8> ops;
4513 ops.insert(op);
4514 ps.addCallback({op, true});
4515 ps.scopedBox(PP::ibox2, [&]() {
4516 ps << "release" << PP::space;
4517 emitExpression(op.getDest(), ops);
4518 ps << ";";
4519 });
4520 ps.addCallback({op, false});
4521 emitLocationInfoAndNewLine(ops);
4522 return success();
4523}
4524
4525LogicalResult StmtEmitter::visitSV(AliasOp op) {
4526 if (hasSVAttributes(op))
4527 emitError(op, "SV attributes emission is unimplemented for the op");
4528
4529 startStatement();
4530 SmallPtrSet<Operation *, 8> ops;
4531 ops.insert(op);
4532 ps.addCallback({op, true});
4533 ps.scopedBox(PP::ibox2, [&]() {
4534 ps << "alias" << PP::space;
4535 ps.scopedBox(PP::cbox0, [&]() { // If any breaks, all break.
4536 llvm::interleave(
4537 op.getOperands(), [&](Value v) { emitExpression(v, ops); },
4538 [&]() { ps << PP::nbsp << "=" << PP::space; });
4539 ps << ";";
4540 });
4541 });
4542 ps.addCallback({op, false});
4543 emitLocationInfoAndNewLine(ops);
4544 return success();
4545}
4546
4547LogicalResult StmtEmitter::visitSV(InterfaceInstanceOp op) {
4548 auto doNotPrint = op.getDoNotPrint();
4549 if (doNotPrint && !state.options.emitBindComments)
4550 return success();
4551
4552 if (hasSVAttributes(op))
4553 emitError(op, "SV attributes emission is unimplemented for the op");
4554
4555 startStatement();
4556 StringRef prefix = "";
4557 ps.addCallback({op, true});
4558 if (doNotPrint) {
4559 prefix = "// ";
4560 ps << "// This interface is elsewhere emitted as a bind statement."
4561 << PP::newline;
4562 }
4563
4564 SmallPtrSet<Operation *, 8> ops;
4565 ops.insert(op);
4566
4567 auto *interfaceOp = op.getReferencedInterface(&state.symbolCache);
4568 assert(interfaceOp && "InterfaceInstanceOp has invalid symbol that does not "
4569 "point to an interface");
4570
4571 auto verilogName = getSymOpName(interfaceOp);
4572 if (!prefix.empty())
4573 ps << PPExtString(prefix);
4574 ps << PPExtString(verilogName)
4575 << PP::nbsp /* don't break, may be comment line */
4576 << PPExtString(op.getName()) << "();";
4577
4578 ps.addCallback({op, false});
4579 emitLocationInfoAndNewLine(ops);
4580
4581 return success();
4582}
4583
4584/// For OutputOp and ReturnOp we put "assign" statements at the end of the
4585/// Verilog module or function respectively to assign outputs to intermediate
4586/// wires.
4587LogicalResult StmtEmitter::emitOutputLikeOp(Operation *op,
4588 const ModulePortInfo &ports) {
4589 SmallPtrSet<Operation *, 8> ops;
4590 size_t operandIndex = 0;
4591 bool isProcedural = op->getParentOp()->hasTrait<ProceduralRegion>();
4592 for (PortInfo port : ports.getOutputs()) {
4593 auto operand = op->getOperand(operandIndex);
4594 // Outputs that are set by the output port of an instance are handled
4595 // directly when the instance is emitted.
4596 // Keep synced with countStatements() and visitStmt(InstanceOp).
4597 if (operand.hasOneUse() && operand.getDefiningOp() &&
4598 isa<InstanceOp>(operand.getDefiningOp())) {
4599 ++operandIndex;
4600 continue;
4601 }
4602
4603 ops.clear();
4604 ops.insert(op);
4605
4606 startStatement();
4607 ps.addCallback({op, true});
4608 bool isZeroBit = isZeroBitType(port.type);
4609 ps.scopedBox(isZeroBit ? PP::neverbox : PP::ibox2, [&]() {
4610 if (isZeroBit)
4611 ps << "// Zero width: ";
4612 // Emit "assign" only in a non-procedural region.
4613 if (!isProcedural)
4614 ps << "assign" << PP::space;
4615 ps << PPExtString(port.getVerilogName());
4616 ps << PP::space << "=" << PP::space;
4617 ps.scopedBox(PP::ibox0, [&]() {
4618 // If this is a zero-width constant then don't emit it (illegal). Else,
4619 // emit the expression - even for zero width - for traceability.
4620 if (isZeroBit &&
4621 isa_and_nonnull<hw::ConstantOp>(operand.getDefiningOp()))
4622 ps << "/*Zero width*/";
4623 else
4624 emitExpression(operand, ops, LowestPrecedence,
4625 /*isAssignmentLikeContext=*/true);
4626 ps << ";";
4627 });
4628 });
4629 ps.addCallback({op, false});
4630 emitLocationInfoAndNewLine(ops);
4631
4632 ++operandIndex;
4633 }
4634 return success();
4635}
4636
4637LogicalResult StmtEmitter::visitStmt(OutputOp op) {
4638 auto parent = op->getParentOfType<PortList>();
4639 ModulePortInfo ports(parent.getPortList());
4640 return emitOutputLikeOp(op, ports);
4641}
4642
4643LogicalResult StmtEmitter::visitStmt(TypeScopeOp op) {
4644 startStatement();
4645 auto typescopeDef = ("_TYPESCOPE_" + op.getSymName()).str();
4646 ps << "`ifndef " << typescopeDef << PP::newline;
4647 ps << "`define " << typescopeDef;
4648 setPendingNewline();
4649 emitStatementBlock(*op.getBodyBlock());
4650 startStatement();
4651 ps << "`endif // " << typescopeDef;
4652 setPendingNewline();
4653 return success();
4654}
4655
4656LogicalResult StmtEmitter::visitStmt(TypedeclOp op) {
4657 if (hasSVAttributes(op))
4658 emitError(op, "SV attributes emission is unimplemented for the op");
4659
4660 startStatement();
4661 auto zeroBitType = isZeroBitType(op.getType());
4662 if (zeroBitType)
4663 ps << PP::neverbox << "// ";
4664
4665 SmallPtrSet<Operation *, 8> ops;
4666 ops.insert(op);
4667 ps.scopedBox(PP::ibox2, [&]() {
4668 ps << "typedef" << PP::space;
4669 ps.invokeWithStringOS([&](auto &os) {
4670 emitter.printPackedType(stripUnpackedTypes(op.getType()), os, op.getLoc(),
4671 op.getAliasType(), false);
4672 });
4673 ps << PP::space << PPExtString(op.getPreferredName());
4674 ps.invokeWithStringOS(
4675 [&](auto &os) { emitter.printUnpackedTypePostfix(op.getType(), os); });
4676 ps << ";";
4677 });
4678 if (zeroBitType)
4679 ps << PP::end;
4680 emitLocationInfoAndNewLine(ops);
4681 return success();
4682}
4683
4684LogicalResult StmtEmitter::visitSV(PackageOp op) {
4685 llvm::SaveAndRestore<Operation *> package(emitter.currentPackage, op);
4686 startStatement();
4687 ps.addCallback({op, true});
4688 ps << "package " << PPExtString(getSymOpName(op)) << ";";
4689 setPendingNewline();
4690 ps.scopedBox(PP::bbox2, [&]() { emitStatementBlock(*op.getBodyBlock()); });
4691 startStatement();
4692 ps << "endpackage";
4693 ps.addCallback({op, false});
4694 setPendingNewline();
4695 return success();
4696}
4697
4698template <typename CallOpTy>
4699LogicalResult StmtEmitter::emitFunctionCall(CallOpTy op) {
4700 startStatement();
4701
4702 auto callee =
4703 dyn_cast<FuncOp>(state.symbolCache.getDefinition(op.getCalleeAttr()));
4704
4705 SmallPtrSet<Operation *, 8> ops;
4706 ops.insert(op);
4707 assert(callee);
4708
4709 auto explicitReturn = op.getExplicitlyReturnedValue(callee);
4710 if (explicitReturn) {
4711 assert(explicitReturn.hasOneUse());
4712 if (op->getParentOp()->template hasTrait<ProceduralRegion>()) {
4713 auto bpassignOp = cast<sv::BPAssignOp>(*explicitReturn.user_begin());
4714 emitExpression(bpassignOp.getDest(), ops);
4715 } else {
4716 auto assignOp = cast<sv::AssignOp>(*explicitReturn.user_begin());
4717 ps << "assign" << PP::nbsp;
4718 emitExpression(assignOp.getDest(), ops);
4719 }
4720 ps << PP::nbsp << "=" << PP::nbsp;
4721 }
4722
4723 auto arguments = callee.getPortList(true);
4724
4725 ps << PPExtString(getSymOpName(callee)) << "(";
4726
4727 bool needsComma = false;
4728 auto printArg = [&](Value value) {
4729 if (needsComma)
4730 ps << "," << PP::space;
4731 emitExpression(value, ops);
4732 needsComma = true;
4733 };
4734
4735 ps.scopedBox(PP::ibox0, [&] {
4736 unsigned inputIndex = 0, outputIndex = 0;
4737 for (auto arg : arguments) {
4738 if (arg.dir == hw::ModulePort::Output)
4739 printArg(
4740 op.getResults()[outputIndex++].getUsers().begin()->getOperand(0));
4741 else
4742 printArg(op.getInputs()[inputIndex++]);
4743 }
4744 });
4745
4746 ps << ");";
4747 emitLocationInfoAndNewLine(ops);
4748 return success();
4749}
4750
4751LogicalResult StmtEmitter::visitSV(FuncCallProceduralOp op) {
4752 return emitFunctionCall(op);
4753}
4754
4755LogicalResult StmtEmitter::visitSV(FuncCallOp op) {
4756 return emitFunctionCall(op);
4757}
4758
4759template <typename PPS>
4760void emitFunctionSignature(ModuleEmitter &emitter, PPS &ps, FuncOp op,
4761 bool isAutomatic = false,
4762 bool emitAsTwoStateType = false) {
4763 ps << "function" << PP::nbsp;
4764 if (isAutomatic)
4765 ps << "automatic" << PP::nbsp;
4766 auto retType = op.getExplicitlyReturnedType();
4767 if (retType) {
4768 ps.invokeWithStringOS([&](auto &os) {
4769 emitter.printPackedType(retType, os, op->getLoc(), {}, false, true,
4770 emitAsTwoStateType);
4771 });
4772 } else
4773 ps << "void";
4774 ps << PP::nbsp << PPExtString(getSymOpName(op));
4775
4776 emitter.emitPortList(
4777 op, ModulePortInfo(op.getPortList(/*excludeExplicitReturn=*/true)), true);
4778}
4779
4780LogicalResult StmtEmitter::visitSV(ReturnOp op) {
4781 auto parent = op->getParentOfType<sv::FuncOp>();
4782 ModulePortInfo ports(parent.getPortList(false));
4783 return emitOutputLikeOp(op, ports);
4784}
4785
4786LogicalResult StmtEmitter::visitSV(IncludeOp op) {
4787 startStatement();
4788 ps << "`include" << PP::nbsp;
4789
4790 if (op.getStyle() == IncludeStyle::System)
4791 ps << "<" << op.getTarget() << ">";
4792 else
4793 ps << "\"" << op.getTarget() << "\"";
4794
4795 emitLocationInfo(op.getLoc());
4796 setPendingNewline();
4797 return success();
4798}
4799
4800LogicalResult StmtEmitter::visitSV(FuncDPIImportOp importOp) {
4801 startStatement();
4802
4803 ps << "import" << PP::nbsp << "\"DPI-C\"" << PP::nbsp << "context"
4804 << PP::nbsp;
4805
4806 // Emit a linkage name if provided.
4807 if (auto linkageName = importOp.getLinkageName())
4808 ps << *linkageName << PP::nbsp << "=" << PP::nbsp;
4809 auto op =
4810 cast<FuncOp>(state.symbolCache.getDefinition(importOp.getCalleeAttr()));
4811 assert(op.isDeclaration() && "function must be a declaration");
4812 emitFunctionSignature(emitter, ps, op, /*isAutomatic=*/false,
4813 /*emitAsTwoStateType=*/true);
4814 assert(state.pendingNewline);
4815 ps << PP::newline;
4816
4817 return success();
4818}
4819
4820LogicalResult StmtEmitter::visitSV(FFlushOp op) {
4821 if (hasSVAttributes(op))
4822 emitError(op, "SV attributes emission is unimplemented for the op");
4823
4824 startStatement();
4825 SmallPtrSet<Operation *, 8> ops;
4826 ops.insert(op);
4827
4828 ps.addCallback({op, true});
4829 ps << "$fflush(";
4830 if (auto fd = op.getFd())
4831 ps.scopedBox(PP::ibox0, [&]() { emitExpression(op.getFd(), ops); });
4832
4833 ps << ");";
4834 ps.addCallback({op, false});
4835 emitLocationInfoAndNewLine(ops);
4836 return success();
4837}
4838
4839LogicalResult StmtEmitter::visitSV(FCloseOp op) {
4840 if (hasSVAttributes(op))
4841 emitError(op, "SV attributes emission is unimplemented for the op");
4842
4843 startStatement();
4844 SmallPtrSet<Operation *, 8> ops;
4845 ops.insert(op);
4846
4847 ps.addCallback({op, true});
4848 ps << "$fclose(";
4849 ps.scopedBox(PP::ibox0, [&]() { emitExpression(op.getFd(), ops); });
4850 ps << ");";
4851 ps.addCallback({op, false});
4852 emitLocationInfoAndNewLine(ops);
4853 return success();
4854}
4855
4856template <typename OpTy, typename EmitPrefixFn>
4857LogicalResult StmtEmitter::emitFormattedWriteLikeOp(OpTy op, StringRef callee,
4858 StringRef formatString,
4859 ValueRange substitutions,
4860 EmitPrefixFn emitPrefix) {
4861 if (hasSVAttributes(op))
4862 emitError(op, "SV attributes emission is unimplemented for the op");
4863
4864 startStatement();
4865 SmallPtrSet<Operation *, 8> ops;
4866 ops.insert(op);
4867
4868 ps.addCallback({op, true});
4869 ps << callee;
4870 ps.scopedBox(PP::ibox0, [&]() {
4871 emitPrefix(ops);
4872 ps.writeQuotedEscaped(formatString);
4873 // TODO: if any of these breaks, it'd be "nice" to break
4874 // after the comma, instead of:
4875 // $fwrite(5, "...", a + b,
4876 // longexpr_goes
4877 // + here, c);
4878 // (without forcing breaking between all elements, like braced list)
4879 for (auto operand : substitutions) {
4880 ps << "," << PP::space;
4881 emitExpression(operand, ops);
4882 }
4883 ps << ");";
4884 });
4885 ps.addCallback({op, false});
4886 emitLocationInfoAndNewLine(ops);
4887 return success();
4888}
4889
4890LogicalResult StmtEmitter::visitSV(WriteOp op) {
4891 return emitFormattedWriteLikeOp(op, "$write(", op.getFormatString(),
4892 op.getSubstitutions(),
4893 [&](SmallPtrSetImpl<Operation *> &) {});
4894}
4895
4896LogicalResult StmtEmitter::visitSV(FWriteOp op) {
4897 return emitFormattedWriteLikeOp(op, "$fwrite(", op.getFormatString(),
4898 op.getSubstitutions(),
4899 [&](SmallPtrSetImpl<Operation *> &ops) {
4900 emitExpression(op.getFd(), ops);
4901 ps << "," << PP::space;
4902 });
4903}
4904
4905LogicalResult StmtEmitter::visitSV(VerbatimOp op) {
4906 if (hasSVAttributes(op))
4907 emitError(op, "SV attributes emission is unimplemented for the op");
4908
4909 startStatement();
4910 SmallPtrSet<Operation *, 8> ops;
4911 ops.insert(op);
4912 ps << PP::neverbox;
4913
4914 // Drop an extraneous \n off the end of the string if present.
4915 StringRef string = op.getFormatString();
4916 if (string.ends_with("\n"))
4917 string = string.drop_back();
4918
4919 // Emit each \n separated piece of the string with each piece properly
4920 // indented. The convention is to not emit the \n so
4921 // emitLocationInfoAndNewLine can do that for the last line.
4922 bool isFirst = true;
4923
4924 // Emit each line of the string at a time.
4925 while (!string.empty()) {
4926 auto lhsRhs = string.split('\n');
4927 if (isFirst)
4928 isFirst = false;
4929 else {
4930 ps << PP::end << PP::newline << PP::neverbox;
4931 }
4932
4933 // Emit each chunk of the line.
4934 emitTextWithSubstitutions(
4935 ps, lhsRhs.first, op,
4936 [&](Value operand) { emitExpression(operand, ops); }, op.getSymbols());
4937 string = lhsRhs.second;
4938 }
4939
4940 ps << PP::end;
4941
4942 emitLocationInfoAndNewLine(ops);
4943 return success();
4944}
4945
4946// Emit macro as a statement.
4947LogicalResult StmtEmitter::visitSV(MacroRefOp op) {
4948 if (hasSVAttributes(op)) {
4949 emitError(op, "SV attributes emission is unimplemented for the op");
4950 return failure();
4951 }
4952 startStatement();
4953 SmallPtrSet<Operation *, 8> ops;
4954 ops.insert(op);
4955 ps << PP::neverbox;
4956
4957 // Use the specified name or the symbol name as appropriate.
4958 auto macroOp = op.getReferencedMacro(&state.symbolCache);
4959 assert(macroOp && "Invalid IR");
4960 StringRef name =
4961 macroOp.getVerilogName() ? *macroOp.getVerilogName() : macroOp.getName();
4962 ps << "`" << PPExtString(name);
4963 if (!op.getInputs().empty()) {
4964 ps << "(";
4965 llvm::interleaveComma(op.getInputs(), ps, [&](Value val) {
4966 emitExpression(val, ops, LowestPrecedence,
4967 /*isAssignmentLikeContext=*/false);
4968 });
4969 ps << ")";
4970 }
4971 ps << PP::end;
4972 emitLocationInfoAndNewLine(ops);
4973 return success();
4974}
4975
4976/// Emit one of the simulation control tasks `$stop`, `$finish`, or `$exit`.
4977LogicalResult
4978StmtEmitter::emitSimulationControlTask(Operation *op, PPExtString taskName,
4979 std::optional<unsigned> verbosity) {
4980 if (hasSVAttributes(op))
4981 emitError(op, "SV attributes emission is unimplemented for the op");
4982
4983 startStatement();
4984 SmallPtrSet<Operation *, 8> ops;
4985 ops.insert(op);
4986 ps.addCallback({op, true});
4987 ps << taskName;
4988 if (verbosity && *verbosity != 1) {
4989 ps << "(";
4990 ps.addAsString(*verbosity);
4991 ps << ")";
4992 }
4993 ps << ";";
4994 ps.addCallback({op, false});
4995 emitLocationInfoAndNewLine(ops);
4996 return success();
4997}
4998
4999LogicalResult StmtEmitter::visitSV(StopOp op) {
5000 return emitSimulationControlTask(op, PPExtString("$stop"), op.getVerbosity());
5001}
5002
5003LogicalResult StmtEmitter::visitSV(FinishOp op) {
5004 return emitSimulationControlTask(op, PPExtString("$finish"),
5005 op.getVerbosity());
5006}
5007
5008LogicalResult StmtEmitter::visitSV(ExitOp op) {
5009 return emitSimulationControlTask(op, PPExtString("$exit"), {});
5010}
5011
5012/// Emit one of the severity message tasks `$fatal`, `$error`, `$warning`, or
5013/// `$info`.
5014LogicalResult
5015StmtEmitter::emitSeverityMessageTask(Operation *op, PPExtString taskName,
5016 std::optional<unsigned> verbosity,
5017 StringAttr message, ValueRange operands) {
5018 if (hasSVAttributes(op))
5019 emitError(op, "SV attributes emission is unimplemented for the op");
5020
5021 startStatement();
5022 SmallPtrSet<Operation *, 8> ops;
5023 ops.insert(op);
5024 ps.addCallback({op, true});
5025 ps << taskName;
5026
5027 // In case we have a message to print, or the operation has an optional
5028 // verbosity and that verbosity is present, print the parenthesized parameter
5029 // list.
5030 if ((verbosity && *verbosity != 1) || message) {
5031 ps << "(";
5032 ps.scopedBox(PP::ibox0, [&]() {
5033 // If the operation takes a verbosity, print it if it is set, or print the
5034 // default "1".
5035 if (verbosity)
5036 ps.addAsString(*verbosity);
5037
5038 // Print the message and interpolation operands if present.
5039 if (message) {
5040 if (verbosity)
5041 ps << "," << PP::space;
5042 ps.writeQuotedEscaped(message.getValue());
5043 // TODO: good comma/wrapping behavior as elsewhere.
5044 for (auto operand : operands) {
5045 ps << "," << PP::space;
5046 emitExpression(operand, ops);
5047 }
5048 }
5049
5050 ps << ")";
5051 });
5052 }
5053
5054 ps << ";";
5055 ps.addCallback({op, false});
5056 emitLocationInfoAndNewLine(ops);
5057 return success();
5058}
5059
5060LogicalResult StmtEmitter::visitSV(FatalProceduralOp op) {
5061 return emitFatalMessageOp(op);
5062}
5063
5064LogicalResult StmtEmitter::visitSV(FatalOp op) {
5065 return emitFatalMessageOp(op);
5066}
5067
5068LogicalResult StmtEmitter::visitSV(ErrorProceduralOp op) {
5069 return emitNonfatalMessageOp(op, "$error");
5070}
5071
5072LogicalResult StmtEmitter::visitSV(WarningProceduralOp op) {
5073 return emitNonfatalMessageOp(op, "$warning");
5074}
5075
5076LogicalResult StmtEmitter::visitSV(InfoProceduralOp op) {
5077 return emitNonfatalMessageOp(op, "$info");
5078}
5079
5080LogicalResult StmtEmitter::visitSV(ErrorOp op) {
5081 return emitNonfatalMessageOp(op, "$error");
5082}
5083
5084LogicalResult StmtEmitter::visitSV(WarningOp op) {
5085 return emitNonfatalMessageOp(op, "$warning");
5086}
5087
5088LogicalResult StmtEmitter::visitSV(InfoOp op) {
5089 return emitNonfatalMessageOp(op, "$info");
5090}
5091
5092LogicalResult StmtEmitter::visitSV(ReadMemOp op) {
5093 SmallPtrSet<Operation *, 8> ops({op});
5094
5095 startStatement();
5096 ps.addCallback({op, true});
5097 ps << "$readmem";
5098 switch (op.getBaseAttr().getValue()) {
5099 case MemBaseTypeAttr::MemBaseBin:
5100 ps << "b";
5101 break;
5102 case MemBaseTypeAttr::MemBaseHex:
5103 ps << "h";
5104 break;
5105 }
5106 ps << "(";
5107 ps.scopedBox(PP::ibox0, [&]() {
5108 ps.writeQuotedEscaped(op.getFilename());
5109 ps << "," << PP::space;
5110 emitExpression(op.getDest(), ops);
5111 });
5112
5113 ps << ");";
5114 ps.addCallback({op, false});
5115 emitLocationInfoAndNewLine(ops);
5116 return success();
5117}
5118
5119LogicalResult StmtEmitter::visitSV(GenerateOp op) {
5120 emitSVAttributes(op);
5121 // TODO: location info?
5122 startStatement();
5123 ps.addCallback({op, true});
5124 ps << "generate" << PP::newline;
5125 ps << "begin: " << PPExtString(getSymOpName(op));
5126 setPendingNewline();
5127 emitStatementBlock(op.getBody().getBlocks().front());
5128 startStatement();
5129 ps << "end: " << PPExtString(getSymOpName(op)) << PP::newline;
5130 ps << "endgenerate";
5131 ps.addCallback({op, false});
5132 setPendingNewline();
5133 return success();
5134}
5135
5136LogicalResult StmtEmitter::visitSV(GenerateCaseOp op) {
5137 emitSVAttributes(op);
5138 // TODO: location info?
5139 startStatement();
5140 ps.addCallback({op, true});
5141 ps << "case (";
5142 ps.invokeWithStringOS([&](auto &os) {
5143 emitter.printParamValue(
5144 op.getCond(), os, VerilogPrecedence::Selection,
5145 [&]() { return op->emitOpError("invalid case parameter"); });
5146 });
5147 ps << ")";
5148 setPendingNewline();
5149
5150 // Ensure that all of the per-case arrays are the same length.
5151 ArrayAttr patterns = op.getCasePatterns();
5152 ArrayAttr caseNames = op.getCaseNames();
5153 MutableArrayRef<Region> regions = op.getCaseRegions();
5154 assert(patterns.size() == regions.size());
5155 assert(patterns.size() == caseNames.size());
5156
5157 // TODO: We'll probably need to store the legalized names somewhere for
5158 // `verbose` formatting. Set up the infra for storing names recursively. Just
5159 // store this locally for now.
5160 llvm::StringMap<size_t> nextGenIds;
5161 ps.scopedBox(PP::bbox2, [&]() {
5162 // Emit each case.
5163 for (size_t i = 0, e = patterns.size(); i < e; ++i) {
5164 auto &region = regions[i];
5165 assert(region.hasOneBlock());
5166 Attribute patternAttr = patterns[i];
5167
5168 startStatement();
5169 if (!isa<mlir::TypedAttr>(patternAttr))
5170 ps << "default";
5171 else
5172 ps.invokeWithStringOS([&](auto &os) {
5173 emitter.printParamValue(
5174 patternAttr, os, VerilogPrecedence::LowestPrecedence,
5175 [&]() { return op->emitOpError("invalid case value"); });
5176 });
5177
5178 StringRef legalName =
5179 legalizeName(cast<StringAttr>(caseNames[i]).getValue(), nextGenIds,
5180 options.caseInsensitiveKeywords);
5181 ps << ": begin: " << PPExtString(legalName);
5182 setPendingNewline();
5183 emitStatementBlock(region.getBlocks().front());
5184 startStatement();
5185 ps << "end: " << PPExtString(legalName);
5186 setPendingNewline();
5187 }
5188 });
5189
5190 startStatement();
5191 ps << "endcase";
5192 ps.addCallback({op, false});
5193 setPendingNewline();
5194 return success();
5195}
5196
5197LogicalResult StmtEmitter::visitSV(GenerateForOp op) {
5198 emitSVAttributes(op);
5199 llvm::SmallPtrSet<Operation *, 8> ops;
5200 ps.addCallback({op, true});
5201 startStatement();
5202
5203 StringRef inductionVarName = op->getAttrOfType<StringAttr>("hw.verilogName");
5204
5205 ps << "for (";
5206 ps.scopedBox(PP::cbox0, [&]() {
5207 emitAssignLike(
5208 [&]() { ps << "genvar" << PP::nbsp << PPExtString(inductionVarName); },
5209 [&]() {
5210 ps.invokeWithStringOS([&](auto &os) {
5211 emitter.printParamValue(
5212 op.getLowerBound(), os, VerilogPrecedence::LowestPrecedence,
5213 [&]() { return op->emitOpError("invalid lower bound"); });
5214 });
5215 },
5216 PPExtString("="));
5217 ps << PP::space;
5218
5219 emitAssignLike(
5220 [&]() { ps << PPExtString(inductionVarName); },
5221 [&]() {
5222 ps.invokeWithStringOS([&](auto &os) {
5223 emitter.printParamValue(
5224 op.getUpperBound(), os, VerilogPrecedence::LowestPrecedence,
5225 [&]() { return op->emitOpError("invalid upper bound"); });
5226 });
5227 },
5228 PPExtString("<"));
5229 ps << PP::space;
5230
5231 ps << PPExtString(inductionVarName) << PP::nbsp << "+=" << PP::nbsp;
5232 ps.invokeWithStringOS([&](auto &os) {
5233 emitter.printParamValue(
5234 op.getStep(), os, VerilogPrecedence::LowestPrecedence,
5235 [&]() { return op->emitOpError("invalid step"); });
5236 });
5237 ps << ") begin";
5238 StringRef blockName = op.getGenBlockName();
5239 if (!blockName.empty())
5240 ps << " : " << PPExtString(blockName);
5241 });
5242
5243 ps << PP::neverbreak;
5244 setPendingNewline();
5245 emitStatementBlock(op.getBody().getBlocks().front());
5246 startStatement();
5247 ps << "end";
5248 if (StringRef blockName = op.getGenBlockName(); !blockName.empty())
5249 ps << " // " << PPExtString(blockName);
5250 ps.addCallback({op, false});
5251 setPendingNewline();
5252 return success();
5253}
5254
5255LogicalResult StmtEmitter::visitSV(ForOp op) {
5256 emitSVAttributes(op);
5257 llvm::SmallPtrSet<Operation *, 8> ops;
5258 ps.addCallback({op, true});
5259 startStatement();
5260 auto inductionVarName = op->getAttrOfType<StringAttr>("hw.verilogName");
5261 ps << "for (";
5262 // Emit statements on same line if possible, or put each on own line.
5263 ps.scopedBox(PP::cbox0, [&]() {
5264 // Emit initialization assignment.
5265 emitAssignLike(
5266 [&]() {
5267 ps << "logic" << PP::nbsp;
5268 ps.invokeWithStringOS([&](auto &os) {
5269 emitter.emitTypeDims(op.getInductionVar().getType(), op.getLoc(),
5270 os);
5271 });
5272 ps << PP::nbsp << PPExtString(inductionVarName);
5273 },
5274 [&]() { emitExpression(op.getLowerBound(), ops); }, PPExtString("="));
5275 // Break between statements.
5276 ps << PP::space;
5277
5278 // Emit bounds-check statement.
5279 emitAssignLike([&]() { ps << PPExtString(inductionVarName); },
5280 [&]() { emitExpression(op.getUpperBound(), ops); },
5281 PPExtString("<"));
5282 // Break between statements.
5283 ps << PP::space;
5284
5285 // Emit update statement and trailing syntax.
5286 emitAssignLike([&]() { ps << PPExtString(inductionVarName); },
5287 [&]() { emitExpression(op.getStep(), ops); },
5288 PPExtString("+="), PPExtString(") begin"));
5289 });
5290 // Don't break for because of newline.
5291 ps << PP::neverbreak;
5292 setPendingNewline();
5293 emitStatementBlock(op.getBody().getBlocks().front());
5294 startStatement();
5295 ps << "end";
5296 ps.addCallback({op, false});
5297 emitLocationInfoAndNewLine(ops);
5298 return success();
5299}
5300
5301/// Emit the `<label>:` portion of a verification operation.
5302void StmtEmitter::emitAssertionLabel(Operation *op) {
5303 if (auto label = op->getAttrOfType<StringAttr>("hw.verilogName"))
5304 ps << PPExtString(label) << ":" << PP::space;
5305}
5306
5307/// Emit the optional ` else $error(...)` portion of an immediate or concurrent
5308/// verification operation.
5309void StmtEmitter::emitAssertionMessage(StringAttr message, ValueRange args,
5310 SmallPtrSetImpl<Operation *> &ops,
5311 bool isConcurrent = false) {
5312 if (!message)
5313 return;
5314 ps << PP::space << "else" << PP::nbsp << "$error(";
5315 ps.scopedBox(PP::ibox0, [&]() {
5316 ps.writeQuotedEscaped(message.getValue());
5317 // TODO: box, break/wrap behavior!
5318 for (auto arg : args) {
5319 ps << "," << PP::space;
5320 emitExpression(arg, ops);
5321 }
5322 ps << ")";
5323 });
5324}
5325
5326template <typename Op>
5327LogicalResult StmtEmitter::emitImmediateAssertion(Op op, PPExtString opName) {
5328 if (hasSVAttributes(op))
5329 emitError(op, "SV attributes emission is unimplemented for the op");
5330
5331 startStatement();
5332 SmallPtrSet<Operation *, 8> ops;
5333 ops.insert(op);
5334 ps.addCallback({op, true});
5335 ps.scopedBox(PP::ibox2, [&]() {
5336 emitAssertionLabel(op);
5337 ps.scopedBox(PP::cbox0, [&]() {
5338 ps << opName;
5339 switch (op.getDefer()) {
5340 case DeferAssert::Immediate:
5341 break;
5342 case DeferAssert::Observed:
5343 ps << " #0 ";
5344 break;
5345 case DeferAssert::Final:
5346 ps << " final ";
5347 break;
5348 }
5349 ps << "(";
5350 ps.scopedBox(PP::ibox0, [&]() {
5351 emitExpression(op.getExpression(), ops);
5352 ps << ")";
5353 });
5354 emitAssertionMessage(op.getMessageAttr(), op.getSubstitutions(), ops);
5355 ps << ";";
5356 });
5357 });
5358 ps.addCallback({op, false});
5359 emitLocationInfoAndNewLine(ops);
5360 return success();
5361}
5362
5363LogicalResult StmtEmitter::visitSV(AssertOp op) {
5364 return emitImmediateAssertion(op, PPExtString("assert"));
5365}
5366
5367LogicalResult StmtEmitter::visitSV(AssumeOp op) {
5368 return emitImmediateAssertion(op, PPExtString("assume"));
5369}
5370
5371LogicalResult StmtEmitter::visitSV(CoverOp op) {
5372 return emitImmediateAssertion(op, PPExtString("cover"));
5373}
5374
5375template <typename Op>
5376LogicalResult StmtEmitter::emitConcurrentAssertion(Op op, PPExtString opName) {
5377 if (hasSVAttributes(op))
5378 emitError(op, "SV attributes emission is unimplemented for the op");
5379
5380 startStatement();
5381 SmallPtrSet<Operation *, 8> ops;
5382 ops.insert(op);
5383 ps.addCallback({op, true});
5384 ps.scopedBox(PP::ibox2, [&]() {
5385 emitAssertionLabel(op);
5386 ps.scopedBox(PP::cbox0, [&]() {
5387 ps << opName << PP::nbsp << "property (";
5388 ps.scopedBox(PP::ibox0, [&]() {
5389 ps << "@(" << PPExtString(stringifyEventControl(op.getEvent()))
5390 << PP::nbsp;
5391 emitExpression(op.getClock(), ops);
5392 ps << ")" << PP::space;
5393 emitExpression(op.getProperty(), ops);
5394 ps << ")";
5395 });
5396 emitAssertionMessage(op.getMessageAttr(), op.getSubstitutions(), ops,
5397 true);
5398 ps << ";";
5399 });
5400 });
5401 ps.addCallback({op, false});
5402 emitLocationInfoAndNewLine(ops);
5403 return success();
5404}
5405
5406LogicalResult StmtEmitter::visitSV(AssertConcurrentOp op) {
5407 return emitConcurrentAssertion(op, PPExtString("assert"));
5408}
5409
5410LogicalResult StmtEmitter::visitSV(AssumeConcurrentOp op) {
5411 return emitConcurrentAssertion(op, PPExtString("assume"));
5412}
5413
5414LogicalResult StmtEmitter::visitSV(CoverConcurrentOp op) {
5415 return emitConcurrentAssertion(op, PPExtString("cover"));
5416}
5417
5418// Property assertions are what gets emitted if the user want to combine
5419// concurrent assertions with a disable signal, a clock and an ltl property.
5420template <typename Op>
5421LogicalResult StmtEmitter::emitPropertyAssertion(Op op, PPExtString opName) {
5422 if (hasSVAttributes(op))
5423 emitError(op, "SV attributes emission is unimplemented for the op");
5424
5425 // If we are inside a procedural region we have the option of emitting either
5426 // an `assert` or `assert property`. If we are in a non-procedural region,
5427 // e.g., the body of a module, we have to use the concurrent form `assert
5428 // property` (which also supports plain booleans).
5429 //
5430 // See IEEE 1800-2017 section 16.14.5 "Using concurrent assertion statements
5431 // outside procedural code" and 16.14.6 "Embedding concurrent assertions in
5432 // procedural code".
5433 Operation *parent = op->getParentOp();
5434 Value property = op.getProperty();
5435 bool isTemporal = !property.getType().isSignlessInteger(1);
5436 bool isProcedural = parent->hasTrait<ProceduralRegion>();
5437 bool emitAsImmediate = !isTemporal && isProcedural;
5438
5439 startStatement();
5440 SmallPtrSet<Operation *, 8> ops;
5441 ops.insert(op);
5442 ps.addCallback({op, true});
5443 ps.scopedBox(PP::ibox2, [&]() {
5444 // Check for a label and emit it if necessary
5445 emitAssertionLabel(op);
5446 // Emit the assertion
5447 ps.scopedBox(PP::cbox0, [&]() {
5448 if (emitAsImmediate)
5449 ps << opName << "(";
5450 else
5451 ps << opName << PP::nbsp << "property" << PP::nbsp << "(";
5452 // Event only exists if the clock exists
5453 Value clock = op.getClock();
5454 auto event = op.getEvent();
5455 if (clock)
5456 ps.scopedBox(PP::ibox2, [&]() {
5457 PropertyEmitter(emitter, ops)
5458 .emitAssertPropertyBody(property, *event, clock, op.getDisable());
5459 });
5460 else
5461 ps.scopedBox(PP::ibox2, [&]() {
5462 PropertyEmitter(emitter, ops)
5463 .emitAssertPropertyBody(property, op.getDisable());
5464 });
5465 ps << ");";
5466 });
5467 });
5468 ps.addCallback({op, false});
5469 emitLocationInfoAndNewLine(ops);
5470 return success();
5471}
5472
5473LogicalResult StmtEmitter::visitSV(AssertPropertyOp op) {
5474 return emitPropertyAssertion(op, PPExtString("assert"));
5475}
5476
5477LogicalResult StmtEmitter::visitSV(AssumePropertyOp op) {
5478 return emitPropertyAssertion(op, PPExtString("assume"));
5479}
5480
5481LogicalResult StmtEmitter::visitSV(CoverPropertyOp op) {
5482 return emitPropertyAssertion(op, PPExtString("cover"));
5483}
5484
5485LogicalResult StmtEmitter::emitIfDef(Operation *op, MacroIdentAttr cond) {
5486 if (hasSVAttributes(op))
5487 emitError(op, "SV attributes emission is unimplemented for the op");
5488
5489 auto ident = PPExtString(
5490 cast<MacroDeclOp>(state.symbolCache.getDefinition(cond.getIdent()))
5491 .getMacroIdentifier());
5492
5493 startStatement();
5494 bool hasEmptyThen = op->getRegion(0).front().empty();
5495 if (hasEmptyThen)
5496 ps << "`ifndef " << ident;
5497 else
5498 ps << "`ifdef " << ident;
5499
5500 SmallPtrSet<Operation *, 8> ops;
5501 ops.insert(op);
5502 emitLocationInfoAndNewLine(ops);
5503
5504 if (!hasEmptyThen)
5505 emitStatementBlock(op->getRegion(0).front());
5506
5507 if (!op->getRegion(1).empty()) {
5508 if (!hasEmptyThen) {
5509 startStatement();
5510 ps << "`else // " << ident;
5511 setPendingNewline();
5512 }
5513 emitStatementBlock(op->getRegion(1).front());
5514 }
5515 startStatement();
5516 ps << "`endif // ";
5517 if (hasEmptyThen)
5518 ps << "not def ";
5519 ps << ident;
5520 setPendingNewline();
5521 return success();
5522}
5523
5524/// Emit the body of a control flow statement that is surrounded by begin/end
5525/// markers if non-singular. If the control flow construct is multi-line and
5526/// if multiLineComment is non-null, the string is included in a comment after
5527/// the 'end' to make it easier to associate.
5528void StmtEmitter::emitBlockAsStatement(
5529 Block *block, const SmallPtrSetImpl<Operation *> &locationOps,
5530 StringRef multiLineComment) {
5531
5532 // Determine if we need begin/end by scanning the block.
5533 auto count = countStatements(*block);
5534 auto needsBeginEnd =
5535 count != BlockStatementCount::One || state.options.alwaysEmitBeginEnd;
5536 if (needsBeginEnd)
5537 ps << " begin";
5538 emitLocationInfoAndNewLine(locationOps);
5539
5540 if (count != BlockStatementCount::Zero)
5541 emitStatementBlock(*block);
5542
5543 if (needsBeginEnd) {
5544 startStatement();
5545 ps << "end";
5546 // Emit comment if there's an 'end', regardless of line count.
5547 if (!multiLineComment.empty())
5548 ps << " // " << multiLineComment;
5549 setPendingNewline();
5550 }
5551}
5552
5553LogicalResult StmtEmitter::visitSV(OrderedOutputOp ooop) {
5554 // Emit the body.
5555 for (auto &op : ooop.getBody().front())
5556 emitStatement(&op);
5557 return success();
5558}
5559
5560LogicalResult StmtEmitter::visitSV(IfOp op) {
5561 SmallPtrSet<Operation *, 8> ops;
5562
5563 auto ifcondBox = PP::ibox2;
5564
5565 emitSVAttributes(op);
5566 startStatement();
5567 ps.addCallback({op, true});
5568 ps << "if (" << ifcondBox;
5569
5570 // In the loop, emit an if statement assuming the keyword introducing
5571 // it (either "if (" or "else if (") was printed already.
5572 IfOp ifOp = op;
5573 for (;;) {
5574 ops.clear();
5575 ops.insert(ifOp);
5576
5577 // Emit the condition and the then block.
5578 emitExpression(ifOp.getCond(), ops);
5579 ps << PP::end << ")";
5580 emitBlockAsStatement(ifOp.getThenBlock(), ops);
5581
5582 if (!ifOp.hasElse())
5583 break;
5584
5585 startStatement();
5586 Block *elseBlock = ifOp.getElseBlock();
5587 auto nestedElseIfOp = findNestedElseIf(elseBlock);
5588 if (!nestedElseIfOp) {
5589 // The else block does not contain an if-else that can be flattened.
5590 ops.clear();
5591 ops.insert(ifOp);
5592 ps << "else";
5593 emitBlockAsStatement(elseBlock, ops);
5594 break;
5595 }
5596
5597 // Introduce the 'else if', and iteratively continue unfolding any if-else
5598 // statements inside of it.
5599 ifOp = nestedElseIfOp;
5600 ps << "else if (" << ifcondBox;
5601 }
5602 ps.addCallback({op, false});
5603
5604 return success();
5605}
5606
5607LogicalResult StmtEmitter::visitSV(AlwaysOp op) {
5608 emitSVAttributes(op);
5609 SmallPtrSet<Operation *, 8> ops;
5610 ops.insert(op);
5611 startStatement();
5612
5613 auto printEvent = [&](AlwaysOp::Condition cond) {
5614 ps << PPExtString(stringifyEventControl(cond.event)) << PP::nbsp;
5615 ps.scopedBox(PP::cbox0, [&]() { emitExpression(cond.value, ops); });
5616 };
5617 ps.addCallback({op, true});
5618
5619 switch (op.getNumConditions()) {
5620 case 0:
5621 ps << "always @*";
5622 break;
5623 case 1:
5624 ps << "always @(";
5625 printEvent(op.getCondition(0));
5626 ps << ")";
5627 break;
5628 default:
5629 ps << "always @(";
5630 ps.scopedBox(PP::cbox0, [&]() {
5631 printEvent(op.getCondition(0));
5632 for (size_t i = 1, e = op.getNumConditions(); i != e; ++i) {
5633 ps << PP::space << "or" << PP::space;
5634 printEvent(op.getCondition(i));
5635 }
5636 ps << ")";
5637 });
5638 break;
5639 }
5640
5641 // Build the comment string, leave out the signal expressions (since they
5642 // can be large).
5643 std::string comment;
5644 if (op.getNumConditions() == 0) {
5645 comment = "always @*";
5646 } else {
5647 comment = "always @(";
5648 llvm::interleave(
5649 op.getEvents(),
5650 [&](Attribute eventAttr) {
5651 auto event = sv::EventControl(cast<IntegerAttr>(eventAttr).getInt());
5652 comment += stringifyEventControl(event);
5653 },
5654 [&]() { comment += ", "; });
5655 comment += ')';
5656 }
5657
5658 emitBlockAsStatement(op.getBodyBlock(), ops, comment);
5659 ps.addCallback({op, false});
5660 return success();
5661}
5662
5663LogicalResult StmtEmitter::visitSV(AlwaysCombOp op) {
5664 emitSVAttributes(op);
5665 SmallPtrSet<Operation *, 8> ops;
5666 ops.insert(op);
5667 startStatement();
5668
5669 ps.addCallback({op, true});
5670 StringRef opString = "always_comb";
5671 if (state.options.noAlwaysComb)
5672 opString = "always @(*)";
5673
5674 ps << PPExtString(opString);
5675 emitBlockAsStatement(op.getBodyBlock(), ops, opString);
5676 ps.addCallback({op, false});
5677 return success();
5678}
5679
5680LogicalResult StmtEmitter::visitSV(AlwaysFFOp op) {
5681 emitSVAttributes(op);
5682
5683 SmallPtrSet<Operation *, 8> ops;
5684 ops.insert(op);
5685 startStatement();
5686
5687 ps.addCallback({op, true});
5688 ps << "always_ff @(";
5689 ps.scopedBox(PP::cbox0, [&]() {
5690 ps << PPExtString(stringifyEventControl(op.getClockEdge())) << PP::nbsp;
5691 emitExpression(op.getClock(), ops);
5692 if (op.getResetStyle() == ResetType::AsyncReset) {
5693 ps << PP::nbsp << "or" << PP::space
5694 << PPExtString(stringifyEventControl(*op.getResetEdge())) << PP::nbsp;
5695 emitExpression(op.getReset(), ops);
5696 }
5697 ps << ")";
5698 });
5699
5700 // Build the comment string, leave out the signal expressions (since they
5701 // can be large).
5702 std::string comment;
5703 comment += "always_ff @(";
5704 comment += stringifyEventControl(op.getClockEdge());
5705 if (op.getResetStyle() == ResetType::AsyncReset) {
5706 comment += " or ";
5707 comment += stringifyEventControl(*op.getResetEdge());
5708 }
5709 comment += ')';
5710
5711 if (op.getResetStyle() == ResetType::NoReset)
5712 emitBlockAsStatement(op.getBodyBlock(), ops, comment);
5713 else {
5714 ps << " begin";
5715 emitLocationInfoAndNewLine(ops);
5716 ps.scopedBox(PP::bbox2, [&]() {
5717 startStatement();
5718 ps << "if (";
5719 // TODO: group, like normal 'if'.
5720 // Negative edge async resets need to invert the reset condition. This
5721 // is noted in the op description.
5722 if (op.getResetStyle() == ResetType::AsyncReset &&
5723 *op.getResetEdge() == sv::EventControl::AtNegEdge)
5724 ps << "!";
5725 emitExpression(op.getReset(), ops);
5726 ps << ")";
5727 emitBlockAsStatement(op.getResetBlock(), ops);
5728 startStatement();
5729 ps << "else";
5730 emitBlockAsStatement(op.getBodyBlock(), ops);
5731 });
5732
5733 startStatement();
5734 ps << "end";
5735 ps << " // " << comment;
5736 setPendingNewline();
5737 }
5738 ps.addCallback({op, false});
5739 return success();
5740}
5741
5742LogicalResult StmtEmitter::visitSV(InitialOp op) {
5743 emitSVAttributes(op);
5744 SmallPtrSet<Operation *, 8> ops;
5745 ops.insert(op);
5746 startStatement();
5747 ps.addCallback({op, true});
5748 ps << "initial";
5749 emitBlockAsStatement(op.getBodyBlock(), ops, "initial");
5750 ps.addCallback({op, false});
5751 return success();
5752}
5753
5754LogicalResult StmtEmitter::visitSV(CaseOp op) {
5755 emitSVAttributes(op);
5756 SmallPtrSet<Operation *, 8> ops, emptyOps;
5757 ops.insert(op);
5758 startStatement();
5759 ps.addCallback({op, true});
5760 if (op.getValidationQualifier() !=
5761 ValidationQualifierTypeEnum::ValidationQualifierPlain)
5762 ps << PPExtString(circt::sv::stringifyValidationQualifierTypeEnum(
5763 op.getValidationQualifier()))
5764 << PP::nbsp;
5765 const char *opname = nullptr;
5766 switch (op.getCaseStyle()) {
5767 case CaseStmtType::CaseStmt:
5768 opname = "case";
5769 break;
5770 case CaseStmtType::CaseXStmt:
5771 opname = "casex";
5772 break;
5773 case CaseStmtType::CaseZStmt:
5774 opname = "casez";
5775 break;
5776 }
5777 ps << opname << " (";
5778 ps.scopedBox(PP::ibox0, [&]() {
5779 emitExpression(op.getCond(), ops);
5780 ps << ")";
5781 });
5782 emitLocationInfoAndNewLine(ops);
5783
5784 size_t caseValueIndex = 0;
5785 ps.scopedBox(PP::bbox2, [&]() {
5786 for (auto &caseInfo : op.getCases()) {
5787 startStatement();
5788 auto &pattern = caseInfo.pattern;
5789
5790 llvm::TypeSwitch<CasePattern *>(pattern.get())
5791 .Case<CaseBitPattern>([&](auto bitPattern) {
5792 // TODO: We could emit in hex if/when the size is a multiple of
5793 // 4 and there are no x's crossing nibble boundaries.
5794 ps.invokeWithStringOS([&](auto &os) {
5795 os << bitPattern->getWidth() << "'b";
5796 for (size_t bit = 0, e = bitPattern->getWidth(); bit != e; ++bit)
5797 os << getLetter(bitPattern->getBit(e - bit - 1));
5798 });
5799 })
5800 .Case<CaseEnumPattern>([&](auto enumPattern) {
5801 ps << PPExtString(emitter.fieldNameResolver.getEnumFieldName(
5802 cast<hw::EnumFieldAttr>(enumPattern->attr())));
5803 })
5804 .Case<CaseExprPattern>([&](auto) {
5805 emitExpression(op.getCaseValues()[caseValueIndex++], ops);
5806 })
5807 .Case<CaseDefaultPattern>([&](auto) { ps << "default"; })
5808 .Default([&](auto) { assert(false && "unhandled case pattern"); });
5809
5810 ps << ":";
5811 emitBlockAsStatement(caseInfo.block, emptyOps);
5812 }
5813 });
5814
5815 startStatement();
5816 ps << "endcase";
5817 ps.addCallback({op, false});
5818 emitLocationInfoAndNewLine(ops);
5819 return success();
5820}
5821
5822LogicalResult StmtEmitter::visitStmt(InstanceOp op) {
5823 bool doNotPrint = op.getDoNotPrint();
5824 if (doNotPrint && !state.options.emitBindComments)
5825 return success();
5826
5827 // Emit SV attributes if the op is not emitted as a bind statement.
5828 if (!doNotPrint)
5829 emitSVAttributes(op);
5830 startStatement();
5831 ps.addCallback({op, true});
5832 if (doNotPrint) {
5833 ps << PP::ibox2
5834 << "/* This instance is elsewhere emitted as a bind statement."
5835 << PP::newline;
5836 if (hasSVAttributes(op))
5837 op->emitWarning() << "is emitted as a bind statement but has SV "
5838 "attributes. The attributes will not be emitted.";
5839 }
5840
5841 SmallPtrSet<Operation *, 8> ops;
5842 ops.insert(op);
5843
5844 // Use the specified name or the symbol name as appropriate.
5845 auto *moduleOp =
5846 state.symbolCache.getDefinition(op.getReferencedModuleNameAttr());
5847 assert(moduleOp && "Invalid IR");
5848 ps << PPExtString(getVerilogModuleName(moduleOp));
5849
5850 // If this is a parameterized module, then emit the parameters.
5851 if (!op.getParameters().empty()) {
5852 // All the parameters may be defaulted -- don't print out an empty list if
5853 // so.
5854 bool printed = false;
5855 for (auto params :
5856 llvm::zip(op.getParameters(),
5857 moduleOp->getAttrOfType<ArrayAttr>("parameters"))) {
5858 auto param = cast<ParamDeclAttr>(std::get<0>(params));
5859 auto modParam = cast<ParamDeclAttr>(std::get<1>(params));
5860 // Ignore values that line up with their default.
5861 if (param.getValue() == modParam.getValue())
5862 continue;
5863
5864 // Handle # if this is the first parameter we're printing.
5865 if (!printed) {
5866 ps << " #(" << PP::bbox2 << PP::newline;
5867 printed = true;
5868 } else {
5869 ps << "," << PP::newline;
5870 }
5871 ps << ".";
5872 ps << PPExtString(
5873 state.globalNames.getParameterVerilogName(moduleOp, param.getName()));
5874 ps << "(";
5875 ps.invokeWithStringOS([&](auto &os) {
5876 emitter.printParamValue(param.getValue(), os, [&]() {
5877 return op->emitOpError("invalid instance parameter '")
5878 << param.getName().getValue() << "' value";
5879 });
5880 });
5881 ps << ")";
5882 }
5883 if (printed) {
5884 ps << PP::end << PP::newline << ")";
5885 }
5886 }
5887
5888 ps << PP::nbsp << PPExtString(getSymOpName(op));
5889
5890 ModulePortInfo modPortInfo(cast<PortList>(moduleOp).getPortList());
5891 SmallVector<Value> instPortValues(modPortInfo.size());
5892 op.getValues(instPortValues, modPortInfo);
5893 emitInstancePortList(op, modPortInfo, instPortValues);
5894
5895 ps.addCallback({op, false});
5896 emitLocationInfoAndNewLine(ops);
5897 if (doNotPrint) {
5898 ps << PP::end;
5899 startStatement();
5900 ps << "*/";
5901 setPendingNewline();
5902 }
5903 return success();
5904}
5905
5906void StmtEmitter::emitInstancePortList(Operation *op,
5907 ModulePortInfo &modPortInfo,
5908 ArrayRef<Value> instPortValues) {
5909 SmallPtrSet<Operation *, 8> ops;
5910 ops.insert(op);
5911
5912 auto containingModule = cast<HWModuleOp>(emitter.currentModuleOp);
5913 ModulePortInfo containingPortList(containingModule.getPortList());
5914
5915 ps << " (";
5916
5917 // Get the max port name length so we can align the '('.
5918 // Exclude outlier names that span the whole line from the alignment column.
5919 size_t maxNameLength = 0;
5920 auto lineLength = state.options.getEmittedLineLength();
5921 for (auto &elt : modPortInfo) {
5922 size_t nameLength = elt.getVerilogName().size();
5923 if (!lineLength || nameLength <= *lineLength / 3)
5924 maxNameLength = std::max(maxNameLength, nameLength);
5925 }
5926
5927 auto getWireForValue = [&](Value result) {
5928 return result.getUsers().begin()->getOperand(0);
5929 };
5930
5931 // Emit the argument and result ports.
5932 bool isFirst = true; // True until we print a port.
5933 bool isZeroWidth = false;
5934
5935 for (size_t portNum = 0, portEnd = modPortInfo.size(); portNum < portEnd;
5936 ++portNum) {
5937 auto &modPort = modPortInfo.at(portNum);
5938 isZeroWidth = isZeroBitType(modPort.type);
5939 Value portVal = instPortValues[portNum];
5940
5941 // Decide if we should print a comma. We can't do this if we're the first
5942 // port or if all the subsequent ports are zero width.
5943 if (!isFirst) {
5944 bool shouldPrintComma = true;
5945 if (isZeroWidth) {
5946 shouldPrintComma = false;
5947 for (size_t i = portNum + 1, e = modPortInfo.size(); i != e; ++i)
5948 if (!isZeroBitType(modPortInfo.at(i).type)) {
5949 shouldPrintComma = true;
5950 break;
5951 }
5952 }
5953
5954 if (shouldPrintComma)
5955 ps << ",";
5956 }
5957 emitLocationInfoAndNewLine(ops);
5958
5959 // Emit the port's name.
5960 startStatement();
5961 if (!isZeroWidth) {
5962 // If this is a real port we're printing, then it isn't the first one. Any
5963 // subsequent ones will need a comma.
5964 isFirst = false;
5965 ps << " ";
5966 } else {
5967 // We comment out zero width ports, so their presence and initializer
5968 // expressions are still emitted textually.
5969 ps << "//";
5970 }
5971
5972 ps.scopedBox(isZeroWidth ? PP::neverbox : PP::ibox2, [&]() {
5973 auto modPortName = modPort.getVerilogName();
5974 ps << "." << PPExtString(modPortName);
5975 // Align to the column if fits, else no-break and accept possible overrun.
5976 if (modPortName.size() <= maxNameLength)
5977 ps.spaces(maxNameLength - modPortName.size() + 1);
5978 else
5979 ps.nbsp();
5980 ps << "(";
5981 ps.scopedBox(PP::ibox0, [&]() {
5982 // Emit the value as an expression.
5983 ops.clear();
5984
5985 // Output ports that are not connected to single use output ports were
5986 // lowered to wire.
5987 OutputOp output;
5988 if (!modPort.isOutput()) {
5989 if (isZeroWidth &&
5990 isa_and_nonnull<ConstantOp>(portVal.getDefiningOp()))
5991 ps << "/* Zero width */";
5992 else
5993 emitExpression(portVal, ops, LowestPrecedence);
5994 } else if (portVal.use_empty()) {
5995 ps << "/* unused */";
5996 } else if (portVal.hasOneUse() &&
5997 (output = dyn_cast_or_null<OutputOp>(
5998 portVal.getUses().begin()->getOwner()))) {
5999 // If this is directly using the output port of the containing module,
6000 // just specify that directly so we avoid a temporary wire.
6001 // Keep this synchronized with countStatements() and
6002 // visitStmt(OutputOp).
6003 size_t outputPortNo = portVal.getUses().begin()->getOperandNumber();
6004 ps << PPExtString(
6005 containingPortList.atOutput(outputPortNo).getVerilogName());
6006 } else {
6007 portVal = getWireForValue(portVal);
6008 emitExpression(portVal, ops);
6009 }
6010 ps << ")";
6011 });
6012 });
6013 }
6014 if (!isFirst || isZeroWidth) {
6015 emitLocationInfoAndNewLine(ops);
6016 ops.clear();
6017 startStatement();
6018 }
6019 ps << ");";
6020}
6021
6022// This may be called in the top-level, not just in an hw.module. Thus we can't
6023// use the name map to find expression names for arguments to the instance, nor
6024// do we need to emit subexpressions. Prepare pass, which has run for all
6025// modules prior to this, has ensured that all arguments are bound to wires,
6026// regs, or ports, with legalized names, so we can lookup up the names through
6027// the IR.
6028LogicalResult StmtEmitter::visitSV(BindOp op) {
6029 emitter.emitBind(op);
6030 assert(state.pendingNewline);
6031 return success();
6032}
6033
6034LogicalResult StmtEmitter::visitSV(InterfaceOp op) {
6035 emitComment(op.getCommentAttr());
6036 // Emit SV attributes.
6037 emitSVAttributes(op);
6038 // TODO: source info!
6039 startStatement();
6040 ps.addCallback({op, true});
6041 ps << "interface " << PPExtString(getSymOpName(op)) << ";";
6042 setPendingNewline();
6043 // FIXME: Don't emit the body of this as general statements, they aren't!
6044 emitStatementBlock(*op.getBodyBlock());
6045 startStatement();
6046 ps << "endinterface" << PP::newline;
6047 ps.addCallback({op, false});
6048 setPendingNewline();
6049 return success();
6050}
6051
6052LogicalResult StmtEmitter::visitSV(sv::SVVerbatimSourceOp op) {
6053 emitSVAttributes(op);
6054 startStatement();
6055 ps.addCallback({op, true});
6056
6057 ps << op.getContent();
6058
6059 ps.addCallback({op, false});
6060 setPendingNewline();
6061 return success();
6062}
6063
6064LogicalResult StmtEmitter::visitSV(InterfaceSignalOp op) {
6065 // Emit SV attributes.
6066 emitSVAttributes(op);
6067 startStatement();
6068 ps.addCallback({op, true});
6069 if (isZeroBitType(op.getType()))
6070 ps << PP::neverbox << "// ";
6071 ps.invokeWithStringOS([&](auto &os) {
6072 emitter.printPackedType(stripUnpackedTypes(op.getType()), os, op->getLoc(),
6073 Type(), false);
6074 });
6075 ps << PP::nbsp << PPExtString(getSymOpName(op));
6076 ps.invokeWithStringOS(
6077 [&](auto &os) { emitter.printUnpackedTypePostfix(op.getType(), os); });
6078 ps << ";";
6079 if (isZeroBitType(op.getType()))
6080 ps << PP::end; // Close never-break group.
6081 ps.addCallback({op, false});
6082 setPendingNewline();
6083 return success();
6084}
6085
6086LogicalResult StmtEmitter::visitSV(InterfaceModportOp op) {
6087 startStatement();
6088 ps.addCallback({op, true});
6089 ps << "modport " << PPExtString(getSymOpName(op)) << "(";
6090
6091 // TODO: revisit, better breaks/grouping.
6092 llvm::interleaveComma(op.getPorts(), ps, [&](const Attribute &portAttr) {
6093 auto port = cast<ModportStructAttr>(portAttr);
6094 ps << PPExtString(stringifyEnum(port.getDirection().getValue())) << " ";
6095 auto *signalDecl = state.symbolCache.getDefinition(port.getSignal());
6096 ps << PPExtString(getSymOpName(signalDecl));
6097 });
6098
6099 ps << ");";
6100 ps.addCallback({op, false});
6101 setPendingNewline();
6102 return success();
6103}
6104
6105LogicalResult StmtEmitter::visitSV(AssignInterfaceSignalOp op) {
6106 startStatement();
6107 ps.addCallback({op, true});
6108 SmallPtrSet<Operation *, 8> emitted;
6109 // TODO: emit like emitAssignLike does, maybe refactor.
6110 ps << "assign ";
6111 emitExpression(op.getIface(), emitted);
6112 ps << "." << PPExtString(op.getSignalName()) << " = ";
6113 emitExpression(op.getRhs(), emitted);
6114 ps << ";";
6115 ps.addCallback({op, false});
6116 setPendingNewline();
6117 return success();
6118}
6119
6120LogicalResult StmtEmitter::visitSV(MacroErrorOp op) {
6121 startStatement();
6122 ps << "`" << op.getMacroIdentifier();
6123 setPendingNewline();
6124 return success();
6125}
6126
6127LogicalResult StmtEmitter::visitSV(MacroDefOp op) {
6128 auto decl = op.getReferencedMacro(&state.symbolCache);
6129 // TODO: source info!
6130 startStatement();
6131 ps.addCallback({op, true});
6132 ps << "`define " << PPExtString(getSymOpName(decl));
6133 if (decl.getArgs()) {
6134 ps << "(";
6135 llvm::interleaveComma(*decl.getArgs(), ps, [&](const Attribute &name) {
6136 ps << cast<StringAttr>(name);
6137 });
6138 ps << ")";
6139 }
6140 if (!op.getFormatString().empty()) {
6141 ps << " ";
6142 emitTextWithSubstitutions(ps, op.getFormatString(), op, {},
6143 op.getSymbols());
6144 }
6145 ps.addCallback({op, false});
6146 setPendingNewline();
6147 return success();
6148}
6149
6150void StmtEmitter::emitStatement(Operation *op) {
6151 // Expressions may either be ignored or emitted as an expression statements.
6152 if (isVerilogExpression(op))
6153 return;
6154
6155 // Ignore LTL expressions as they are emitted as part of verification
6156 // statements. Ignore debug ops as they are emitted as part of debug info.
6157 if (isa_and_nonnull<ltl::LTLDialect, debug::DebugDialect>(op->getDialect()))
6158 return;
6159
6160 // Handle HW statements, SV statements.
6161 if (succeeded(dispatchStmtVisitor(op)) || succeeded(dispatchSVVisitor(op)) ||
6162 succeeded(dispatchVerifVisitor(op)))
6163 return;
6164
6165 emitOpError(op, "emission to Verilog not supported");
6166 emitPendingNewlineIfNeeded();
6167 ps << "unknown MLIR operation " << PPExtString(op->getName().getStringRef());
6168 setPendingNewline();
6169}
6170
6171/// Given an operation corresponding to a VerilogExpression, determine whether
6172/// it is safe to emit inline into a 'localparam' or 'automatic logic' varaible
6173/// initializer in a procedural region.
6174///
6175/// We can't emit exprs inline when they refer to something else that can't be
6176/// emitted inline, when they're in a general #ifdef region,
6177static bool
6179 StmtEmitter &stmtEmitter) {
6180 if (!isVerilogExpression(op))
6181 return false;
6182
6183 // If the expression exists in an #ifdef region, then bail. Emitting it
6184 // inline would cause it to be executed unconditionally, because the
6185 // declarations are outside the #ifdef.
6186 if (isa<IfDefProceduralOp>(op->getParentOp()))
6187 return false;
6188
6189 // This expression tree can be emitted into the initializer if all leaf
6190 // references are safe to refer to from here. They are only safe if they are
6191 // defined in an enclosing scope (guaranteed to already be live by now) or if
6192 // they are defined in this block and already emitted to an inline automatic
6193 // logic variable.
6194 SmallVector<Value, 8> exprsToScan(op->getOperands());
6195
6196 // This loop is guaranteed to terminate because we're only scanning up
6197 // single-use expressions and other things that 'isExpressionEmittedInline'
6198 // returns success for. Cycles won't get in here.
6199 while (!exprsToScan.empty()) {
6200 Operation *expr = exprsToScan.pop_back_val().getDefiningOp();
6201 if (!expr)
6202 continue; // Ports are always safe to reference.
6203
6204 // If this is an inout op, check that its inout op has no blocking
6205 // assignment. A register or logic might be mutated by a blocking assignment
6206 // so it is not always safe to inline.
6207 if (auto readInout = dyn_cast<sv::ReadInOutOp>(expr)) {
6208 auto *defOp = readInout.getOperand().getDefiningOp();
6209
6210 // If it is a read from an inout port, it's unsafe to inline in general.
6211 if (!defOp)
6212 return false;
6213
6214 // If the operand is a wire, it's OK to inline the read.
6215 if (isa<sv::WireOp>(defOp))
6216 continue;
6217
6218 // Reject struct_field_inout/array_index_inout for now because it's
6219 // necessary to consider aliasing inout operations.
6220 if (!isa<RegOp, LogicOp, sv::VarOp>(defOp))
6221 return false;
6222
6223 // It's safe to inline if all users are read op, passign or assign.
6224 // If the op is a logic op whose single assignment is inlined into
6225 // declaration, we can inline the read.
6226 if (isa<LogicOp, sv::VarOp>(defOp) &&
6227 stmtEmitter.emitter.expressionsEmittedIntoDecl.count(defOp))
6228 continue;
6229
6230 // Check that it's safe for all users to be inlined.
6231 if (llvm::all_of(defOp->getResult(0).getUsers(), [&](Operation *op) {
6232 return isa<ReadInOutOp, PAssignOp, AssignOp>(op);
6233 }))
6234 continue;
6235 return false;
6236 }
6237
6238 // If this is an internal node in the expression tree, process its operands.
6239 if (isExpressionEmittedInline(expr, stmtEmitter.state.options)) {
6240 exprsToScan.append(expr->getOperands().begin(),
6241 expr->getOperands().end());
6242 continue;
6243 }
6244
6245 // Otherwise, this isn't an inlinable expression. If it is defined outside
6246 // this block, then it is live-in.
6247 if (expr->getBlock() != op->getBlock())
6248 continue;
6249
6250 // Otherwise, if it is defined in this block then it is only ok to reference
6251 // if it has already been emitted into an automatic logic.
6252 if (!stmtEmitter.emitter.expressionsEmittedIntoDecl.count(expr))
6253 return false;
6254 }
6255
6256 return true;
6257}
6258
6259template <class AssignTy>
6260static AssignTy getSingleAssignAndCheckUsers(Operation *op) {
6261 AssignTy singleAssign;
6262 if (llvm::all_of(op->getUsers(), [&](Operation *user) {
6263 if (hasSVAttributes(user))
6264 return false;
6265
6266 if (auto assign = dyn_cast<AssignTy>(user)) {
6267 if (singleAssign)
6268 return false;
6269 singleAssign = assign;
6270 return true;
6271 }
6272
6273 return isa<ReadInOutOp>(user);
6274 }))
6275 return singleAssign;
6276 return {};
6277}
6278
6279/// Return true if `op1` dominates users of `op2`.
6280static bool checkDominanceOfUsers(Operation *op1, Operation *op2) {
6281 return llvm::all_of(op2->getUsers(), [&](Operation *user) {
6282 /// TODO: Use MLIR DominanceInfo.
6283
6284 // If the op1 and op2 are in different blocks, conservatively return false.
6285 if (op1->getBlock() != user->getBlock())
6286 return false;
6287
6288 if (op1 == user)
6289 return true;
6290
6291 return op1->isBeforeInBlock(user);
6292 });
6293}
6294
6295LogicalResult StmtEmitter::emitDeclaration(Operation *op) {
6296 emitSVAttributes(op);
6297 auto value = op->getResult(0);
6298 SmallPtrSet<Operation *, 8> opsForLocation;
6299 opsForLocation.insert(op);
6300 startStatement();
6301 ps.addCallback({op, true});
6302
6303 // Emit the leading word, like 'wire', 'reg' or 'logic'.
6304 auto type = value.getType();
6305 auto word = getVerilogDeclWord(op, emitter);
6306 auto isZeroBit = isZeroBitType(type);
6307
6308 // LocalParams always need the bitwidth, otherwise they are considered to have
6309 // an unknown size.
6310 bool singleBitDefaultType = !isa<LocalParamOp>(op);
6311
6312 ps.scopedBox(isZeroBit ? PP::neverbox : PP::ibox2, [&]() {
6313 unsigned targetColumn = 0;
6314 unsigned column = 0;
6315
6316 // Emit the declaration keyword.
6317 if (maxDeclNameWidth > 0)
6318 targetColumn += maxDeclNameWidth + 1;
6319
6320 if (isZeroBit) {
6321 ps << "// Zero width: " << PPExtString(word) << PP::space;
6322 } else if (!word.empty()) {
6323 ps << PPExtString(word);
6324 column += word.size();
6325 unsigned numSpaces = targetColumn > column ? targetColumn - column : 1;
6326 ps.spaces(numSpaces);
6327 column += numSpaces;
6328 }
6329
6330 SmallString<8> typeString;
6331 // Convert the port's type to a string and measure it.
6332 {
6333 llvm::raw_svector_ostream stringStream(typeString);
6334 emitter.printPackedType(stripUnpackedTypes(type), stringStream,
6335 op->getLoc(), /*optionalAliasType=*/{},
6336 /*implicitIntType=*/true, singleBitDefaultType);
6337 }
6338 // Emit the type.
6339 if (maxTypeWidth > 0)
6340 targetColumn += maxTypeWidth + 1;
6341 unsigned numSpaces = 0;
6342 if (!typeString.empty()) {
6343 ps << typeString;
6344 column += typeString.size();
6345 ++numSpaces;
6346 }
6347 if (targetColumn > column)
6348 numSpaces = targetColumn - column;
6349 ps.spaces(numSpaces);
6350 column += numSpaces;
6351
6352 // Emit the name.
6353 ps << PPExtString(getSymOpName(op));
6354
6355 // Print out any array subscripts or other post-name stuff.
6356 ps.invokeWithStringOS(
6357 [&](auto &os) { emitter.printUnpackedTypePostfix(type, os); });
6358
6359 // Print debug info.
6360 if (state.options.printDebugInfo) {
6361 if (auto innerSymOp = dyn_cast<hw::InnerSymbolOpInterface>(op)) {
6362 auto innerSym = innerSymOp.getInnerSymAttr();
6363 if (innerSym && !innerSym.empty()) {
6364 ps << " /* ";
6365 ps.invokeWithStringOS([&](auto &os) { os << innerSym; });
6366 ps << " */";
6367 }
6368 }
6369 }
6370
6371 if (auto localparam = dyn_cast<LocalParamOp>(op)) {
6372 ps << PP::space << "=" << PP::space;
6373 ps.invokeWithStringOS([&](auto &os) {
6374 emitter.printParamValue(localparam.getValue(), os, [&]() {
6375 return op->emitOpError("invalid localparam value");
6376 });
6377 });
6378 }
6379
6380 if (auto varOp = dyn_cast<VarOp>(op)) {
6381 if (auto initValue = varOp.getInit()) {
6382 ps << PP::space << "=" << PP::space;
6383 ps.scopedBox(PP::ibox0, [&]() {
6384 emitExpression(initValue, opsForLocation, LowestPrecedence,
6385 /*isAssignmentLikeContext=*/true);
6386 });
6387 }
6388 }
6389
6390 if (auto regOp = dyn_cast<RegOp>(op)) {
6391 if (auto initValue = regOp.getInit()) {
6392 ps << PP::space << "=" << PP::space;
6393 ps.scopedBox(PP::ibox0, [&]() {
6394 emitExpression(initValue, opsForLocation, LowestPrecedence,
6395 /*isAssignmentLikeContext=*/true);
6396 });
6397 }
6398 }
6399
6400 // Try inlining an assignment into declarations.
6401 // FIXME: Unpacked array is not inlined since several tools doesn't support
6402 // that syntax. See Issue 6363.
6403 if (!state.options.disallowDeclAssignments && isa<sv::WireOp>(op) &&
6404 !op->getParentOp()->hasTrait<ProceduralRegion>() &&
6405 !hasLeadingUnpackedType(op->getResult(0).getType())) {
6406 // Get a single assignments if any.
6407 if (auto singleAssign = getSingleAssignAndCheckUsers<AssignOp>(op)) {
6408 auto *source = singleAssign.getSrc().getDefiningOp();
6409 // Check that the source value is OK to inline in the current emission
6410 // point. A port or constant is fine, otherwise check that the assign is
6411 // next to the operation.
6412 if (!source || isa<ConstantOp>(source) ||
6413 op->getNextNode() == singleAssign) {
6414 ps << PP::space << "=" << PP::space;
6415 ps.scopedBox(PP::ibox0, [&]() {
6416 emitExpression(singleAssign.getSrc(), opsForLocation,
6417 LowestPrecedence,
6418 /*isAssignmentLikeContext=*/true);
6419 });
6420 emitter.assignsInlined.insert(singleAssign);
6421 }
6422 }
6423 }
6424
6425 // Try inlining a blocking assignment to logic op declaration.
6426 // FIXME: Unpacked array is not inlined since several tools doesn't support
6427 // that syntax. See Issue 6363.
6428 if (!state.options.disallowDeclAssignments && isa<LogicOp, sv::VarOp>(op) &&
6429 op->getParentOp()->hasTrait<ProceduralRegion>() &&
6430 !hasLeadingUnpackedType(op->getResult(0).getType())) {
6431 // Get a single assignment which might be possible to inline.
6432 if (auto singleAssign = getSingleAssignAndCheckUsers<BPAssignOp>(op)) {
6433 // It is necessary for the assignment to dominate users of the op.
6434 if (checkDominanceOfUsers(singleAssign, op)) {
6435 auto *source = singleAssign.getSrc().getDefiningOp();
6436 // A port or constant can be inlined at everywhere. Otherwise, check
6437 // the validity by
6438 // `isExpressionEmittedInlineIntoProceduralDeclaration`.
6439 if (!source || isa<ConstantOp>(source) ||
6441 *this)) {
6442 ps << PP::space << "=" << PP::space;
6443 ps.scopedBox(PP::ibox0, [&]() {
6444 emitExpression(singleAssign.getSrc(), opsForLocation,
6445 LowestPrecedence,
6446 /*isAssignmentLikeContext=*/true);
6447 });
6448 // Remember that the assignment and logic op are emitted into decl.
6449 emitter.assignsInlined.insert(singleAssign);
6450 emitter.expressionsEmittedIntoDecl.insert(op);
6451 }
6452 }
6453 }
6454 }
6455 ps << ";";
6456 });
6457 ps.addCallback({op, false});
6458 emitLocationInfoAndNewLine(opsForLocation);
6459 return success();
6460}
6461
6462void StmtEmitter::collectNamesAndCalculateDeclarationWidths(Block &block) {
6463 // In the first pass, we fill in the symbol table, calculate the max width
6464 // of the declaration words and the max type width.
6465 NameCollector collector(emitter);
6466 collector.collectNames(block);
6467
6468 // Record maxDeclNameWidth and maxTypeWidth in the current scope.
6469 maxDeclNameWidth = collector.getMaxDeclNameWidth();
6470 maxTypeWidth = collector.getMaxTypeWidth();
6471}
6472
6473void StmtEmitter::emitStatementBlock(Block &body) {
6474 ps.scopedBox(PP::bbox2, [&]() {
6475 // Ensure decl alignment values are preserved after the block is emitted.
6476 // These values were computed for and from all declarations in the current
6477 // block (before/after this nested block), so be sure they're restored
6478 // and not overwritten by the declaration alignment within the block.
6479 llvm::SaveAndRestore<size_t> x(maxDeclNameWidth);
6480 llvm::SaveAndRestore<size_t> x2(maxTypeWidth);
6481
6482 // Build up the symbol table for all of the values that need names in the
6483 // module. #ifdef's in procedural regions are special because local
6484 // variables are all emitted at the top of their enclosing blocks.
6485 if (!isa<IfDefProceduralOp>(body.getParentOp()))
6486 collectNamesAndCalculateDeclarationWidths(body);
6487
6488 // Emit the body.
6489 for (auto &op : body) {
6490 emitStatement(&op);
6491 }
6492 });
6493}
6494// NOLINTEND(misc-no-recursion)
6495
6496void ModuleEmitter::emitStatement(Operation *op) {
6497 StmtEmitter(*this, state.options).emitStatement(op);
6498}
6499
6500/// Emit SystemVerilog attributes attached to the expression op as dialect
6501/// attributes.
6502void ModuleEmitter::emitSVAttributes(Operation *op) {
6503 // SystemVerilog 2017 Section 5.12.
6504 auto svAttrs = getSVAttributes(op);
6505 if (!svAttrs)
6506 return;
6507
6508 startStatement(); // For attributes.
6509 emitSVAttributesImpl(ps, svAttrs, /*mayBreak=*/true);
6510 setPendingNewline();
6511}
6512
6513//===----------------------------------------------------------------------===//
6514// Module Driver
6515//===----------------------------------------------------------------------===//
6516
6517void ModuleEmitter::emitHWGeneratedModule(HWModuleGeneratedOp module) {
6518 auto verilogName = module.getVerilogModuleNameAttr();
6519 startStatement();
6520 ps << "// external generated module " << PPExtString(verilogName.getValue())
6521 << PP::newline;
6522 setPendingNewline();
6523}
6524
6525// This may be called in the top-level, not just in an hw.module. Thus we can't
6526// use the name map to find expression names for arguments to the instance, nor
6527// do we need to emit subexpressions. Prepare pass, which has run for all
6528// modules prior to this, has ensured that all arguments are bound to wires,
6529// regs, or ports, with legalized names, so we can lookup up the names through
6530// the IR.
6531void ModuleEmitter::emitBind(BindOp op) {
6532 if (hasSVAttributes(op))
6533 emitError(op, "SV attributes emission is unimplemented for the op");
6534 InstanceOp inst = op.getReferencedInstance(&state.symbolCache);
6535
6536 HWModuleOp parentMod = inst->getParentOfType<hw::HWModuleOp>();
6537 ModulePortInfo parentPortList(parentMod.getPortList());
6538 auto parentVerilogName = getVerilogModuleNameAttr(parentMod);
6539
6540 Operation *childMod =
6541 state.symbolCache.getDefinition(inst.getReferencedModuleNameAttr());
6542 auto childVerilogName = getVerilogModuleNameAttr(childMod);
6543
6544 startStatement();
6545 ps.addCallback({op, true});
6546 ps << "bind " << PPExtString(parentVerilogName.getValue()) << PP::nbsp
6547 << PPExtString(childVerilogName.getValue()) << PP::nbsp
6548 << PPExtString(getSymOpName(inst)) << " (";
6549 bool isFirst = true; // True until we print a port.
6550 ps.scopedBox(PP::bbox2, [&]() {
6551 auto parentPortInfo = parentMod.getPortList();
6552 ModulePortInfo childPortInfo(cast<PortList>(childMod).getPortList());
6553
6554 // Get the max port name length so we can align the '('.
6555 // Exclude outlier names longer than the line.
6556 size_t maxNameLength = 0;
6557 auto lineLength = state.options.getEmittedLineLength();
6558 for (auto &elt : childPortInfo) {
6559 auto portName = elt.getVerilogName();
6560 elt.name = Builder(inst.getContext()).getStringAttr(portName);
6561 size_t nameLength = elt.getName().size();
6562 if (!lineLength || nameLength <= *lineLength / 3)
6563 maxNameLength = std::max(maxNameLength, nameLength);
6564 }
6565
6566 SmallVector<Value> instPortValues(childPortInfo.size());
6567 inst.getValues(instPortValues, childPortInfo);
6568 // Emit the argument and result ports.
6569 for (auto [idx, elt] : llvm::enumerate(childPortInfo)) {
6570 // Figure out which value we are emitting.
6571 Value portVal = instPortValues[idx];
6572 bool isZeroWidth = isZeroBitType(elt.type);
6573
6574 // Decide if we should print a comma. We can't do this if we're the
6575 // first port or if all the subsequent ports are zero width.
6576 if (!isFirst) {
6577 bool shouldPrintComma = true;
6578 if (isZeroWidth) {
6579 shouldPrintComma = false;
6580 for (size_t i = idx + 1, e = childPortInfo.size(); i != e; ++i)
6581 if (!isZeroBitType(childPortInfo.at(i).type)) {
6582 shouldPrintComma = true;
6583 break;
6584 }
6585 }
6586
6587 if (shouldPrintComma)
6588 ps << ",";
6589 }
6590 ps << PP::newline;
6591
6592 // Emit the port's name.
6593 if (!isZeroWidth) {
6594 // If this is a real port we're printing, then it isn't the first
6595 // one. Any subsequent ones will need a comma.
6596 isFirst = false;
6597 } else {
6598 // We comment out zero width ports, so their presence and
6599 // initializer expressions are still emitted textually.
6600 ps << PP::neverbox << "//";
6601 }
6602
6603 ps << "." << PPExtString(elt.getName());
6604 // Align to the column if fits, else no-break and accept possible overrun.
6605 if (elt.getName().size() <= maxNameLength)
6606 ps.nbsp(maxNameLength - elt.getName().size());
6607 ps << " (";
6608 llvm::SmallPtrSet<Operation *, 4> ops;
6609 if (elt.isOutput()) {
6610 assert((portVal.hasOneUse() || portVal.use_empty()) &&
6611 "output port must have either single or no use");
6612 if (portVal.use_empty()) {
6613 ps << "/* unused */";
6614 } else if (auto output = dyn_cast_or_null<OutputOp>(
6615 portVal.getUses().begin()->getOwner())) {
6616 // If this is directly using the output port of the containing
6617 // module, just specify that directly.
6618 size_t outputPortNo = portVal.getUses().begin()->getOperandNumber();
6619 ps << PPExtString(
6620 parentPortList.atOutput(outputPortNo).getVerilogName());
6621 } else {
6622 portVal = portVal.getUsers().begin()->getOperand(0);
6623 ExprEmitter(*this, ops)
6624 .emitExpression(portVal, LowestPrecedence,
6625 /*isAssignmentLikeContext=*/false);
6626 }
6627 } else {
6628 ExprEmitter(*this, ops)
6629 .emitExpression(portVal, LowestPrecedence,
6630 /*isAssignmentLikeContext=*/false);
6631 }
6632
6633 ps << ")";
6634
6635 if (isZeroWidth)
6636 ps << PP::end; // Close never-break group.
6637 }
6638 });
6639 if (!isFirst)
6640 ps << PP::newline;
6641 ps << ");";
6642 ps.addCallback({op, false});
6643 setPendingNewline();
6644}
6645
6646void ModuleEmitter::emitBindInterface(BindInterfaceOp op) {
6647 if (hasSVAttributes(op))
6648 emitError(op, "SV attributes emission is unimplemented for the op");
6649
6650 auto instance = op.getReferencedInstance(&state.symbolCache);
6651 auto instantiator = instance->getParentOfType<HWModuleOp>().getName();
6652 auto *interface = op->getParentOfType<ModuleOp>().lookupSymbol(
6653 instance.getInterfaceType().getInterface());
6654 startStatement();
6655 ps.addCallback({op, true});
6656 ps << "bind " << PPExtString(instantiator) << PP::nbsp
6657 << PPExtString(cast<InterfaceOp>(*interface).getSymName()) << PP::nbsp
6658 << PPExtString(getSymOpName(instance)) << " (.*);" << PP::newline;
6659 ps.addCallback({op, false});
6660 setPendingNewline();
6661}
6662
6663void ModuleEmitter::emitParameters(Operation *module, ArrayAttr params) {
6664 if (params.empty())
6665 return;
6666
6667 auto printParamType = [&](Type type, Attribute defaultValue,
6668 SmallString<8> &result) {
6669 result.clear();
6670 llvm::raw_svector_ostream sstream(result);
6671
6672 // If there is a default value like "32" then just print without type at
6673 // all.
6674 if (defaultValue) {
6675 if (auto intAttr = dyn_cast<IntegerAttr>(defaultValue))
6676 if (intAttr.getValue().getBitWidth() == 32)
6677 return;
6678 if (auto fpAttr = dyn_cast<FloatAttr>(defaultValue))
6679 if (fpAttr.getType().isF64())
6680 return;
6681 }
6682 if (isa<NoneType>(type))
6683 return;
6684
6685 // Classic Verilog parser don't allow a type in the parameter declaration.
6686 // For compatibility with them, we omit the type when it is implicit based
6687 // on its initializer value, and print the type commented out when it is
6688 // a 32-bit "integer" parameter.
6689 if (auto intType = type_dyn_cast<IntegerType>(type))
6690 if (intType.getWidth() == 32) {
6691 sstream << "/*integer*/";
6692 return;
6693 }
6694
6695 printPackedType(type, sstream, module->getLoc(),
6696 /*optionalAliasType=*/Type(),
6697 /*implicitIntType=*/true,
6698 // Print single-bit values as explicit `[0:0]` type.
6699 /*singleBitDefaultType=*/false);
6700 };
6701
6702 // Determine the max width of the parameter types so things are lined up.
6703 size_t maxTypeWidth = 0;
6704 SmallString<8> scratch;
6705 for (auto param : params) {
6706 auto paramAttr = cast<ParamDeclAttr>(param);
6707 // Measure the type length by printing it to a temporary string.
6708 printParamType(paramAttr.getType(), paramAttr.getValue(), scratch);
6709 maxTypeWidth = std::max(scratch.size(), maxTypeWidth);
6710 }
6711
6712 if (maxTypeWidth > 0) // add a space if any type exists.
6713 maxTypeWidth += 1;
6714
6715 ps.scopedBox(PP::bbox2, [&]() {
6716 ps << PP::newline << "#(";
6717 ps.scopedBox(PP::cbox0, [&]() {
6718 llvm::interleave(
6719 params,
6720 [&](Attribute param) {
6721 auto paramAttr = cast<ParamDeclAttr>(param);
6722 auto defaultValue = paramAttr.getValue(); // may be null if absent.
6723 ps << "parameter ";
6724 printParamType(paramAttr.getType(), defaultValue, scratch);
6725 if (!scratch.empty())
6726 ps << scratch;
6727 if (scratch.size() < maxTypeWidth)
6728 ps.nbsp(maxTypeWidth - scratch.size());
6729
6730 ps << PPExtString(state.globalNames.getParameterVerilogName(
6731 module, paramAttr.getName()));
6732
6733 if (defaultValue) {
6734 ps << " = ";
6735 ps.invokeWithStringOS([&](auto &os) {
6736 printParamValue(defaultValue, os, [&]() {
6737 return module->emitError("parameter '")
6738 << paramAttr.getName().getValue()
6739 << "' has invalid value";
6740 });
6741 });
6742 }
6743 },
6744 [&]() { ps << "," << PP::newline; });
6745 ps << ") ";
6746 });
6747 });
6748}
6749
6750void ModuleEmitter::emitPortList(Operation *module,
6751 const ModulePortInfo &portInfo,
6752 bool emitAsTwoStateType) {
6753 ps << "(";
6754 if (portInfo.size())
6755 emitLocationInfo(module->getLoc());
6756
6757 // Determine the width of the widest type we have to print so everything
6758 // lines up nicely.
6759 bool hasOutputs = false, hasZeroWidth = false;
6760 size_t maxTypeWidth = 0, lastNonZeroPort = -1;
6761 SmallVector<SmallString<8>, 16> portTypeStrings;
6762
6763 for (size_t i = 0, e = portInfo.size(); i < e; ++i) {
6764 auto port = portInfo.at(i);
6765 hasOutputs |= port.isOutput();
6766 hasZeroWidth |= isZeroBitType(port.type);
6767 if (!isZeroBitType(port.type))
6768 lastNonZeroPort = i;
6769
6770 // Convert the port's type to a string and measure it.
6771 portTypeStrings.push_back({});
6772 {
6773 llvm::raw_svector_ostream stringStream(portTypeStrings.back());
6774 printPackedType(stripUnpackedTypes(port.type), stringStream,
6775 module->getLoc(), {}, true, true, emitAsTwoStateType);
6776 }
6777
6778 maxTypeWidth = std::max(portTypeStrings.back().size(), maxTypeWidth);
6779 }
6780
6781 if (maxTypeWidth > 0) // add a space if any type exists
6782 maxTypeWidth += 1;
6783
6784 auto getPortSVAttrs = [](const PortInfo &port) -> ArrayAttr {
6785 if (!port.attrs)
6786 return {};
6787 auto attrs = port.attrs.getAs<ArrayAttr>(
6788 sv::SVAttributeAttr::getSVAttributesAttrName());
6789 if (!attrs || attrs.empty())
6790 return {};
6791 return attrs;
6792 };
6793
6794 // Emit the port list.
6795 ps.scopedBox(PP::bbox2, [&]() {
6796 for (size_t portIdx = 0, e = portInfo.size(); portIdx != e;) {
6797 auto lastPort = e - 1;
6798
6799 ps << PP::newline;
6800 auto portType = portInfo.at(portIdx).type;
6801
6802 // If this is a zero width type, emit the port as a comment and create a
6803 // neverbox to ensure we don't insert a line break.
6804 bool isZeroWidth = false;
6805 if (hasZeroWidth) {
6806 isZeroWidth = isZeroBitType(portType);
6807 if (isZeroWidth)
6808 ps << PP::neverbox;
6809 ps << (isZeroWidth ? "// " : " ");
6810 }
6811
6812 // Emit the port direction and optional wire keyword.
6813 auto thisPortInfo = portInfo.at(portIdx);
6814 auto svAttrs = getPortSVAttrs(thisPortInfo);
6815 if (svAttrs && !isZeroWidth) {
6816 emitSVAttributesImpl(ps, svAttrs, /*mayBreak=*/false);
6817 ps << PP::newline;
6818 if (hasZeroWidth)
6819 ps << " ";
6820 }
6821 auto thisPortDirection = thisPortInfo.dir;
6822 bool isInOut = isa<InOutType, sv::NetType>(portType);
6823 StringRef direction;
6824 if (isInOut) {
6825 direction = hasOutputs ? "inout " : "inout ";
6826 } else {
6827 switch (thisPortDirection) {
6828 case ModulePort::Direction::Output:
6829 direction = "output ";
6830 break;
6831 case ModulePort::Direction::Input:
6832 direction = hasOutputs ? "input " : "input ";
6833 break;
6834 }
6835 }
6836 StringRef portDecl;
6837 switch (state.options.emitPortType) {
6839 portDecl = "wire ";
6840 break;
6842 if (!hasExplicitDataType(portType))
6843 portDecl = emitAsTwoStateType ? "var " : "var logic ";
6844 break;
6846 break;
6847 }
6848 size_t startOfNamePos = direction.size() + portDecl.size() + maxTypeWidth;
6849 // Modport-typed ports (e.g., MyBundle.sink) already encode their
6850 // direction in the interface modport definition, so we suppress the
6851 // direction and wire keywords for them.
6852 if (!isa<ModportType>(portType)) {
6853 ps << direction;
6854 if (!portDecl.empty())
6855 ps << portDecl;
6856 if (!portTypeStrings[portIdx].empty())
6857 ps << portTypeStrings[portIdx];
6858 if (portTypeStrings[portIdx].size() < maxTypeWidth)
6859 ps.nbsp(maxTypeWidth - portTypeStrings[portIdx].size());
6860 } else {
6861 ps << portTypeStrings[portIdx];
6862 if (portTypeStrings[portIdx].size() < startOfNamePos)
6863 ps.nbsp(startOfNamePos - portTypeStrings[portIdx].size());
6864 }
6865
6866 // Emit the name.
6867 ps << PPExtString(portInfo.at(portIdx).getVerilogName());
6868
6869 // Emit array dimensions.
6870 ps.invokeWithStringOS(
6871 [&](auto &os) { printUnpackedTypePostfix(portType, os); });
6872
6873 // Emit the symbol.
6874 auto innerSym = portInfo.at(portIdx).getSym();
6875 if (state.options.printDebugInfo && innerSym && !innerSym.empty()) {
6876 ps << " /* ";
6877 ps.invokeWithStringOS([&](auto &os) { os << innerSym; });
6878 ps << " */";
6879 }
6880
6881 // Emit the comma if this is not the last real port.
6882 if (portIdx != lastNonZeroPort && portIdx != lastPort)
6883 ps << ",";
6884
6885 // Emit the location.
6886 if (auto loc = portInfo.at(portIdx).loc)
6887 emitLocationInfo(loc);
6888
6889 if (isZeroWidth)
6890 ps << PP::end; // Close never-break group.
6891
6892 ++portIdx;
6893
6894 // If we have any more ports with the same types, the same direction,
6895 // and the same emitted kind (plain/net), emit them in a list one
6896 // per line. Optionally skip this behavior when requested by user. This
6897 // kind of check is important because two ports can share a direction and
6898 // an (unwrapped) element type, emitting completely different keywords.
6899 // Thus we must ensure they are not folded into one shared declaration.
6900 if (!state.options.disallowPortDeclSharing && !svAttrs) {
6901 while (portIdx != e && !getPortSVAttrs(portInfo.at(portIdx)) &&
6902 portInfo.at(portIdx).dir == thisPortDirection &&
6903 isInOut ==
6904 isa<InOutType, sv::NetType>(portInfo.at(portIdx).type) &&
6905 stripUnpackedTypes(portType) ==
6906 stripUnpackedTypes(portInfo.at(portIdx).type)) {
6907 auto port = portInfo.at(portIdx);
6908 // Append this to the running port decl.
6909 ps << PP::newline;
6910
6911 bool isZeroWidth = false;
6912 if (hasZeroWidth) {
6913 isZeroWidth = isZeroBitType(portType);
6914 if (isZeroWidth)
6915 ps << PP::neverbox;
6916 ps << (isZeroWidth ? "// " : " ");
6917 }
6918
6919 ps.nbsp(startOfNamePos);
6920
6921 // Emit the name.
6922 StringRef name = port.getVerilogName();
6923 ps << PPExtString(name);
6924
6925 // Emit array dimensions.
6926 ps.invokeWithStringOS(
6927 [&](auto &os) { printUnpackedTypePostfix(port.type, os); });
6928
6929 // Emit the symbol.
6930 auto sym = port.getSym();
6931 if (state.options.printDebugInfo && sym && !sym.empty())
6932 ps << " /* inner_sym: " << PPExtString(sym.getSymName().getValue())
6933 << " */";
6934
6935 // Emit the comma if this is not the last real port.
6936 if (portIdx != lastNonZeroPort && portIdx != lastPort)
6937 ps << ",";
6938
6939 // Emit the location.
6940 if (auto loc = port.loc)
6941 emitLocationInfo(loc);
6942
6943 if (isZeroWidth)
6944 ps << PP::end; // Close never-break group.
6945
6946 ++portIdx;
6947 }
6948 }
6949 }
6950 });
6951
6952 if (!portInfo.size()) {
6953 ps << ");";
6954 SmallPtrSet<Operation *, 8> moduleOpSet;
6955 moduleOpSet.insert(module);
6956 emitLocationInfoAndNewLine(moduleOpSet);
6957 } else {
6958 ps << PP::newline;
6959 ps << ");" << PP::newline;
6960 setPendingNewline();
6961 }
6962}
6963
6964void ModuleEmitter::emitHWModule(HWModuleOp module) {
6965 currentModuleOp = module;
6966
6967 emitComment(module.getCommentAttr());
6968 emitSVAttributes(module);
6969 startStatement();
6970 ps.addCallback({module, true});
6971 ps << "module " << PPExtString(getVerilogModuleName(module));
6972
6973 // If we have any parameters, print them on their own line.
6974 emitParameters(module, module.getParameters());
6975
6976 emitPortList(module, ModulePortInfo(module.getPortList()));
6977
6978 assert(state.pendingNewline);
6979
6980 // Emit the body of the module.
6981 StmtEmitter(*this, state.options).emitStatementBlock(*module.getBodyBlock());
6982 startStatement();
6983 ps << "endmodule";
6984 ps.addCallback({module, false});
6985 ps << PP::newline;
6986 setPendingNewline();
6987
6988 currentModuleOp = nullptr;
6989}
6990
6991void ModuleEmitter::emitFunc(FuncOp func) {
6992 // Nothing to emit for a declaration.
6993 if (func.isDeclaration())
6994 return;
6995
6996 currentModuleOp = func;
6997 startStatement();
6998 ps.addCallback({func, true});
6999 // A function is moduled as an automatic function.
7000 emitFunctionSignature(*this, ps, func, /*isAutomatic=*/true);
7001 // Emit the body of the module.
7002 StmtEmitter(*this, state.options).emitStatementBlock(*func.getBodyBlock());
7003 startStatement();
7004 ps << "endfunction";
7005 ps << PP::newline;
7006 currentModuleOp = nullptr;
7007}
7008
7009//===----------------------------------------------------------------------===//
7010// Emitter for files & file lists.
7011//===----------------------------------------------------------------------===//
7012
7013class FileEmitter : public EmitterBase {
7014public:
7015 explicit FileEmitter(VerilogEmitterState &state) : EmitterBase(state) {}
7016
7017 void emit(emit::FileOp op) {
7018 emit(op.getBody());
7019 ps.eof();
7020 }
7021 void emit(emit::FragmentOp op) { emit(op.getBody()); }
7022 void emit(emit::FileListOp op);
7023
7024private:
7025 void emit(Block *block);
7026
7027 void emitOp(emit::RefOp op);
7028 void emitOp(emit::VerbatimOp op);
7029};
7030
7032 for (Operation &op : *block) {
7033 TypeSwitch<Operation *>(&op)
7034 .Case<emit::VerbatimOp, emit::RefOp>([&](auto op) { emitOp(op); })
7035 .Case<VerbatimOp, IfDefOp, MacroDefOp, sv::FuncDPIImportOp>(
7036 [&](auto op) { ModuleEmitter(state).emitStatement(op); })
7037 .Case<BindOp>([&](auto op) { ModuleEmitter(state).emitBind(op); })
7038 .Case<BindInterfaceOp>(
7039 [&](auto op) { ModuleEmitter(state).emitBindInterface(op); })
7040 .Case<TypeScopeOp>([&](auto typedecls) {
7041 ModuleEmitter(state).emitStatement(typedecls);
7042 })
7043 .Default(
7044 [&](auto op) { emitOpError(op, "cannot be emitted to a file"); });
7045 }
7046}
7047
7048void FileEmitter::emit(emit::FileListOp op) {
7049 // Find the associated file ops and write the paths on individual lines.
7050 for (auto sym : op.getFiles()) {
7051 auto fileName = cast<FlatSymbolRefAttr>(sym).getAttr();
7052
7053 auto it = state.fileMapping.find(fileName);
7054 if (it == state.fileMapping.end()) {
7055 emitOpError(op, " references an invalid file: ") << sym;
7056 continue;
7057 }
7058
7059 auto file = cast<emit::FileOp>(it->second);
7060 ps << PP::neverbox << PPExtString(file.getFileName()) << PP::end
7061 << PP::newline;
7062 }
7063 ps.eof();
7064}
7065
7066void FileEmitter::emitOp(emit::RefOp op) {
7067 StringAttr target = op.getTargetAttr().getAttr();
7068 auto *targetOp = state.symbolCache.getDefinition(target);
7069 assert(isa<emit::Emittable>(targetOp) && "target must be emittable");
7070
7071 TypeSwitch<Operation *>(targetOp)
7072 .Case<sv::FuncOp>([&](auto func) { ModuleEmitter(state).emitFunc(func); })
7073 .Case<hw::HWModuleOp>(
7074 [&](auto module) { ModuleEmitter(state).emitHWModule(module); })
7075 .Case<TypeScopeOp, PackageOp>([&](auto typedecls) {
7076 ModuleEmitter(state).emitStatement(typedecls);
7077 })
7078 .Default(
7079 [&](auto op) { emitOpError(op, "cannot be emitted to a file"); });
7080}
7081
7082void FileEmitter::emitOp(emit::VerbatimOp op) {
7083 startStatement();
7084
7085 SmallPtrSet<Operation *, 8> ops;
7086 ops.insert(op);
7087
7088 // Emit each line of the string at a time, emitting the
7089 // location comment after the last emitted line.
7090 StringRef text = op.getText();
7091
7092 ps << PP::neverbox;
7093 do {
7094 const auto &[lhs, rhs] = text.split('\n');
7095 if (!lhs.empty())
7096 ps << PPExtString(lhs);
7097 if (!rhs.empty())
7098 ps << PP::end << PP::newline << PP::neverbox;
7099 text = rhs;
7100 } while (!text.empty());
7101 ps << PP::end;
7102
7103 emitLocationInfoAndNewLine(ops);
7104}
7105
7106//===----------------------------------------------------------------------===//
7107// Top level "file" emitter logic
7108//===----------------------------------------------------------------------===//
7109
7110/// Organize the operations in the root MLIR module into output files to be
7111/// generated. If `separateModules` is true, a handful of top-level
7112/// declarations will be split into separate output files even in the absence
7113/// of an explicit output file attribute.
7114void SharedEmitterState::gatherFiles(bool separateModules) {
7115
7116 /// Collect all the inner names from the specified module and add them to the
7117 /// IRCache. Declarations (named things) only exist at the top level of the
7118 /// module. Also keep track of any modules that contain bind operations.
7119 /// These are non-hierarchical references which we need to be careful about
7120 /// during emission.
7121 auto collectInstanceSymbolsAndBinds = [&](Operation *moduleOp) {
7122 moduleOp->walk([&](Operation *op) {
7123 // Populate the symbolCache with all operations that can define a symbol.
7124 // Register every property, including per-field inner symbols.
7125 if (auto name = op->getAttrOfType<InnerSymAttr>(
7126 hw::InnerSymbolTable::getInnerSymbolAttrName()))
7127 for (auto prop : name)
7128 symbolCache.addDefinition(
7129 cast<mlir::SymbolOpInterface>(moduleOp).getNameAttr(),
7130 prop.getName(), op);
7131 if (isa<BindOp>(op))
7132 modulesContainingBinds.insert(moduleOp);
7133 });
7134 };
7135
7136 /// Collect any port marked as being referenced via symbol.
7137 auto collectPorts = [&](auto moduleOp) {
7138 auto portInfo = moduleOp.getPortList();
7139 for (auto [i, p] : llvm::enumerate(portInfo)) {
7140 if (!p.attrs || p.attrs.empty())
7141 continue;
7142 for (NamedAttribute portAttr : p.attrs) {
7143 if (auto sym = dyn_cast<InnerSymAttr>(portAttr.getValue())) {
7144 symbolCache.addDefinition(moduleOp.getNameAttr(), sym.getSymName(),
7145 moduleOp, i);
7146 }
7147 }
7148 }
7149 };
7150
7151 // Create a mapping identifying the files each symbol is emitted to.
7152 DenseMap<StringAttr, SmallVector<emit::FileOp>> symbolsToFiles;
7153 for (auto file : designOp.getOps<emit::FileOp>())
7154 for (auto refs : file.getOps<emit::RefOp>())
7155 symbolsToFiles[refs.getTargetAttr().getAttr()].push_back(file);
7156
7157 SmallString<32> outputPath;
7158 for (auto &op : *designOp.getBody()) {
7159 auto info = OpFileInfo{&op, replicatedOps.size()};
7160
7161 bool isFileOp = isa<emit::FileOp, emit::FileListOp>(&op);
7162
7163 bool hasFileName = false;
7164 bool emitReplicatedOps = !isFileOp;
7165 bool addToFilelist = !isFileOp;
7166
7167 outputPath.clear();
7168
7169 // Check if the operation has an explicit `output_file` attribute set. If
7170 // it does, extract the information from the attribute.
7171 auto attr = op.getAttrOfType<hw::OutputFileAttr>("output_file");
7172 if (attr) {
7173 LLVM_DEBUG(llvm::dbgs() << "Found output_file attribute " << attr
7174 << " on " << op << "\n";);
7175 if (!attr.isDirectory())
7176 hasFileName = true;
7177 appendPossiblyAbsolutePath(outputPath, attr.getFilename().getValue());
7178 emitReplicatedOps = attr.getIncludeReplicatedOps().getValue();
7179 addToFilelist = !attr.getExcludeFromFilelist().getValue();
7180 }
7181
7182 auto separateFile = [&](Operation *op, Twine defaultFileName = "") {
7183 // If we're emitting to a separate file and the output_file attribute
7184 // didn't specify a filename, take the default one if present or emit an
7185 // error if not.
7186 if (!hasFileName) {
7187 if (!defaultFileName.isTriviallyEmpty()) {
7188 llvm::sys::path::append(outputPath, defaultFileName);
7189 } else {
7190 op->emitError("file name unspecified");
7191 encounteredError = true;
7192 llvm::sys::path::append(outputPath, "error.out");
7193 }
7194 }
7195
7196 auto destFile = StringAttr::get(op->getContext(), outputPath);
7197 auto &file = files[destFile];
7198 file.ops.push_back(info);
7199 file.emitReplicatedOps = emitReplicatedOps;
7200 file.addToFilelist = addToFilelist;
7201 file.isVerilog = outputPath.ends_with(".sv");
7202
7203 // Back-annotate the op with an OutputFileAttr if there wasn't one. If it
7204 // was a directory, back-annotate the final file path. This is so output
7205 // files are explicit in the final MLIR after export.
7206 if (!attr || attr.isDirectory()) {
7207 auto excludeFromFileListAttr =
7208 BoolAttr::get(op->getContext(), !addToFilelist);
7209 auto includeReplicatedOpsAttr =
7210 BoolAttr::get(op->getContext(), emitReplicatedOps);
7211 auto outputFileAttr = hw::OutputFileAttr::get(
7212 destFile, excludeFromFileListAttr, includeReplicatedOpsAttr);
7213 op->setAttr("output_file", outputFileAttr);
7214 }
7215 };
7216
7217 // Separate the operation into dedicated output file, or emit into the
7218 // root file, or replicate in all output files.
7219 TypeSwitch<Operation *>(&op)
7220 .Case<emit::FileOp, emit::FileListOp>([&](auto file) {
7221 // Emit file ops to their respective files.
7222 fileMapping.try_emplace(file.getSymNameAttr(), file);
7223 separateFile(file, file.getFileName());
7224 })
7225 .Case<emit::FragmentOp>([&](auto fragment) {
7226 fragmentMapping.try_emplace(fragment.getSymNameAttr(), fragment);
7227 })
7228 .Case<HWModuleOp>([&](auto mod) {
7229 // Build the IR cache.
7230 auto sym = mod.getNameAttr();
7231 symbolCache.addDefinition(sym, mod);
7232 collectPorts(mod);
7233 collectInstanceSymbolsAndBinds(mod);
7234
7235 if (auto it = symbolsToFiles.find(sym); it != symbolsToFiles.end()) {
7236 if (it->second.size() != 1 || attr) {
7237 // This is a temporary check, present as long as both
7238 // output_file and file operations are used.
7239 op.emitError("modules can be emitted to a single file");
7240 encounteredError = true;
7241 } else {
7242 // The op is not separated into a file as it will be
7243 // pulled into the unique file operation it references.
7244 }
7245 } else {
7246 // Emit into a separate file named after the module.
7247 if (attr || separateModules)
7248 separateFile(mod, getVerilogModuleName(mod) + ".sv");
7249 else
7250 rootFile.ops.push_back(info);
7251 }
7252 })
7253 .Case<InterfaceOp>([&](InterfaceOp intf) {
7254 // Build the IR cache.
7255 symbolCache.addDefinition(intf.getNameAttr(), intf);
7256 // Populate the symbolCache with all operations that can define a
7257 // symbol.
7258 for (auto &op : *intf.getBodyBlock())
7259 if (auto symOp = dyn_cast<mlir::SymbolOpInterface>(op))
7260 if (auto name = symOp.getNameAttr())
7261 symbolCache.addDefinition(name, symOp);
7262
7263 // Emit into a separate file named after the interface.
7264 if (attr || separateModules)
7265 separateFile(intf, intf.getSymName() + ".sv");
7266 else
7267 rootFile.ops.push_back(info);
7268 })
7269 .Case<PackageOp>([&](PackageOp package) {
7270 // Build the IR cache.
7271 auto sym = package.getSymNameAttr();
7272 symbolCache.addDefinition(sym, package);
7273
7274 if (auto it = symbolsToFiles.find(sym); it != symbolsToFiles.end()) {
7275 if (it->second.size() != 1 || attr) {
7276 package.emitError(
7277 "packages can only be emitted to a single file");
7278 encounteredError = true;
7279 }
7280 // Otherwise the package is pulled into the file operation which
7281 // references it.
7282 return;
7283 }
7284
7285 // Emit into a separate file named after the package.
7286 if (attr || separateModules)
7287 separateFile(package, getSymOpName(package) + ".sv");
7288 else
7289 rootFile.ops.push_back(info);
7290 })
7291 .Case<PackageExternOp>([&](PackageExternOp package) {
7292 symbolCache.addDefinition(package.getSymNameAttr(), package);
7293 })
7294 .Case<sv::SVVerbatimSourceOp>([&](sv::SVVerbatimSourceOp op) {
7295 symbolCache.addDefinition(op.getNameAttr(), op);
7296 separateFile(op, op.getOutputFile().getFilename().getValue());
7297 })
7298 .Case<HWModuleExternOp, sv::SVVerbatimModuleOp>([&](auto op) {
7299 // Build the IR cache.
7300 symbolCache.addDefinition(op.getNameAttr(), op);
7301 collectPorts(op);
7302 // External modules are _not_ emitted.
7303 })
7304 .Case<VerbatimOp, IfDefOp, MacroDefOp, IncludeOp, FuncDPIImportOp>(
7305 [&](Operation *op) {
7306 // Emit into a separate file using the specified file name or
7307 // replicate the operation in each outputfile.
7308 if (!attr) {
7309 replicatedOps.push_back(op);
7310 } else
7311 separateFile(op, "");
7312 })
7313 .Case<FuncOp>([&](auto op) {
7314 // Emit into a separate file using the specified file name or
7315 // replicate the operation in each outputfile.
7316 if (!attr) {
7317 replicatedOps.push_back(op);
7318 } else
7319 separateFile(op, "");
7320
7321 symbolCache.addDefinition(op.getNameAttr(), op);
7322 })
7323 .Case<HWGeneratorSchemaOp>([&](HWGeneratorSchemaOp schemaOp) {
7324 symbolCache.addDefinition(schemaOp.getNameAttr(), schemaOp);
7325 })
7326 .Case<HierPathOp>([&](HierPathOp hierPathOp) {
7327 symbolCache.addDefinition(hierPathOp.getSymNameAttr(), hierPathOp);
7328 })
7329 .Case<TypeScopeOp>([&](TypeScopeOp op) {
7330 symbolCache.addDefinition(op.getSymNameAttr(), op);
7331 // TODO: How do we want to handle typedefs in a split output?
7332 if (!attr) {
7333 replicatedOps.push_back(op);
7334 } else
7335 separateFile(op, "");
7336 })
7337 .Case<BindOp>([&](auto op) {
7338 if (!attr) {
7339 separateFile(op, "bindfile.sv");
7340 } else {
7341 separateFile(op);
7342 }
7343 })
7344 .Case<MacroErrorOp>([&](auto op) { replicatedOps.push_back(op); })
7345 .Case<MacroDeclOp>([&](auto op) {
7346 symbolCache.addDefinition(op.getSymNameAttr(), op);
7347 })
7348 .Case<sv::ReserveNamesOp>([](auto op) {
7349 // This op was already used in gathering used names.
7350 })
7351 .Case<om::ClassLike>([&](auto op) {
7352 symbolCache.addDefinition(op.getSymNameAttr(), op);
7353 })
7354 .Case<om::ConstantOp>([&](auto op) {
7355 // Constant ops might reference symbols, skip them.
7356 })
7357 .Default([&](auto *) {
7358 op.emitError("unknown operation (SharedEmitterState::gatherFiles)");
7359 encounteredError = true;
7360 });
7361 }
7362
7363 // We've built the whole symbol cache. Freeze it so things can start
7364 // querying it (potentially concurrently).
7365 symbolCache.freeze();
7366}
7367
7368/// Given a FileInfo, collect all the replicated and designated operations
7369/// that go into it and append them to "thingsToEmit".
7371 EmissionList &thingsToEmit,
7372 bool emitHeader) {
7373 // Include the version string comment when the file is verilog.
7374 if (file.isVerilog && !options.omitVersionComment)
7375 thingsToEmit.emplace_back(circt::getCirctVersionComment());
7376
7377 // If we're emitting replicated ops, keep track of where we are in the list.
7378 size_t lastReplicatedOp = 0;
7379
7380 bool emitHeaderInclude =
7381 emitHeader && file.emitReplicatedOps && !file.isHeader;
7382
7383 if (emitHeaderInclude)
7384 thingsToEmit.emplace_back(circtHeaderInclude);
7385
7386 size_t numReplicatedOps =
7387 file.emitReplicatedOps && !emitHeaderInclude ? replicatedOps.size() : 0;
7388
7389 // Emit each operation in the file preceded by the replicated ops not yet
7390 // printed.
7391 DenseSet<emit::FragmentOp> includedFragments;
7392 for (const auto &opInfo : file.ops) {
7393 Operation *op = opInfo.op;
7394
7395 // Emit the replicated per-file operations before the main operation's
7396 // position (if enabled).
7397 for (; lastReplicatedOp < std::min(opInfo.position, numReplicatedOps);
7398 ++lastReplicatedOp)
7399 thingsToEmit.emplace_back(replicatedOps[lastReplicatedOp]);
7400
7401 // Pull in the fragments that the op references. In one file, each
7402 // fragment is emitted only once.
7403 if (auto fragments =
7404 op->getAttrOfType<ArrayAttr>(emit::getFragmentsAttrName())) {
7405 for (auto sym : fragments.getAsRange<FlatSymbolRefAttr>()) {
7406 auto it = fragmentMapping.find(sym.getAttr());
7407 if (it == fragmentMapping.end()) {
7408 encounteredError = true;
7409 op->emitError("cannot find referenced fragment ") << sym;
7410 continue;
7411 }
7412 emit::FragmentOp fragment = it->second;
7413 if (includedFragments.insert(fragment).second) {
7414 thingsToEmit.emplace_back(it->second);
7415 }
7416 }
7417 }
7418
7419 // Emit the operation itself.
7420 thingsToEmit.emplace_back(op);
7421 }
7422
7423 // Emit the replicated per-file operations after the last operation (if
7424 // enabled).
7425 for (; lastReplicatedOp < numReplicatedOps; lastReplicatedOp++)
7426 thingsToEmit.emplace_back(replicatedOps[lastReplicatedOp]);
7427}
7428
7429static void emitOperation(VerilogEmitterState &state, Operation *op) {
7430 TypeSwitch<Operation *>(op)
7431 .Case<HWModuleOp>([&](auto op) { ModuleEmitter(state).emitHWModule(op); })
7432 .Case<HWModuleExternOp, sv::SVVerbatimModuleOp, PackageExternOp>(
7433 [&](auto op) {
7434 // External declarations are _not_ emitted.
7435 })
7436 .Case<HWModuleGeneratedOp>(
7437 [&](auto op) { ModuleEmitter(state).emitHWGeneratedModule(op); })
7438 .Case<HWGeneratorSchemaOp>([&](auto op) { /* Empty */ })
7439 .Case<BindOp>([&](auto op) { ModuleEmitter(state).emitBind(op); })
7440 .Case<InterfaceOp, VerbatimOp, IfDefOp, sv::SVVerbatimSourceOp>(
7441 [&](auto op) { ModuleEmitter(state).emitStatement(op); })
7442 .Case<TypeScopeOp, PackageOp>([&](auto typedecls) {
7443 ModuleEmitter(state).emitStatement(typedecls);
7444 })
7445 .Case<emit::FileOp, emit::FileListOp, emit::FragmentOp>(
7446 [&](auto op) { FileEmitter(state).emit(op); })
7447 .Case<MacroErrorOp, MacroDefOp, FuncDPIImportOp>(
7448 [&](auto op) { ModuleEmitter(state).emitStatement(op); })
7449 .Case<FuncOp>([&](auto op) { ModuleEmitter(state).emitFunc(op); })
7450 .Case<IncludeOp>([&](auto op) { ModuleEmitter(state).emitStatement(op); })
7451 .Default([&](auto *op) {
7452 state.encounteredError = true;
7453 op->emitError("unknown operation (ExportVerilog::emitOperation)");
7454 });
7455}
7456
7457/// Actually emit the collected list of operations and strings to the
7458/// specified file.
7460 llvm::formatted_raw_ostream &os,
7461 StringAttr fileName, bool parallelize) {
7462 MLIRContext *context = designOp->getContext();
7463
7464 // Disable parallelization overhead if MLIR threading is disabled.
7465 if (parallelize)
7466 parallelize &= context->isMultithreadingEnabled();
7467
7468 // If we aren't parallelizing output, directly output each operation to the
7469 // specified stream.
7470 if (!parallelize) {
7471 // All the modules share the same map to store the verilog output location
7472 // on the stream.
7473 OpLocMap verilogLocMap(os);
7474 VerilogEmitterState state(designOp, *this, options, symbolCache,
7475 globalNames, fileMapping, os, fileName,
7476 verilogLocMap);
7477 size_t lineOffset = 0;
7478 for (auto &entry : thingsToEmit) {
7479 entry.verilogLocs.setStream(os);
7480 if (auto *op = entry.getOperation()) {
7481 emitOperation(state, op);
7482 // Since the modules are exported sequentially, update all the ops with
7483 // the verilog location. This also clears the map, so that the map only
7484 // contains the current iteration's ops.
7485 state.addVerilogLocToOps(lineOffset, fileName);
7486 } else {
7487 os << entry.getStringData();
7488 ++lineOffset;
7489 }
7490 }
7491
7492 if (state.encounteredError)
7493 encounteredError = true;
7494 return;
7495 }
7496
7497 // If we are parallelizing emission, we emit each independent operation to a
7498 // string buffer in parallel, then concat at the end.
7499 parallelForEach(context, thingsToEmit, [&](StringOrOpToEmit &stringOrOp) {
7500 auto *op = stringOrOp.getOperation();
7501 if (!op)
7502 return; // Ignore things that are already strings.
7503
7504 // BindOp emission reaches into the hw.module of the instance, and that
7505 // body may be being transformed by its own emission. Defer their
7506 // emission to the serial phase. They are speedy to emit anyway.
7507 if (isa<BindOp>(op) || modulesContainingBinds.count(op))
7508 return;
7509
7510 SmallString<256> buffer;
7511 llvm::raw_svector_ostream tmpStream(buffer);
7512 llvm::formatted_raw_ostream rs(tmpStream);
7513 // Each `thingToEmit` (op) uses a unique map to store verilog locations.
7514 stringOrOp.verilogLocs.setStream(rs);
7515 VerilogEmitterState state(designOp, *this, options, symbolCache,
7516 globalNames, fileMapping, rs, fileName,
7517 stringOrOp.verilogLocs);
7518 emitOperation(state, op);
7519 stringOrOp.setString(buffer);
7520 if (state.encounteredError)
7521 encounteredError = true;
7522 });
7523
7524 // Finally emit each entry now that we know it is a string.
7525 for (auto &entry : thingsToEmit) {
7526 // Almost everything is lowered to a string, just concat the strings onto
7527 // the output stream.
7528 auto *op = entry.getOperation();
7529 if (!op) {
7530 auto lineOffset = os.getLine() + 1;
7531 os << entry.getStringData();
7532 // Ensure the line numbers are offset properly in the map. Each `entry`
7533 // was exported in parallel onto independent string streams, hence the
7534 // line numbers need to be updated with the offset in the current stream.
7535 entry.verilogLocs.updateIRWithLoc(lineOffset, fileName, context);
7536 continue;
7537 }
7538 entry.verilogLocs.setStream(os);
7539
7540 // If this wasn't emitted to a string (e.g. it is a bind) do so now.
7541 VerilogEmitterState state(designOp, *this, options, symbolCache,
7542 globalNames, fileMapping, os, fileName,
7543 entry.verilogLocs);
7544 emitOperation(state, op);
7545 state.addVerilogLocToOps(0, fileName);
7546 if (state.encounteredError) {
7547 encounteredError = true;
7548 return;
7549 }
7550 }
7551}
7552
7553//===----------------------------------------------------------------------===//
7554// Unified Emitter
7555//===----------------------------------------------------------------------===//
7556
7557static LogicalResult exportVerilogImpl(ModuleOp module, llvm::raw_ostream &os) {
7558 LoweringOptions options(module);
7559 GlobalNameTable globalNames = legalizeGlobalNames(module, options);
7560
7561 SharedEmitterState emitter(module, options, std::move(globalNames));
7562 emitter.gatherFiles(false);
7563
7565 module.emitWarning()
7566 << "`emitReplicatedOpsToHeader` option is enabled but an header is "
7567 "created only at SplitExportVerilog";
7568
7570
7571 // Collect the contents of the main file. This is a container for anything
7572 // not explicitly split out into a separate file.
7573 emitter.collectOpsForFile(emitter.rootFile, list);
7574
7575 // Emit the separate files.
7576 for (const auto &it : emitter.files) {
7577 list.emplace_back("\n// ----- 8< ----- FILE \"" + it.first.str() +
7578 "\" ----- 8< -----\n\n");
7579 emitter.collectOpsForFile(it.second, list);
7580 }
7581
7582 // Emit the filelists.
7583 for (auto &it : emitter.fileLists) {
7584 std::string contents("\n// ----- 8< ----- FILE \"" + it.first().str() +
7585 "\" ----- 8< -----\n\n");
7586 for (auto &name : it.second)
7587 contents += name.str() + "\n";
7588 list.emplace_back(contents);
7589 }
7590
7591 llvm::formatted_raw_ostream rs(os);
7592 // Finally, emit all the ops we collected.
7593 // output file name is not known, it can be specified as command line
7594 // argument.
7595 emitter.emitOps(list, rs, StringAttr::get(module.getContext(), ""),
7596 /*parallelize=*/true);
7597 return failure(emitter.encounteredError);
7598}
7599
7600LogicalResult circt::exportVerilog(ModuleOp module, llvm::raw_ostream &os) {
7601 LoweringOptions options(module);
7602 SmallVector<HWEmittableModuleLike> modulesToPrepare;
7603 module.walk(
7604 [&](HWEmittableModuleLike op) { modulesToPrepare.push_back(op); });
7605 if (failed(failableParallelForEach(
7606 module->getContext(), modulesToPrepare,
7607 [&](auto op) { return prepareHWModule(op, options); })))
7608 return failure();
7609 return exportVerilogImpl(module, os);
7610}
7611
7612namespace {
7613
7614struct ExportVerilogPass
7615 : public circt::impl::ExportVerilogBase<ExportVerilogPass> {
7616 ExportVerilogPass(raw_ostream &os) : os(os) {}
7617 void runOnOperation() override {
7618 // Prepare the ops in the module for emission.
7619 mlir::OpPassManager preparePM("builtin.module");
7620 preparePM.addPass(createLegalizeAnonEnums());
7621 auto &modulePM = preparePM.nestAny();
7622 modulePM.addPass(createPrepareForEmission());
7623 if (failed(runPipeline(preparePM, getOperation())))
7624 return signalPassFailure();
7625
7626 if (failed(exportVerilogImpl(getOperation(), os)))
7627 return signalPassFailure();
7628 }
7629
7630private:
7631 raw_ostream &os;
7632};
7633
7634struct ExportVerilogStreamOwnedPass : public ExportVerilogPass {
7635 ExportVerilogStreamOwnedPass(std::unique_ptr<llvm::raw_ostream> os)
7636 : ExportVerilogPass{*os} {
7637 owned = std::move(os);
7638 }
7639
7640private:
7641 std::unique_ptr<llvm::raw_ostream> owned;
7642};
7643} // end anonymous namespace
7644
7645std::unique_ptr<mlir::Pass>
7646circt::createExportVerilogPass(std::unique_ptr<llvm::raw_ostream> os) {
7647 return std::make_unique<ExportVerilogStreamOwnedPass>(std::move(os));
7648}
7649
7650std::unique_ptr<mlir::Pass>
7651circt::createExportVerilogPass(llvm::raw_ostream &os) {
7652 return std::make_unique<ExportVerilogPass>(os);
7653}
7654
7655std::unique_ptr<mlir::Pass> circt::createExportVerilogPass() {
7656 return createExportVerilogPass(llvm::outs());
7657}
7658
7659//===----------------------------------------------------------------------===//
7660// Split Emitter
7661//===----------------------------------------------------------------------===//
7662
7663static std::unique_ptr<llvm::ToolOutputFile>
7664createOutputFile(StringRef fileName, StringRef dirname,
7665 SharedEmitterState &emitter) {
7666 // Determine the output path from the output directory and filename.
7667 SmallString<128> outputFilename(dirname);
7668 appendPossiblyAbsolutePath(outputFilename, fileName);
7669 auto outputDir = llvm::sys::path::parent_path(outputFilename);
7670
7671 // Create the output directory if needed.
7672 std::error_code error = llvm::sys::fs::create_directories(outputDir);
7673 if (error) {
7674 emitter.designOp.emitError("cannot create output directory \"")
7675 << outputDir << "\": " << error.message();
7676 emitter.encounteredError = true;
7677 return {};
7678 }
7679
7680 // Open the output file.
7681 std::string errorMessage;
7682 auto output = mlir::openOutputFile(outputFilename, &errorMessage);
7683 if (!output) {
7684 emitter.designOp.emitError(errorMessage);
7685 emitter.encounteredError = true;
7686 }
7687 return output;
7688}
7689
7690static void createSplitOutputFile(StringAttr fileName, FileInfo &file,
7691 StringRef dirname,
7692 SharedEmitterState &emitter) {
7693 auto output = createOutputFile(fileName, dirname, emitter);
7694 if (!output)
7695 return;
7696
7698 emitter.collectOpsForFile(file, list,
7700
7701 llvm::formatted_raw_ostream rs(output->os());
7702 // Emit the file, copying the global options into the individual module
7703 // state. Don't parallelize emission of the ops within this file - we
7704 // already parallelize per-file emission and we pay a string copy overhead
7705 // for parallelization.
7706 emitter.emitOps(list, rs,
7707 StringAttr::get(fileName.getContext(), output->getFilename()),
7708 /*parallelize=*/false);
7709 output->keep();
7710}
7711
7712static LogicalResult exportSplitVerilogImpl(ModuleOp module,
7713 StringRef dirname) {
7714 // Prepare the ops in the module for emission and legalize the names that will
7715 // end up in the output.
7716 LoweringOptions options(module);
7717 GlobalNameTable globalNames = legalizeGlobalNames(module, options);
7718
7719 SharedEmitterState emitter(module, options, std::move(globalNames));
7720 emitter.gatherFiles(true);
7721
7722 if (emitter.options.emitReplicatedOpsToHeader) {
7723 // Add a header to the file list.
7724 bool insertSuccess =
7725 emitter.files
7726 .insert({StringAttr::get(module.getContext(), circtHeader),
7727 FileInfo{/*ops*/ {},
7728 /*emitReplicatedOps*/ true,
7729 /*addToFilelist*/ true,
7730 /*isHeader*/ true}})
7731 .second;
7732 if (!insertSuccess) {
7733 module.emitError() << "tried to emit a heder to " << circtHeader
7734 << ", but the file is used as an output too.";
7735 return failure();
7736 }
7737 }
7738
7739 // Emit each file in parallel if context enables it.
7740 parallelForEach(module->getContext(), emitter.files.begin(),
7741 emitter.files.end(), [&](auto &it) {
7742 createSplitOutputFile(it.first, it.second, dirname,
7743 emitter);
7744 });
7745
7746 // Write the file list.
7747 SmallString<128> filelistPath(dirname);
7748 llvm::sys::path::append(filelistPath, "filelist.f");
7749
7750 std::string errorMessage;
7751 auto output = mlir::openOutputFile(filelistPath, &errorMessage);
7752 if (!output) {
7753 module->emitError(errorMessage);
7754 return failure();
7755 }
7756
7757 for (const auto &it : emitter.files) {
7758 if (it.second.addToFilelist)
7759 output->os() << it.first.str() << "\n";
7760 }
7761 output->keep();
7762
7763 // Emit the filelists.
7764 for (auto &it : emitter.fileLists) {
7765 auto output = createOutputFile(it.first(), dirname, emitter);
7766 if (!output)
7767 continue;
7768 for (auto &name : it.second)
7769 output->os() << name.str() << "\n";
7770 output->keep();
7771 }
7772
7773 return failure(emitter.encounteredError);
7774}
7775
7776LogicalResult circt::exportSplitVerilog(ModuleOp module, StringRef dirname) {
7777 LoweringOptions options(module);
7778 SmallVector<HWEmittableModuleLike> modulesToPrepare;
7779 module.walk(
7780 [&](HWEmittableModuleLike op) { modulesToPrepare.push_back(op); });
7781 if (failed(failableParallelForEach(
7782 module->getContext(), modulesToPrepare,
7783 [&](auto op) { return prepareHWModule(op, options); })))
7784 return failure();
7785
7786 return exportSplitVerilogImpl(module, dirname);
7787}
7788
7789namespace {
7790
7791struct ExportSplitVerilogPass
7792 : public circt::impl::ExportSplitVerilogBase<ExportSplitVerilogPass> {
7793 ExportSplitVerilogPass(StringRef directory) {
7794 directoryName = directory.str();
7795 }
7796 void runOnOperation() override {
7797 // Prepare the ops in the module for emission.
7798 mlir::OpPassManager preparePM("builtin.module");
7799
7800 auto &modulePM = preparePM.nest<hw::HWModuleOp>();
7801 modulePM.addPass(createPrepareForEmission());
7802 if (failed(runPipeline(preparePM, getOperation())))
7803 return signalPassFailure();
7804
7805 if (failed(exportSplitVerilogImpl(getOperation(), directoryName)))
7806 return signalPassFailure();
7807 }
7808};
7809} // end anonymous namespace
7810
7811std::unique_ptr<mlir::Pass>
7812circt::createExportSplitVerilogPass(StringRef directory) {
7813 return std::make_unique<ExportSplitVerilogPass>(directory);
7814}
assert(baseType &&"element must be base type")
MlirType elementType
Definition CHIRRTL.cpp:29
static SmallVector< T > concat(const SmallVectorImpl< T > &a, const SmallVectorImpl< T > &b)
Returns a new vector containing the concatenation of vectors a and b.
Definition CalyxOps.cpp:555
static bool hasSVAttributes(Operation *op)
Definition CombFolds.cpp:69
static void emitOperation(VerilogEmitterState &state, Operation *op)
static LogicalResult exportVerilogImpl(ModuleOp module, llvm::raw_ostream &os)
static void emitDim(Attribute width, raw_ostream &os, Location loc, ModuleEmitter &emitter, bool downTo)
Emit a single dimension.
static int compareLocs(Location lhs, Location rhs)
static bool isDuplicatableExpression(Operation *op)
static TypedAttr getInt32Attr(MLIRContext *ctx, uint32_t value)
StringRef getVerilogValueName(Value val)
Retrieve value's verilog name from IR.
static void sortLocationVector(TVector &vec)
static bool hasStructType(Type type)
Return true if the element type is emitted as a type name or a keyword (struct, union,...
static StringRef getVerilogDeclWord(Operation *op, const ModuleEmitter &emitter)
Return the word (e.g.
static bool isOkToBitSelectFrom(Value v)
Most expressions are invalid to bit-select from in Verilog, but some things are ok.
static LogicalResult exportSplitVerilogImpl(ModuleOp module, StringRef dirname)
static int compareLocsImpl(mlir::NameLoc lhs, mlir::NameLoc rhs)
static void emitZeroWidthIndexingValue(PPS &os)
Emits a known-safe token that is legal when indexing into singleton arrays.
static bool checkDominanceOfUsers(Operation *op1, Operation *op2)
Return true if op1 dominates users of op2.
static void emitDims(ArrayRef< Attribute > dims, raw_ostream &os, Location loc, ModuleEmitter &emitter)
Emit a list of packed dimensions.
static bool isExpressionEmittedInlineIntoProceduralDeclaration(Operation *op, StmtEmitter &stmtEmitter)
Given an operation corresponding to a VerilogExpression, determine whether it is safe to emit inline ...
StringRef circtHeader
static StringRef getPortVerilogName(Operation *module, size_t portArgNum)
Return the verilog name of the port for the module.
BlockStatementCount
static void collectAndUniqueLocations(Location loc, SmallPtrSetImpl< Attribute > &locationSet)
Pull apart any fused locations into the location set, such that they are uniqued.
static Value isZeroExtension(Value value)
If the specified extension is a zero extended version of another value, return the shorter value,...
static void createSplitOutputFile(StringAttr fileName, FileInfo &file, StringRef dirname, SharedEmitterState &emitter)
static StringRef getInputPortVerilogName(Operation *module, size_t portArgNum)
Return the verilog name of the port for the module.
static StringRef getTwoStateIntegerAtomType(size_t width)
Return a 2-state integer atom type name if the width matches.
static TypedAttr getIntAttr(MLIRContext *ctx, Type t, const APInt &value)
static BlockStatementCount countStatements(Block &block)
Compute how many statements are within this block, for begin/end markers.
static Type stripUnpackedTypes(Type type)
Given a set of known nested types (those supported by this pass), strip off leading unpacked types.
FailureOr< int > dispatchCompareLocations(Location lhs, Location rhs)
static bool haveMatchingDims(Type a, Type b, Location loc, llvm::function_ref< mlir::InFlightDiagnostic(Location)> errorHandler)
True iff 'a' and 'b' have the same wire dims.
static void getTypeDims(SmallVectorImpl< Attribute > &dims, Type type, Location loc, llvm::function_ref< mlir::InFlightDiagnostic(Location)> errorHandler)
Push this type's dimension into a vector.
static bool isExpressionUnableToInline(Operation *op, const LoweringOptions &options)
Return true if we are unable to ever inline the specified operation.
void emitFunctionSignature(ModuleEmitter &emitter, PPS &ps, FuncOp op, bool isAutomatic=false, bool emitAsTwoStateType=false)
static AssignTy getSingleAssignAndCheckUsers(Operation *op)
static bool hasLeadingUnpackedType(Type type)
Return true if the type has a leading unpacked type.
static bool printPackedTypeImpl(Type type, raw_ostream &os, Location loc, SmallVectorImpl< Attribute > &dims, bool implicitIntType, bool singleBitDefaultType, ModuleEmitter &emitter, Type optionalAliasType={}, bool emitAsTwoStateType=false)
Output the basic type that consists of packed and primitive types.
static void emitSVAttributesImpl(PPS &ps, ArrayAttr attrs, bool mayBreak)
Emit SystemVerilog attributes.
static bool hasExplicitDataType(Type type)
Returns true if type prints its own SystemVerilog data_type, so its declaration must not be prefixed ...
static bool isDuplicatableNullaryExpression(Operation *op)
Return true for nullary operations that are better emitted multiple times as inline expression (when ...
static IfOp findNestedElseIf(Block *elseBlock)
Find a nested IfOp in an else block that can be printed as else if instead of nesting it into a new b...
StringRef circtHeaderInclude
static ValueRange getNonOverlappingConcatSubrange(Value value)
For a value concat(..., delay(const(true), 1, 0)), return ....
static std::unique_ptr< Context > context
static StringRef legalizeName(StringRef name, llvm::StringMap< size_t > &nextGeneratedNameIDs)
Legalize the given name such that it only consists of valid identifier characters in Verilog and does...
#define isdigit(x)
Definition FIRLexer.cpp:26
static void printParamValue(OpAsmPrinter &p, Operation *, Attribute value, Type resultType)
Definition HWOps.cpp:545
static SmallVector< PortInfo > getPortList(ModuleTy &mod)
Definition HWOps.cpp:1488
false return failure()
Parse an optional keyword or string and set instance into 'result'.
return success()
NamedAttrList attrs
static InstancePath empty
void emit(emit::FragmentOp op)
FileEmitter(VerilogEmitterState &state)
void emit(emit::FileOp op)
void emitOp(emit::RefOp op)
LocationEmitter(LoweringOptions::LocationInfoStyle style, Location loc)
void emitLocationSetInfo(llvm::raw_string_ostream &os, LoweringOptions::LocationInfoStyle style, const SmallPtrSetImpl< Attribute > &locationSet)
LocationEmitter(LoweringOptions::LocationInfoStyle style, const SmallPtrSetImpl< Operation * > &ops)
Track the output verilog line,column number information for every op.
void setStream(llvm::formatted_raw_ostream &f)
Set the output stream.
This class wraps an operation or a fixed string that should be emitted.
Operation * getOperation() const
If the value is an Operation*, return it. Otherwise return null.
OpLocMap verilogLocs
Verilog output location information for entry.
void setString(StringRef value)
This method transforms the entry from an operation to a string value.
Signals that an operation's regions are procedural.
HWSymbolCache::Item getInnerDefinition(mlir::StringAttr modSymbol, mlir::StringAttr name) const
Definition HWSymCache.h:66
mlir::Operation * getDefinition(mlir::Attribute attr) const override
Lookup a definition for 'symbol' in the cache.
Definition HWSymCache.h:57
DenseMap< StringAttr, Operation * > FileMapping
Mapping from symbols to file operations.
bool isExpressionEmittedInline(Operation *op, const LoweringOptions &options)
Return true if this expression should be emitted inline into any statement that uses it.
bool isVerilogExpression(Operation *op)
This predicate returns true if the specified operation is considered a potentially inlinable Verilog ...
GlobalNameTable legalizeGlobalNames(ModuleOp topLevel, const LoweringOptions &options)
Rewrite module names and interfaces to not conflict with each other or with Verilog keywords.
StringAttr inferStructuralNameForTemporary(Value expr)
Given an expression that is spilled into a temporary wire, try to synthesize a better name than "_T_4...
static bool isConstantExpression(Operation *op)
Return whether an operation is a constant.
bool isZeroBitType(Type type)
Return true if this is a zero bit type, e.g.
StringRef getSymOpName(Operation *symOp)
Return the verilog name of the operations that can define a symbol.
StringRef getFragmentsAttrName()
Return the name of the fragments array attribute.
Definition EmitOps.h:30
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
BaseTy type_cast(Type type)
Definition HWTypes.h:222
bool isCombinational(Operation *op)
Return true if the specified operation is a combinational logic op.
Definition HWOps.cpp:57
StringRef getVerilogModuleName(Operation *module)
Definition HWOps.h:56
BaseTy type_dyn_cast(Type type)
Definition HWTypes.h:234
StringAttr getVerilogModuleNameAttr(Operation *module)
Returns the verilog module name attribute or symbol name of any module-like operations.
Definition HWOps.cpp:591
mlir::Type getCanonicalType(mlir::Type type)
Recursively remove HW type aliases from a type and its subelements.
Definition HWTypes.cpp:51
void info(Twine message)
Definition LSPUtils.cpp:20
PP
Send one of these to TokenStream to add the corresponding token.
mlir::ArrayAttr getSVAttributes(mlir::Operation *op)
Return all the SV attributes of an operation, or null if there are none.
char getLetter(CasePatternBit bit)
Return the letter for the specified pattern bit, e.g. "0", "1", "x" or "z".
Definition SVOps.cpp:947
circt::hw::InOutType InOutType
Definition SVTypes.h:25
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
std::unique_ptr< mlir::Pass > createExportSplitVerilogPass(llvm::StringRef directory="./")
mlir::LogicalResult exportVerilog(mlir::ModuleOp module, llvm::raw_ostream &os)
Export a module containing HW, and SV dialect code.
mlir::LogicalResult exportSplitVerilog(mlir::ModuleOp module, llvm::StringRef dirname)
Export a module containing HW, and SV dialect code, as one file per SV module.
const char * getCirctVersionComment()
std::unique_ptr< llvm::ToolOutputFile > createOutputFile(StringRef filename, StringRef dirname, function_ref< InFlightDiagnostic()> emitError)
Creates an output file with the given filename in the specified directory.
Definition Path.cpp:55
std::unique_ptr< mlir::Pass > createExportVerilogPass()
void appendPossiblyAbsolutePath(llvm::SmallVectorImpl< char > &base, const llvm::Twine &suffix)
Append a path to an existing path, replacing it if the other path is absolute.
Definition Path.cpp:26
Definition comb.py:1
Definition emit.py:1
Definition hw.py:1
Definition sv.py:1
llvm::raw_string_ostream & os
void emitLocationInfo(Location loc)
Return the location information in the specified style.
Impl(llvm::raw_string_ostream &os, LoweringOptions::LocationInfoStyle style, const SmallPtrSetImpl< Attribute > &locationSet)
void emitLocationInfo(FileLineColLoc loc)
void emitLocationSetInfoImpl(const SmallPtrSetImpl< Attribute > &locationSet)
Emit the location information of locationSet to sstr.
void emitLocationInfo(mlir::NameLoc loc)
LoweringOptions::LocationInfoStyle style
void emitLocationInfo(mlir::CallSiteLoc loc)
void printFileLineColSetInfo(llvm::SmallVector< FileLineColLoc, 8 > locVector)
StringAttr getRenamedFieldName(StringAttr fieldName)
std::string getEnumFieldName(hw::EnumFieldAttr attr, Operation *currentPackage=nullptr)
Returns the field name for an enum field of a given enum field attr.
Information to control the emission of a list of operations into a file.
bool isVerilog
If true, the file is known to be (system) verilog source code.
SmallVector< OpFileInfo, 1 > ops
The operations to be emitted into a separate file, and where among the replicated per-file operations...
bool isHeader
If true, the file is a header.
bool emitReplicatedOps
Whether to emit the replicated per-file operations.
This class keeps track of global names at the module/interface level.
StringRef getParameterVerilogName(Operation *module, StringAttr paramName) const
Return the string to use for the specified parameter name in the specified module.
Information to control the emission of a single operation into a file.
This class tracks the top-level state for the emitters, which is built and then shared across all per...
llvm::MapVector< StringAttr, FileInfo > files
The additional files to emit, with the output file name as the key into the map.
std::vector< StringOrOpToEmit > EmissionList
FileMapping fileMapping
Tracks the referenceable files through their symbol.
hw::HWSymbolCache symbolCache
A cache of symbol -> defining ops built once and used by each of the verilog module emitters.
void collectOpsForFile(const FileInfo &fileInfo, EmissionList &thingsToEmit, bool emitHeader=false)
Given a FileInfo, collect all the replicated and designated operations that go into it and append the...
ModuleOp designOp
The MLIR module to emit.
void emitOps(EmissionList &thingsToEmit, llvm::formatted_raw_ostream &os, StringAttr fileName, bool parallelize)
Actually emit the collected list of operations and strings to the specified file.
FileInfo rootFile
The main file that collects all operations that are neither replicated per-file ops nor specifically ...
llvm::StringMap< SmallVector< StringAttr > > fileLists
The various file lists and their contents to emit.
SmallPtrSet< Operation *, 8 > modulesContainingBinds
This is a set is populated at "gather" time, containing the hw.module operations that have a sv....
std::atomic< bool > encounteredError
Whether any error has been encountered during emission.
FragmentMapping fragmentMapping
Tracks referenceable files through their symbol.
void gatherFiles(bool separateModules)
Organize the operations in the root MLIR module into output files to be generated.
SmallVector< Operation *, 0 > replicatedOps
A list of operations replicated in each output file (e.g., sv.verbatim or sv.ifdef without dedicated ...
const GlobalNameTable globalNames
Information about renamed global symbols, parameters, etc.
Options which control the emission from CIRCT to Verilog.
bool noAlwaysComb
If true, emits sv.alwayscomb as Verilog always @(*) statements.
bool printDebugInfo
Print debug info.
LocationInfoStyle
This option controls emitted location information style.
enum circt::LoweringOptions::EmitPortType emitPortType
bool disallowPortDeclSharing
If true, every port is declared separately (each includes direction and type (e.g....
std::optional< unsigned > getEmittedLineLength() const
Return std::nullopt if not wrapping, else the target emission line length.
bool explicitBitcast
Add an explicit bitcast for avoiding bitwidth mismatch LINT errors.
bool disallowReplicate
If true, expand comb.replicate into an explicit concatenation instead of emitting the {N{....
bool disallowMuxInlining
If true, every mux expression is spilled to a wire.
bool caseInsensitiveKeywords
If true, then unique names that collide with keywords case insensitively.
bool alwaysEmitBeginEnd
If true, always emit begin/end blocks around if/else/always bodies, even when there is only a single ...
bool emitReplicatedOpsToHeader
If true, replicated ops are emitted to a header file.
bool allowExprInEventControl
If true, expressions are allowed in the sensitivity list of always statements, otherwise they are for...
bool emitBindComments
If true, emit a comment wherever an instance wasn't printed, because it's emitted elsewhere as a bind...
This holds a decoded list of input/inout and output ports for a module or instance.
PortInfo & at(size_t idx)
PortDirectionRange getOutputs()
mlir::Type type
Definition HWTypes.h:34
StringRef getVerilogName() const
InnerSymAttr getSym() const
SmallVectorImpl< Token > BufferVec
void flush(PrettyPrinter &pp)
Flush buffered tokens to the specified pretty printer.
String wrapper to indicate string has external storage.