SILICON
Loading...
Searching...
No Matches
yosys_tool.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
20#ifndef __EMSCRIPTEN__
21TEST(YosysToolTest, RejectsMissingConfiguredExecutable)
22{
23 const auto missing = std::filesystem::temp_directory_path()
24 / "silicon_yosys_executable_that_does_not_exist";
25 try {
27 "help", SILICON::yosys::ToolOptions{.executable = missing,
28 .technologyLibraryDirectory = std::nullopt});
29 FAIL() << "Expected a missing Yosys executable to be rejected";
30 } catch (const std::runtime_error& error) {
31 EXPECT_NE(std::string(error.what()).find("executable-validation phase"),
32 std::string::npos);
33 EXPECT_NE(std::string(error.what()).find(missing.string()), std::string::npos);
34 }
35}
36
37 #if !defined(_WIN32)
38TEST(YosysToolTest, ReportsProcessCreationFailure)
39{
40 const auto path =
41 std::filesystem::temp_directory_path()
42 / std::format("silicon_yosys_non_executable_{}",
43 std::chrono::steady_clock::now().time_since_epoch().count());
44 {
45 std::ofstream file(path);
46 ASSERT_TRUE(file.good());
47 file << "not an executable";
48 }
49 std::filesystem::permissions(path, std::filesystem::perms::owner_read,
50 std::filesystem::perm_options::replace);
51
52 std::string message;
53 try {
55 "help", SILICON::yosys::ToolOptions{.executable = path,
56 .technologyLibraryDirectory = std::nullopt});
57 } catch (const std::runtime_error& error) {
58 message = error.what();
59 }
60 std::filesystem::remove(path);
61
62 EXPECT_NE(message.find("process-creation phase"), std::string::npos);
63 EXPECT_NE(message.find("'yosys' logs"), std::string::npos);
64}
65
66TEST(YosysToolTest, ReportsPathDiscoveryFailure)
67{
68 std::string message;
69 {
70 const PathEnvironmentGuard emptyPath;
71 try {
72 (void)SILICON::yosys::runScript("help");
73 } catch (const std::runtime_error& error) {
74 message = error.what();
75 }
76 }
77 EXPECT_NE(message.find("executable-discovery phase"), std::string::npos);
78 EXPECT_NE(message.find("PATH"), std::string::npos);
79}
80 #endif
81#endif
82#ifdef SILICON_TEST_YOSYS_EXECUTABLE
83
84TEST(YosysToolTest, RunsScriptsWithPathDiscoveryAndExplicitSelection)
85{
86 YosysLogCapture logCapture;
87 const auto discovered = SILICON::yosys::runScript("help echo");
88 EXPECT_FALSE(discovered.standardOutput.empty());
89
90 const SILICON::yosys::ToolOptions explicitOptions{
91 .executable = std::filesystem::path(SILICON_TEST_YOSYS_EXECUTABLE),
92 .technologyLibraryDirectory = std::nullopt};
93 const auto explicitResult = SILICON::yosys::runScript("help echo", explicitOptions);
94 EXPECT_FALSE(explicitResult.standardOutput.empty());
95 EXPECT_EQ(explicitResult.standardError, discovered.standardError);
96 EXPECT_NE(logCapture.text().find("stdout:"), std::string::npos);
97}
98
99TEST(YosysToolTest, LogsCapturedDiagnosticsAndReferencesLogs)
100{
101 YosysLogCapture logCapture;
102 std::string message;
103 try {
104 (void)SILICON::yosys::runScript("this_command_does_not_exist");
105 } catch (const std::runtime_error& error) {
106 message = error.what();
107 }
108
109 EXPECT_NE(message.find("script-execution phase"), std::string::npos);
110 EXPECT_NE(message.find("exit status"), std::string::npos);
111 EXPECT_NE(message.find("'yosys' logs"), std::string::npos);
112 EXPECT_EQ(message.find("stdout:"), std::string::npos);
113 EXPECT_EQ(message.find("stderr:"), std::string::npos);
114
115 const auto logs = logCapture.text();
116 EXPECT_NE(logs.find("stderr:"), std::string::npos);
117 EXPECT_NE(logs.find("this_command_does_not_exist"), std::string::npos);
118 EXPECT_NE(logs.find("Command failed with exit status"), std::string::npos);
119}
120
121TEST(YosysToolTest, RejectsInvalidMultiSourceInputs)
122{
124
125 const std::array unsafe{
126 SourceFile{.path = "../top.v", .contents = "module top; endmodule"}};
127 EXPECT_THROW((void)SILICON::verilog::read(unsafe, "../top.v"), std::invalid_argument);
128
129 const std::array duplicate{
130 SourceFile{.path = "code/top.v", .contents = "module top; endmodule"},
131 SourceFile{.path = "code/top.v", .contents = "module other; endmodule"}};
132 EXPECT_THROW((void)SILICON::verilog::read(duplicate, "code/top.v"),
133 std::invalid_argument);
134
135 const std::array SOURCES{
136 SourceFile{.path = "code/helper.v", .contents = "module helper; endmodule"}};
137 EXPECT_THROW((void)SILICON::verilog::read(SOURCES, "code/top.v"),
138 std::invalid_argument);
139}
140
141TEST(YosysToolTest, RejectsImplicitNets)
142{
143 YosysLogCapture logCapture;
144 std::string message;
145 try {
147 "module top(input [7:0] a, output [7:0] y); assign y = a + B; endmodule");
148 } catch (const std::runtime_error& error) {
149 message = error.what();
150 }
151
152 EXPECT_NE(message.find("script-execution phase"), std::string::npos);
153 EXPECT_NE(logCapture.text().find("Identifier `\\B' is implicitly declared"),
154 std::string::npos);
155}
156
157TEST(YosysToolTest, ResolvesTransitiveProjectIncludesWithoutParsingUnrelatedFiles)
158{
160
161 constexpr std::array SOURCES{
162 SourceFile{.path = "code/top.v", .contents = R"(`include "helper.v"
163module top(input a, output y);
164 helper child(.a(a), .y(y));
165endmodule
166)"},
167 SourceFile{.path = "code/helper.v", .contents = R"(`include "defs.v"
168module helper(input a, output y);
169 assign y = `APPLY(a);
170endmodule
171)"},
172 SourceFile{.path = "code/defs.v", .contents = "`define APPLY(signal) ~signal\n"},
173 SourceFile{.path = "code/unrelated.v",
174 .contents = "this is deliberately invalid Verilog\n"}};
175
176 const auto designJson = SILICON::verilog::read(SOURCES, "code/top.v");
177 const auto design = SILICON::yosys::Json::parse(designJson);
178 ASSERT_TRUE(design.at("modules").contains("top"));
179 ASSERT_TRUE(design.at("modules").contains("helper"));
180 EXPECT_FALSE(design.at("modules").contains("unrelated"));
181
182 const auto graph = SILICON::yosys::moduleDependencyGraph(designJson);
183 EXPECT_EQ(graph.modules(), (std::vector<std::string>{"helper", "top"}));
184 EXPECT_EQ(graph.dependenciesOf("top"), (std::vector<std::string>{"helper"}));
185
186 const auto& helperCells = design.at("modules").at("helper").at("cells");
187 ASSERT_EQ(helperCells.size(), 1);
188 EXPECT_EQ(helperCells.begin().value().at("type"), "$not");
189}
190
191TEST(YosysToolTest, ReportsMissingProjectIncludeThroughYosysDiagnostics)
192{
193 constexpr std::array SOURCES{SILICON::verilog::SourceFile{
194 .path = "code/top.v", .contents = "`include \"missing.v\"\n"}};
195 YosysLogCapture logCapture;
196 std::string message;
197 try {
198 (void)SILICON::verilog::read(SOURCES, "code/top.v");
199 } catch (const std::runtime_error& error) {
200 message = error.what();
201 }
202
203 EXPECT_NE(message.find("script-execution phase"), std::string::npos);
204 EXPECT_NE(logCapture.text().find("missing.v"), std::string::npos);
205}
206
207TEST(YosysToolTest, BuildsDependencyGraphFromMultiModuleVerilog)
208{
209 constexpr std::string_view SOURCE = R"(
210 module leaf(input a, output reg y);
211 always @* y = ~a;
212 endmodule
213 module helper(input a, output y0, output y1);
214 leaf first(.a(a), .y(y0));
215 leaf second(.a(a), .y(y1));
216 endmodule
217 module unused(input a, output y);
218 assign y = a;
219 endmodule
220 module top(
221 input a,
222 input b,
223 output y0,
224 output y1,
225 output y2,
226 output and_y,
227 output or_y,
228 output not_y
229 );
230 helper helper_instance(.a(a), .y0(y0), .y1(y1));
231 leaf leaf_instance(.a(a), .y(y2));
232 assign and_y = a & b;
233 assign or_y = a | b;
234 assign not_y = ~a;
235 endmodule
236 )";
237
238 const auto designJson = SILICON::verilog::read(SOURCE);
239 const auto design = SILICON::yosys::Json::parse(designJson);
240
241 std::set<std::string> topCellTypes;
242 for (const auto& cell : design.at("modules").at("top").at("cells"))
243 topCellTypes.insert(cell.at("type").get<std::string>());
244 EXPECT_TRUE(topCellTypes.contains("$and"));
245 EXPECT_TRUE(topCellTypes.contains("$or"));
246 EXPECT_TRUE(topCellTypes.contains("$not"));
247
248 const auto graph = SILICON::yosys::moduleDependencyGraph(designJson);
249
250 EXPECT_EQ(graph.modules(),
251 (std::vector<std::string>{"helper", "leaf", "top", "unused"}));
252 EXPECT_EQ(graph.dependenciesOf("top"), (std::vector<std::string>{"helper", "leaf"}));
253 EXPECT_EQ(graph.dependenciesOf("helper"), (std::vector<std::string>{"leaf"}));
254 EXPECT_EQ(graph.dependenciesOf("leaf"), std::vector<std::string>{});
255 EXPECT_EQ(graph.dependenciesOf("unused"), std::vector<std::string>{});
256
257 const auto top = SILICON::yosys::deserialize(designJson, "top");
258 EXPECT_EQ(componentTypes(top).count("Subcircuit"), 2);
259}
260
261TEST(YosysToolTest, ResolvesParameterizedInstancesBeforeJsonExport)
262{
263 constexpr std::string_view SOURCE = R"(
264 module leaf #(parameter WIDTH = 1)(input [WIDTH-1:0] a, output [WIDTH-1:0] y);
265 assign y = ~a;
266 endmodule
267 module helper #(parameter WIDTH = 1)(input [WIDTH-1:0] a, output [WIDTH-1:0] y);
268 leaf #(.WIDTH(WIDTH)) child(.a(a), .y(y));
269 endmodule
270 module top(input [7:0] a, output [7:0] y, output [3:0] z);
271 helper #(.WIDTH(8)) wide(.a(a), .y(y));
272 helper #(.WIDTH(4)) narrow(.a(a[3:0]), .y(z));
273 endmodule
274 module unused(input a, output y);
275 assign y = a;
276 endmodule
277 )";
278
279 const auto designJson = SILICON::verilog::read(SOURCE);
280 const auto design = SILICON::yosys::Json::parse(designJson);
281 const auto& modules = design.at("modules");
282 EXPECT_TRUE(modules.contains("unused"));
283
284 for (const auto& [instance, expectedWidth] :
285 std::array{std::pair{"wide", 8}, std::pair{"narrow", 4}}) {
286 const auto& cell = modules.at("top").at("cells").at(instance);
287 EXPECT_TRUE(cell.at("parameters").empty());
288 const auto& helper = modules.at(cell.at("type").get<std::string>());
289 EXPECT_EQ(helper.at("ports").at("a").at("bits").size(), expectedWidth);
290 const auto& child = helper.at("cells").at("child");
291 EXPECT_TRUE(child.at("parameters").empty());
292 const auto& leaf = modules.at(child.at("type").get<std::string>());
293 EXPECT_EQ(leaf.at("ports").at("y").at("bits").size(), expectedWidth);
294 }
295
296 const auto legalized = SILICON::yosys::elaborateHierarchy(designJson);
297 const auto graph = SILICON::yosys::moduleDependencyGraph(legalized);
298 for (const auto& module : graph.dependencyOrder({"top"}))
299 EXPECT_NO_THROW((void)SILICON::yosys::deserialize(legalized, module));
300}
301
302TEST(YosysToolTest, ImportsCombinationalVerilogPreservingHelperHierarchy)
303{
304 constexpr std::string_view SOURCE = R"(
305 module helper(input a, input b, output y);
306 assign y = a & b;
307 endmodule
308 module unused(input a, output y);
309 assign y = ~a;
310 endmodule
311 module selected(input a, input b, output y);
312 helper instance(.a(a), .b(b), .y(y));
313 endmodule
314 )";
315
316 const Circuit circuit = importVerilog(SOURCE, "selected");
317 // Elaboration preserves the module hierarchy, so the helper instance is kept
318 // as a subcircuit rather than flattened into its gates.
319 EXPECT_EQ(componentTypes(circuit),
320 (std::multiset<std::string>{"Subcircuit", "DummyInputComponent",
321 "DummyInputComponent", "DummyOutputComponent"}));
322 EXPECT_THROW((void)importVerilog(SOURCE, "missing"), std::runtime_error);
323}
324
325TEST(YosysToolTest, ImportsLogicalOperatorsWithVectorTruthSemantics)
326{
327 const auto verify = [](const std::string_view expression,
328 const std::string_view yosysCell,
329 const std::string_view siliconComponent, const auto& expected) {
330 const auto SOURCE = std::format("module top(input [2:0] a, input [2:0] b, output y); "
331 "assign y = {}; endmodule",
332 expression);
333
334 const auto hierarchicalJson =
336 EXPECT_NE(hierarchicalJson.find(yosysCell), std::string::npos);
337
338 const std::array circuits{
339 std::make_shared<Circuit>(SILICON::yosys::deserialize(hierarchicalJson, "top")),
340 std::make_shared<Circuit>(importVerilog(SOURCE, "top")),
341 };
342 for (const auto& circuit : circuits) {
343 EXPECT_EQ(componentTypes(*circuit).count(std::string(siliconComponent)), 1);
344 EXPECT_EQ(componentTypes(*circuit).count("WireSplitter"), 0);
345 EXPECT_EQ(componentTypes(*circuit).count("WireMerger"), 0);
346 for (unsigned int a = 0; a < 8; ++a) {
347 for (unsigned int b = 0; b < 8; ++b) {
348 SCOPED_TRACE(std::format("{} with a={} b={}", expression, a, b));
349 EXPECT_EQ(evaluateBinaryCircuit(circuit, a, b),
350 valueFor(1, expected(a != 0, b != 0)));
351 }
352 }
353 }
354 };
355
356 verify("a && b", "$logic_and", "AndGate",
357 [](const bool a, const bool b) { return a && b; });
358 verify("a || b", "$logic_or", "OrGate",
359 [](const bool a, const bool b) { return a || b; });
360}
361
362TEST(YosysToolTest, ImportsLogicalNotAsOneGate)
363{
364 constexpr std::string_view SOURCE =
365 "module top(input [2:0] a, output y); assign y = !a; endmodule";
366 auto circuit = std::make_shared<Circuit>(importVerilog(SOURCE, "top"));
367
368 EXPECT_EQ(componentTypes(*circuit).count("NotGate"), 1);
369 EXPECT_EQ(componentTypes(*circuit).count("OrGate"), 0);
370 EXPECT_EQ(componentTypes(*circuit).count("WireSplitter"), 0);
371 ASSERT_TRUE(findComponent<NotGate>(*circuit));
372 EXPECT_EQ(findComponent<NotGate>(*circuit)->getPropertyValue<int>("size"), 1);
373 const auto serialized = SILICON::yosys::serialize(*circuit, "top");
374 EXPECT_NE(serialized.find("$logic_not"), std::string::npos);
375
376 const auto input = findNamedComponent<DummyBusInputComponent>(*circuit, "a");
377 const auto output = findNamedComponent<DummyOutputComponent>(*circuit, "y");
378 ASSERT_TRUE(input);
379 ASSERT_TRUE(output);
380
381 input->setBusValue(valueFor(input->outputBuses()[0], 0));
382 Simulator simulator(circuit);
383 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
384 EXPECT_EQ(output->inputBuses()[0].getCurrentValue(), valueFor(1, 1));
385
386 ASSERT_EQ(
387 simulator.setBus(input->outputBuses()[0], valueFor(input->outputBuses()[0], 2)),
388 Simulator::RunResult::Completed);
389 EXPECT_EQ(output->inputBuses()[0].getCurrentValue(), valueFor(1, 0));
390}
391
392TEST(YosysToolTest, KeepsAluLogicalOperationsAndVectorNotCompact)
393{
394 constexpr std::string_view SOURCE = R"(
395 module alu(
396 input [2:0] opcode,
397 input [7:0] OperandA,
398 input B,
399 output reg [7:0] result
400 );
401 always @* begin
402 case (opcode)
403 3'b000: result = OperandA + B;
404 3'b001: result = OperandA - B;
405 3'b100: result = OperandA && B;
406 3'b101: result = OperandA || B;
407 3'b110: result = ~OperandA;
408 3'b111: result = OperandA ^ OperandA;
409 default: result = 0;
410 endcase
411 end
412 endmodule
413 )";
414
415 const Circuit circuit = importVerilog(SOURCE, "alu");
416 const auto types = componentTypes(circuit);
417 EXPECT_EQ(types.count("AndGate"), 1);
418 EXPECT_EQ(types.count("OrGate"), 1);
419 EXPECT_EQ(types.count("NotGate"), 1);
420 EXPECT_EQ(types.count("Multiplexer"), 1);
421 EXPECT_LT(types.size(), 25);
422 ASSERT_TRUE(findComponent<NotGate>(circuit));
423 EXPECT_EQ(findComponent<NotGate>(circuit)->getPropertyValue<int>("size"), 8);
424}
425
426TEST(YosysToolTest, ImportsOnlyASingleDiscoveredModule)
427{
428 const auto discover = [](const std::string_view SOURCE) -> std::string {
429 const auto modules =
431 if (modules.size() != 1)
432 throw std::runtime_error("Verilog source must declare exactly one module");
433 return modules.front();
434 };
435
436 const std::string_view SOURCE =
437 "module sole(input a, output y); assign y = ~a; endmodule";
438 const auto top = discover(SOURCE);
439 const auto circuit = importVerilog(SOURCE, top);
440 EXPECT_EQ(top, "sole");
441
442 EXPECT_THROW((void)discover(""), std::runtime_error);
443 EXPECT_THROW((void)discover("module first; endmodule module second; endmodule"),
444 std::runtime_error);
445}
446
447TEST(YosysToolTest, ImportsZeroExtendedOutputAsUnsignedExtender)
448{
449 constexpr std::string_view SOURCE = R"(
450 module a(output [7:0] bus_out, input in);
451 assign bus_out = { 7'h00, in };
452 endmodule
453 )";
454
455 const Circuit circuit = importVerilog(SOURCE, "a");
456 const auto extender = findComponent<Extender>(circuit);
457 ASSERT_TRUE(extender);
458 EXPECT_EQ(extender->getPropertyValue<int>("inSize"), 1);
459 EXPECT_EQ(extender->getPropertyValue<int>("outSize"), 8);
460 EXPECT_EQ(extender->getPropertyValue<std::string>("mode"),
461 std::string(Extender::UNSIGNED_MODE));
462 EXPECT_FALSE(findComponent<ConstantComponent>(circuit));
463}
464
465TEST(YosysToolTest, RaisesSharedConstantEqualityComparisonsToDecoder)
466{
467 #ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
468 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
469 #else
470 constexpr std::string_view SOURCE = R"(
471 module top(input [2:0] select, output [1:0] matches);
472 assign matches[0] = select == 3'd1;
473 assign matches[1] = 3'd6 == select;
474 endmodule
475 )";
476
477 auto circuit = std::make_shared<Circuit>(importVerilog(SOURCE, "top"));
478 auto decoder = findComponent<Decoder>(*circuit);
479 ASSERT_TRUE(decoder);
480 EXPECT_EQ(decoder->getPropertyValue<int>("selectionSize"), 3);
481 EXPECT_EQ(componentTypes(*circuit).count("Decoder"), 1);
482
483 Simulator simulator(circuit);
484 ASSERT_EQ(
485 simulator.setBus(decoder->inputBuses()[1], valueFor(decoder->inputBuses()[1], 1)),
486 Simulator::RunResult::Completed);
487 EXPECT_EQ(decoder->outputBuses()[0][1]->getCurrentState(), State::HIGH);
488 EXPECT_EQ(decoder->outputBuses()[0][6]->getCurrentState(), State::LOW);
489
490 ASSERT_EQ(
491 simulator.setBus(decoder->inputBuses()[1], valueFor(decoder->inputBuses()[1], 6)),
492 Simulator::RunResult::Completed);
493 EXPECT_EQ(decoder->outputBuses()[0][1]->getCurrentState(), State::LOW);
494 EXPECT_EQ(decoder->outputBuses()[0][6]->getCurrentState(), State::HIGH);
495
496 ASSERT_EQ(
497 simulator.setBus(decoder->inputBuses()[1], valueFor(decoder->inputBuses()[1], 3)),
498 Simulator::RunResult::Completed);
499 EXPECT_EQ(decoder->outputBuses()[0][1]->getCurrentState(), State::LOW);
500 EXPECT_EQ(decoder->outputBuses()[0][6]->getCurrentState(), State::LOW);
501 #endif
502}
503
504TEST(YosysToolTest, LegalizationAcceptsTechnologyMapPathWithSpaces)
505{
506#ifndef SILICON_TEST_YOSYS_PLUGIN_PATH
507 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
508#else
509 const auto directory = std::filesystem::temp_directory_path()
510 / std::format("silicon technology map {}",
511 std::chrono::steady_clock::now().time_since_epoch().count());
512 std::filesystem::create_directories(directory);
513 try {
514 // This design needs no technology cells, but the pipeline must still load
515 // the map through the nested techmap invocation.
516 { std::ofstream file(directory / "silicon_cells.v"); file << "// empty library\n"; }
517 { std::ofstream file(directory / "silicon_techmap.v"); file << "// empty map\n"; }
518 const SILICON::yosys::ToolOptions options{
519 .executable = std::nullopt,
520 .technologyLibraryDirectory = directory};
521 const auto raw = SILICON::yosys::readVerilog(
522 "module top(input a, output y); assign y = a; endmodule", options);
523 const auto legalized = SILICON::yosys::elaborateHierarchy(raw, options);
524 EXPECT_NO_THROW((void)SILICON::yosys::deserialize(legalized, "top"));
525 } catch (...) {
526 std::filesystem::remove_all(directory);
527 throw;
528 }
529 std::filesystem::remove_all(directory);
530#endif
531}
532
533TEST(YosysToolTest, PmgenMatchesSelectedPmuxWithUnselectedPredicates)
534{
535 #ifndef SILICON_TEST_YOSYS_PLUGIN_PATH
536 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
537 #else
538 constexpr std::string_view SOURCE = R"(
539 module top(
540 input [1:0] select,
541 input [3:0] lane0,
542 input [3:0] lane1,
543 input [3:0] lane2,
544 input [3:0] lane3,
545 output reg [3:0] y
546 );
547 always @* begin
548 case (select)
549 2'd0: y = lane0;
550 2'd1: y = lane1;
551 2'd2: y = lane2;
552 2'd3: y = lane3;
553 endcase
554 end
555 endmodule
556 )";
557
558 EXPECT_NO_THROW(runPluginScript(SOURCE,
559 "hierarchy -check -top top\n"
560 "proc\n"
561 "muxpack\n"
562 "select top/t:$pmux\n"
563 "silicon_pmux_bmux\n"
564 "select -assert-count 1 top/t:$bmux\n"
565 "select -assert-count 0 top/t:$pmux\n",
566 "selected_pmux"));
567 #endif
568}
569
570TEST(YosysToolTest, PmgenLeavesInvalidGroupsAndRaisesValidSignedGroup)
571{
572 #ifndef SILICON_TEST_YOSYS_PLUGIN_PATH
573 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
574 #else
575 constexpr std::string_view SOURCE = R"(
576 module top(
577 input [2:0] first,
578 input [2:0] second,
579 input signed [2:0] signed_select,
580 output [5:0] matches
581 );
582 assign matches[0] = first == 3'd1;
583 assign matches[1] = first == 3'd3;
584 assign matches[2] = first == 3'd3;
585 assign matches[3] = second == 3'd2;
586 assign matches[4] = signed_select == 3'sd1;
587 assign matches[5] = signed_select == 3'sd2;
588 endmodule
589 )";
590
591 EXPECT_NO_THROW(runPluginScript(SOURCE,
592 "hierarchy -check -top top\n"
593 "proc\n"
594 "silicon_eq_decoder\n"
595 "select -assert-count 4 top/t:$eq\n"
596 "select -assert-count 1 top/t:$demux\n",
597 "invalid_eq_groups"));
598 #endif
599}
600
601TEST(YosysToolTest, FoldsPrivateClockedRomAddressInPlugin)
602{
603 #ifndef SILICON_TEST_YOSYS_PLUGIN_PATH
604 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
605 #else
606 constexpr std::string_view SOURCE = R"(
607 module top(input clk, input en, input [1:0] addr, output [7:0] data);
608 reg [1:0] saved_addr;
609 reg [7:0] rom [0:3];
610 initial begin
611 rom[0] = 8'h12; rom[1] = 8'h34;
612 rom[2] = 8'h56; rom[3] = 8'h78;
613 end
614 always @(posedge clk) if (en) saved_addr <= addr;
615 assign data = rom[saved_addr];
616 endmodule
617 )";
618 EXPECT_NO_THROW(runPluginScript(SOURCE,
619 "hierarchy -check -top top\n"
620 "proc\n"
621 "memory_collect\n"
622 "opt -nosdff\n"
623 "memory_dff\n"
624 "select -assert-count 1 top/t:$dffe\n"
625 "select -assert-count 1 top/t:$mux\n"
626 "silicon_memrd_address\n"
627 "select -assert-count 0 top/t:$dffe\n"
628 "select -assert-count 0 top/t:$mux\n"
629 "select -assert-count 1 top/t:$mem_v2\n",
630 "private_rom_address"));
631 #endif
632}
633
634TEST(YosysToolTest, KeepsRomAddressRegisterWithExternalConsumer)
635{
636 #ifndef SILICON_TEST_YOSYS_PLUGIN_PATH
637 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
638 #else
639 constexpr std::string_view SOURCE = R"(
640 module top(input clk, input en, input [1:0] addr,
641 output [1:0] saved, output [7:0] data);
642 reg [1:0] saved_addr;
643 reg [7:0] rom [0:3];
644 initial begin
645 rom[0] = 8'h12; rom[1] = 8'h34;
646 rom[2] = 8'h56; rom[3] = 8'h78;
647 end
648 always @(posedge clk) if (en) saved_addr <= addr;
649 assign saved = saved_addr;
650 assign data = rom[saved_addr];
651 endmodule
652 )";
653 EXPECT_NO_THROW(runPluginScript(SOURCE,
654 "hierarchy -check -top top\n"
655 "proc\n"
656 "memory_collect\n"
657 "opt -nosdff\n"
658 "memory_dff\n"
659 "silicon_memrd_address\n"
660 "select -assert-count 1 top/t:$dffe\n"
661 "select -assert-count 1 top/t:$mux\n",
662 "shared_rom_address"));
663 #endif
664}
665
666TEST(YosysToolTest, KeepsRomAddressRegisterWithResetOrInitialization)
667{
668 #ifndef SILICON_TEST_YOSYS_PLUGIN_PATH
669 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
670 #else
671 constexpr std::string_view SOURCE = R"(
672 module top(input clk, input en, input rst, input [1:0] addr,
673 output [7:0] data);
674 reg [1:0] saved_addr;
675 reg [7:0] rom [0:3];
676 initial begin
677 rom[0] = 8'h12; rom[1] = 8'h34;
678 rom[2] = 8'h56; rom[3] = 8'h78;
679 end
680 always @(posedge clk) if (en) saved_addr <= addr;
681 assign data = rom[saved_addr];
682 endmodule
683 )";
684
685 constexpr std::array cases{
686 std::pair{"read_arst", "connect -port rom RD_ARST rst\n"
687 "setparam -set RD_ARST_VALUE 8'h00 rom\n"},
688 std::pair{"read_srst", "connect -port rom RD_SRST rst\n"
689 "setparam -set RD_SRST_VALUE 8'h00 rom\n"},
690 std::pair{"read_init", "setparam -set RD_INIT_VALUE 8'h00 rom\n"},
691 std::pair{"address_init", "setattr -set init 2'bx1 saved_addr\n"}};
692
693 for (const auto& [name, change] : cases) {
694 SCOPED_TRACE(name);
695 EXPECT_NO_THROW(runPluginScript(
696 SOURCE,
697 std::format("hierarchy -check -top top\n"
698 "proc\n"
699 "memory_collect\n"
700 "opt -nosdff\n"
701 "memory_dff\n"
702 "select -assert-count 1 top/t:$dffe\n"
703 "select -assert-count 1 top/t:$mux\n"
704 "cd top\n"
705 "{}"
706 "cd\n"
707 "silicon_memrd_address\n"
708 "select -assert-count 1 top/t:$dffe\n"
709 "select -assert-count 1 top/t:$mux\n"
710 "select -assert-count 1 top/t:$mem_v2\n",
711 change),
712 name));
713 }
714 #endif
715}
716
717TEST(YosysToolTest, LowersPriorityMuxCellsBeforeImport)
718{
719 constexpr std::string_view SOURCE = R"(
720 module top(
721 input [1:0] fallback,
722 input [1:0] lane0,
723 input [1:0] lane1,
724 input [1:0] lane2,
725 input [2:0] select,
726 output reg [1:0] y
727 );
728 always @* begin
729 y = fallback;
730 (* parallel_case *)
731 casez (select)
732 3'b??1: y = lane0;
733 3'b?1?: y = lane1;
734 3'b1??: y = lane2;
735 endcase
736 end
737 endmodule
738 )";
739
740 const Circuit circuit = importVerilog(SOURCE, "top");
741 EXPECT_GT(componentTypes(circuit).count("Multiplexer"), 0);
742}
743
744TEST(YosysToolTest, ImportsSequentialVerilog)
745{
746 constexpr std::string_view SOURCE = R"(
747 module storage(input d, input clk, output reg q);
748 always @(posedge clk)
749 q <= d;
750 endmodule
751 )";
752 const Circuit circuit = importVerilog(SOURCE, "storage");
753 EXPECT_TRUE(componentTypes(circuit).contains("DFlipFlop"));
754}
755
756TEST(YosysToolTest, FoldsSparseCaseIntoOneWideMultiplexer)
757{
758 #ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
759 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
760 #endif
761 constexpr std::string_view SOURCE = R"(
762 module top(
763 input [7:0] a,
764 input [7:0] b,
765 input [3:0] select,
766 output reg [7:0] y
767 );
768 always @* begin
769 case (select)
770 4'h1: y = a;
771 4'h6: y = b;
772 4'hd: y = a ^ b;
773 default: y = 8'h00;
774 endcase
775 end
776 endmodule
777 )";
778
779 const Circuit circuit = importVerilog(SOURCE, "top");
780 EXPECT_EQ(componentTypes(circuit).count("Multiplexer"), 1);
781 EXPECT_EQ(componentTypes(circuit).count("Decoder"), 0);
782 EXPECT_EQ(componentTypes(circuit).count("OrGate"), 0);
783}
784
785TEST(YosysToolTest, KeepsSynchronousResetAsScalarMuxAndDFlipFlop)
786{
787 constexpr std::string_view SOURCE = R"(
788 module sdff_test(
789 input wire clk,
790 input wire rst,
791 input wire d,
792 output reg q
793 );
794 always @(posedge clk) begin
795 if (rst)
796 q <= 1'b0;
797 else
798 q <= d;
799 end
800 endmodule
801 )";
802
803 const Circuit circuit = importVerilog(SOURCE, "sdff_test");
804 EXPECT_EQ(componentTypes(circuit).count("Multiplexer"), 1);
805 EXPECT_EQ(componentTypes(circuit).count("DFlipFlop"), 1);
806 EXPECT_EQ(componentTypes(circuit).count("WireMerger"), 0);
807
808 const auto mux = findComponent<Multiplexer>(circuit);
809 ASSERT_TRUE(mux);
810 ASSERT_EQ(mux->inputBuses().size(), 3);
811 EXPECT_EQ(mux->inputBuses()[0].size(), 1);
812 EXPECT_EQ(mux->inputBuses()[1].size(), 1);
813 EXPECT_EQ(mux->inputBuses()[2].size(), 1);
814}
815
816TEST(YosysToolTest, FoldsExhaustiveCaseIntoOneWideMultiplexer)
817{
818 #ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
819 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
820 #endif
821 constexpr std::string_view SOURCE = R"(
822 module mux(
823 input [3:0] bus_1,
824 input [3:0] bus_2,
825 input [3:0] bus_3,
826 input [3:0] bus_4,
827 input [1:0] bus_in,
828 output reg [3:0] bus_out
829 );
830 always @* begin
831 case (bus_in)
832 2'h0: bus_out = bus_1;
833 2'h1: bus_out = bus_2;
834 2'h2: bus_out = bus_3;
835 2'h3: bus_out = bus_4;
836 default: bus_out = 4'hx;
837 endcase
838 end
839 endmodule
840 )";
841
842 const Circuit circuit = importVerilog(SOURCE, "mux");
843 EXPECT_EQ(componentTypes(circuit).count("Multiplexer"), 1);
844 EXPECT_EQ(componentTypes(circuit).count("Decoder"), 0);
845 EXPECT_EQ(componentTypes(circuit).count("OrGate"), 0);
846
847 const auto mux = findComponent<Multiplexer>(circuit);
848 ASSERT_TRUE(mux);
849 EXPECT_EQ(mux->getPropertyValue<int>("selectionSize"), 2);
850 EXPECT_EQ(mux->getPropertyValue<int>("busSize"), 4);
851 EXPECT_EQ(mux->inputBuses().size(), 5);
852}
853
854TEST(YosysToolTest, ImportsCaseLiteralLanesAsSizedConstants)
855{
856 #ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
857 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
858 #endif
859 constexpr std::string_view SOURCE = R"(
860 module my_mux(input [1:0] a, input [3:0] b, c, output reg [3:0] o);
861 always @(a, b, c) begin
862 case (a)
863 2'b00: o = b;
864 2'b01: o = c;
865 2'b11: o = 4;
866 default: o = 3;
867 endcase
868 end
869 endmodule
870 )";
871
872 const Circuit circuit = importVerilog(SOURCE, "my_mux");
873 EXPECT_EQ(componentTypes(circuit).count("Multiplexer"), 1);
874 EXPECT_EQ(componentTypes(circuit).count("ConstantComponent"), 2);
875 EXPECT_EQ(componentTypes(circuit).count("WireMerger"), 0);
876 EXPECT_EQ(componentTypes(circuit).count("WireSplitter"), 0);
877
878 std::set<BusValue> values;
879 for (const auto& component : componentsIn(circuit)) {
880 if (auto constant = std::dynamic_pointer_cast<ConstantComponent>(component)) {
881 EXPECT_EQ(constant->getPropertyValue<int>("size"), 4);
882 values.insert(*constant->getPropertyValue<BusValue>("value"));
883 }
884 }
885 EXPECT_EQ(values,
886 (std::set<BusValue>{busValueFromBits("0011"), busValueFromBits("0100")}));
887}
888
889TEST(YosysTest, LegalizesScalarActiveHighNativeDlatch)
890{
892
893 auto latch =
894 std::make_shared<DLatch>(std::make_shared<Wire>(), std::make_shared<Wire>(),
895 std::make_shared<Wire>(), std::make_shared<Wire>());
896 auto design = nlohmann::json::parse(
897 SILICON::yosys::serialize(circuitWithBoundaryPorts(latch), "top"));
898 auto& cell = onlyModule(design)["cells"].begin().value();
899 cell["type"] = "$dlatch";
900 cell["parameters"]["WIDTH"] = SerializationContext::parameter(1);
901 cell["connections"].erase("QN");
902 cell["port_directions"].erase("QN");
903
904 EXPECT_TRUE(findComponent<DLatch>(SILICON::yosys::deserialize(
905 SILICON::yosys::elaborateHierarchy(design.dump()), "top")));
906
907 cell["parameters"]["EN_POLARITY"] = SerializationContext::parameter(0, 1);
908 EXPECT_THROW((void)SILICON::yosys::deserialize(
909 SILICON::yosys::elaborateHierarchy(design.dump()), "top"),
910 std::runtime_error);
911
912 cell["parameters"]["EN_POLARITY"] = SerializationContext::parameter(1, 1);
913 cell["parameters"]["WIDTH"] = SerializationContext::parameter(2);
914 EXPECT_THROW((void)SILICON::yosys::deserialize(
915 SILICON::yosys::elaborateHierarchy(design.dump()), "top"),
916 std::runtime_error);
917}
918
919#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 constexpr std::string_view UNSIGNED_MODE
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
ModuleNameList modules() const
Returns every declared module name.
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::optional< Mux > mux(Cell *cell, SigMap &signals)
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
std::string read(const std::string_view source, const yosys::ToolOptions &options)
Definition verilog.cpp:477
core::SourceFile SourceFile
Definition verilog.hpp:33
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)
ModuleDependencyGraph moduleDependencyGraph(const std::string_view json)
Build a module dependency graph from a Yosys write_json document.
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
std::string readVerilog(const std::string_view source, const ToolOptions &options)
TEST(YosysToolTest, RejectsMissingConfiguredExecutable)
BusValue valueFor(const Bus &bus, const std::uint64_t value)
Definition tests.hpp:11