diff --git a/src/najaeda/najaeda/docs/source/loading.rst b/src/najaeda/najaeda/docs/source/loading.rst index ae2a2f860..d362d1f84 100644 --- a/src/najaeda/najaeda/docs/source/loading.rst +++ b/src/najaeda/najaeda/docs/source/loading.rst @@ -17,6 +17,44 @@ Call :func:`najaeda.netlist.reset` at the beginning of scripts and tests when you need an empty universe. Loading a design returns the top :class:`najaeda.netlist.Instance` wrapper. +RTL specialization names +------------------------ + +The SystemVerilog and VHDL loaders share a specialization naming policy. +Instances with the same resolved parameters/generics share a model, including +explicit values equal to defaults. The selected top retains its source +module/entity name, including when its parameters are overridden. Its resolved +values remain available as metadata. For child models, the all-default +specialization keeps the source name. If a non-default top already owns that +name in a finite recursive hierarchy, the default-valued child uses the hash +fallback. If a VHDL default environment cannot be evaluated, naming uses all +resolved values; an unused overridden default does not prevent elaboration. +Other names list values differing from the declared +default environment, in declaration order: for example ``queue__DEPTH_12`` in +SystemVerilog or ``queue__depth_12`` in VHDL. SystemVerilog identifier case is +preserved; VHDL basic identifiers are canonicalized to lower case. + +Integers use decimal with ``n`` for a minus sign, logic vectors use full-width +upper-case hexadecimal prefixed by ``h``, and vectors containing X/Z use binary +prefixed by ``b``. Scalar bits use ``0``/``1``, and VHDL booleans use +``true``/``false``. String values use readable names when sanitization preserves +all characters; otherwise they use hashes to avoid order-dependent collisions +between values such as ``"a-b"`` and ``"a b"``. A candidate longer than 64 characters, or an override without +a readable encoding, uses ``__h<8 hex digits>`` from SHA-256 of a +versioned, length-prefixed canonical resolved environment. Digest-prefix +collisions promote both designs to 16 digits. Source module names are reserved +before elaboration; collisions with them use the hash form or report an error +if that is also occupied. Source identifiers themselves are never truncated. +SystemVerilog interface port bindings also contribute their resolved types and +alias relationships to identity; these implicit specializations use hash names. + +Resolved values and the original source identifier are available from the raw +API; see :doc:`raw_api`. Names do not replace that metadata. Supported generic +types remain subject to each frontend's language subset. VHDL logic generics +preserve supported X/Z constants; other std_ulogic states and unsupported composite generic types produce diagnostics. +VHDL real generics support finite static real expressions; they do not imply +real-valued hardware support. Enumeration generics use their declared literal names. + Gate-level Verilog ------------------ diff --git a/src/najaeda/najaeda/docs/source/raw_api.rst b/src/najaeda/najaeda/docs/source/raw_api.rst index 13fcf360e..8d5ca441e 100644 --- a/src/najaeda/najaeda/docs/source/raw_api.rst +++ b/src/najaeda/najaeda/docs/source/raw_api.rst @@ -6,6 +6,36 @@ by ``SNLInstance.getInstParameters()`` iterate in lexical parameter-name order. This order is independent of name interning and is preserved across fresh-process NajaIF reloads. +Elaborated RTL specializations +------------------------------ + +SystemVerilog and VHDL elaborated designs expose every resolved non-local +parameter/generic through ``SNLDesign.getParameters()``. The selected top retains +its source name even with non-default parameters; child models use specialization +names. Both expose the resolved values. ``getValue()`` returns +source-language literal text (including quotes on string literals), rather than +an instance override. These parameters describe fixed elaborated circuitry; +changing an instance parameter does not re-elaborate it. ``getInstParameters()`` +therefore remains empty for these RTL instances. Use the raw API directly when +inspecting specialization metadata; high-level instance traversal still returns +the same specialized model. + +The design attribute ``naja.source_module`` records the original module/entity +identifier. It is available without retaining source intent or a live AST: + +.. code-block:: python + + model = instance.getModel() + source_module = next(a.getValue() for a in model.getAttributes() + if a.getName() == "naja.source_module") + resolved = {p.getName(): p.getValue() for p in model.getParameters()} + +The ``naja.elaboration_signature`` attribute is a versioned internal identity +record; callers should treat it as opaque. Both attributes and resolved values +survive NajaIF save/load, cloning and fresh-process reloads. Gate-level Verilog +uses the specialized design names directly and omits these informational +parameter declarations, including VHDL literal text. + ``najaeda`` ships two Python API levels: * :mod:`najaeda.netlist` is the supported high-level API for most tools. diff --git a/src/nl/formats/hdl/BUILD.bazel b/src/nl/formats/hdl/BUILD.bazel index ef05e8e94..58ffdd188 100644 --- a/src/nl/formats/hdl/BUILD.bazel +++ b/src/nl/formats/hdl/BUILD.bazel @@ -4,9 +4,9 @@ load("@rules_cc//cc:cc_library.bzl", "cc_library") cc_library( name = "naja_snl_hdl", - srcs = ["SNLRTLPrimitives.cpp"], - hdrs = ["SNLRTLPrimitives.h", "SNLHDLLibrary.h", "SNLHDLMuxSelection.h"], + srcs = ["SNLRTLPrimitives.cpp", "SNLHDLSpecialization.cpp"], + hdrs = ["SNLHDLSpecialization.h", "SNLRTLPrimitives.h", "SNLHDLLibrary.h", "SNLHDLMuxSelection.h"], includes = ["."], visibility = ["//visibility:public"], - deps = ["//src/nl/netlist:naja_nl"], + deps = ["//src/nl/netlist:naja_nl", "//thirdparty/sha256"], ) diff --git a/src/nl/formats/hdl/CMakeLists.txt b/src/nl/formats/hdl/CMakeLists.txt index ac8cc8570..a461e1c75 100644 --- a/src/nl/formats/hdl/CMakeLists.txt +++ b/src/nl/formats/hdl/CMakeLists.txt @@ -1,12 +1,13 @@ # SPDX-License-Identifier: Apache-2.0 -add_library(naja_snl_hdl STATIC SNLRTLPrimitives.cpp) +add_library(naja_snl_hdl STATIC SNLRTLPrimitives.cpp SNLHDLSpecialization.cpp) set_property(TARGET naja_snl_hdl PROPERTY POSITION_INDEPENDENT_CODE ON) target_link_libraries(naja_snl_hdl PUBLIC naja_nl) +target_include_directories(naja_snl_hdl PRIVATE ${PROJECT_SOURCE_DIR}/thirdparty/sha256) target_include_directories(naja_snl_hdl PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) if(NOT BUILD_NAJA_PYTHON) - set_target_properties(naja_snl_hdl PROPERTIES PUBLIC_HEADER "SNLRTLPrimitives.h;SNLHDLLibrary.h") + set_target_properties(naja_snl_hdl PROPERTIES PUBLIC_HEADER "SNLRTLPrimitives.h;SNLHDLLibrary.h;SNLHDLSpecialization.h") install(TARGETS naja_snl_hdl ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) diff --git a/src/nl/formats/hdl/SNLHDLSpecialization.cpp b/src/nl/formats/hdl/SNLHDLSpecialization.cpp new file mode 100644 index 000000000..825ce9c90 --- /dev/null +++ b/src/nl/formats/hdl/SNLHDLSpecialization.cpp @@ -0,0 +1,164 @@ +// SPDX-FileCopyrightText: 2026 The Naja authors +// SPDX-License-Identifier: Apache-2.0 +#include "SNLHDLSpecialization.h" + +#include "NLLibrary.h" +#include "NLException.h" +#include "SNLDesign.h" +#include "SNLAttributes.h" +#include "SNLParameter.h" +#include "sha-256.h" + +namespace naja::NL { +namespace { +constexpr auto sourceAttribute = "naja.source_module"; +constexpr auto signatureAttribute = "naja.elaboration_signature"; +std::string digest(const std::string& text) { + uint8_t bytes[32]; + calc_sha_256(bytes, text.data(), text.size()); + std::string result; + for (auto byte : bytes) { + result += "0123456789abcdef"[byte >> 4]; + result += "0123456789abcdef"[byte & 15]; + } + return result; +} +void append(std::string& result, const std::string& value) { + result += std::to_string(value.size()) + ":" + value; +} +} + +std::string SNLHDLSpecialization::signature(const std::vector& parameters, const std::string& context) { + std::string result = "naja-elaboration-v1:"; + for (const auto& parameter : parameters) { + append(result, parameter.name); + append(result, parameter.identity); + } + if (!context.empty()) append(result, context); + return result; +} + +std::string SNLHDLSpecialization::attribute(const SNLDesign* design, const std::string& name) { + for (const auto& attr : SNLAttributes::getAttributes(design)) + if (attr.getName().getString() == name) return attr.getValue().getString(); + return {}; +} +bool SNLHDLSpecialization::isElaborated(const SNLDesign* design) { + return !attribute(design, sourceAttribute).empty(); +} + +std::string SNLHDLSpecialization::name(NLLibrary* library, const std::string& source, + const std::vector& parameters, const std::set& sourceNames, + const std::string& context, bool isTop) { + const auto identity = signature(parameters, context); + auto candidate = source; + bool defaults = context.empty(), readable = context.empty(); + for (const auto& parameter : parameters) { + if (parameter.isDefault) continue; + defaults = false; + if (!parameter.nameValue) readable = false; + else { + const auto safe = [](const std::string& value) { + return value.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") == std::string::npos; + }; + if (!safe(parameter.name) || !safe(*parameter.nameValue)) readable = false; + candidate += "__" + parameter.name + "_" + *parameter.nameValue; + } + } + const auto matches = [&](SNLDesign* design) { + return attribute(design, sourceAttribute) == source && + attribute(design, signatureAttribute) == identity; + }; + const auto available = [&](const std::string& value) { + auto* existing = library->getSNLDesign(NLName(value)); + return (!existing || matches(existing)) && (value == source || !sourceNames.contains(value)); + }; + // The selected root is an external interface. Parameter specialization only + // changes child model names; root metadata still records the resolved values. + if (isTop || defaults) { + if (available(source)) return source; + auto* existing = library->getSNLDesign(NLName(source)); + if (isTop || !existing || attribute(existing, sourceAttribute) != source) + throw NLException("Conflicting HDL source design name: " + source); + // A non-default root may own the plain name in a finite recursive + // hierarchy. Its default-valued child follows the usual hash fallback. + } + if (readable && candidate.size() <= 64 && available(candidate)) return candidate; + const auto hash = digest(identity); + candidate = source + "__h" + hash.substr(0, 8); + // Once a prefix has collided, all members of that bucket use 64 bits. + for (auto* design : library->getSNLDesigns()) { + if (attribute(design, sourceAttribute) != source) continue; + const auto previousHash = digest(attribute(design, signatureAttribute)); + if (previousHash.substr(0, 8) == hash.substr(0, 8) && + design->getName().getString() == source + "__h" + previousHash.substr(0, 16)) { + const auto longer = source + "__h" + hash.substr(0, 16); + if (available(longer)) return longer; + throw NLException("Conflicting hashed HDL specialization: " + longer); + } + } + if (available(candidate)) return candidate; + // A genuine truncated-digest collision promotes both specializations. User + // names never get renamed and cannot be bypassed with a longer digest. + auto* previous = library->getSNLDesign(NLName(candidate)); + if (previous && attribute(previous, sourceAttribute) == source && !sourceNames.contains(candidate)) { + const auto previousIdentity = attribute(previous, signatureAttribute); + const auto previousHash = digest(previousIdentity); + if (previousHash.substr(0, 8) == hash.substr(0, 8) && previousIdentity != identity) { + const auto longer = source + "__h" + hash.substr(0, 16); + const auto previousLonger = source + "__h" + previousHash.substr(0, 16); + if (longer != previousLonger && available(longer) && + !sourceNames.contains(previousLonger) && !library->getSNLDesign(NLName(previousLonger))) { + previous->setName(NLName(previousLonger)); + return longer; + } + } + } + // Reuse an already-promoted specialization on a later load. + const auto longer = source + "__h" + hash.substr(0, 16); + if (auto* existing = library->getSNLDesign(NLName(longer)); existing && matches(existing)) return longer; + throw NLException("Conflicting hashed HDL specialization: " + candidate); +} + +void SNLHDLSpecialization::annotate(SNLDesign* design, const std::string& source, + const std::vector& parameters, const std::string& context) { + SNLAttributes::addAttribute(design, SNLAttribute(NLName(sourceAttribute), SNLAttributeValue(source))); + SNLAttributes::addAttribute(design, SNLAttribute(NLName(signatureAttribute), SNLAttributeValue(signature(parameters, context)))); + for (const auto& parameter : parameters) + SNLParameter::create(design, NLName(parameter.name), SNLParameter::Type::Decimal, parameter.literal); +} + +std::string SNLHDLSpecialization::identifierValue(std::string value) { + for (auto& c : value) + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))) c = '_'; + return value; +} +std::string SNLHDLSpecialization::integerValue(std::string value) { + std::string result; + for (char c : value) { + if (c == '+') continue; + if (c == '-') c = 'n'; + else if (c == '.') c = 'p'; + else if (c == 'E') c = 'e'; + result += c; + } + return result; +} +std::string SNLHDLSpecialization::bitValue(const std::string& bits, bool scalar) { + if (scalar && bits.size() == 1 && (bits[0] == '0' || bits[0] == '1')) return bits; + if (bits.find_first_not_of("01") != std::string::npos) { + std::string result = "b" + bits; + for (auto& c : result) if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; + return result; + } + std::string padded((4 - bits.size() % 4) % 4, '0'); + padded += bits; + std::string result = "h"; + for (size_t i = 0; i < padded.size(); i += 4) { + unsigned digit = 0; + for (size_t j = 0; j < 4; ++j) digit = digit * 2 + (padded[i + j] == '1'); + result += "0123456789ABCDEF"[digit]; + } + return result; +} +} diff --git a/src/nl/formats/hdl/SNLHDLSpecialization.h b/src/nl/formats/hdl/SNLHDLSpecialization.h new file mode 100644 index 000000000..44496239d --- /dev/null +++ b/src/nl/formats/hdl/SNLHDLSpecialization.h @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2026 The Naja authors +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include +#include +#include +#include + +namespace naja::NL { +class NLLibrary; +class SNLDesign; + +// Frontends supply resolved values in declaration order. Identity text must +// include type/shape information; literal text is valid in the source language. +struct SNLHDLParameter { + std::string name; + std::string identity; + std::string literal; + std::optional nameValue; + bool isDefault = false; +}; + +class SNLHDLSpecialization { + public: + static std::string signature(const std::vector& parameters, const std::string& context = {}); + static std::string name(NLLibrary* library, const std::string& source, + const std::vector& parameters, + const std::set& sourceNames, const std::string& context = {}, + bool isTop = false); + static void annotate(SNLDesign* design, const std::string& source, + const std::vector& parameters, const std::string& context = {}); + static bool isElaborated(const SNLDesign* design); + static std::string attribute(const SNLDesign* design, const std::string& name); + static std::string identifierValue(std::string value); + static std::string integerValue(std::string value); + static std::string bitValue(const std::string& bits, bool scalar = false); +}; +} diff --git a/src/nl/formats/systemverilog/frontend/SNLSVConstructor.cpp b/src/nl/formats/systemverilog/frontend/SNLSVConstructor.cpp index 651245246..8e20d3fe8 100644 --- a/src/nl/formats/systemverilog/frontend/SNLSVConstructor.cpp +++ b/src/nl/formats/systemverilog/frontend/SNLSVConstructor.cpp @@ -57,6 +57,7 @@ #include "SNLUtils.h" #include "SNLClockGating.h" #include "SNLParameter.h" +#include "SNLHDLSpecialization.h" #include "SNLRTLInfos.h" #include "SNLRTLPrimitives.h" #include "SNLHDLMuxSelection.h" @@ -98,6 +99,8 @@ #include "slang/diagnostics/DeclarationsDiags.h" #include "slang/driver/Driver.h" #include "slang/syntax/SyntaxNode.h" +#include "slang/syntax/AllSyntax.h" +#include "slang/ast/types/TypePrinter.h" #include "slang/syntax/SyntaxTree.h" #include "slang/text/Json.h" #include "slang/text/SourceManager.h" @@ -1533,7 +1536,7 @@ class SNLSVConstructorImpl { ++svPerfReport_.topInstanceBuildsStarted; noteSVPerfProgress(); #endif - buildDesign(top->body); + buildDesign(top->body, true); #ifdef NAJA_ENABLE_SV_CONSTRUCTOR_PERF_REPORT ++svPerfReport_.topInstanceBuildsCompleted; maybeWriteSVPerfReportSnapshot(); @@ -3382,21 +3385,169 @@ endmodule // LCOV_EXCL_STOP } - std::string allocateElaboratedDesignName(const std::string& defName) { - auto& nextOrdinal = elaboratedDesignOrdinals_[defName]; - while (true) { - std::string candidate = defName; - if (nextOrdinal != 0) { - candidate += "__elab" + std::to_string(nextOrdinal); - } - ++nextOrdinal; - if (!library_->getSNLDesign(NLName(candidate))) { - return candidate; + static std::string specializationType(const Type& type) { + slang::ast::TypePrinter printer; + printer.options.skipScopedTypeNames = true; + printer.options.elideScopeNames = true; + printer.options.fullEnumType = true; + printer.append(type.getCanonicalType()); + return printer.toString(); + } + + static std::string nominalTypeIdentity(const Type& type) { + const auto& canonical = type.getCanonicalType(); + if (const auto* element = canonical.getArrayElementType()) return nominalTypeIdentity(*element); + if (!canonical.isEnum() && !canonical.isStruct() && !canonical.isUnion()) return {}; + const auto* scope = canonical.getParentScope(); + std::string identity = scope ? scope->asSymbol().getLexicalPath() : std::string{}; + for (auto* syntax = canonical.getSyntax(); syntax; syntax = syntax->parent) { + if (syntax->kind == slang::syntax::SyntaxKind::TypedefDeclaration) + return identity + "::" + std::string(syntax->as().name.valueText()); + if (syntax->kind == slang::syntax::SyntaxKind::TypeAssignment) + return identity + "::" + std::string(syntax->as().name.valueText()); + } + return identity; + } + + std::vector specializationParameters(const InstanceBodySymbol& body) { + const auto& definition = body.getDefinition(); + const InstanceBodySymbol* defaults = nullptr; + if (std::all_of(definition.parameters.begin(), definition.parameters.end(), + [](const auto& parameter) { return parameter.hasDefault(); })) { + auto [it, inserted] = defaultParameterBodies_.try_emplace(&definition, nullptr); + if (inserted) it->second = &InstanceSymbol::createDefault(*compilation_, definition).body; + defaults = it->second; + } + std::vector result; + const auto parameters = body.getParameters(); + const auto defaultParameters = defaults ? defaults->getParameters() : decltype(parameters){}; + for (size_t i = 0; i < parameters.size(); ++i) { + const auto& parameter = *parameters[i]; + if (parameter.isLocalParam()) continue; + const auto& symbol = parameter.symbol; + SNLHDLParameter record; + record.name = std::string(symbol.name); + if (symbol.kind == SymbolKind::TypeParameter) { + const auto& type = symbol.as().targetType.getType(); + const auto canonical = specializationType(type); + record.literal = type.isUnpackedArray() && type.kind == SymbolKind::TypeAlias ? type.toString() : canonical; + record.identity = "type:" + nominalTypeIdentity(type) + ":" + canonical; + if (i < defaultParameters.size()) { + const auto& defaultType = defaultParameters[i]->symbol.as().targetType.getType(); + record.isDefault = type.isMatching(defaultType) || record.identity == + "type:" + nominalTypeIdentity(defaultType) + ":" + specializationType(defaultType); + } + } else { + const auto& valueSymbol = symbol.as(); + const auto& value = valueSymbol.getValue(); + const auto& type = valueSymbol.getType(); + record.literal = value.toString(slang::SVInt::MAX_BITS, true, true); + record.identity = specializationType(type) + ":" + record.literal; + if (i < defaultParameters.size()) { + const auto& defaultSymbol = defaultParameters[i]->symbol.as(); + record.isDefault = specializationType(type) == specializationType(defaultSymbol.getType()) && + value == defaultSymbol.getValue(); + } + if (type.isEnum()) { + for (const auto& literal : type.getCanonicalType().as().values()) { + if (literal.getValue() == value) { + record.nameValue = std::string(literal.name); + record.literal = std::string(literal.name); + const auto* scope = literal.getParentScope(); + if (scope && scope->asSymbol().kind == SymbolKind::EnumType) + scope = scope->asSymbol().getParentScope(); + if (scope && (scope->asSymbol().kind == SymbolKind::Package || + scope->asSymbol().kind == SymbolKind::ClassType)) + record.literal = scope->asSymbol().getHierarchicalPath() + "::" + record.literal; + break; + } + } + } else if (value.isString()) { + const auto readableString = SNLHDLSpecialization::identifierValue(value.str()); + if (readableString == value.str()) record.nameValue = readableString; + // ConstantValue's display formatter does not escape source strings. + record.literal = "\""; + for (unsigned char c : value.str()) { + if (c == '\\' || c == '"') record.literal += '\\'; + if (c == '\n') record.literal += "\\n"; + else if (c == '\r') record.literal += "\\r"; + else if (c == '\t') record.literal += "\\t"; + else if (c < 32 || c >= 127) { + record.literal += '\\'; + record.literal += char('0' + ((c >> 6) & 7)); + record.literal += char('0' + ((c >> 3) & 7)); + record.literal += char('0' + (c & 7)); + } else record.literal += c; + } + record.literal += '"'; + record.identity = specializationType(type) + ":" + record.literal; + } else if (value.isReal() || value.isShortReal()) { + record.nameValue = SNLHDLSpecialization::integerValue(record.literal); + } else if (value.isInteger() && (type.isPredefinedInteger() || type.isSimpleBitVector())) { + const auto& integer = value.integer(); + const auto* declared = valueSymbol.getDeclaredType()->getTypeSyntax(); + const bool inferredInteger = declared && declared->kind == slang::syntax::SyntaxKind::ImplicitType && + declared->as().dimensions.empty() && integer.isSigned(); + if ((type.isPredefinedInteger() || inferredInteger) && !integer.hasUnknown()) { + record.literal = integer.toString(slang::LiteralBase::Decimal, false); + record.nameValue = SNLHDLSpecialization::integerValue(record.literal); + } else { + std::string bits; + for (auto bit = integer.getBitWidth(); bit > 0; --bit) bits += integer[int32_t(bit - 1)].toChar(); + const auto component = SNLHDLSpecialization::bitValue(bits, type.isScalar()); + record.nameValue = component; + const auto width = std::to_string(integer.getBitWidth()); + if (integer.hasUnknown() || bits.size() == 1) + record.literal = width + (integer.isSigned() ? "'sb" : "'b") + bits; + else record.literal = width + (integer.isSigned() ? "'sh" : "'h") + component.substr(1); + } + } } + result.push_back(std::move(record)); + } + return result; + } + + std::string specializationContext(const InstanceBodySymbol& body) { + // Interface bindings are implicit type/alias parameters. Slang's ordinary + // module parameter comparison does not cover them. + std::string context; + std::unordered_map aliases; + const auto append = [&](const std::string& value) { + context += std::to_string(value.size()) + ":" + value; + }; + for (const auto* symbol : body.getPortList()) { + if (symbol->kind != SymbolKind::InterfacePort) continue; + const auto& port = symbol->as(); + append(std::string(port.name)); + const auto [connected, modport] = port.getConnection(); + if (modport) append(std::string(modport->name)); + const auto describe = [&](const auto& self, const Symbol* connection) -> void { + if (!connection) return; + if (connection->kind == SymbolKind::InstanceArray) { + const auto& array = connection->as(); + append(array.range.toString()); + for (const auto* element : array.elements) self(self, element); + } else if (connection->kind == SymbolKind::Instance) { + const auto& instance = connection->as(); + append(std::string(instance.getDefinition().name)); + append(SNLHDLSpecialization::signature(specializationParameters(instance.body))); + } + }; + describe(describe, connected); + visitInterfacePortSignals(port, [&](const std::string& name, + const slang::ast::ModportPortSymbol& member) { + append(name); + append(specializationType(member.getType())); + append(std::to_string(int(member.direction))); + const auto [it, inserted] = aliases.try_emplace(member.internalSymbol, aliases.size()); + append(std::to_string(it->second)); + }); } + return context; } - SNLDesign* buildDesign(const InstanceBodySymbol& body) { + SNLDesign* buildDesign(const InstanceBodySymbol& body, bool isTop = false) { #ifdef NAJA_ENABLE_SV_CONSTRUCTOR_PERF_REPORT ++svPerfReport_.buildDesignCalls; noteSVPerfProgress(); @@ -3470,7 +3621,18 @@ endmodule inferredMemorySequentialBlocks_ = std::move(savedInferredMemorySequentialBlocks); }); - auto design = SNLDesign::create(library_, NLName(allocateElaboratedDesignName(defName))); + const auto parameters = specializationParameters(body); + const auto context = specializationContext(body); + std::set sourceNames; + for (const auto* symbol : compilation_->getDefinitions()) sourceNames.emplace(symbol->name); + const auto name = SNLHDLSpecialization::name(library_, defName, parameters, sourceNames, context, isTop); + if (auto* existing = library_->getSNLDesign(NLName(name)); existing && hasInterfacePorts) { + bodyToDesign_[&body] = existing; + representativeBodies.push_back(&body); + return existing; + } + auto design = SNLDesign::create(library_, NLName(name)); + SNLHDLSpecialization::annotate(design, defName, parameters, context); bodyToDesign_[&body] = design; representativeBodies.push_back(&body); annotateSourceInfo(design, getSourceRange(definition), true); @@ -37348,7 +37510,7 @@ endmodule std::unordered_map unknownBlackboxes_; std::unordered_map> representativeBodiesByDefinition_; - std::unordered_map elaboratedDesignOrdinals_; + std::unordered_map defaultParameterBodies_; std::ofstream diagnosticsReportStream_; std::unordered_set reportSections_; std::unordered_map slangSeverityCounts_; diff --git a/src/nl/formats/verilog/backend/SNLVRLDumper.cpp b/src/nl/formats/verilog/backend/SNLVRLDumper.cpp index eea2f2acd..6fd2da21a 100644 --- a/src/nl/formats/verilog/backend/SNLVRLDumper.cpp +++ b/src/nl/formats/verilog/backend/SNLVRLDumper.cpp @@ -1265,6 +1265,10 @@ void SNLVRLDumper::dumpAttributes( snlAttributesStart = std::chrono::steady_clock::now(); // LCOV_EXCL_LINE } for (const auto& attribute: SNLAttributes::getAttributes(object)) { + // Elaboration metadata is preserved by NajaIF; its source-language values + // and internal identity encoding are not Verilog attributes. + const auto& name = attribute.getName().getString(); + if (name == "naja.source_module" || name == "naja.elaboration_signature") continue; ++dumpedSNLAttributes; o << "(* "; o << attribute.getName().getString(); @@ -2429,6 +2433,9 @@ void SNLVRLDumper::dumpParameters(const SNLDesign* design, std::ostream& o) { [](const SNLParameter* lhs, const SNLParameter* rhs) { return lhs->getName().getString() < rhs->getName().getString(); }); + for (const auto& attribute : SNLAttributes::getAttributes(design)) + if (attribute.getName().getString() == "naja.elaboration_signature" && + attribute.getValue().getString().starts_with("naja-elaboration-v1:")) return; bool atLeastOne = false; for (auto parameter: parameters) { atLeastOne = true; diff --git a/src/nl/formats/vhdl/VHDLConstructor.cpp b/src/nl/formats/vhdl/VHDLConstructor.cpp index fdbd7e570..8dcdb8931 100644 --- a/src/nl/formats/vhdl/VHDLConstructor.cpp +++ b/src/nl/formats/vhdl/VHDLConstructor.cpp @@ -3,6 +3,7 @@ #include "VHDLConstructor.h" #include "VHDLIntent.h" +#include "SNLHDLSpecialization.h" #include "NajaPrivateProperty.h" #include "VHDLRTLConstructor.h" #include "VHDLSourceInfo.h" @@ -534,6 +535,7 @@ SNLDesign* VHDLConstructor::constructInputs( } auto* design = SNLDesign::create(library_, NLName(topEntity->name.spelling)); topDesign = design; + SNLHDLSpecialization::annotate(design, std::string(nameKey(topEntity->name)), {}); sourceMap.annotate(design, topEntity->span, true); sourceMap.annotate(design, topArchitecture->span); std::unordered_map nets; @@ -827,6 +829,7 @@ SNLDesign* VHDLConstructor::constructInputs( SNLDesign::create(library_, NLName(entity.name.spelling)), [](SNLDesign* design) { design->destroy(); }); auto* design = designGuard.get(); + SNLHDLSpecialization::annotate(design, std::string(nameKey(entity.name)), {}); sourceMap.annotate(design, entity.span, true); sourceMap.annotate(design, architecture.span); for (const auto& port : entity.ports) { diff --git a/src/nl/formats/vhdl/VHDLRTLConstructor.cpp b/src/nl/formats/vhdl/VHDLRTLConstructor.cpp index 78278ebe8..d98385030 100644 --- a/src/nl/formats/vhdl/VHDLRTLConstructor.cpp +++ b/src/nl/formats/vhdl/VHDLRTLConstructor.cpp @@ -7,6 +7,7 @@ #include "NLException.h" #include "NLDB0.h" #include "SNLHDLLibrary.h" +#include "SNLHDLSpecialization.h" #include "SNLInstParameter.h" #include "NLLibrary.h" #include "NajaPrivateProperty.h" @@ -34,12 +35,15 @@ #include #include #include +#include #include #include +#include #include #include #include #include +#include #include #include @@ -273,9 +277,10 @@ struct StaticScalar { }; struct GenericValue { StaticScalar scalar; - // Binary bits in declaration order, independent of the caller's netlist. + // Logic bits in declaration order, independent of the caller's netlist. std::optional bits; std::optional text; + std::optional real; }; using GenericValues = std::map; @@ -300,13 +305,18 @@ class RTLConstructor { const auto type = key(generic.type.name); const bool vector = type == "bit_vector" || type == "std_logic_vector" || type == "std_ulogic_vector" || type == "unsigned" || type == "signed"; - if (!vector && type != "integer" && type != "natural" && type != "positive" && type != "boolean" && type != "string") - fail("RTL generics require an integer subtype, boolean, string, or constrained binary vector"); + const bool logic = type == "bit" || type == "std_logic" || type == "std_ulogic"; + const bool enumeration = enumerations_.contains(type); + if (!vector && !logic && !enumeration && type != "real" && type != "integer" && type != "natural" && type != "positive" && type != "boolean" && type != "string") + fail("RTL generics require an integer subtype, boolean, real, enumeration, string, bit, or constrained logic vector"); std::optional target; if (type == "string") { if (generic.type.constraint) fail("constrained string generics are unsupported"); target = Shape{{"string"}, {}}; - } else if (vector) { + } else if (type == "real") { + if (generic.type.constraint) fail("constrained real generics are unsupported"); + target = Shape{{"real"}, {}}; + } else if (vector || logic || enumeration) { target = shape(generic.type); target->size(); } @@ -326,7 +336,10 @@ class RTLConstructor { record["declared_type"] = declaredTypeIntent(generic.type, target ? &*target : nullptr); record["default_expression"] = expressionIntent(generic.defaultValue.get()); record["overridden"] = genericOverrides_.contains(id); - if (value.text) record["effective_value"] = *value.text; + if (value.real) { + record["effective_value"] = realLiteral(*value.real); + record["value_format"] = "real_literal"; + } else if (value.text) record["effective_value"] = *value.text; else if (value.bits) { record["effective_value"] = *value.bits; record["value_format"] = "bits_in_declaration_order"; @@ -347,18 +360,54 @@ class RTLConstructor { } else record["default_value_status"] = "unsupported_without_additional_elaboration"; intentDeclarations_.emplace_back(record); } + SNLHDLParameter parameter; + parameter.name = id; + if (value.real) { + parameter.literal = realLiteral(*value.real); + parameter.nameValue = SNLHDLSpecialization::integerValue(parameter.literal); + } else if (value.text) { + parameter.literal = "\""; + for (const char c : *value.text) { + parameter.literal += c; + if (c == '"') parameter.literal += c; + } + parameter.literal += '"'; + const auto readableString = SNLHDLSpecialization::identifierValue(*value.text); + if (readableString == *value.text) parameter.nameValue = readableString; + } else if (value.bits && enumeration) { + size_t index = 0; + for (const char bit : *value.bits) index = 2 * index + (bit == '1'); + if (index >= target->enumeration->literals.size()) fail("invalid enumeration generic value"); + parameter.literal = key(target->enumeration->literals[index]); + parameter.nameValue = parameter.literal; + } else if (value.bits) { + parameter.nameValue = SNLHDLSpecialization::bitValue(*value.bits, logic); + const bool binary = value.bits->find_first_not_of("01") == std::string::npos; + parameter.literal = logic ? "'" + *value.bits + "'" : + binary && value.bits->size() % 4 == 0 ? + "x\"" + parameter.nameValue->substr(1) + "\"" : "\"" + *value.bits + "\""; + } else { + parameter.literal = value.scalar.boolean ? (value.scalar.value ? "true" : "false") : + std::to_string(value.scalar.value); + parameter.nameValue = SNLHDLSpecialization::integerValue(parameter.literal); + } + parameter.identity = type + ":" + parameter.literal; + specializationParameters_.push_back(std::move(parameter)); interfaceBindings_->declare(id); if (retainingIntent()) intentBindings_[id] = intentDeclarations_.back(); - if (type == "string") { + if (type == "real") { + if (!value.real) fail("real generic requires a static real value: " + id); + reals_.emplace(id, *value.real); + } else if (type == "string") { if (!value.text) fail("string generic requires a static string value: " + id); strings_.emplace(id, *value.text); - } else if (vector) { + } else if (vector || logic || enumeration) { if (!value.bits || value.bits->size() != target->size()) fail("vector generic type or length mismatch: " + id); Value object{*target, {}}; - for (char bit : *value.bits) object.bits.push_back(constant(bit == '1')); + for (char bit : *value.bits) object.bits.push_back(logicLiteral(bit, *target)); objects_.emplace(id, Object{std::move(object), false, false, false, true}); } else { - if (value.text || value.bits || value.scalar.boolean != (type == "boolean")) fail("generic value type mismatch: " + id); + if (value.real || value.text || value.bits || value.scalar.boolean != (type == "boolean")) fail("generic value type mismatch: " + id); if (type == "boolean" && generic.type.constraint) fail("boolean generic constraints are unsupported"); if (generic.type.constraint) range(*generic.type.constraint).position(value.scalar.value); if ((type == "positive" && value.scalar.value < 1) || (type == "natural" && value.scalar.value < 0)) @@ -370,6 +419,8 @@ class RTLConstructor { } } + const auto& specializationParameters() const { return specializationParameters_; } + bool staticString(const Expr& expr) const { return expr.kind == Expr::Kind::StringLiteral || (expr.kind == Expr::Kind::Name && strings_.contains(key(expr))) || @@ -402,8 +453,62 @@ class RTLConstructor { fail("unsupported string generic attribute: " + name); } + static std::string realLiteral(double value) { + char buffer[128]; + const auto converted = std::to_chars(buffer, buffer + sizeof(buffer), value == 0 ? 0.0 : value); + if (converted.ec != std::errc{}) fail("cannot format real generic"); + std::string text(buffer, converted.ptr); + const auto exponent = text.find_first_of("eE"); + if (text.substr(0, exponent).find('.') == std::string::npos) + text.insert(exponent == std::string::npos ? text.size() : exponent, ".0"); + return text; + } + + double realValue(const Expr& expr) { + double value; + if (expr.kind == Expr::Kind::RealLiteral) { + std::string text; + for (char c : expr.text) if (c != '_') text += c; + // Floating-point from_chars is unavailable in older supported libc++. + // The classic locale keeps source literals independent of the host locale. + std::istringstream literal(text); + literal.imbue(std::locale::classic()); + value = 0; + literal >> std::noskipws >> value; + // Some libraries set failbit for representable subnormals, including + // values rounding to the smallest normal. Preserve those, but reject + // overflow and nonzero literals that underflow to zero. + const bool representableTinyValue = value != 0 && + std::abs(value) <= std::numeric_limits::min(); + // Other libraries underflow to zero without setting failbit. Exponent + // digits do not make an otherwise zero significand nonzero. + const auto significandEnd = text.begin() + std::min(text.find_first_of("eE"), text.size()); + const bool nonzeroSignificand = std::any_of(text.begin(), significandEnd, + [](char digit) { return digit >= '1' && digit <= '9'; }); + if (!literal.eof() || literal.bad() || (literal.fail() && !representableTinyValue) || + (value == 0 && nonzeroSignificand)) + fail("unsupported real generic literal"); + } else if (expr.kind == Expr::Kind::Name && reals_.contains(key(expr))) value = reals_.at(key(expr)); + else if (expr.kind == Expr::Kind::Unary && (expr.text == "+" || expr.text == "-")) + value = (expr.text == "-" ? -1 : 1) * realValue(*expr.left); + else if (expr.kind == Expr::Kind::Binary) { + const auto left = realValue(*expr.left), right = realValue(*expr.right); + if (expr.text == "+") value = left + right; + else if (expr.text == "-") value = left - right; + else if (expr.text == "*") value = left * right; + else if (expr.text == "/") { + if (right == 0) fail("division by zero in real generic"); + value = left / right; + } else fail("unsupported real generic operator"); + } else fail("real generic requires a static real expression"); + if (!std::isfinite(value)) fail("non-finite real generic value"); + return value; + } + GenericValue genericValue(const Expr& actual, const Shape* expected) { DiagnosticScope location(actual.span); + if (expected && expected->types == std::vector{"real"}) + return {{}, {}, {}, realValue(actual)}; if (expected && expected->types == std::vector{"string"}) return {{}, {}, stringValue(actual)}; if (!expected) return {scalar(actual), {}}; @@ -411,8 +516,10 @@ class RTLConstructor { std::string bits; for (auto* bit : value.bits) { const auto binary = constantValue(bit); - if (!binary) fail("vector generic actual must be static and binary"); - bits += *binary ? '1' : '0'; + if (binary) bits += *binary ? '1' : '0'; + else if (bit && bit->isConstantX()) bits += 'X'; + else if (bit && bit->isConstantZ()) bits += 'Z'; + else fail("logic generic actual must be static"); } return {{}, std::move(bits)}; } @@ -1151,7 +1258,7 @@ class RTLConstructor { void addSubtype(const vhdl::SubtypeDeclaration& declaration) { DiagnosticScope location(declaration.span); const auto name = key(declaration.name); - if (strings_.contains(name) || subtypes_.contains(name) || functions_.contains(name) || objects_.contains(name) || + if (reals_.contains(name) || strings_.contains(name) || subtypes_.contains(name) || functions_.contains(name) || objects_.contains(name) || integers_.contains(name) || booleans_.contains(name) || arrayDeclarations_.contains(name) || records_.contains(name) || enumerations_.contains(name) || integerTables_.contains(name) || name == "bit" || name == "bit_vector" || name == "boolean" || name == "integer" || @@ -1198,7 +1305,7 @@ class RTLConstructor { void addArray(const vhdl::ArrayTypeDeclaration& declaration) { DiagnosticScope location(declaration.span); const auto name = key(declaration.name); - if (strings_.contains(name) || subtypes_.contains(name) || functions_.contains(name) || booleans_.contains(name) || (enumerations_.contains(name) || records_.contains(name)) || arrayDeclarations_.contains(name) || integerTables_.contains(name) || integers_.contains(name) || objects_.contains(name) || + if (reals_.contains(name) || strings_.contains(name) || subtypes_.contains(name) || functions_.contains(name) || booleans_.contains(name) || (enumerations_.contains(name) || records_.contains(name)) || arrayDeclarations_.contains(name) || integerTables_.contains(name) || integers_.contains(name) || objects_.contains(name) || name == "bit" || name == "bit_vector" || name == "std_logic" || name == "std_logic_vector" || name == "std_ulogic" || name == "std_ulogic_vector" || name == "unsigned" || name == "signed" || name == "integer" || @@ -1250,7 +1357,7 @@ class RTLConstructor { void addRecord(const vhdl::RecordTypeDeclaration& declaration) { DiagnosticScope location(declaration.span); const auto name = key(declaration.name); - if (strings_.contains(name) || subtypes_.contains(name) || functions_.contains(name) || booleans_.contains(name) || (enumerations_.contains(name) || records_.contains(name)) || arrayDeclarations_.contains(name) || + if (reals_.contains(name) || strings_.contains(name) || subtypes_.contains(name) || functions_.contains(name) || booleans_.contains(name) || (enumerations_.contains(name) || records_.contains(name)) || arrayDeclarations_.contains(name) || objects_.contains(name) || integers_.contains(name) || integerTables_.contains(name) || name == "bit" || name == "bit_vector" || name == "std_logic" || name == "std_ulogic" || name == "std_logic_vector" || name == "std_ulogic_vector" || name == "unsigned" || @@ -1489,7 +1596,7 @@ class RTLConstructor { const auto name = key(type.name); std::set names; for (const auto& id : declaration.object.names) - if (strings_.contains(key(id)) || subtypes_.contains(key(id)) || functions_.contains(key(id)) || booleans_.contains(key(id)) || !names.insert(key(id)).second || objects_.contains(key(id)) || integers_.contains(key(id)) || + if (reals_.contains(key(id)) || strings_.contains(key(id)) || subtypes_.contains(key(id)) || functions_.contains(key(id)) || booleans_.contains(key(id)) || !names.insert(key(id)).second || objects_.contains(key(id)) || integers_.contains(key(id)) || integerTables_.contains(key(id)) || (enumerations_.contains(key(id)) || records_.contains(key(id))) || arrayDeclarations_.contains(key(id))) fail("duplicate constant: " + key(id)); if (name == "string") { @@ -1628,7 +1735,7 @@ class RTLConstructor { return; } auto name = key(generate.iterator); - if (integers_.contains(name) || objects_.contains(name) || integerTables_.contains(name) || + if (reals_.contains(name) || integers_.contains(name) || objects_.contains(name) || integerTables_.contains(name) || (enumerations_.contains(name) || records_.contains(name)) || arrayDeclarations_.contains(name)) fail("shadowed generate parameter"); const auto bounds = range(generate.range); for (size_t i = 0; i < bounds.size(); ++i) { @@ -1680,16 +1787,19 @@ class RTLConstructor { const auto parentIntegers = integers_; const auto parentBooleans = booleans_; const auto parentStrings = strings_; + const auto parentReals = reals_; for (const auto& generic : entity->generics) for (const auto& name : generic.names) { const auto id = key(name); integers_.erase(id); booleans_.erase(id); strings_.erase(id); + reals_.erase(id); objects_.erase(id); if (childScope.objects_.contains(id)) objects_[id] = childScope.objects_.at(id); else if (childScope.booleans_.contains(id)) booleans_[id] = childScope.booleans_.at(id); else if (childScope.strings_.contains(id)) strings_[id] = childScope.strings_.at(id); + else if (childScope.reals_.contains(id)) reals_[id] = childScope.reals_.at(id); else integers_[id] = childScope.integers_.at(id); } std::map formalShapes; @@ -1725,6 +1835,7 @@ class RTLConstructor { integers_ = parentIntegers; booleans_ = parentBooleans; strings_ = parentStrings; + reals_ = parentReals; auto* model = build_(targetLibrary, key(instance.entity), overrides); if (const auto* property = dynamic_cast(model->getProperty("VHDLRTLSource"))) for (const auto& [path, content] : property->initializationFiles) { @@ -2135,7 +2246,7 @@ class RTLConstructor { void addLocalFunction(const vhdl::FunctionDeclaration& function) { const auto name = key(function.name); if (!function.body) fail("architecture function forward declarations are unsupported: " + name); - if (strings_.contains(name) || subtypes_.contains(name) || functions_.contains(name) || integers_.contains(name) || booleans_.contains(name) || + if (reals_.contains(name) || strings_.contains(name) || subtypes_.contains(name) || functions_.contains(name) || integers_.contains(name) || booleans_.contains(name) || (objects_.contains(name) && !enumLiterals_.contains(name)) || integerTables_.contains(name) || records_.contains(name) || enumerations_.contains(name) || arrayDeclarations_.contains(name)) fail("duplicate or overloaded architecture function: " + name); @@ -3476,7 +3587,7 @@ class RTLConstructor { const auto id = key(name); if (port && type.ranges.size() > 1) fail("RTL ports require scalar values or one-dimensional logic vectors"); - if (strings_.contains(id) || functions_.contains(id) || booleans_.contains(id) || objects_.contains(id) || integers_.contains(id) || (enumerations_.contains(id) || records_.contains(id)) || arrayDeclarations_.contains(id) || integerTables_.contains(id)) + if (reals_.contains(id) || strings_.contains(id) || functions_.contains(id) || booleans_.contains(id) || objects_.contains(id) || integers_.contains(id) || (enumerations_.contains(id) || records_.contains(id)) || arrayDeclarations_.contains(id) || integerTables_.contains(id)) fail("duplicate or shadowing object: " + id); Bits bits; const auto size = type.size(); @@ -5673,6 +5784,7 @@ class RTLConstructor { hide(owner.aliases_, name); hide(owner.integers_, name); hide(owner.strings_, name); + hide(owner.reals_, name); hide(owner.booleans_, name); hide(owner.functions_, name); hide(owner.enumLiterals_, name); @@ -6159,6 +6271,7 @@ class RTLConstructor { const LibraryContext& libraryContext_; NLLibrary* work_; GenericValues genericOverrides_; + std::vector specializationParameters_; std::function genericActual_; std::function build_; std::set> imported_; @@ -6169,6 +6282,7 @@ class RTLConstructor { std::set instanceNames_; std::map integers_; std::map strings_; + std::map reals_; std::set locallyStaticIntegers_; SubtypeMap subtypes_; std::map functions_; @@ -6243,6 +6357,8 @@ bool requiresVHDLRTL(const vhdl::DesignFile& syntax) { self(self, expression->right.get()) || self(self, expression->condition.get())); }; for (const auto& entity : syntax.entities) { + // All generic specialization uses the same resolver and naming policy. + if (!entity.generics.empty()) return true; if (rtlContext(entity.context)) return true; for (const auto& generic : entity.generics) if (generic.type.constraint || !generic.defaultValue || extendedExpression(extendedExpression, generic.defaultValue.get()) || @@ -6413,20 +6529,37 @@ SNLDesign* constructVHDLRTL(NLLibrary* library, const vhdl::DesignFile& syntax, architecture = &candidate; } if (!entity || !architecture) fail("missing RTL entity or architecture: " + name); - std::string modelName = entity->name.spelling; - for (const auto& [generic, value] : overrides) { - modelName += "__" + generic + "_"; - if (value.text) { - modelName += "s" + std::to_string(value.text->size()) + "_"; - for (const unsigned char c : *value.text) { - modelName += "0123456789abcdef"[c >> 4]; - modelName += "0123456789abcdef"[c & 15]; - } - } else modelName += value.bits ? "v" + *value.bits : value.scalar.boolean ? - (value.scalar.value ? "true" : "false") : std::to_string(value.scalar.value); - } + // Resolve the full environment before looking up a specialization. Actuals + // have already been evaluated in the parent; defaults use the entity scope. + auto scratchDeleter = [](SNLDesign* design) { design->destroy(); }; + std::unique_ptr scratch( + SNLDesign::create(owner), scratchDeleter); + RTLConstructor resolved(scratch.get(), *entity, *architecture, syntax, context, overrides, build); + resolved.prepareEntity(); + auto parameters = resolved.specializationParameters(); + + const bool hasDefaults = std::all_of(entity->generics.begin(), entity->generics.end(), + [](const auto& generic) { return bool(generic.defaultValue); }); + if (hasDefaults) { + try { + RTLConstructor defaults(scratch.get(), *entity, *architecture, syntax, context, {}, build); + defaults.prepareEntity(); + const auto& declared = defaults.specializationParameters(); + for (size_t i = 0; i < parameters.size(); ++i) + parameters[i].isDefault = parameters[i].identity == declared[i].identity; + } catch (const NLException&) { + // The resolved environment above is valid. Unused defaults need not + // elaborate; retain every resolved value in the specialization name. + } + } + scratch.reset(); + std::set sourceNames; + for (const auto& candidate : syntax.entities) + if (context.owner(candidate.span.start.offset) == owner) sourceNames.insert(key(candidate.name)); + const auto modelName = SNLHDLSpecialization::name( + owner, key(entity->name), parameters, sourceNames, {}, owner == library && name == selected); const auto signature = std::string(source.substr(context.start(owner), - std::max(entity->span.end.offset, architecture->span.end.offset) - context.start(owner))) + modelName; + std::max(entity->span.end.offset, architecture->span.end.offset) - context.start(owner))) + SNLHDLSpecialization::signature(parameters); if (auto* existing = owner->getSNLDesign(NLName(modelName))) { auto* property = dynamic_cast(existing->getProperty("VHDLRTLSource")); if (!property || property->signature != signature) fail("conflicting RTL design: " + modelName); @@ -6442,6 +6575,7 @@ SNLDesign* constructVHDLRTL(NLLibrary* library, const vhdl::DesignFile& syntax, } auto* design = SNLDesign::create(owner, NLName(modelName)); created.push_back(design); + SNLHDLSpecialization::annotate(design, key(entity->name), parameters); sourceMap.annotate(design, entity->span, true); sourceMap.annotate(design, architecture->span); RTLConstructor constructor(design, *entity, *architecture, syntax, context, overrides, build); diff --git a/test/najaeda/test_najaeda_determinism.py b/test/najaeda/test_najaeda_determinism.py index c70dc3934..be5d1e683 100644 --- a/test/najaeda/test_najaeda_determinism.py +++ b/test/najaeda/test_najaeda_determinism.py @@ -234,8 +234,13 @@ def worker(kind, source, output, run): universe = naja.NLUniverse.create() db = naja.NLDB.create(universe) universe.setTopDB(db) - if kind in ("sv", "sv_timing", "sv_resets"): - db.loadSystemVerilog([source], diagnostics_report_path=None) + if kind in ("sv", "sv_timing", "sv_resets", "sv_top", "sv_recursive_top"): + options = None + if kind == "sv_top": + options = {"slang": ["-GWIDTH=5"]} + elif kind == "sv_recursive_top": + options = {"slang": ["--top=top", "-GN=2"]} + db.loadSystemVerilog([source], diagnostics_report_path=None, frontend_options=options) elif kind == "v": db.loadGateLevelVerilog([source]) from najaeda import naja @@ -310,7 +315,7 @@ def check_determinism(self, kind, source, files=None): self.assertGreaterEqual(runs, 5, "determinism requires at least five fresh processes") with tempfile.TemporaryDirectory(dir=os.environ.get("NAJAEDA_TEST_PATH")) as directory: directory = Path(directory) - source_path = directory / ("source." + ("sv" if kind in ("sv_timing", "sv_resets") else kind)) + source_path = directory / ("source." + ("sv" if kind in ("sv_timing", "sv_resets", "sv_top", "sv_recursive_top") else kind)) for name, contents in (files or {}).items(): (directory / name).write_text(contents, encoding="utf-8") source_path.write_text(source.replace("__DATA_DIRECTORY__", str(directory)), encoding="utf-8") @@ -1038,6 +1043,64 @@ def test_timing_shared_models_across_hierarchy_levels(self): branch u1(a[5:3], b[5:3], y[5:3]); branch u2(a[8:6], b[8:6], y[8:6]); endmodule +""") + + def test_selected_top_name_with_parameter_override(self): + self.check_determinism("sv_top", """ +module tile #(parameter int WIDTH=3)(input [WIDTH-1:0] a,output [WIDTH-1:0] y); + assign y=a; +endmodule +module top #(parameter int WIDTH=3)(input [WIDTH-1:0] a,output [WIDTH-1:0] y); + tile #(.WIDTH(WIDTH)) only_child(a,y); +endmodule +""") + + def test_selected_top_name_in_finite_recursive_hierarchy(self): + self.check_determinism("sv_recursive_top", """ +module top #(parameter int N=0)(input a,output y); + if(N>0) begin:branch + top #(.N(N-1)) inner(a,y); + end else assign y=a; +endmodule +""") + + def test_overridden_unevaluable_vhdl_defaults(self): + self.check_determinism("vhd", """ +entity tile is generic(divisor:integer:=0;width:positive:=12/divisor;epsilon:real:=1.0e-320); + port(a:in bit_vector(width-1 downto 0);y:out bit_vector(width-1 downto 0));end; +architecture rtl of tile is begin y<=a;end; +entity top is port(a:in bit_vector(3 downto 0);y,z:out bit_vector(3 downto 0));end; +architecture rtl of top is begin + first:entity work.tile generic map(divisor=>3) port map(a,y); + second:entity work.tile generic map(divisor=>3,width=>4) port map(a,z); +end; +""") + + def test_elaborated_specialization_identity(self): + self.check_determinism("sv", """ +module tile #(parameter int SIZE=3, parameter logic[255:0] MASK=0, + parameter real RATE=1.0, parameter string LABEL="base", parameter bit EN=0)(input a,output y); + assign y=a; +endmodule +module top(input a,output [3:0] y); + tile #(.SIZE(5), .RATE(2.5), .LABEL("other-core"), .EN(1)) first(a,y[0]); + tile implicit_default(a,y[1]); + tile #(.SIZE(3)) explicit_default(a,y[2]); + tile #(.MASK(256'h123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0)) wide(a,y[3]); +endmodule +""") + self.check_determinism("vhd", """ +entity tile is generic(size:integer:=3;mask:bit_vector(255 downto 0):=(others=>'0'); + rate:real:=1.0;label_value:string:="base";en:boolean:=false); + port(a:in bit;y:out bit);end; +architecture rtl of tile is begin y<=a;end; +entity top is port(a:in bit;y:out bit_vector(3 downto 0));end; +architecture rtl of top is begin + first:entity work.tile generic map(size=>5,rate=>2.5,label_value=>"other-core",en=>true) port map(a,y(0)); + implicit_default:entity work.tile port map(a,y(1)); + explicit_default:entity work.tile generic map(size=>3) port map(a,y(2)); + wide:entity work.tile generic map(mask=>x"123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0") port map(a,y(3)); +end; """) def test_systemverilog_interfaces(self): diff --git a/test/najaeda/test_najaeda_vhdl_intent.py b/test/najaeda/test_najaeda_vhdl_intent.py index 8b0082233..450af26b7 100644 --- a/test/najaeda/test_najaeda_vhdl_intent.py +++ b/test/najaeda/test_najaeda_vhdl_intent.py @@ -360,6 +360,9 @@ def test_overridden_unevaluable_scalar_defaults(self): self.assertTrue(generic["overridden"]) self.assertEqual("unavailable", generic["default_value_status"]) self.assertNotIn("default_value", generic) + model = top.getInstance("child").getModel() + self.assertEqual("defaults_leaf__n_2", model.getName()) + self.assertEqual("2", model.getParameter("n").getValue()) def test_required_generic_has_no_default_expression(self): path = self.path("required_generic.vhd", """ diff --git a/test/nl/formats/systemverilog/frontend/SNLSVConstructorTestElab.cpp b/test/nl/formats/systemverilog/frontend/SNLSVConstructorTestElab.cpp index 379e57cf3..1e58c623b 100644 --- a/test/nl/formats/systemverilog/frontend/SNLSVConstructorTestElab.cpp +++ b/test/nl/formats/systemverilog/frontend/SNLSVConstructorTestElab.cpp @@ -46,7 +46,7 @@ TEST_F(SNLSVConstructorTestElab, elaborateParameterizedPorts) { std::filesystem::path benchmarksPath(SNL_SV_BENCHMARKS_PATH); constructor.construct(benchmarksPath/"param_inst"/"param_inst.sv"); - auto leaf = library_->getSNLDesign(NLName("leaf")); + auto leaf = library_->getSNLDesign(NLName("leaf__W_4")); auto top = library_->getSNLDesign(NLName("top")); ASSERT_NE(leaf, nullptr); ASSERT_NE(top, nullptr); @@ -102,8 +102,11 @@ TEST_F(SNLSVConstructorTestElab, elaborateInstanceArrays) { auto leaf = library_->getSNLDesign(NLName("instance_array_leaf")); auto interfaceModel = library_->getSNLDesign(NLName("instance_array_if")); - auto sink = library_->getSNLDesign(NLName("instance_array_sink")); auto top = library_->getSNLDesign(NLName("instance_arrays_top")); + ASSERT_NE(top, nullptr); + auto* sinkInstance = top->getInstance(NLName("instance_arrays_top_gen_interfaces_0_sink")); + ASSERT_NE(sinkInstance, nullptr); + auto* sink = sinkInstance->getModel(); ASSERT_NE(leaf, nullptr); ASSERT_NE(interfaceModel, nullptr); ASSERT_NE(sink, nullptr); diff --git a/test/nl/formats/systemverilog/frontend/SNLSVConstructorTestSimple.cpp b/test/nl/formats/systemverilog/frontend/SNLSVConstructorTestSimple.cpp index 75a6d77b0..5f6322c2b 100644 --- a/test/nl/formats/systemverilog/frontend/SNLSVConstructorTestSimple.cpp +++ b/test/nl/formats/systemverilog/frontend/SNLSVConstructorTestSimple.cpp @@ -1657,9 +1657,9 @@ TEST_F(SNLSVConstructorTestSimple, parseDistinctParameterizedInstanceBodiesUseDi ASSERT_NE(u2Model, nullptr); ASSERT_NE(u4Model, nullptr); EXPECT_NE(u2Model, u4Model); - EXPECT_EQ(std::string("leaf"), u2Model->getName().getString()); + EXPECT_EQ(std::string("leaf__W_2"), u2Model->getName().getString()); EXPECT_NE(std::string("leaf"), u4Model->getName().getString()); - EXPECT_EQ(u2Model, library_->getSNLDesign(NLName("leaf"))); + EXPECT_EQ(u2Model, library_->getSNLDesign(NLName("leaf__W_2"))); auto* u2A = u2Model->getBusTerm(NLName("a")); auto* u2Y = u2Model->getBusTerm(NLName("y")); @@ -8432,6 +8432,9 @@ TEST_F(SNLSVConstructorTestSimple, rejectStaticArrayFunctionState) { assign values = retain(a); assign y = values[1]; endmodule)"); + auto* db = library_->getDB(); + library_->destroy(); + library_ = NLLibrary::create(db, NLName("SVLIB")); SNLSVConstructor constructor(library_); expectUnsupportedConstruct(constructor, path, {"Unsupported RHS in continuous assign", "Call"}); } @@ -8447,6 +8450,9 @@ TEST_F(SNLSVConstructorTestSimple, rejectConstantFunctionUnsupportedSignatures) "function automatic logic [3:0] outer(input real v=1.5); return int'(v); endfunction\n"}) { const auto path = writeSVTestFile("unsupported_constant_call", "module top(output wire [3:0] y);\n" + body + "assign y = outer(); endmodule\n"); + auto* db = library_->getDB(); + library_->destroy(); + library_ = NLLibrary::create(db, NLName("SVLIB")); SNLSVConstructor constructor(library_); expectUnsupportedConstruct(constructor, path, {"Unsupported RHS in continuous assign", "Call"}); } @@ -11791,11 +11797,10 @@ endmodule ASSERT_NE(yNet, nullptr); EXPECT_EQ(3, yNet->getWidth()); - auto child = library_->getSNLDesign(NLName("shift_reg")); - ASSERT_NE(child, nullptr); auto inst = top->getInstance(NLName("i_pipe_reg_load")); ASSERT_NE(inst, nullptr); - EXPECT_EQ(child, inst->getModel()); + ASSERT_NE(inst->getModel(), nullptr); + EXPECT_EQ(3, inst->getModel()->getBusTerm(NLName("d_i"))->getWidth()); } TEST_F(SNLSVConstructorTestSimple, parseInstanceConnectionOutputElementSelectSupported) { @@ -12225,9 +12230,10 @@ endmodule auto top = library_->getSNLDesign( NLName("interface_modport_lazy_flattened_connection_supported")); - auto child = library_->getSNLDesign( - NLName("interface_modport_lazy_flattened_connection_child")); ASSERT_NE(top, nullptr); + auto* instance = top->getInstance(NLName("u_child")); + ASSERT_NE(instance, nullptr); + auto* child = instance->getModel(); ASSERT_NE(child, nullptr); EXPECT_NE(child->getTerm(NLName("bus__sig")), nullptr); EXPECT_NE(child->getTerm(NLName("bus__data")), nullptr); diff --git a/test/nl/formats/systemverilog/frontend/SNLSVIntentTest.cpp b/test/nl/formats/systemverilog/frontend/SNLSVIntentTest.cpp index 0afe42b44..d0b40313f 100644 --- a/test/nl/formats/systemverilog/frontend/SNLSVIntentTest.cpp +++ b/test/nl/formats/systemverilog/frontend/SNLSVIntentTest.cpp @@ -371,7 +371,7 @@ TEST_F(SNLSVIntentTest, returnsParametersAndPackageMembers) { ASSERT_TRUE(voidType.valid); EXPECT_EQ("void", voidType.canonicalKind); - auto* child = findInstanceByModel(top, "intent_child"); + auto* child = top->getInstance(NLName("u_child")); ASSERT_NE(nullptr, child); const auto childParams = SNLSVIntent::parametersOf(child); ASSERT_TRUE(childParams.valid); diff --git a/test/nl/formats/vhdl/VHDLConstructorTest.cpp b/test/nl/formats/vhdl/VHDLConstructorTest.cpp index 3964c4f7e..4a906ff68 100644 --- a/test/nl/formats/vhdl/VHDLConstructorTest.cpp +++ b/test/nl/formats/vhdl/VHDLConstructorTest.cpp @@ -17,8 +17,10 @@ #include "SNLInstance.h" #include "SNLEquipotential.h" #include "SNLInstParameter.h" +#include "SNLParameter.h" #include "SNLInstTerm.h" #include "SNLRTLPrimitives.h" +#include "SNLHDLSpecialization.h" #include "SNLRTLInfos.h" #include "SNLVRLDumper.h" #include "SNLScalarTerm.h" @@ -29,6 +31,7 @@ #include #include +#include #include #include #include @@ -5964,8 +5967,8 @@ end; ASSERT_NE(first, nullptr); ASSERT_NE(second, nullptr); EXPECT_NE(first->getModel(), second->getModel()); - EXPECT_EQ(first->getModel()->getName(), NLName("leaf_extra_1_m_3_n_3")); - EXPECT_EQ(second->getModel()->getName(), NLName("leaf_extra_2_m_3_n_3")); + EXPECT_EQ(first->getModel()->getName(), NLName("leaf__n_3__m_3__extra_1")); + EXPECT_EQ(second->getModel()->getName(), NLName("leaf__n_3__m_3__extra_2")); EXPECT_EQ(first->getModel()->getBusTerm(NLName("a"))->getWidth(), 3); EXPECT_EQ(second->getModel()->getBusTerm(NLName("y"))->getWidth(), 3); } @@ -5986,7 +5989,7 @@ end; EXPECT_THROW(VHDLConstructor(library_).construct(prefix, "top"), NLException); EXPECT_EQ(library_->getSNLDesigns().size(), 1); EXPECT_EQ(library_->getSNLDesign(NLName("blocked")), existing); - EXPECT_EQ(library_->getSNLDesign(NLName("leaf_n_3")), nullptr); + EXPECT_EQ(library_->getSNLDesign(NLName("leaf__n_3")), nullptr); EXPECT_EQ(library_->getSNLDesign(NLName("top")), nullptr); try { VHDLConstructor(library_).construct(R"( @@ -5994,12 +5997,12 @@ entity grouped is generic(n, m : positive := 2); port(a : in bit; y : out bit); architecture rtl of grouped is begin y <= a; end; entity top is port(a : in bit; y : out bit); end; architecture rtl of top is begin - u: entity work.grouped generic map(2, 3) port map(a, y); + u: entity work.grouped generic map(2, 0) port map(a, y); end; )", "top"); - FAIL() << "expected grouped generic rejection"; + FAIL() << "expected invalid positive generic rejection"; } catch (const NLException& error) { - EXPECT_NE(std::string(error.what()).find("grouped generics with different actual values"), + EXPECT_NE(std::string(error.what()).find("generic value violates its subtype"), std::string::npos) << error.what(); } EXPECT_EQ(library_->getSNLDesigns().size(), 1); @@ -7814,7 +7817,7 @@ TEST_F(VHDLConstructorTest, StringGenericAttributesAndOrderingAreStatic) { TEST_F(VHDLConstructorTest, RTLValidationDiagnosticsRollBackDesigns) { library_->setName(NLName("design")); const std::vector> cases{ - {"entity bad is generic(v : bit := '0'); end; architecture rtl of bad is begin end;", + {"entity bad is generic(v : time := 1); end; architecture rtl of bad is begin end;", "RTL generics require"}, {"entity bad is generic(v : string := 7); end; architecture rtl of bad is begin end;", "string generic actual must be a static string"}, @@ -8581,3 +8584,155 @@ TEST_F(VHDLConstructorTest, NullArrayReadsRejectBeforeComputingElementStrides) { EXPECT_TRUE(library_->getSNLDesigns().empty()); } } + +TEST_F(VHDLConstructorTest, SharedSpecializationDigestCollisionsPromoteBothNames) { + // These independent integer values collide in the first 32 SHA-256 bits of + // the versioned canonical parameter record, but not in the first 64 bits. + const std::vector first{{"tag", "integer:85019", "85019", std::nullopt, false}}; + const std::vector second{{"tag", "integer:135170", "135170", std::nullopt, false}}; + auto* a = SNLDesign::create(library_, NLName(SNLHDLSpecialization::name(library_, "cell", first, {}))); + SNLHDLSpecialization::annotate(a, "cell", first); + EXPECT_EQ(a->getName().getString(), "cell__hc4c28cf5"); + const auto secondName = SNLHDLSpecialization::name(library_, "cell", second, {}); + EXPECT_EQ(secondName, "cell__hc4c28cf596ab9078"); + EXPECT_EQ(a->getName().getString(), "cell__hc4c28cf51c2efecd"); + auto* b = SNLDesign::create(library_, NLName(secondName)); + SNLHDLSpecialization::annotate(b, "cell", second); + EXPECT_EQ(SNLHDLSpecialization::name(library_, "cell", first, {}), a->getName().getString()); + EXPECT_EQ(SNLHDLSpecialization::name(library_, "cell", second, {}), b->getName().getString()); + EXPECT_EQ(SNLHDLSpecialization::attribute(a, "naja.source_module"), "cell"); + EXPECT_TRUE(SNLHDLSpecialization::isElaborated(a)); + a->destroy(); + b->destroy(); + // Reversing discovery order gives the same final names. + b = SNLDesign::create(library_, NLName(SNLHDLSpecialization::name(library_, "cell", second, {}))); + SNLHDLSpecialization::annotate(b, "cell", second); + EXPECT_EQ(SNLHDLSpecialization::name(library_, "cell", first, {}), "cell__hc4c28cf51c2efecd"); + EXPECT_EQ(b->getName().getString(), "cell__hc4c28cf596ab9078"); +} + +TEST_F(VHDLConstructorTest, SharedSpecializationPolicyFormatsAndRejectsCollisions) { + EXPECT_EQ(SNLHDLSpecialization::integerValue("-1.5e-8"), "n1p5en8"); + EXPECT_EQ(SNLHDLSpecialization::bitValue("00001"), "h01"); + EXPECT_EQ(SNLHDLSpecialization::bitValue("1"), "h1"); + EXPECT_EQ(SNLHDLSpecialization::bitValue("1", true), "1"); + EXPECT_EQ(SNLHDLSpecialization::bitValue("01-XU"), "b01-xu"); + const std::vector values{{"mode", "enumeration:fast", "fast", "fast", false}}; + EXPECT_EQ(SNLHDLSpecialization::name(library_, "cell", values, {}, {}, true), "cell"); + EXPECT_EQ(SNLHDLSpecialization::name(library_, "cell", values, {}), "cell__mode_fast"); + const auto hashed = SNLHDLSpecialization::name(library_, "cell", values, {"cell__mode_fast"}); + EXPECT_EQ(hashed.find("cell__h"), 0); + SNLDesign::create(library_, NLName(hashed)); + EXPECT_THROW(SNLHDLSpecialization::name(library_, "cell", values, {"cell__mode_fast"}), NLException); + // Non-identifier logic states are represented in identity, never emitted in + // an unsafe readable name. Frontends still own value-domain validation. + const std::vector unknown{{"mask", "logic:01-XU", "\"01-XU\"", "b01-xu", false}}; + EXPECT_EQ(SNLHDLSpecialization::name(library_, "other", unknown, {}).find("other__h"), 0); +} + +TEST_F(VHDLConstructorTest, RealGenericLiteralsPreserveRangeAndIgnoreGlobalLocale) { + struct CommaDecimalPoint : std::numpunct { + char do_decimal_point() const override { return ','; } + }; + struct RestoreLocale { + std::locale previous = std::locale(); + ~RestoreLocale() { std::locale::global(previous); } + } restoreLocale; + std::locale::global(std::locale(std::locale::classic(), new CommaDecimalPoint)); + const auto source = [](const std::string& value) { + return "entity probe is generic(rate:real:=" + value + ");end;" + "architecture rtl of probe is begin end;"; + }; + for (const auto& [literal, expected] : std::vector>{ + {"1.2_5", "1.25"}, {"1.25e+2", "125.0"}, {"-1.25E-2", "-0.0125"}, + {"0.0e-999", "0.0"}, {"0.000_00e-999", "0.0"}, {"0.0e999", "0.0"}, {"-0.0", "0.0"}, + {"4.9406564584124654e-324", "5.0e-324"}, {"1.0e-320", "1.0e-320"}, + {"2.2250738585072014e-308", "2.2250738585072014e-308"}, + {"1.7976931348623157e308", "1.7976931348623157e+308"}}) { + SCOPED_TRACE(literal); + auto* design = VHDLConstructor(library_).construct(source(literal), "probe"); + ASSERT_NE(design, nullptr); + auto* parameter = design->getParameter(NLName("rate")); + ASSERT_NE(parameter, nullptr); + EXPECT_EQ(parameter->getValue(), expected); + design->destroy(); + } + for (const auto& literal : {"1.0e309", "-1.0e309", "1.0e-999", "-1.0e-999", "0.000_01e-999", "16#1.8#"}) { + SCOPED_TRACE(literal); + try { + VHDLConstructor(library_).construct(source(literal), "probe"); + FAIL() << "expected invalid or out-of-range real literal rejection"; + } catch (const NLException& error) { + EXPECT_NE(std::string(error.what()).find("unsupported real generic literal"), std::string::npos) + << error.what(); + } + EXPECT_TRUE(library_->getSNLDesigns().empty()); + } +} + +TEST_F(VHDLConstructorTest, SpecializationNamesDoNotRequireUnusedDefaultsToElaborate) { + for (const auto& [type, defaultExpression, actual] : + std::vector>{ + {"integer", "-(1 / 0)", "2"}, + {"boolean", "(1 / 0) = 0", "true"}, + {"real", "1.0 / 0.0", "2.5"}}) { + SCOPED_TRACE(type); + const auto declarations = "entity cell is generic(value:" + type + ":=" + defaultExpression + + ");port(y:out bit);end;architecture rtl of cell is begin y<='1';end;"; + const auto source = declarations + "entity top is port(y,z:out bit);end;" + "architecture rtl of top is begin " + "first:entity work.cell generic map(value=>" + actual + ") port map(y);" + "second:entity work.cell generic map(value=>" + actual + ") port map(z);end;"; + auto* top = VHDLConstructor(library_).construct(source, "top"); + ASSERT_NE(top, nullptr); + auto* first = top->getInstance(NLName("first"))->getModel(); + EXPECT_EQ(first, top->getInstance(NLName("second"))->getModel()); + EXPECT_EQ(first->getParameter(NLName("value"))->getValue(), actual); + EXPECT_TRUE(assignSource(first->getScalarTerm(NLName("y"))->getNet())->isConstant1()); + top->destroy(); + first->destroy(); + // An invalid default actually selected for elaboration must still fail. + try { + VHDLConstructor(library_).construct(declarations, "cell"); + FAIL() << "expected the selected invalid default to fail"; + } catch (const NLException& error) { + EXPECT_NE(std::string(error.what()).find("division by zero"), std::string::npos) << error.what(); + } + EXPECT_TRUE(library_->getSNLDesigns().empty()); + } +} + +TEST_F(VHDLConstructorTest, CounterfactualDefaultsDoNotOverrideResolvedDependentValues) { + const std::string declarations = R"( +entity cell is generic(divisor:integer:=0;width:positive:=12/divisor); + port(a:in bit_vector(width-1 downto 0);y:out bit_vector(width-1 downto 0));end; +architecture rtl of cell is begin y<=a;end; +)"; + auto* top = VHDLConstructor(library_).construct(declarations + R"( +entity top is port(a:in bit_vector(3 downto 0);y,z:out bit_vector(3 downto 0));end; +architecture rtl of top is begin + first:entity work.cell generic map(divisor=>3) port map(a,y); + second:entity work.cell generic map(divisor=>3,width=>4) port map(a,z); +end; +)", "top"); + ASSERT_NE(top, nullptr); + auto* model = top->getInstance(NLName("first"))->getModel(); + EXPECT_EQ(model, top->getInstance(NLName("second"))->getModel()); + EXPECT_EQ(model->getParameter(NLName("divisor"))->getValue(), "3"); + EXPECT_EQ(model->getParameter(NLName("width"))->getValue(), "4"); + EXPECT_EQ(model->getBusTerm(NLName("y"))->getWidth(), 4); + top->destroy(); + model->destroy(); + try { + VHDLConstructor(library_).construct(declarations + R"( +entity top is port(a:in bit_vector(3 downto 0);y:out bit_vector(3 downto 0));end; +architecture rtl of top is begin + invalid_actual:entity work.cell generic map(divisor=>1/0) port map(a,y); +end; +)", "top"); + FAIL() << "expected the invalid actual value to fail"; + } catch (const NLException& error) { + EXPECT_NE(std::string(error.what()).find("division by zero"), std::string::npos) << error.what(); + } + EXPECT_TRUE(library_->getSNLDesigns().empty()); +} diff --git a/test/nl/python/naja_wrapping/test_nldb.py b/test/nl/python/naja_wrapping/test_nldb.py index 0eb2ca032..4ecb1652c 100644 --- a/test/nl/python/naja_wrapping/test_nldb.py +++ b/test/nl/python/naja_wrapping/test_nldb.py @@ -56,6 +56,329 @@ """ class SNLDBTest(unittest.TestCase): + def _load_specializations(self, language, source, reserved=None, **sv_options): + if naja.NLUniverse.get(): + naja.NLUniverse.get().destroy() + universe = naja.NLUniverse.create() + db = naja.NLDB.create(universe) + if reserved: + library = naja.NLLibrary.create(db, "DESIGN") + naja.SNLDesign.create(library, reserved) + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "synthetic." + language) + with open(path, "w") as stream: + stream.write(source) + if language == "sv": + top = db.loadSystemVerilog([path], diagnostics_report_path=None, **sv_options) + else: + top = db.loadVHDL([path], top="top") + return db, top + + def test_selected_top_retains_source_name_with_parameter_overrides(self): + source = """ +module tile #(parameter int WIDTH=3)(input [WIDTH-1:0] a,output [WIDTH-1:0] y); + assign y=a; +endmodule +module top #(parameter int WIDTH=3, parameter logic [255:0] MASK=0) + (input [WIDTH-1:0] a,output [WIDTH-1:0] y); + tile #(.WIDTH(WIDTH)) only_child(a,y); +endmodule +""" + wide = "256'h" + "123456789ABCDEF0" * 4 + for options, width in (([], 3), (["-GWIDTH=5"], 5), + (["-GWIDTH=5", "-GMASK=" + wide], 5)): + with self.subTest(options=options): + db, top = self._load_specializations( + "sv", source, frontend_options={"slang": ["--top=top", *options]}) + self.assertEqual("top", top.getName()) + self.assertEqual(str(width), top.getParameter("WIDTH").getValue()) + self.assertEqual(width, top.getBusTerm("a").getWidth()) + self.assertEqual("top", dict((a.getName(),a.getValue()) for a in top.getAttributes())["naja.source_module"]) + child = top.getInstance("only_child").getModel() + self.assertEqual("tile" if width == 3 else "tile__WIDTH_5", child.getName()) + if len(options) == 2: + self.assertEqual(wide, top.getParameter("MASK").getValue()) + with tempfile.TemporaryDirectory() as directory: + top.dumpGateLevelVerilog(directory, "netlist.v") + with open(os.path.join(directory, "netlist.v")) as stream: + dumped = stream.read() + self.assertRegex(dumped, r"(?m)^module top\(") + self.assertNotIn("module top__", dumped) + snapshot = os.path.join(directory, "snapshot") + db.dumpNajaIF(snapshot) + naja.NLUniverse.get().destroy() + naja.NLUniverse.create() + restored = naja.NLDB.loadNajaIF(snapshot).getTopDesign() + self.assertEqual("top", restored.getName()) + self.assertEqual(str(width), restored.getParameter("WIDTH").getValue()) + self.assertEqual("tile" if width == 3 else "tile__WIDTH_5", + restored.getInstance("only_child").getModel().getName()) + + def test_selected_top_reserves_source_name_in_finite_recursive_hierarchy(self): + source = """ +module top #(parameter int N=0)(input a,output y); + if(N>0) begin:branch + top #(.N(N-1)) inner(a,y); + end else assign y=a; +endmodule +""" + _, top = self._load_specializations( + "sv", source, frontend_options={"slang": ["--top=top", "-GN=2"]}) + self.assertEqual("top", top.getName()) + child = next(iter(top.getNonPrimitiveInstances())).getModel() + self.assertEqual("top__N_1", child.getName()) + default_child = next(iter(child.getNonPrimitiveInstances())).getModel() + self.assertEqual("0", default_child.getParameter("N").getValue()) + self.assertRegex(default_child.getName(), r"^top__h[0-9a-f]{8}$") + self.assertEqual(0, len(list(default_child.getNonPrimitiveInstances()))) + + def test_elaborated_specializations_share_names_and_values(self): + sources = { + "sv": (""" +module tile #(parameter int COUNT=3, parameter logic [15:0] MASK=0, + parameter bit ACTIVE=0)(input logic a, output logic y); + assign y=a; +endmodule +module top(input logic a, output wire y); + tile #(.COUNT(6), .MASK(16'hA590), .ACTIVE(1)) first(a,y); + tile #(.COUNT(6), .MASK(16'h1830), .ACTIVE(1)) second(a,); + tile implicit_default(a,); + tile #(.COUNT(6), .MASK(16'hA590), .ACTIVE(1)) repeated(a,); + tile #(.COUNT(3)) explicit_default(a,); +endmodule +""", "COUNT_6__MASK_hA590__ACTIVE_1", { + "COUNT": "6", "MASK": "16'hA590", "ACTIVE": "1'b1"}), + "vhd": (""" +library ieee; use ieee.std_logic_1164.all; +entity tile is generic(COUNT:integer:=3; + MASK:std_ulogic_vector(15 downto 0):=(others=>'0'); ACTIVE:boolean:=false); + port(a:in bit;y:out bit);end; +architecture rtl of tile is begin y<=a;end; +entity top is port(a:in bit;y:out bit);end; +architecture rtl of top is begin + first:entity work.tile generic map(6,x"A590",true) port map(a,y); + second:entity work.tile generic map(6,x"1830",true) port map(a,open); + implicit_default:entity work.tile port map(a,open); + repeated:entity work.tile generic map(6,x"A590",true) port map(a,open); + explicit_default:entity work.tile generic map(COUNT=>3) port map(a,open); +end; +""", "count_6__mask_hA590__active_true", { + "count": "6", "mask": 'x"A590"', "active": "true"}), + } + for language, (source, suffix, expected) in sources.items(): + with self.subTest(language=language): + db, top = self._load_specializations(language, source) + models = {inst.getName(): inst.getModel() for inst in top.getInstances()} + self.assertEqual("tile__" + suffix, models["first"].getName()) + self.assertEqual(models["first"], models["repeated"]) + self.assertEqual(models["implicit_default"], models["explicit_default"]) + self.assertEqual("tile", models["implicit_default"].getName()) + self.assertNotEqual(models["first"], models["second"]) + self.assertEqual(expected, {p.getName(): p.getValue() for p in models["first"].getParameters()}) + self.assertEqual("tile", dict((a.getName(), a.getValue()) for a in models["first"].getAttributes())["naja.source_module"]) + names = {key: model.getName() for key, model in models.items()} + with tempfile.TemporaryDirectory() as directory: + top.dumpGateLevelVerilog(directory, "netlist.v") + with open(os.path.join(directory, "netlist.v")) as stream: + dumped = stream.read() + self.assertIn("module tile__" + suffix, dumped) + self.assertNotIn("parameter ", dumped) + snapshot = os.path.join(directory, "snapshot") + db.dumpNajaIF(snapshot) + naja.NLUniverse.get().destroy() + naja.NLUniverse.create() + reloaded = naja.NLDB.loadNajaIF(snapshot) + model = next(d for lib in reloaded.getLibraries() for d in lib.getSNLDesigns() + if d.getName() == names["first"]) + self.assertEqual(expected, {p.getName():p.getValue() for p in model.getParameters()}) + self.assertEqual("tile", dict((a.getName(),a.getValue()) for a in model.getAttributes())["naja.source_module"]) + # Moving the default instance first must not rename any specialization. + lines = source.splitlines() + first = next(i for i,line in enumerate(lines) if "first" in line) + default = next(i for i,line in enumerate(lines) if "implicit_default" in line) + lines[first], lines[default] = lines[default], lines[first] + _, reordered = self._load_specializations(language, "\n".join(lines)) + self.assertEqual(names, {inst.getName():inst.getModel().getName() for inst in reordered.getInstances()}) + + def test_elaborated_specialization_hash_generate_and_collision(self): + sources = { + "sv": """ +module tile #(parameter int N=0)(input a, output y);assign y=a;endmodule +module tile__N_2(input a, output y);assign y=~a;endmodule +module wide #(parameter logic [255:0] MASK=0)(input a, output y);assign y=a;endmodule +module top(input a, output [4:0] y); + for(genvar i=0;i<3;i++) begin:lanes tile #(.N(i)) u(a,y[i]);end + tile__N_2 user_name(a,y[3]); + wide #(.MASK(256'h123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0)) hashed(a,y[4]); +endmodule +""", + "vhd": """ +entity tile is generic(n:integer:=0);port(a:in bit;y:out bit);end; +architecture rtl of tile is begin y<=a;end; +entity tile__n_2 is port(a:in bit;y:out bit);end; +architecture rtl of tile__n_2 is begin y<=not a;end; +entity wide is generic(mask:bit_vector(255 downto 0):=(others=>'0'));port(a:in bit;y:out bit);end; +architecture rtl of wide is begin y<=a;end; +entity top is port(a:in bit;y:out bit_vector(4 downto 0));end; +architecture rtl of top is begin + lanes:for i in 0 to 2 generate u:entity work.tile generic map(i) port map(a,y(i));end generate; + user_name:entity work.tile__n_2 port map(a,y(3)); + hashed:entity work.wide generic map(x"123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0") port map(a,y(4)); +end; +"""} + for language, source in sources.items(): + with self.subTest(language=language): + # VHDL basic identifiers cannot contain adjacent underscores. Reserve + # the generated spelling through the netlist API for this frontend. + if language == "vhd": + source = source.replace("entity tile__n_2 is port(a:in bit;y:out bit);end;", "") + source = source.replace("architecture rtl of tile__n_2 is begin y<=not a;end;", "") + source = source.replace("user_name:entity work.tile__n_2 port map(a,y(3));", "y(3)<=a;") + reserved = "tile__n_2" if language == "vhd" else None + _, top = self._load_specializations(language, source, reserved) + models = {inst.getName():inst.getModel() for inst in top.getInstances()} + hashed = models["hashed"].getName() + self.assertRegex(hashed, r"^wide__h[0-9a-f]{8}$") + lane = (lambda i: "top_lanes_" + str(i) + "_u") if language == "sv" else (lambda i: "lanes[" + str(i) + "].u") + self.assertEqual("tile", models[lane(0)].getName()) + self.assertEqual("tile__" + ("N" if language == "sv" else "n") + "_1", models[lane(1)].getName()) + self.assertRegex(models[lane(2)].getName(), r"^tile__h[0-9a-f]{8}$") + _, repeated = self._load_specializations(language, source, reserved) + self.assertEqual(hashed, repeated.getInstance("hashed").getModel().getName()) + + def test_elaborated_specialization_value_kinds(self): + source = """ +package choices; typedef enum {slow,fast} mode_t; endpackage +module values #(parameter int OFFSET=0, parameter logic [3:0] MASK=0, + parameter string LABEL="base", parameter real RATE=1.0, + parameter choices::mode_t MODE=choices::slow, + parameter type DATA=logic, parameter int TABLE[2]='{1,2})(input a,output y); + assign y=a; +endmodule +module top(input a, output [7:0] y); + values #(.OFFSET(-7)) negative(a,y[0]); + values #(.MASK(4'b1xz0)) unknowns(a,y[1]); + values #(.LABEL("other_core")) text_value(a,y[2]); + values #(.RATE(2.5)) real_value(a,y[3]); + values #(.MODE(choices::fast)) enumeration(a,y[4]); + values #(.DATA(logic[2:0])) type_value(a,y[5]); + values #(.TABLE('{3,4})) array_value(a,y[6]); + values #(.LABEL("other-core")) lossy_string(a,y[7]); +endmodule +""" + _, top = self._load_specializations("sv", source) + models = {i.getName():i.getModel() for i in top.getInstances()} + for instance, suffix in (("negative", "OFFSET_n7"), ("unknowns", "MASK_b1xz0"), + ("text_value", "LABEL_other_core"), ("real_value", "RATE_2p5"), + ("enumeration", "MODE_fast")): + self.assertEqual("values__" + suffix, models[instance].getName()) + for instance in ("type_value", "array_value", "lossy_string"): + self.assertRegex(models[instance].getName(), r"^values__h[0-9a-f]{8}$") + self.assertEqual("4'b1xz0", models["unknowns"].getParameter("MASK").getValue()) + self.assertEqual('"other_core"', models["text_value"].getParameter("LABEL").getValue()) + self.assertEqual("choices::fast", models["enumeration"].getParameter("MODE").getValue()) + source = """ +library ieee;use ieee.std_logic_1164.all; +entity values is generic(offset:integer:=0;mask:std_ulogic_vector(3 downto 0):="0000"; + label_value:string:="base";flag:std_ulogic:='0');port(a:in bit;y:out bit);end; +architecture rtl of values is begin y<=a;end; +entity top is port(a:in bit;y:out bit_vector(4 downto 0));end; +architecture rtl of top is begin + negative:entity work.values generic map(offset=>-7) port map(a,y(0)); + unknowns:entity work.values generic map(mask=>"1XZ0") port map(a,y(1)); + text_value:entity work.values generic map(label_value=>"other_core") port map(a,y(2)); + bit_value:entity work.values generic map(flag=>'1') port map(a,y(3)); + lossy_string:entity work.values generic map(label_value=>"other-core") port map(a,y(4)); +end; +""" + _, top = self._load_specializations("vhd", source) + models = {i.getName():i.getModel() for i in top.getInstances()} + for instance, suffix in (("negative", "offset_n7"), ("unknowns", "mask_b1xz0"), + ("text_value", "label_value_other_core"), ("bit_value", "flag_1")): + self.assertEqual("values__" + suffix, models[instance].getName()) + self.assertRegex(models["lossy_string"].getName(), r"^values__h[0-9a-f]{8}$") + self.assertEqual('"1XZ0"', models["unknowns"].getParameter("mask").getValue()) + source = """ +package choices is type mode_t is (slow,fast);end; +use work.choices.all; +entity values is generic(rate:real:=1.0;mode:mode_t:=slow);port(a:in bit;y:out bit);end; +architecture rtl of values is begin y<=a when mode=fast else not a;end; +use work.choices.all; +entity top is port(a:in bit;y:out bit_vector(2 downto 0));end; +architecture rtl of top is begin + real_value:entity work.values generic map(rate=>2.5) port map(a,y(0)); + computed:entity work.values generic map(rate=>1.25*2.0) port map(a,y(1)); + enumeration:entity work.values generic map(mode=>fast) port map(a,y(2)); +end; +""" + _, top = self._load_specializations("vhd", source) + self.assertEqual("values__rate_2p5", top.getInstance("real_value").getModel().getName()) + self.assertEqual(top.getInstance("real_value").getModel(), top.getInstance("computed").getModel()) + self.assertEqual("values__mode_fast", top.getInstance("enumeration").getModel().getName()) + self.assertEqual("2.5", top.getInstance("real_value").getModel().getParameter("rate").getValue()) + self.assertEqual("fast", top.getInstance("enumeration").getModel().getParameter("mode").getValue()) + # Unsupported std_ulogic values retain an explicit diagnostic. + with self.assertRaisesRegex(RuntimeError, "RTL literals require"): + self._load_specializations("vhd", """ +library ieee;use ieee.std_logic_1164.all; +entity top is generic(mask:std_ulogic_vector(3 downto 0):="1-X0");end; +architecture rtl of top is begin end; +""") + + def test_elaborated_specialization_types_and_string_identity(self): + source = r""" +package choices; + typedef logic [2:0] word_t; + typedef word_t alias_t; + typedef struct packed {logic [2:0] value;} record_t; +endpackage +module tile #(parameter type DATA=logic, parameter logic [2:0] MASK=0, + parameter string LABEL="base")(input a, output y); + assign y=a; +endmodule +module typed_default #(parameter type DATA=choices::record_t)(input a,output y); + assign y=a; +endmodule +module enum_default #(parameter type DATA=enum {idle,busy})(input a,output y); + assign y=a; +endmodule +module top(input a,output [7:0] y); + tile #(.DATA(choices::word_t)) first(a,y[0]); + tile #(.DATA(choices::alias_t)) equivalent(a,y[1]); + tile #(.LABEL("a-b")) punctuation(a,y[2]); + tile #(.LABEL("a b")) space(a,y[3]); + tile #(.MASK(3'b001)) narrow(a,y[4]); + tile #(.LABEL("quote\"line\n\001")) controls(a,y[5]); + typed_default default_record(a,y[6]); + enum_default default_enum(a,y[7]); +endmodule +""" + _, top = self._load_specializations("sv", source) + models = {i.getName():i.getModel() for i in top.getInstances()} + self.assertEqual(models["first"], models["equivalent"]) + self.assertEqual("logic[2:0]", models["first"].getParameter("DATA").getValue()) + self.assertEqual("typed_default", models["default_record"].getName()) + self.assertEqual("enum_default", models["default_enum"].getName()) + self.assertEqual("tile__MASK_h1", models["narrow"].getName()) + self.assertNotEqual(models["punctuation"].getName(), models["space"].getName()) + self.assertEqual(r'"quote\"line\n\001"', models["controls"].getParameter("LABEL").getValue()) + for instance in ("punctuation", "space", "controls"): + self.assertRegex(models[instance].getName(), r"^tile__h[0-9a-f]{8}$") + names = {key:value.getName() for key,value in models.items()} + # Type declaration allocation and specialization discovery must not enter + # canonical identities. Alias spelling must not split a specialization. + reordered = source.replace(" typedef logic [2:0] word_t;", + " typedef logic unrelated_t;\n typedef logic [2:0] word_t;") + lines = reordered.splitlines() + first = next(i for i,line in enumerate(lines) if ")) first" in line) + equivalent = next(i for i,line in enumerate(lines) if ")) equivalent" in line) + punctuation = next(i for i,line in enumerate(lines) if ")) punctuation" in line) + space = next(i for i,line in enumerate(lines) if ")) space" in line) + lines[first], lines[equivalent] = lines[equivalent], lines[first] + lines[punctuation], lines[space] = lines[space], lines[punctuation] + _, top = self._load_specializations("sv", "\n".join(lines)) + self.assertEqual(names, {i.getName():i.getModel().getName() for i in top.getInstances()}) + def test_clock_gate_wrapper_does_not_create_an_extra_root(self): source = '''module phase_cell(input source, request, output result); reg held; diff --git a/thirdparty/sha256/BUILD.bazel b/thirdparty/sha256/BUILD.bazel index 1c11762ed..6fa835311 100644 --- a/thirdparty/sha256/BUILD.bazel +++ b/thirdparty/sha256/BUILD.bazel @@ -8,5 +8,5 @@ cc_library( srcs = ["sha-256.c"], hdrs = ["sha-256.h"], includes = ["."], - visibility = ["//src/nl/netlist:__pkg__"], + visibility = ["//src/nl/netlist:__pkg__", "//src/nl/formats/hdl:__pkg__"], )