SILICON
Loading...
Searching...
No Matches
yosys_test_helpers.hpp
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#pragma once
19
22#include "tests.hpp"
23
24#include <algorithm>
25#include <array>
26#include <chrono>
27#include <cstdlib>
28#include <filesystem>
29#include <format>
30#include <fstream>
31#include <map>
32#include <memory>
33#include <ranges>
34#include <set>
35#include <string>
36#include <tuple>
37#include <vector>
38
39#include <core/circuit.hpp>
40#include <core/flipflops.hpp>
41#include <core/io.hpp>
42#include <core/memory.hpp>
46#include <core/register.hpp>
53#include <core/simulator.hpp>
54#include <core/subcircuit.hpp>
58#include <logging/logger.hpp>
59#include <nlohmann/json.hpp>
60
61using namespace SILICON::core;
62using namespace SILICON::extra;
63using namespace SILICON::logging;
64using namespace SILICON::simulation;
65using namespace SILICON::waveform;
66
67namespace {
68
69class YosysLogCapture {
70public:
71 YosysLogCapture()
72 : handle(Logger::addCallbackSink([this](const LogMessage& message) {
73 if (message.category == "yosys")
74 messages.push_back(message);
75 }))
76 {
77 }
78
79 ~YosysLogCapture() { Logger::removeSink(handle); }
80
81 [[nodiscard]] std::string text() const
82 {
83 std::string result;
84 for (const auto& message : messages)
85 result += message.message + '\n';
86 return result;
87 }
88
89private:
90 std::vector<LogMessage> messages;
91 Logger::SinkHandle handle;
92};
93
94class DefaultedInputYosysComponent : public Component {
95public:
96 DefaultedInputYosysComponent() : Component({Bus{Wire_ptr{}}}, {Bus(1)})
97 {
98 defineUnconnectedInputDefault(0, State::HIGH);
99 }
100
101 std::string_view typeName() const override { return "DefaultedInputYosys"; }
102 void simulate(Simulator&) override {}
103
104 void serializeYosys(SILICON::yosys::SerializationContext& context) const override
105 {
107 using SILICON::yosys::SerializationContext;
108 context.addCell("default_input", "$pos",
109 Json{{"A_SIGNED", SerializationContext::parameter(0, 1)},
110 {"A_WIDTH", SerializationContext::parameter(1)},
111 {"Y_WIDTH", SerializationContext::parameter(1)}},
112 Json{{"A", "input"}, {"Y", "output"}},
113 Json{{"A", context.inputBits(*this, 0, 1)},
114 {"Y", context.bits(outputBuses().at(0))}});
115 }
116};
117
118#if !defined(_WIN32) && !defined(__EMSCRIPTEN__)
119class PathEnvironmentGuard {
120public:
121 PathEnvironmentGuard()
122 {
123 if (const char* value = std::getenv("PATH"))
124 original = value;
125 setenv("PATH", "", 1);
126 }
127
128 ~PathEnvironmentGuard()
129 {
130 if (original)
131 setenv("PATH", original->c_str(), 1);
132 else
133 unsetenv("PATH");
134 }
135
136private:
137 std::optional<std::string> original;
138};
139#endif
140
141// Local composition of the primitive Yosys API (the convenience wrappers were
142// removed from the library): read and resolve parameters, then elaborate
143// preserving the module hierarchy, then deserialize into a Silicon circuit.
144[[nodiscard]] inline Circuit importVerilog(const std::string_view source,
145 const std::string_view topModule,
146 const SILICON::yosys::ToolOptions& options = {})
147{
150 topModule);
151}
152
153// Exercise the expression passes without unrelated synthesis or technology mapping.
154[[nodiscard]] inline std::string legalizeExpressions(std::string_view rawJson,
155 std::string_view passes = "silicon_logic\nsilicon_compare\nsilicon_shift")
156{
157#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
158 const auto directory = std::filesystem::temp_directory_path()
159 / std::format("silicon_expression_{}",
160 std::chrono::steady_clock::now().time_since_epoch().count());
161 std::filesystem::create_directories(directory);
162 const auto input = directory / "input.json";
163 const auto output = directory / "output.json";
164 try {
165 { std::ofstream file(input); file << rawJson; }
166 (void)SILICON::yosys::runScript(std::format(
167 "plugin -i \"{}\"\nread_json \"{}\"\n{}\nwrite_json \"{}\"",
168 SILICON_TEST_YOSYS_PLUGIN_PATH, input.string(), passes, output.string()));
169 std::ifstream file(output);
170 std::string result((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
171 std::filesystem::remove_all(directory);
172 return result;
173 } catch (...) {
174 std::filesystem::remove_all(directory);
175 throw;
176 }
177#else
178 return std::string(rawJson);
179#endif
180}
181
182[[nodiscard]] inline nlohmann::json exportComponent(const Component_ptr& component)
183{
184 Circuit circuit(component, false);
185 return nlohmann::json::parse(SILICON::yosys::serialize(circuit, "component_test"));
186}
187
188[[nodiscard]] inline nlohmann::json signalBits(int& nextSignal, const std::size_t width)
189{
190 auto bits = nlohmann::json::array();
191 for (std::size_t bit = 0; bit < width; ++bit)
192 bits.push_back(nextSignal++);
193 return bits;
194}
195
196[[nodiscard]] inline nlohmann::json subtractionDesign(const std::size_t aWidth,
197 const std::size_t bWidth,
198 const std::size_t yWidth,
199 const bool aSigned, const bool bSigned)
200{
203
204 int nextSignal = 2;
205 const Json aBits = signalBits(nextSignal, aWidth);
206 const Json bBits = signalBits(nextSignal, bWidth);
207 const Json yBits = signalBits(nextSignal, yWidth);
208 const Json parameters{
209 {"A_SIGNED", SerializationContext::parameter(aSigned, 1)},
210 {"B_SIGNED", SerializationContext::parameter(bSigned, 1)},
211 {"A_WIDTH", SerializationContext::parameter(aWidth)},
212 {"B_WIDTH", SerializationContext::parameter(bWidth)},
213 {"Y_WIDTH", SerializationContext::parameter(yWidth)},
214 };
215
216 return Json{{"creator", "test"},
217 {"modules",
218 {{"top",
219 {{"attributes", Json::object()},
220 {"ports",
221 {{"a", {{"direction", "input"}, {"bits", aBits}}},
222 {"b", {{"direction", "input"}, {"bits", bBits}}},
223 {"y", {{"direction", "output"}, {"bits", yBits}}}}},
224 {"cells",
225 {{"subtract",
226 {{"type", "$sub"},
227 {"parameters", parameters},
228 {"connections", {{"A", aBits}, {"B", bBits}, {"Y", yBits}}}}}}},
229 {"netnames", Json::object()}}}}}};
230}
231
232[[nodiscard]] inline nlohmann::json comparisonDesign(const std::string_view type,
233 const std::size_t aWidth,
234 const std::size_t bWidth,
235 const std::size_t yWidth,
236 const bool aSigned, const bool bSigned)
237{
240
241 int nextSignal = 2;
242 const Json aBits = signalBits(nextSignal, aWidth);
243 const Json bBits = signalBits(nextSignal, bWidth);
244 const Json yBits = signalBits(nextSignal, yWidth);
245
246 return Json{{"creator", "test"},
247 {"modules",
248 {{"top",
249 {{"attributes", Json::object()},
250 {"ports",
251 {{"a", {{"direction", "input"}, {"bits", aBits}}},
252 {"b", {{"direction", "input"}, {"bits", bBits}}},
253 {"y", {{"direction", "output"}, {"bits", yBits}}}}},
254 {"cells",
255 {{"compare",
256 {{"type", type},
257 {"parameters",
258 {{"A_SIGNED", SerializationContext::parameter(aSigned, 1)},
259 {"B_SIGNED", SerializationContext::parameter(bSigned, 1)},
260 {"A_WIDTH", SerializationContext::parameter(aWidth)},
261 {"B_WIDTH", SerializationContext::parameter(bWidth)},
262 {"Y_WIDTH", SerializationContext::parameter(yWidth)}}},
263 {"connections", {{"A", aBits}, {"B", bBits}, {"Y", yBits}}}}}}},
264 {"netnames", Json::object()}}}}}};
265}
266
267[[nodiscard]] inline BusValue evaluateBinaryCircuit(const std::shared_ptr<Circuit>& circuit,
268 const unsigned int a, const unsigned int b)
269{
270 std::map<std::string, std::shared_ptr<DummyBusInputComponent>> inputs;
271 Component_ptr output;
272 for (const auto vertex :
273 boost::make_iterator_range(boost::vertices(circuit->getGraph()))) {
274 const auto& component = circuit->getGraph()[vertex].component;
275 if (auto input = std::dynamic_pointer_cast<DummyBusInputComponent>(component))
276 inputs.emplace(input->getPropertyValue<std::string>("name").value_or(""), input);
277 if (std::dynamic_pointer_cast<DummyOutputComponent>(component)
278 || std::dynamic_pointer_cast<DummyBusOutputComponent>(component))
279 output = component;
280 }
281
282 if (!inputs.contains("a") || !inputs.contains("b") || !output)
283 throw std::runtime_error("Expected named binary circuit boundary components");
284 inputs.at("a")->setBusValue(valueFor(inputs.at("a")->outputBuses()[0], a));
285 inputs.at("b")->setBusValue(valueFor(inputs.at("b")->outputBuses()[0], b));
286 Simulator simulator(circuit);
287 if (simulator.runUntilIdle() != Simulator::RunResult::Completed)
288 throw std::runtime_error("Binary circuit simulation did not complete");
289 return output->inputBuses()[0].getCurrentValue();
290}
291
292[[nodiscard]] inline std::multiset<std::string> cellTypes(const nlohmann::json& module)
293{
294 std::multiset<std::string> result;
295 for (const auto& cell : module.at("cells"))
296 result.insert(cell.at("type").get<std::string>());
297 return result;
298}
299
300template <typename ComponentType>
301[[nodiscard]] inline std::shared_ptr<ComponentType>
302findNamedComponent(const Circuit& circuit, const std::string_view name)
303{
304 for (const auto& component : componentsIn(circuit)) {
305 auto candidate = std::dynamic_pointer_cast<ComponentType>(component);
306 if (candidate
307 && candidate->template getPropertyValue<std::string>("name").value_or("")
308 == name) {
309 return candidate;
310 }
311 }
312 return nullptr;
313}
314
315[[nodiscard]] inline const nlohmann::json& onlyModule(const nlohmann::json& design)
316{
317 return design.at("modules").begin().value();
318}
319
320[[nodiscard]] inline nlohmann::json& onlyModule(nlohmann::json& design)
321{
322 return design.at("modules").begin().value();
323}
324
325[[nodiscard]] inline const nlohmann::json& onlyCell(const nlohmann::json& design)
326{
327 return onlyModule(design).at("cells").begin().value();
328}
329
330template <typename ComponentType>
331[[nodiscard]] inline std::shared_ptr<ComponentType> findComponent(const Circuit& circuit)
332{
333 for (const auto vertex :
334 boost::make_iterator_range(boost::vertices(circuit.getGraph()))) {
335 if (auto component = std::dynamic_pointer_cast<ComponentType>(
336 circuit.getGraph()[vertex].component))
337 return component;
338 }
339 return nullptr;
340}
341
342[[nodiscard]] inline Circuit circuitWithBoundaryPorts(const Component_ptr& component)
343{
344 Component_set components{component};
345 for (std::size_t index = 0; index < component->inputBuses().size(); ++index) {
346 components.insert(std::make_shared<DummyBusInputComponent>(
347 component->inputBuses()[index], std::format("input_{}", index)));
348 }
349 for (std::size_t index = 0; index < component->outputBuses().size(); ++index) {
350 components.insert(std::make_shared<DummyBusOutputComponent>(
351 component->outputBuses()[index], std::format("output_{}", index)));
352 }
353 Circuit circuit(components, false);
354 return circuit;
355}
356
357[[nodiscard]] inline std::shared_ptr<Register>
358registerWithMode(const bool parallelInput, const bool parallelOutput, const int width = 4)
359{
360 auto reg = std::make_shared<Register>(
361 Bus(static_cast<unsigned short>(width)), std::make_shared<Wire>(),
362 std::make_shared<Wire>(), std::make_shared<Wire>(),
363 Bus(static_cast<unsigned short>(width)));
364 reg->setProperty("inputType", std::string(parallelInput ? Register::PARALLEL_TYPE
366 reg->setProperty("outputType", std::string(parallelOutput ? Register::PARALLEL_TYPE
368 return reg;
369}
370
371#ifdef SILICON_TEST_YOSYS_EXECUTABLE
372[[nodiscard]] inline int validateWithYosys(const Circuit& circuit, const std::string_view tag)
373{
374 const auto path =
375 std::filesystem::temp_directory_path() / std::format("silicon_yosys_{}.json", tag);
376 {
377 std::ofstream output(path);
378 if (!output.good())
379 return -1;
380 output << SILICON::yosys::serialize(circuit, "top");
381 }
382
383 int result = 0;
384 try {
385 const SILICON::yosys::ToolOptions options{
386 .executable = std::filesystem::path(SILICON_TEST_YOSYS_EXECUTABLE),
387 .technologyLibraryDirectory = std::nullopt};
389 std::format("read_verilog -lib -D SILICON_BLACKBOX \"{}/silicon_cells.v\"\n"
390 "read_json \"{}\"\n"
391 "hierarchy -check -top top\n"
392 "check -assert\n",
393 SILICON_TEST_YOSYS_RESOURCE_DIR, path.string()),
394 options);
395 } catch (const std::runtime_error&) {
396 result = 1;
397 }
398 std::filesystem::remove(path);
399 return result;
400}
401
402#ifdef SILICON_TEST_YOSYS_PLUGIN_PATH
403inline void runPluginScript(const std::string_view source, const std::string_view commands,
404 const std::string_view tag)
405{
406 const auto path =
407 std::filesystem::temp_directory_path()
408 / std::format("silicon_yosys_{}_{}.v", tag,
409 std::chrono::steady_clock::now().time_since_epoch().count());
410 {
411 std::ofstream output(path);
412 if (!output.good())
413 throw std::runtime_error("Could not create temporary Verilog source");
414 output << source;
415 }
416
417 try {
418 const SILICON::yosys::ToolOptions options{
419 .executable = std::filesystem::path(SILICON_TEST_YOSYS_EXECUTABLE),
420 .technologyLibraryDirectory = std::nullopt};
422 std::format("plugin -i \"{}\"\nread_verilog \"{}\"\n{}",
423 SILICON_TEST_YOSYS_PLUGIN_PATH, path.string(), commands),
424 options);
425 } catch (...) {
426 std::filesystem::remove(path);
427 throw;
428 }
429 std::filesystem::remove(path);
430}
431#endif
432#endif
433
434} // namespace
std::vector< Component_ptr > componentsIn(const Circuit &circuit)
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
const CircuitGraph & getGraph() const
Gets the underlying circuit graph.
Definition circuit.hpp:349
Base class for all digital circuit components.
static constexpr std::string_view SERIAL_TYPE
Definition register.hpp:33
static constexpr std::string_view PARALLEL_TYPE
Definition register.hpp:32
std::size_t SinkHandle
Definition logger.hpp:28
static void removeSink(SinkHandle handle)
Definition logger.cpp:258
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
Mutable module-building interface passed to component serializers.
Definition netlist.hpp:174
Json bits(const core::Bus &bus, std::string_view nullValue="x") const
Convert a Silicon bus to a Yosys least-significant-bit-first vector.
Definition netlist.cpp:276
static std::string parameter(std::uint64_t value, std::size_t width=32)
Encode an unsigned Yosys parameter as a fixed-width binary string.
Definition netlist.cpp:331
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.
Definition netlist.cpp:290
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.
Definition netlist.cpp:346
int width(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
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
Definition wire.hpp:54
std::vector< State > BusValue
Definition wire.hpp:120
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
std::string read(const std::string_view source, const yosys::ToolOptions &options)
Definition verilog.cpp:477
std::string elaborateHierarchy(const std::string_view json, const ToolOptions &options)
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.
ScriptResult runScript(const std::string_view script, const ToolOptions &options)
std::string serialize(const Circuit &circuit, const std::string_view moduleName)
Serialize a complete Silicon circuit as Yosys write_json-compatible JSON.
Definition netlist.cpp:443
nlohmann::ordered_json Json
Definition netlist.hpp:44
BusValue valueFor(const Bus &bus, const std::uint64_t value)
Definition tests.hpp:11