SILICON
Loading...
Searching...
No Matches
yosys_cells.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
19
20namespace {
21nlohmann::json gateTreeDesign(const bool conjunction)
22{
23 using Json = nlohmann::json;
25 Json ports = Json::object();
26 for (int i = 0; i < 4; ++i)
27 ports[std::string(1, 'a' + i)] = {{"direction", "input"},
28 {"bits", Json::array({2 + 2 * i, 3 + 2 * i})}};
29 ports["y"] = {{"direction", "output"}, {"bits", Json::array({14, 15})}};
30 const Json parameters{{"A_SIGNED", SerializationContext::parameter(0, 1)},
31 {"B_SIGNED", SerializationContext::parameter(0, 1)},
32 {"A_WIDTH", SerializationContext::parameter(2)},
33 {"B_WIDTH", SerializationContext::parameter(2)},
34 {"Y_WIDTH", SerializationContext::parameter(2)}};
35 const auto cell = [&](const Json& a, const Json& b, const Json& y) {
36 return Json{{"type", conjunction ? "$and" : "$or"},
37 {"parameters", parameters},
38 {"connections", {{"A", a}, {"B", b}, {"Y", y}}}};
39 };
40 const Json cells{{"left", cell({2, 3}, {4, 5}, {10, 11})},
41 {"right", cell({6, 7}, {8, 9}, {12, 13})},
42 {"root", cell({10, 11}, {12, 13}, {14, 15})}};
43 return Json{{"modules", {{"top", {{"ports", ports}, {"cells", cells}}}}}};
44}
45Circuit importGateStructure(const nlohmann::json& design)
46{
48 legalizeExpressions(design.dump(), "silicon_logic\nsilicon_gates"));
49}
50} // namespace
51
52TEST(YosysTest, CollapsesGateTreesWithFourStateAndBusSemantics)
53{
54#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
55 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
56#endif
57 for (const bool logical : {false, true})
58 for (const bool conjunction : {false, true}) {
59 SCOPED_TRACE(conjunction);
60 SCOPED_TRACE(logical);
61 auto design = gateTreeDesign(conjunction);
62 if (logical) {
63 auto& module = onlyModule(design);
64 module["ports"]["y"]["bits"] = nlohmann::json::array({14});
65 for (auto& cell : module["cells"]) {
66 cell["type"] = conjunction ? "$logic_and" : "$logic_or";
67 cell["parameters"]["Y_WIDTH"] =
69 cell["connections"]["Y"].erase(1);
70 }
71 auto& root = module["cells"]["root"];
72 for (const auto port : {"A", "B"}) {
73 root["parameters"][std::string(port) + "_WIDTH"] =
75 root["connections"][port].erase(1);
76 }
77 }
78 auto circuit = std::make_shared<Circuit>(importGateStructure(design));
79 const auto type = conjunction ? "AndGate" : "OrGate";
80 EXPECT_EQ(componentTypes(*circuit).count(type), 1);
81 for (const auto& component : componentsIn(*circuit)) {
82 if (component->typeName() == type) {
83 ASSERT_EQ(component->inputBuses().size(), 4);
84 }
85 }
86
87 ComponentRegistry registry;
88 registerAllComponents(registry);
89 circuit =
90 std::make_shared<Circuit>(Circuit::deserialize(circuit->serialize(), registry));
91#ifdef SILICON_TEST_YOSYS_EXECUTABLE
92 circuit = std::make_shared<Circuit>(importVerilog(
94 "top"));
95 EXPECT_EQ(componentTypes(*circuit).count(type), 1);
96#endif
97
98 std::array<std::shared_ptr<DummyBusInputComponent>, 4> inputs;
99 for (std::size_t i = 0; i < inputs.size(); ++i) {
100 inputs[i] =
101 findNamedComponent<DummyBusInputComponent>(*circuit, std::string(1, 'a' + i));
102 ASSERT_TRUE(inputs[i]);
103 }
104 const auto output = findNamedComponent<BoundaryIoComponent>(*circuit, "y");
105 ASSERT_TRUE(output);
106 Simulator simulator(circuit);
107 constexpr std::array states{State::LOW, State::HIGH, State::UNKNOWN, State::ERROR};
108 for (unsigned int pattern = 0; pattern < 256; ++pattern) {
109 BusValue expected(logical ? 1 : 2, conjunction ? State::HIGH : State::LOW);
110 for (std::size_t i = 0; i < inputs.size(); ++i) {
111 const auto index = (pattern >> (2 * i)) & 3;
112 const BusValue value{states[index], states[(index + 1) & 3]};
113 simulator.setBus(inputs[i]->outputBuses()[0], value);
114 if (logical) {
115 State truth = State::LOW;
116 for (const auto state : value)
117 truth = truth || state;
118 expected[0] = conjunction ? expected[0] && truth : expected[0] || truth;
119 } else
120 for (std::size_t bit = 0; bit < value.size(); ++bit)
121 expected[bit] =
122 conjunction ? expected[bit] && value[bit] : expected[bit] || value[bit];
123 }
124 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
125 EXPECT_EQ(output->inputBuses()[0].getCurrentValue(), expected);
126 }
127 }
128}
129
130TEST(YosysTest, KeepsSharedGateOutputsAndBitTaps)
131{
132#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
133 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
134#endif
136 for (const bool conjunction : {false, true})
137 for (const auto& tap : {Json::array({10, 11}), Json::array({10})}) {
138 auto design = gateTreeDesign(conjunction);
139 onlyModule(design)["ports"]["tap"] = {{"direction", "output"}, {"bits", tap}};
140 const auto circuit = importGateStructure(design);
141 EXPECT_EQ(componentTypes(circuit).count(conjunction ? "AndGate" : "OrGate"), 2);
142 }
143
144 auto mixed = gateTreeDesign(true);
145 onlyModule(mixed)["cells"]["root"]["type"] = "$or";
146 const auto circuit = importGateStructure(mixed);
147 EXPECT_EQ(componentTypes(circuit).count("AndGate"), 2);
148 EXPECT_EQ(componentTypes(circuit).count("OrGate"), 1);
149}
150
151TEST(YosysTest, LeavesGateFeedbackLoopsIntact)
152{
153#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
154 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
155#endif
156 auto design = gateTreeDesign(true);
157 onlyModule(design)["cells"]["left"]["connections"]["A"] =
158 SILICON::yosys::Json::array({14, 15});
159 const auto circuit = importGateStructure(design);
160 // Reject the whole proposed contraction when it reaches the root again.
161 EXPECT_EQ(componentTypes(circuit).count("AndGate"), 3);
162}
163
164TEST(YosysTest, GatePassRespectsSelectionKeepAndRepeatedRuns)
165{
166#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
167 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
168#endif
169 using Json = nlohmann::json;
170 const auto source = gateTreeDesign(true);
171 const auto first = Json::parse(legalizeExpressions(source.dump(), "silicon_gates"));
172 ASSERT_EQ(onlyModule(first).at("cells").size(), 1);
173 EXPECT_EQ(onlyCell(first).at("type"), "SILICON_GATE");
174 EXPECT_EQ(Json::parse(legalizeExpressions(first.dump(), "silicon_gates")).at("modules"),
175 first.at("modules"));
176 const auto selected = Json::parse(
177 legalizeExpressions(source.dump(), "select top/root\nsilicon_gates\nselect *"));
178 EXPECT_EQ(onlyModule(selected).at("cells").size(), 3);
179
180 auto kept = source;
181 onlyModule(kept)["cells"]["left"]["attributes"]["keep"] = "1";
182 EXPECT_EQ(componentTypes(importGateStructure(kept)).count("AndGate"), 2);
183 kept = source;
184 onlyModule(kept)["netnames"]["left_alias"] = {
185 {"hide_name", 0}, {"bits", Json::array({10, 11})}, {"attributes", {{"keep", "1"}}}};
186 EXPECT_EQ(componentTypes(importGateStructure(kept)).count("AndGate"), 2);
187
188 for (const auto& parameter : {"MODE", "INPUTS", "BITWISE", "WIDTH"}) {
189 auto malformed = first;
190 onlyModule(malformed)["cells"]["root"]["parameters"].erase(parameter);
191 EXPECT_THROW((void)SILICON::yosys::deserialize(malformed.dump()), std::runtime_error);
192 }
193 auto malformed = first;
194 onlyModule(malformed)["cells"]["root"]["connections"]["A0"] = Json::array({2});
195 EXPECT_THROW((void)SILICON::yosys::deserialize(malformed.dump()), std::runtime_error);
196}
197
198TEST(YosysTest, ExportsNamedPortsAndNativeGate)
199{
200 auto a = std::make_shared<Wire>();
201 auto b = std::make_shared<Wire>();
202 auto y = std::make_shared<Wire>();
203 Component_set components{
204 std::make_shared<DummyInputComponent>(Bus{a}, "a"),
205 std::make_shared<DummyInputComponent>(Bus{b}, "b"),
206 std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, y),
207 std::make_shared<DummyOutputComponent>(Bus{y}, "y"),
208 };
209 Circuit circuit(components, false);
210
211 const auto json = nlohmann::json::parse(SILICON::yosys::serialize(circuit, "top"));
212 const auto& module = json.at("modules").at("top");
213 EXPECT_EQ(module.at("ports").at("a").at("direction"), "input");
214 EXPECT_EQ(module.at("ports").at("b").at("direction"), "input");
215 EXPECT_EQ(module.at("ports").at("y").at("direction"), "output");
216 EXPECT_EQ(cellTypes(module), std::multiset<std::string>{"$and"});
217}
218
219TEST(YosysTest, MakesDuplicateBoundaryNamesUnique)
220{
221 auto a = std::make_shared<Wire>();
222 auto b = std::make_shared<Wire>();
223 Circuit circuit(Component_set{std::make_shared<DummyInputComponent>(Bus{a}, "signal"),
224 std::make_shared<DummyOutputComponent>(Bus{b}, "signal")},
225 false);
226 const auto json = nlohmann::json::parse(SILICON::yosys::serialize(circuit, "top"));
227 const auto& ports = onlyModule(json).at("ports");
228 EXPECT_TRUE(ports.contains("signal"));
229 EXPECT_TRUE(ports.contains("signal_2"));
230}
231
232TEST(YosysTest, LowersCombinationalComponents)
233{
234 auto a = std::make_shared<Wire>();
235 auto b = std::make_shared<Wire>();
236 auto c = std::make_shared<Wire>();
237 auto y = std::make_shared<Wire>();
238 auto carry = std::make_shared<Wire>();
239
240 EXPECT_EQ(cellTypes(onlyModule(exportComponent(
241 std::make_shared<NandGate>(std::vector<Wire_ptr>{a, b, c}, y)))),
242 (std::multiset<std::string>{"$and", "$and", "$not"}));
243 EXPECT_EQ(cellTypes(onlyModule(exportComponent(std::make_shared<FullAdder>(
244 std::array<Wire_ptr, 2>{a, b}, c, y, carry)))),
245 std::multiset<std::string>{"SILICON_FULL_ADDER"});
246
247 auto adder = std::make_shared<AdderNBits>(std::array<Bus, 2>{Bus(4), Bus(4)}, Bus(4),
248 std::make_shared<Wire>());
249 EXPECT_EQ(cellTypes(onlyModule(exportComponent(adder))),
250 std::multiset<std::string>{"SILICON_ADDER"});
251
252 auto extender = std::make_shared<Extender>(Bus(3), Bus(5));
253 EXPECT_EQ(cellTypes(onlyModule(exportComponent(extender))),
254 std::multiset<std::string>{"$pos"});
255
256 auto mux = std::make_shared<Multiplexer>(Bus(4), Bus(2), std::make_shared<Wire>());
257 EXPECT_EQ(cellTypes(onlyModule(exportComponent(mux))),
258 std::multiset<std::string>{"$bmux"});
259
260 auto demux = std::make_shared<Demultiplexer>(Bus(1), Bus(2), Bus(4));
261 EXPECT_EQ(cellTypes(onlyModule(exportComponent(demux))),
262 std::multiset<std::string>{"$demux"});
263
264 auto decoder = std::make_shared<Decoder>(Bus(1), Bus(2), Bus(4));
265 EXPECT_EQ(cellTypes(onlyModule(exportComponent(decoder))),
266 std::multiset<std::string>{"$demux"});
267
268 auto splitter =
269 std::make_shared<WireSplitter>(Bus(2), std::vector<Bus>{Bus(1), Bus(1)});
270 auto merger = std::make_shared<WireMerger>(std::vector<Bus>{Bus(1), Bus(1)}, Bus(2));
271 EXPECT_EQ(cellTypes(onlyModule(exportComponent(splitter))),
272 std::multiset<std::string>{"$pos"});
273 EXPECT_EQ(cellTypes(onlyModule(exportComponent(merger))),
274 std::multiset<std::string>{"$pos"});
275}
276
277TEST(YosysTest, ExportsUnusedAdderCarryOutput)
278{
279 auto adder =
280 std::make_shared<AdderNBits>(std::array<Bus, 2>{Bus(4), Bus(4)}, Bus(4), nullptr);
281
282 const auto exported = exportComponent(adder);
283 const auto& carry = onlyCell(exported).at("connections").at("COUT");
284 ASSERT_EQ(carry.size(), 1);
285 EXPECT_TRUE(carry.at(0).is_number_integer());
286 EXPECT_NO_THROW((void)SILICON::yosys::deserialize(exported.dump()));
287}
288
289TEST(YosysTest, EncodesDeclaredUnconnectedInputDefault)
290{
291 const auto exported = exportComponent(std::make_shared<DefaultedInputYosysComponent>());
292 const auto& input = onlyCell(exported).at("connections").at("A");
293 ASSERT_EQ(input.size(), 1);
294 EXPECT_EQ(input.at(0), "1");
295 EXPECT_NO_THROW((void)SILICON::yosys::deserialize(exported.dump()));
296}
297
298TEST(YosysTest, ExtenderLowersToPosAndRoundTripsWithItsModeAndWidths)
299{
300 auto extender =
301 std::make_shared<Extender>(Bus(3), Bus(6), std::string(Extender::SIGNED_MODE));
302 auto exported = exportComponent(extender);
303 EXPECT_EQ(cellTypes(onlyModule(exported)), std::multiset<std::string>{"$pos"});
304
305 const auto& cell = onlyCell(exported);
306 EXPECT_EQ(cell.at("parameters").at("A_SIGNED"),
308 EXPECT_EQ(cell.at("parameters").at("A_WIDTH"),
310 EXPECT_EQ(cell.at("parameters").at("Y_WIDTH"),
312
313 const Circuit imported = SILICON::yosys::deserialize(exported.dump());
314 const auto restored = findComponent<Extender>(imported);
315 ASSERT_TRUE(restored);
316 EXPECT_EQ(restored->getPropertyValue<int>("inSize"), 3);
317 EXPECT_EQ(restored->getPropertyValue<int>("outSize"), 6);
318 EXPECT_EQ(restored->getPropertyValue<std::string>("mode"),
319 std::string(Extender::SIGNED_MODE));
320 EXPECT_EQ(cellTypes(onlyModule(
321 nlohmann::json::parse(SILICON::yosys::serialize(imported, "top")))),
322 (std::multiset<std::string>{"$pos", "$pos"}));
323}
324
325TEST(YosysTest, ComplementerLowersToNegAndRoundTripsWithoutAnAdder)
326{
327 auto complementer = std::make_shared<Complementer>(Bus(5), Bus(5));
328 auto exported = exportComponent(complementer);
329 EXPECT_EQ(cellTypes(onlyModule(exported)), std::multiset<std::string>{"$neg"});
330
331 const auto& cell = onlyCell(exported);
332 EXPECT_EQ(cell.at("parameters").at("A_WIDTH"),
334 EXPECT_EQ(cell.at("parameters").at("Y_WIDTH"),
336 EXPECT_EQ(cell.at("parameters").at("A_SIGNED"), "0");
337 EXPECT_EQ(cell.at("connections").size(), 2);
338 EXPECT_FALSE(cell.at("parameters").contains("B_WIDTH"));
339 EXPECT_FALSE(cell.at("parameters").contains("B_SIGNED"));
340 EXPECT_EQ(cell.at("connections").at("A").size(), 5);
341
342 const Circuit imported = SILICON::yosys::deserialize(exported.dump());
343 const auto restored = findComponent<Complementer>(imported);
344 ASSERT_TRUE(restored);
345 EXPECT_EQ(restored->getPropertyValue<int>("size"), 5);
346 EXPECT_FALSE(findComponent<AdderNBits>(imported));
347 EXPECT_EQ(cellTypes(onlyModule(
348 nlohmann::json::parse(SILICON::yosys::serialize(imported, "top")))),
349 (std::multiset<std::string>{"$pos", "$neg"}));
350}
351
352TEST(YosysTest, ComparatorLowersToNativeComparisonCellsAndRoundTrips)
353{
354 // Re-importing an exported comparator needs the plugin to legalize $eq, $lt, ...
355#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
356 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
357#endif
358
359 static constexpr std::array MODES{
360 std::pair<std::string_view, std::string_view>{"==", "$eq"},
361 std::pair<std::string_view, std::string_view>{"<", "$lt"},
362 std::pair<std::string_view, std::string_view>{"<=", "$le"},
363 std::pair<std::string_view, std::string_view>{">", "$gt"},
364 std::pair<std::string_view, std::string_view>{">=", "$ge"},
365 };
366
367 for (const auto& [mode, cellType] : MODES) {
368 SCOPED_TRACE(mode);
369 auto comparator = std::make_shared<Comparator>(std::array<Bus, 2>{Bus(5), Bus(5)},
370 std::make_shared<Wire>());
371 comparator->setProperty("mode", std::string(mode));
372 comparator->setProperty("signed", true);
373
374 const auto exported = exportComponent(comparator);
375 const auto& cell = onlyCell(exported);
376 EXPECT_EQ(cell.at("type"), cellType);
377 EXPECT_EQ(cell.at("parameters").at("A_SIGNED"), "1");
378 EXPECT_EQ(cell.at("parameters").at("B_SIGNED"), "1");
379 EXPECT_EQ(cell.at("parameters").at("A_WIDTH"),
381 EXPECT_EQ(cell.at("parameters").at("B_WIDTH"),
383 EXPECT_EQ(cell.at("parameters").at("Y_WIDTH"),
385
386 const Circuit imported = SILICON::yosys::deserialize(legalizeExpressions(exported.dump()));
387 const auto restored = findComponent<Comparator>(imported);
388 ASSERT_TRUE(restored);
389 EXPECT_EQ(restored->getPropertyValue<int>("size"), 5);
390 EXPECT_EQ(restored->getPropertyValue<std::string>("mode"), mode);
391 EXPECT_EQ(restored->getPropertyValue<bool>("signed"), true);
392 }
393}
394
395TEST(YosysTest, LowersSequentialComponents)
396{
397 auto latch =
398 std::make_shared<DLatch>(std::make_shared<Wire>(), std::make_shared<Wire>(),
399 std::make_shared<Wire>(), std::make_shared<Wire>());
400 EXPECT_EQ(cellTypes(onlyModule(exportComponent(latch))),
401 std::multiset<std::string>{"SILICON_DLATCH"});
402
403 auto dff = std::make_shared<DFlipFlop>(
404 std::make_shared<Wire>(), std::make_shared<Wire>(), nullptr, nullptr,
405 std::make_shared<Wire>(), std::make_shared<Wire>());
406 EXPECT_EQ(cellTypes(onlyModule(exportComponent(dff))),
407 std::multiset<std::string>{"SILICON_DFF"});
408
409 auto effe = std::make_shared<EFlipFlop>(
410 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>(),
411 nullptr, nullptr, std::make_shared<Wire>(), std::make_shared<Wire>());
412 EXPECT_EQ(cellTypes(onlyModule(exportComponent(effe))),
413 std::multiset<std::string>{"SILICON_DFFE"});
414
415 auto jk = std::make_shared<JKFlipFlop>(
416 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>(),
417 nullptr, nullptr, std::make_shared<Wire>(), std::make_shared<Wire>());
418 EXPECT_EQ(cellTypes(onlyModule(exportComponent(jk))),
419 std::multiset<std::string>{"SILICON_JKFF"});
420
421 EXPECT_EQ(cellTypes(onlyModule(exportComponent(registerWithMode(true, false)))),
422 std::multiset<std::string>{"SILICON_PISO"});
423}
424
425TEST(YosysTest, CustomTechnologyCellsRoundTripToNativeComponents)
426{
427 // The shifter cases export raw $shl, $shr and $sshr cells that only the
428 // plugin legalizes, so the round trip needs the plugin.
429#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
430 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
431#endif
432
433 const auto roundTrip = [](const Component_ptr& component) {
434 return SILICON::yosys::deserialize(legalizeExpressions(exportComponent(component).dump()));
435 };
436
437 auto latch =
438 std::make_shared<DLatch>(std::make_shared<Wire>(), std::make_shared<Wire>(),
439 std::make_shared<Wire>(), std::make_shared<Wire>());
440 const auto latchDesign = exportComponent(latch);
441 const auto& latchCell = onlyCell(latchDesign);
442 EXPECT_EQ(latchCell.at("type"), "SILICON_DLATCH");
443 EXPECT_EQ(latchCell.at("parameters").at("EN_POLARITY"), "1");
444 EXPECT_TRUE(findComponent<DLatch>(roundTrip(latch)));
445
446 auto dff = std::make_shared<DFlipFlop>(
447 std::make_shared<Wire>(), std::make_shared<Wire>(), nullptr, nullptr,
448 std::make_shared<Wire>(), std::make_shared<Wire>());
449 dff->setProperty("triggerEdge", std::string("NET"));
450 const auto dffDesign = exportComponent(dff);
451 const auto& dffCell = onlyCell(dffDesign);
452 EXPECT_EQ(dffCell.at("type"), "SILICON_DFF");
453 EXPECT_EQ(dffCell.at("connections").size(), 4);
454 EXPECT_EQ(dffCell.at("parameters").at("CLK_POLARITY"), "0");
455 const auto importedDff = roundTrip(dff);
456 ASSERT_TRUE(findComponent<DFlipFlop>(importedDff));
457 EXPECT_EQ(
458 findComponent<DFlipFlop>(importedDff)->getPropertyValue<std::string>("triggerEdge"),
459 std::optional<std::string>("NET"));
460
461 auto dffsr = std::make_shared<DFlipFlop>(
462 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>(),
463 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>());
464 EXPECT_EQ(onlyCell(exportComponent(dffsr)).at("type"), "SILICON_DFFSR");
465 EXPECT_TRUE(findComponent<DFlipFlop>(roundTrip(dffsr)));
466
467 auto dffe = std::make_shared<EFlipFlop>(
468 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>(),
469 nullptr, nullptr, std::make_shared<Wire>(), std::make_shared<Wire>());
470 EXPECT_EQ(onlyCell(exportComponent(dffe)).at("type"), "SILICON_DFFE");
471 EXPECT_TRUE(findComponent<EFlipFlop>(roundTrip(dffe)));
472
473 auto dffsre = std::make_shared<EFlipFlop>(
474 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>(),
475 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>(),
476 std::make_shared<Wire>());
477 EXPECT_EQ(onlyCell(exportComponent(dffsre)).at("type"), "SILICON_DFFSRE");
478 EXPECT_TRUE(findComponent<EFlipFlop>(roundTrip(dffsre)));
479
480 auto jkff = std::make_shared<JKFlipFlop>(
481 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>(),
482 nullptr, nullptr, std::make_shared<Wire>(), std::make_shared<Wire>());
483 EXPECT_EQ(onlyCell(exportComponent(jkff)).at("type"), "SILICON_JKFF");
484 EXPECT_TRUE(findComponent<JKFlipFlop>(roundTrip(jkff)));
485
486 auto halfAdder = std::make_shared<HalfAdder>(
487 std::array<Wire_ptr, 2>{std::make_shared<Wire>(), std::make_shared<Wire>()},
488 std::make_shared<Wire>(), std::make_shared<Wire>());
489 EXPECT_EQ(onlyCell(exportComponent(halfAdder)).at("type"), "SILICON_HALF_ADDER");
490 EXPECT_TRUE(findComponent<HalfAdder>(roundTrip(halfAdder)));
491
492 auto fullAdder = std::make_shared<FullAdder>(
493 std::array<Wire_ptr, 2>{std::make_shared<Wire>(), std::make_shared<Wire>()},
494 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>());
495 EXPECT_EQ(onlyCell(exportComponent(fullAdder)).at("type"), "SILICON_FULL_ADDER");
496 EXPECT_TRUE(findComponent<FullAdder>(roundTrip(fullAdder)));
497
498 auto adder = std::make_shared<AdderNBits>(std::array<Bus, 2>{Bus(5), Bus(5)}, Bus(5),
499 std::make_shared<Wire>());
500 const auto adderDesign = exportComponent(adder);
501 const auto& adderCell = onlyCell(adderDesign);
502 EXPECT_EQ(adderCell.at("type"), "SILICON_ADDER");
503 EXPECT_EQ(adderCell.at("parameters").at("SIGNED"), "0");
504 EXPECT_FALSE(adderCell.at("parameters").contains("A_SIGNED"));
505 EXPECT_FALSE(adderCell.at("parameters").contains("B_SIGNED"));
506 EXPECT_EQ(adderCell.at("connections").at("A").size(), 5);
507 const auto importedAdder = roundTrip(adder);
508 ASSERT_TRUE(findComponent<AdderNBits>(importedAdder));
509 EXPECT_EQ(findComponent<AdderNBits>(importedAdder)->getPropertyValue<int>("size"), 5);
510
511 for (const auto& [mode, isSigned, cellType] :
512 std::array<std::tuple<std::string_view, bool, std::string_view>, 3>{
513 {{Shifter::LEFT_MODE, false, "$shl"},
514 {Shifter::RIGHT_MODE, false, "$shr"},
515 {Shifter::RIGHT_MODE, true, "$sshr"}}}) {
516 auto shifter = std::make_shared<Shifter>(Bus(5), Bus(3), Bus(5));
517 shifter->setProperty("mode", std::string(mode));
518 shifter->setProperty("signed", isSigned);
519 const auto design = exportComponent(shifter);
520 EXPECT_EQ(onlyCell(design).at("type"), cellType);
521 const auto imported = findComponent<Shifter>(roundTrip(shifter));
522 ASSERT_TRUE(imported);
523 EXPECT_EQ(imported->getPropertyValue<std::string>("mode"), mode);
524 EXPECT_EQ(imported->getPropertyValue<bool>("signed"), isSigned);
525 EXPECT_EQ(imported->getPropertyValue<int>("size"), 5);
526 EXPECT_EQ(imported->getPropertyValue<int>("amountSize"), 3);
527 }
528
529 struct RegisterMode {
530 bool parallelInput;
531 bool parallelOutput;
532 std::string_view cellType;
533 };
534 static constexpr std::array REGISTER_MODES{
535 RegisterMode{true, true, "SILICON_PIPO"},
536 RegisterMode{true, false, "SILICON_PISO"},
537 RegisterMode{false, true, "SILICON_SIPO"},
538 RegisterMode{false, false, "SILICON_SISO"},
539 };
540 for (const auto& mode : REGISTER_MODES) {
541 SCOPED_TRACE(mode.cellType);
542 const auto reg = registerWithMode(mode.parallelInput, mode.parallelOutput);
543 const auto registerDesign = exportComponent(reg);
544 const auto& registerCell = onlyCell(registerDesign);
545 EXPECT_EQ(registerCell.at("type"), mode.cellType);
546 EXPECT_EQ(registerCell.at("connections").at("DATA").size(),
547 mode.parallelInput ? 4 : 1);
548 EXPECT_EQ(registerCell.at("connections").at("OUT").size(),
549 mode.parallelOutput ? 4 : 1);
550 EXPECT_EQ(registerCell.at("connections").contains("LOAD"),
551 mode.parallelInput && !mode.parallelOutput);
552 EXPECT_EQ(registerCell.at("parameters").contains("LOAD_POLARITY"),
553 mode.parallelInput && !mode.parallelOutput);
554 EXPECT_FALSE(registerCell.at("parameters").contains("INPUT_PARALLEL"));
555 EXPECT_FALSE(registerCell.at("parameters").contains("OUTPUT_PARALLEL"));
556
557 const auto importedCircuit = roundTrip(reg);
558 const auto importedRegister = findComponent<Register>(importedCircuit);
559 ASSERT_TRUE(importedRegister);
560 EXPECT_EQ(importedRegister->getPropertyValue<int>("size"), 4);
561 EXPECT_EQ(importedRegister->getPropertyValue<std::string>("inputType"),
562 std::optional<std::string>(mode.parallelInput ? Register::PARALLEL_TYPE
564 EXPECT_EQ(importedRegister->getPropertyValue<std::string>("outputType"),
565 std::optional<std::string>(mode.parallelOutput ? Register::PARALLEL_TYPE
567 }
568}
569
570TEST(YosysTest, RejectsMalformedCustomTechnologyCells)
571{
572 auto component = std::make_shared<DFlipFlop>(
573 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>(),
574 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>());
575 const auto reject = [](const nlohmann::json& design) {
576 EXPECT_THROW((void)SILICON::yosys::deserialize(design.dump()), std::runtime_error);
577 };
578
579 auto missingPort = exportComponent(component);
580 onlyModule(missingPort)["cells"].begin().value()["connections"].erase("D");
581 reject(missingPort);
582
583 auto unexpectedPort = exportComponent(component);
584 onlyModule(unexpectedPort)["cells"].begin().value()["connections"]["EXTRA"] =
585 nlohmann::json::array({2});
586 reject(unexpectedPort);
587
588 auto incorrectWidth = exportComponent(component);
589 onlyModule(incorrectWidth)["cells"].begin().value()["connections"]["D"].push_back(3);
590 reject(incorrectWidth);
591
592 auto invalidBoolean = exportComponent(component);
593 onlyModule(invalidBoolean)["cells"].begin().value()["parameters"]["CLK_POLARITY"] =
594 "10";
595 reject(invalidBoolean);
596
597 auto unsupportedPolarity = exportComponent(component);
598 onlyModule(unsupportedPolarity)["cells"].begin().value()["parameters"]["SET_POLARITY"] =
599 "0";
600 reject(unsupportedPolarity);
601
602 auto latch =
603 std::make_shared<DLatch>(std::make_shared<Wire>(), std::make_shared<Wire>(),
604 std::make_shared<Wire>(), std::make_shared<Wire>());
605 auto unsupportedLatchPolarity = exportComponent(latch);
606 onlyModule(unsupportedLatchPolarity)["cells"].begin().value()["parameters"]
607 ["EN_POLARITY"] = "0";
608 reject(unsupportedLatchPolarity);
609
610 auto duplicateDriver = exportComponent(component);
611 auto& duplicateConnections =
612 onlyModule(duplicateDriver)["cells"].begin().value()["connections"];
613 duplicateConnections["QN"] = duplicateConnections["Q"];
614 reject(duplicateDriver);
615
616 auto adder = std::make_shared<AdderNBits>(std::array<Bus, 2>{Bus(3), Bus(3)}, Bus(3),
617 std::make_shared<Wire>());
618 auto malformedAdder = exportComponent(adder);
619 onlyModule(malformedAdder)["cells"].begin().value()["parameters"]["WIDTH"] =
621 reject(malformedAdder);
622
623 auto missingRegisterLoad = exportComponent(registerWithMode(true, false));
624 onlyModule(missingRegisterLoad)["cells"].begin().value()["connections"].erase("LOAD");
625 reject(missingRegisterLoad);
626
627 auto unsupportedRegisterPolarity = exportComponent(registerWithMode(false, true));
628 onlyModule(unsupportedRegisterPolarity)["cells"].begin().value()["parameters"]
629 ["EN_POLARITY"] = "0";
630 reject(unsupportedRegisterPolarity);
631
632 auto unexpectedRegisterLoad = exportComponent(registerWithMode(true, true));
633 onlyModule(unexpectedRegisterLoad)["cells"].begin().value()["connections"]["LOAD"] =
634 nlohmann::json::array({"0"});
635 reject(unexpectedRegisterLoad);
636
637 EXPECT_THROW((void)exportComponent(std::make_shared<HalfAdder>()), std::runtime_error);
638}
639
640TEST(YosysTest, EncodesWideParametersWithoutTruncatingTheirWidth)
641{
642 const auto parameter = SILICON::yosys::SerializationContext::parameter(1, 65);
643 EXPECT_EQ(parameter.size(), 65);
644 EXPECT_EQ(parameter.back(), '1');
645}
646
647TEST(YosysTest, SharesOneSplitterAcrossIndexedBusConsumers)
648{
650
651 const Json design{
652 {"modules",
653 {{"top",
654 {{"attributes", Json::object()},
655 {"ports",
656 {{"a", {{"direction", "input"}, {"bits", Json::array({2, 3})}}},
657 {"whole", {{"direction", "output"}, {"bits", Json::array({2, 3})}}},
658 {"low", {{"direction", "output"}, {"bits", Json::array({2})}}},
659 {"low_copy", {{"direction", "output"}, {"bits", Json::array({2})}}},
660 {"high", {{"direction", "output"}, {"bits", Json::array({3})}}}}},
661 {"cells", Json::object()},
662 {"netnames", Json::object()}}}}}};
663
664 const Circuit circuit = SILICON::yosys::deserialize(design.dump());
665 EXPECT_EQ(componentTypes(circuit).count("WireSplitter"), 1);
666 EXPECT_EQ(componentTypes(circuit).count("WireMerger"), 0);
667
668 const auto input = findNamedComponent<DummyBusInputComponent>(circuit, "a");
669 const auto whole = findNamedComponent<DummyBusOutputComponent>(circuit, "whole");
670 const auto low = findNamedComponent<DummyOutputComponent>(circuit, "low");
671 const auto lowCopy = findNamedComponent<DummyOutputComponent>(circuit, "low_copy");
672 const auto high = findNamedComponent<DummyOutputComponent>(circuit, "high");
673 const auto splitter = findComponent<WireSplitter>(circuit);
674 ASSERT_TRUE(input && whole && low && lowCopy && high && splitter);
675 ASSERT_EQ(splitter->outputBuses().size(), 2);
676 EXPECT_EQ(splitter->getPropertyValue<int>("size"), 2);
677 EXPECT_EQ(splitter->inputBuses()[0], input->outputBuses()[0]);
678 EXPECT_EQ(whole->inputBuses()[0], input->outputBuses()[0]);
679 EXPECT_EQ(low->inputBuses()[0], splitter->outputBuses()[0]);
680 EXPECT_EQ(lowCopy->inputBuses()[0], splitter->outputBuses()[0]);
681 EXPECT_EQ(high->inputBuses()[0], splitter->outputBuses()[1]);
682}
683
684TEST(YosysTest, SharesOneMergerAcrossIdenticalAssembledBuses)
685{
687
688 const Json design{
689 {"modules",
690 {{"top",
691 {{"attributes", Json::object()},
692 {"ports",
693 {{"x", {{"direction", "input"}, {"bits", Json::array({2})}}},
694 {"y", {{"direction", "input"}, {"bits", Json::array({3})}}},
695 {"q", {{"direction", "output"}, {"bits", Json::array({2, 3})}}},
696 {"q_copy", {{"direction", "output"}, {"bits", Json::array({2, 3})}}}}},
697 {"cells", Json::object()},
698 {"netnames", Json::object()}}}}}};
699
700 const Circuit circuit = SILICON::yosys::deserialize(design.dump());
701 EXPECT_EQ(componentTypes(circuit).count("WireSplitter"), 0);
702 EXPECT_EQ(componentTypes(circuit).count("WireMerger"), 1);
703
704 const auto x = findNamedComponent<DummyInputComponent>(circuit, "x");
705 const auto y = findNamedComponent<DummyInputComponent>(circuit, "y");
706 const auto q = findNamedComponent<DummyBusOutputComponent>(circuit, "q");
707 const auto qCopy = findNamedComponent<DummyBusOutputComponent>(circuit, "q_copy");
708 const auto merger = findComponent<WireMerger>(circuit);
709 ASSERT_TRUE(x && y && q && qCopy && merger);
710 ASSERT_EQ(merger->inputBuses().size(), 2);
711 EXPECT_EQ(merger->getPropertyValue<int>("size"), 2);
712 EXPECT_EQ(merger->inputBuses()[0], x->outputBuses()[0]);
713 EXPECT_EQ(merger->inputBuses()[1], y->outputBuses()[0]);
714 EXPECT_EQ(q->inputBuses()[0], merger->outputBuses()[0]);
715 EXPECT_EQ(qCopy->inputBuses()[0], merger->outputBuses()[0]);
716}
717
718TEST(YosysTest, NormalizesReorderedPartSelectThroughOneSplitterAndMerger)
719{
721
722 const Json design{
723 {"modules",
724 {{"top",
725 {{"attributes", Json::object()},
726 {"ports",
727 {{"a", {{"direction", "input"}, {"bits", Json::array({2, 3, 4, 5})}}},
728 {"q", {{"direction", "output"}, {"bits", Json::array({5, 2})}}}}},
729 {"cells", Json::object()},
730 {"netnames", Json::object()}}}}}};
731
732 auto circuit = std::make_shared<Circuit>(SILICON::yosys::deserialize(design.dump()));
733 EXPECT_EQ(componentTypes(*circuit).count("WireSplitter"), 1);
734 EXPECT_EQ(componentTypes(*circuit).count("WireMerger"), 1);
735
736 const auto input = findNamedComponent<DummyBusInputComponent>(*circuit, "a");
737 const auto output = findNamedComponent<DummyBusOutputComponent>(*circuit, "q");
738 const auto splitter = findComponent<WireSplitter>(*circuit);
739 const auto merger = findComponent<WireMerger>(*circuit);
740 ASSERT_TRUE(input && output && splitter && merger);
741 ASSERT_EQ(splitter->outputBuses().size(), 2);
742 ASSERT_EQ(merger->inputBuses().size(), 2);
743 EXPECT_EQ(merger->inputBuses()[0], splitter->outputBuses()[1]);
744 EXPECT_EQ(merger->inputBuses()[1], splitter->outputBuses()[0]);
745 EXPECT_EQ(output->inputBuses()[0], merger->outputBuses()[0]);
746
747 input->setBusValue(valueFor(input->outputBuses()[0], 8));
748 Simulator simulator(circuit);
749 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
750 EXPECT_EQ(output->inputBuses()[0].getCurrentValue(),
751 valueFor(output->inputBuses()[0], 1));
752}
753
754TEST(YosysTest, SharesBusSlicesWithoutReconstructingThemFromIndividualBits)
755{
757 Json ports = Json::object();
758 ports["a"] = {{"direction", "input"}, {"bits", Json::array({2, 3, 4, 5, 6, 7, 8, 9})}};
759 ports["whole"] = {{"direction", "output"}, {"bits", ports["a"]["bits"]}};
760 ports["low"] = {{"direction", "output"}, {"bits", Json::array({2, 3, 4, 5})}};
761 ports["low_copy"] = ports["low"];
762 ports["high"] = {{"direction", "output"}, {"bits", Json::array({6, 7, 8, 9})}};
763 ports["overlap"] = {{"direction", "output"}, {"bits", Json::array({4, 5, 6, 7})}};
764 ports["tap"] = {{"direction", "output"}, {"bits", Json::array({5})}};
765 const Json design{
766 {"modules", {{"top", {{"ports", ports}, {"cells", Json::object()}}}}}};
767
768 auto circuit = std::make_shared<Circuit>(SILICON::yosys::deserialize(design.dump()));
769 EXPECT_EQ(componentTypes(*circuit).count("WireSplitter"), 1);
770 EXPECT_EQ(componentTypes(*circuit).count("WireMerger"), 0);
771 const auto splitter = findComponent<WireSplitter>(*circuit);
772 ASSERT_TRUE(splitter);
773 EXPECT_EQ(splitter->outputSlices(), (std::vector<std::pair<unsigned int, unsigned int>>{
774 {0, 4}, {2, 4}, {3, 1}, {4, 4}}));
775 const auto low = findNamedComponent<DummyBusOutputComponent>(*circuit, "low");
776 const auto copy = findNamedComponent<DummyBusOutputComponent>(*circuit, "low_copy");
777 ASSERT_TRUE(low && copy);
778 EXPECT_EQ(low->inputBuses()[0], copy->inputBuses()[0]);
779
780 // Native save/load must retain the bus port shapes and their shared wires.
781 ComponentRegistry registry;
782 registerAllComponents(registry);
783 circuit =
784 std::make_shared<Circuit>(Circuit::deserialize(circuit->serialize(), registry));
785
786#ifdef SILICON_TEST_YOSYS_EXECUTABLE
787 // Yosys export must preserve overlapping slices as well as native save/load.
788 circuit = std::make_shared<Circuit>(importVerilog(
790 EXPECT_EQ(componentTypes(*circuit).count("WireMerger"), 0);
791#endif
792 const auto input = findNamedComponent<DummyBusInputComponent>(*circuit, "a");
793 ASSERT_TRUE(input);
794 Simulator simulator(circuit);
795 for (unsigned int value = 0; value < 256; ++value) {
796 simulator.setBus(input->outputBuses()[0], valueFor(input->outputBuses()[0], value));
797 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
798 for (const auto& [name, expected] :
799 std::map<std::string, unsigned int>{{"low", value & 15},
800 {"low_copy", value & 15},
801 {"high", value >> 4},
802 {"overlap", (value >> 2) & 15},
803 {"whole", value}}) {
804 const auto output = findNamedComponent<DummyBusOutputComponent>(*circuit, name);
805 ASSERT_TRUE(output);
806 EXPECT_EQ(output->inputBuses()[0].getCurrentValue(),
807 valueFor(output->inputBuses()[0], expected));
808 }
809 const auto bit = findNamedComponent<DummyOutputComponent>(*circuit, "tap");
810 ASSERT_TRUE(bit);
811 EXPECT_EQ(bit->inputBuses()[0].getCurrentValue(),
812 valueFor(bit->inputBuses()[0], (value >> 3) & 1));
813 }
814}
815
816TEST(YosysTest, ConcatenatesBusRunsAndPacksLiteralRuns)
817{
819 const Json ports{
820 {"a", {{"direction", "input"}, {"bits", Json::array({2, 3, 4, 5, 6, 7, 8, 9})}}},
821 {"b", {{"direction", "input"}, {"bits", Json::array({10, 11, 12, 13})}}},
822 {"q",
823 {{"direction", "output"},
824 {"bits", Json::array({6, 7, 8, 9, "0", "x", "1", "0", 10, 11, 12, 13})}}}};
825 const Json design{
826 {"modules", {{"top", {{"ports", ports}, {"cells", Json::object()}}}}}};
827 auto circuit = std::make_shared<Circuit>(SILICON::yosys::deserialize(design.dump()));
828 EXPECT_EQ(componentTypes(*circuit).count("WireSplitter"), 1);
829 EXPECT_EQ(componentTypes(*circuit).count("WireMerger"), 1);
830 const auto merger = findComponent<WireMerger>(*circuit);
831 ASSERT_TRUE(merger);
832 ASSERT_EQ(merger->inputBuses().size(), 3);
833 for (const auto& input : merger->inputBuses())
834 EXPECT_EQ(input.size(), 4);
835 ComponentRegistry registry;
836 registerAllComponents(registry);
837 circuit =
838 std::make_shared<Circuit>(Circuit::deserialize(circuit->serialize(), registry));
839 const auto a = findNamedComponent<DummyBusInputComponent>(*circuit, "a");
840 const auto b = findNamedComponent<DummyBusInputComponent>(*circuit, "b");
841 const auto q = findNamedComponent<DummyBusOutputComponent>(*circuit, "q");
842 ASSERT_TRUE(a && b && q);
843 a->setBusValue(valueFor(a->outputBuses()[0], 0xa5));
844 b->setBusValue(valueFor(b->outputBuses()[0], 3));
845 Simulator simulator(circuit);
846 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
847 EXPECT_EQ(q->inputBuses()[0].getCurrentValue(), busValueFromBits("001101X01010"));
848
849#ifdef SILICON_TEST_YOSYS_EXECUTABLE
850 auto restored = std::make_shared<Circuit>(importVerilog(
852 const auto restoredA = findNamedComponent<DummyBusInputComponent>(*restored, "a");
853 const auto restoredB = findNamedComponent<DummyBusInputComponent>(*restored, "b");
854 const auto restoredQ = findNamedComponent<DummyBusOutputComponent>(*restored, "q");
855 ASSERT_TRUE(restoredA && restoredB && restoredQ);
856 restoredA->setBusValue(valueFor(restoredA->outputBuses()[0], 0xa5));
857 restoredB->setBusValue(valueFor(restoredB->outputBuses()[0], 3));
858 Simulator restoredSimulator(restored);
859 ASSERT_EQ(restoredSimulator.runUntilIdle(), Simulator::RunResult::Completed);
860 EXPECT_EQ(restoredQ->inputBuses()[0].getCurrentValue(),
861 busValueFromBits("001101X01010"));
862#endif
863}
864
865TEST(YosysTest, RecognizesSharedSignAndZeroExtensionOfBusSlices)
866{
868 const Json ports{
869 {"a", {{"direction", "input"}, {"bits", Json::array({2, 3, 4, 5})}}},
870 {"signed_q", {{"direction", "output"}, {"bits", Json::array({3, 4, 5, 5, 5, 5})}}},
871 {"signed_copy",
872 {{"direction", "output"}, {"bits", Json::array({3, 4, 5, 5, 5, 5})}}},
873 {"unsigned_q",
874 {{"direction", "output"}, {"bits", Json::array({3, 4, 5, "0", "0", "0"})}}}};
875 const Json design{
876 {"modules", {{"top", {{"ports", ports}, {"cells", Json::object()}}}}}};
877 auto circuit = std::make_shared<Circuit>(SILICON::yosys::deserialize(design.dump()));
878 EXPECT_EQ(componentTypes(*circuit).count("WireSplitter"), 1);
879 EXPECT_EQ(componentTypes(*circuit).count("WireMerger"), 0);
880 EXPECT_EQ(componentTypes(*circuit).count("Extender"), 2);
881 const auto input = findNamedComponent<DummyBusInputComponent>(*circuit, "a");
882 const auto signedQ = findNamedComponent<DummyBusOutputComponent>(*circuit, "signed_q");
883 const auto copy = findNamedComponent<DummyBusOutputComponent>(*circuit, "signed_copy");
884 const auto unsignedQ =
885 findNamedComponent<DummyBusOutputComponent>(*circuit, "unsigned_q");
886 ASSERT_TRUE(input && signedQ && copy && unsignedQ);
887 EXPECT_EQ(signedQ->inputBuses()[0], copy->inputBuses()[0]);
888 Simulator simulator(circuit);
889 for (const auto& bits : {"1010", "0011", "X010", "E010"}) {
890 simulator.setBus(input->outputBuses()[0], busValueFromBits(bits));
891 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
892 const auto value = input->outputBuses()[0].getCurrentValue();
893 EXPECT_EQ(
894 unsignedQ->inputBuses()[0].getCurrentValue(),
895 (BusValue{value[1], value[2], value[3], State::LOW, State::LOW, State::LOW}));
896 EXPECT_EQ(signedQ->inputBuses()[0].getCurrentValue(),
897 (BusValue{value[1], value[2], value[3], value[3], value[3], value[3]}));
898 }
899}
900
901TEST(YosysTest, ImportsGeneralCombinationalNetlistWithConstants)
902{
905
906 const Json binaryParameters{
907 {"A_SIGNED", SerializationContext::parameter(0, 1)},
908 {"B_SIGNED", SerializationContext::parameter(0, 1)},
909 {"A_WIDTH", SerializationContext::parameter(2)},
910 {"B_WIDTH", SerializationContext::parameter(2)},
911 {"Y_WIDTH", SerializationContext::parameter(2)},
912 };
913 const Json unaryParameters{
914 {"A_SIGNED", SerializationContext::parameter(0, 1)},
915 {"A_WIDTH", SerializationContext::parameter(2)},
916 {"Y_WIDTH", SerializationContext::parameter(2)},
917 };
918 const Json design{
919 {"creator", "test"},
920 {"modules",
921 {{"logic_top",
922 {{"attributes", Json::object()},
923 {"ports",
924 {{"a", {{"direction", "input"}, {"bits", Json::array({2, 3})}}},
925 {"y", {{"direction", "output"}, {"bits", Json::array({6, 7})}}}}},
926 {"cells",
927 {{"generic_and",
928 {{"type", "$and"},
929 {"parameters", binaryParameters},
930 {"connections",
931 {{"A", Json::array({2, 3})},
932 {"B", Json::array({"1", "0"})},
933 {"Y", Json::array({4, 5})}}}}},
934 {"generic_not",
935 {{"type", "$not"},
936 {"parameters", unaryParameters},
937 {"connections",
938 {{"A", Json::array({4, 5})}, {"Y", Json::array({6, 7})}}}}}}},
939 {"netnames", Json::object()}}}}}};
940
941 Circuit imported = SILICON::yosys::deserialize(design.dump());
942 EXPECT_EQ(componentTypes(imported),
943 (std::multiset<std::string>{"AndGate", "ConstantComponent",
944 "DummyBusInputComponent",
945 "DummyBusOutputComponent", "NotGate"}));
946 auto importedConstant = findComponent<ConstantComponent>(imported);
947 ASSERT_TRUE(importedConstant);
948 EXPECT_EQ(importedConstant->getPropertyValue<int>("size"), 2);
949 EXPECT_EQ(importedConstant->getPropertyValue<BusValue>("value"),
950 busValueFromBits("01"));
951 const auto importedNot = findComponent<NotGate>(imported);
952 ASSERT_TRUE(importedNot);
953 EXPECT_EQ(importedNot->getPropertyValue<int>("size"), 2);
954
955 auto registry = ComponentRegistry::empty();
956 registerAllComponents(registry);
957 const Circuit restored = Circuit::deserialize(imported.serialize(), registry);
958 EXPECT_EQ(componentTypes(restored), componentTypes(imported));
959 ASSERT_TRUE(findComponent<NotGate>(restored));
960 EXPECT_EQ(findComponent<NotGate>(restored)->getPropertyValue<int>("size"), 2);
961 EXPECT_NO_THROW({
962 const auto reparsed =
963 nlohmann::json::parse(SILICON::yosys::serialize(restored, "top"));
964 EXPECT_TRUE(reparsed.is_object());
965 });
966
967#ifdef SILICON_TEST_YOSYS_EXECUTABLE
968 EXPECT_EQ(validateWithYosys(restored, "import_constants"), 0);
969#endif
970
971 auto simulated = std::make_shared<Circuit>(SILICON::yosys::deserialize(design.dump()));
972 std::shared_ptr<DummyBusInputComponent> inputComponent;
973 std::shared_ptr<DummyBusOutputComponent> outputComponent;
974 for (const auto vertex :
975 boost::make_iterator_range(boost::vertices(simulated->getGraph()))) {
976 const auto& component = simulated->getGraph()[vertex].component;
977 if (auto input = std::dynamic_pointer_cast<DummyBusInputComponent>(component))
978 inputComponent = std::move(input);
979 if (auto output = std::dynamic_pointer_cast<DummyBusOutputComponent>(component))
980 outputComponent = std::move(output);
981 }
982 ASSERT_TRUE(inputComponent);
983 ASSERT_TRUE(outputComponent);
984 inputComponent->setBusValue(valueFor(inputComponent->outputBuses()[0], 3));
985 Simulator simulator(simulated);
986 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
987 EXPECT_EQ(outputComponent->inputBuses()[0].getCurrentValue(),
988 valueFor(outputComponent->inputBuses()[0], 2));
989}
990
991TEST(YosysTest, ExportsArithmeticCellsAndPreservesComponentProperties)
992{
993 for (const bool sign : {false, true}) {
994 std::vector<Component_ptr> components{
995 std::make_shared<Multiplier>(std::array<Bus, 2>{Bus(5), Bus(5)}, Bus(5)),
996 std::make_shared<Divider>(std::array<Bus, 2>{Bus(5), Bus(5)}, Bus(5), Bus(5))};
997 for (const auto& component : components) {
998 component->setProperty("signed", sign);
999 component->setProperty("delay", 7);
1000 const auto design = exportComponent(component);
1001 const bool multiplication = component->typeName() == Multiplier::Type;
1002 EXPECT_EQ(cellTypes(onlyModule(design)),
1003 std::multiset<std::string>{multiplication ? "SILICON_MULTIPLIER"
1004 : "SILICON_DIVIDER"});
1005 for (const auto& cell : onlyModule(design).at("cells")) {
1006 EXPECT_EQ(cell.at("parameters").at("SIGNED"), sign ? "1" : "0");
1007 EXPECT_FALSE(cell.at("parameters").contains("A_SIGNED"));
1008 EXPECT_FALSE(cell.at("parameters").contains("B_SIGNED"));
1009 EXPECT_EQ(
1010 cell.at("connections").at(multiplication ? "PRODUCT" : "div").size(), 5);
1011 }
1012 const auto imported = SILICON::yosys::deserialize(design.dump());
1013 EXPECT_EQ(componentTypes(imported).count(multiplication ? "Multiplier" : "Divider"),
1014 1);
1015 const auto importedComponent =
1016 multiplication
1017 ? std::static_pointer_cast<Component>(findComponent<Multiplier>(imported))
1018 : std::static_pointer_cast<Component>(findComponent<Divider>(imported));
1019 ASSERT_TRUE(importedComponent);
1020 EXPECT_EQ(importedComponent->getPropertyValue<bool>("signed"), sign);
1021 EXPECT_EQ(importedComponent->getPropertyValue<int>("size"), 5);
1022 auto registry = ComponentRegistry::empty();
1023 registerAllComponents(registry);
1024 const auto circuit = circuitWithBoundaryPorts(component);
1025 const auto restored = Circuit::deserialize(circuit.serialize(), registry);
1026 const auto restoredComponent =
1027 multiplication
1028 ? std::static_pointer_cast<Component>(findComponent<Multiplier>(restored))
1029 : std::static_pointer_cast<Component>(findComponent<Divider>(restored));
1030 ASSERT_TRUE(restoredComponent);
1031 EXPECT_EQ(restoredComponent->getPropertyValue<int>("size"), 5);
1032 EXPECT_EQ(restoredComponent->getPropertyValue<int>("delay"), 7);
1033 EXPECT_EQ(restoredComponent->getPropertyValue<bool>("signed"), sign);
1034#ifdef SILICON_TEST_YOSYS_EXECUTABLE
1035 EXPECT_EQ(validateWithYosys(circuit, multiplication ? "multiplier" : "divider"), 0);
1036#endif
1037 }
1038 }
1039}
1040
1041TEST(YosysTest, RejectsMalformedArithmeticTechnologyCells)
1042{
1043 for (const auto& component : std::vector<Component_ptr>{
1044 std::make_shared<AdderNBits>(std::array<Bus, 2>{Bus(4), Bus(4)}, Bus(4),
1045 std::make_shared<Wire>()),
1046 std::make_shared<Multiplier>(std::array<Bus, 2>{Bus(4), Bus(4)}, Bus(4)),
1047 std::make_shared<Divider>(std::array<Bus, 2>{Bus(4), Bus(4)}, Bus(4),
1048 Bus(4))}) {
1049 const auto design = exportComponent(component);
1050 auto wrongWidth = design;
1051 onlyModule(wrongWidth)["cells"].begin().value()["parameters"]["WIDTH"] =
1053 EXPECT_THROW((void)SILICON::yosys::deserialize(wrongWidth.dump()),
1054 std::runtime_error);
1055 auto missingOutput = design;
1056 onlyModule(missingOutput)["cells"].begin().value()["connections"].erase(
1057 component->typeName() == AdderNBits::Type ? "SUM"
1058 : component->typeName() == Multiplier::Type ? "PRODUCT" : "mod");
1059 EXPECT_THROW((void)SILICON::yosys::deserialize(missingOutput.dump()),
1060 std::runtime_error);
1061 auto invalidFlag = design;
1062 onlyModule(invalidFlag)["cells"].begin().value()["parameters"]["SIGNED"] = "10";
1063 EXPECT_THROW((void)SILICON::yosys::deserialize(invalidFlag.dump()),
1064 std::runtime_error);
1065 }
1066}
1067
1068TEST(YosysTest, RejectsCellsThatRequireTechnologyMapping)
1069{
1072 std::vector<Json> designs;
1073 for (const auto type : {"$mul", "$div", "$mod"}) {
1074 auto design = subtractionDesign(3, 3, 3, false, false);
1075 onlyModule(design)["cells"].begin().value()["type"] = type;
1076 designs.push_back(std::move(design));
1077 }
1078 const auto wire = [] { return std::make_shared<Wire>(); };
1079 const std::array<std::pair<Component_ptr, const char*>, 4> storage{
1080 std::pair{
1081 std::make_shared<DFlipFlop>(wire(), wire(), nullptr, nullptr, wire(), wire()),
1082 "$dff"},
1083 std::pair{
1084 std::make_shared<DFlipFlop>(wire(), wire(), wire(), wire(), wire(), wire()),
1085 "$dffsr"},
1086 std::pair{std::make_shared<EFlipFlop>(wire(), wire(), wire(), wire(), wire(),
1087 wire(), wire()),
1088 "$dffsre"},
1089 std::pair{std::make_shared<DLatch>(wire(), wire(), wire(), wire()), "$dlatch"}};
1090 for (const auto& [component, type] : storage) {
1091 auto design = exportComponent(component);
1092 auto& cell = onlyModule(design)["cells"].begin().value();
1093 cell["type"] = type;
1094 cell["parameters"]["WIDTH"] = SerializationContext::parameter(1);
1095 cell["connections"].erase("QN");
1096 cell["port_directions"].erase("QN");
1097 designs.push_back(std::move(design));
1098 }
1099 for (const auto& design : designs) {
1100 SCOPED_TRACE(onlyCell(design).at("type"));
1101 EXPECT_THROW((void)SILICON::yosys::deserialize(design.dump()), std::runtime_error);
1102#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
1103 EXPECT_THROW((void)legalizeExpressions(design.dump(), "silicon_validate"),
1104 std::runtime_error);
1105#endif
1106 }
1107}
1108
1109TEST(YosysTest, ExportsBusReductionGates)
1110{
1111 const std::vector<std::pair<std::shared_ptr<Gate>, std::multiset<std::string>>> cases{
1112 {std::make_shared<AndGate>(), {"$reduce_and"}},
1113 {std::make_shared<OrGate>(), {"$reduce_or"}},
1114 {std::make_shared<NandGate>(), {"$reduce_and", "$not"}},
1115 {std::make_shared<NorGate>(), {"$reduce_or", "$not"}},
1116 {std::make_shared<XorGate>(), {"$reduce_xor"}},
1117 };
1118 for (const auto& [gate, expected] : cases) {
1119 gate->setInputs({Bus(1), Bus(1)});
1120 gate->setOutputs({Bus(1)});
1121 gate->setProperty("size", 4);
1122 const auto json = exportComponent(gate);
1123 const auto& module = onlyModule(json);
1124 EXPECT_EQ(cellTypes(module), expected);
1125 for (const auto& cell : module.at("cells")) {
1126 if (cell.at("type") != "$not") {
1127 EXPECT_EQ(cell.at("connections").at("A").size(), 4);
1128 EXPECT_EQ(cell.at("connections").at("Y").size(), 1);
1129 }
1130 }
1131 }
1132}
1133
1134#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
1135namespace {
1136nlohmann::json gateChain(int count, bool reverseNames)
1137{
1138 using Json = nlohmann::json;
1139 Json cells = Json::object();
1140 const Json parameters{{"A_SIGNED", "0"},
1141 {"B_SIGNED", "0"},
1142 {"A_WIDTH", "1"},
1143 {"B_WIDTH", "1"},
1144 {"Y_WIDTH", "1"}};
1145 for (int i = 0; i < count; ++i)
1146 cells[std::format("g{:06}", reverseNames ? count - i - 1 : i)] = {
1147 {"type", "$and"},
1148 {"parameters", parameters},
1149 {"connections",
1150 {{"A", Json::array({i == 0 ? 2 : count + i + 2})},
1151 {"B", Json::array({i + 3})},
1152 {"Y", Json::array({count + i + 3})}}}};
1153 Json inputs = Json::array();
1154 for (int bit = 2; bit < count + 3; ++bit)
1155 inputs.push_back(bit);
1156 return {
1157 {"modules",
1158 {{"top",
1159 {{"ports",
1160 {{"a", {{"direction", "input"}, {"bits", inputs}}},
1161 {"y", {{"direction", "output"}, {"bits", Json::array({2 * count + 2})}}}}},
1162 {"cells", cells}}}}}};
1163}
1164} // namespace
1165
1166TEST(YosysTest, FoldsLongGateChainOnceInEitherCellOrder)
1167{
1168 using Json = nlohmann::json;
1169 constexpr int count = 4096;
1170 for (bool reversed : {false, true}) {
1171 const auto result = Json::parse(
1172 legalizeExpressions(gateChain(count, reversed).dump(), "silicon_gates"));
1173 const auto& cells = onlyModule(result).at("cells");
1174 ASSERT_EQ(cells.size(), 1);
1175 const auto& cell = cells.begin().value();
1176 EXPECT_EQ(cell.at("type"), "SILICON_GATE");
1177 EXPECT_EQ(
1178 std::stoi(cell.at("parameters").at("INPUTS").get<std::string>(), nullptr, 2),
1179 count + 1);
1180 // DFS must preserve original A/B order even when storage order is reversed.
1181 const auto& inputPort = onlyModule(result).at("ports").at("a").at("bits");
1182 for (int i = 0; i <= count; ++i)
1183 EXPECT_EQ(cell.at("connections").at("A" + std::to_string(i)).at(0),
1184 inputPort.at(i));
1185 }
1186}
1187
1188TEST(YosysTest, MaximalGateChainsStopAtSharedIntermediateOutputs)
1189{
1190 using Json = nlohmann::json;
1191 for (bool reversed : {false, true}) {
1192 auto source = gateChain(64, reversed);
1193 onlyModule(source)["ports"]["tap"] = {{"direction", "output"},
1194 {"bits", Json::array({98})}};
1195 const auto result = Json::parse(legalizeExpressions(source.dump(), "silicon_gates"));
1196 EXPECT_EQ(onlyModule(result).at("cells").size(), 2);
1197 }
1198}
1199
1200TEST(YosysTest, RootlessCompatibleGateCyclesAreUnchanged)
1201{
1202 using Json = nlohmann::json;
1203 for (bool reversed : {false, true}) {
1204 auto source = gateChain(32, reversed);
1205 auto& module = onlyModule(source);
1206 module["ports"].erase("y");
1207 const auto name = std::format("g{:06}", reversed ? 31 : 0);
1208 module["cells"][name]["connections"]["A"] = Json::array({66});
1209 const auto result = Json::parse(legalizeExpressions(source.dump(), "silicon_gates"));
1210 ASSERT_EQ(onlyModule(result).at("cells").size(), 32);
1211 for (const auto& cell : onlyModule(result).at("cells"))
1212 EXPECT_EQ(cell.at("type"), "$and");
1213 }
1214}
1215#endif
std::multiset< std::string > componentTypes(const Circuit &circuit)
std::vector< Component_ptr > componentsIn(const Circuit &circuit)
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
static Circuit deserialize(const std::string &jsonStr, const ComponentRegistry &reg, const CircuitResolver *resolver=nullptr)
Deserializes the core circuit model from a JSON string.
Definition circuit.cpp:749
std::string serialize() const
Serializes the core circuit model to a JSON string.
Definition circuit.cpp:694
static ComponentRegistry empty()
static constexpr std::string_view SERIAL_TYPE
Definition register.hpp:33
static constexpr std::string_view PARALLEL_TYPE
Definition register.hpp:32
static constexpr std::string_view Type
Serialization/type-registry identifier.
static constexpr std::string_view SIGNED_MODE
static constexpr std::string_view Type
static constexpr std::string_view RIGHT_MODE
static constexpr std::string_view LEFT_MODE
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
RunResult setBus(Bus bus, BusValue value, CancellationCheck isCancelled={})
Forces a bus to a specific value and propagates the change through the circuit.
RunResult runUntilIdle(CancellationCheck isCancelled={})
Runs pending timed events until no further propagation is scheduled.
Mutable module-building interface passed to component serializers.
Definition netlist.hpp:174
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
std::shared_ptr< Component > Component_ptr
void registerAllComponents(ComponentRegistry &registry)
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
Definition wire.hpp:54
BusValue busValueFromBits(const std::string_view bits)
Strictly decodes an MSB-first raw string containing 0, 1, X, or E.
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.
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.
std::string writeVerilog(std::string_view json, 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
TEST(YosysTest, CollapsesGateTreesWithFourStateAndBusSemantics)