28#include <unordered_map>
31#include <boost/graph/adjacency_list.hpp>
42using namespace SILICON::core;
46 struct ModuleInterface {
47 std::string moduleName;
48 std::vector<CircuitPort> inputs;
49 std::vector<CircuitPort> outputs;
54 std::string direction;
60 [[nodiscard]] std::string fallbackPortName(
const bool input,
const std::size_t index)
62 return std::format(
"{}_{}", input ?
"input" :
"output", index);
65 [[nodiscard]] std::string identifierPart(
const std::string_view value)
68 result.reserve(
value.size());
69 for (
const char character : value) {
70 const bool valid = (character >=
'a' && character <=
'z')
71 || (character >=
'A' && character <=
'Z')
72 || (character >=
'0' && character <=
'9') || character ==
'_';
75 else if (result.empty() || result.back() !=
'_')
80 if (result.front() >=
'0' && result.front() <=
'9')
81 result.insert(0,
"component_");
85 [[nodiscard]] std::string readableCellType(std::string type)
87 if (type.starts_with(
"SILICON_"))
88 type.erase(0, std::string_view(
"SILICON_").size());
89 while (!type.empty() && type.front() ==
'$')
90 type.erase(type.begin());
91 std::ranges::transform(type, type.begin(), [](
const unsigned char character) {
92 return static_cast<char>(std::tolower(character));
94 return identifierPart(type);
101 Json* module =
nullptr;
113 throw std::logic_error(
"Cannot allocate a numeric Yosys signal for a null wire");
114 const auto id = wire->getId();
123 const std::string_view direction)
125 if (requested.empty())
126 requested = direction ==
"input" ?
"input" :
"output";
130 for (std::size_t suffix = 2;; ++suffix) {
131 auto candidate = std::format(
"{}_{}", requested, suffix);
140 class DesignBuilder {
142 Json modules = Json::object();
143 std::map<std::string, ModuleInterface> subcircuitInterfaces;
144 std::set<std::string> moduleNames;
146 void serializeModule(
const Circuit& circuit,
const std::string& moduleName,
147 const std::vector<ForcedPort>& forcedPorts = {})
151 if (!moduleNames.insert(moduleName).second)
152 throw std::runtime_error(
153 std::format(
"Duplicate Yosys module name '{}'", moduleName));
155 Json module =
Json{{
"attributes", Json::object()},
156 {
"ports", Json::object()},
157 {
"cells", Json::object()},
158 {
"netnames", Json::object()}};
159 SerializationContext::Impl impl;
161 impl.module = &
module;
162 SerializationContext context(impl);
164 for (
const auto& port : forcedPorts)
167 const auto& graph = circuit.
getGraph();
168 for (
const auto vertex : boost::make_iterator_range(boost::vertices(graph))) {
169 const auto& component = graph[vertex].component;
174 component->serializeYosys(context);
179 Json renamedCells = Json::object();
180 std::set<std::string> renamedCellNames;
181 for (
const auto& [cellName, cell] : module[
"cells"].items()) {
182 std::string readableName = cellName;
183 for (
const auto& [portName, port] : module[
"ports"].items()) {
184 for (
const auto& [cellPort, direction] : cell.at(
"port_directions").items()) {
185 if (direction ==
"output"
186 && cell.at(
"connections").at(cellPort) ==
port.at(
"bits")) {
188 std::format(
"{}_{}", identifierPart(portName),
189 readableCellType(cell.at(
"type").get<std::string>()));
193 if (readableName != cellName)
196 const auto baseName = readableName;
197 for (std::size_t index = 2; !renamedCellNames.insert(readableName).second;
199 readableName = std::format(
"{}_{}", baseName, index);
200 renamedCells[readableName] = cell;
202 module["cells"] = std::move(renamedCells);
207 for (
const auto& [portName, port] : module[
"ports"].items()) {
208 for (
auto net = module[
"netnames"].begin(); net !=
module["netnames"].end();) {
209 if (net.key() != portName && net.value().at(
"bits") ==
port.at(
"bits"))
210 net =
module["netnames"].erase(net);
216 modules[moduleName] = std::move(module);
219 [[nodiscard]] ModuleInterface
220 ensureSubcircuit(
const std::string_view slug,
221 const SILICON::core::CircuitResolver* resolver)
223 const std::string slugString(slug);
224 if (slugString.empty())
225 throw std::runtime_error(
"Cannot export a subcircuit with an empty slug");
226 if (
const auto it = subcircuitInterfaces.find(slugString);
227 it != subcircuitInterfaces.end()) {
232 throw std::runtime_error(
"Subcircuit serialization requires a circuit resolver");
233 auto definition = resolver->
resolve(slugString);
235 ModuleInterface interface;
236 interface.moduleName = slugString;
237 interface.inputs = definition.inputs;
238 interface.outputs = definition.outputs;
240 std::set<std::string> names;
241 auto makeUnique = [&names](std::string name,
const std::string_view fallback) {
244 if (names.insert(name).second)
246 for (std::size_t index = 2;; ++index) {
247 auto candidate = std::format(
"{}_{}", name, index);
248 if (names.insert(candidate).second)
252 for (std::size_t index = 0; index < interface.inputs.size(); ++index)
253 interface.inputs[index].name =
254 makeUnique(interface.inputs[index].name, fallbackPortName(
true, index));
255 for (std::size_t index = 0; index < interface.outputs.size(); ++index)
256 interface.outputs[index].name =
257 makeUnique(interface.outputs[index].name, fallbackPortName(
false, index));
261 subcircuitInterfaces.emplace(slugString, interface);
263 std::vector<ForcedPort> ports;
264 for (
const auto& port : interface.inputs)
265 ports.push_back({
port.name,
"input",
port.bus});
266 for (
const auto& port : interface.outputs)
267 ports.push_back({
port.name,
"output",
port.bus});
269 serializeModule(definition.circuit, interface.moduleName, ports);
280 Json result = Json::array();
281 for (
const auto& wire : bus) {
283 result.push_back(
impl.signalFor(wire));
285 result.push_back(std::string(nullValue));
291 const std::size_t expectedWidth)
const
294 if (index >= buses.size() || buses[index].size() != expectedWidth) {
295 throw std::runtime_error(
296 std::format(
"Cannot export '{}': input bus {} must be a {}-bit bus",
297 component.
typeName(), index, expectedWidth));
301 if (!defaultState && std::ranges::contains(buses[index],
nullptr)) {
302 throw std::runtime_error(
303 std::format(
"Cannot export '{}': input bus {} must be connected",
307 const bool binaryDefault =
309 const std::string defaultBit =
311 return bits(buses[index], defaultBit);
316 Json result = Json::array();
317 for (std::size_t bit = 0; bit < width; ++bit)
318 result.push_back(
impl.nextSignal++);
324 Json result = Json::array();
325 for (
const auto& vector : vectors)
326 for (
const auto& bit : vector)
327 result.push_back(bit);
332 const std::size_t width)
335 throw std::invalid_argument(
"Yosys parameter width must be positive");
343 return std::format(
"{}_{}", identifierPart(
impl.componentType),
impl.vertex);
347 const std::string_view type,
Json parameters,
350 const bool isConstant =
351 type ==
"$pos" && connections.contains(
"A")
352 && std::ranges::all_of(connections.at(
"A"),
353 [](
const Json& bit) { return bit.is_string(); });
354 const auto baseName =
355 std::format(
"{}_{}", identifierPart(
impl.componentType),
impl.vertex);
357 suffix.empty() ? baseName : std::format(
"{}_{}", baseName, identifierPart(suffix));
360 if (!
impl.cellNames.insert(name).second) {
361 for (std::size_t index = 2;; ++index) {
362 auto candidate = std::format(
"{}_{}", name, index);
363 if (
impl.cellNames.insert(candidate).second) {
364 name = std::move(candidate);
375 for (
const auto& [port, direction] : portDirections.items()) {
376 if (direction !=
"output" || !connections.contains(port))
378 for (
auto& bit : connections.at(port)) {
380 bit =
impl.nextSignal++;
384 for (
const auto& [port, direction] : portDirections.items()) {
385 if (isConstant || direction !=
"output" || !connections.contains(port))
387 std::string netName = std::format(
"{}_{}", baseName, identifierPart(port));
388 for (std::size_t index = 2; !
impl.netNames.insert(netName).second; ++index)
389 netName = std::format(
"{}_{}_{}", baseName, identifierPart(port), index);
390 (*
impl.module)[
"netnames"][netName] =
Json{
391 {
"hide_name", 0}, {
"bits", connections.at(port)}, {
"attributes", Json::object()}};
394 (*
impl.module)[
"cells"][name] =
Json{{
"hide_name", isConstant ? 1 : 0},
396 {
"parameters", std::move(parameters)},
398 {
"port_directions", std::move(portDirections)},
399 {
"connections", std::move(connections)}};
405 if (direction !=
"input" && direction !=
"output" && direction !=
"inout")
406 throw std::invalid_argument(
"Invalid Yosys port direction");
407 name =
impl.uniquePortName(std::move(name), direction);
408 impl.netNames.insert(name);
410 (*
impl.module)[
"ports"][name] =
Json{{
"direction", direction}, {
"bits", portBits}};
411 (*
impl.module)[
"netnames"][name] =
412 Json{{
"hide_name", 0}, {
"bits", portBits}, {
"attributes", Json::object()}};
416 const std::string_view slug,
const std::vector<Bus>& inputs,
419 const auto interface = impl.design->ensureSubcircuit(slug, resolver);
420 if (inputs.size() != interface.inputs.size()
421 || outputs.size() != interface.outputs.size()) {
422 throw std::runtime_error(std::format(
"Subcircuit '{}' interface mismatch: expected "
423 "{} inputs and {} outputs, got {} and {}",
424 slug, interface.inputs.size(),
425 interface.outputs.size(), inputs.size(),
429 Json portDirections = Json::object();
430 Json connections = Json::object();
431 for (std::size_t index = 0; index < inputs.size(); ++index) {
432 portDirections[interface.inputs[index].name] =
"input";
433 connections[interface.inputs[index].name] =
bits(inputs[index]);
435 for (std::size_t index = 0; index < outputs.size(); ++index) {
436 portDirections[interface.outputs[index].name] =
"output";
437 connections[interface.outputs[index].name] =
bits(outputs[index]);
439 addCell(
"instance", interface.moduleName, Json::object(), std::move(portDirections),
440 std::move(connections));
445 DesignBuilder builder;
446 builder.serializeModule(circuit, std::string(moduleName));
447 Json design =
Json{{
"creator", std::format(
"Silicon {}", SILICON_VERSION)},
448 {
"modules", std::move(builder.modules)}};
449 return design.dump(2);
virtual SubcircuitDefinition resolve(std::string_view slug) const =0
Represents a digital circuit as a directed graph of components.
const CircuitGraph & getGraph() const
Gets the underlying circuit graph.
Base class for all digital circuit components.
const std::vector< Bus > & inputBuses() const
Gets all input buses without copying.
virtual std::string_view typeName() const =0
Gets the component type name.
std::optional< State > unconnectedInputDefault(unsigned int input) const
Gets the state used when an input has no connected wire.
void addPort(std::string name, std::string_view direction, const core::Bus &bus)
Register a named top-level input or output port.
void addSubcircuitInstance(std::string_view slug, const std::vector< core::Bus > &inputs, const std::vector< core::Bus > &outputs, const core::CircuitResolver *resolver)
Emit a hierarchical instance and recursively serialize its definition.
Json bits(const core::Bus &bus, std::string_view nullValue="x") const
Convert a Silicon bus to a Yosys least-significant-bit-first vector.
Json allocateBits(std::size_t width)
Allocate module-local temporary signal bits.
static std::string parameter(std::uint64_t value, std::size_t width=32)
Encode an unsigned Yosys parameter as a fixed-width binary string.
std::string componentIdentifier() const
Stable name of the component being serialized within its module.
Json inputBits(const core::Component &component, std::size_t index, std::size_t expectedWidth) const
Encode a component input, applying its declared unconnected-input default.
void addCell(std::string_view suffix, std::string_view type, Json parameters, Json portDirections, Json connections, Json attributes=Json::object())
Emit one native Yosys cell for the current Silicon component.
static Json concatenate(const std::vector< Json > &vectors)
Concatenate bit vectors in their existing LSB-first order.
RTLIL::SigSpec port(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key, int expected)
std::shared_ptr< Wire > Wire_ptr
boost::graph_traits< CircuitGraph >::vertex_descriptor VertexDescriptor
Descriptor type for vertices in the circuit graph.
BusValue busValueFromInteger(const BigInt &value, const std::size_t width)
Builds an LSB-first BusValue from the low width bits of an integer. Negative values use two's complem...
std::string formatValue(const BusValue &value, const BusValueFormat format, const std::size_t fixedWidth)
Format an LSB-first BusValue for display.
std::vector< State > BusValue
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
std::string serialize(const Circuit &circuit, const std::string_view moduleName)
Serialize a complete Silicon circuit as Yosys write_json-compatible JSON.
nlohmann::ordered_json Json
std::string componentType
std::set< std::string > netNames
std::string componentType
int signalFor(const Wire_ptr &wire)
std::map< std::uint64_t, int > wireSignals
std::set< std::string > portNames
std::string uniquePortName(std::string requested, const std::string_view direction)
std::set< std::string > cellNames