From 49d436689f2d6600f3600ca06d864f5dfcbcffaf Mon Sep 17 00:00:00 2001 From: xtof Date: Thu, 19 Nov 2026 15:38:23 +0100 Subject: [PATCH 1/2] Add initial values to primitive sequential models --- src/najaeda/najaeda/docs/source/raw_api.rst | 32 +- src/najaeda/najaeda/primitives/xilinx.py | 3 +- .../netlist/decorators/SNLDesignModeling.cpp | 284 ++++++++++++++++++ src/nl/netlist/decorators/SNLDesignModeling.h | 10 + .../serialization/capnp/SNLCapnPInterface.cpp | 7 + src/nl/python/naja_wrapping/PySNLInstance.cpp | 2 + .../naja_wrapping/PySNLSequentialModel.cpp | 61 ++++ .../naja_wrapping/PySNLSequentialModel.h | 1 + test/najaeda/test_najaeda_determinism.py | 36 +++ .../test_najaeda_netlist_primitives.py | 7 + .../naja_wrapping/test_snldesign_modeling.py | 110 +++++++ .../snl/decorators/SNLDesignModelingTest0.cpp | 42 +++ .../snl/serialization/capnp/SNLCapnPTest0.cpp | 27 ++ 13 files changed, 620 insertions(+), 2 deletions(-) diff --git a/src/najaeda/najaeda/docs/source/raw_api.rst b/src/najaeda/najaeda/docs/source/raw_api.rst index 15f61ce4d..24bd16751 100644 --- a/src/najaeda/najaeda/docs/source/raw_api.rst +++ b/src/najaeda/najaeda/docs/source/raw_api.rst @@ -646,6 +646,36 @@ memory are not represented by that interface. Parameter-dependent sequential models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Each state may optionally specify ``init: 0`` or ``init: 1`` for a power-up +value, or ``init_from: {"parameter": "INIT_VAL", "bit": 0}`` to read a +primitive instance parameter. These fields are mutually exclusive and apply to +both static models and every entry in a parameter-selected model table. The +parameter must already be declared on the primitive; a missing declaration is +an error at model-definition time. The bit index is a nonnegative offset from +the least-significant bit of the value, independent of terminal bounds. + +``instance.getSequentialInitialValues()`` returns one ``0``, ``1``, or ``None`` +per model state, in state order. The C++ equivalent is +``SNLDesignModeling::getSequentialInitialValues(instance)``. An instance override +takes precedence over the design default. Binary (``1'b1``, ``4'b0001``), decimal +(``4'd1``, ``1``), and quoted scalar (``'0'``, ``'1'``) values are accepted. +Unknown ``x``, ``u``, or ``z`` bits, absent defaults/overrides, empty values, and +bits beyond a declared width resolve to ``None`` (free). Known bits of mixed +binary values remain known. Malformed values raise an error. Decimal values can +exceed 64 bits. ``getSequentialModel()`` preserves the original ``init`` or +``init_from`` metadata on read-back; resolution always reads current parameters. +Experts can use this raw API to describe technology primitives directly; no +high-level netlist wrapper is needed for primitive model construction. + +The built-in Xilinx FDCE/FDPE/FDRE/FDSE models declare ``init_from`` using +their ``INIT`` parameters, so direct raw queries honor each default or override. + +Sequential behavior, including these fields and parameter tables, is saved in +a versioned dumpable property and restored by NajaIF in a fresh process. This +preserves expression graphs and state/output order, including complemented +outputs. This payload does not serialize the separately declared timing arcs +or term roles; reload the primitive library when those decorations are needed. + Use ``SNLDesign.setSequentialModelFromParameters(parameters, models)`` when instance parameters select sequential behavior. ``parameters`` is an ordered list of numeric parameter names declared on the primitive. ``models`` is a @@ -791,7 +821,7 @@ semantic source of truth. * - :class:`najaeda.naja.SNLDesign` - ``isClockGate()`` (canonical clock-gate predicate), :meth:`getContentHash `, :meth:`create `, :meth:`createPrimitive `, :meth:`clone `, :meth:`destroy `, :meth:`getName `, :meth:`setName `, :meth:`getDB `, :meth:`getLibrary `, :meth:`getID `, :meth:`getNLID `, :meth:`getRevisionCount `, :meth:`getTerms `, :meth:`getTerm `, :meth:`getTermByID `, :meth:`getScalarTerms `, :meth:`getBusTerms `, :meth:`getBundleTerms `, :meth:`getNets `, :meth:`getNet `, :meth:`getNetByID `, :meth:`getScalarNets `, :meth:`getBusNets `, :meth:`getInstances `, :meth:`getInstance `, :meth:`getInstanceByID `, :meth:`getInstanceByIDList `, :meth:`getParameters `, :meth:`getParameter `, :meth:`addCombinatorialArcs `, :meth:`addInputsToClockArcs `, :meth:`addClockToOutputsArcs `, :meth:`setTimingModelParameter `, :meth:`getCombinatorialInputs `, :meth:`getCombinatorialOutputs `, :meth:`getClockRelatedInputs `, :meth:`getClockRelatedOutputs `, :meth:`getInputRelatedClocks `, :meth:`getOutputRelatedClocks `, :meth:`getClockTerms `, :meth:`getAsyncResetTerms `, :meth:`getAsyncSetTerms `, :meth:`getSyncResetTerms `, :meth:`getSyncSetTerms `, :meth:`getDataInputTerms `, :meth:`getOutputTerms `, :meth:`setTruthTable `, :meth:`setSequentialModel `, :meth:`setSequentialModelFromParameters `, :meth:`setRolesFromParameters `, :meth:`hasRolesFromParameters `, :meth:`hasSequentialModel `, :meth:`hasSequentialModelFromParameters `, :meth:`getSequentialModel `, :meth:`hasMemoryInterface `, :meth:`getMemoryInterface `, :meth:`setTruthTableFromParameter `, :meth:`setTruthTables `, :meth:`getTruthTable `, :meth:`getTruthTableByOutputID `, :meth:`isConst0 `, :meth:`isConst1 `, :meth:`isConst `, :meth:`isBuf `, :meth:`isInv `, :meth:`isAnd `, :meth:`isNand `, :meth:`isOr `, :meth:`isNor `, :meth:`isXor `, :meth:`isXnor `, :meth:`isMux `, :meth:`isAddSub `, :meth:`isSubtract `, :meth:`isMultiply `, :meth:`isShift `, :meth:`isDivMod `, :meth:`isShiftRight `, :meth:`isShiftArithmetic `, :meth:`dumpGateLevelVerilog `, :meth:`dumpVerilog (compatibility alias) `, :meth:`dumpFullDotFile `, :meth:`dumpContextDotFile `, :meth:`getClocks ` * - :class:`najaeda.naja.SNLInstance` - - :meth:`getContentHash `, :meth:`create `, :meth:`destroy `, :meth:`getName `, :meth:`setName `, :meth:`getID `, :meth:`getNLID `, :meth:`getDesign `, :meth:`getModel `, :meth:`getSequentialModel `, :meth:`getMemoryInterface `, :meth:`getInstTerm `, :meth:`getInstTerms `, :meth:`getInstParameter `, :meth:`getInstParameters `, :meth:`getCombinatorialInputs `, :meth:`getCombinatorialOutputs `, :meth:`getClockRelatedInputs `, :meth:`getClockRelatedOutputs `, :meth:`getInputRelatedClocks `, :meth:`getOutputRelatedClocks ` + - :meth:`getContentHash `, :meth:`create `, :meth:`destroy `, :meth:`getName `, :meth:`setName `, :meth:`getID `, :meth:`getNLID `, :meth:`getDesign `, :meth:`getModel `, :meth:`getSequentialModel `, :meth:`getSequentialInitialValues `, :meth:`getMemoryInterface `, :meth:`getInstTerm `, :meth:`getInstTerms `, :meth:`getInstParameter `, :meth:`getInstParameters `, :meth:`getCombinatorialInputs `, :meth:`getCombinatorialOutputs `, :meth:`getClockRelatedInputs `, :meth:`getClockRelatedOutputs `, :meth:`getInputRelatedClocks `, :meth:`getOutputRelatedClocks ` * - :class:`najaeda.naja.SNLTerm` and term subclasses - :class:`Direction `, :meth:`getName `, :meth:`setName `, :meth:`getDirection `, :meth:`getDesign `, :meth:`getNet `, :meth:`setNet `, :meth:`getBits `, :meth:`getWidth `, :meth:`getNLID `, :meth:`getSourceLoc `, :meth:`hasSourceLoc `; bit terms also expose :meth:`setRole `, :meth:`getRole `, :meth:`getResetActiveLevel `, :meth:`isClock `, :meth:`isAsyncReset `, :meth:`isAsyncSet `, :meth:`isSyncReset `, :meth:`isSyncSet `, :meth:`isReset `, :meth:`isEnable `, :meth:`isData `, :meth:`isDataInput `, :meth:`isDataOutput ` * - :class:`najaeda.naja.SNLNet` and net subclasses diff --git a/src/najaeda/najaeda/primitives/xilinx.py b/src/najaeda/najaeda/primitives/xilinx.py index 6bfc512d1..628c99090 100644 --- a/src/najaeda/najaeda/primitives/xilinx.py +++ b/src/najaeda/najaeda/primitives/xilinx.py @@ -259,7 +259,8 @@ def constructSRL16E(lib): def _set_flip_flop_model(primitive, next_state, clear=None, preset=None): - state = {"name": "IQ", "next_state": next_state} + state = {"name": "IQ", "next_state": next_state, + "init_from": {"parameter": "INIT", "bit": 0}} if clear is not None: state["clear"] = clear if preset is not None: diff --git a/src/nl/netlist/decorators/SNLDesignModeling.cpp b/src/nl/netlist/decorators/SNLDesignModeling.cpp index 602c31c2f..3c13c8829 100644 --- a/src/nl/netlist/decorators/SNLDesignModeling.cpp +++ b/src/nl/netlist/decorators/SNLDesignModeling.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include "NLBitDependencies.h" @@ -1858,6 +1859,285 @@ void SNLDesignModeling::setMemoryInterface( property->getModeling()->setMemoryInterface_(memInterface); } +namespace { +// Sequential models use the existing dumpable-property transport, so NajaIF +// does not need a parallel schema for expression graphs. Version this payload +// independently and encode terminal identity rather than process-local pointers. +const std::string sequentialPropertyName = "SNLSequentialModels"; +using Modeling = SNLDesignModeling; +using Expression = Modeling::BooleanExpression; + +void writeSequentialExpression(std::ostream& out, const Expression& expression) { + out << expression.root << ' ' << expression.nodes.size() << ' '; + for (const auto& node : expression.nodes) { + out << static_cast(node.operation) << ' ' << node.constant << ' ' + << node.state << ' ' << bool(node.term) << ' '; + if (node.term) out << node.term->getID() << ' ' << node.term->getBit() << ' '; + out << node.operands.size() << ' '; + for (auto operand : node.operands) out << operand << ' '; + } +} + +Expression readSequentialExpression(std::istream& in, SNLDesign* design) { + Expression expression; + size_t count = 0; + in >> expression.root >> count; + for (size_t i = 0; i < count && in; ++i) { + Expression::Node node; + int operation = 0; + bool hasTerm = false; + in >> operation >> node.constant >> node.state >> hasTerm; + if (operation < 0 || operation > static_cast(Expression::Operator::Xor)) { + throw NLException("Invalid serialized sequential expression operator"); + } + node.operation = static_cast(operation); + if (hasTerm) { + NLID::DesignObjectID id = 0; + NLID::Bit bit = 0; + in >> id >> bit; + node.term = design->getBitTerm(id, bit); + if (!node.term) throw NLException("Missing serialized sequential model terminal"); + } + size_t operands = 0; + in >> operands; + for (size_t j = 0; j < operands && in; ++j) { + size_t operand = 0; + in >> operand; + node.operands.push_back(operand); + } + expression.nodes.push_back(std::move(node)); + } + return expression; +} + +void writeSequentialModel(std::ostream& out, const Modeling::SequentialModel& model) { + out << static_cast(model.kind) << ' '; + writeSequentialExpression(out, model.clockedOn); + out << model.states.size() << ' '; + for (const auto& state : model.states) { + out << (state.init ? (*state.init ? 1 : 0) : -1) << ' ' << bool(state.initFrom) << ' '; + if (state.initFrom) out << std::quoted(state.initFrom->parameter) << ' ' << state.initFrom->bit << ' '; + out << static_cast(state.clearPresetValue) << ' '; + writeSequentialExpression(out, state.nextState); + for (const auto* expression : {&state.clear, &state.preset}) { + out << bool(*expression) << ' '; + if (*expression) writeSequentialExpression(out, **expression); + } + } + out << model.outputs.size() << ' '; + for (const auto& output : model.outputs) { + out << output.term->getID() << ' ' << output.term->getBit() << ' '; + writeSequentialExpression(out, output.function); + } +} + +Modeling::SequentialModel readSequentialModel(std::istream& in, SNLDesign* design) { + Modeling::SequentialModel model; + int kind = 0; + in >> kind; + model.kind = static_cast(kind); + model.clockedOn = readSequentialExpression(in, design); + size_t count = 0; + in >> count; + for (size_t i = 0; i < count && in; ++i) { + Modeling::SequentialState state; + int init = -1; + bool fromParameter = false; + in >> init >> fromParameter; + if (init < -1 || init > 1) throw NLException("Invalid serialized sequential initial value"); + if (init != -1) state.init = init != 0; + if (fromParameter) { + Modeling::SequentialState::InitialValueParameter source; + in >> std::quoted(source.parameter) >> source.bit; + state.initFrom = std::move(source); + } + int clearPresetValue = 0; + in >> clearPresetValue; + state.clearPresetValue = static_cast(clearPresetValue); + state.nextState = readSequentialExpression(in, design); + for (auto* expression : {&state.clear, &state.preset}) { + bool present = false; + in >> present; + if (present) *expression = readSequentialExpression(in, design); + } + model.states.push_back(std::move(state)); + } + in >> count; + for (size_t i = 0; i < count && in; ++i) { + NLID::DesignObjectID id = 0; + NLID::Bit bit = 0; + in >> id >> bit; + auto* term = design->getBitTerm(id, bit); + if (!term) throw NLException("Missing serialized sequential output terminal"); + model.outputs.push_back({term, readSequentialExpression(in, design)}); + } + return model; +} + +void storeSequentialModels(SNLDesign* design, const std::vector& parameters, + const Modeling::SequentialModelTable& models) { + if (auto* old = design->getProperty(sequentialPropertyName)) old->destroy(); + // Static setters historically permit incomplete/foreign-pin models so + // consumers can diagnose them. Keep that behavior, but never persist an + // invalid pointer as a different terminal in the destination design. + for (const auto& [key, model] : models) { + for (const auto& output : model.outputs) { + if (!output.term || output.term->getDesign() != design) return; + } + const auto localTerms = [design](const Expression& expression) { + return std::all_of(expression.nodes.begin(), expression.nodes.end(), [design](const auto& node) { + return node.operation != Expression::Operator::Term || + (node.term && node.term->getDesign() == design); + }); + }; + if (!localTerms(model.clockedOn)) return; + for (const auto& state : model.states) { + if (!localTerms(state.nextState) || (state.clear && !localTerms(*state.clear)) || + (state.preset && !localTerms(*state.preset))) return; + } + for (const auto& output : model.outputs) if (!localTerms(output.function)) return; + } + std::ostringstream out; + out << 1 << ' ' << parameters.size() << ' '; + for (const auto& name : parameters) out << std::quoted(name) << ' '; + out << models.size() << ' '; + for (const auto& [key, model] : models) { + for (auto value : key) out << value << ' '; + writeSequentialModel(out, model); + } + auto* property = naja::NajaDumpableProperty::create(design, sequentialPropertyName); + property->addStringValue(out.str()); +} + +void validateSequentialInitialValues(const SNLDesign* design, + const SNLDesignModeling::SequentialModel& model) { + for (const auto& state : model.states) { + if (state.init && state.initFrom) { + throw NLException("Sequential state cannot specify both init and init_from"); + } + if (state.initFrom && !design->getParameter(NLName(state.initFrom->parameter))) { + throw NLException("Unknown sequential initial-value parameter <" + state.initFrom->parameter + ">"); + } + } +} + +std::optional parseSequentialInitialBit(const std::string& literal, size_t bit) { + std::string text; + for (unsigned char c : literal) { + if (!std::isspace(c) && c != '_') text.push_back(std::tolower(c)); + } + if (text.empty()) return std::nullopt; + // VHDL-style quoted scalar bits, also commonly used by primitive libraries. + if (text.size() == 3 && text.front() == '\'' && text.back() == '\'') { + if (std::string("01xuz").find(text[1]) == std::string::npos) { + throw NLException("Invalid sequential initial value <" + literal + ">"); + } + if (bit != 0 || (text[1] != '0' && text[1] != '1')) return std::nullopt; + return text[1] == '1'; + } + unsigned base = 10; + std::optional width; + auto quote = text.find('\''); + if (quote != std::string::npos) { + if (quote > 0) { + width = static_cast(parseUnsignedDigits(text.substr(0, quote), 10, literal)); + if (*width == 0) throw NLException("Zero-width sequential initial value <" + literal + ">"); + } + auto position = quote + 1; + if (position < text.size() && text[position] == 's') ++position; + if (position >= text.size() || (text[position] != 'b' && text[position] != 'd')) { + throw NLException("Invalid sequential initial value <" + literal + ">"); + } + base = text[position] == 'b' ? 2 : 10; + text = text.substr(position + 1); + } + if (text.empty()) return std::nullopt; + for (char c : text) { + if (c != 'x' && c != 'u' && c != 'z' && + (c < '0' || c > (base == 2 ? '1' : '9'))) { + throw NLException("Invalid sequential initial value <" + literal + ">"); + } + } + if (width && bit >= *width) return std::nullopt; + if (base == 2) { + // Unknown digits affect only their own bit. Short values are zero-extended, + // except for an unknown leading digit, which extends that unknown value. + char digit = bit < text.size() ? text[text.size() - 1 - bit] : + (text.front() == '0' || text.front() == '1' ? '0' : text.front()); + if (digit != '0' && digit != '1') return std::nullopt; + return digit == '1'; + } + if (text.find_first_of("xuz") != std::string::npos) return std::nullopt; + // Decimal division avoids a host integer width limit for wide parameters. + for (size_t index = 0; ; ++index) { + unsigned carry = 0; + for (char& digit : text) { + unsigned value = carry * 10 + static_cast(digit - '0'); + digit = static_cast('0' + value / 2); + carry = value % 2; + } + if (index == bit) return carry != 0; + auto first = text.find_first_not_of('0'); + if (first == std::string::npos) return false; + text.erase(0, first); + } +} +} // namespace + +void SNLDesignModeling::restoreSequentialModels(SNLDesign* design) { + auto* property = dynamic_cast(design->getProperty(sequentialPropertyName)); + if (!property) return; + std::istringstream in(property->getStringValue(0)); + unsigned version = 0; + size_t count = 0; + in >> version >> count; + if (version != 1) throw NLException("Unsupported serialized sequential model version"); + std::vector parameters; + for (size_t i = 0; i < count && in; ++i) { + std::string name; + in >> std::quoted(name); + parameters.push_back(std::move(name)); + } + SequentialModelTable models; + in >> count; + for (size_t i = 0; i < count && in; ++i) { + std::vector key(parameters.size()); + for (auto& value : key) in >> value; + auto model = readSequentialModel(in, design); + if (!models.emplace(key, std::move(model)).second) throw NLException("Duplicate serialized sequential model key"); + } + if (!in || (in >> std::ws, !in.eof()) || models.empty()) { + throw NLException("Invalid serialized sequential model payload"); + } + if (parameters.empty()) { + if (models.size() != 1) throw NLException("Invalid static sequential model payload"); + setSequentialModel(design, models.begin()->second); + } else { + setSequentialModelFromParameters(design, parameters, models); + } +} + +std::vector> SNLDesignModeling::getSequentialInitialValues( + const SNLInstance* instance) { + const auto& model = getSequentialModel(instance); + std::vector> values; + values.reserve(model.states.size()); + for (const auto& state : model.states) { + auto value = state.init; + if (state.initFrom) { + const auto& source = *state.initFrom; + auto* parameter = instance->getModel()->getParameter(NLName(source.parameter)); + if (!parameter) throw NLException("Unknown sequential initial-value parameter <" + source.parameter + ">"); + auto* override = instance->getInstParameter(NLName(source.parameter)); + if (override || parameter->hasDefaultValue()) { + value = parseSequentialInitialBit(override ? override->getValue() : parameter->getValue(), source.bit); + } + } + values.push_back(value); + } + return values; +} + void SNLDesignModeling::setSequentialModel( SNLDesign* design, const SequentialModel& model) { @@ -1867,9 +2147,11 @@ void SNLDesignModeling::setSequentialModel( if (!model.isValid()) { throw NLException("Cannot add invalid sequential model"); } + validateSequentialInitialValues(design, model); auto property = getOrCreateProperty(design, NO_PARAMETER); std::lock_guard lock(property->getModeling()->instanceSequentialModelsMutex_); property->getModeling()->setSequentialModel_(model); + storeSequentialModels(design, {}, {{{}, model}}); } bool SNLDesignModeling::hasSequentialModel(const SNLDesign* design) { @@ -1971,6 +2253,7 @@ void SNLDesignModeling::setSequentialModelFromParameters( } } }; + validateSequentialInitialValues(design, model); validateExpression(model.clockedOn, "clocked_on"); for (size_t i = 0; i < model.states.size(); ++i) { const auto& state = model.states[i]; @@ -2006,6 +2289,7 @@ void SNLDesignModeling::setSequentialModelFromParameters( modeling->sequentialModel_.reset(); modeling->sequentialParameters_ = parameters; modeling->sequentialModels_ = models; + storeSequentialModels(design, parameters, models); } bool SNLDesignModeling::hasSequentialModelFromParameters(const SNLDesign* design) { diff --git a/src/nl/netlist/decorators/SNLDesignModeling.h b/src/nl/netlist/decorators/SNLDesignModeling.h index b9355b5c3..fc921d8ad 100644 --- a/src/nl/netlist/decorators/SNLDesignModeling.h +++ b/src/nl/netlist/decorators/SNLDesignModeling.h @@ -146,10 +146,16 @@ class SNLDesignModeling { struct SequentialState { enum class ClearPresetValue { Zero, One, Hold, Toggle, Unknown }; + struct InitialValueParameter { + std::string parameter {}; + size_t bit {0}; // Least-significant bit is zero, independent of pin indexing. + }; BooleanExpression nextState {}; std::optional clear {}; std::optional preset {}; ClearPresetValue clearPresetValue {ClearPresetValue::Unknown}; + std::optional init {}; + std::optional initFrom {}; }; struct SequentialOutput { SNLBitTerm* term {nullptr}; @@ -253,6 +259,10 @@ class SNLDesignModeling { static const SequentialModel& getSequentialModel(std::nullptr_t) { return getSequentialModel(static_cast(nullptr)); } + // State order matches getSequentialModel(instance). nullopt denotes a free state. + static std::vector> getSequentialInitialValues(const SNLInstance* instance); + // Restore the versioned dumpable-property payload after loading an interface. + static void restoreSequentialModels(SNLDesign* design); static void invalidateSequentialModelCache(const SNLInstance* instance); static void setTruthTable(SNLDesign* design, const SNLTruthTable& truthTable); diff --git a/src/nl/netlist/serialization/capnp/SNLCapnPInterface.cpp b/src/nl/netlist/serialization/capnp/SNLCapnPInterface.cpp index f3de30623..3a615a7c4 100644 --- a/src/nl/netlist/serialization/capnp/SNLCapnPInterface.cpp +++ b/src/nl/netlist/serialization/capnp/SNLCapnPInterface.cpp @@ -27,6 +27,7 @@ #include "NLException.h" #include "SNLDesign.h" +#include "SNLDesignModeling.h" #include "SNLDesignObject.h" #include "SNLRTLInfos.h" #include "SNLCapnPRTLInfos.h" @@ -190,6 +191,11 @@ void dumpDesignInterface( if (snlDesign->hasRTLInfos()) { dumpRTLInfos(designInterface.initRtlInfos(), snlDesign->getRTLInfos()); } + if (SNLDesignModeling::hasSequentialModel(snlDesign) && + !snlDesign->getProperty("SNLSequentialModels")) { + throw NLException("Cannot serialize sequential model with missing or foreign terminals: " + + snlDesign->getDescription()); + } auto lambda = [](SNLDesignInterface::Builder& builder, size_t nbProperties) { return builder.initProperties(nbProperties); }; @@ -457,6 +463,7 @@ void loadDesignInterface( } } } + SNLDesignModeling::restoreSequentialModels(snlDesign); } void loadLibraryInterface( diff --git a/src/nl/python/naja_wrapping/PySNLInstance.cpp b/src/nl/python/naja_wrapping/PySNLInstance.cpp index ab57c114e..425f95b6c 100644 --- a/src/nl/python/naja_wrapping/PySNLInstance.cpp +++ b/src/nl/python/naja_wrapping/PySNLInstance.cpp @@ -150,6 +150,8 @@ PyMethodDef PySNLInstance_Methods[] = { { "getMemoryInterface", (PyCFunction)PySNLInstance_getMemoryInterface, METH_NOARGS, "Return the memory interface dictionary; raise RuntimeError if absent."}, + { "getSequentialInitialValues", (PyCFunction)PySNLInstance_getSequentialInitialValues, METH_NOARGS, + "Resolve each sequential state initial value (0, 1, or None)."}, { "getSequentialModel", (PyCFunction)PySNLInstance_getSequentialModel, METH_NOARGS, "Resolve the instance sequential model as expression trees."}, { "create", (PyCFunction)PySNLInstance_create, METH_VARARGS|METH_STATIC, diff --git a/src/nl/python/naja_wrapping/PySNLSequentialModel.cpp b/src/nl/python/naja_wrapping/PySNLSequentialModel.cpp index 17e8023f6..2c8b2f4c8 100644 --- a/src/nl/python/naja_wrapping/PySNLSequentialModel.cpp +++ b/src/nl/python/naja_wrapping/PySNLSequentialModel.cpp @@ -166,6 +166,41 @@ bool parseSequentialModel(const SNLDesign* selfObject, const char* clockedOn, if (nextState == nullptr) return false; SNLDesignModeling::SequentialState state; + auto* init = PyDict_GetItemString(stateObject, "init"); + auto* initFrom = PyDict_GetItemString(stateObject, "init_from"); + if (init && initFrom) { + setError("Sequential state cannot specify both init and init_from"); + return false; + } + if (init) { + if (!PyLong_Check(init)) { + setError("Sequential state init must be 0 or 1"); + return false; + } + long value = PyLong_AsLong(init); + if (PyErr_Occurred() || (value != 0 && value != 1)) { + PyErr_Clear(); + setError("Sequential state init must be 0 or 1"); + return false; + } + state.init = value != 0; + } + if (initFrom) { + if (!PyDict_Check(initFrom)) { + setError("Sequential state init_from must be a dictionary"); + return false; + } + const char* parameter = getStringField(initFrom, "parameter", true); + if (!parameter) return false; + auto* bitObject = PyDict_GetItemString(initFrom, "bit"); + if (!bitObject || !PyLong_Check(bitObject)) { + setError("Sequential state init_from.bit must be a nonnegative integer"); + return false; + } + size_t bit = PyLong_AsSize_t(bitObject); + if (PyErr_Occurred()) return false; + state.initFrom = SNLDesignModeling::SequentialState::InitialValueParameter{parameter, bit}; + } state.nextState = parseExpression( selfObject, nextState, stateIdentifiers); if (fieldPath) *fieldPath = "states[" + std::to_string(i) + "].clear"; @@ -396,6 +431,15 @@ PyObject* modelToPython(const SNLDesignModeling::SequentialModel& model) { "clear", optionalExpressionToPython(state.clear), "preset", optionalExpressionToPython(state.preset), "clear_preset_value", values[static_cast(state.clearPresetValue)]); + if (entry && (state.init || state.initFrom)) { + auto* value = state.init ? PyLong_FromLong(*state.init) : + Py_BuildValue("{s:s,s:K}", "parameter", state.initFrom->parameter.c_str(), + "bit", static_cast(state.initFrom->bit)); + if (!value || PyDict_SetItemString(entry, state.init ? "init" : "init_from", value) < 0) { + Py_XDECREF(value); Py_DECREF(entry); Py_DECREF(states); Py_DECREF(outputs); return nullptr; + } + Py_DECREF(value); + } if (!entry || PyList_Append(states, entry) < 0) { // LCOV_EXCL_START: Python allocation failure cleanup. Py_XDECREF(entry); Py_DECREF(states); Py_DECREF(outputs); return nullptr; @@ -439,4 +483,21 @@ PyObject* PySNLInstance_getSequentialModel(PySNLInstance* self) { NLCATCH } +PyObject* PySNLInstance_getSequentialInitialValues(PySNLInstance* self) { + auto* selfObject = PYSNLInstance_O(self); + if (!selfObject) { + setError("SNLInstance.getSequentialInitialValues(): destroyed instance"); + return nullptr; + } + TRY + const auto values = SNLDesignModeling::getSequentialInitialValues(selfObject); + auto* result = PyList_New(values.size()); + if (!result) return nullptr; + for (size_t i = 0; i < values.size(); ++i) { + PyList_SET_ITEM(result, i, values[i] ? PyLong_FromLong(*values[i]) : Py_NewRef(Py_None)); + } + return result; + NLCATCH +} + } // namespace PYNAJA diff --git a/src/nl/python/naja_wrapping/PySNLSequentialModel.h b/src/nl/python/naja_wrapping/PySNLSequentialModel.h index c287485e5..d0d9a4df1 100644 --- a/src/nl/python/naja_wrapping/PySNLSequentialModel.h +++ b/src/nl/python/naja_wrapping/PySNLSequentialModel.h @@ -16,6 +16,7 @@ PyObject* PySNLDesign_hasSequentialModelFromParameters(PySNLDesign* self); PyObject* PySNLDesign_setSequentialModelFromParameters( PySNLDesign* self, PyObject* args, PyObject* kwargs); PyObject* PySNLDesign_getSequentialModel(PySNLDesign* self); +PyObject* PySNLInstance_getSequentialInitialValues(PySNLInstance* self); PyObject* PySNLInstance_getSequentialModel(PySNLInstance* self); } // namespace PYNAJA diff --git a/test/najaeda/test_najaeda_determinism.py b/test/najaeda/test_najaeda_determinism.py index 25ee2cf19..75ad61cb1 100644 --- a/test/najaeda/test_najaeda_determinism.py +++ b/test/najaeda/test_najaeda_determinism.py @@ -169,6 +169,12 @@ def visit(library): [[t.getNLID().toTuple(), attributes(t)] for t in design.getBitTerms()], [[n.getNLID().toTuple(), attributes(n)] for n in design.getBitNets()], ]) + for instance in design.getInstances(): + if instance.getModel().hasSequentialModel(): + model = instance.getSequentialModel() + state.append(["sequential_initial_values", instance.getNLID().toTuple(), + instance.getSequentialInitialValues(), + [[row.get("init"), row.get("init_from")] for row in model["states"]]]) for child in library.getLibraries(): visit(child) @@ -236,6 +242,9 @@ def worker(kind, source, output, run): universe.setTopDB(db) if kind in ("sv", "sv_timing", "sv_resets"): db.loadSystemVerilog([source], diagnostics_report_path=None) + elif kind == "seq": + exec(compile(Path(source).read_text(), source, "exec"), + {"naja": naja, "db": db, "universe": universe}) elif kind == "v": db.loadGateLevelVerilog([source]) from najaeda import naja @@ -353,6 +362,33 @@ def check_determinism(self, kind, source, files=None): with self.subTest(language=kind, run=run, phase="fresh process"): self.assert_artifacts_equal(baseline, original) + def test_primitive_sequential_initial_values(self): + self.check_determinism("seq", """ +primitives = naja.NLLibrary.createPrimitives(db, "PRIMS") +designs = naja.NLLibrary.create(db, "DESIGN") +top = naja.SNLDesign.create(designs, "top") +universe.setTopDesign(top) +for table in (False, True): + model = naja.SNLDesign.createPrimitive(primitives, "FF_" + str(table)) + c = naja.SNLScalarTerm.create(model, naja.SNLTerm.Direction.Input, "C") + d = naja.SNLScalarTerm.create(model, naja.SNLTerm.Direction.Input, "D") + q = naja.SNLBusTerm.create(model, naja.SNLTerm.Direction.Output, 1, 0, "Q") + naja.SNLParameter.createBinary(model, "MODE", 1, 0) + init = naja.SNLParameter.createBinary(model, "INIT_VAL", 2, 2) + states = [dict(name="S", next_state="D", init=0), + dict(name="T", next_state="!S", init_from=dict(parameter="INIT_VAL", bit=1))] + outputs = [(q.getBusTermBit(0), "S"), (q.getBusTermBit(1), "!T")] + if table: + model.setSequentialModelFromParameters(["MODE"], [dict( + values=[mode], clocked_on="!C" if mode else "C", states=states, outputs=outputs) + for mode in (0, 1)]) + else: + model.setSequentialModel("C", states, outputs) + for number, value in enumerate(("2'b00", "2'b10", "2'bx0")): + instance = naja.SNLInstance.create(top, model, "ff_" + str(table) + str(number)) + naja.SNLInstParameter.create(instance, init, value) +""") + def test_canonical_db0_families(self): binary = os.environ.get("NAJA_DB0_AUDIT_BINARY") self.assertTrue(binary, "Set NAJA_DB0_AUDIT_BINARY to the snlCapnPTests executable") diff --git a/test/najaeda/test_najaeda_netlist_primitives.py b/test/najaeda/test_najaeda_netlist_primitives.py index 172fb067f..c4bf25262 100644 --- a/test/najaeda/test_najaeda_netlist_primitives.py +++ b/test/najaeda/test_najaeda_netlist_primitives.py @@ -166,6 +166,13 @@ def test_xilinx_sequential_instance_models(self): self.assertEqual("flip_flop", model["kind"]) self.assertEqual(("term", primitive.getScalarTerm("C")), model["clocked_on"]) state = model["states"][0] + self.assertEqual({"parameter": "INIT", "bit": 0}, state["init_from"]) + self.assertEqual([1 if name == "FDPE" else 0], + instance.getSequentialInitialValues()) + override = naja.SNLInstParameter.create(instance, primitive.getParameter("INIT"), "1'b1") + self.assertEqual([1], instance.getSequentialInitialValues()) + override.setValue("1'bx") + self.assertEqual([None], instance.getSequentialInitialValues()) if name == "FDCE": self.assertEqual(("term", primitive.getScalarTerm("CLR")), state["clear"]) elif name == "FDPE": diff --git a/test/nl/python/naja_wrapping/test_snldesign_modeling.py b/test/nl/python/naja_wrapping/test_snldesign_modeling.py index e992719e5..4cee41be8 100644 --- a/test/nl/python/naja_wrapping/test_snldesign_modeling.py +++ b/test/nl/python/naja_wrapping/test_snldesign_modeling.py @@ -3,6 +3,8 @@ # SPDX-License-Identifier: Apache-2.0 import os +import subprocess +import sys import tempfile import unittest import warnings @@ -21,6 +23,114 @@ def tearDown(self): if naja.NLUniverse.get(): naja.NLUniverse.get().destroy() + def testSequentialInitialValues(self): + reg = naja.SNLDesign.createPrimitive(self.primitives, "initial_model") + for name in ("C", "D"): + naja.SNLScalarTerm.create(reg, naja.SNLTerm.Direction.Input, name) + q = naja.SNLScalarTerm.create(reg, naja.SNLTerm.Direction.Output, "Q") + parameter = naja.SNLParameter.createString(reg, "INIT_VAL", "4'b0001") + required = naja.SNLParameter.createDecimal(reg, "REQUIRED") + mode = naja.SNLParameter.createDecimal(reg, "MODE", 0) + top = naja.SNLDesign.create(self.designs, "initial_top") + instance = naja.SNLInstance.create(top, reg, "ff") + + def define(fields, table=False): + state = dict(name="S", next_state="D", **fields) + if table: + reg.setSequentialModelFromParameters(["MODE"], [dict( + values=[0], clocked_on="C", states=[state], outputs=[(q, "S")])]) + else: + reg.setSequentialModel("C", [state], [(q, "S")]) + + for table in (False, True): + for value in (0, 1): + define(dict(init=value), table) + self.assertEqual([value], instance.getSequentialInitialValues()) + self.assertEqual(value, instance.getSequentialModel()["states"][0]["init"]) + if not table: + self.assertEqual(value, reg.getSequentialModel()["states"][0]["init"]) + source = dict(parameter="INIT_VAL", bit=0) + define(dict(init_from=source), table) + self.assertEqual(source, instance.getSequentialModel()["states"][0]["init_from"]) + self.assertEqual([1], instance.getSequentialInitialValues()) + override = naja.SNLInstParameter.create(instance, parameter, "0") + for text, expected in (("1'b1", 1), ("4'b0001", 1), ("4'd1", 1), + ("1", 1), ("'0'", 0), ("'1'", 1), ("0", 0), + ("1'bx", None), ("1'bu", None), ("1'bz", None), + ("'X'", None), ("'U'", None), ("'Z'", None), + ("4'dx", None), ("", None)): + with self.subTest(table=table, text=text): + override.setValue(text) + self.assertEqual([expected], instance.getSequentialInitialValues()) + for text in ("'2'", "1'b2", "4'd12a", "4'h1"): + override.setValue(text) + with self.assertRaisesRegex(RuntimeError, "Invalid sequential initial value"): + instance.getSequentialInitialValues() + define(dict(init_from=dict(parameter="INIT_VAL", bit=3)), table) + for text, expected in (("4'b1000", 1), ("4'd8", 1), ("4'b0001", 0), + ("4'bx001", None), ("4'b1x01", 1), ("1'b1", None)): + override.setValue(text) + self.assertEqual([expected], instance.getSequentialInitialValues()) + define(dict(init_from=dict(parameter="INIT_VAL", bit=80)), table) + override.setValue("81'd1208925819614629174706176") + self.assertEqual([1], instance.getSequentialInitialValues()) + override.destroy() + define(dict(init_from=dict(parameter="REQUIRED", bit=0)), table) + self.assertEqual([None], instance.getSequentialInitialValues()) + for fields in (dict(init_from=dict(parameter="MISSING", bit=0)), + dict(init=0, init_from=source), dict(init=2), dict(init="1"), + dict(init_from=dict(parameter="INIT_VAL", bit=-1)), + dict(init_from=dict(parameter="INIT_VAL", bit="0"))): + with self.assertRaises((RuntimeError, OverflowError)): + define(fields, table) + + def testSequentialInitialValuesSnapshot(self): + for table in (False, True): + with self.subTest(table=table), tempfile.TemporaryDirectory() as directory: + reg = naja.SNLDesign.createPrimitive(self.primitives, "snapshot_" + str(table)) + c = naja.SNLScalarTerm.create(reg, naja.SNLTerm.Direction.Input, "C") + d = naja.SNLScalarTerm.create(reg, naja.SNLTerm.Direction.Input, "D") + q = naja.SNLBusTerm.create(reg, naja.SNLTerm.Direction.Output, 1, 0, "Q") + parameter = naja.SNLParameter.createString(reg, "INIT_VAL", "2'b10") + naja.SNLParameter.createDecimal(reg, "MODE", 0) + states = [dict(name="S", next_state="D", init=0), + dict(name="T", next_state="!S", clear="!C", preset="D", + clear_preset_value="hold", + init_from=dict(parameter="INIT_VAL", bit=1))] + outputs = [(q.getBusTermBit(0), "S"), (q.getBusTermBit(1), "!T")] + if table: + reg.setSequentialModelFromParameters(["MODE"], [dict( + values=[0], clocked_on="C", states=states, outputs=outputs)]) + else: + reg.setSequentialModel("C", states, outputs) + top = naja.SNLDesign.create(self.designs, "snapshot_top_" + str(table)) + instance = naja.SNLInstance.create(top, reg, "ff") + naja.SNLInstParameter.create(instance, parameter, "2'd0") + naja.NLUniverse.get().setTopDesign(top) + self.db.dumpNajaIF(directory) + # A fresh process has no primitive construction or process-local cache. + script = """ +import naja, sys +universe = naja.NLUniverse.create() +db = naja.NLDB.loadNajaIF(sys.argv[1]) +reg = db.getLibrary(int(sys.argv[2])).getSNLDesign(sys.argv[3]) +top = db.getLibrary(int(sys.argv[4])).getSNLDesign(sys.argv[5]) +instance = top.getInstance("ff") +assert instance.getSequentialInitialValues() == [0, 0] +model = instance.getSequentialModel() +assert model['states'][0]['init'] == 0 +assert model['states'][1]['init_from'] == {'parameter': 'INIT_VAL', 'bit': 1} +assert model['states'][1]['clear_preset_value'] == 'hold' +assert model['outputs'][1][1] == ('not', ('state', 1)) +instance.getInstParameter('INIT_VAL').destroy() +assert instance.getSequentialInitialValues() == [0, 1] +universe.destroy() +""" + result = subprocess.run([sys.executable, "-X", "faulthandler", "-c", script, directory, + str(self.primitives.getID()), reg.getName(), str(self.designs.getID()), + top.getName()], capture_output=True, text=True) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + def testDeprecatedRoleAliases(self): model = naja.SNLDesign.createPrimitive(self.primitives, "alias_model") term = naja.SNLScalarTerm.create(model, naja.SNLTerm.Direction.Input, "CLK") diff --git a/test/nl/snl/decorators/SNLDesignModelingTest0.cpp b/test/nl/snl/decorators/SNLDesignModelingTest0.cpp index 692080ac0..a5732634b 100644 --- a/test/nl/snl/decorators/SNLDesignModelingTest0.cpp +++ b/test/nl/snl/decorators/SNLDesignModelingTest0.cpp @@ -1566,3 +1566,45 @@ TEST_F(SNLDesignModelingTest0, testParameterizedTermRoles) { EXPECT_EQ(Role::Other, Modeling::getTermRole(r)); EXPECT_FALSE(Modeling::hasRolesFromParameters(nullptr)); } + +TEST_F(SNLDesignModelingTest0, testSequentialInitialValues) { + using Modeling = SNLDesignModeling; + NLUniverse::create(); + auto* db = NLDB::create(NLUniverse::get()); + auto* primitives = NLLibrary::create(db, NLLibrary::Type::Primitives); + auto* designs = NLLibrary::create(db); + auto* top = SNLDesign::create(designs, NLName("top")); + auto* primitive = SNLDesign::create(primitives, SNLDesign::Type::Primitive, NLName("FF")); + auto* clock = SNLScalarTerm::create(primitive, SNLTerm::Direction::Input, NLName("C")); + auto* output = SNLScalarTerm::create(primitive, SNLTerm::Direction::Output, NLName("Q")); + auto* parameter = SNLParameter::create(primitive, NLName("INIT_VAL"), SNLParameter::Type::Binary, "2'b10"); + auto* instance = SNLInstance::create(top, primitive, NLName("ff")); + Modeling::SequentialModel model; + model.clockedOn.root = model.clockedOn.addTerm(clock); + Modeling::SequentialState state; + state.nextState.root = state.nextState.addConstant(false); + state.init = false; + model.states.push_back(state); + Modeling::SequentialOutput pin; + pin.term = output; + pin.function.root = pin.function.addState(0); + model.outputs.push_back(pin); + Modeling::setSequentialModel(primitive, model); + EXPECT_EQ(Modeling::getSequentialInitialValues(instance), std::vector>{false}); + model.states[0].initFrom = Modeling::SequentialState::InitialValueParameter{"INIT_VAL", 1}; + EXPECT_THROW(Modeling::setSequentialModel(primitive, model), NLException); + model.states[0].init.reset(); + Modeling::setSequentialModel(primitive, model); + EXPECT_EQ(Modeling::getSequentialInitialValues(instance), std::vector>{true}); + auto* override = SNLInstParameter::create(instance, parameter, "2'd0"); + EXPECT_EQ(Modeling::getSequentialInitialValues(instance), std::vector>{false}); + override->setValue("2'bx0"); + EXPECT_EQ(Modeling::getSequentialInitialValues(instance), std::vector>{std::nullopt}); + override->setValue("2'b10"); + EXPECT_EQ(Modeling::getSequentialInitialValues(instance), std::vector>{true}); + override->setValue("2'b20"); + EXPECT_THROW(Modeling::getSequentialInitialValues(instance), NLException); + model.states[0].initFrom->parameter = "MISSING"; + EXPECT_THROW(Modeling::setSequentialModel(primitive, model), NLException); + EXPECT_THROW(Modeling::getSequentialInitialValues(nullptr), NLException); +} diff --git a/test/nl/snl/serialization/capnp/SNLCapnPTest0.cpp b/test/nl/snl/serialization/capnp/SNLCapnPTest0.cpp index 1a092d0cc..14733c28d 100644 --- a/test/nl/snl/serialization/capnp/SNLCapnPTest0.cpp +++ b/test/nl/snl/serialization/capnp/SNLCapnPTest0.cpp @@ -14,6 +14,7 @@ using ::testing::Property; #include "NLUniverse.h" #include "NLDB.h" #include "SNLScalarTerm.h" +#include "SNLDesignModeling.h" #include "SNLBusTerm.h" #include "SNLBusTermBit.h" #include "SNLScalarNet.h" @@ -434,3 +435,29 @@ TEST_F(SNLCapNpTest0, incompatibleDB0LibraryIDsThrowBeforePayloadLoad) { } } } + +TEST_F(SNLCapNpTest0, RejectsSequentialModelsWithForeignTerminals) { + auto* library = NLLibrary::create(db_, NLLibrary::Type::Primitives); + auto* model = SNLDesign::create(library, SNLDesign::Type::Primitive, NLName("FF")); + auto* foreign = SNLDesign::create(library, SNLDesign::Type::Primitive, NLName("OTHER")); + auto* c = SNLScalarTerm::create(model, SNLTerm::Direction::Input, NLName("C")); + auto* q = SNLScalarTerm::create(model, SNLTerm::Direction::Output, NLName("Q")); + auto* other = SNLScalarTerm::create(foreign, SNLTerm::Direction::Output, NLName("Q")); + SNLDesignModeling::SequentialModel sequence; + sequence.clockedOn.root = sequence.clockedOn.addTerm(c); + SNLDesignModeling::SequentialState state; + state.nextState.root = state.nextState.addConstant(false); + sequence.states.push_back(state); + SNLDesignModeling::BooleanExpression function; + function.root = function.addState(0); + sequence.outputs.push_back({other, function}); + const auto path = std::filesystem::path(SNL_CAPNP_TEST_PATH) / "foreignSequentialTerm.snl"; + // In-memory models remain available for consumer diagnostics, while snapshot + // writing must never turn the foreign pointer into an unrelated local pin. + EXPECT_NO_THROW(SNLDesignModeling::setSequentialModel(model, sequence)); + EXPECT_THROW(SNLCapnP::dump(db_, path), NajaException); + sequence.outputs[0].term = q; + sequence.states[0].nextState.root = sequence.states[0].nextState.addTerm(other); + EXPECT_NO_THROW(SNLDesignModeling::setSequentialModel(model, sequence)); + EXPECT_THROW(SNLCapnP::dump(db_, path), NajaException); +} From dd32d39c36c0510c414dedcda0d44fe21020c929 Mon Sep 17 00:00:00 2001 From: xtof Date: Fri, 20 Nov 2026 00:11:23 +0100 Subject: [PATCH 2/2] Defer sequential model serialization until snapshot writes --- .../netlist/decorators/SNLDesignModeling.cpp | 76 +++++++++++-------- src/nl/netlist/decorators/SNLDesignModeling.h | 2 + .../serialization/capnp/SNLCapnPInterface.cpp | 29 +++++-- 3 files changed, 66 insertions(+), 41 deletions(-) diff --git a/src/nl/netlist/decorators/SNLDesignModeling.cpp b/src/nl/netlist/decorators/SNLDesignModeling.cpp index 3c13c8829..0d00f7d44 100644 --- a/src/nl/netlist/decorators/SNLDesignModeling.cpp +++ b/src/nl/netlist/decorators/SNLDesignModeling.cpp @@ -1974,39 +1974,27 @@ Modeling::SequentialModel readSequentialModel(std::istream& in, SNLDesign* desig return model; } -void storeSequentialModels(SNLDesign* design, const std::vector& parameters, - const Modeling::SequentialModelTable& models) { - if (auto* old = design->getProperty(sequentialPropertyName)) old->destroy(); - // Static setters historically permit incomplete/foreign-pin models so - // consumers can diagnose them. Keep that behavior, but never persist an - // invalid pointer as a different terminal in the destination design. - for (const auto& [key, model] : models) { - for (const auto& output : model.outputs) { - if (!output.term || output.term->getDesign() != design) return; - } - const auto localTerms = [design](const Expression& expression) { - return std::all_of(expression.nodes.begin(), expression.nodes.end(), [design](const auto& node) { - return node.operation != Expression::Operator::Term || - (node.term && node.term->getDesign() == design); - }); - }; - if (!localTerms(model.clockedOn)) return; - for (const auto& state : model.states) { - if (!localTerms(state.nextState) || (state.clear && !localTerms(*state.clear)) || - (state.preset && !localTerms(*state.preset))) return; - } - for (const auto& output : model.outputs) if (!localTerms(output.function)) return; +void validateSerializableSequentialModel(const SNLDesign* design, + const Modeling::SequentialModel& model) { + const auto fail = [design]() { + throw NLException("Cannot serialize sequential model with missing or foreign terminals: " + + design->getDescription()); + }; + for (const auto& output : model.outputs) { + if (!output.term || output.term->getDesign() != design) fail(); } - std::ostringstream out; - out << 1 << ' ' << parameters.size() << ' '; - for (const auto& name : parameters) out << std::quoted(name) << ' '; - out << models.size() << ' '; - for (const auto& [key, model] : models) { - for (auto value : key) out << value << ' '; - writeSequentialModel(out, model); + const auto localTerms = [design](const Expression& expression) { + return std::all_of(expression.nodes.begin(), expression.nodes.end(), [design](const auto& node) { + return node.operation != Expression::Operator::Term || + (node.term && node.term->getDesign() == design); + }); + }; + if (!localTerms(model.clockedOn)) fail(); + for (const auto& state : model.states) { + if (!localTerms(state.nextState) || (state.clear && !localTerms(*state.clear)) || + (state.preset && !localTerms(*state.preset))) fail(); } - auto* property = naja::NajaDumpableProperty::create(design, sequentialPropertyName); - property->addStringValue(out.str()); + for (const auto& output : model.outputs) if (!localTerms(output.function)) fail(); } void validateSequentialInitialValues(const SNLDesign* design, @@ -2084,6 +2072,29 @@ std::optional parseSequentialInitialBit(const std::string& literal, size_t } } // namespace +std::string SNLDesignModeling::serializeSequentialModels(const SNLDesign* design) { + auto* property = design ? getProperty(design) : nullptr; + if (!property || !property->getModeling()->hasSequentialModel_()) return {}; + auto* modeling = property->getModeling(); + std::lock_guard lock(modeling->instanceSequentialModelsMutex_); + std::ostringstream out; + out << 1 << ' ' << modeling->sequentialParameters_.size() << ' '; + for (const auto& name : modeling->sequentialParameters_) out << std::quoted(name) << ' '; + if (modeling->sequentialModel_) { + out << 1 << ' '; + validateSerializableSequentialModel(design, *modeling->sequentialModel_); + writeSequentialModel(out, *modeling->sequentialModel_); + } else { + out << modeling->sequentialModels_.size() << ' '; + for (const auto& [key, model] : modeling->sequentialModels_) { + validateSerializableSequentialModel(design, model); + for (auto value : key) out << value << ' '; + writeSequentialModel(out, model); + } + } + return out.str(); +} + void SNLDesignModeling::restoreSequentialModels(SNLDesign* design) { auto* property = dynamic_cast(design->getProperty(sequentialPropertyName)); if (!property) return; @@ -2109,6 +2120,7 @@ void SNLDesignModeling::restoreSequentialModels(SNLDesign* design) { if (!in || (in >> std::ws, !in.eof()) || models.empty()) { throw NLException("Invalid serialized sequential model payload"); } + property->destroy(); // The wire payload is transient; the model owns the live state. if (parameters.empty()) { if (models.size() != 1) throw NLException("Invalid static sequential model payload"); setSequentialModel(design, models.begin()->second); @@ -2151,7 +2163,6 @@ void SNLDesignModeling::setSequentialModel( auto property = getOrCreateProperty(design, NO_PARAMETER); std::lock_guard lock(property->getModeling()->instanceSequentialModelsMutex_); property->getModeling()->setSequentialModel_(model); - storeSequentialModels(design, {}, {{{}, model}}); } bool SNLDesignModeling::hasSequentialModel(const SNLDesign* design) { @@ -2289,7 +2300,6 @@ void SNLDesignModeling::setSequentialModelFromParameters( modeling->sequentialModel_.reset(); modeling->sequentialParameters_ = parameters; modeling->sequentialModels_ = models; - storeSequentialModels(design, parameters, models); } bool SNLDesignModeling::hasSequentialModelFromParameters(const SNLDesign* design) { diff --git a/src/nl/netlist/decorators/SNLDesignModeling.h b/src/nl/netlist/decorators/SNLDesignModeling.h index fc921d8ad..6e33662e4 100644 --- a/src/nl/netlist/decorators/SNLDesignModeling.h +++ b/src/nl/netlist/decorators/SNLDesignModeling.h @@ -261,6 +261,8 @@ class SNLDesignModeling { } // State order matches getSequentialModel(instance). nullopt denotes a free state. static std::vector> getSequentialInitialValues(const SNLInstance* instance); + // Serialize only for snapshot I/O; model construction never formats a payload. + static std::string serializeSequentialModels(const SNLDesign* design); // Restore the versioned dumpable-property payload after loading an interface. static void restoreSequentialModels(SNLDesign* design); static void invalidateSequentialModelCache(const SNLInstance* instance); diff --git a/src/nl/netlist/serialization/capnp/SNLCapnPInterface.cpp b/src/nl/netlist/serialization/capnp/SNLCapnPInterface.cpp index 3a615a7c4..0bafd2e71 100644 --- a/src/nl/netlist/serialization/capnp/SNLCapnPInterface.cpp +++ b/src/nl/netlist/serialization/capnp/SNLCapnPInterface.cpp @@ -191,15 +191,28 @@ void dumpDesignInterface( if (snlDesign->hasRTLInfos()) { dumpRTLInfos(designInterface.initRtlInfos(), snlDesign->getRTLInfos()); } - if (SNLDesignModeling::hasSequentialModel(snlDesign) && - !snlDesign->getProperty("SNLSequentialModels")) { - throw NLException("Cannot serialize sequential model with missing or foreign terminals: " + - snlDesign->getDescription()); - } - auto lambda = [](SNLDesignInterface::Builder& builder, size_t nbProperties) { - return builder.initProperties(nbProperties); + const auto sequentialModel = SNLDesignModeling::serializeSequentialModels(snlDesign); + constexpr auto sequentialPropertyName = "SNLSequentialModels"; + auto properties = designInterface.initProperties( + snlDesign->getDumpableProperties().size() + (sequentialModel.empty() ? 0 : 1)); + size_t propertyID = 0; + bool sequentialWritten = sequentialModel.empty(); + const auto writeSequentialProperty = [&]() { + auto property = properties[propertyID++]; + property.setName(sequentialPropertyName); + property.initValues(1)[0].setText(sequentialModel); + sequentialWritten = true; }; - dumpProperties(designInterface, snlDesign, lambda); + // Preserve the property-name order of the existing dumpable-property format + // without attaching formatted snapshot data to the live design. + for (auto property : snlDesign->getDumpableProperties()) { + if (!sequentialWritten && property->getName() > sequentialPropertyName) { + writeSequentialProperty(); + } + auto builder = properties[propertyID++]; + dumpProperty(builder, property); + } + if (!sequentialWritten) writeSequentialProperty(); size_t id = 0; auto parameters = designInterface.initParameters(snlDesign->getParameters().size());