SILICON
Loading...
Searching...
No Matches
deserialization.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18/* Strict lowering from a supported Yosys write_json module to Silicon components. */
19
20#include "cells.hpp"
21#include "netlist.hpp"
22
23#include <algorithm>
24#include <bit>
25#include <array>
26#include <charconv>
27#include <format>
28#include <functional>
29#include <limits>
30#include <map>
31#include <memory>
32#include <optional>
33#include <ranges>
34#include <set>
35#include <span>
36#include <stdexcept>
37#include <string>
38#include <string_view>
39#include <utility>
40#include <vector>
41
42#include <core/circuit.hpp>
43#include <core/flipflops.hpp>
44#include <core/gates.hpp>
45#include <core/io.hpp>
46#include <core/memory.hpp>
48#include <core/register.hpp>
49#include <core/subcircuit.hpp>
54
55namespace SILICON::yosys {
56
57using namespace SILICON::core;
58using namespace SILICON::extra;
59namespace {
60
61 [[noreturn]] void fail(const std::string_view context, const std::string_view message)
62 {
63 throw std::runtime_error(
64 std::format("Invalid Yosys JSON at {}: {}", context, message));
65 }
66
67 [[nodiscard]] std::string_view binaryDigits(const Json& value,
68 const std::string_view context)
69 {
70 if (!value.is_string())
71 fail(context, "expected a binary string or unsigned integer");
72 const auto& digits = value.get_ref<const std::string&>();
73 if (digits.empty())
74 fail(context, "binary value must not be empty");
75 if (!std::ranges::all_of(
76 digits, [](const char digit) { return digit == '0' || digit == '1'; })) {
77 fail(context, "expected a fully defined binary string");
78 }
79 return digits;
80 }
81
82 [[nodiscard]] std::uint64_t parseUnsigned(const Json& value,
83 const std::string_view context)
84 {
85 if (value.is_number_unsigned())
86 return value.get<std::uint64_t>();
87 if (value.is_number_integer()) {
88 const auto result = value.get<std::int64_t>();
89 if (result < 0)
90 fail(context, "expected an unsigned value");
91 return static_cast<std::uint64_t>(result);
92 }
93 const auto decimal = formatValue(busValueFromBits(binaryDigits(value, context)),
94 BusValueFormat::Unsigned);
95 std::uint64_t result = 0;
96 const auto [end, error] =
97 std::from_chars(decimal.data(), decimal.data() + decimal.size(), result);
98 if (error == std::errc::result_out_of_range)
99 fail(context, "binary value does not fit in 64 bits");
100 if (error != std::errc{} || end != decimal.data() + decimal.size())
101 fail(context, "expected a fully defined binary string");
102 return result;
103 }
104
105 [[nodiscard]] bool isZeroParameter(const Json& value, const std::string_view context)
106 {
107 if (value.is_number_integer() || value.is_number_unsigned())
108 return parseUnsigned(value, context) == 0;
109 return std::ranges::all_of(binaryDigits(value, context),
110 [](const char digit) { return digit == '0'; });
111 }
112
113 [[nodiscard]] const Json& requireObjectMember(const Json& object,
114 const std::string_view key,
115 const std::string_view context)
116 {
117 if (!object.is_object())
118 fail(context, "expected an object");
119 const auto it = object.find(key);
120 if (it == object.end())
121 fail(context, std::format("missing '{}'", key));
122 return *it;
123 }
124
125 void requireExactMembers(const Json& object,
126 const std::span<const std::string_view> names,
127 const std::string_view context,
128 const std::string_view memberKind)
129 {
130 if (!object.is_object())
131 fail(context, "expected an object");
132 if (object.size() != names.size())
133 fail(context, std::format("cell has missing or unexpected {}s", memberKind));
134 for (const auto name : names)
135 if (!object.contains(name))
136 fail(context, std::format("missing '{}' {}", name, memberKind));
137 }
138
139 [[nodiscard]] Bus slice(const Bus& bus, const std::size_t offset,
140 const std::size_t width)
141 {
142 std::vector<Wire_ptr> wires;
143 wires.reserve(width);
144 for (std::size_t bit = 0; bit < width; ++bit)
145 wires.push_back(bus[static_cast<unsigned short>(offset + bit)]);
146 return Bus(std::move(wires));
147 }
148
149 class Importer {
150 public:
151 explicit Importer(Json design) : design(std::move(design)) {}
152
153 [[nodiscard]] Circuit run(const std::optional<std::string_view> requestedModule)
154 {
155 const auto& modules = requireObjectMember(design, "modules", "design");
156 if (!modules.is_object() || modules.empty())
157 fail("design.modules", "expected at least one module");
158
159 const auto [name, module] = selectModule(modules, requestedModule);
160 moduleName = name;
161 importModule(module);
162 normalizeBusConnections();
163
164 // Boundary ports and imported instances both follow the JSON port order.
165 // Sorting components by shared_ptr ownership would make the definition's
166 // interface depend on allocation order and miswire positional instances.
167 return Circuit(components, false);
168 }
169
170 private:
171 enum class ConnectionRole { Driver, Consumer };
172
173 class Cell {
174 public:
175 Cell(Importer& importer, const Json& cell, std::string context)
176 : context(std::move(context)),
177 importer(importer),
178 parametersJson(requireObjectMember(cell, "parameters", this->context)),
179 connectionsJson(requireObjectMember(cell, "connections", this->context))
180 {
181 if (!cell.is_object())
182 fail(this->context, "expected an object");
183 const auto& typeJson = requireObjectMember(cell, "type", this->context);
184 if (!typeJson.is_string())
185 fail(std::format("{}.type", this->context), "expected a string");
186 type = typeJson.get<std::string>();
187 if (!parametersJson.is_object())
188 fail(std::format("{}.parameters", this->context), "expected an object");
189 if (!connectionsJson.is_object())
190 fail(std::format("{}.connections", this->context), "expected an object");
191 }
192
193 [[nodiscard]] const std::string& cellType() const { return type; }
194 [[nodiscard]] const std::string& where() const { return context; }
195
196 void requireConnections(const std::initializer_list<std::string_view> names) const
197 {
198 requireExactMembers(connectionsJson, std::span(names.begin(), names.size()),
199 context, "connection");
200 }
201
202 void requireParameters(const std::initializer_list<std::string_view> names) const
203 {
204 requireExactMembers(parametersJson, std::span(names.begin(), names.size()),
205 context, "parameter");
206 }
207
208 template <std::size_t ParameterCount, std::size_t ConnectionCount>
209 void requireSchema(
210 const std::array<std::string_view, ParameterCount>& PARAMETER_NAMES,
211 const std::array<std::string_view, ConnectionCount>& CONNECTION_NAMES) const
212 {
213 requireExactMembers(parametersJson, PARAMETER_NAMES, context, "parameter");
214 requireExactMembers(connectionsJson, CONNECTION_NAMES, context, "connection");
215 }
216
217 [[nodiscard]] const Json& parameter(const std::string_view name) const
218 {
219 return requireObjectMember(parametersJson, name, context);
220 }
221
222 void requireKnownConnectionNames(const std::span<const std::string> names) const
223 {
224 for (const auto& [name, _] : connectionsJson.items())
225 if (!std::ranges::contains(names, name))
226 fail(context, std::format("unexpected '{}' connection", name));
227 }
228
229 [[nodiscard]] std::size_t width(const std::string_view name) const
230 {
231 const auto result =
232 parseUnsigned(parameter(name), std::format("{}.{}", context, name));
233 if (result == 0 || result > std::numeric_limits<unsigned short>::max())
234 fail(context, std::format("'{}' is outside Silicon's supported width", name));
235 return static_cast<std::size_t>(result);
236 }
237
238 [[nodiscard]] bool flag(const std::string_view name) const
239 {
240 const auto result =
241 parseUnsigned(parameter(name), std::format("{}.{}", context, name));
242 if (result > 1)
243 fail(context, std::format("'{}' must be zero or one", name));
244 return result == 1;
245 }
246
247 [[nodiscard]] bool zeroParameter(const std::string_view name) const
248 {
249 return isZeroParameter(parameter(name), std::format("{}.{}", context, name));
250 }
251
252 [[nodiscard]] Bus
253 consumer(const std::string_view port,
254 const std::optional<std::size_t> expectedWidth = std::nullopt) const
255 {
256 return bus(port, ConnectionRole::Consumer, expectedWidth);
257 }
258
259 [[nodiscard]] std::vector<Bus> consumerLanes(const std::string_view port,
260 const std::size_t laneWidth,
261 const std::size_t laneCount) const
262 {
263 // Yosys flattens word lanes into one LSB-first JSON array. Decode each lane
264 // separately so readBus() can recognize an all-literal word as a constant bus.
265 const auto& bits = requireObjectMember(connectionsJson, port, context);
266 const auto expectedWidth = laneWidth * laneCount;
267 if (!bits.is_array() || bits.size() != expectedWidth) {
268 fail(context, std::format("'{}' must be {} bits wide", port, expectedWidth));
269 }
270
271 std::vector<Bus> lanes;
272 lanes.reserve(laneCount);
273 for (std::size_t lane = 0; lane < laneCount; ++lane) {
274 Json laneBits = Json::array();
275 for (std::size_t bit = 0; bit < laneWidth; ++bit)
276 laneBits.push_back(bits[lane * laneWidth + bit]);
277 lanes.push_back(importer.readBus(
278 laneBits, ConnectionRole::Consumer,
279 std::format("{}.{} lane {}", context, port, lane), laneWidth));
280 }
281 return lanes;
282 }
283
284 [[nodiscard]] Bus
285 driver(const std::string_view port,
286 const std::optional<std::size_t> expectedWidth = std::nullopt) const
287 {
288 return bus(port, ConnectionRole::Driver, expectedWidth);
289 }
290
291 [[nodiscard]] Bus optionalDriver(const std::string_view port,
292 const std::size_t width) const
293 {
294 const auto connection = connectionsJson.find(port);
295 if (connection == connectionsJson.end()
296 || (connection->is_array() && connection->empty())) {
297 if (width == 0 || width > std::numeric_limits<unsigned short>::max())
298 fail(context, std::format("'{}' is outside Silicon's supported width", port));
299 // Preserve the module interface with private wires for each unused output.
300 return Bus(static_cast<unsigned short>(width));
301 }
302 return driver(port, width);
303 }
304
305 [[nodiscard]] Wire_ptr consumerBit(const std::string_view port) const
306 {
307 return consumer(port, 1)[0];
308 }
309
310 [[nodiscard]] Wire_ptr driverBit(const std::string_view port) const
311 {
312 return driver(port, 1)[0];
313 }
314
315 [[nodiscard]] bool rawConstant(const std::string_view port,
316 const std::string_view value,
317 const std::size_t expectedWidth = 1) const
318 {
319 const auto& bits = requireObjectMember(connectionsJson, port, context);
320 if (!bits.is_array() || bits.empty() || bits.size() != expectedWidth)
321 fail(context, std::format("'{}' must be {} bit{} wide", port, expectedWidth,
322 expectedWidth == 1 ? "" : "s"));
323 return std::ranges::all_of(bits, [value](const Json& bit) {
324 return bit.is_string() && bit.get_ref<const std::string&>() == value;
325 });
326 }
327
328 [[nodiscard]] Wire_ptr optionalActiveHighBit(const std::string_view port) const
329 {
330 return rawConstant(port, "0") ? nullptr : consumerBit(port);
331 }
332
333 private:
334 std::string context;
335 Importer& importer;
336 const Json& parametersJson;
337 const Json& connectionsJson;
338 std::string type;
339
340 [[nodiscard]] Bus bus(const std::string_view port, const ConnectionRole role,
341 const std::optional<std::size_t> expectedWidth) const
342 {
343 return importer.readBus(requireObjectMember(connectionsJson, port, context), role,
344 std::format("{}.{}", context, port), expectedWidth);
345 }
346 };
347
348 Json design;
349 std::string moduleName;
350 std::map<std::uint64_t, Wire_ptr> signals;
351 std::map<State, Wire_ptr> constants;
352 std::map<BusValue, Bus> constantBuses;
353 std::set<std::uint64_t> drivenSignals;
354 std::vector<Component_ptr> components;
355
356 using BusKey = std::vector<Wire_ptr>;
357
358 struct ProducerBus {
359 BusKey key;
360 };
361
362 struct ConsumerBus {
363 Component_ptr component;
364 std::size_t inputIndex;
365 };
366
367 [[nodiscard]] static BusKey busKey(const Bus& bus)
368 {
369 return static_cast<std::vector<Wire_ptr>>(bus);
370 }
371
372 [[nodiscard]] static bool fullyConnected(const BusKey& key)
373 {
374 return std::ranges::all_of(key,
375 [](const Wire_ptr& wire) { return wire != nullptr; });
376 }
377
378 void normalizeBusConnections()
379 {
380 // Yosys represents every net as individual signal bits. Silicon instead uses
381 // explicit components at scalar, sliced, concatenated or reordered boundaries.
382 // Snapshot the imported topology before adding those components so the generated
383 // helpers do not get normalized again.
384 std::vector<ProducerBus> producers;
385 std::map<Wire_ptr, std::size_t, std::owner_less<Wire_ptr>> producerByWire;
386 std::map<BusKey, std::vector<ConsumerBus>> consumers;
387
388 for (const auto& component : components) {
389 for (const auto& output : component->outputBuses()) {
390 if (output.size() == 0)
391 continue;
392 const auto producerIndex = producers.size();
393 producers.push_back({busKey(output)});
394 for (const auto& wire : producers.back().key)
395 if (wire)
396 producerByWire.try_emplace(wire, producerIndex);
397 }
398
399 for (std::size_t inputIndex = 0; inputIndex < component->inputBuses().size();
400 ++inputIndex) {
401 const auto& input = component->inputBuses()[inputIndex];
402 if (input.size() != 0)
403 consumers[busKey(input)].push_back({component, inputIndex});
404 }
405 }
406
407 // Keep contiguous runs together. Each producer has one shared splitter with
408 // just the requested slices (which may overlap), rather than one output per
409 // bit followed by a merger at every part-select.
410 using Range = std::pair<unsigned int, unsigned int>; // offset, width
411 std::vector<std::map<Range, Bus>> producerSlices(producers.size());
412 std::map<Wire_ptr, unsigned int, std::owner_less<Wire_ptr>> bitByWire;
413 std::map<Wire_ptr, State, std::owner_less<Wire_ptr>> constantStates;
414 for (std::size_t i = 0; i < producers.size(); ++i)
415 for (unsigned int bit = 0; bit < producers[i].key.size(); ++bit)
416 bitByWire.try_emplace(producers[i].key[bit], bit);
417 for (const auto& component : components) {
418 if (const auto constant =
419 std::dynamic_pointer_cast<ConstantComponent>(component)) {
420 const auto value = constant->getPropertyValue<BusValue>("value").value();
421 const auto& output = constant->outputBuses().at(0);
422 for (unsigned int bit = 0; bit < output.size(); ++bit)
423 constantStates.try_emplace(output[bit], value[bit]);
424 }
425 }
426
427 std::vector<Component_ptr> helpers;
428 const auto sourceSlice = [&](const std::size_t producerIndex,
429 const unsigned int offset, const unsigned int width) {
430 const auto& source = producers[producerIndex].key;
431 if (offset == 0 && width == source.size())
432 return Bus(source);
433 auto [slice, inserted] =
434 producerSlices[producerIndex].try_emplace(Range{offset, width});
435 if (inserted)
436 slice->second = Bus(static_cast<unsigned short>(width));
437 return slice->second;
438 };
439 for (const auto& [key, occurrences] : consumers) {
440 if (!fullyConnected(key))
441 continue;
442
443 // Restore extensions that Yosys represents as concatenated zeroes or
444 // repeated sign bits. Only consume a contiguous source slice, avoiding
445 // an extra extender on general concatenations that still need a merger.
446 std::size_t prefix = key.size();
447 while (prefix > 0 && constantStates.contains(key[prefix - 1])
448 && constantStates.at(key[prefix - 1]) == State::LOW)
449 --prefix;
450 bool signExtend = false;
451 if (prefix == key.size()) {
452 while (prefix > 1 && key[prefix - 1] == key[prefix - 2])
453 --prefix;
454 signExtend = true;
455 }
456 Bus replacement;
457 if (prefix > 0 && prefix < key.size()) {
458 const auto producer = producerByWire.find(key.front());
459 if (producer != producerByWire.end() && !constantStates.contains(key.front())) {
460 const auto offset = bitByWire.at(key.front());
461 const auto& source = producers[producer->second].key;
462 if (offset + prefix <= source.size()
463 && std::equal(key.begin(), key.begin() + prefix,
464 source.begin() + offset)) {
465 replacement = Bus(static_cast<unsigned short>(key.size()));
466 helpers.push_back(std::make_shared<Extender>(
467 sourceSlice(producer->second, offset,
468 static_cast<unsigned int>(prefix)),
469 replacement,
470 std::string(signExtend ? Extender::SIGNED_MODE
472 }
473 }
474 }
475
476 if (replacement.size() != 0) {
477 for (const auto& occurrence : occurrences)
478 occurrence.component->setInput(
479 static_cast<unsigned int>(occurrence.inputIndex), replacement);
480 continue;
481 }
482
483 std::vector<Bus> parts;
484 for (std::size_t start = 0; start < key.size();) {
485 // Mixed literal/signal connections should also keep literal runs on a
486 // bus, rather than fanning a scalar zero out to every merger input.
487 if (constantStates.contains(key[start])) {
488 Json literals = Json::array();
489 auto end = start;
490 while (end < key.size() && constantStates.contains(key[end])) {
491 const auto state = constantStates.at(key[end]);
492 literals.push_back(state == State::LOW ? "0"
493 : state == State::HIGH ? "1"
494 : "x");
495 ++end;
496 }
497 if (end - start == 1)
498 parts.emplace_back(Bus{key[start]});
499 else
500 parts.push_back(constantBus(literals, moduleContext()));
501 start = end;
502 continue;
503 }
504
505 const auto producer = producerByWire.find(key[start]);
506 if (producer == producerByWire.end()) {
507 parts.emplace_back(Bus{key[start++]});
508 continue;
509 }
510 const auto producerIndex = producer->second;
511 const auto& source = producers[producerIndex].key;
512 const auto offset = bitByWire.at(key[start]);
513 std::size_t width = 1;
514 while (start + width < key.size() && offset + width < source.size()
515 && key[start + width] == source[offset + width])
516 ++width;
517
518 parts.push_back(
519 sourceSlice(producerIndex, offset, static_cast<unsigned int>(width)));
520 start += width;
521 }
522
523 if (parts.size() == 1) {
524 replacement = parts.front();
525 } else {
526 replacement = Bus(static_cast<unsigned short>(key.size()));
527 auto merger = std::make_shared<WireMerger>();
528 merger->setProperty("size", static_cast<int>(key.size()));
529 std::string widths;
530 for (const auto& part : parts) {
531 if (!widths.empty())
532 widths += ',';
533 widths += std::to_string(part.size());
534 }
535 merger->setProperty("widths", widths);
536 merger->setInputs(parts);
537 merger->setOutputs({replacement});
538 helpers.push_back(std::move(merger));
539 }
540 for (const auto& occurrence : occurrences)
541 occurrence.component->setInput(static_cast<unsigned int>(occurrence.inputIndex),
542 replacement);
543 }
544
545 for (std::size_t i = 0; i < producers.size(); ++i) {
546 if (producerSlices[i].empty())
547 continue;
548 std::string specification;
549 std::vector<Bus> outputs;
550 for (const auto& [range, bus] : producerSlices[i]) {
551 if (!specification.empty())
552 specification += ',';
553 specification += std::format("{}:{}", range.first, range.second);
554 outputs.push_back(bus);
555 }
556 auto splitter = std::make_shared<WireSplitter>();
557 splitter->setProperty("size", static_cast<int>(producers[i].key.size()));
558 splitter->setProperty("slices", specification);
559 splitter->setInputs({Bus(producers[i].key)});
560 splitter->setOutputs(outputs);
561 helpers.push_back(std::move(splitter));
562 }
563
564 components.insert(components.end(), helpers.begin(), helpers.end());
565 }
566
567 [[nodiscard]] std::pair<std::string, const Json&>
568 selectModule(const Json& modules,
569 const std::optional<std::string_view> requested) const
570 {
571 if (requested) {
572 const auto it = modules.find(*requested);
573 if (it == modules.end())
574 fail("design.modules", std::format("module '{}' was not found", *requested));
575 return {std::string(*requested), *it};
576 }
577
578 if (modules.size() == 1)
579 return {modules.begin().key(), modules.begin().value()};
580
581 const Json* top = nullptr;
582 std::string topName;
583 for (const auto& [name, module] : modules.items()) {
584 if (!module.is_object())
585 fail(std::format("design.modules.{}", name), "expected an object");
586 const auto attributes = module.find("attributes");
587 if (attributes == module.end() || !attributes->is_object())
588 continue;
589 const auto topAttribute = attributes->find("top");
590 if (topAttribute == attributes->end()
591 || parseUnsigned(*topAttribute,
592 std::format("design.modules.{}.attributes.top", name))
593 == 0) {
594 continue;
595 }
596 if (top)
597 fail("design.modules", "more than one module is marked as top");
598 top = &module;
599 topName = name;
600 }
601 if (!top)
602 fail("design.modules", "module selection is ambiguous and no top is marked");
603 return {std::move(topName), *top};
604 }
605
606 void importModule(const Json& module)
607 {
608 if (!module.is_object())
609 fail(std::format("design.modules.{}", moduleName), "expected an object");
610
611 if (const auto memories = module.find("memories");
612 memories != module.end() && (!memories->is_object() || !memories->empty())) {
613 fail(moduleContext(), "memories are not supported");
614 }
615
616 importPorts(requireObjectMember(module, "ports", moduleContext()));
617 importCells(requireObjectMember(module, "cells", moduleContext()));
618 }
619
620 [[nodiscard]] std::string moduleContext() const
621 {
622 return std::format("design.modules.{}", moduleName);
623 }
624
625 [[nodiscard]] Wire_ptr numericWire(const std::uint64_t signal)
626 {
627 auto& wire = signals[signal];
628 if (!wire)
629 wire = std::make_shared<Wire>(State::UNKNOWN);
630 return wire;
631 }
632
633 [[nodiscard]] Wire_ptr constantWire(const std::string_view value,
634 const std::string_view context)
635 {
636 if (value == "z")
637 fail(context, "high-impedance 'z' has no Silicon equivalent");
638 if (value != "0" && value != "1" && value != "x")
639 fail(context, std::format("unsupported signal literal '{}'", value));
640
641 const auto state = busValueFromBits(value).front();
642 auto& wire = constants[state];
643 if (!wire) {
644 wire = std::make_shared<Wire>(state);
645 components.push_back(std::make_shared<ConstantComponent>(wire, BusValue{state}));
646 }
647 return wire;
648 }
649
650 [[nodiscard]] Bus constantBus(const Json& bits, const std::string_view context)
651 {
652 std::string rawValue;
653 rawValue.reserve(bits.size());
654 for (std::size_t bit = bits.size(); bit > 0; --bit) {
655 const auto& digitJson = bits[bit - 1];
656 if (!digitJson.is_string())
657 fail(context, "expected a fully literal bus");
658 const auto& digit = digitJson.get_ref<const std::string&>();
659 if (digit == "z")
660 fail(context, "high-impedance 'z' has no Silicon equivalent");
661 if (digit != "0" && digit != "1" && digit != "x")
662 fail(context, std::format("unsupported signal literal '{}'", digit));
663 rawValue += digit;
664 }
665 const BusValue value = busValueFromBits(rawValue);
666
667 auto [it, inserted] = constantBuses.try_emplace(value);
668 if (inserted) {
669 it->second = Bus(static_cast<unsigned short>(bits.size()));
670 components.push_back(std::make_shared<ConstantComponent>(it->second, value));
671 }
672 return it->second;
673 }
674
675 [[nodiscard]] Bus
676 readBus(const Json& bits, const ConnectionRole role, const std::string_view context,
677 const std::optional<std::size_t> expectedWidth = std::nullopt)
678 {
679 if (!bits.is_array() || bits.empty())
680 fail(context, "expected a non-empty bit array");
681 if (expectedWidth && bits.size() != *expectedWidth)
682 fail(context, std::format("expected {} bit{}", *expectedWidth,
683 *expectedWidth == 1 ? "" : "s"));
684
685 const bool fullyLiteralConsumer =
686 role == ConnectionRole::Consumer && bits.size() > 1
687 && std::ranges::all_of(bits, [](const Json& bit) { return bit.is_string(); });
688 if (fullyLiteralConsumer)
689 return constantBus(bits, context);
690
691 std::vector<Wire_ptr> wires;
692 wires.reserve(bits.size());
693 for (std::size_t index = 0; index < bits.size(); ++index) {
694 const auto& bit = bits[index];
695 const auto bitContext = std::format("{}[{}]", context, index);
696 if (bit.is_number_integer() || bit.is_number_unsigned()) {
697 const auto signal = parseUnsigned(bit, bitContext);
698 if (role == ConnectionRole::Driver && !drivenSignals.insert(signal).second)
699 fail(bitContext, std::format("signal {} has more than one driver", signal));
700 wires.push_back(numericWire(signal));
701 continue;
702 }
703 if (role == ConnectionRole::Driver || !bit.is_string())
704 fail(bitContext, role == ConnectionRole::Consumer
705 ? "expected a signal number or literal"
706 : "expected a numeric signal");
707 wires.push_back(constantWire(bit.get_ref<const std::string&>(), bitContext));
708 }
709 return Bus(std::move(wires));
710 }
711
712 void importPorts(const Json& ports)
713 {
714 if (!ports.is_object())
715 fail(std::format("{}.ports", moduleContext()), "expected an object");
716
717 for (const auto& [name, port] : ports.items()) {
718 const auto context = std::format("{}.ports.{}", moduleContext(), name);
719 if (!port.is_object())
720 fail(context, "expected an object");
721 const auto& directionJson = requireObjectMember(port, "direction", context);
722 const auto& bitsJson = requireObjectMember(port, "bits", context);
723 if (!directionJson.is_string())
724 fail(std::format("{}.direction", context), "expected a string");
725 const auto direction = directionJson.get<std::string>();
726
727 if (direction == "inout")
728 fail(context, "inout ports are not supported");
729 if (direction != "input" && direction != "output")
730 fail(context, std::format("invalid port direction '{}'", direction));
731
732 if (direction == "input") {
733 const Bus bus =
734 readBus(bitsJson, ConnectionRole::Driver, std::format("{}.bits", context));
735 if (bus.size() == 1)
736 components.push_back(std::make_shared<DummyInputComponent>(bus, name));
737 else
738 components.push_back(std::make_shared<DummyBusInputComponent>(bus, name));
739 } else {
740 // Yosys flattens a zero-extension assignment into a cell-free output
741 // connection whose most-significant bits are literal zeroes. Restore the
742 // word-level component when the remaining least-significant bits are all
743 // signals; mixed concatenations keep using the generic connection path.
744 Bus bus;
745 std::size_t inputWidth = bitsJson.size();
746 while (inputWidth > 0 && bitsJson[inputWidth - 1].is_string()
747 && bitsJson[inputWidth - 1].get_ref<const std::string&>() == "0") {
748 --inputWidth;
749 }
750
751 const bool isUnsignedExtension =
752 inputWidth > 0 && inputWidth < bitsJson.size()
753 && std::ranges::all_of(
754 bitsJson.begin(), bitsJson.begin() + inputWidth,
755 [](const Json& bit) {
756 return bit.is_number_integer() || bit.is_number_unsigned();
757 });
758 if (isUnsignedExtension) {
759 Json inputBits = Json::array();
760 for (std::size_t bit = 0; bit < inputWidth; ++bit)
761 inputBits.push_back(bitsJson[bit]);
762
763 const Bus input = readBus(inputBits, ConnectionRole::Consumer,
764 std::format("{}.bits", context));
765 bus = Bus(static_cast<unsigned short>(bitsJson.size()));
766 components.push_back(std::make_shared<Extender>(
767 input, bus, std::string(Extender::UNSIGNED_MODE)));
768 } else {
769 bus = readBus(bitsJson, ConnectionRole::Consumer,
770 std::format("{}.bits", context));
771 }
772
773 if (bus.size() == 1)
774 components.push_back(std::make_shared<DummyOutputComponent>(bus, name));
775 else
776 components.push_back(std::make_shared<DummyBusOutputComponent>(bus, name));
777 }
778 }
779 }
780
781 void importCells(const Json& cells)
782 {
783 if (!cells.is_object())
784 fail(std::format("{}.cells", moduleContext()), "expected an object");
785
786 for (const auto& [name, cell] : cells.items())
787 if (cell.is_object() && cell.value("type", std::string()) == "SILICON_ROM")
788 importRom(name, cell);
789 for (const auto& [name, cell] : cells.items())
790 if (cell.value("type", std::string()) != "SILICON_ROM")
791 importCell(name, cell);
792 }
793
794 void importRom(const std::string_view name, const Json& raw)
795 {
796 Cell cell(*this, raw, std::format("{}.cells.{}", moduleContext(), name));
797 cell.requireSchema(
798 std::array<std::string_view, 7>{"WIDTH", "SIZE", "ABITS", "INIT", "ID", "SYNC", "CLK_POLARITY"},
799 std::array<std::string_view, 5>{"ADDR", "DATA", "SELECT", "CLK", "EN"});
800 const auto width = cell.width("WIDTH");
801 const auto count = static_cast<std::size_t>(parseUnsigned(cell.parameter("SIZE"), cell.where()));
802 const auto abits = cell.width("ABITS");
803 if (!std::has_single_bit(count) || count > std::numeric_limits<int>::max()
804 || abits != std::max<std::size_t>(1, std::bit_width(count - 1)))
805 fail(cell.where(), "invalid canonical ROM geometry");
806 const bool synchronous = cell.flag("SYNC");
807 const bool positiveClock = cell.flag("CLK_POLARITY");
808 const auto init = binaryDigits(cell.parameter("INIT"), cell.where());
809 if (init.size() != count * width)
810 fail(cell.where(), "invalid canonical ROM initialization");
811 std::string bytes((init.size() + 7) / 8, '\0');
812 for (std::size_t bit = 0; bit < init.size(); ++bit)
813 if (init[init.size() - bit - 1] == '1')
814 bytes[bit / 8] = static_cast<char>(static_cast<unsigned char>(bytes[bit / 8]) | (1u << (bit % 8)));
815
816 const auto& id = cell.parameter("ID");
817 if (!id.is_string())
818 fail(cell.where(), "canonical ROM identifier must be a string");
819 std::string memoryName = id.get<std::string>();
820 if (!memoryName.empty() && memoryName.front() == '\\')
821 memoryName.erase(0, 1);
822 for (auto& character : memoryName)
823 if (character == '/' || character == '\\' || static_cast<unsigned char>(character) < 32
824 || static_cast<unsigned char>(character) == 127)
825 character = '_';
826 std::string assetName = std::format("{}_{}", moduleName, memoryName);
827 const auto attributes = raw.value("attributes", Json::object());
828 if (!attributes.is_object())
829 fail(cell.where(), "ROM attributes must be an object");
830 if (const auto attribute = attributes.find(std::string(attributes::BINARY_DOCUMENT));
831 attribute != attributes.end()) {
832 if (!attribute->is_string())
833 fail(cell.where(), "binary document attribute must be a string");
834 assetName = attribute->get<std::string>();
836 fail(cell.where(), "binary document attribute is not a valid document name");
837 }
838
839 Bus address = cell.consumer("ADDR", abits);
840 const Bus select = cell.consumer("SELECT", 1);
841 const Bus clockBus = cell.consumer("CLK", 1);
842 const Bus enableBus = cell.consumer("EN", 1);
843 if (count == 1 && !cell.rawConstant("ADDR", "0", abits))
844 fail(cell.where(), "one-word ROM requires a constant zero address");
845 if (!synchronous && (!cell.rawConstant("CLK", "0") || !cell.rawConstant("EN", "1")))
846 fail(cell.where(), "asynchronous ROM has invalid clock or enable");
847 Wire_ptr clock = clockBus[0];
848 if (synchronous && !positiveClock) {
849 const auto inverted = std::make_shared<Wire>();
850 addWithZeroDelay(std::make_shared<NotGate>(clock, inverted));
851 clock = inverted;
852 }
853 if (synchronous && count > 1) {
854 std::vector<Wire_ptr> data(address.begin(), address.end());
855 while (data.size() < 2)
856 data.push_back(constantWire("0", cell.where()));
857 Bus registeredAddress(static_cast<unsigned short>(data.size()));
858 addWithZeroDelay(std::make_shared<Register>(
859 Bus(std::move(data)), clock, enableBus[0], nullptr, registeredAddress));
860 address = slice(registeredAddress, 0, abits);
861 }
862
863 auto rom = std::make_shared<ROM>();
864 rom->setProperty("dataWidth", static_cast<int>(width));
865 rom->setProperty("binaryContents", assetName);
866 const Bus romOutput = synchronous && count == 1
867 ? Bus(static_cast<unsigned short>(width))
868 : cell.driver("DATA", width);
869 connectAndAdd(rom, {address, select,
870 readBus(Json::array({"1"}), ConnectionRole::Consumer, cell.where(), 1)},
871 {romOutput});
872 rom->refreshBinaryContents(std::make_shared<const std::string>(bytes), count);
873 if (synchronous && count == 1) {
874 const Bus registeredData = cell.driver("DATA", width);
875 std::vector<Wire_ptr> data(romOutput.begin(), romOutput.end());
876 std::vector<Wire_ptr> outputs(registeredData.begin(), registeredData.end());
877 while (data.size() < 2) {
878 data.push_back(constantWire("0", cell.where()));
879 outputs.push_back(std::make_shared<Wire>());
880 }
881 addWithZeroDelay(std::make_shared<Register>(
882 Bus(std::move(data)), clock, enableBus[0], nullptr, Bus(std::move(outputs))));
883 }
884 }
885
886 [[nodiscard]] static std::vector<Bus>
887 split(const Bus& packed, const std::size_t laneWidth, const std::size_t laneCount)
888 {
889 std::vector<Bus> lanes;
890 lanes.reserve(laneCount);
891 for (std::size_t lane = 0; lane < laneCount; ++lane)
892 lanes.push_back(slice(packed, lane * laneWidth, laneWidth));
893 return lanes;
894 }
895
896 [[nodiscard]] static std::size_t laneCount(const std::size_t selectionWidth,
897 const std::string_view type,
898 const std::string_view context)
899 {
900 if (selectionWidth >= std::numeric_limits<std::size_t>::digits)
901 fail(context, std::format("{} selection width is too large", type));
902 return std::size_t{1} << selectionWidth;
903 }
904
905 void connectAndAdd(Component_ptr component, std::vector<Bus> inputs,
906 std::vector<Bus> outputs)
907 {
908 component->setInputs(inputs);
909 component->setOutputs(outputs);
910 components.push_back(std::move(component));
911 }
912
913 void addWithZeroDelay(Component_ptr component,
914 const std::string_view property = "delay")
915 {
916 component->setProperty(property, 0);
917 components.push_back(std::move(component));
918 }
919
920 template <typename ComponentType>
921 void addMuxLike(const std::size_t selectionWidth, const std::size_t busWidth,
922 std::vector<Bus> inputs, std::vector<Bus> outputs)
923 {
924 auto component = std::make_shared<ComponentType>();
925 component->setProperty("selectionSize", static_cast<int>(selectionWidth));
926 component->setProperty("busSize", static_cast<int>(busWidth));
927 component->setProperty("delay", 0);
928 connectAndAdd(std::move(component), std::move(inputs), std::move(outputs));
929 }
930
931 template <typename FlipFlopType>
932 void addFlipFlop(std::shared_ptr<FlipFlopType> flipFlop, const bool positiveClock)
933 {
934 flipFlop->setProperty("triggerEdge",
935 positiveClock ? std::string("PET") : std::string("NET"));
936 addWithZeroDelay(std::move(flipFlop), "propagationDelay");
937 }
938
939 [[nodiscard]] std::pair<Bus, Bus> equalWidthUnary(const Cell& cell,
940 const std::string_view type)
941 {
942 cell.requireConnections({"A", "Y"});
943 const auto aWidth = cell.width("A_WIDTH");
944 const auto yWidth = cell.width("Y_WIDTH");
945 Bus a = cell.consumer("A", aWidth);
946 Bus y = cell.driver("Y", yWidth);
947 if (aWidth != yWidth)
948 fail(cell.where(),
949 std::format("{} requires equal input and output widths", type));
950 return {std::move(a), std::move(y)};
951 }
952
953 template <typename GateType> void importBinaryGate(const Cell& cell)
954 {
955 cell.requireConnections({"A", "B", "Y"});
956 const auto aWidth = cell.width("A_WIDTH");
957 const auto bWidth = cell.width("B_WIDTH");
958 const auto yWidth = cell.width("Y_WIDTH");
959 const Bus a = cell.consumer("A", aWidth);
960 const Bus b = cell.consumer("B", bWidth);
961 const Bus y = cell.driver("Y", yWidth);
962 if (aWidth != bWidth || aWidth != yWidth)
963 fail(cell.where(), "binary gate widths must match its connections");
964
965 auto gate = std::make_shared<GateType>();
966 gate->setProperty("bitwise", true);
967 gate->setProperty("size", static_cast<int>(yWidth));
968 gate->setProperty("delay", 0);
969 connectAndAdd(std::move(gate), {a, b}, {y});
970 }
971
972 template <typename GateType> void importFineBinaryGate(const Cell& cell)
973 {
974 cell.requireSchema(std::array<std::string_view, 0>{},
975 std::array<std::string_view, 3>{"A", "B", "Y"});
976 const Bus a = cell.consumer("A", 1);
977 const Bus b = cell.consumer("B", 1);
978 const Bus y = cell.driver("Y", 1);
979
980 auto gate = std::make_shared<GateType>(std::vector<Wire_ptr>{a[0], b[0]}, y[0]);
981 addWithZeroDelay(std::move(gate));
982 }
983
984 void importNot(const Cell& cell)
985 {
986 const auto [a, y] = equalWidthUnary(cell, "$not");
987 auto gate = std::make_shared<NotGate>(a[0], y[0]);
988 gate->setProperty("size", static_cast<int>(y.size()));
989 gate->setInputs({a});
990 gate->setOutputs({y});
991 addWithZeroDelay(std::move(gate));
992 }
993
994 void importSiliconLogic(const Cell& cell)
995 {
996 const auto mode = parseUnsigned(cell.parameter("MODE"), cell.where());
997 if (mode > 2)
998 fail(cell.where(), "invalid SILICON_LOGIC mode");
999 const auto aWidth = cell.width("A_WIDTH");
1000 if (mode == 2) {
1001 cell.requireSchema(std::to_array<std::string_view>({"MODE", "A_WIDTH"}),
1002 std::to_array<std::string_view>({"A", "Y"}));
1003 const Bus a = cell.consumer("A", aWidth);
1004 const Bus y = cell.driver("Y", 1);
1005 auto gate = std::make_shared<NotGate>(a[0], y[0]);
1006 gate->setInputs({a});
1007 gate->setOutputs({y});
1008 addWithZeroDelay(std::move(gate));
1009 return;
1010 }
1011 cell.requireSchema(std::to_array<std::string_view>({"MODE", "A_WIDTH", "B_WIDTH"}),
1012 std::to_array<std::string_view>({"A", "B", "Y"}));
1013 const Bus a = cell.consumer("A", aWidth);
1014 const Bus b = cell.consumer("B", cell.width("B_WIDTH"));
1015 const Bus y = cell.driver("Y", 1);
1016 if (mode == 0) {
1017 auto gate = std::make_shared<AndGate>();
1018 gate->setProperty("delay", 0);
1019 connectAndAdd(std::move(gate), {a, b}, {y});
1020 } else {
1021 auto gate = std::make_shared<OrGate>();
1022 gate->setProperty("delay", 0);
1023 connectAndAdd(std::move(gate), {a, b}, {y});
1024 }
1025 }
1026
1027 void importPos(const Cell& cell)
1028 {
1029 cell.requireConnections({"A", "Y"});
1030 const auto aWidth = cell.width("A_WIDTH");
1031 const auto yWidth = cell.width("Y_WIDTH");
1032 const Bus a = cell.consumer("A", aWidth);
1033 const Bus y = cell.driver("Y", yWidth);
1034
1035 if (aWidth != yWidth) {
1036 components.push_back(std::make_shared<Extender>(
1037 a, y,
1038 std::string(cell.flag("A_SIGNED") ? Extender::SIGNED_MODE
1040 return;
1041 }
1042
1043 auto merger = std::make_shared<WireMerger>();
1044 merger->setProperty("size", static_cast<int>(y.size()));
1045 connectAndAdd(std::move(merger), split(a, 1, a.size()), {y});
1046 }
1047
1048 void importAdd(const Cell& cell)
1049 {
1050 cell.requireConnections({"A", "B", "Y"});
1051 const bool signedArithmetic = cell.flag("A_SIGNED") && cell.flag("B_SIGNED");
1052 const auto aWidth = cell.width("A_WIDTH");
1053 const auto bWidth = cell.width("B_WIDTH");
1054 const auto yWidth = cell.width("Y_WIDTH");
1055 const Bus a = cell.consumer("A", aWidth);
1056 const Bus b = cell.consumer("B", bWidth);
1057 const Bus y = cell.driver("Y", yWidth);
1058
1059 const auto arithmeticWidth = std::max({aWidth, bWidth, yWidth});
1060 const Bus extendedA = resizeArithmeticOperand(a, arithmeticWidth, signedArithmetic);
1061 const Bus extendedB = resizeArithmeticOperand(b, arithmeticWidth, signedArithmetic);
1062
1063 auto sumWires = static_cast<std::vector<Wire_ptr>>(y);
1064 while (sumWires.size() < arithmeticWidth)
1065 sumWires.push_back(std::make_shared<Wire>(State::UNKNOWN));
1066
1067 auto adder = std::make_shared<AdderNBits>(std::array<Bus, 2>{extendedA, extendedB},
1068 Bus(std::move(sumWires)),
1069 std::make_shared<Wire>(State::UNKNOWN));
1070 addWithZeroDelay(std::move(adder));
1071 }
1072
1073 void importSiliconShift(const Cell& cell)
1074 {
1075 cell.requireSchema(
1076 std::to_array<std::string_view>({"WIDTH", "B_WIDTH", "DIRECTION", "ARITHMETIC"}),
1077 std::to_array<std::string_view>({"A", "B", "Y"}));
1078 const auto direction = parseUnsigned(cell.parameter("DIRECTION"), cell.where());
1079 const auto arithmetic = cell.flag("ARITHMETIC");
1080 if (direction > 1 || (direction == 0 && arithmetic))
1081 fail(cell.where(), "invalid SILICON_SHIFT mode");
1082 const auto width = cell.width("WIDTH");
1083 auto shifter = std::make_shared<Shifter>(cell.consumer("A", width),
1084 cell.consumer("B", cell.width("B_WIDTH")),
1085 cell.driver("Y", width));
1086 shifter->setProperty("mode", std::string(direction == 0 ? Shifter::LEFT_MODE
1088 shifter->setProperty("signed", arithmetic);
1089 addWithZeroDelay(std::move(shifter));
1090 }
1091
1092 [[nodiscard]] Bus resizeArithmeticOperand(const Bus& operand, const std::size_t width,
1093 const bool signExtend)
1094 {
1095 if (operand.size() > width)
1096 return slice(operand, 0, width);
1097 if (operand.size() == width)
1098 return operand;
1099
1100 Bus result(static_cast<unsigned short>(width));
1101 auto extender = std::make_shared<Extender>(
1102 operand, result,
1103 std::string(signExtend ? Extender::SIGNED_MODE : Extender::UNSIGNED_MODE));
1104 components.push_back(std::move(extender));
1105 return result;
1106 }
1107
1108 void importNeg(const Cell& cell)
1109 {
1110 cell.requireConnections({"A", "Y"});
1111 const auto aWidth = cell.width("A_WIDTH");
1112 const auto yWidth = cell.width("Y_WIDTH");
1113 const bool sign = cell.flag("A_SIGNED");
1114 const Bus a = cell.consumer("A", aWidth);
1115 const Bus y = cell.driver("Y", yWidth);
1116 auto complementer = std::make_shared<Complementer>(
1117 resizeArithmeticOperand(a, yWidth, sign), y);
1118 addWithZeroDelay(std::move(complementer));
1119 }
1120
1121 void importSub(const Cell& cell)
1122 {
1123 cell.requireConnections({"A", "B", "Y"});
1124 const auto aWidth = cell.width("A_WIDTH");
1125 const auto bWidth = cell.width("B_WIDTH");
1126 const auto yWidth = cell.width("Y_WIDTH");
1127 const bool signedArithmetic = cell.flag("A_SIGNED") && cell.flag("B_SIGNED");
1128 const Bus b = cell.consumer("B", bWidth);
1129 const Bus y = cell.driver("Y", yWidth);
1130
1131 const Bus a = cell.consumer("A", aWidth);
1132
1133 // Yosys evaluates binary arithmetic at the widest operand/result width, sign
1134 // extending only when both operands are signed, and then truncates to Y_WIDTH.
1135 const auto arithmeticWidth = std::max({aWidth, bWidth, yWidth});
1136 const Bus extendedA = resizeArithmeticOperand(a, arithmeticWidth, signedArithmetic);
1137 const Bus extendedB = resizeArithmeticOperand(b, arithmeticWidth, signedArithmetic);
1138
1139 Bus complementedB(static_cast<unsigned short>(arithmeticWidth));
1140 auto complementer = std::make_shared<Complementer>(extendedB, complementedB);
1141 addWithZeroDelay(std::move(complementer));
1142
1143 auto sumWires = static_cast<std::vector<Wire_ptr>>(y);
1144 while (sumWires.size() < arithmeticWidth)
1145 sumWires.push_back(std::make_shared<Wire>(State::UNKNOWN));
1146 Bus sum(std::move(sumWires));
1147
1148 auto adder =
1149 std::make_shared<AdderNBits>(std::array<Bus, 2>{extendedA, complementedB}, sum,
1150 std::make_shared<Wire>(State::UNKNOWN));
1151 addWithZeroDelay(std::move(adder));
1152 }
1153
1154 void importSiliconCompare(const Cell& cell)
1155 {
1156 cell.requireSchema(std::to_array<std::string_view>({"WIDTH", "MODE", "SIGNED"}),
1157 std::to_array<std::string_view>({"A", "B", "Y"}));
1158 const auto mode = parseUnsigned(cell.parameter("MODE"), cell.where());
1159 static constexpr std::array<std::string_view, 5> MODES{"==", "<", "<=", ">", ">="};
1160 if (mode >= MODES.size())
1161 fail(cell.where(), "invalid SILICON_COMPARE mode");
1162 const auto width = cell.width("WIDTH");
1163 const Bus a = cell.consumer("A", width);
1164 const Bus b = cell.consumer("B", width);
1165 const Bus y = cell.driver("Y", 1);
1166 auto comparator = std::make_shared<Comparator>(std::array<Bus, 2>{a, b}, y[0]);
1167 comparator->setProperty("mode", std::string(MODES[mode]));
1168 comparator->setProperty("signed", cell.flag("SIGNED"));
1169 addWithZeroDelay(std::move(comparator));
1170 }
1171
1172 void importSiliconGate(const Cell& cell)
1173 {
1174 cell.requireParameters({"MODE", "WIDTH", "INPUTS", "BITWISE"});
1175 const auto mode = parseUnsigned(cell.parameter("MODE"), cell.where());
1176 const auto width = cell.width("WIDTH");
1177 const auto count = cell.width("INPUTS");
1178 const auto bitwise = cell.flag("BITWISE");
1179 if (mode > 1 || count < 2 || (!bitwise && width != 1))
1180 fail(cell.where(), "invalid SILICON_GATE geometry or mode");
1181 std::vector<std::string> names{"Y"};
1182 std::vector<Bus> inputs;
1183 for (std::size_t i = 0; i < count; ++i) {
1184 names.push_back(std::format("A{}", i));
1185 inputs.push_back(cell.consumer(
1186 names.back(), bitwise ? std::optional<std::size_t>(width) : std::nullopt));
1187 }
1188 cell.requireKnownConnectionNames(names);
1190 mode == 0 ? std::static_pointer_cast<Component>(std::make_shared<AndGate>())
1191 : std::static_pointer_cast<Component>(std::make_shared<OrGate>());
1192 gate->setProperty("size", static_cast<int>(width));
1193 gate->setProperty("bitwise", bitwise);
1194 gate->setProperty("delay", 0);
1195 connectAndAdd(std::move(gate), std::move(inputs), {cell.driver("Y", width)});
1196 }
1197
1198 void importSiliconMux(const Cell& cell)
1199 {
1200 cell.requireSchema(
1201 std::to_array<std::string_view>({"WIDTH", "S_WIDTH", "INPUTS", "TABLE"}),
1202 std::to_array<std::string_view>({"A", "S", "Y"}));
1203 const auto width = cell.width("WIDTH");
1204 const auto selectionWidth = cell.width("S_WIDTH");
1205 if (selectionWidth > 15)
1206 fail(cell.where(), "SILICON_MUX selector is too wide");
1207 const auto lanes = std::size_t{1} << selectionWidth;
1208 const auto count = cell.width("INPUTS");
1209 const auto bits = binaryDigits(cell.parameter("TABLE"), cell.where());
1210 if (count > lanes || bits.size() != lanes * selectionWidth)
1211 fail(cell.where(), "invalid SILICON_MUX selection table geometry");
1212 std::string table;
1213 std::vector<bool> seen(count);
1214 for (std::size_t lane = 0; lane < lanes; ++lane) {
1215 const auto word =
1216 bits.substr(bits.size() - (lane + 1) * selectionWidth, selectionWidth);
1217 unsigned int index = 0;
1218 const auto [end, error] =
1219 std::from_chars(word.data(), word.data() + word.size(), index, 2);
1220 if (error != std::errc{} || end != word.data() + word.size() || index >= count)
1221 fail(cell.where(),
1222 "SILICON_MUX selection table index is outside its data inputs");
1223 seen[index] = true;
1224 if (!table.empty())
1225 table += ',';
1226 table += std::to_string(index);
1227 }
1228 if (std::ranges::find(seen, false) != seen.end())
1229 fail(cell.where(), "SILICON_MUX contains unused data inputs");
1230 auto mux = std::make_shared<Multiplexer>();
1231 mux->setProperty("selectionSize", static_cast<int>(selectionWidth));
1232 mux->setProperty("busSize", static_cast<int>(width));
1233 mux->setProperty("selectionTable", table);
1234 auto inputs = cell.consumerLanes("A", width, count);
1235 inputs.push_back(cell.consumer("S", selectionWidth));
1236 connectAndAdd(std::move(mux), std::move(inputs), {cell.driver("Y", width)});
1237 }
1238
1239 void importMux(const Cell& cell)
1240 {
1241 cell.requireConnections({"A", "B", "S", "Y"});
1242 const auto width = cell.width("WIDTH");
1243 const Bus a = cell.consumer("A", width);
1244 const Bus b = cell.consumer("B", width);
1245 const Bus s = cell.consumer("S", 1);
1246 const Bus y = cell.driver("Y", width);
1247
1248 std::vector<Bus> inputs{a, b, s};
1249 addMuxLike<Multiplexer>(1, width, std::move(inputs), {y});
1250 }
1251
1252 void importBmux(const Cell& cell)
1253 {
1254 cell.requireConnections({"A", "S", "Y"});
1255 const auto width = cell.width("WIDTH");
1256 const auto selectionWidth = cell.width("S_WIDTH");
1257 const auto lanes = laneCount(selectionWidth, "$bmux", cell.where());
1258 if (lanes > std::numeric_limits<std::size_t>::max() / width)
1259 fail(cell.where(), "$bmux packed input width is too large");
1260 const Bus s = cell.consumer("S", selectionWidth);
1261 const Bus y = cell.driver("Y", width);
1262
1263 // Read packed data one lane at a time for scalar and vector muxes alike. This
1264 // also preserves a fully literal lane as one correctly-sized constant.
1265 std::vector<Bus> inputs = cell.consumerLanes("A", width, lanes);
1266 inputs.push_back(s);
1267 addMuxLike<Multiplexer>(selectionWidth, width, std::move(inputs), {y});
1268 }
1269
1270 void importDemux(const Cell& cell)
1271 {
1272 cell.requireConnections({"A", "S", "Y"});
1273 const auto width = cell.width("WIDTH");
1274 const auto selectionWidth = cell.width("S_WIDTH");
1275 const auto lanes = laneCount(selectionWidth, "$demux", cell.where());
1276 if (lanes > std::numeric_limits<std::size_t>::max() / width)
1277 fail(cell.where(), "$demux packed output width is too large");
1278 const Bus a = cell.consumer("A", width);
1279 const Bus s = cell.consumer("S", selectionWidth);
1280 const Bus y = cell.driver("Y", width * lanes);
1281
1282 if (width == 1 && cell.rawConstant("A", "1")) {
1283 auto decoder = std::make_shared<Decoder>(a, s, y);
1284 decoder->setProperty("delay", 0);
1285 components.push_back(std::move(decoder));
1286 return;
1287 }
1288
1289 auto outputs = width == 1 ? std::vector<Bus>{y} : split(y, width, lanes);
1290 addMuxLike<Demultiplexer>(selectionWidth, width, {a, s}, std::move(outputs));
1291 }
1292
1293 void importAdffe(const Cell& cell)
1294 {
1295 cell.requireConnections({"CLK", "ARST", "EN", "D", "Q"});
1296 // Vector $adffe cells are already mapped to SILICON_PIPO. Only the scalar
1297 // zero-reset form can survive the technology map and reach this handler.
1298 if (cell.width("WIDTH") != 1)
1299 fail(cell.where(), "only scalar $adffe cells may remain after legalization");
1300 if (!cell.flag("EN_POLARITY") || !cell.flag("ARST_POLARITY"))
1301 fail(cell.where(), "only active-high EN and ARST are supported");
1302 if (!cell.zeroParameter("ARST_VALUE"))
1303 fail(cell.where(), "only an all-zero asynchronous reset value is supported");
1304
1305 auto dff = std::make_shared<EFlipFlop>(
1306 cell.consumerBit("D"), cell.consumerBit("EN"), cell.consumerBit("CLK"),
1307 cell.consumerBit("ARST"), nullptr, cell.driverBit("Q"),
1308 std::make_shared<Wire>());
1309 addFlipFlop(std::move(dff), cell.flag("CLK_POLARITY"));
1310 }
1311
1312 template <bool Enabled, bool SetReset> void importSiliconDff(const Cell& cell)
1313 {
1314 static constexpr auto PARAMETER_NAMES = [] {
1315 std::array<std::string_view, 1 + Enabled + 2 * SetReset> names{};
1316 std::size_t index = 0;
1317 names[index++] = "CLK_POLARITY";
1318 if constexpr (Enabled)
1319 names[index++] = "EN_POLARITY";
1320 if constexpr (SetReset) {
1321 names[index++] = "SET_POLARITY";
1322 names[index] = "CLR_POLARITY";
1323 }
1324 return names;
1325 }();
1326 static constexpr auto CONNECTION_NAMES = [] {
1327 std::array<std::string_view, 4 + Enabled + 2 * SetReset> names{};
1328 std::size_t index = 0;
1329 names[index++] = "D";
1330 if constexpr (Enabled)
1331 names[index++] = "EN";
1332 names[index++] = "CLK";
1333 if constexpr (SetReset) {
1334 names[index++] = "SET";
1335 names[index++] = "CLR";
1336 }
1337 names[index++] = "Q";
1338 names[index] = "QN";
1339 return names;
1340 }();
1341 cell.requireSchema(PARAMETER_NAMES, CONNECTION_NAMES);
1342
1343 if constexpr (Enabled) {
1344 if (!cell.flag("EN_POLARITY"))
1345 fail(cell.where(), "SILICON enabled flip-flops require active-high EN");
1346 }
1347 if constexpr (SetReset) {
1348 if (!cell.flag("SET_POLARITY") || !cell.flag("CLR_POLARITY"))
1349 fail(cell.where(), "SILICON flip-flops require active-high SET and CLR");
1350 }
1351
1352 const bool positive = cell.flag("CLK_POLARITY");
1353 const auto d = cell.consumerBit("D");
1354 const auto clock = cell.consumerBit("CLK");
1355 const auto enable = [&] {
1356 if constexpr (Enabled)
1357 return cell.consumerBit("EN");
1358 return Wire_ptr{};
1359 }();
1360 const auto set = [&] {
1361 if constexpr (SetReset)
1362 return cell.optionalActiveHighBit("SET");
1363 return Wire_ptr{};
1364 }();
1365 const auto clear = [&] {
1366 if constexpr (SetReset)
1367 return cell.optionalActiveHighBit("CLR");
1368 return Wire_ptr{};
1369 }();
1370 const auto q = cell.driverBit("Q");
1371 const auto qn = cell.driverBit("QN");
1372
1373 if constexpr (Enabled)
1374 addFlipFlop(std::make_shared<EFlipFlop>(d, enable, clock, clear, set, q, qn),
1375 positive);
1376 else
1377 addFlipFlop(std::make_shared<DFlipFlop>(d, clock, clear, set, q, qn), positive);
1378 }
1379
1380 void importSiliconJkff(const Cell& cell)
1381 {
1382 static constexpr auto PARAMETERS = std::to_array<std::string_view>(
1383 {"CLK_POLARITY", "SET_POLARITY", "CLR_POLARITY"});
1384 static constexpr auto CONNECTIONS =
1385 std::to_array<std::string_view>({"J", "K", "CLK", "SET", "CLR", "Q", "QN"});
1386 cell.requireSchema(PARAMETERS, CONNECTIONS);
1387 if (!cell.flag("SET_POLARITY") || !cell.flag("CLR_POLARITY"))
1388 fail(cell.where(), "SILICON_JKFF requires active-high SET and CLR");
1389
1390 auto flipFlop = std::make_shared<JKFlipFlop>(
1391 cell.consumerBit("J"), cell.consumerBit("K"), cell.consumerBit("CLK"),
1392 cell.optionalActiveHighBit("CLR"), cell.optionalActiveHighBit("SET"),
1393 cell.driverBit("Q"), cell.driverBit("QN"));
1394 addFlipFlop(std::move(flipFlop), cell.flag("CLK_POLARITY"));
1395 }
1396
1397 void importSiliconDlatch(const Cell& cell)
1398 {
1399 static constexpr auto PARAMETERS = std::to_array<std::string_view>({"EN_POLARITY"});
1400 static constexpr auto CONNECTIONS =
1401 std::to_array<std::string_view>({"D", "EN", "Q", "QN"});
1402 cell.requireSchema(PARAMETERS, CONNECTIONS);
1403 if (!cell.flag("EN_POLARITY"))
1404 fail(cell.where(), "SILICON_DLATCH requires active-high EN");
1405
1406 auto latch = std::make_shared<DLatch>(cell.consumerBit("D"), cell.consumerBit("EN"),
1407 cell.driverBit("Q"), cell.driverBit("QN"));
1408 addWithZeroDelay(std::move(latch), "propagationDelay");
1409 }
1410
1411 void importSiliconHalfAdder(const Cell& cell)
1412 {
1413 static constexpr std::array<std::string_view, 0> PARAMETERS{};
1414 static constexpr auto CONNECTIONS =
1415 std::to_array<std::string_view>({"A", "B", "SUM", "COUT"});
1416 cell.requireSchema(PARAMETERS, CONNECTIONS);
1417 auto adder = std::make_shared<HalfAdder>(
1418 std::array<Wire_ptr, 2>{cell.consumerBit("A"), cell.consumerBit("B")},
1419 cell.driverBit("SUM"), cell.driverBit("COUT"));
1420 addWithZeroDelay(std::move(adder));
1421 }
1422
1423 void importSiliconFullAdder(const Cell& cell)
1424 {
1425 static constexpr std::array<std::string_view, 0> PARAMETERS{};
1426 static constexpr auto CONNECTIONS =
1427 std::to_array<std::string_view>({"A", "B", "CIN", "SUM", "COUT"});
1428 cell.requireSchema(PARAMETERS, CONNECTIONS);
1429 auto adder = std::make_shared<FullAdder>(
1430 std::array<Wire_ptr, 2>{cell.consumerBit("A"), cell.consumerBit("B")},
1431 cell.consumerBit("CIN"), cell.driverBit("SUM"), cell.driverBit("COUT"));
1432 addWithZeroDelay(std::move(adder));
1433 }
1434
1435 void importSiliconAdder(const Cell& cell)
1436 {
1437 static constexpr auto PARAMETERS =
1438 std::to_array<std::string_view>({"WIDTH", "SIGNED"});
1439 static constexpr auto CONNECTIONS =
1440 std::to_array<std::string_view>({"A", "B", "SUM", "COUT"});
1441 cell.requireSchema(PARAMETERS, CONNECTIONS);
1442 const auto width = cell.width("WIDTH");
1443 if (cell.flag("SIGNED"))
1444 fail(cell.where(), "SILICON_ADDER supports unsigned operands only");
1445
1446 const auto a = cell.consumer("A", width);
1447 const auto b = cell.consumer("B", width);
1448 const auto sum = cell.driver("SUM", width);
1449 const auto cout = cell.driverBit("COUT");
1450 auto adder = std::make_shared<AdderNBits>(std::array<Bus, 2>{a, b}, sum, cout);
1451 addWithZeroDelay(std::move(adder));
1452 }
1453
1454 template <bool multiplication> void importSiliconMulDiv(const Cell& cell)
1455 {
1456 static constexpr auto PARAMETERS =
1457 std::to_array<std::string_view>({"WIDTH", "SIGNED"});
1458 if constexpr (multiplication)
1459 cell.requireSchema(PARAMETERS,
1460 std::to_array<std::string_view>({"A", "B", "PRODUCT"}));
1461 else
1462 cell.requireSchema(PARAMETERS, std::to_array<std::string_view>(
1463 {"A", "B", "div", "mod"}));
1464 const auto width = cell.width("WIDTH");
1465 const bool sign = cell.flag("SIGNED");
1466 const auto a = cell.consumer("A", width);
1467 const auto b = cell.consumer("B", width);
1468 Component_ptr component;
1469 if constexpr (multiplication)
1470 component = std::make_shared<Multiplier>(std::array<Bus, 2>{a, b},
1471 cell.driver("PRODUCT", width));
1472 else
1473 component = std::make_shared<Divider>(std::array<Bus, 2>{a, b},
1474 cell.driver("div", width),
1475 cell.driver("mod", width));
1476 component->setProperty("signed", sign);
1477 addWithZeroDelay(std::move(component));
1478 }
1479
1480 template <bool ParallelInput, bool ParallelOutput>
1481 void importSiliconRegister(const Cell& cell)
1482 {
1483 if constexpr (ParallelInput && !ParallelOutput) {
1484 static constexpr auto PARAMETERS = std::to_array<std::string_view>(
1485 {"WIDTH", "CLK_POLARITY", "EN_POLARITY", "CLR_POLARITY", "LOAD_POLARITY"});
1486 static constexpr auto CONNECTIONS =
1487 std::to_array<std::string_view>({"DATA", "CLK", "EN", "CLR", "LOAD", "OUT"});
1488 cell.requireSchema(PARAMETERS, CONNECTIONS);
1489 } else {
1490 static constexpr auto PARAMETERS = std::to_array<std::string_view>(
1491 {"WIDTH", "CLK_POLARITY", "EN_POLARITY", "CLR_POLARITY"});
1492 static constexpr auto CONNECTIONS =
1493 std::to_array<std::string_view>({"DATA", "CLK", "EN", "CLR", "OUT"});
1494 cell.requireSchema(PARAMETERS, CONNECTIONS);
1495 }
1496
1497 const auto width = cell.width("WIDTH");
1498 if (width <= 1)
1499 fail(cell.where(),
1500 std::format("{} WIDTH must be greater than one", cell.cellType()));
1501 if (!cell.flag("CLK_POLARITY") || !cell.flag("EN_POLARITY")
1502 || !cell.flag("CLR_POLARITY")) {
1503 fail(cell.where(),
1504 std::format("{} supports positive polarities only", cell.cellType()));
1505 }
1506 if constexpr (ParallelInput && !ParallelOutput) {
1507 if (!cell.flag("LOAD_POLARITY"))
1508 fail(cell.where(),
1509 std::format("{} supports positive polarities only", cell.cellType()));
1510 }
1511
1512 std::vector<Bus> inputs{cell.consumer("DATA", ParallelInput ? width : 1),
1513 Bus{cell.consumerBit("CLK")}, Bus{cell.consumerBit("EN")},
1514 Bus{cell.consumerBit("CLR")}};
1515 if constexpr (ParallelInput && !ParallelOutput)
1516 inputs.emplace_back(Bus{cell.consumerBit("LOAD")});
1517 std::vector<Bus> outputs{cell.driver("OUT", ParallelOutput ? width : 1)};
1518
1519 auto reg = std::make_shared<Register>();
1520 reg->setProperty("size", static_cast<int>(width));
1521 reg->setProperty("inputType", std::string(ParallelInput ? Register::PARALLEL_TYPE
1523 reg->setProperty("outputType", std::string(ParallelOutput ? Register::PARALLEL_TYPE
1525 reg->setProperty("delay", 0);
1526 connectAndAdd(std::move(reg), std::move(inputs), std::move(outputs));
1527 }
1528
1529 void importCell(const std::string_view name, const Json& cell)
1530 {
1531 using CellHandler = void (Importer::*)(const Cell&);
1532 static constexpr auto HANDLERS =
1533 std::to_array<std::pair<std::string_view, CellHandler>>({
1534 {cells::DFF, &Importer::importSiliconDff<false, false>},
1535 {cells::DFFE, &Importer::importSiliconDff<true, false>},
1536 {cells::DLATCH, &Importer::importSiliconDlatch},
1537 {cells::DFFSR, &Importer::importSiliconDff<false, true>},
1538 {cells::DFFSRE, &Importer::importSiliconDff<true, true>},
1539 {cells::JKFF, &Importer::importSiliconJkff},
1540 {cells::HALF_ADDER, &Importer::importSiliconHalfAdder},
1541 {cells::FULL_ADDER, &Importer::importSiliconFullAdder},
1542 {cells::ADDER, &Importer::importSiliconAdder},
1543 {cells::MULTIPLIER, &Importer::importSiliconMulDiv<true>},
1544 {cells::DIVIDER, &Importer::importSiliconMulDiv<false>},
1545 {cells::PIPO, &Importer::importSiliconRegister<true, true>},
1546 {cells::PISO, &Importer::importSiliconRegister<true, false>},
1547 {cells::SIPO, &Importer::importSiliconRegister<false, true>},
1548 {cells::SISO, &Importer::importSiliconRegister<false, false>},
1549 {"$and", &Importer::importBinaryGate<AndGate>},
1550 {"$or", &Importer::importBinaryGate<OrGate>},
1551 {"$xor", &Importer::importBinaryGate<XorGate>},
1552 {"$not", &Importer::importNot},
1553 {cells::LOGIC, &Importer::importSiliconLogic},
1554 {cells::GATE, &Importer::importSiliconGate},
1555 {cells::MUX, &Importer::importSiliconMux},
1556 {"$_NAND_", &Importer::importFineBinaryGate<NandGate>},
1557 {"$_NOR_", &Importer::importFineBinaryGate<NorGate>},
1558 {"$pos", &Importer::importPos},
1559 {"$add", &Importer::importAdd},
1560 {"$neg", &Importer::importNeg},
1561 {"$sub", &Importer::importSub},
1562 {cells::COMPARE, &Importer::importSiliconCompare},
1563 {cells::SHIFT, &Importer::importSiliconShift},
1564 {"$mux", &Importer::importMux},
1565 {"$bmux", &Importer::importBmux},
1566 {"$demux", &Importer::importDemux},
1567 {"$adffe", &Importer::importAdffe},
1568 });
1569
1570 Cell view(*this, cell, std::format("{}.cells.{}", moduleContext(), name));
1571 for (const auto& [type, handler] : HANDLERS) {
1572 if (view.cellType() == type)
1573 return (this->*handler)(view);
1574 }
1575
1576 const auto& modules = requireObjectMember(design, "modules", "design");
1577 if (const auto dependency = modules.find(view.cellType());
1578 dependency != modules.end()) {
1579 const auto attributes = dependency->find("attributes");
1580 const bool blackbox =
1581 attributes != dependency->end() && attributes->is_object()
1582 && attributes->contains("blackbox")
1583 && parseUnsigned(
1584 attributes->at("blackbox"),
1585 std::format("design.modules.{}.attributes.blackbox", view.cellType()))
1586 != 0;
1587 if (!blackbox)
1588 return importSubcircuit(view, *dependency);
1589 }
1590
1591 if (view.cellType().starts_with("SILICON_"))
1592 fail(view.where(), std::format("unsupported SILICON technology cell type '{}'",
1593 view.cellType()));
1594 fail(view.where(), std::format("unsupported cell type '{}'", view.cellType()));
1595 }
1596
1597 void importSubcircuit(const Cell& cell, const Json& dependencyModule)
1598 {
1599 if (!dependencyModule.is_object())
1600 fail(std::format("design.modules.{}", cell.cellType()), "expected an object");
1601 const auto& ports = requireObjectMember(
1602 dependencyModule, "ports", std::format("design.modules.{}", cell.cellType()));
1603 if (!ports.is_object())
1604 fail(std::format("design.modules.{}.ports", cell.cellType()),
1605 "expected an object");
1606
1607 std::vector<std::string> portNames;
1608 portNames.reserve(ports.size());
1609 for (const auto& [portName, _] : ports.items())
1610 portNames.push_back(portName);
1611 cell.requireKnownConnectionNames(portNames);
1612
1613 std::vector<Bus> inputs;
1614 std::vector<Bus> outputs;
1615 std::vector<std::string> inputNames;
1616 std::vector<std::string> outputNames;
1617 for (const auto& [portName, port] : ports.items()) {
1618 const auto context =
1619 std::format("design.modules.{}.ports.{}", cell.cellType(), portName);
1620 if (!port.is_object())
1621 fail(context, "expected an object");
1622 const auto& directionJson = requireObjectMember(port, "direction", context);
1623 const auto& bitsJson = requireObjectMember(port, "bits", context);
1624 if (!directionJson.is_string() || !bitsJson.is_array() || bitsJson.empty())
1625 fail(context, "expected a direction and a non-empty bit array");
1626
1627 const auto direction = directionJson.get<std::string>();
1628 if (direction == "input") {
1629 inputNames.push_back(portName);
1630 inputs.push_back(cell.consumer(portName, bitsJson.size()));
1631 } else if (direction == "output") {
1632 outputNames.push_back(portName);
1633 outputs.push_back(cell.optionalDriver(portName, bitsJson.size()));
1634 } else if (direction == "inout")
1635 fail(context, "inout ports are not supported");
1636 else
1637 fail(context, std::format("invalid port direction '{}'", direction));
1638 }
1639
1640 components.push_back(SubcircuitComponent::imported(
1641 cell.cellType(), std::move(inputNames), std::move(inputs),
1642 std::move(outputNames), std::move(outputs)));
1643 }
1644 };
1645
1646} // namespace
1647
1648void ModuleDependencyGraph::addModule(const std::string_view moduleName)
1649{
1650 ensureVertex(moduleName);
1651}
1652
1653void ModuleDependencyGraph::addDependency(const std::string_view from,
1654 const std::string_view to)
1655{
1656 const Vertex source = ensureVertex(from);
1657 const Vertex target = ensureVertex(to);
1658 boost::add_edge(source, target, graph);
1659}
1660
1663{
1664 enum class VisitState { Unvisited, Visiting, Visited };
1665 std::vector<VisitState> states(boost::num_vertices(graph), VisitState::Unvisited);
1666 ModuleNameList result;
1667 ModuleNameList stack;
1668
1669 std::function<void(Vertex)> visit = [&](const Vertex vertex) {
1670 if (states[vertex] == VisitState::Visited)
1671 return;
1672 if (states[vertex] == VisitState::Visiting) {
1673 const auto repeated = graph[vertex].name;
1674 const auto begin = std::ranges::find(stack, repeated);
1675 ModuleNameList cycle(begin, stack.end());
1676 cycle.push_back(repeated);
1677 std::string trace;
1678 for (const auto& module : cycle) {
1679 if (!trace.empty())
1680 trace += " -> ";
1681 trace += module;
1682 }
1683 throw std::runtime_error(
1684 std::format("Recursive Verilog module dependency detected: {}", trace));
1685 }
1686
1687 states[vertex] = VisitState::Visiting;
1688 stack.push_back(graph[vertex].name);
1689 auto dependencies = dependenciesOf(graph[vertex].name);
1690 for (const auto& dependency : dependencies)
1691 visit(*findVertex(dependency));
1692 stack.pop_back();
1693 states[vertex] = VisitState::Visited;
1694 result.push_back(graph[vertex].name);
1695 };
1696
1697 auto sortedRoots = roots;
1698 std::ranges::sort(sortedRoots);
1699 sortedRoots.erase(std::ranges::unique(sortedRoots).begin(), sortedRoots.end());
1700 for (const auto& root : sortedRoots) {
1701 const auto vertex = findVertex(root);
1702 if (!vertex)
1703 throw std::invalid_argument(std::format("Unknown Verilog module '{}'", root));
1704 visit(*vertex);
1705 }
1706 return result;
1707}
1708
1710ModuleDependencyGraph::dependenciesOf(const std::string_view moduleName) const
1711{
1712 const auto vertex = findVertex(moduleName);
1713 if (!vertex)
1714 return {};
1715
1716 ModuleNameList dependencies;
1717 for (const auto edge : boost::make_iterator_range(boost::out_edges(*vertex, graph)))
1718 dependencies.push_back(graph[boost::target(edge, graph)].name);
1719 std::ranges::sort(dependencies);
1720 return dependencies;
1721}
1722
1724{
1725 ModuleNameList names;
1726 names.reserve(boost::num_vertices(graph));
1727 for (const auto vertex : boost::make_iterator_range(boost::vertices(graph)))
1728 names.push_back(graph[vertex].name);
1729 std::ranges::sort(names);
1730 return names;
1731}
1732
1733bool ModuleDependencyGraph::containsModule(const std::string_view moduleName) const
1734{
1735 return findVertex(moduleName).has_value();
1736}
1737
1738std::optional<ModuleDependencyGraph::Vertex>
1739ModuleDependencyGraph::findVertex(std::string_view moduleName) const
1740{
1741 const auto it = nameToVertex.find(moduleName);
1742 if (it == nameToVertex.end())
1743 return std::nullopt;
1744 return it->second;
1745}
1746
1748ModuleDependencyGraph::ensureVertex(const std::string_view moduleName)
1749{
1750 if (const auto existing = findVertex(moduleName))
1751 return *existing;
1752 const auto vertex = boost::add_vertex(VertexProperty{std::string(moduleName)}, graph);
1753 nameToVertex.emplace(std::string(moduleName), vertex);
1754 return vertex;
1755}
1756
1758{
1759 nameToVertex.clear();
1760 for (const auto vertex : boost::make_iterator_range(boost::vertices(graph)))
1761 nameToVertex.emplace(graph[vertex].name, vertex);
1762}
1763
1765{
1766 try {
1767 const Json design = Json::parse(json);
1768 if (!design.is_object())
1769 throw std::runtime_error("Invalid Yosys JSON: design must be an object");
1770
1771 const auto modules = design.find("modules");
1772 if (modules == design.end() || !modules->is_object())
1773 throw std::runtime_error("Invalid Yosys JSON: design.modules must be an object");
1774
1775 const auto isBlackbox = [](const std::string& moduleName, const Json& module) {
1776 const auto attributes = module.find("attributes");
1777 if (attributes == module.end())
1778 return false;
1779 if (!attributes->is_object())
1780 throw std::runtime_error(std::format(
1781 "Invalid Yosys JSON: design.modules.{}.attributes must be an object",
1782 moduleName));
1783 const auto blackbox = attributes->find("blackbox");
1784 return blackbox != attributes->end()
1785 && parseUnsigned(
1786 *blackbox,
1787 std::format("design.modules.{}.attributes.blackbox", moduleName))
1788 != 0;
1789 };
1790
1791 ModuleDependencyGraph result;
1792 for (const auto& [moduleName, module] : modules->items()) {
1793 if (!module.is_object())
1794 throw std::runtime_error(std::format(
1795 "Invalid Yosys JSON: design.modules.{} must be an object", moduleName));
1796 if (!isBlackbox(moduleName, module))
1797 result.addModule(moduleName);
1798 }
1799
1800 for (const auto& [moduleName, module] : modules->items()) {
1801 if (!result.containsModule(moduleName))
1802 continue;
1803 const auto cells = module.find("cells");
1804 if (cells == module.end())
1805 continue;
1806 if (!cells->is_object())
1807 throw std::runtime_error(std::format(
1808 "Invalid Yosys JSON: design.modules.{}.cells must be an object", moduleName));
1809
1810 for (const auto& [cellName, cell] : cells->items()) {
1811 if (!cell.is_object())
1812 throw std::runtime_error(std::format(
1813 "Invalid Yosys JSON: design.modules.{}.cells.{} must be an object",
1814 moduleName, cellName));
1815 const auto type = cell.find("type");
1816 if (type == cell.end() || !type->is_string())
1817 throw std::runtime_error(std::format(
1818 "Invalid Yosys JSON: design.modules.{}.cells.{}.type must be a string",
1819 moduleName, cellName));
1820
1821 const auto dependency = type->get<std::string>();
1822 if (result.containsModule(dependency))
1823 result.addDependency(moduleName, dependency);
1824 }
1825 }
1826 return result;
1827 } catch (const nlohmann::json::exception& error) {
1828 throw std::runtime_error(std::format("Invalid Yosys JSON: {}", error.what()));
1829 }
1830}
1831
1832Circuit deserialize(const std::string_view json,
1833 const std::optional<std::string_view> moduleName)
1834{
1835 try {
1836 return Importer(Json::parse(json)).run(moduleName);
1837 } catch (const nlohmann::json::exception& error) {
1838 throw std::runtime_error(std::format("Invalid Yosys JSON: {}", error.what()));
1839 }
1840}
1841
1842} // namespace SILICON::yosys
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
static constexpr std::string_view SERIAL_TYPE
Definition register.hpp:33
static constexpr std::string_view PARALLEL_TYPE
Definition register.hpp:32
static std::shared_ptr< SubcircuitComponent > imported(std::string slug, std::vector< std::string > inputNames, std::vector< Bus > inputs, std::vector< std::string > outputNames, std::vector< Bus > outputs)
Creates an imported module instance before its project document exists.
static constexpr std::string_view UNSIGNED_MODE
static constexpr std::string_view SIGNED_MODE
static constexpr std::string_view RIGHT_MODE
static constexpr std::string_view LEFT_MODE
Module-instantiation dependency graph for a Yosys JSON design.
Definition netlist.hpp:58
std::vector< std::string > ModuleNameList
List of module names.
Definition netlist.hpp:61
NameToVertex nameToVertex
Name-to-vertex index kept in sync with graph.
Definition netlist.hpp:139
void rebuildNameIndex()
Rebuilds nameToVertex from the current graph.
Graph graph
The dependency graph itself.
Definition netlist.hpp:137
bool containsModule(std::string_view moduleName) const
Checks whether a module vertex is present in the graph.
ModuleNameList dependencyOrder(const ModuleNameList &roots) const
Returns the unique dependency closure of roots in dependency-first order.
void addDependency(std::string_view from, std::string_view to)
Records that from instantiates to.
ModuleNameList dependenciesOf(std::string_view moduleName) const
Returns the sorted, unique modules moduleName instantiates.
Vertex ensureVertex(std::string_view moduleName)
Ensures a module vertex exists in this graph (O(1)).
boost::graph_traits< Graph >::vertex_descriptor Vertex
Boost vertex descriptor (an integer index under vecS).
Definition netlist.hpp:72
void addModule(std::string_view moduleName)
Ensures a module vertex exists, creating it if necessary.
ModuleNameList modules() const
Returns every declared module name.
std::optional< Vertex > findVertex(std::string_view moduleName) const
int width(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
RTLIL::SigSpec port(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key, int expected)
std::optional< Gate > gate(Cell *cell, SigMap &signals)
std::optional< Mux > mux(Cell *cell, SigMap &signals)
bool flag(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
std::shared_ptr< Component > Component_ptr
std::shared_ptr< Wire > Wire_ptr
Definition wire.hpp:116
BusValue busValueFromBits(const std::string_view bits)
Strictly decodes an MSB-first raw string containing 0, 1, X, or E.
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
Definition wire.hpp:120
bool isValidDocumentSlug(const std::string_view slug)
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
constexpr std::string_view BINARY_DOCUMENT
Definition cells.hpp:51
constexpr std::string_view ADDER
Definition cells.hpp:38
constexpr std::string_view MUX
Definition cells.hpp:29
constexpr std::string_view COMPARE
Definition cells.hpp:26
constexpr std::string_view GATE
Definition cells.hpp:28
constexpr std::string_view LOGIC
Definition cells.hpp:25
constexpr std::string_view PISO
Definition cells.hpp:42
constexpr std::string_view DFFSRE
Definition cells.hpp:34
constexpr std::string_view DIVIDER
Definition cells.hpp:40
constexpr std::string_view SISO
Definition cells.hpp:44
constexpr std::string_view DFFSR
Definition cells.hpp:33
constexpr std::string_view SHIFT
Definition cells.hpp:27
constexpr std::string_view PIPO
Definition cells.hpp:41
constexpr std::string_view JKFF
Definition cells.hpp:35
constexpr std::string_view DLATCH
Definition cells.hpp:32
constexpr std::string_view MULTIPLIER
Definition cells.hpp:39
constexpr std::string_view FULL_ADDER
Definition cells.hpp:37
constexpr std::string_view SIPO
Definition cells.hpp:43
constexpr std::string_view DFF
Definition cells.hpp:30
constexpr std::string_view DFFE
Definition cells.hpp:31
constexpr std::string_view HALF_ADDER
Definition cells.hpp:36
Circuit deserialize(const std::string_view json, const std::optional< std::string_view > moduleName)
Deserialize one supported Yosys write_json module into a Silicon circuit.
ModuleDependencyGraph moduleDependencyGraph(const std::string_view json)
Build a module dependency graph from a Yosys write_json document.
nlohmann::ordered_json Json
Definition netlist.hpp:44
Per-vertex payload holding the declared module name.
Definition netlist.hpp:64