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"
61#define GEN_PASS_DEF_EXPORTSPLITVERILOG
62#define GEN_PASS_DEF_EXPORTVERILOG
63#include "circt/Conversion/Passes.h.inc"
74#define DEBUG_TYPE "export-verilog"
82enum VerilogPrecedence {
103enum SubExprSignResult { IsSigned, IsUnsigned };
109 VerilogPrecedence precedence;
112 SubExprSignResult signedness;
114 SubExprInfo(VerilogPrecedence precedence, SubExprSignResult signedness)
115 : precedence(precedence), signedness(signedness) {}
125 return Builder(ctx).getI32IntegerAttr(value);
128static TypedAttr
getIntAttr(MLIRContext *ctx, Type t,
const APInt &value) {
129 return Builder(ctx).getIntegerAttr(t, value);
145 if (isa<VerbatimExprOp>(op)) {
146 if (op->getNumOperands() == 0 &&
147 op->getAttrOfType<StringAttr>(
"format_string").getValue().size() <= 32)
152 if (isa<XMRRefOp>(op))
156 if (isa<MacroRefExprOp>(op))
166 if (op->getNumOperands() == 0)
170 if (isa<comb::ExtractOp, hw::StructExtractOp, hw::UnionExtractOp>(op))
174 if (
auto array = dyn_cast<hw::ArrayGetOp>(op)) {
175 auto *indexOp = array.getIndex().getDefiningOp();
176 if (!indexOp || isa<ConstantOp>(indexOp))
178 if (
auto read = dyn_cast<ReadInOutOp>(indexOp)) {
179 auto *readSrc = read.getInput().getDefiningOp();
181 return !readSrc || isa<sv::WireOp, LogicOp, sv::VarOp>(readSrc);
196 if (
auto attr = symOp->getAttrOfType<StringAttr>(
"hw.verilogName"))
197 return attr.getValue();
198 return TypeSwitch<Operation *, StringRef>(symOp)
203 return op.getVerilogNameAttr().getValue();
205 .Case<PackageExternOp>([](PackageExternOp op) {
206 return op.getVerilogName().value_or(op.getSymName());
208 .Case<InterfaceOp>([&](InterfaceOp op) {
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(
"");
230template <
typename PPS>
232 os <<
"/*Zero width*/ 1\'b0";
237 auto hml = cast<HWModuleLike>(module);
238 return hml.getPort(portArgNum).getVerilogName();
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);
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))
265 if (isa<verif::ContractOp>(op))
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()));
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);
289 if (
auto intType = hw::type_dyn_cast<IntType>(type)) {
290 dims.push_back(intType.getWidth());
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))
307 errorHandler(loc) <<
"value has an unsupported verilog type " << type;
313 Type a, Type b, Location loc,
314 llvm::function_ref<mlir::InFlightDiagnostic(Location)> errorHandler) {
315 SmallVector<Attribute, 4> aDims;
318 SmallVector<Attribute, 4> bDims;
321 return aDims == bDims;
327 if (
auto intType = dyn_cast<IntegerType>(type))
328 return intType.getWidth() == 0;
329 if (
auto inout = dyn_cast<hw::InOutType>(type))
331 if (
auto net = dyn_cast<sv::NetType>(type))
333 if (
auto var = dyn_cast<sv::VarType>(type))
335 if (
auto uarray = dyn_cast<hw::UnpackedArrayType>(type))
336 return uarray.getNumElements() == 0 ||
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;
358 return TypeSwitch<Type, Type>(type)
359 .Case<InOutType, NetType, VarType>([](
auto valueType) {
362 .Case<UnpackedArrayType, sv::UnpackedOpenArrayType>([](
auto arrayType) {
365 .Default([](Type type) {
return type; });
378 return TypeSwitch<Type, bool>(type)
379 .Case<InOutType, NetType, VarType, UnpackedArrayType, ArrayType>(
380 [](
auto parentType) {
383 .Case<StructType, UnionType, EnumType, TypeAliasType>(
384 [](
auto) {
return true; })
385 .Default([](
auto) {
return false; });
399 if (
auto name = lhs.getName().compare(rhs.getName()))
401 return compareLocs(lhs.getChildLoc(), rhs.getChildLoc());
406 if (
auto fn = lhs.getFilename().compare(rhs.getFilename()))
408 if (lhs.getLine() != rhs.getLine())
409 return lhs.getLine() < rhs.getLine() ? -1 : 1;
410 return lhs.getColumn() < rhs.getColumn() ? -1 : 1;
415 Location lhsCallee = lhs.getCallee();
416 Location rhsCallee = rhs.getCallee();
420 Location lhsCaller = lhs.getCaller();
421 Location rhsCaller = rhs.getCaller();
425template <
typename TTargetLoc>
427 auto lhsT = dyn_cast<TTargetLoc>(lhs);
428 auto rhsT = dyn_cast<TTargetLoc>(rhs);
482 SmallPtrSetImpl<Attribute> &locationSet) {
483 llvm::TypeSwitch<Location, void>(loc)
484 .Case<FusedLoc>([&](
auto fusedLoc) {
485 for (
auto subLoc : fusedLoc.getLocations())
488 .Default([&](
auto loc) { locationSet.insert(loc); });
492template <
typename TVector>
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));
504 SmallPtrSet<Attribute, 8> locationSet;
505 locationSet.insert(loc);
506 llvm::raw_string_ostream os(
output);
512 const SmallPtrSetImpl<Operation *> &ops) {
516 SmallPtrSet<Attribute, 8> locationSet;
519 llvm::raw_string_ostream os(
output);
528 const SmallPtrSetImpl<Attribute> &locationSet) {
532 llvm::raw_string_ostream sstr(resstr);
539 "other styles must be already handled");
540 os <<
"@[" << resstr <<
"]";
549 const SmallPtrSetImpl<Attribute> &locationSet)
565 bool withName = !loc.getName().empty();
567 os <<
"'" << loc.getName().strref() <<
"'(";
576 os << loc.getFilename().getValue();
577 if (
auto line = loc.getLine()) {
579 if (
auto col = loc.getColumn())
591 StringRef lastFileName;
592 for (
size_t i = 0, e = locVector.size(); i != e;) {
597 auto first = locVector[i];
598 if (first.getFilename() != lastFileName) {
599 lastFileName = first.getFilename();
606 first.getFilename() == locVector[
end].getFilename() &&
607 first.getLine() == locVector[
end].getLine())
612 if (
auto line = first.getLine()) {
614 if (
auto col = first.getColumn())
622 os <<
':' << first.getLine() <<
":{";
624 os << locVector[i++].getColumn();
636 llvm::TypeSwitch<Location, void>(loc)
637 .Case<mlir::CallSiteLoc, mlir::NameLoc, mlir::FileLineColLoc>(
639 .Case<mlir::FusedLoc>([&](
auto loc) {
640 SmallPtrSet<Attribute, 8> locationSet;
644 .Default([&](
auto loc) {
656 switch (locationSet.size()) {
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);
675 otherLocs.push_back(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;
693 return emittedSomethingSinceLastCheck;
702 if (recheckEmittedSomething()) {
704 recheckEmittedSomething();
710 if (emittedAnything && !flcLocs.empty())
715 llvm::raw_string_ostream &
os;
727 if (isa<BlockArgument>(v))
736 if (isa_and_nonnull<StructExtractOp, UnionExtractOp, ArrayGetOp>(
741 if (v.getDefiningOp<ReadInterfaceSignalOp>())
754 if (
auto cast = dyn_cast<BitcastOp>(op))
755 if (!
haveMatchingDims(cast.getInput().getType(), cast.getResult().getType(),
757 [&](Location loc) { return emitError(loc); })) {
760 if (op->hasOneUse() &&
761 isa<comb::ConcatOp, hw::ArrayConcatOp>(*op->getUsers().begin()))
769 if (isa<StructCreateOp, UnionCreateOp, UnpackedArrayCreateOp, ArrayInjectOp>(
775 if (
auto aggConstantOp = dyn_cast<AggregateConstantOp>(op))
779 if (
auto verbatim = dyn_cast<VerbatimExprOp>(op))
780 if (verbatim.getFormatString().size() > 32)
785 for (
auto &use : op->getUses()) {
786 auto *user = use.getOwner();
796 StructInjectOp, StructExplodeOp, UnionExtractOp,
797 IndexedPartSelectOp>(user))
798 if (use.getOperandNumber() == 0 &&
809 auto usedInExprControl = [user, &use]() {
810 return TypeSwitch<Operation *, bool>(user)
811 .Case<ltl::ClockOp>([&](
auto clockOp) {
813 return clockOp.getClock() == use.get();
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();
822 .Case<AlwaysOp, AlwaysFFOp>([](
auto) {
827 .Default([](
auto) {
return false; });
830 if (!usedInExprControl())
834 auto read = dyn_cast<ReadInOutOp>(op);
837 if (!isa_and_nonnull<sv::WireOp, RegOp, sv::VarOp>(
838 read.getInput().getDefiningOp()))
849 unsigned numStatements = 0;
850 block.walk([&](Operation *op) {
852 isa_and_nonnull<ltl::LTLDialect>(op->getDialect()))
853 return WalkResult::advance();
855 TypeSwitch<Operation *, unsigned>(op)
856 .Case<VerbatimOp>([&](
auto) {
862 .Case<IfOp>([&](
auto) {
873 .Case<IfDefOp, IfDefProceduralOp>([&](
auto) {
return 3; })
874 .Case<OutputOp>([&](OutputOp oop) {
877 return llvm::count_if(oop->getOperands(), [&](
auto operand) {
878 Operation *op = operand.getDefiningOp();
879 return !operand.hasOneUse() || !op || !isa<HWInstanceLike>(op);
882 .Default([](
auto) {
return 1; });
883 if (numStatements > 1)
884 return WalkResult::interrupt();
885 return WalkResult::advance();
887 if (numStatements == 0)
889 if (numStatements == 1)
899 if (op->getResult(0).use_empty())
904 if (op->hasOneUse() &&
905 isa<hw::OutputOp, sv::AssignOp, sv::BPAssignOp, sv::PAssignOp>(
906 *op->getUsers().begin()))
928 for (
auto &op : *elseBlock) {
929 if (
auto opIf = dyn_cast<IfOp>(op)) {
946template <
typename PPS>
948 enum Container { NoContainer, InComment, InAttr };
949 Container currentContainer = NoContainer;
951 auto closeContainer = [&] {
952 if (currentContainer == NoContainer)
954 if (currentContainer == InComment)
956 else if (currentContainer == InAttr)
958 ps << PP::end << PP::end;
960 currentContainer = NoContainer;
963 bool isFirstContainer =
true;
964 auto openContainer = [&](Container newContainer) {
965 assert(newContainer != NoContainer);
966 if (currentContainer == newContainer)
970 if (!isFirstContainer)
971 ps << (mayBreak ? PP::space : PP::nbsp);
972 isFirstContainer =
false;
975 if (newContainer == InComment)
977 else if (newContainer == InAttr)
979 currentContainer = newContainer;
987 ps.scopedBox(PP::cbox0, [&]() {
988 for (
auto attr :
attrs.getAsRange<SVAttributeAttr>()) {
989 if (!openContainer(attr.getEmitAsComment().getValue() ? InComment
991 ps <<
"," << (mayBreak ? PP::space : PP::nbsp);
993 if (attr.getExpression())
994 ps <<
" = " <<
PPExtString(attr.getExpression().getValue());
1003 if (
auto *op = val.getDefiningOp())
1006 if (
auto port = dyn_cast<BlockArgument>(val)) {
1008 auto *parent = port.getParentBlock()->getParentOp();
1009 if (isa<ForOp, GenerateForOp>(parent))
1010 return parent->getAttrOfType<StringAttr>(
"hw.verilogName");
1012 port.getArgNumber());
1014 assert(
false &&
"unhandled value");
1026class VerilogEmitterState {
1028 explicit VerilogEmitterState(ModuleOp designOp,
1029 const SharedEmitterState &shared,
1030 const LoweringOptions &options,
1031 const HWSymbolCache &symbolCache,
1032 const GlobalNameTable &globalNames,
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);
1045 const SharedEmitterState &shared;
1048 const LoweringOptions &options;
1051 const HWSymbolCache &symbolCache;
1055 const GlobalNameTable &globalNames;
1063 llvm::formatted_raw_ostream &os;
1065 bool encounteredError =
false;
1074 bool pendingNewline =
false;
1077 OpLocMap &verilogLocMap;
1080 PrintEventAndStorageListener<OpLocMap, std::pair<Operation *, bool>> saver =
1081 PrintEventAndStorageListener<OpLocMap, std::pair<Operation *, bool>>(
1088 StringAttr fileName;
1094 void addVerilogLocToOps(
unsigned int lineOffset, StringAttr fileName) {
1095 verilogLocMap.updateIRWithLoc(lineOffset, fileName,
1096 shared.designOp->getContext());
1097 verilogLocMap.clear();
1101 VerilogEmitterState(
const VerilogEmitterState &) =
delete;
1102 void operator=(
const VerilogEmitterState &) =
delete;
1115using CallbackDataTy = std::pair<Operation *, bool>;
1119 VerilogEmitterState &state;
1122 TokenStreamWithCallback<OpLocMap, CallbackDataTy> ps;
1124 explicit EmitterBase(VerilogEmitterState &state)
1126 ps(state.pp, state.saver, state.options.emitVerilogLocations) {}
1128 InFlightDiagnostic emitError(Operation *op,
const Twine &message) {
1129 state.encounteredError =
true;
1130 return op->emitError(message);
1133 InFlightDiagnostic emitOpError(Operation *op,
const Twine &message) {
1134 state.encounteredError =
true;
1135 return op->emitOpError(message);
1138 InFlightDiagnostic emitError(Location loc,
const Twine &message =
"") {
1139 state.encounteredError =
true;
1140 return mlir::emitError(loc, message);
1143 void emitLocationImpl(llvm::StringRef location) {
1146 ps << PP::neverbreak;
1147 if (!location.empty())
1148 ps <<
"\t// " << location;
1151 void emitLocationInfo(Location loc) {
1153 LocationEmitter(state.options.locationInfoStyle, loc).strref());
1159 void emitLocationInfoAndNewLine(
const SmallPtrSetImpl<Operation *> &ops) {
1161 LocationEmitter(state.options.locationInfoStyle, ops).strref());
1162 setPendingNewline();
1165 template <
typename PPS>
1166 void emitTextWithSubstitutions(PPS &ps, StringRef
string, Operation *op,
1167 llvm::function_ref<
void(Value)> operandEmitter,
1168 ArrayAttr symAttrs);
1174 void emitComment(StringAttr comment);
1178 void emitPendingNewlineIfNeeded() {
1179 if (state.pendingNewline) {
1180 state.pendingNewline =
false;
1184 void setPendingNewline() {
1185 assert(!state.pendingNewline);
1186 state.pendingNewline =
true;
1189 void startStatement() { emitPendingNewlineIfNeeded(); }
1192 void operator=(
const EmitterBase &) =
delete;
1193 EmitterBase(
const EmitterBase &) =
delete;
1197template <
typename PPS>
1198void EmitterBase::emitTextWithSubstitutions(
1199 PPS &ps, StringRef
string, Operation *op,
1200 llvm::function_ref<
void(Value)> operandEmitter, ArrayAttr symAttrs) {
1204 auto namify = [&](Attribute sym, HWSymbolCache::Item item) {
1211 if (
auto *itemOp = item.getOp()) {
1212 if (item.hasPort()) {
1216 if (!symOpName.empty())
1218 emitError(itemOp,
"cannot get name for symbol ") << sym;
1220 emitError(op,
"cannot get name for symbol ") << sym;
1222 return StringRef(
"<INVALID>");
1228 unsigned numSymOps = symAttrs.size();
1229 auto emitUntilSubstitution = [&](
size_t next = 0) ->
bool {
1232 next =
string.find(
"{{", next);
1233 if (next == StringRef::npos)
1240 while (next <
string.size() &&
isdigit(
string[next]))
1243 if (start == next) {
1247 size_t operandNoLength = next - start;
1250 StringRef fmtOptsStr;
1251 if (
string[next] ==
':') {
1252 size_t startFmtOpts = next + 1;
1253 while (next <
string.size() &&
string[next] !=
'}')
1255 fmtOptsStr =
string.substr(startFmtOpts, next - startFmtOpts);
1259 if (!
string.substr(next).starts_with(
"}}"))
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");
1273 auto before =
string.take_front(start - 2);
1274 if (!before.empty())
1275 ps << PPExtString(before);
1279 if (operandNo < op->getNumOperands())
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)) {
1288 if (
auto globalRef = dyn_cast<HierPathOp>(symOp)) {
1289 auto namepath = globalRef.getNamepathAttr().getValue();
1290 for (
auto [index, sym] : llvm::enumerate(namepath)) {
1293 ps << (fmtOptsStr.empty() ?
"." : fmtOptsStr);
1295 auto innerRef = cast<InnerRefAttr>(sym);
1297 innerRef.getModule(), innerRef.getName());
1298 ps << namify(innerRef, ref);
1301 symVerilogName = namify(sym, symOp);
1304 }
else if (
auto isym = dyn_cast<InnerRefAttr>(sym)) {
1307 symVerilogName = namify(sym, symOp);
1309 if (!symVerilogName.empty())
1310 ps << PPExtString(symVerilogName);
1312 emitError(op,
"operand " + llvm::utostr(operandNo) +
" isn't valid");
1316 string =
string.drop_front(next);
1322 while (emitUntilSubstitution())
1326 if (!
string.
empty())
1327 ps << PPExtString(
string);
1330void EmitterBase::emitComment(StringAttr comment) {
1339 lineLength = std::max<size_t>(*lineLength, 3) - 3;
1343 auto ref = comment.getValue();
1345 while (!ref.empty()) {
1346 std::tie(line, ref) = ref.split(
"\n");
1353 if (!lineLength || line.size() <= lineLength) {
1354 ps << PPExtString(line);
1355 setPendingNewline();
1366 auto breakPos = line.rfind(
' ', *lineLength);
1368 if (breakPos == StringRef::npos) {
1369 breakPos = line.find(
' ', *lineLength);
1372 if (breakPos == StringRef::npos)
1373 breakPos = line.size();
1379 ps << PPExtString(line.take_front(breakPos));
1380 setPendingNewline();
1381 breakPos = line.find_first_not_of(
' ', breakPos);
1383 if (breakPos == StringRef::npos)
1386 line = line.drop_front(breakPos);
1396 bool addPrefixUnderScore =
true;
1399 if (
auto read = expr.getDefiningOp<
ReadInOutOp>())
1403 if (
auto blockArg = dyn_cast<BlockArgument>(expr)) {
1405 cast<HWEmittableModuleLike>(blockArg.getOwner()->getParentOp());
1407 result = StringAttr::get(expr.getContext(), name);
1409 }
else if (
auto *op = expr.getDefiningOp()) {
1411 if (isa<sv::WireOp, RegOp, LogicOp, sv::VarOp>(op)) {
1413 result = StringAttr::get(expr.getContext(), name);
1415 }
else if (
auto nameHint = op->getAttrOfType<StringAttr>(
"sv.namehint")) {
1421 addPrefixUnderScore =
false;
1423 TypeSwitch<Operation *>(op)
1426 .Case([&result](VerbatimExprOp verbatim) {
1427 verbatim.getAsmResultNames([&](Value, StringRef name) {
1428 result = StringAttr::get(verbatim.getContext(), name);
1431 .Case([&result](VerbatimExprSEOp verbatim) {
1432 verbatim.getAsmResultNames([&](Value, StringRef name) {
1433 result = StringAttr::get(verbatim.getContext(), name);
1439 if (
auto operandName =
1442 cast<IntegerType>(extract.getType()).getWidth();
1444 result = StringAttr::get(extract.getContext(),
1445 operandName.strref() +
"_" +
1446 Twine(extract.getLowBit()));
1448 result = StringAttr::get(
1449 extract.getContext(),
1450 operandName.strref() +
"_" +
1451 Twine(extract.getLowBit() + numBits - 1) +
"to" +
1452 Twine(extract.getLowBit()));
1460 if (!result || result.strref().empty())
1464 if (addPrefixUnderScore && result.strref().front() !=
'_')
1465 result = StringAttr::get(expr.getContext(),
"_" + result.strref());
1477class ModuleEmitter :
public EmitterBase {
1479 explicit ModuleEmitter(VerilogEmitterState &state)
1480 : EmitterBase(state), currentModuleOp(nullptr),
1484 emitPendingNewlineIfNeeded();
1488 void emitParameters(Operation *module, ArrayAttr params);
1489 void emitPortList(Operation *module,
const ModulePortInfo &portInfo,
1490 bool emitAsTwoStateType =
false);
1492 void emitHWModule(HWModuleOp module);
1493 void emitHWGeneratedModule(HWModuleGeneratedOp module);
1494 void emitFunc(FuncOp);
1497 void emitStatement(Operation *op);
1498 void emitBind(BindOp op);
1499 void emitBindInterface(BindInterfaceOp op);
1501 void emitSVAttributes(Operation *op);
1504 StringRef getVerilogStructFieldName(StringAttr field) {
1512 void emitTypeDims(Type type, Location loc, raw_ostream &os);
1524 bool printPackedType(Type type, raw_ostream &os, Location loc,
1525 Type optionalAliasType = {},
bool implicitIntType =
true,
1526 bool singleBitDefaultType =
true,
1527 bool emitAsTwoStateType =
false);
1531 void printUnpackedTypePostfix(Type type, raw_ostream &os);
1539 function_ref<InFlightDiagnostic()> emitError);
1542 VerilogPrecedence parenthesizeIfLooserThan,
1543 function_ref<InFlightDiagnostic()> emitError);
1549 Operation *currentModuleOp;
1550 Operation *currentPackage =
nullptr;
1556 SmallPtrSet<Operation *, 16> expressionsEmittedIntoDecl;
1559 FieldNameResolver fieldNameResolver;
1562 SmallPtrSet<Operation *, 16> assignsInlined;
1573 return TypeSwitch<Type, bool>(type)
1574 .Case<UnpackedArrayType, ArrayType>(
1576 .Case<IntegerType>([](
auto) {
return false; })
1577 .Default([](
auto) {
return true; });
1584 const ModuleEmitter &emitter) {
1585 if (isa<RegOp>(op)) {
1590 cast<InOutType>(op->getResult(0).getType()).getElementType();
1593 while (
auto arrayType = hw::type_dyn_cast<UnpackedArrayType>(
elementType))
1595 while (
auto arrayType = hw::type_dyn_cast<ArrayType>(
elementType))
1598 if (isa<StructType, UnionType, EnumType, TypeAliasType>(
elementType))
1604 if (isa<sv::WireOp>(op))
1606 if (isa<ConstantOp, AggregateConstantOp, LocalParamOp, ParamValueOp>(op))
1607 return "localparam";
1610 if (
auto interface = dyn_cast<InterfaceInstanceOp>(op))
1611 return interface.getInterfaceType().getInterface().getValue();
1619 bool stripAutomatic = isa_and_nonnull<FuncOp>(emitter.currentModuleOp);
1621 if (
auto var = dyn_cast<VarOp>(op)) {
1628 if (isProcedural && !stripAutomatic && !var->hasAttr(
"sv.no_automatic"))
1630 :
"automatic logic";
1632 switch (emitter.state.options.varOpDeclStyle) {
1634 return hasExplicitType ?
"var" :
"var logic";
1636 return hasExplicitType ?
"" :
"logic";
1638 return hasExplicitType ?
"" :
"reg";
1642 if (isa<LogicOp>(op)) {
1648 if (isProcedural && !stripAutomatic)
1649 return hasStruct ?
"automatic" :
"automatic logic";
1650 return hasStruct ?
"" :
"logic";
1657 return hasStructType(op->getResult(0).getType()) ?
"" :
"logic";
1660 assert(!emitter.state.options.disallowLocalVariables &&
1661 "automatic variables not allowed");
1665 return hasStructType(op->getResult(0).getType()) ?
"automatic"
1666 :
"automatic logic";
1673static void emitDim(Attribute width, raw_ostream &os, Location loc,
1674 ModuleEmitter &emitter,
bool downTo) {
1676 os <<
"<<invalid type>>";
1679 if (
auto intAttr = dyn_cast<IntegerAttr>(width)) {
1680 if (intAttr.getValue().isZero()) {
1681 os <<
"/*Zero Width*/";
1686 os << (intAttr.getValue().getZExtValue() - 1);
1696 auto typedAttr = dyn_cast<TypedAttr>(width);
1698 emitter.emitError(loc,
"untyped dimension attribute ") << width;
1702 getIntAttr(loc.getContext(), typedAttr.getType(),
1703 APInt(typedAttr.getType().getIntOrFloatBitWidth(), -1L,
true));
1704 width = ParamExprAttr::get(PEO::Add, typedAttr, negOne);
1708 emitter.printParamValue(width, os, [loc, &emitter]() {
1709 return emitter.emitError(loc,
"invalid parameter in type");
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,
true);
1725void ModuleEmitter::emitTypeDims(Type type, Location loc, raw_ostream &os) {
1726 SmallVector<Attribute, 4> dims;
1728 [&](Location loc) {
return this->emitError(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()) {
1768 if (!typeName.empty()) {
1773 if (integerType.getWidth() != 1 || !singleBitDefaultType)
1775 getInt32Attr(type.getContext(), integerType.getWidth()));
1777 StringRef typeName =
1778 (emitAsTwoStateType ?
"bit" : (implicitIntType ?
"" :
"logic"));
1779 if (!typeName.empty()) {
1786 return !dims.empty() || !implicitIntType;
1788 .Case<IntType>([&](IntType intType) {
1789 if (!implicitIntType)
1791 dims.push_back(intType.getWidth());
1795 .Case<ArrayType>([&](ArrayType arrayType) {
1796 dims.push_back(arrayType.getSizeAttr());
1798 implicitIntType, singleBitDefaultType,
1800 emitAsTwoStateType);
1802 .Case<InOutType, sv::NetType, sv::VarType>([&](
auto handleType) {
1804 implicitIntType, singleBitDefaultType,
1806 emitAsTwoStateType);
1808 .Case<EnumType>([&](EnumType enumType) {
1809 assert(enumType.getBitWidth().has_value() &&
1810 "enum type must have bitwidth");
1812 if (enumType.getBitWidth() != 32)
1813 os <<
"bit [" << *enumType.getBitWidth() - 1 <<
":0] ";
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);
1826 .Case<StructType>([&](StructType structType) {
1827 if (structType.getElements().empty() ||
isZeroBitType(structType)) {
1828 os <<
"/*Zero Width*/";
1831 os <<
"struct packed {";
1832 for (
auto &element : structType.getElements()) {
1834 os <<
"/*" << emitter.getVerilogStructFieldName(element.name)
1835 <<
": Zero Width;*/ ";
1838 SmallVector<Attribute, 8> structDims;
1843 {}, emitAsTwoStateType);
1844 os <<
' ' << emitter.getVerilogStructFieldName(element.name);
1845 emitter.printUnpackedTypePostfix(element.type, os);
1852 .Case<UnionType>([&](UnionType unionType) {
1853 if (unionType.getElements().empty() ||
isZeroBitType(unionType)) {
1854 os <<
"/*Zero Width*/";
1858 int64_t unionWidth = hw::getBitWidth(unionType);
1860 "SV packed union must have known positive bitwidth");
1861 os <<
"union packed {";
1862 for (
auto &element : unionType.getElements()) {
1864 os <<
"/*" << emitter.getVerilogStructFieldName(element.name)
1865 <<
": Zero Width;*/ ";
1868 int64_t elementWidth = hw::getBitWidth(element.type);
1871 auto elementOffset =
static_cast<int64_t
>(element.offset);
1872 bool needsPadding = elementWidth < unionWidth || elementOffset > 0;
1873 int64_t prePadding = unionWidth - (elementWidth + elementOffset);
1875 os <<
" struct packed {";
1876 if (prePadding > 0) {
1877 os << (emitAsTwoStateType ?
"bit" :
"logic") <<
" ["
1878 << prePadding - 1 <<
":0] "
1879 <<
"__pre_padding_" << element.name.getValue() <<
"; ";
1883 SmallVector<Attribute, 8> structDims;
1887 true, emitter, {}, emitAsTwoStateType);
1888 os <<
' ' << emitter.getVerilogStructFieldName(element.name);
1889 emitter.printUnpackedTypePostfix(element.type, os);
1893 if (elementOffset > 0) {
1894 os <<
" " << (emitAsTwoStateType ?
"bit" :
"logic") <<
" ["
1895 << elementOffset - 1 <<
":0] "
1896 <<
"__post_padding_" << element.name.getValue() <<
";";
1898 os <<
"} " << emitter.getVerilogStructFieldName(element.name)
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();
1914 .Case<UnpackedArrayType>([&](UnpackedArrayType arrayType) {
1915 os <<
"<<unexpected unpacked array>>";
1916 emitter.emitError(loc,
"Unexpected unpacked array in packed type ")
1920 .Case<TypeAliasType>([&](TypeAliasType typeRef) {
1921 auto typedecl = typeRef.getTypeDecl(emitter.state.symbolCache);
1923 emitter.emitError(loc,
"unresolvable type reference");
1926 if (typedecl.getType() != typeRef.getInnerType()) {
1927 emitter.emitError(loc,
"declared type did not match aliased type");
1931 if (
auto *package = typedecl->getParentOp();
1932 isa<PackageOp, PackageExternOp>(package)) {
1933 if (package != emitter.currentPackage)
1936 os << typedecl.getPreferredName();
1937 emitDims(dims, os, typedecl->getLoc(), emitter);
1940 .Default([&](Type type) {
1941 os <<
"<<invalid type '" << type <<
"'>>";
1942 emitter.emitError(loc,
"value has an unsupported verilog type ")
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;
1966 singleBitDefaultType, *
this, optionalAliasType,
1967 emitAsTwoStateType);
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);
1978 .Case<UnpackedArrayType>([&](UnpackedArrayType arrayType) {
1979 auto loc = currentModuleOp ? currentModuleOp->getLoc()
1980 : state.designOp->getLoc();
1981 emitDim(arrayType.getSizeAttr(), os, loc, *
this,
1983 printUnpackedTypePostfix(arrayType.getElementType(), os);
1985 .Case<sv::UnpackedOpenArrayType>([&](
auto arrayType) {
1987 printUnpackedTypePostfix(arrayType.getElementType(), os);
1989 .Case<InterfaceType>([&](
auto) {
2003ModuleEmitter::printParamValue(Attribute value, raw_ostream &os,
2004 function_ref<InFlightDiagnostic()> emitError) {
2005 return printParamValue(value, os, VerilogPrecedence::LowestPrecedence,
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();
2022 if (intTy.getWidth() > 32) {
2024 if (value.isNegative() && (intTy.isSigned() || intTy.isSignless())) {
2028 if (intTy.isSigned())
2029 os << intTy.getWidth() <<
"'sd";
2031 os << intTy.getWidth() <<
"'d";
2033 value.print(os, intTy.isSigned());
2034 return {Symbol, intTy.isSigned() ? IsSigned : IsUnsigned};
2036 if (
auto strAttr = dyn_cast<StringAttr>(value)) {
2038 os.write_escaped(strAttr.getValue());
2040 return {Symbol, IsUnsigned};
2042 if (
auto fpAttr = dyn_cast<FloatAttr>(value)) {
2044 os << fpAttr.getValueAsDouble();
2045 return {Symbol, IsUnsigned};
2047 if (
auto verbatimParam = dyn_cast<ParamVerbatimAttr>(value)) {
2048 os << verbatimParam.getValue().getValue();
2049 return {Symbol, IsUnsigned};
2051 if (
auto parameterRef = dyn_cast<ParamDeclRefAttr>(value)) {
2054 parameterRef.getName());
2057 return {Symbol, IsUnsigned};
2061 auto expr = dyn_cast<ParamExprAttr>(value);
2063 os <<
"<<UNKNOWN MLIRATTR: " << value <<
">>";
2064 emitError() <<
" = " << value;
2065 return {LowestPrecedence, IsUnsigned};
2068 StringRef operatorStr;
2069 StringRef openStr, closeStr;
2070 VerilogPrecedence subprecedence = LowestPrecedence;
2071 VerilogPrecedence prec;
2072 std::optional<SubExprSignResult> operandSign;
2073 bool isUnary =
false;
2074 bool hasOpenClose =
false;
2076 switch (expr.getOpcode()) {
2078 operatorStr =
" + ";
2079 subprecedence = Addition;
2082 operatorStr =
" * ";
2083 subprecedence = Multiply;
2086 operatorStr =
" & ";
2087 subprecedence = And;
2090 operatorStr =
" | ";
2094 operatorStr =
" ^ ";
2095 subprecedence = Xor;
2098 operatorStr =
" << ";
2099 subprecedence = Shift;
2103 operatorStr =
" >> ";
2104 subprecedence = Shift;
2108 operatorStr =
" >>> ";
2109 subprecedence = Shift;
2110 operandSign = IsSigned;
2113 operatorStr =
" / ";
2114 subprecedence = Multiply;
2115 operandSign = IsUnsigned;
2118 operatorStr =
" / ";
2119 subprecedence = Multiply;
2120 operandSign = IsSigned;
2123 operatorStr =
" % ";
2124 subprecedence = Multiply;
2125 operandSign = IsUnsigned;
2128 operatorStr =
" % ";
2129 subprecedence = Multiply;
2130 operandSign = IsSigned;
2133 openStr =
"$clog2(";
2135 operandSign = IsUnsigned;
2136 hasOpenClose =
true;
2139 case PEO::StrConcat:
2142 hasOpenClose =
true;
2145 subprecedence = LowestPrecedence;
2150 prec = subprecedence;
2153 assert(!isUnary || llvm::hasSingleElement(expr.getOperands()));
2155 assert(isUnary || hasOpenClose ||
2156 !llvm::hasSingleElement(expr.getOperands()));
2163 auto emitOperand = [&](Attribute operand) ->
bool {
2165 auto subprec = operandSign.has_value() ? LowestPrecedence : subprecedence;
2166 if (operandSign.has_value())
2167 os << (*operandSign == IsSigned ?
"$signed(" :
"$unsigned(");
2170 if (operandSign.has_value()) {
2172 signedness = *operandSign;
2174 return signedness == IsSigned;
2178 if (prec > parenthesizeIfLooserThan)
2187 bool allOperandsSigned = emitOperand(expr.getOperands()[0]);
2188 for (
auto op : expr.getOperands().drop_front()) {
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()) {
2196 allOperandsSigned &=
2197 emitOperand(IntegerAttr::get(op.getType(), -value));
2204 allOperandsSigned &= emitOperand(op);
2208 if (prec > parenthesizeIfLooserThan) {
2212 return {prec, allOperandsSigned ? IsSigned : IsUnsigned};
2227class ExprEmitter :
public EmitterBase,
2228 public TypeOpVisitor<ExprEmitter, SubExprInfo>,
2229 public CombinationalVisitor<ExprEmitter, SubExprInfo>,
2230 public sv::Visitor<ExprEmitter, SubExprInfo> {
2234 ExprEmitter(ModuleEmitter &emitter,
2235 SmallPtrSetImpl<Operation *> &emittedExprs)
2236 : ExprEmitter(emitter, emittedExprs, localTokens) {}
2238 ExprEmitter(ModuleEmitter &emitter,
2239 SmallPtrSetImpl<Operation *> &emittedExprs,
2241 : EmitterBase(emitter.state), emitter(emitter),
2242 emittedExprs(emittedExprs), buffer(tokens),
2243 ps(buffer, state.saver, state.options.emitVerilogLocations) {
2251 void emitExpression(Value exp, VerilogPrecedence parenthesizeIfLooserThan,
2252 bool isAssignmentLikeContext) {
2253 assert(localTokens.empty());
2255 ps.scopedBox(PP::ibox0, [&]() {
2258 emitSubExpr(exp, parenthesizeIfLooserThan,
2260 isAssignmentLikeContext ? RequireUnsigned : NoRequirement,
2262 isAssignmentLikeContext);
2267 if (&buffer.
tokens == &localTokens)
2268 buffer.
flush(state.pp);
2272 friend class TypeOpVisitor<ExprEmitter, SubExprInfo>;
2273 friend class CombinationalVisitor<ExprEmitter, SubExprInfo>;
2274 friend class sv::Visitor<ExprEmitter, SubExprInfo>;
2276 enum SubExprSignRequirement { NoRequirement, RequireSigned, RequireUnsigned };
2284 SubExprInfo emitSubExpr(Value exp, VerilogPrecedence parenthesizeIfLooserThan,
2285 SubExprSignRequirement signReq = NoRequirement,
2286 bool isSelfDeterminedUnsignedValue =
false,
2287 bool isAssignmentLikeContext =
false);
2291 void emitSVAttributes(Operation *op);
2293 SubExprInfo visitUnhandledExpr(Operation *op);
2294 SubExprInfo visitInvalidComb(Operation *op) {
2295 return dispatchTypeOpVisitor(op);
2297 SubExprInfo visitUnhandledComb(Operation *op) {
2298 return visitUnhandledExpr(op);
2300 SubExprInfo visitInvalidTypeOp(Operation *op) {
2301 return dispatchSVVisitor(op);
2303 SubExprInfo visitUnhandledTypeOp(Operation *op) {
2304 return visitUnhandledExpr(op);
2306 SubExprInfo visitUnhandledSV(Operation *op) {
return visitUnhandledExpr(op); }
2309 enum EmitBinaryFlags {
2310 EB_RequireSignedOperands = RequireSigned,
2311 EB_RequireUnsignedOperands = RequireUnsigned,
2312 EB_OperandSignRequirementMask = 0x3,
2317 EB_RHS_UnsignedWithSelfDeterminedWidth = 0x4,
2321 EB_ForceResultSigned = 0x8,
2326 SubExprInfo emitBinary(Operation *op, VerilogPrecedence prec,
2327 const char *syntax,
unsigned emitBinaryFlags = 0);
2329 SubExprInfo emitUnary(Operation *op,
const char *syntax,
2330 bool resultAlwaysUnsigned =
false);
2333 void emitSubExprIBox2(
2334 Value v, VerilogPrecedence parenthesizeIfLooserThan = LowestPrecedence) {
2335 ps.scopedBox(PP::ibox2,
2336 [&]() { emitSubExpr(v, parenthesizeIfLooserThan); });
2341 template <
typename Container,
typename EachFn>
2342 void interleaveComma(
const Container &c, EachFn eachFn) {
2343 llvm::interleave(c, eachFn, [&]() { ps <<
"," << PP::space; });
2348 void interleaveComma(ValueRange ops) {
2349 return interleaveComma(ops, [&](Value v) { emitSubExprIBox2(v); });
2366 template <
typename Container,
typename OpenFunc,
typename CloseFunc,
2368 void emitBracedList(
const Container &c, OpenFunc openFn, EachFunc eachFn,
2369 CloseFunc closeFn) {
2371 ps.scopedBox(PP::cbox0, [&]() {
2372 interleaveComma(c, eachFn);
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);
2385 void emitBracedList(ValueRange ops) {
2386 return emitBracedList(
2387 ops, [&]() { ps <<
"{"; }, [&]() { ps <<
"}"; });
2391 SubExprInfo printConstantScalar(APInt &value, IntegerType type);
2394 void printConstantArray(ArrayAttr elementValues, Type
elementType,
2395 bool printAsPattern, Operation *op);
2397 void printConstantStruct(ArrayRef<hw::detail::FieldInfo> fieldInfos,
2398 ArrayAttr fieldValues,
bool printAsPattern,
2401 void printConstantAggregate(Attribute attr, Type type, Operation *op);
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());
2414 SubExprInfo visitSV(VerbatimExprSEOp op) {
2415 return visitVerbatimExprOp(op, op.getSymbols());
2417 SubExprInfo visitSV(MacroRefExprOp op);
2418 SubExprInfo visitSV(MacroRefExprSEOp op);
2419 template <
typename MacroTy>
2420 SubExprInfo emitMacroCall(MacroTy op);
2422 SubExprInfo visitSV(ConstantXOp op);
2423 SubExprInfo visitSV(ConstantZOp op);
2424 SubExprInfo visitSV(ConstantStrOp op);
2425 SubExprInfo visitSV(ConcatStrOp op);
2427 SubExprInfo visitSV(sv::UnpackedArrayCreateOp op);
2428 SubExprInfo visitSV(sv::UnpackedOpenArrayCastOp op) {
2430 return emitSubExpr(op->getOperand(0), LowestPrecedence);
2434 SubExprInfo visitSV(ReadInOutOp op) {
2435 auto result = emitSubExpr(op->getOperand(0), LowestPrecedence);
2436 emitSVAttributes(op);
2439 SubExprInfo visitSV(ArrayIndexInOutOp op);
2440 SubExprInfo visitSV(IndexedPartSelectInOutOp op);
2441 SubExprInfo visitSV(IndexedPartSelectOp op);
2442 SubExprInfo visitSV(StructFieldInOutOp op);
2445 SubExprInfo visitSV(SampledOp op);
2448 SubExprInfo visitSV(TimeOp op);
2449 SubExprInfo visitSV(STimeOp op);
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);
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,
"+");
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,
"*");
2482 SubExprInfo visitComb(DivUOp op) {
2483 return emitBinary(op, Multiply,
"/", EB_RequireUnsignedOperands);
2485 SubExprInfo visitComb(DivSOp op) {
2486 return emitBinary(op, Multiply,
"/",
2487 EB_RequireSignedOperands | EB_ForceResultSigned);
2489 SubExprInfo visitComb(ModUOp op) {
2490 return emitBinary(op, Multiply,
"%", EB_RequireUnsignedOperands);
2492 SubExprInfo visitComb(ModSOp op) {
2493 return emitBinary(op, Multiply,
"%",
2494 EB_RequireSignedOperands | EB_ForceResultSigned);
2496 SubExprInfo visitComb(ShlOp op) {
2497 return emitBinary(op, Shift,
"<<", EB_RHS_UnsignedWithSelfDeterminedWidth);
2499 SubExprInfo visitComb(ShrUOp op) {
2501 return emitBinary(op, Shift,
">>", EB_RHS_UnsignedWithSelfDeterminedWidth);
2503 SubExprInfo visitComb(ShrSOp op) {
2506 return emitBinary(op, Shift,
">>>",
2507 EB_RequireSignedOperands | EB_ForceResultSigned |
2508 EB_RHS_UnsignedWithSelfDeterminedWidth);
2510 SubExprInfo visitComb(AndOp op) {
2511 assert(op.getNumOperands() == 2 &&
"prelowering should handle variadics");
2512 return emitBinary(op, And,
"&");
2514 SubExprInfo visitComb(OrOp op) {
2515 assert(op.getNumOperands() == 2 &&
"prelowering should handle variadics");
2516 return emitBinary(op, Or,
"|");
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,
"^");
2527 SubExprInfo visitComb(ParityOp op) {
return emitUnary(op,
"^",
true); }
2529 SubExprInfo visitComb(ReplicateOp op);
2530 SubExprInfo visitComb(ConcatOp op);
2531 SubExprInfo visitComb(ExtractOp op);
2532 SubExprInfo visitComb(ICmpOp op);
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";
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);
2548 ModuleEmitter &emitter;
2555 SubExprSignRequirement signPreference = NoRequirement;
2559 SmallPtrSetImpl<Operation *> &emittedExprs;
2562 SmallVector<Token> localTokens;
2568 TokenStreamWithCallback<OpLocMap, CallbackDataTy, BufferingPP> ps;
2576 bool isAssignmentLikeContext =
false;
2580SubExprInfo ExprEmitter::emitBinary(Operation *op, VerilogPrecedence prec,
2582 unsigned emitBinaryFlags) {
2584 emitError(op,
"SV attributes emission is unimplemented for the op");
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);
2602 auto lhsSpace = (prec == VerilogPrecedence::Comparison ||
2603 prec == VerilogPrecedence::Equality)
2607 ps << lhsSpace << syntax << PP::nbsp;
2614 auto rhsPrec = prec;
2615 if (!isa<AddOp, MulOp, AndOp, OrOp, XorOp>(op))
2616 rhsPrec = VerilogPrecedence(prec - 1);
2621 bool rhsIsUnsignedValueWithSelfDeterminedWidth =
false;
2622 if (emitBinaryFlags & EB_RHS_UnsignedWithSelfDeterminedWidth) {
2623 rhsIsUnsignedValueWithSelfDeterminedWidth =
true;
2624 operandSignReq = NoRequirement;
2627 auto rhsInfo = emitSubExpr(op->getOperand(1), rhsPrec, operandSignReq,
2628 rhsIsUnsignedValueWithSelfDeterminedWidth);
2632 SubExprSignResult signedness = IsUnsigned;
2633 if (lhsInfo.signedness == IsSigned && rhsInfo.signedness == IsSigned)
2634 signedness = IsSigned;
2636 if (emitBinaryFlags & EB_ForceResultSigned) {
2637 ps << PP::end <<
")";
2638 signedness = IsSigned;
2642 return {prec, signedness};
2645SubExprInfo ExprEmitter::emitUnary(Operation *op,
const char *syntax,
2646 bool resultAlwaysUnsigned) {
2648 emitError(op,
"SV attributes emission is unimplemented for the op");
2651 auto signedness = emitSubExpr(op->getOperand(0), Selection).signedness;
2655 return {isa<ICmpOp>(op) ? LowestPrecedence : Unary,
2656 resultAlwaysUnsigned ? IsUnsigned : signedness};
2661void ExprEmitter::emitSVAttributes(Operation *op) {
2680 if (constant && constant.getValue().isZero())
2681 return concat.getOperand(1);
2691SubExprInfo ExprEmitter::emitSubExpr(Value exp,
2692 VerilogPrecedence parenthesizeIfLooserThan,
2693 SubExprSignRequirement signRequirement,
2694 bool isSelfDeterminedUnsignedValue,
2695 bool isAssignmentLikeContext) {
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);
2706 if (isSelfDeterminedUnsignedValue && exp.hasOneUse()) {
2711 auto *op = exp.getDefiningOp();
2715 if (!shouldEmitInlineExpr) {
2718 if (signRequirement == RequireSigned) {
2720 return {Symbol, IsSigned};
2724 return {Symbol, IsUnsigned};
2727 unsigned subExprStartIndex = buffer.
tokens.size();
2729 ps.addCallback({op,
true});
2730 llvm::scope_exit done([&]() {
2732 ps.addCallback({op,
false});
2738 signPreference = signRequirement;
2740 bool bitCastAdded =
false;
2743 dyn_cast_or_null<IntegerType>(op->getResult(0).getType())) {
2744 ps.addAsString(inType.getWidth());
2745 ps <<
"'(" << PP::ibox0;
2746 bitCastAdded =
true;
2750 llvm::SaveAndRestore restoreALC(this->isAssignmentLikeContext,
2751 isAssignmentLikeContext);
2752 auto expInfo = dispatchCombinationalVisitor(exp.getDefiningOp());
2756 auto addPrefix = [&](StringToken &&t) {
2758 buffer.
tokens.insert(buffer.
tokens.begin() + subExprStartIndex,
2760 buffer.
tokens.insert(buffer.
tokens.begin() + subExprStartIndex, t);
2762 auto closeBoxAndParen = [&]() { ps << PP::end <<
")"; };
2763 if (signRequirement == RequireSigned && expInfo.signedness == IsUnsigned) {
2764 addPrefix(StringToken(
"$signed("));
2766 expInfo.signedness = IsSigned;
2767 expInfo.precedence = Selection;
2768 }
else if (signRequirement == RequireUnsigned &&
2769 expInfo.signedness == IsSigned) {
2770 addPrefix(StringToken(
"$unsigned("));
2772 expInfo.signedness = IsUnsigned;
2773 expInfo.precedence = Selection;
2774 }
else if (expInfo.precedence > parenthesizeIfLooserThan) {
2778 addPrefix(StringToken(
"("));
2781 expInfo.precedence = Selection;
2788 emittedExprs.insert(exp.getDefiningOp());
2792SubExprInfo ExprEmitter::visitComb(ReplicateOp op) {
2796 emitBracedList(SmallVector<Value>(op.getMultiple(), op.getOperand()));
2797 return {Symbol, IsUnsigned};
2800 auto openFn = [&]() {
2802 ps.addAsString(op.getMultiple());
2805 auto closeFn = [&]() { ps <<
"}}"; };
2809 if (
auto concatOp = op.getOperand().getDefiningOp<ConcatOp>()) {
2810 if (op.getOperand().hasOneUse()) {
2811 emitBracedList(concatOp.getOperands(), openFn, closeFn);
2812 return {Symbol, IsUnsigned};
2815 emitBracedList(op.getOperand(), openFn, closeFn);
2816 return {Symbol, IsUnsigned};
2819SubExprInfo ExprEmitter::visitComb(ConcatOp op) {
2820 emitBracedList(op.getOperands());
2821 return {Symbol, IsUnsigned};
2824SubExprInfo ExprEmitter::visitTypeOp(BitcastOp op) {
2828 Type toType = op.getType();
2830 toType, op.getInput().getType(), op.getLoc(),
2831 [&](Location loc) { return emitter.emitError(loc,
""); })) {
2833 ps.invokeWithStringOS(
2834 [&](
auto &os) { emitter.emitTypeDims(toType, op.getLoc(), os); });
2837 return emitSubExpr(op.getInput(), LowestPrecedence);
2840SubExprInfo ExprEmitter::visitComb(ICmpOp op) {
2841 const char *symop[] = {
"==",
"!=",
"<",
"<=",
">",
">=",
"<",
2842 "<=",
">",
">=",
"===",
"!==",
"==?",
"!=?"};
2843 SubExprSignRequirement signop[] = {
2845 NoRequirement, NoRequirement,
2847 RequireSigned, RequireSigned, RequireSigned, RequireSigned,
2849 RequireUnsigned, RequireUnsigned, RequireUnsigned, RequireUnsigned,
2851 NoRequirement, NoRequirement, NoRequirement, NoRequirement};
2853 auto pred =
static_cast<uint64_t
>(op.getPredicate());
2854 assert(pred <
sizeof(symop) /
sizeof(symop[0]));
2857 if (op.isEqualAllOnes())
2858 return emitUnary(op,
"&",
true);
2861 if (op.isNotEqualZero())
2862 return emitUnary(op,
"|",
true);
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;
2875 precedence = Comparison;
2878 auto result = emitBinary(op, precedence, symop[pred], signop[pred]);
2882 result.signedness = IsUnsigned;
2886SubExprInfo ExprEmitter::visitComb(ExtractOp op) {
2888 emitError(op,
"SV attributes emission is unimplemented for the op");
2890 unsigned loBit = op.getLowBit();
2891 unsigned hiBit = loBit + cast<IntegerType>(op.getType()).getWidth() - 1;
2893 auto x = emitSubExpr(op.getInput(), LowestPrecedence);
2894 assert((x.precedence == Symbol ||
2896 "should be handled by isExpressionUnableToInline");
2901 op.getInput().getType().getIntOrFloatBitWidth() == hiBit + 1)
2905 ps.addAsString(hiBit);
2906 if (hiBit != loBit) {
2908 ps.addAsString(loBit);
2911 return {Unary, IsUnsigned};
2914SubExprInfo ExprEmitter::visitSV(GetModportOp op) {
2916 emitError(op,
"SV attributes emission is unimplemented for the op");
2918 auto decl = op.getReferencedDecl(state.symbolCache);
2921 return {Selection, IsUnsigned};
2924SubExprInfo ExprEmitter::visitSV(SystemFunctionOp op) {
2926 emitError(op,
"SV attributes emission is unimplemented for the op");
2928 ps <<
"$" << PPExtString(op.getFnName()) <<
"(";
2929 ps.scopedBox(PP::ibox0, [&]() {
2931 op.getOperands(), [&](Value v) { emitSubExpr(v, LowestPrecedence); },
2932 [&]() { ps <<
"," << PP::space; });
2935 return {Symbol, IsUnsigned};
2938SubExprInfo ExprEmitter::visitSV(ReadInterfaceSignalOp op) {
2940 emitError(op,
"SV attributes emission is unimplemented for the op");
2942 auto decl = op.getReferencedDecl(state.symbolCache);
2946 return {Selection, IsUnsigned};
2949SubExprInfo ExprEmitter::visitSV(XMROp op) {
2951 emitError(op,
"SV attributes emission is unimplemented for the op");
2953 if (op.getIsRooted())
2955 for (
auto s : op.getPath())
2956 ps << PPExtString(cast<StringAttr>(s).getValue()) <<
".";
2957 ps << PPExtString(op.getTerminal());
2958 return {Selection, IsUnsigned};
2963SubExprInfo ExprEmitter::visitSV(XMRRefOp op) {
2965 emitError(op,
"SV attributes emission is unimplemented for the op");
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());
2973 for (
auto sym : namepath) {
2975 auto innerRef = cast<InnerRefAttr>(sym);
2977 innerRef.getName());
2978 if (ref.hasPort()) {
2984 auto leaf = op.getVerbatimSuffixAttr();
2985 if (leaf && leaf.size())
2986 ps << PPExtString(leaf);
2987 return {Selection, IsUnsigned};
2990SubExprInfo ExprEmitter::visitVerbatimExprOp(Operation *op, ArrayAttr symbols) {
2992 emitError(op,
"SV attributes emission is unimplemented for the op");
2994 emitTextWithSubstitutions(
2995 ps, op->getAttrOfType<StringAttr>(
"format_string").getValue(), op,
2996 [&](Value operand) { emitSubExpr(operand, LowestPrecedence); }, symbols);
2998 return {Unary, IsUnsigned};
3001template <
typename MacroTy>
3002SubExprInfo ExprEmitter::emitMacroCall(MacroTy op) {
3004 emitError(op,
"SV attributes emission is unimplemented for the op");
3007 auto macroOp = op.getReferencedMacro(&state.symbolCache);
3008 assert(macroOp &&
"Invalid IR");
3010 macroOp.getVerilogName() ? *macroOp.getVerilogName() : macroOp.getName();
3011 ps <<
"`" << PPExtString(name);
3012 if (!op.getInputs().empty()) {
3014 llvm::interleaveComma(op.getInputs(), ps, [&](Value val) {
3015 emitExpression(val, LowestPrecedence, false);
3019 return {LowestPrecedence, IsUnsigned};
3022SubExprInfo ExprEmitter::visitSV(MacroRefExprOp op) {
3023 return emitMacroCall(op);
3026SubExprInfo ExprEmitter::visitSV(MacroRefExprSEOp op) {
3027 return emitMacroCall(op);
3030SubExprInfo ExprEmitter::visitSV(ConstantXOp op) {
3032 emitError(op,
"SV attributes emission is unimplemented for the op");
3034 ps.addAsString(op.getWidth());
3036 return {Unary, IsUnsigned};
3039SubExprInfo ExprEmitter::visitSV(ConstantStrOp op) {
3041 emitError(op,
"SV attributes emission is unimplemented for the op");
3043 ps.writeQuotedEscaped(op.getStr());
3044 return {Symbol, IsUnsigned};
3047SubExprInfo ExprEmitter::visitSV(ConcatStrOp op) {
3049 emitError(op,
"SV attributes emission is unimplemented for the op");
3053 emitBracedList(op.getInputs());
3054 return {Symbol, IsUnsigned};
3057SubExprInfo ExprEmitter::visitSV(ConstantZOp op) {
3059 emitError(op,
"SV attributes emission is unimplemented for the op");
3061 ps.addAsString(op.getWidth());
3063 return {Unary, IsUnsigned};
3066SubExprInfo ExprEmitter::printConstantScalar(APInt &value, IntegerType type) {
3067 bool isNegated =
false;
3070 if (signPreference == RequireSigned && value.isNegative() &&
3071 !value.isMinSignedValue()) {
3076 ps.addAsString(type.getWidth());
3080 if (signPreference == RequireSigned)
3086 SmallString<32> valueStr;
3088 (-value).toStringUnsigned(valueStr, 16);
3090 value.toStringUnsigned(valueStr, 16);
3093 return {Unary, signPreference == RequireSigned ? IsSigned : IsUnsigned};
3096SubExprInfo ExprEmitter::visitTypeOp(ConstantOp op) {
3098 emitError(op,
"SV attributes emission is unimplemented for the op");
3100 auto value = op.getValue();
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};
3111 return printConstantScalar(value, hw::type_cast<IntegerType>(op.getType()));
3114void ExprEmitter::printConstantArray(ArrayAttr elementValues, Type
elementType,
3115 bool printAsPattern, Operation *op) {
3116 if (printAsPattern && !isAssignmentLikeContext)
3117 emitAssignmentPatternContextError(op);
3118 StringRef openDelim = printAsPattern ?
"'{" :
"{";
3121 elementValues, [&]() { ps << openDelim; },
3122 [&](Attribute elementValue) {
3123 printConstantAggregate(elementValue,
elementType, op);
3125 [&]() { ps <<
"}"; });
3128void ExprEmitter::printConstantStruct(
3129 ArrayRef<hw::detail::FieldInfo> fieldInfos, ArrayAttr fieldValues,
3130 bool printAsPattern, Operation *op) {
3131 if (printAsPattern && !isAssignmentLikeContext)
3132 emitAssignmentPatternContextError(op);
3139 auto fieldRange = llvm::make_filter_range(
3140 llvm::zip(fieldInfos, fieldValues), [](
const auto &fieldAndValue) {
3145 if (printAsPattern) {
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);
3156 [&]() { ps <<
"}"; });
3159 fieldRange, [&]() { ps <<
"{"; },
3160 [&](
const auto &fieldAndValue) {
3161 ps.scopedBox(PP::ibox2, [&]() {
3162 const auto &[field, value] = fieldAndValue;
3163 printConstantAggregate(value, field.type, op);
3166 [&]() { ps <<
"}"; });
3170void ExprEmitter::printConstantAggregate(Attribute attr, Type type,
3173 if (
auto arrayType = hw::type_dyn_cast<ArrayType>(type))
3174 return printConstantArray(cast<ArrayAttr>(attr), arrayType.getElementType(),
3175 isAssignmentLikeContext, op);
3178 if (
auto arrayType = hw::type_dyn_cast<UnpackedArrayType>(type))
3179 return printConstantArray(cast<ArrayAttr>(attr), arrayType.getElementType(),
3183 if (
auto structType = hw::type_dyn_cast<StructType>(type))
3184 return printConstantStruct(structType.getElements(), cast<ArrayAttr>(attr),
3185 isAssignmentLikeContext, op);
3187 if (
auto intType = hw::type_dyn_cast<IntegerType>(type)) {
3188 auto value = cast<IntegerAttr>(attr).getValue();
3189 printConstantScalar(value, intType);
3193 emitOpError(op,
"contains constant of type ")
3194 << type <<
" which cannot be emitted as Verilog";
3197SubExprInfo ExprEmitter::visitTypeOp(AggregateConstantOp op) {
3199 emitError(op,
"SV attributes emission is unimplemented for the op");
3203 "zero-bit types not allowed at this point");
3205 printConstantAggregate(op.getFields(), op.getType(), op);
3206 return {Symbol, IsUnsigned};
3209SubExprInfo ExprEmitter::visitTypeOp(ParamValueOp op) {
3211 emitError(op,
"SV attributes emission is unimplemented for the op");
3213 return ps.invokeWithStringOS([&](
auto &os) {
3214 return emitter.printParamValue(op.getValue(), os, [&]() {
3215 return op->emitOpError(
"invalid parameter use");
3222SubExprInfo ExprEmitter::visitTypeOp(ArraySliceOp op) {
3224 emitError(op,
"SV attributes emission is unimplemented for the op");
3226 auto arrayPrec = emitSubExpr(op.getInput(), Selection);
3230 emitSubExpr(op.getLowIndex(), LowestPrecedence);
3232 ps.addAsString(dstWidth);
3234 return {Selection, arrayPrec.signedness};
3237SubExprInfo ExprEmitter::visitTypeOp(ArrayGetOp op) {
3238 emitSubExpr(op.getInput(), Selection);
3243 emitSubExpr(op.getIndex(), LowestPrecedence);
3245 emitSVAttributes(op);
3246 return {Selection, IsUnsigned};
3250SubExprInfo ExprEmitter::visitTypeOp(ArrayCreateOp op) {
3252 emitError(op,
"SV attributes emission is unimplemented for the op");
3254 if (op.isUniform()) {
3256 ps.addAsString(op.getInputs().size());
3258 emitSubExpr(op.getUniformElement(), LowestPrecedence);
3262 op.getInputs(), [&]() { ps <<
"{"; },
3265 emitSubExprIBox2(v);
3268 [&]() { ps <<
"}"; });
3270 return {Unary, IsUnsigned};
3273SubExprInfo ExprEmitter::visitSV(UnpackedArrayCreateOp op) {
3275 emitError(op,
"SV attributes emission is unimplemented for the op");
3278 llvm::reverse(op.getInputs()), [&]() { ps <<
"'{"; },
3279 [&](Value v) { emitSubExprIBox2(v); }, [&]() { ps <<
"}"; });
3280 return {Unary, IsUnsigned};
3283SubExprInfo ExprEmitter::visitTypeOp(ArrayConcatOp op) {
3285 emitError(op,
"SV attributes emission is unimplemented for the op");
3287 emitBracedList(op.getOperands());
3288 return {Unary, IsUnsigned};
3291SubExprInfo ExprEmitter::visitSV(ArrayIndexInOutOp op) {
3293 emitError(op,
"SV attributes emission is unimplemented for the op");
3295 auto index = op.getIndex();
3296 auto arrayPrec = emitSubExpr(op.getInput(), Selection);
3301 emitSubExpr(index, LowestPrecedence);
3303 return {Selection, arrayPrec.signedness};
3306SubExprInfo ExprEmitter::visitSV(IndexedPartSelectInOutOp op) {
3308 emitError(op,
"SV attributes emission is unimplemented for the op");
3310 auto prec = emitSubExpr(op.getInput(), Selection);
3312 emitSubExpr(op.getBase(), LowestPrecedence);
3313 if (op.getDecrement())
3317 ps.addAsString(op.getWidth());
3319 return {Selection, prec.signedness};
3322SubExprInfo ExprEmitter::visitSV(IndexedPartSelectOp op) {
3324 emitError(op,
"SV attributes emission is unimplemented for the op");
3326 auto info = emitSubExpr(op.getInput(), LowestPrecedence);
3328 emitSubExpr(op.getBase(), LowestPrecedence);
3329 if (op.getDecrement())
3333 ps.addAsString(op.getWidth());
3338SubExprInfo ExprEmitter::visitSV(StructFieldInOutOp op) {
3340 emitError(op,
"SV attributes emission is unimplemented for the op");
3342 auto prec = emitSubExpr(op.getInput(), Selection);
3344 << PPExtString(emitter.getVerilogStructFieldName(op.getFieldAttr()));
3345 return {Selection, prec.signedness};
3348SubExprInfo ExprEmitter::visitSV(SampledOp op) {
3350 emitError(op,
"SV attributes emission is unimplemented for the op");
3353 auto info = emitSubExpr(op.getExpression(), LowestPrecedence);
3358SubExprInfo ExprEmitter::visitSV(SFormatFOp op) {
3360 emitError(op,
"SV attributes emission is unimplemented for the op");
3363 ps.scopedBox(PP::ibox0, [&]() {
3364 ps.writeQuotedEscaped(op.getFormatString());
3371 for (
auto operand : op.getSubstitutions()) {
3372 ps <<
"," << PP::space;
3373 emitSubExpr(operand, LowestPrecedence);
3377 return {Symbol, IsUnsigned};
3380SubExprInfo ExprEmitter::visitSV(TimeOp op) {
3382 emitError(op,
"SV attributes emission is unimplemented for the op");
3385 return {Symbol, IsUnsigned};
3388SubExprInfo ExprEmitter::visitSV(STimeOp op) {
3390 emitError(op,
"SV attributes emission is unimplemented for the op");
3393 return {Symbol, IsUnsigned};
3396SubExprInfo ExprEmitter::visitComb(MuxOp op) {
3410 return ps.scopedBox(PP::cbox0, [&]() -> SubExprInfo {
3411 ps.scopedBox(PP::ibox0, [&]() {
3412 emitSubExpr(op.getCond(), VerilogPrecedence(Conditional - 1));
3414 ps << BreakToken(1, 2);
3416 emitSVAttributes(op);
3418 auto lhsInfo = ps.scopedBox(PP::ibox0, [&]() {
3419 return emitSubExpr(op.getTrueValue(), VerilogPrecedence(Conditional - 1));
3421 ps << BreakToken(1, 2) <<
": ";
3423 auto rhsInfo = ps.scopedBox(PP::ibox0, [&]() {
3424 return emitSubExpr(op.getFalseValue(), Conditional);
3427 SubExprSignResult signedness = IsUnsigned;
3428 if (lhsInfo.signedness == IsSigned && rhsInfo.signedness == IsSigned)
3429 signedness = IsSigned;
3431 return {Conditional, signedness};
3435SubExprInfo ExprEmitter::visitComb(ReverseOp op) {
3437 emitError(op,
"SV attributes emission is unimplemented for the op");
3440 emitSubExpr(op.getInput(), LowestPrecedence);
3443 return {Symbol, IsUnsigned};
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);
3454 auto filteredFields = llvm::make_filter_range(
3455 llvm::enumerate(fieldInfos),
3456 [](
const auto &field) {
return !
isZeroBitType(field.value().type); });
3458 if (printAsPattern) {
3460 filteredFields, [&]() { ps <<
"'{"; },
3461 [&](
const auto &field) {
3462 ps.scopedBox(PP::ibox2, [&]() {
3464 emitter.getVerilogStructFieldName(field.value().name))
3465 <<
":" << PP::space;
3466 fieldFn(field.value(), field.index());
3469 [&]() { ps <<
"}"; });
3472 filteredFields, [&]() { ps <<
"{"; },
3473 [&](
const auto &field) {
3474 ps.scopedBox(PP::ibox2,
3475 [&]() { fieldFn(field.value(), field.index()); });
3477 [&]() { ps <<
"}"; });
3480 return {Selection, IsUnsigned};
3483SubExprInfo ExprEmitter::visitTypeOp(StructCreateOp op) {
3485 emitError(op,
"SV attributes emission is unimplemented for the op");
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,
3496 isAssignmentLikeContext);
3498 printAsPattern, op);
3501SubExprInfo ExprEmitter::visitTypeOp(StructExtractOp op) {
3503 emitError(op,
"SV attributes emission is unimplemented for the op");
3505 emitSubExpr(op.getInput(), Selection);
3507 << PPExtString(emitter.getVerilogStructFieldName(op.getFieldNameAttr()));
3508 return {Selection, IsUnsigned};
3511SubExprInfo ExprEmitter::visitTypeOp(StructInjectOp op) {
3513 emitError(op,
"SV attributes emission is unimplemented for the op");
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);
3525 emitSubExpr(op.getInput(), Selection);
3527 << PPExtString(emitter.getVerilogStructFieldName(field.name));
3530 printAsPattern, op);
3533SubExprInfo ExprEmitter::visitTypeOp(EnumConstantOp op) {
3534 ps << PPSaveString(emitter.fieldNameResolver.
getEnumFieldName(op.getField()));
3535 return {Selection, IsUnsigned};
3538SubExprInfo ExprEmitter::visitTypeOp(EnumCmpOp op) {
3540 emitError(op,
"SV attributes emission is unimplemented for the op");
3541 auto result = emitBinary(op, Comparison,
"==", NoRequirement);
3544 result.signedness = IsUnsigned;
3548SubExprInfo ExprEmitter::visitTypeOp(UnionCreateOp op) {
3550 emitError(op,
"SV attributes emission is unimplemented for the op");
3554 auto unionWidth = hw::getBitWidth(unionType);
3555 auto &element = unionType.getElements()[op.getFieldIndex()];
3556 auto elementWidth = hw::getBitWidth(element.type);
3559 if (!elementWidth) {
3560 ps.addAsString(unionWidth);
3562 return {Unary, IsUnsigned};
3566 if (elementWidth == unionWidth) {
3567 emitSubExpr(op.getInput(), LowestPrecedence);
3568 return {Unary, IsUnsigned};
3573 auto elementOffset =
static_cast<int64_t
>(element.offset);
3574 int64_t prePadding = unionWidth - elementWidth - elementOffset;
3576 ps.scopedBox(PP::ibox0, [&]() {
3577 if (prePadding > 0) {
3578 ps.addAsString(prePadding);
3579 ps <<
"'h0," << PP::space;
3581 emitSubExpr(op.getInput(), Selection);
3582 if (elementOffset > 0) {
3583 ps <<
"," << PP::space;
3584 ps.addAsString(elementOffset);
3590 return {Unary, IsUnsigned};
3593SubExprInfo ExprEmitter::visitTypeOp(UnionExtractOp op) {
3595 emitError(op,
"SV attributes emission is unimplemented for the op");
3596 emitSubExpr(op.getInput(), Selection);
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);
3609 ps <<
"." << PPExtString(verilogFieldName);
3612 ps <<
"." << PPExtString(verilogFieldName);
3613 return {Selection, IsUnsigned};
3616SubExprInfo ExprEmitter::visitUnhandledExpr(Operation *op) {
3617 emitOpError(op,
"cannot emit this expression to Verilog");
3618 ps <<
"<<unsupported expr: " << PPExtString(op->getName().getStringRef())
3620 return {Symbol, IsUnsigned};
3636enum class PropertyPrecedence {
3656struct EmittedProperty {
3658 PropertyPrecedence precedence;
3663class PropertyEmitter :
public EmitterBase,
3664 public ltl::Visitor<PropertyEmitter, EmittedProperty> {
3668 PropertyEmitter(ModuleEmitter &emitter,
3669 SmallPtrSetImpl<Operation *> &emittedOps)
3670 : PropertyEmitter(emitter, emittedOps, localTokens) {}
3671 PropertyEmitter(ModuleEmitter &emitter,
3672 SmallPtrSetImpl<Operation *> &emittedOps,
3674 : EmitterBase(emitter.state), emitter(emitter), emittedOps(emittedOps),
3676 ps(buffer, state.saver, state.options.emitVerilogLocations) {
3680 void emitAssertPropertyDisable(
3681 Value property, Value disable,
3682 PropertyPrecedence parenthesizeIfLooserThan = PropertyPrecedence::Lowest);
3684 void emitAssertPropertyBody(
3685 Value property, Value disable,
3686 PropertyPrecedence parenthesizeIfLooserThan = PropertyPrecedence::Lowest);
3688 void emitAssertPropertyBody(
3689 Value property, sv::EventControl event, Value clock, Value disable,
3690 PropertyPrecedence parenthesizeIfLooserThan = PropertyPrecedence::Lowest);
3695 emitNestedProperty(Value property,
3696 PropertyPrecedence parenthesizeIfLooserThan);
3697 using ltl::Visitor<PropertyEmitter, EmittedProperty>::visitLTL;
3698 friend class ltl::Visitor<PropertyEmitter, EmittedProperty>;
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,
3718 EmittedProperty visitLTL(ltl::ClockOp op);
3719 EmittedProperty visitLTL(ltl::WeakOp op);
3720 EmittedProperty visitLTL(ltl::StrongOp op);
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);
3728 ModuleEmitter &emitter;
3733 SmallPtrSetImpl<Operation *> &emittedOps;
3736 SmallVector<Token> localTokens;
3742 TokenStreamWithCallback<OpLocMap, CallbackDataTy, BufferingPP> ps;
3749void PropertyEmitter::emitAssertPropertyDisable(
3750 Value property, Value disable,
3751 PropertyPrecedence parenthesizeIfLooserThan) {
3754 ps <<
"disable iff" << PP::nbsp <<
"(";
3755 ps.scopedBox(PP::ibox2, [&] {
3756 emitNestedProperty(disable, PropertyPrecedence::Unary);
3762 ps.scopedBox(PP::ibox0,
3763 [&] { emitNestedProperty(property, parenthesizeIfLooserThan); });
3769void PropertyEmitter::emitAssertPropertyBody(
3770 Value property, Value disable,
3771 PropertyPrecedence parenthesizeIfLooserThan) {
3772 assert(localTokens.empty());
3774 emitAssertPropertyDisable(property, disable, parenthesizeIfLooserThan);
3779 if (&buffer.
tokens == &localTokens)
3780 buffer.
flush(state.pp);
3783void PropertyEmitter::emitAssertPropertyBody(
3784 Value property, sv::EventControl event, Value clock, Value disable,
3785 PropertyPrecedence parenthesizeIfLooserThan) {
3786 assert(localTokens.empty());
3789 ps.scopedBox(PP::ibox2, [&] {
3790 ps << PPExtString(stringifyEventControl(event)) << PP::space;
3791 emitNestedProperty(clock, PropertyPrecedence::Lowest);
3797 emitAssertPropertyDisable(property, disable, parenthesizeIfLooserThan);
3802 if (&buffer.
tokens == &localTokens)
3803 buffer.
flush(state.pp);
3806EmittedProperty PropertyEmitter::emitNestedProperty(
3807 Value property, PropertyPrecedence parenthesizeIfLooserThan) {
3817 if (!isa<ltl::SequenceType, ltl::PropertyType>(property.getType())) {
3818 ExprEmitter(emitter, emittedOps, buffer.
tokens)
3819 .emitExpression(property, LowestPrecedence,
3821 return {PropertyPrecedence::Symbol};
3824 unsigned startIndex = buffer.
tokens.size();
3825 auto info = dispatchLTLVisitor(property.getDefiningOp());
3830 if (
info.precedence > parenthesizeIfLooserThan) {
3832 buffer.
tokens.insert(buffer.
tokens.begin() + startIndex, BeginToken(0));
3833 buffer.
tokens.insert(buffer.
tokens.begin() + startIndex, StringToken(
"("));
3835 ps << PP::end <<
")";
3837 info.precedence = PropertyPrecedence::Symbol;
3841 emittedOps.insert(property.getDefiningOp());
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};
3851EmittedProperty PropertyEmitter::visitLTL(ltl::BooleanConstantOp op) {
3853 ps << (op.getValueAttr().getValue() ?
"1'h1" :
"1'h0");
3854 return {PropertyPrecedence::Symbol};
3857EmittedProperty PropertyEmitter::visitLTL(ltl::AndOp op) {
3860 [&](
auto input) { emitNestedProperty(input, PropertyPrecedence::And); },
3861 [&]() { ps << PP::space <<
"and" << PP::nbsp; });
3862 return {PropertyPrecedence::And};
3865EmittedProperty PropertyEmitter::visitLTL(ltl::OrOp op) {
3868 [&](
auto input) { emitNestedProperty(input, PropertyPrecedence::Or); },
3869 [&]() { ps << PP::space <<
"or" << PP::nbsp; });
3870 return {PropertyPrecedence::Or};
3873EmittedProperty PropertyEmitter::visitLTL(ltl::IntersectOp op) {
3877 emitNestedProperty(input, PropertyPrecedence::Intersect);
3879 [&]() { ps << PP::space <<
"intersect" << PP::nbsp; });
3880 return {PropertyPrecedence::Intersect};
3883void PropertyEmitter::emitLTLDelay(int64_t delay,
3884 std::optional<int64_t> length) {
3888 ps.addAsString(delay);
3891 ps.addAsString(delay);
3893 ps.addAsString(delay + *length);
3899 }
else if (delay == 1) {
3903 ps.addAsString(delay);
3909void PropertyEmitter::emitLTLClockingEvent(ltl::ClockEdge edge, Value clock) {
3911 ps.scopedBox(PP::ibox2, [&] {
3912 ps << PPExtString(stringifyClockEdge(edge)) << PP::space;
3913 emitNestedProperty(clock, PropertyPrecedence::Lowest);
3918EmittedProperty PropertyEmitter::visitLTL(ltl::DelayOp op) {
3919 emitLTLDelay(op.getDelay(), op.getLength());
3921 emitNestedProperty(op.getInput(), PropertyPrecedence::Concat);
3922 return {PropertyPrecedence::Concat};
3925EmittedProperty PropertyEmitter::visitLTL(ltl::ClockedDelayOp op) {
3926 emitLTLClockingEvent(op.getEdge(), op.getClock());
3928 emitLTLDelay(op.getDelay(), op.getLength());
3930 emitNestedProperty(op.getInput(), PropertyPrecedence::Concat);
3931 return {PropertyPrecedence::Clocking};
3934void PropertyEmitter::emitLTLConcat(ValueRange inputs) {
3935 bool addSeparator =
false;
3936 for (
auto input : inputs) {
3939 if (!input.getDefiningOp<ltl::DelayOp>())
3940 ps <<
"##0" << PP::space;
3942 addSeparator =
true;
3943 emitNestedProperty(input, PropertyPrecedence::Concat);
3947EmittedProperty PropertyEmitter::visitLTL(ltl::ConcatOp op) {
3948 emitLTLConcat(op.getInputs());
3949 return {PropertyPrecedence::Concat};
3952EmittedProperty PropertyEmitter::visitLTL(ltl::RepeatOp op) {
3953 emitNestedProperty(op.getInput(), PropertyPrecedence::Repeat);
3954 if (
auto more = op.getMore()) {
3956 ps.addAsString(op.getBase());
3959 ps.addAsString(op.getBase() + *more);
3963 if (op.getBase() == 0) {
3965 }
else if (op.getBase() == 1) {
3969 ps.addAsString(op.getBase());
3973 return {PropertyPrecedence::Repeat};
3976EmittedProperty PropertyEmitter::visitLTL(ltl::GoToRepeatOp op) {
3977 emitNestedProperty(op.getInput(), PropertyPrecedence::Repeat);
3979 auto more = op.getMore();
3981 ps.addAsString(op.getBase());
3984 ps.addAsString(op.getBase() + more);
3988 return {PropertyPrecedence::Repeat};
3991EmittedProperty PropertyEmitter::visitLTL(ltl::NonConsecutiveRepeatOp op) {
3992 emitNestedProperty(op.getInput(), PropertyPrecedence::Repeat);
3994 auto more = op.getMore();
3996 ps.addAsString(op.getBase());
3999 ps.addAsString(op.getBase() + more);
4003 return {PropertyPrecedence::Repeat};
4006EmittedProperty PropertyEmitter::visitLTL(ltl::NotOp op) {
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"
4013 accept.getCondition(), innerNot.getInput());
4016 if (
auto ev = op.getInput().getDefiningOp<ltl::EventuallyOp>()) {
4017 ps <<
"always" << PP::space;
4018 if (
auto innerNot = ev.getInput().getDefiningOp<ltl::NotOp>()) {
4020 emitNestedProperty(innerNot.getInput(), PropertyPrecedence::Qualifier);
4023 ps <<
"not" << PP::space;
4024 emitNestedProperty(ev.getInput(), PropertyPrecedence::Unary);
4026 return {PropertyPrecedence::Qualifier};
4028 ps <<
"not" << PP::space;
4029 emitNestedProperty(op.getInput(), PropertyPrecedence::Unary);
4030 return {PropertyPrecedence::Unary};
4036 auto concatOp = value.getDefiningOp<ltl::ConcatOp>();
4037 if (!concatOp || concatOp.getInputs().size() < 2)
4039 auto delayOp = concatOp.getInputs().back().getDefiningOp<ltl::DelayOp>();
4040 if (!delayOp || delayOp.getDelay() != 1 || delayOp.getLength() != 0)
4042 auto constOp = delayOp.getInput().getDefiningOp<
ConstantOp>();
4043 if (!constOp || !constOp.getValue().isOne())
4045 return concatOp.getInputs().drop_back();
4048EmittedProperty PropertyEmitter::visitLTL(ltl::ImplicationOp op) {
4052 emitLTLConcat(range);
4053 ps << PP::space <<
"|=>" << PP::nbsp;
4055 emitNestedProperty(op.getAntecedent(), PropertyPrecedence::Implication);
4056 ps << PP::space <<
"|->" << PP::nbsp;
4058 emitNestedProperty(op.getConsequent(), PropertyPrecedence::Implication);
4059 return {PropertyPrecedence::Implication};
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};
4069EmittedProperty PropertyEmitter::visitLTL(ltl::EventuallyOp op) {
4070 ps <<
"s_eventually" << PP::space;
4071 emitNestedProperty(op.getInput(), PropertyPrecedence::Qualifier);
4072 return {PropertyPrecedence::Qualifier};
4075EmittedProperty PropertyEmitter::emitAcceptRejectOn(StringRef mnemonic,
4078 ps << mnemonic << PP::nbsp <<
"(";
4079 ps.scopedBox(PP::ibox0, [&] {
4080 emitNestedProperty(condition, PropertyPrecedence::Lowest);
4084 emitNestedProperty(input, PropertyPrecedence::Qualifier);
4085 return {PropertyPrecedence::Qualifier};
4088EmittedProperty PropertyEmitter::visitLTL(ltl::AcceptOnOp op) {
4089 return emitAcceptRejectOn(op.getSync() ?
"sync_accept_on" :
"accept_on",
4090 op.getCondition(), op.getInput());
4093EmittedProperty PropertyEmitter::visitLTL(ltl::ClockOp op) {
4094 emitLTLClockingEvent(op.getEdge(), op.getClock());
4096 emitNestedProperty(op.getInput(), PropertyPrecedence::Clocking);
4097 return {PropertyPrecedence::Clocking};
4101EmittedProperty PropertyEmitter::emitWeakStrongOp(StringRef mnemonic,
4103 ps << mnemonic << PP::space <<
"(";
4104 ps.scopedBox(PP::ibox2, [&] {
4105 emitNestedProperty(input, PropertyPrecedence::Unary);
4108 return {PropertyPrecedence::Lowest};
4111EmittedProperty PropertyEmitter::visitLTL(ltl::WeakOp op) {
4112 return emitWeakStrongOp(
"weak", op.getInput());
4115EmittedProperty PropertyEmitter::visitLTL(ltl::StrongOp op) {
4116 return emitWeakStrongOp(
"strong", op.getInput());
4126class NameCollector {
4128 NameCollector(ModuleEmitter &moduleEmitter) : moduleEmitter(moduleEmitter) {}
4132 void collectNames(
Block &block);
4134 size_t getMaxDeclNameWidth()
const {
return maxDeclNameWidth; }
4135 size_t getMaxTypeWidth()
const {
return maxTypeWidth; }
4138 size_t maxDeclNameWidth = 0, maxTypeWidth = 0;
4139 ModuleEmitter &moduleEmitter;
4144 static constexpr size_t maxTypeWidthBound = 32;
4149void NameCollector::collectNames(
Block &block) {
4152 for (
auto &op : block) {
4156 if (isa<InstanceOp, InterfaceInstanceOp, FuncCallProceduralOp, FuncCallOp>(
4159 if (isa<ltl::LTLDialect, debug::DebugDialect>(op.getDialect()))
4163 for (
auto result : op.getResults()) {
4165 maxDeclNameWidth = std::max(declName.size(), maxDeclNameWidth);
4166 SmallString<16> typeString;
4170 llvm::raw_svector_ostream stringStream(typeString);
4172 stringStream, op.getLoc());
4174 if (typeString.size() <= maxTypeWidthBound)
4175 maxTypeWidth = std::max(typeString.size(), maxTypeWidth);
4182 if (isa<IfDefProceduralOp, OrderedOutputOp>(op)) {
4183 for (
auto ®ion : op.getRegions()) {
4184 if (!region.empty())
4185 collectNames(region.front());
4199class StmtEmitter :
public EmitterBase,
4200 public hw::StmtVisitor<StmtEmitter, LogicalResult>,
4201 public sv::Visitor<StmtEmitter, LogicalResult>,
4202 public verif::Visitor<StmtEmitter, LogicalResult> {
4206 StmtEmitter(ModuleEmitter &emitter,
const LoweringOptions &options)
4207 : EmitterBase(emitter.state), emitter(emitter), options(options) {}
4209 void emitStatement(Operation *op);
4210 void emitStatementBlock(
Block &body);
4213 LogicalResult emitDeclaration(Operation *op);
4216 void collectNamesAndCalculateDeclarationWidths(
Block &block);
4219 emitExpression(Value exp, SmallPtrSetImpl<Operation *> &emittedExprs,
4220 VerilogPrecedence parenthesizeIfLooserThan = LowestPrecedence,
4221 bool isAssignmentLikeContext =
false);
4222 void emitSVAttributes(Operation *op);
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>;
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(); }
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>
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);
4263 LogicalResult visitStmt(InstanceOp op);
4264 void emitInstancePortList(Operation *op, ModulePortInfo &modPortInfo,
4265 ArrayRef<Value> instPortValues);
4267 LogicalResult visitStmt(TypeScopeOp op);
4268 LogicalResult visitStmt(TypedeclOp op);
4269 LogicalResult visitSV(PackageOp op);
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());
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>
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);
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);
4300 LogicalResult emitSeverityMessageTask(Operation *op, PPExtString taskName,
4301 std::optional<unsigned> verbosity,
4303 ValueRange operands);
4306 template <
typename OpTy>
4307 LogicalResult emitNonfatalMessageOp(OpTy op,
const char *taskName) {
4308 return emitSeverityMessageTask(op, PPExtString(taskName), {},
4309 op.getMessageAttr(), op.getSubstitutions());
4313 template <
typename OpTy>
4314 LogicalResult emitFatalMessageOp(OpTy op) {
4315 return emitSeverityMessageTask(op, PPExtString(
"$fatal"), op.getVerbosity(),
4316 op.getMessageAttr(), op.getSubstitutions());
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);
4328 LogicalResult visitSV(ReadMemOp op);
4330 LogicalResult visitSV(GenerateOp op);
4331 LogicalResult visitSV(GenerateCaseOp op);
4332 LogicalResult visitSV(GenerateForOp op);
4334 LogicalResult visitSV(ForOp op);
4336 void emitAssertionLabel(Operation *op);
4337 void emitAssertionMessage(StringAttr message, ValueRange args,
4338 SmallPtrSetImpl<Operation *> &ops,
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);
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);
4365 void emitBlockAsStatement(
Block *block,
4366 const SmallPtrSetImpl<Operation *> &locationOps,
4367 StringRef multiLineComment = StringRef());
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);
4378 ModuleEmitter &emitter;
4383 size_t maxDeclNameWidth = 0;
4384 size_t maxTypeWidth = 0;
4386 const LoweringOptions &options;
4395void StmtEmitter::emitExpression(Value exp,
4396 SmallPtrSetImpl<Operation *> &emittedExprs,
4397 VerilogPrecedence parenthesizeIfLooserThan,
4398 bool isAssignmentLikeContext) {
4399 ExprEmitter(emitter, emittedExprs)
4400 .emitExpression(exp, parenthesizeIfLooserThan, isAssignmentLikeContext);
4405void StmtEmitter::emitSVAttributes(Operation *op) {
4413 setPendingNewline();
4416void StmtEmitter::emitAssignLike(llvm::function_ref<
void()> emitLHS,
4417 llvm::function_ref<
void()> emitRHS,
4418 PPExtString syntax, PPExtString postSyntax,
4419 std::optional<PPExtString> wordBeforeLHS) {
4421 ps.scopedBox(PP::ibox2, [&]() {
4422 if (wordBeforeLHS) {
4423 ps << *wordBeforeLHS << PP::space;
4427 ps << PP::space << syntax << PP::space;
4429 ps.scopedBox(PP::ibox0, [&]() {
4436template <
typename Op>
4438StmtEmitter::emitAssignLike(Op op, PPExtString syntax,
4439 std::optional<PPExtString> wordBeforeLHS) {
4440 SmallPtrSet<Operation *, 8> ops;
4444 ps.addCallback({op,
true});
4445 emitAssignLike([&]() { emitExpression(op.getDest(), ops); },
4447 emitExpression(op.getSrc(), ops, LowestPrecedence,
4450 syntax, PPExtString(
";"), wordBeforeLHS);
4452 ps.addCallback({op,
false});
4453 emitLocationInfoAndNewLine(ops);
4457LogicalResult StmtEmitter::visitSV(AssignOp op) {
4460 if (isa_and_nonnull<HWInstanceLike, FuncCallOp>(op.getSrc().getDefiningOp()))
4463 if (emitter.assignsInlined.count(op))
4467 emitSVAttributes(op);
4469 return emitAssignLike(op, PPExtString(
"="), PPExtString(
"assign"));
4472LogicalResult StmtEmitter::visitSV(VarAssignOp op) {
4474 emitSVAttributes(op);
4476 return emitAssignLike(op, PPExtString(
"="), PPExtString(
"assign"));
4479LogicalResult StmtEmitter::visitSV(BPAssignOp op) {
4480 if (op.getSrc().getDefiningOp<FuncCallProceduralOp>())
4484 if (emitter.assignsInlined.count(op))
4488 emitSVAttributes(op);
4490 return emitAssignLike(op, PPExtString(
"="));
4493LogicalResult StmtEmitter::visitSV(PAssignOp op) {
4495 emitSVAttributes(op);
4497 return emitAssignLike(op, PPExtString(
"<="));
4500LogicalResult StmtEmitter::visitSV(ForceOp op) {
4502 emitError(op,
"SV attributes emission is unimplemented for the op");
4504 return emitAssignLike(op, PPExtString(
"="), PPExtString(
"force"));
4507LogicalResult StmtEmitter::visitSV(ReleaseOp op) {
4509 emitError(op,
"SV attributes emission is unimplemented for the op");
4512 SmallPtrSet<Operation *, 8> ops;
4514 ps.addCallback({op,
true});
4515 ps.scopedBox(PP::ibox2, [&]() {
4516 ps <<
"release" << PP::space;
4517 emitExpression(op.getDest(), ops);
4520 ps.addCallback({op,
false});
4521 emitLocationInfoAndNewLine(ops);
4525LogicalResult StmtEmitter::visitSV(AliasOp op) {
4527 emitError(op,
"SV attributes emission is unimplemented for the op");
4530 SmallPtrSet<Operation *, 8> ops;
4532 ps.addCallback({op,
true});
4533 ps.scopedBox(PP::ibox2, [&]() {
4534 ps <<
"alias" << PP::space;
4535 ps.scopedBox(PP::cbox0, [&]() {
4537 op.getOperands(), [&](Value v) { emitExpression(v, ops); },
4538 [&]() { ps << PP::nbsp <<
"=" << PP::space; });
4542 ps.addCallback({op,
false});
4543 emitLocationInfoAndNewLine(ops);
4547LogicalResult StmtEmitter::visitSV(InterfaceInstanceOp op) {
4548 auto doNotPrint = op.getDoNotPrint();
4553 emitError(op,
"SV attributes emission is unimplemented for the op");
4556 StringRef prefix =
"";
4557 ps.addCallback({op,
true});
4560 ps <<
"// This interface is elsewhere emitted as a bind statement."
4564 SmallPtrSet<Operation *, 8> ops;
4567 auto *interfaceOp = op.getReferencedInterface(&state.symbolCache);
4568 assert(interfaceOp &&
"InterfaceInstanceOp has invalid symbol that does not "
4569 "point to an interface");
4572 if (!prefix.empty())
4573 ps << PPExtString(prefix);
4574 ps << PPExtString(verilogName)
4576 << PPExtString(op.getName()) <<
"();";
4578 ps.addCallback({op,
false});
4579 emitLocationInfoAndNewLine(ops);
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>();
4593 auto operand = op->getOperand(operandIndex);
4597 if (operand.hasOneUse() && operand.getDefiningOp() &&
4598 isa<InstanceOp>(operand.getDefiningOp())) {
4607 ps.addCallback({op,
true});
4609 ps.scopedBox(isZeroBit ? PP::neverbox : PP::ibox2, [&]() {
4611 ps <<
"// Zero width: ";
4614 ps <<
"assign" << PP::space;
4615 ps << PPExtString(port.getVerilogName());
4616 ps << PP::space <<
"=" << PP::space;
4617 ps.scopedBox(PP::ibox0, [&]() {
4621 isa_and_nonnull<hw::ConstantOp>(operand.getDefiningOp()))
4622 ps <<
"/*Zero width*/";
4624 emitExpression(operand, ops, LowestPrecedence,
4629 ps.addCallback({op,
false});
4630 emitLocationInfoAndNewLine(ops);
4637LogicalResult StmtEmitter::visitStmt(OutputOp op) {
4638 auto parent = op->getParentOfType<PortList>();
4639 ModulePortInfo ports(parent.getPortList());
4640 return emitOutputLikeOp(op, ports);
4643LogicalResult StmtEmitter::visitStmt(TypeScopeOp op) {
4645 auto typescopeDef = (
"_TYPESCOPE_" + op.getSymName()).str();
4646 ps <<
"`ifndef " << typescopeDef << PP::newline;
4647 ps <<
"`define " << typescopeDef;
4648 setPendingNewline();
4649 emitStatementBlock(*op.getBodyBlock());
4651 ps <<
"`endif // " << typescopeDef;
4652 setPendingNewline();
4656LogicalResult StmtEmitter::visitStmt(TypedeclOp op) {
4658 emitError(op,
"SV attributes emission is unimplemented for the op");
4663 ps << PP::neverbox <<
"// ";
4665 SmallPtrSet<Operation *, 8> ops;
4667 ps.scopedBox(PP::ibox2, [&]() {
4668 ps <<
"typedef" << PP::space;
4669 ps.invokeWithStringOS([&](
auto &os) {
4671 op.getAliasType(),
false);
4673 ps << PP::space << PPExtString(op.getPreferredName());
4674 ps.invokeWithStringOS(
4675 [&](
auto &os) { emitter.printUnpackedTypePostfix(op.getType(), os); });
4680 emitLocationInfoAndNewLine(ops);
4684LogicalResult StmtEmitter::visitSV(PackageOp op) {
4685 llvm::SaveAndRestore<Operation *> package(emitter.currentPackage, op);
4687 ps.addCallback({op,
true});
4688 ps <<
"package " << PPExtString(
getSymOpName(op)) <<
";";
4689 setPendingNewline();
4690 ps.scopedBox(PP::bbox2, [&]() { emitStatementBlock(*op.getBodyBlock()); });
4693 ps.addCallback({op,
false});
4694 setPendingNewline();
4698template <
typename CallOpTy>
4699LogicalResult StmtEmitter::emitFunctionCall(CallOpTy op) {
4703 dyn_cast<FuncOp>(state.symbolCache.
getDefinition(op.getCalleeAttr()));
4705 SmallPtrSet<Operation *, 8> ops;
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);
4716 auto assignOp = cast<sv::AssignOp>(*explicitReturn.user_begin());
4717 ps <<
"assign" << PP::nbsp;
4718 emitExpression(assignOp.getDest(), ops);
4720 ps << PP::nbsp <<
"=" << PP::nbsp;
4723 auto arguments = callee.getPortList(
true);
4727 bool needsComma =
false;
4728 auto printArg = [&](Value value) {
4730 ps <<
"," << PP::space;
4731 emitExpression(value, ops);
4735 ps.scopedBox(PP::ibox0, [&] {
4736 unsigned inputIndex = 0, outputIndex = 0;
4737 for (
auto arg : arguments) {
4738 if (arg.dir == hw::ModulePort::Output)
4740 op.getResults()[outputIndex++].getUsers().begin()->getOperand(0));
4742 printArg(op.getInputs()[inputIndex++]);
4747 emitLocationInfoAndNewLine(ops);
4751LogicalResult StmtEmitter::visitSV(FuncCallProceduralOp op) {
4752 return emitFunctionCall(op);
4755LogicalResult StmtEmitter::visitSV(FuncCallOp op) {
4756 return emitFunctionCall(op);
4759template <
typename PPS>
4761 bool isAutomatic =
false,
4762 bool emitAsTwoStateType =
false) {
4763 ps <<
"function" << PP::nbsp;
4765 ps <<
"automatic" << PP::nbsp;
4766 auto retType = op.getExplicitlyReturnedType();
4768 ps.invokeWithStringOS([&](
auto &os) {
4769 emitter.printPackedType(retType, os, op->getLoc(), {},
false,
true,
4770 emitAsTwoStateType);
4776 emitter.emitPortList(
4780LogicalResult StmtEmitter::visitSV(ReturnOp op) {
4781 auto parent = op->getParentOfType<sv::FuncOp>();
4782 ModulePortInfo ports(parent.getPortList(
false));
4783 return emitOutputLikeOp(op, ports);
4786LogicalResult StmtEmitter::visitSV(IncludeOp op) {
4788 ps <<
"`include" << PP::nbsp;
4790 if (op.getStyle() == IncludeStyle::System)
4791 ps <<
"<" << op.getTarget() <<
">";
4793 ps <<
"\"" << op.getTarget() <<
"\"";
4795 emitLocationInfo(op.getLoc());
4796 setPendingNewline();
4800LogicalResult StmtEmitter::visitSV(FuncDPIImportOp importOp) {
4803 ps <<
"import" << PP::nbsp <<
"\"DPI-C\"" << PP::nbsp <<
"context"
4807 if (
auto linkageName = importOp.getLinkageName())
4808 ps << *linkageName << PP::nbsp <<
"=" << PP::nbsp;
4810 cast<FuncOp>(state.symbolCache.
getDefinition(importOp.getCalleeAttr()));
4811 assert(op.isDeclaration() &&
"function must be a declaration");
4814 assert(state.pendingNewline);
4820LogicalResult StmtEmitter::visitSV(FFlushOp op) {
4822 emitError(op,
"SV attributes emission is unimplemented for the op");
4825 SmallPtrSet<Operation *, 8> ops;
4828 ps.addCallback({op,
true});
4830 if (
auto fd = op.getFd())
4831 ps.scopedBox(PP::ibox0, [&]() { emitExpression(op.getFd(), ops); });
4834 ps.addCallback({op,
false});
4835 emitLocationInfoAndNewLine(ops);
4839LogicalResult StmtEmitter::visitSV(FCloseOp op) {
4841 emitError(op,
"SV attributes emission is unimplemented for the op");
4844 SmallPtrSet<Operation *, 8> ops;
4847 ps.addCallback({op,
true});
4849 ps.scopedBox(PP::ibox0, [&]() { emitExpression(op.getFd(), ops); });
4851 ps.addCallback({op,
false});
4852 emitLocationInfoAndNewLine(ops);
4856template <
typename OpTy,
typename EmitPrefixFn>
4857LogicalResult StmtEmitter::emitFormattedWriteLikeOp(OpTy op, StringRef callee,
4858 StringRef formatString,
4859 ValueRange substitutions,
4860 EmitPrefixFn emitPrefix) {
4862 emitError(op,
"SV attributes emission is unimplemented for the op");
4865 SmallPtrSet<Operation *, 8> ops;
4868 ps.addCallback({op,
true});
4870 ps.scopedBox(PP::ibox0, [&]() {
4872 ps.writeQuotedEscaped(formatString);
4879 for (
auto operand : substitutions) {
4880 ps <<
"," << PP::space;
4881 emitExpression(operand, ops);
4885 ps.addCallback({op,
false});
4886 emitLocationInfoAndNewLine(ops);
4890LogicalResult StmtEmitter::visitSV(WriteOp op) {
4891 return emitFormattedWriteLikeOp(op,
"$write(", op.getFormatString(),
4892 op.getSubstitutions(),
4893 [&](SmallPtrSetImpl<Operation *> &) {});
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;
4905LogicalResult StmtEmitter::visitSV(VerbatimOp op) {
4907 emitError(op,
"SV attributes emission is unimplemented for the op");
4910 SmallPtrSet<Operation *, 8> ops;
4915 StringRef
string = op.getFormatString();
4916 if (
string.ends_with(
"\n"))
4917 string =
string.drop_back();
4922 bool isFirst =
true;
4925 while (!
string.
empty()) {
4926 auto lhsRhs =
string.split(
'\n');
4930 ps << PP::end << PP::newline << PP::neverbox;
4934 emitTextWithSubstitutions(
4935 ps, lhsRhs.first, op,
4936 [&](Value operand) { emitExpression(operand, ops); }, op.getSymbols());
4937 string = lhsRhs.second;
4942 emitLocationInfoAndNewLine(ops);
4947LogicalResult StmtEmitter::visitSV(MacroRefOp op) {
4949 emitError(op,
"SV attributes emission is unimplemented for the op");
4953 SmallPtrSet<Operation *, 8> ops;
4958 auto macroOp = op.getReferencedMacro(&state.symbolCache);
4959 assert(macroOp &&
"Invalid IR");
4961 macroOp.getVerilogName() ? *macroOp.getVerilogName() : macroOp.getName();
4962 ps <<
"`" << PPExtString(name);
4963 if (!op.getInputs().empty()) {
4965 llvm::interleaveComma(op.getInputs(), ps, [&](Value val) {
4966 emitExpression(val, ops, LowestPrecedence,
4972 emitLocationInfoAndNewLine(ops);
4978StmtEmitter::emitSimulationControlTask(Operation *op, PPExtString taskName,
4979 std::optional<unsigned> verbosity) {
4981 emitError(op,
"SV attributes emission is unimplemented for the op");
4984 SmallPtrSet<Operation *, 8> ops;
4986 ps.addCallback({op,
true});
4988 if (verbosity && *verbosity != 1) {
4990 ps.addAsString(*verbosity);
4994 ps.addCallback({op,
false});
4995 emitLocationInfoAndNewLine(ops);
4999LogicalResult StmtEmitter::visitSV(StopOp op) {
5000 return emitSimulationControlTask(op, PPExtString(
"$stop"), op.getVerbosity());
5003LogicalResult StmtEmitter::visitSV(FinishOp op) {
5004 return emitSimulationControlTask(op, PPExtString(
"$finish"),
5008LogicalResult StmtEmitter::visitSV(ExitOp op) {
5009 return emitSimulationControlTask(op, PPExtString(
"$exit"), {});
5015StmtEmitter::emitSeverityMessageTask(Operation *op, PPExtString taskName,
5016 std::optional<unsigned> verbosity,
5017 StringAttr message, ValueRange operands) {
5019 emitError(op,
"SV attributes emission is unimplemented for the op");
5022 SmallPtrSet<Operation *, 8> ops;
5024 ps.addCallback({op,
true});
5030 if ((verbosity && *verbosity != 1) || message) {
5032 ps.scopedBox(PP::ibox0, [&]() {
5036 ps.addAsString(*verbosity);
5041 ps <<
"," << PP::space;
5042 ps.writeQuotedEscaped(message.getValue());
5044 for (
auto operand : operands) {
5045 ps <<
"," << PP::space;
5046 emitExpression(operand, ops);
5055 ps.addCallback({op,
false});
5056 emitLocationInfoAndNewLine(ops);
5060LogicalResult StmtEmitter::visitSV(FatalProceduralOp op) {
5061 return emitFatalMessageOp(op);
5064LogicalResult StmtEmitter::visitSV(FatalOp op) {
5065 return emitFatalMessageOp(op);
5068LogicalResult StmtEmitter::visitSV(ErrorProceduralOp op) {
5069 return emitNonfatalMessageOp(op,
"$error");
5072LogicalResult StmtEmitter::visitSV(WarningProceduralOp op) {
5073 return emitNonfatalMessageOp(op,
"$warning");
5076LogicalResult StmtEmitter::visitSV(InfoProceduralOp op) {
5077 return emitNonfatalMessageOp(op,
"$info");
5080LogicalResult StmtEmitter::visitSV(ErrorOp op) {
5081 return emitNonfatalMessageOp(op,
"$error");
5084LogicalResult StmtEmitter::visitSV(WarningOp op) {
5085 return emitNonfatalMessageOp(op,
"$warning");
5088LogicalResult StmtEmitter::visitSV(InfoOp op) {
5089 return emitNonfatalMessageOp(op,
"$info");
5092LogicalResult StmtEmitter::visitSV(ReadMemOp op) {
5093 SmallPtrSet<Operation *, 8> ops({op});
5096 ps.addCallback({op,
true});
5098 switch (op.getBaseAttr().getValue()) {
5099 case MemBaseTypeAttr::MemBaseBin:
5102 case MemBaseTypeAttr::MemBaseHex:
5107 ps.scopedBox(PP::ibox0, [&]() {
5108 ps.writeQuotedEscaped(op.getFilename());
5109 ps <<
"," << PP::space;
5110 emitExpression(op.getDest(), ops);
5114 ps.addCallback({op,
false});
5115 emitLocationInfoAndNewLine(ops);
5119LogicalResult StmtEmitter::visitSV(GenerateOp op) {
5120 emitSVAttributes(op);
5123 ps.addCallback({op,
true});
5124 ps <<
"generate" << PP::newline;
5126 setPendingNewline();
5127 emitStatementBlock(op.getBody().getBlocks().front());
5129 ps <<
"end: " << PPExtString(
getSymOpName(op)) << PP::newline;
5130 ps <<
"endgenerate";
5131 ps.addCallback({op,
false});
5132 setPendingNewline();
5136LogicalResult StmtEmitter::visitSV(GenerateCaseOp op) {
5137 emitSVAttributes(op);
5140 ps.addCallback({op,
true});
5142 ps.invokeWithStringOS([&](
auto &os) {
5143 emitter.printParamValue(
5144 op.getCond(), os, VerilogPrecedence::Selection,
5145 [&]() { return op->emitOpError(
"invalid case parameter"); });
5148 setPendingNewline();
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());
5160 llvm::StringMap<size_t> nextGenIds;
5161 ps.scopedBox(PP::bbox2, [&]() {
5163 for (
size_t i = 0, e = patterns.size(); i < e; ++i) {
5164 auto ®ion = regions[i];
5165 assert(region.hasOneBlock());
5166 Attribute patternAttr = patterns[i];
5169 if (!isa<mlir::TypedAttr>(patternAttr))
5172 ps.invokeWithStringOS([&](
auto &os) {
5173 emitter.printParamValue(
5174 patternAttr, os, VerilogPrecedence::LowestPrecedence,
5175 [&]() {
return op->emitOpError(
"invalid case value"); });
5178 StringRef legalName =
5179 legalizeName(cast<StringAttr>(caseNames[i]).getValue(), nextGenIds,
5181 ps <<
": begin: " << PPExtString(legalName);
5182 setPendingNewline();
5183 emitStatementBlock(region.getBlocks().front());
5185 ps <<
"end: " << PPExtString(legalName);
5186 setPendingNewline();
5192 ps.addCallback({op,
false});
5193 setPendingNewline();
5197LogicalResult StmtEmitter::visitSV(GenerateForOp op) {
5198 emitSVAttributes(op);
5199 llvm::SmallPtrSet<Operation *, 8> ops;
5200 ps.addCallback({op,
true});
5203 StringRef inductionVarName = op->getAttrOfType<StringAttr>(
"hw.verilogName");
5206 ps.scopedBox(PP::cbox0, [&]() {
5208 [&]() { ps <<
"genvar" << PP::nbsp << PPExtString(inductionVarName); },
5210 ps.invokeWithStringOS([&](
auto &os) {
5211 emitter.printParamValue(
5212 op.getLowerBound(), os, VerilogPrecedence::LowestPrecedence,
5213 [&]() { return op->emitOpError(
"invalid lower bound"); });
5220 [&]() { ps << PPExtString(inductionVarName); },
5222 ps.invokeWithStringOS([&](
auto &os) {
5223 emitter.printParamValue(
5224 op.getUpperBound(), os, VerilogPrecedence::LowestPrecedence,
5225 [&]() { return op->emitOpError(
"invalid upper bound"); });
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"); });
5238 StringRef blockName = op.getGenBlockName();
5239 if (!blockName.empty())
5240 ps <<
" : " << PPExtString(blockName);
5243 ps << PP::neverbreak;
5244 setPendingNewline();
5245 emitStatementBlock(op.getBody().getBlocks().front());
5248 if (StringRef blockName = op.getGenBlockName(); !blockName.empty())
5249 ps <<
" // " << PPExtString(blockName);
5250 ps.addCallback({op,
false});
5251 setPendingNewline();
5255LogicalResult StmtEmitter::visitSV(ForOp op) {
5256 emitSVAttributes(op);
5257 llvm::SmallPtrSet<Operation *, 8> ops;
5258 ps.addCallback({op,
true});
5260 auto inductionVarName = op->getAttrOfType<StringAttr>(
"hw.verilogName");
5263 ps.scopedBox(PP::cbox0, [&]() {
5267 ps <<
"logic" << PP::nbsp;
5268 ps.invokeWithStringOS([&](
auto &os) {
5269 emitter.emitTypeDims(op.getInductionVar().getType(), op.getLoc(),
5272 ps << PP::nbsp << PPExtString(inductionVarName);
5274 [&]() { emitExpression(op.getLowerBound(), ops); }, PPExtString(
"="));
5279 emitAssignLike([&]() { ps << PPExtString(inductionVarName); },
5280 [&]() { emitExpression(op.getUpperBound(), ops); },
5286 emitAssignLike([&]() { ps << PPExtString(inductionVarName); },
5287 [&]() { emitExpression(op.getStep(), ops); },
5288 PPExtString(
"+="), PPExtString(
") begin"));
5291 ps << PP::neverbreak;
5292 setPendingNewline();
5293 emitStatementBlock(op.getBody().getBlocks().front());
5296 ps.addCallback({op,
false});
5297 emitLocationInfoAndNewLine(ops);
5302void StmtEmitter::emitAssertionLabel(Operation *op) {
5303 if (
auto label = op->getAttrOfType<StringAttr>(
"hw.verilogName"))
5304 ps << PPExtString(label) <<
":" << PP::space;
5309void StmtEmitter::emitAssertionMessage(StringAttr message, ValueRange args,
5310 SmallPtrSetImpl<Operation *> &ops,
5311 bool isConcurrent =
false) {
5314 ps << PP::space <<
"else" << PP::nbsp <<
"$error(";
5315 ps.scopedBox(PP::ibox0, [&]() {
5316 ps.writeQuotedEscaped(message.getValue());
5318 for (
auto arg : args) {
5319 ps <<
"," << PP::space;
5320 emitExpression(arg, ops);
5326template <
typename Op>
5327LogicalResult StmtEmitter::emitImmediateAssertion(Op op, PPExtString opName) {
5329 emitError(op,
"SV attributes emission is unimplemented for the op");
5332 SmallPtrSet<Operation *, 8> ops;
5334 ps.addCallback({op,
true});
5335 ps.scopedBox(PP::ibox2, [&]() {
5336 emitAssertionLabel(op);
5337 ps.scopedBox(PP::cbox0, [&]() {
5339 switch (op.getDefer()) {
5340 case DeferAssert::Immediate:
5342 case DeferAssert::Observed:
5345 case DeferAssert::Final:
5350 ps.scopedBox(PP::ibox0, [&]() {
5351 emitExpression(op.getExpression(), ops);
5354 emitAssertionMessage(op.getMessageAttr(), op.getSubstitutions(), ops);
5358 ps.addCallback({op,
false});
5359 emitLocationInfoAndNewLine(ops);
5363LogicalResult StmtEmitter::visitSV(AssertOp op) {
5364 return emitImmediateAssertion(op, PPExtString(
"assert"));
5367LogicalResult StmtEmitter::visitSV(AssumeOp op) {
5368 return emitImmediateAssertion(op, PPExtString(
"assume"));
5371LogicalResult StmtEmitter::visitSV(CoverOp op) {
5372 return emitImmediateAssertion(op, PPExtString(
"cover"));
5375template <
typename Op>
5376LogicalResult StmtEmitter::emitConcurrentAssertion(Op op, PPExtString opName) {
5378 emitError(op,
"SV attributes emission is unimplemented for the op");
5381 SmallPtrSet<Operation *, 8> ops;
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()))
5391 emitExpression(op.getClock(), ops);
5392 ps <<
")" << PP::space;
5393 emitExpression(op.getProperty(), ops);
5396 emitAssertionMessage(op.getMessageAttr(), op.getSubstitutions(), ops,
5401 ps.addCallback({op,
false});
5402 emitLocationInfoAndNewLine(ops);
5406LogicalResult StmtEmitter::visitSV(AssertConcurrentOp op) {
5407 return emitConcurrentAssertion(op, PPExtString(
"assert"));
5410LogicalResult StmtEmitter::visitSV(AssumeConcurrentOp op) {
5411 return emitConcurrentAssertion(op, PPExtString(
"assume"));
5414LogicalResult StmtEmitter::visitSV(CoverConcurrentOp op) {
5415 return emitConcurrentAssertion(op, PPExtString(
"cover"));
5420template <
typename Op>
5421LogicalResult StmtEmitter::emitPropertyAssertion(Op op, PPExtString opName) {
5423 emitError(op,
"SV attributes emission is unimplemented for the op");
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;
5440 SmallPtrSet<Operation *, 8> ops;
5442 ps.addCallback({op,
true});
5443 ps.scopedBox(PP::ibox2, [&]() {
5445 emitAssertionLabel(op);
5447 ps.scopedBox(PP::cbox0, [&]() {
5448 if (emitAsImmediate)
5449 ps << opName <<
"(";
5451 ps << opName << PP::nbsp <<
"property" << PP::nbsp <<
"(";
5453 Value clock = op.getClock();
5454 auto event = op.getEvent();
5456 ps.scopedBox(PP::ibox2, [&]() {
5457 PropertyEmitter(emitter, ops)
5458 .emitAssertPropertyBody(property, *event, clock, op.getDisable());
5461 ps.scopedBox(PP::ibox2, [&]() {
5462 PropertyEmitter(emitter, ops)
5463 .emitAssertPropertyBody(property, op.getDisable());
5468 ps.addCallback({op,
false});
5469 emitLocationInfoAndNewLine(ops);
5473LogicalResult StmtEmitter::visitSV(AssertPropertyOp op) {
5474 return emitPropertyAssertion(op, PPExtString(
"assert"));
5477LogicalResult StmtEmitter::visitSV(AssumePropertyOp op) {
5478 return emitPropertyAssertion(op, PPExtString(
"assume"));
5481LogicalResult StmtEmitter::visitSV(CoverPropertyOp op) {
5482 return emitPropertyAssertion(op, PPExtString(
"cover"));
5485LogicalResult StmtEmitter::emitIfDef(Operation *op, MacroIdentAttr cond) {
5487 emitError(op,
"SV attributes emission is unimplemented for the op");
5489 auto ident = PPExtString(
5490 cast<MacroDeclOp>(state.symbolCache.
getDefinition(cond.getIdent()))
5491 .getMacroIdentifier());
5494 bool hasEmptyThen = op->getRegion(0).front().empty();
5496 ps <<
"`ifndef " << ident;
5498 ps <<
"`ifdef " << ident;
5500 SmallPtrSet<Operation *, 8> ops;
5502 emitLocationInfoAndNewLine(ops);
5505 emitStatementBlock(op->getRegion(0).front());
5507 if (!op->getRegion(1).empty()) {
5508 if (!hasEmptyThen) {
5510 ps <<
"`else // " << ident;
5511 setPendingNewline();
5513 emitStatementBlock(op->getRegion(1).front());
5520 setPendingNewline();
5528void StmtEmitter::emitBlockAsStatement(
5529 Block *block,
const SmallPtrSetImpl<Operation *> &locationOps,
5530 StringRef multiLineComment) {
5534 auto needsBeginEnd =
5538 emitLocationInfoAndNewLine(locationOps);
5541 emitStatementBlock(*block);
5543 if (needsBeginEnd) {
5547 if (!multiLineComment.empty())
5548 ps <<
" // " << multiLineComment;
5549 setPendingNewline();
5553LogicalResult StmtEmitter::visitSV(OrderedOutputOp ooop) {
5555 for (
auto &op : ooop.getBody().front())
5560LogicalResult StmtEmitter::visitSV(IfOp op) {
5561 SmallPtrSet<Operation *, 8> ops;
5563 auto ifcondBox = PP::ibox2;
5565 emitSVAttributes(op);
5567 ps.addCallback({op,
true});
5568 ps <<
"if (" << ifcondBox;
5578 emitExpression(ifOp.getCond(), ops);
5579 ps << PP::end <<
")";
5580 emitBlockAsStatement(ifOp.getThenBlock(), ops);
5582 if (!ifOp.hasElse())
5586 Block *elseBlock = ifOp.getElseBlock();
5588 if (!nestedElseIfOp) {
5593 emitBlockAsStatement(elseBlock, ops);
5599 ifOp = nestedElseIfOp;
5600 ps <<
"else if (" << ifcondBox;
5602 ps.addCallback({op,
false});
5607LogicalResult StmtEmitter::visitSV(AlwaysOp op) {
5608 emitSVAttributes(op);
5609 SmallPtrSet<Operation *, 8> ops;
5613 auto printEvent = [&](AlwaysOp::Condition cond) {
5614 ps << PPExtString(stringifyEventControl(cond.event)) << PP::nbsp;
5615 ps.scopedBox(PP::cbox0, [&]() { emitExpression(cond.value, ops); });
5617 ps.addCallback({op,
true});
5619 switch (op.getNumConditions()) {
5625 printEvent(op.getCondition(0));
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));
5643 std::string comment;
5644 if (op.getNumConditions() == 0) {
5645 comment =
"always @*";
5647 comment =
"always @(";
5650 [&](Attribute eventAttr) {
5651 auto event = sv::EventControl(cast<IntegerAttr>(eventAttr).getInt());
5652 comment += stringifyEventControl(event);
5654 [&]() { comment +=
", "; });
5658 emitBlockAsStatement(op.getBodyBlock(), ops, comment);
5659 ps.addCallback({op,
false});
5663LogicalResult StmtEmitter::visitSV(AlwaysCombOp op) {
5664 emitSVAttributes(op);
5665 SmallPtrSet<Operation *, 8> ops;
5669 ps.addCallback({op,
true});
5670 StringRef opString =
"always_comb";
5672 opString =
"always @(*)";
5674 ps << PPExtString(opString);
5675 emitBlockAsStatement(op.getBodyBlock(), ops, opString);
5676 ps.addCallback({op,
false});
5680LogicalResult StmtEmitter::visitSV(AlwaysFFOp op) {
5681 emitSVAttributes(op);
5683 SmallPtrSet<Operation *, 8> ops;
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);
5702 std::string comment;
5703 comment +=
"always_ff @(";
5704 comment += stringifyEventControl(op.getClockEdge());
5705 if (op.getResetStyle() == ResetType::AsyncReset) {
5707 comment += stringifyEventControl(*op.getResetEdge());
5711 if (op.getResetStyle() == ResetType::NoReset)
5712 emitBlockAsStatement(op.getBodyBlock(), ops, comment);
5715 emitLocationInfoAndNewLine(ops);
5716 ps.scopedBox(PP::bbox2, [&]() {
5722 if (op.getResetStyle() == ResetType::AsyncReset &&
5723 *op.getResetEdge() == sv::EventControl::AtNegEdge)
5725 emitExpression(op.getReset(), ops);
5727 emitBlockAsStatement(op.getResetBlock(), ops);
5730 emitBlockAsStatement(op.getBodyBlock(), ops);
5735 ps <<
" // " << comment;
5736 setPendingNewline();
5738 ps.addCallback({op,
false});
5742LogicalResult StmtEmitter::visitSV(InitialOp op) {
5743 emitSVAttributes(op);
5744 SmallPtrSet<Operation *, 8> ops;
5747 ps.addCallback({op,
true});
5749 emitBlockAsStatement(op.getBodyBlock(), ops,
"initial");
5750 ps.addCallback({op,
false});
5754LogicalResult StmtEmitter::visitSV(CaseOp op) {
5755 emitSVAttributes(op);
5756 SmallPtrSet<Operation *, 8> ops, emptyOps;
5759 ps.addCallback({op,
true});
5760 if (op.getValidationQualifier() !=
5761 ValidationQualifierTypeEnum::ValidationQualifierPlain)
5762 ps << PPExtString(circt::sv::stringifyValidationQualifierTypeEnum(
5763 op.getValidationQualifier()))
5765 const char *opname =
nullptr;
5766 switch (op.getCaseStyle()) {
5767 case CaseStmtType::CaseStmt:
5770 case CaseStmtType::CaseXStmt:
5773 case CaseStmtType::CaseZStmt:
5777 ps << opname <<
" (";
5778 ps.scopedBox(PP::ibox0, [&]() {
5779 emitExpression(op.getCond(), ops);
5782 emitLocationInfoAndNewLine(ops);
5784 size_t caseValueIndex = 0;
5785 ps.scopedBox(PP::bbox2, [&]() {
5786 for (
auto &caseInfo : op.getCases()) {
5788 auto &pattern = caseInfo.pattern;
5790 llvm::TypeSwitch<CasePattern *>(pattern.get())
5791 .Case<CaseBitPattern>([&](
auto bitPattern) {
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));
5800 .Case<CaseEnumPattern>([&](
auto enumPattern) {
5802 cast<hw::EnumFieldAttr>(enumPattern->attr())));
5804 .Case<CaseExprPattern>([&](
auto) {
5805 emitExpression(op.getCaseValues()[caseValueIndex++], ops);
5807 .Case<CaseDefaultPattern>([&](
auto) { ps <<
"default"; })
5808 .Default([&](
auto) {
assert(
false &&
"unhandled case pattern"); });
5811 emitBlockAsStatement(caseInfo.block, emptyOps);
5817 ps.addCallback({op,
false});
5818 emitLocationInfoAndNewLine(ops);
5822LogicalResult StmtEmitter::visitStmt(InstanceOp op) {
5823 bool doNotPrint = op.getDoNotPrint();
5829 emitSVAttributes(op);
5831 ps.addCallback({op,
true});
5834 <<
"/* This instance is elsewhere emitted as a bind statement."
5837 op->emitWarning() <<
"is emitted as a bind statement but has SV "
5838 "attributes. The attributes will not be emitted.";
5841 SmallPtrSet<Operation *, 8> ops;
5846 state.symbolCache.
getDefinition(op.getReferencedModuleNameAttr());
5847 assert(moduleOp &&
"Invalid IR");
5851 if (!op.getParameters().empty()) {
5854 bool printed =
false;
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));
5861 if (param.getValue() == modParam.getValue())
5866 ps <<
" #(" << PP::bbox2 << PP::newline;
5869 ps <<
"," << PP::newline;
5875 ps.invokeWithStringOS([&](
auto &os) {
5876 emitter.printParamValue(param.getValue(), os, [&]() {
5877 return op->emitOpError(
"invalid instance parameter '")
5878 << param.getName().getValue() <<
"' value";
5884 ps << PP::end << PP::newline <<
")";
5890 ModulePortInfo modPortInfo(cast<PortList>(moduleOp).
getPortList());
5891 SmallVector<Value> instPortValues(modPortInfo.size());
5892 op.getValues(instPortValues, modPortInfo);
5893 emitInstancePortList(op, modPortInfo, instPortValues);
5895 ps.addCallback({op,
false});
5896 emitLocationInfoAndNewLine(ops);
5901 setPendingNewline();
5906void StmtEmitter::emitInstancePortList(Operation *op,
5907 ModulePortInfo &modPortInfo,
5908 ArrayRef<Value> instPortValues) {
5909 SmallPtrSet<Operation *, 8> ops;
5912 auto containingModule = cast<HWModuleOp>(emitter.currentModuleOp);
5913 ModulePortInfo containingPortList(containingModule.getPortList());
5919 size_t maxNameLength = 0;
5921 for (
auto &elt : modPortInfo) {
5922 size_t nameLength = elt.getVerilogName().size();
5923 if (!lineLength || nameLength <= *lineLength / 3)
5924 maxNameLength = std::max(maxNameLength, nameLength);
5927 auto getWireForValue = [&](Value result) {
5928 return result.getUsers().begin()->getOperand(0);
5932 bool isFirst =
true;
5933 bool isZeroWidth =
false;
5935 for (
size_t portNum = 0, portEnd = modPortInfo.size(); portNum < portEnd;
5937 auto &modPort = modPortInfo.at(portNum);
5939 Value portVal = instPortValues[portNum];
5944 bool shouldPrintComma =
true;
5946 shouldPrintComma =
false;
5947 for (
size_t i = portNum + 1, e = modPortInfo.size(); i != e; ++i)
5949 shouldPrintComma =
true;
5954 if (shouldPrintComma)
5957 emitLocationInfoAndNewLine(ops);
5972 ps.scopedBox(isZeroWidth ? PP::neverbox : PP::ibox2, [&]() {
5973 auto modPortName = modPort.getVerilogName();
5974 ps <<
"." << PPExtString(modPortName);
5976 if (modPortName.size() <= maxNameLength)
5977 ps.spaces(maxNameLength - modPortName.size() + 1);
5981 ps.scopedBox(PP::ibox0, [&]() {
5988 if (!modPort.isOutput()) {
5990 isa_and_nonnull<ConstantOp>(portVal.getDefiningOp()))
5991 ps <<
"/* Zero width */";
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()))) {
6003 size_t outputPortNo = portVal.getUses().begin()->getOperandNumber();
6005 containingPortList.atOutput(outputPortNo).getVerilogName());
6007 portVal = getWireForValue(portVal);
6008 emitExpression(portVal, ops);
6014 if (!isFirst || isZeroWidth) {
6015 emitLocationInfoAndNewLine(ops);
6028LogicalResult StmtEmitter::visitSV(BindOp op) {
6029 emitter.emitBind(op);
6030 assert(state.pendingNewline);
6034LogicalResult StmtEmitter::visitSV(InterfaceOp op) {
6035 emitComment(op.getCommentAttr());
6037 emitSVAttributes(op);
6040 ps.addCallback({op,
true});
6041 ps <<
"interface " << PPExtString(
getSymOpName(op)) <<
";";
6042 setPendingNewline();
6044 emitStatementBlock(*op.getBodyBlock());
6046 ps <<
"endinterface" << PP::newline;
6047 ps.addCallback({op,
false});
6048 setPendingNewline();
6053 emitSVAttributes(op);
6055 ps.addCallback({op,
true});
6057 ps << op.getContent();
6059 ps.addCallback({op,
false});
6060 setPendingNewline();
6064LogicalResult StmtEmitter::visitSV(InterfaceSignalOp op) {
6066 emitSVAttributes(op);
6068 ps.addCallback({op,
true});
6070 ps << PP::neverbox <<
"// ";
6071 ps.invokeWithStringOS([&](
auto &os) {
6076 ps.invokeWithStringOS(
6077 [&](
auto &os) { emitter.printUnpackedTypePostfix(op.getType(), os); });
6081 ps.addCallback({op,
false});
6082 setPendingNewline();
6086LogicalResult StmtEmitter::visitSV(InterfaceModportOp op) {
6088 ps.addCallback({op,
true});
6089 ps <<
"modport " << PPExtString(
getSymOpName(op)) <<
"(";
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));
6100 ps.addCallback({op,
false});
6101 setPendingNewline();
6105LogicalResult StmtEmitter::visitSV(AssignInterfaceSignalOp op) {
6107 ps.addCallback({op,
true});
6108 SmallPtrSet<Operation *, 8> emitted;
6111 emitExpression(op.getIface(), emitted);
6112 ps <<
"." << PPExtString(op.getSignalName()) <<
" = ";
6113 emitExpression(op.getRhs(), emitted);
6115 ps.addCallback({op,
false});
6116 setPendingNewline();
6120LogicalResult StmtEmitter::visitSV(MacroErrorOp op) {
6122 ps <<
"`" << op.getMacroIdentifier();
6123 setPendingNewline();
6127LogicalResult StmtEmitter::visitSV(MacroDefOp op) {
6128 auto decl = op.getReferencedMacro(&state.symbolCache);
6131 ps.addCallback({op,
true});
6133 if (decl.getArgs()) {
6135 llvm::interleaveComma(*decl.getArgs(), ps, [&](
const Attribute &name) {
6136 ps << cast<StringAttr>(name);
6140 if (!op.getFormatString().empty()) {
6142 emitTextWithSubstitutions(ps, op.getFormatString(), op, {},
6145 ps.addCallback({op,
false});
6146 setPendingNewline();
6150void StmtEmitter::emitStatement(Operation *op) {
6157 if (isa_and_nonnull<ltl::LTLDialect, debug::DebugDialect>(op->getDialect()))
6161 if (succeeded(dispatchStmtVisitor(op)) || succeeded(dispatchSVVisitor(op)) ||
6162 succeeded(dispatchVerifVisitor(op)))
6165 emitOpError(op,
"emission to Verilog not supported");
6166 emitPendingNewlineIfNeeded();
6167 ps <<
"unknown MLIR operation " << PPExtString(op->getName().getStringRef());
6168 setPendingNewline();
6179 StmtEmitter &stmtEmitter) {
6186 if (isa<IfDefProceduralOp>(op->getParentOp()))
6194 SmallVector<Value, 8> exprsToScan(op->getOperands());
6199 while (!exprsToScan.empty()) {
6200 Operation *expr = exprsToScan.pop_back_val().getDefiningOp();
6207 if (
auto readInout = dyn_cast<sv::ReadInOutOp>(expr)) {
6208 auto *defOp = readInout.getOperand().getDefiningOp();
6215 if (isa<sv::WireOp>(defOp))
6220 if (!isa<RegOp, LogicOp, sv::VarOp>(defOp))
6226 if (isa<LogicOp, sv::VarOp>(defOp) &&
6227 stmtEmitter.emitter.expressionsEmittedIntoDecl.count(defOp))
6231 if (llvm::all_of(defOp->getResult(0).getUsers(), [&](Operation *op) {
6232 return isa<ReadInOutOp, PAssignOp, AssignOp>(op);
6240 exprsToScan.append(expr->getOperands().begin(),
6241 expr->getOperands().end());
6247 if (expr->getBlock() != op->getBlock())
6252 if (!stmtEmitter.emitter.expressionsEmittedIntoDecl.count(expr))
6259template <
class AssignTy>
6261 AssignTy singleAssign;
6262 if (llvm::all_of(op->getUsers(), [&](Operation *user) {
6263 if (hasSVAttributes(user))
6266 if (auto assign = dyn_cast<AssignTy>(user)) {
6269 singleAssign = assign;
6273 return isa<ReadInOutOp>(user);
6275 return singleAssign;
6281 return llvm::all_of(op2->getUsers(), [&](Operation *user) {
6285 if (op1->getBlock() != user->getBlock())
6291 return op1->isBeforeInBlock(user);
6295LogicalResult StmtEmitter::emitDeclaration(Operation *op) {
6296 emitSVAttributes(op);
6297 auto value = op->getResult(0);
6298 SmallPtrSet<Operation *, 8> opsForLocation;
6299 opsForLocation.insert(op);
6301 ps.addCallback({op,
true});
6304 auto type = value.getType();
6310 bool singleBitDefaultType = !isa<LocalParamOp>(op);
6312 ps.scopedBox(isZeroBit ? PP::neverbox : PP::ibox2, [&]() {
6313 unsigned targetColumn = 0;
6314 unsigned column = 0;
6317 if (maxDeclNameWidth > 0)
6318 targetColumn += maxDeclNameWidth + 1;
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;
6330 SmallString<8> typeString;
6333 llvm::raw_svector_ostream stringStream(typeString);
6336 true, singleBitDefaultType);
6339 if (maxTypeWidth > 0)
6340 targetColumn += maxTypeWidth + 1;
6341 unsigned numSpaces = 0;
6342 if (!typeString.empty()) {
6344 column += typeString.size();
6347 if (targetColumn > column)
6348 numSpaces = targetColumn - column;
6349 ps.spaces(numSpaces);
6350 column += numSpaces;
6356 ps.invokeWithStringOS(
6357 [&](
auto &os) { emitter.printUnpackedTypePostfix(type, os); });
6361 if (
auto innerSymOp = dyn_cast<hw::InnerSymbolOpInterface>(op)) {
6362 auto innerSym = innerSymOp.getInnerSymAttr();
6363 if (innerSym && !innerSym.empty()) {
6365 ps.invokeWithStringOS([&](
auto &os) { os << innerSym; });
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");
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,
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,
6404 !op->getParentOp()->hasTrait<ProceduralRegion>() &&
6408 auto *source = singleAssign.getSrc().getDefiningOp();
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,
6420 emitter.assignsInlined.insert(singleAssign);
6429 op->getParentOp()->hasTrait<ProceduralRegion>() &&
6435 auto *source = singleAssign.getSrc().getDefiningOp();
6439 if (!source || isa<ConstantOp>(source) ||
6442 ps << PP::space <<
"=" << PP::space;
6443 ps.scopedBox(PP::ibox0, [&]() {
6444 emitExpression(singleAssign.getSrc(), opsForLocation,
6449 emitter.assignsInlined.insert(singleAssign);
6450 emitter.expressionsEmittedIntoDecl.insert(op);
6457 ps.addCallback({op,
false});
6458 emitLocationInfoAndNewLine(opsForLocation);
6462void StmtEmitter::collectNamesAndCalculateDeclarationWidths(
Block &block) {
6465 NameCollector collector(emitter);
6466 collector.collectNames(block);
6469 maxDeclNameWidth = collector.getMaxDeclNameWidth();
6470 maxTypeWidth = collector.getMaxTypeWidth();
6473void StmtEmitter::emitStatementBlock(
Block &body) {
6474 ps.scopedBox(PP::bbox2, [&]() {
6479 llvm::SaveAndRestore<size_t> x(maxDeclNameWidth);
6480 llvm::SaveAndRestore<size_t> x2(maxTypeWidth);
6485 if (!isa<IfDefProceduralOp>(body.getParentOp()))
6486 collectNamesAndCalculateDeclarationWidths(body);
6489 for (
auto &op : body) {
6496void ModuleEmitter::emitStatement(Operation *op) {
6497 StmtEmitter(*
this, state.options).emitStatement(op);
6502void ModuleEmitter::emitSVAttributes(Operation *op) {
6510 setPendingNewline();
6517void ModuleEmitter::emitHWGeneratedModule(HWModuleGeneratedOp module) {
6518 auto verilogName =
module.getVerilogModuleNameAttr();
6520 ps <<
"// external generated module " << PPExtString(verilogName.getValue())
6522 setPendingNewline();
6531void ModuleEmitter::emitBind(BindOp op) {
6533 emitError(op,
"SV attributes emission is unimplemented for the op");
6534 InstanceOp inst = op.getReferencedInstance(&state.symbolCache);
6536 HWModuleOp parentMod = inst->getParentOfType<hw::HWModuleOp>();
6537 ModulePortInfo parentPortList(parentMod.getPortList());
6540 Operation *childMod =
6541 state.symbolCache.
getDefinition(inst.getReferencedModuleNameAttr());
6545 ps.addCallback({op,
true});
6546 ps <<
"bind " << PPExtString(parentVerilogName.getValue()) << PP::nbsp
6547 << PPExtString(childVerilogName.getValue()) << PP::nbsp
6549 bool isFirst =
true;
6550 ps.scopedBox(PP::bbox2, [&]() {
6551 auto parentPortInfo = parentMod.getPortList();
6552 ModulePortInfo childPortInfo(cast<PortList>(childMod).
getPortList());
6556 size_t maxNameLength = 0;
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);
6566 SmallVector<Value> instPortValues(childPortInfo.size());
6567 inst.getValues(instPortValues, childPortInfo);
6569 for (
auto [idx, elt] : llvm::enumerate(childPortInfo)) {
6571 Value portVal = instPortValues[idx];
6577 bool shouldPrintComma =
true;
6579 shouldPrintComma =
false;
6580 for (
size_t i = idx + 1, e = childPortInfo.size(); i != e; ++i)
6582 shouldPrintComma =
true;
6587 if (shouldPrintComma)
6600 ps << PP::neverbox <<
"//";
6603 ps <<
"." << PPExtString(elt.getName());
6605 if (elt.getName().size() <= maxNameLength)
6606 ps.nbsp(maxNameLength - elt.getName().size());
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())) {
6618 size_t outputPortNo = portVal.getUses().begin()->getOperandNumber();
6620 parentPortList.atOutput(outputPortNo).getVerilogName());
6622 portVal = portVal.getUsers().begin()->getOperand(0);
6623 ExprEmitter(*
this, ops)
6624 .emitExpression(portVal, LowestPrecedence,
6628 ExprEmitter(*
this, ops)
6629 .emitExpression(portVal, LowestPrecedence,
6642 ps.addCallback({op,
false});
6643 setPendingNewline();
6646void ModuleEmitter::emitBindInterface(BindInterfaceOp op) {
6648 emitError(op,
"SV attributes emission is unimplemented for the op");
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());
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();
6663void ModuleEmitter::emitParameters(Operation *module, ArrayAttr params) {
6667 auto printParamType = [&](Type type, Attribute defaultValue,
6668 SmallString<8> &result) {
6670 llvm::raw_svector_ostream sstream(result);
6675 if (
auto intAttr = dyn_cast<IntegerAttr>(defaultValue))
6676 if (intAttr.getValue().getBitWidth() == 32)
6678 if (
auto fpAttr = dyn_cast<FloatAttr>(defaultValue))
6679 if (fpAttr.getType().isF64())
6682 if (isa<NoneType>(type))
6690 if (intType.getWidth() == 32) {
6691 sstream <<
"/*integer*/";
6695 printPackedType(type, sstream, module->getLoc(),
6703 size_t maxTypeWidth = 0;
6704 SmallString<8> scratch;
6705 for (
auto param : params) {
6706 auto paramAttr = cast<ParamDeclAttr>(param);
6708 printParamType(paramAttr.getType(), paramAttr.getValue(), scratch);
6709 maxTypeWidth = std::max(scratch.size(), maxTypeWidth);
6712 if (maxTypeWidth > 0)
6715 ps.scopedBox(PP::bbox2, [&]() {
6716 ps << PP::newline <<
"#(";
6717 ps.scopedBox(PP::cbox0, [&]() {
6720 [&](Attribute param) {
6721 auto paramAttr = cast<ParamDeclAttr>(param);
6722 auto defaultValue = paramAttr.getValue();
6724 printParamType(paramAttr.getType(), defaultValue, scratch);
6725 if (!scratch.empty())
6727 if (scratch.size() < maxTypeWidth)
6728 ps.nbsp(maxTypeWidth - scratch.size());
6731 module, paramAttr.getName()));
6735 ps.invokeWithStringOS([&](
auto &os) {
6737 return module->emitError("parameter '")
6738 << paramAttr.getName().getValue()
6739 << "' has invalid value";
6744 [&]() { ps <<
"," << PP::newline; });
6750void ModuleEmitter::emitPortList(Operation *module,
6751 const ModulePortInfo &portInfo,
6752 bool emitAsTwoStateType) {
6754 if (portInfo.
size())
6755 emitLocationInfo(module->getLoc());
6759 bool hasOutputs =
false, hasZeroWidth =
false;
6760 size_t maxTypeWidth = 0, lastNonZeroPort = -1;
6761 SmallVector<SmallString<8>, 16> portTypeStrings;
6763 for (
size_t i = 0, e = portInfo.
size(); i < e; ++i) {
6764 auto port = portInfo.
at(i);
6765 hasOutputs |= port.isOutput();
6768 lastNonZeroPort = i;
6771 portTypeStrings.push_back({});
6773 llvm::raw_svector_ostream stringStream(portTypeStrings.back());
6775 module->getLoc(), {},
true,
true, emitAsTwoStateType);
6778 maxTypeWidth = std::max(portTypeStrings.back().size(), maxTypeWidth);
6781 if (maxTypeWidth > 0)
6784 auto getPortSVAttrs = [](
const PortInfo &port) -> ArrayAttr {
6787 auto attrs = port.attrs.getAs<ArrayAttr>(
6788 sv::SVAttributeAttr::getSVAttributesAttrName());
6795 ps.scopedBox(PP::bbox2, [&]() {
6796 for (
size_t portIdx = 0, e = portInfo.
size(); portIdx != e;) {
6797 auto lastPort = e - 1;
6800 auto portType = portInfo.
at(portIdx).
type;
6804 bool isZeroWidth =
false;
6809 ps << (isZeroWidth ?
"// " :
" ");
6813 auto thisPortInfo = portInfo.
at(portIdx);
6814 auto svAttrs = getPortSVAttrs(thisPortInfo);
6815 if (svAttrs && !isZeroWidth) {
6821 auto thisPortDirection = thisPortInfo.dir;
6822 bool isInOut = isa<InOutType, sv::NetType>(portType);
6823 StringRef direction;
6825 direction = hasOutputs ?
"inout " :
"inout ";
6827 switch (thisPortDirection) {
6828 case ModulePort::Direction::Output:
6829 direction =
"output ";
6831 case ModulePort::Direction::Input:
6832 direction = hasOutputs ?
"input " :
"input ";
6843 portDecl = emitAsTwoStateType ?
"var " :
"var logic ";
6848 size_t startOfNamePos = direction.size() + portDecl.size() + maxTypeWidth;
6852 if (!isa<ModportType>(portType)) {
6854 if (!portDecl.empty())
6856 if (!portTypeStrings[portIdx].
empty())
6857 ps << portTypeStrings[portIdx];
6858 if (portTypeStrings[portIdx].size() < maxTypeWidth)
6859 ps.nbsp(maxTypeWidth - portTypeStrings[portIdx].size());
6861 ps << portTypeStrings[portIdx];
6862 if (portTypeStrings[portIdx].size() < startOfNamePos)
6863 ps.nbsp(startOfNamePos - portTypeStrings[portIdx].size());
6870 ps.invokeWithStringOS(
6871 [&](
auto &os) { printUnpackedTypePostfix(portType, os); });
6874 auto innerSym = portInfo.
at(portIdx).
getSym();
6875 if (state.options.
printDebugInfo && innerSym && !innerSym.empty()) {
6877 ps.invokeWithStringOS([&](
auto &os) { os << innerSym; });
6882 if (portIdx != lastNonZeroPort && portIdx != lastPort)
6886 if (
auto loc = portInfo.
at(portIdx).
loc)
6887 emitLocationInfo(loc);
6901 while (portIdx != e && !getPortSVAttrs(portInfo.
at(portIdx)) &&
6902 portInfo.
at(portIdx).
dir == thisPortDirection &&
6904 isa<InOutType, sv::NetType>(portInfo.
at(portIdx).
type) &&
6907 auto port = portInfo.
at(portIdx);
6911 bool isZeroWidth =
false;
6916 ps << (isZeroWidth ?
"// " :
" ");
6919 ps.nbsp(startOfNamePos);
6922 StringRef name = port.getVerilogName();
6923 ps << PPExtString(name);
6926 ps.invokeWithStringOS(
6927 [&](
auto &os) { printUnpackedTypePostfix(port.type, os); });
6930 auto sym = port.getSym();
6932 ps <<
" /* inner_sym: " << PPExtString(sym.getSymName().getValue())
6936 if (portIdx != lastNonZeroPort && portIdx != lastPort)
6940 if (
auto loc = port.loc)
6941 emitLocationInfo(loc);
6952 if (!portInfo.
size()) {
6954 SmallPtrSet<Operation *, 8> moduleOpSet;
6955 moduleOpSet.insert(module);
6956 emitLocationInfoAndNewLine(moduleOpSet);
6959 ps <<
");" << PP::newline;
6960 setPendingNewline();
6964void ModuleEmitter::emitHWModule(HWModuleOp module) {
6965 currentModuleOp =
module;
6967 emitComment(module.getCommentAttr());
6968 emitSVAttributes(module);
6970 ps.addCallback({module,
true});
6974 emitParameters(module, module.getParameters());
6976 emitPortList(module, ModulePortInfo(module.getPortList()));
6978 assert(state.pendingNewline);
6981 StmtEmitter(*
this, state.options).emitStatementBlock(*module.getBodyBlock());
6984 ps.addCallback({module,
false});
6986 setPendingNewline();
6988 currentModuleOp =
nullptr;
6991void ModuleEmitter::emitFunc(FuncOp func) {
6993 if (func.isDeclaration())
6996 currentModuleOp = func;
6998 ps.addCallback({func,
true});
7002 StmtEmitter(*
this, state.options).emitStatementBlock(*func.getBodyBlock());
7004 ps <<
"endfunction";
7006 currentModuleOp =
nullptr;
7015 explicit FileEmitter(VerilogEmitterState &state) : EmitterBase(state) {}
7022 void emit(emit::FileListOp op);
7027 void emitOp(emit::RefOp op);
7028 void emitOp(emit::VerbatimOp op);
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);
7044 [&](
auto op) { emitOpError(op,
"cannot be emitted to a file"); });
7050 for (
auto sym : op.getFiles()) {
7051 auto fileName = cast<FlatSymbolRefAttr>(sym).getAttr();
7053 auto it = state.fileMapping.find(fileName);
7054 if (it == state.fileMapping.end()) {
7055 emitOpError(op,
" references an invalid file: ") << sym;
7059 auto file = cast<emit::FileOp>(it->second);
7067 StringAttr target = op.getTargetAttr().getAttr();
7068 auto *targetOp = state.symbolCache.getDefinition(target);
7069 assert(isa<emit::Emittable>(targetOp) &&
"target must be emittable");
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);
7079 [&](
auto op) { emitOpError(op,
"cannot be emitted to a file"); });
7085 SmallPtrSet<Operation *, 8> ops;
7090 StringRef text = op.getText();
7094 const auto &[lhs, rhs] = text.split(
'\n');
7100 }
while (!text.empty());
7103 emitLocationInfoAndNewLine(ops);
7121 auto collectInstanceSymbolsAndBinds = [&](Operation *moduleOp) {
7122 moduleOp->walk([&](Operation *op) {
7125 if (
auto name = op->getAttrOfType<InnerSymAttr>(
7126 hw::InnerSymbolTable::getInnerSymbolAttrName()))
7127 for (
auto prop : name)
7129 cast<mlir::SymbolOpInterface>(moduleOp).getNameAttr(),
7130 prop.getName(), op);
7131 if (isa<BindOp>(op))
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())
7142 for (NamedAttribute portAttr : p.attrs) {
7143 if (
auto sym = dyn_cast<InnerSymAttr>(portAttr.getValue())) {
7144 symbolCache.addDefinition(moduleOp.getNameAttr(), sym.getSymName(),
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);
7157 SmallString<32> outputPath;
7158 for (
auto &op : *
designOp.getBody()) {
7161 bool isFileOp = isa<emit::FileOp, emit::FileListOp>(&op);
7163 bool hasFileName =
false;
7164 bool emitReplicatedOps = !isFileOp;
7165 bool addToFilelist = !isFileOp;
7171 auto attr = op.getAttrOfType<hw::OutputFileAttr>(
"output_file");
7173 LLVM_DEBUG(llvm::dbgs() <<
"Found output_file attribute " << attr
7174 <<
" on " << op <<
"\n";);
7175 if (!attr.isDirectory())
7178 emitReplicatedOps = attr.getIncludeReplicatedOps().getValue();
7179 addToFilelist = !attr.getExcludeFromFilelist().getValue();
7182 auto separateFile = [&](Operation *op, Twine defaultFileName =
"") {
7187 if (!defaultFileName.isTriviallyEmpty()) {
7188 llvm::sys::path::append(outputPath, defaultFileName);
7190 op->emitError(
"file name unspecified");
7192 llvm::sys::path::append(outputPath,
"error.out");
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");
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);
7219 TypeSwitch<Operation *>(&op)
7220 .Case<emit::FileOp, emit::FileListOp>([&](
auto file) {
7222 fileMapping.try_emplace(file.getSymNameAttr(), file);
7223 separateFile(file, file.getFileName());
7225 .Case<emit::FragmentOp>([&](
auto fragment) {
7228 .Case<HWModuleOp>([&](
auto mod) {
7230 auto sym = mod.getNameAttr();
7233 collectInstanceSymbolsAndBinds(mod);
7235 if (
auto it = symbolsToFiles.find(sym); it != symbolsToFiles.end()) {
7236 if (it->second.size() != 1 || attr) {
7239 op.emitError(
"modules can be emitted to a single file");
7247 if (attr || separateModules)
7253 .Case<InterfaceOp>([&](InterfaceOp intf) {
7255 symbolCache.addDefinition(intf.getNameAttr(), intf);
7258 for (
auto &op : *intf.getBodyBlock())
7259 if (
auto symOp = dyn_cast<mlir::SymbolOpInterface>(op))
7260 if (
auto name = symOp.getNameAttr())
7264 if (attr || separateModules)
7265 separateFile(intf, intf.getSymName() +
".sv");
7269 .Case<PackageOp>([&](PackageOp package) {
7271 auto sym = package.getSymNameAttr();
7274 if (
auto it = symbolsToFiles.find(sym); it != symbolsToFiles.end()) {
7275 if (it->second.size() != 1 || attr) {
7277 "packages can only be emitted to a single file");
7286 if (attr || separateModules)
7291 .Case<PackageExternOp>([&](PackageExternOp package) {
7292 symbolCache.addDefinition(package.getSymNameAttr(), package);
7296 separateFile(op, op.getOutputFile().getFilename().getValue());
7298 .Case<HWModuleExternOp, sv::SVVerbatimModuleOp>([&](
auto op) {
7304 .Case<VerbatimOp, IfDefOp, MacroDefOp, IncludeOp, FuncDPIImportOp>(
7305 [&](Operation *op) {
7311 separateFile(op,
"");
7313 .Case<FuncOp>([&](
auto op) {
7319 separateFile(op,
"");
7323 .Case<HWGeneratorSchemaOp>([&](HWGeneratorSchemaOp schemaOp) {
7324 symbolCache.addDefinition(schemaOp.getNameAttr(), schemaOp);
7326 .Case<HierPathOp>([&](HierPathOp hierPathOp) {
7327 symbolCache.addDefinition(hierPathOp.getSymNameAttr(), hierPathOp);
7330 symbolCache.addDefinition(op.getSymNameAttr(), op);
7335 separateFile(op,
"");
7337 .Case<BindOp>([&](
auto op) {
7339 separateFile(op,
"bindfile.sv");
7344 .Case<MacroErrorOp>([&](
auto op) {
replicatedOps.push_back(op); })
7345 .Case<MacroDeclOp>([&](
auto op) {
7346 symbolCache.addDefinition(op.getSymNameAttr(), op);
7348 .Case<sv::ReserveNamesOp>([](
auto op) {
7351 .Case<om::ClassLike>([&](
auto op) {
7352 symbolCache.addDefinition(op.getSymNameAttr(), op);
7354 .Case<om::ConstantOp>([&](
auto op) {
7357 .Default([&](
auto *) {
7358 op.emitError(
"unknown operation (SharedEmitterState::gatherFiles)");
7378 size_t lastReplicatedOp = 0;
7380 bool emitHeaderInclude =
7383 if (emitHeaderInclude)
7386 size_t numReplicatedOps =
7391 DenseSet<emit::FragmentOp> includedFragments;
7392 for (
const auto &opInfo : file.
ops) {
7393 Operation *op = opInfo.op;
7397 for (; lastReplicatedOp < std::min(opInfo.position, numReplicatedOps);
7403 if (
auto fragments =
7405 for (
auto sym : fragments.getAsRange<FlatSymbolRefAttr>()) {
7409 op->emitError(
"cannot find referenced fragment ") << sym;
7412 emit::FragmentOp fragment = it->second;
7413 if (includedFragments.insert(fragment).second) {
7414 thingsToEmit.emplace_back(it->second);
7420 thingsToEmit.emplace_back(op);
7425 for (; lastReplicatedOp < numReplicatedOps; lastReplicatedOp++)
7430 TypeSwitch<Operation *>(op)
7431 .Case<
HWModuleOp>([&](
auto op) { ModuleEmitter(state).emitHWModule(op); })
7432 .Case<HWModuleExternOp, sv::SVVerbatimModuleOp, PackageExternOp>(
7436 .Case<HWModuleGeneratedOp>(
7437 [&](
auto op) { ModuleEmitter(state).emitHWGeneratedModule(op); })
7438 .Case<HWGeneratorSchemaOp>([&](
auto op) { })
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);
7445 .Case<emit::FileOp, emit::FileListOp, emit::FragmentOp>(
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)");
7460 llvm::formatted_raw_ostream &os,
7461 StringAttr fileName,
bool parallelize) {
7466 parallelize &=
context->isMultithreadingEnabled();
7477 size_t lineOffset = 0;
7478 for (
auto &entry : thingsToEmit) {
7479 entry.verilogLocs.setStream(os);
7480 if (
auto *op = entry.getOperation()) {
7485 state.addVerilogLocToOps(lineOffset, fileName);
7487 os << entry.getStringData();
7492 if (state.encounteredError)
7510 SmallString<256> buffer;
7511 llvm::raw_svector_ostream tmpStream(buffer);
7512 llvm::formatted_raw_ostream rs(tmpStream);
7520 if (state.encounteredError)
7525 for (
auto &entry : thingsToEmit) {
7528 auto *op = entry.getOperation();
7530 auto lineOffset = os.getLine() + 1;
7531 os << entry.getStringData();
7535 entry.verilogLocs.updateIRWithLoc(lineOffset, fileName,
context);
7538 entry.verilogLocs.setStream(os);
7545 state.addVerilogLocToOps(0, fileName);
7546 if (state.encounteredError) {
7565 module.emitWarning()
7566 << "`emitReplicatedOpsToHeader` option is enabled but an header is "
7567 "created only at SplitExportVerilog";
7576 for (
const auto &it : emitter.
files) {
7577 list.emplace_back(
"\n// ----- 8< ----- FILE \"" + it.first.str() +
7578 "\" ----- 8< -----\n\n");
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);
7591 llvm::formatted_raw_ostream rs(os);
7595 emitter.
emitOps(list, rs, StringAttr::get(module.getContext(),
""),
7601 LoweringOptions options(module);
7602 SmallVector<HWEmittableModuleLike> modulesToPrepare;
7604 [&](HWEmittableModuleLike op) { modulesToPrepare.push_back(op); });
7605 if (failed(failableParallelForEach(
7606 module->getContext(), modulesToPrepare,
7607 [&](
auto op) { return prepareHWModule(op, options); })))
7614struct ExportVerilogPass
7615 :
public circt::impl::ExportVerilogBase<ExportVerilogPass> {
7616 ExportVerilogPass(raw_ostream &os) : os(os) {}
7617 void runOnOperation()
override {
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();
7627 return signalPassFailure();
7634struct ExportVerilogStreamOwnedPass :
public ExportVerilogPass {
7635 ExportVerilogStreamOwnedPass(std::unique_ptr<llvm::raw_ostream> os)
7636 : ExportVerilogPass{*os} {
7637 owned = std::move(os);
7641 std::unique_ptr<llvm::raw_ostream> owned;
7645std::unique_ptr<mlir::Pass>
7647 return std::make_unique<ExportVerilogStreamOwnedPass>(std::move(os));
7650std::unique_ptr<mlir::Pass>
7652 return std::make_unique<ExportVerilogPass>(os);
7663static std::unique_ptr<llvm::ToolOutputFile>
7667 SmallString<128> outputFilename(dirname);
7669 auto outputDir = llvm::sys::path::parent_path(outputFilename);
7672 std::error_code error = llvm::sys::fs::create_directories(outputDir);
7674 emitter.
designOp.emitError(
"cannot create output directory \"")
7675 << outputDir <<
"\": " << error.message();
7681 std::string errorMessage;
7682 auto output = mlir::openOutputFile(outputFilename, &errorMessage);
7684 emitter.
designOp.emitError(errorMessage);
7701 llvm::formatted_raw_ostream rs(output->os());
7707 StringAttr::get(fileName.getContext(), output->getFilename()),
7713 StringRef dirname) {
7724 bool insertSuccess =
7726 .insert({StringAttr::get(module.getContext(),
circtHeader),
7732 if (!insertSuccess) {
7733 module.emitError() << "tried to emit a heder to " << circtHeader
7734 << ", but the file is used as an output too.";
7740 parallelForEach(module->getContext(), emitter.
files.begin(),
7741 emitter.
files.end(), [&](
auto &it) {
7742 createSplitOutputFile(it.first, it.second, dirname,
7747 SmallString<128> filelistPath(dirname);
7748 llvm::sys::path::append(filelistPath,
"filelist.f");
7750 std::string errorMessage;
7751 auto output = mlir::openOutputFile(filelistPath, &errorMessage);
7753 module->emitError(errorMessage);
7757 for (
const auto &it : emitter.
files) {
7758 if (it.second.addToFilelist)
7759 output->os() << it.first.str() <<
"\n";
7768 for (
auto &name : it.second)
7769 output->os() << name.str() <<
"\n";
7777 LoweringOptions options(module);
7778 SmallVector<HWEmittableModuleLike> modulesToPrepare;
7780 [&](HWEmittableModuleLike op) { modulesToPrepare.push_back(op); });
7781 if (failed(failableParallelForEach(
7782 module->getContext(), modulesToPrepare,
7783 [&](
auto op) { return prepareHWModule(op, options); })))
7791struct ExportSplitVerilogPass
7792 :
public circt::impl::ExportSplitVerilogBase<ExportSplitVerilogPass> {
7793 ExportSplitVerilogPass(StringRef directory) {
7794 directoryName = directory.str();
7796 void runOnOperation()
override {
7798 mlir::OpPassManager preparePM(
"builtin.module");
7800 auto &modulePM = preparePM.nest<hw::HWModuleOp>();
7801 modulePM.addPass(createPrepareForEmission());
7802 if (failed(runPipeline(preparePM, getOperation())))
7803 return signalPassFailure();
7806 return signalPassFailure();
7811std::unique_ptr<mlir::Pass>
7813 return std::make_unique<ExportSplitVerilogPass>(directory);
assert(baseType &&"element must be base type")
static SmallVector< T > concat(const SmallVectorImpl< T > &a, const SmallVectorImpl< T > &b)
Returns a new vector containing the concatenation of vectors a and b.
static bool hasSVAttributes(Operation *op)
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 ...
static StringRef getPortVerilogName(Operation *module, size_t portArgNum)
Return the verilog name of the port for the module.
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...
static void printParamValue(OpAsmPrinter &p, Operation *, Attribute value, Type resultType)
static SmallVector< PortInfo > getPortList(ModuleTy &mod)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
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
mlir::Operation * getDefinition(mlir::Attribute attr) const override
Lookup a definition for 'symbol' in the cache.
auto * getListener() const
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.
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)
bool isCombinational(Operation *op)
Return true if the specified operation is a combinational logic op.
StringRef getVerilogModuleName(Operation *module)
BaseTy type_dyn_cast(Type type)
StringAttr getVerilogModuleNameAttr(Operation *module)
Returns the verilog module name attribute or symbol name of any module-like operations.
mlir::Type getCanonicalType(mlir::Type type)
Recursively remove HW type aliases from a type and its subelements.
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".
circt::hw::InOutType InOutType
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.
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.
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.
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....
const LoweringOptions & options
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 disallowDeclAssignments
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()
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.