SILICON
Loading...
Searching...
No Matches
yosys_legalization.cpp
Go to the documentation of this file.
2
3namespace {
6
7Json expression(const std::string& type, int aWidth, int bWidth, int yWidth,
8 bool aSigned = false, bool bSigned = false)
9{
10 int next = 2;
11 Json a = signalBits(next, aWidth);
12 Json b = signalBits(next, bWidth);
13 Json y = signalBits(next, yWidth);
14 Json parameters{{"A_SIGNED", SerializationContext::parameter(aSigned, 1)},
15 {"A_WIDTH", SerializationContext::parameter(aWidth)},
16 {"Y_WIDTH", SerializationContext::parameter(yWidth)}};
17 Json connections{{"A", a}, {"Y", y}};
18 if (type != "$logic_not") {
19 parameters["B_SIGNED"] = SerializationContext::parameter(bSigned, 1);
20 parameters["B_WIDTH"] = SerializationContext::parameter(bWidth);
21 connections["B"] = b;
22 }
23 return Json{{"modules",
24 {{"top", {{"ports", Json::object()},
25 {"cells", {{"op", {{"type", type},
26 {"parameters", parameters},
27 {"connections", connections}}}}}}}}}};
28}
29} // namespace
30
31#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
32namespace {
33const Json& operation(const Json& design)
34{
35 return design.at("modules").at("top").at("cells").at("op");
36}
37int parameter(const Json& cell, const char* name)
38{
39 return std::stoi(cell.at("parameters").at(name).get<std::string>(), nullptr, 2);
40}
41} // namespace
42
43TEST(YosysLegalizationTest, LogicalPassPreservesWholeOperandTruthAndNarrowsResults)
44{
45 for (const auto& [type, mode] : std::array<std::pair<const char*, int>, 3>{
46 {{"$logic_and", 0}, {"$logic_or", 1}, {"$logic_not", 2}}}) {
47 for (int width : {1, 4}) {
48 auto source = expression(type, width, 3, 3);
49 const auto first = Json::parse(legalizeExpressions(source.dump(), "silicon_logic"));
50 const auto& cell = operation(first);
51 EXPECT_EQ(cell.at("type"), "SILICON_LOGIC");
52 EXPECT_EQ(parameter(cell, "MODE"), mode);
53 EXPECT_EQ(parameter(cell, "A_WIDTH"), width);
54 EXPECT_EQ(cell.at("connections").at("A").size(), width);
55 EXPECT_EQ(cell.at("connections").at("Y").size(), 1);
56 EXPECT_EQ(operation(Json::parse(legalizeExpressions(first.dump(), "silicon_logic"))), cell);
57 EXPECT_NO_THROW((void)SILICON::yosys::deserialize(first.dump()));
58 }
59 }
60}
61
62TEST(YosysLegalizationTest, ComparisonPassNormalizesWidthsModesAndSignedness)
63{
64 for (const auto& [type, mode] : std::array<std::pair<const char*, int>, 5>{
65 {{"$eq", 0}, {"$lt", 1}, {"$le", 2}, {"$gt", 3}, {"$ge", 4}}}) {
66 for (const auto& [aSigned, bSigned] : {std::pair{false, false},
67 std::pair{true, true}, std::pair{true, false}}) {
68 const auto first = Json::parse(legalizeExpressions(
69 expression(type, 3, 5, 3, aSigned, bSigned).dump(), "silicon_compare"));
70 const auto& cell = operation(first);
71 EXPECT_EQ(cell.at("type"), "SILICON_COMPARE");
72 EXPECT_EQ(parameter(cell, "WIDTH"), 5);
73 EXPECT_EQ(parameter(cell, "MODE"), mode);
74 EXPECT_EQ(parameter(cell, "SIGNED"), aSigned && bSigned);
75 EXPECT_EQ(cell.at("connections").at("A").size(), 5);
76 EXPECT_EQ(cell.at("connections").at("B").size(), 5);
77 EXPECT_EQ(cell.at("connections").at("Y").size(), 1);
78 EXPECT_EQ(cell.at("connections").at("A").at(3),
79 aSigned && bSigned ? cell.at("connections").at("A").at(2) : Json("0"));
80 EXPECT_EQ(operation(Json::parse(legalizeExpressions(first.dump(), "silicon_compare"))), cell);
81 EXPECT_NO_THROW((void)SILICON::yosys::deserialize(first.dump()));
82 }
83 }
84}
85
86TEST(YosysLegalizationTest, InequalityPassInvertsEqualityAndIsIdempotent)
87{
88 const auto source = comparisonDesign("$ne", 3, 5, 3, true, true);
89 const auto first = Json::parse(legalizeExpressions(source.dump(), "silicon_compare"));
90 const auto& module = first.at("modules").at("top");
91 const auto& cells = module.at("cells");
92 ASSERT_EQ(cells.size(), 2);
93 const auto& compare = cells.at("compare");
94 EXPECT_EQ(compare.at("type"), "SILICON_COMPARE");
95 EXPECT_EQ(parameter(compare, "MODE"), 0);
96 EXPECT_EQ(parameter(compare, "WIDTH"), 5);
97 EXPECT_EQ(parameter(compare, "SIGNED"), 1);
98 for (const auto& cell : cells) {
99 if (cell.at("type") != "$not")
100 continue;
101 EXPECT_EQ(cell.at("connections").at("A"), compare.at("connections").at("Y"));
102 EXPECT_EQ(cell.at("connections").at("Y").at(0),
103 module.at("ports").at("y").at("bits").at(0));
104 }
105 EXPECT_EQ(module.at("ports").at("y").at("bits").at(1), "0");
106 EXPECT_EQ(module.at("ports").at("y").at("bits").at(2), "0");
107 const auto second = Json::parse(legalizeExpressions(first.dump(), "silicon_compare"));
108 EXPECT_EQ(second.at("modules"), first.at("modules"));
109 EXPECT_NO_THROW((void)SILICON::yosys::deserialize(first.dump()));
110}
111
112TEST(YosysLegalizationTest, ShiftPassNormalizesWidthDirectionAndArithmeticMode)
113{
114 for (const auto& [type, direction] : std::array<std::pair<const char*, int>, 3>{
115 {{"$shl", 0}, {"$shr", 1}, {"$sshr", 1}}}) {
116 for (bool sign : {false, true}) {
117 for (const auto& [aWidth, yWidth] : {std::pair{3, 5}, std::pair{5, 3}}) {
118 const auto first = Json::parse(legalizeExpressions(
119 expression(type, aWidth, 2, yWidth, sign).dump(), "silicon_shift"));
120 const auto& cell = operation(first);
121 EXPECT_EQ(cell.at("type"), "SILICON_SHIFT");
122 EXPECT_EQ(parameter(cell, "WIDTH"), yWidth);
123 EXPECT_EQ(parameter(cell, "DIRECTION"), direction);
124 EXPECT_EQ(parameter(cell, "ARITHMETIC"), type == std::string("$sshr") && sign);
125 EXPECT_EQ(cell.at("connections").at("A").size(), yWidth);
126 EXPECT_EQ(cell.at("connections").at("B").size(), 2);
127 EXPECT_EQ(operation(Json::parse(legalizeExpressions(first.dump(), "silicon_shift"))), cell);
128 EXPECT_NO_THROW((void)SILICON::yosys::deserialize(first.dump()));
129 }
130 }
131 }
132 EXPECT_THROW((void)legalizeExpressions(expression("$shr", 3, 2, 3, false, true).dump(),
133 "silicon_shift"), std::runtime_error);
134}
135
136TEST(YosysLegalizationTest, FinalValidationRejectsUnsupportedCell)
137{
138 EXPECT_THROW(
139 (void)legalizeExpressions(expression("$pow", 3, 3, 3).dump(), "silicon_validate"),
140 std::runtime_error);
141}
142
143TEST(YosysLegalizationTest, DynamicSelectionsPreserveSignedOffsetsAndUnknownPadding)
144{
145 const auto passes = std::format("silicon_legalize \"{}/silicon_techmap.v\"",
146 SILICON_TEST_YOSYS_RESOURCE_DIR);
147 for (int aWidth : {1, 3, 5}) {
148 for (int yWidth : {1, 2, 7}) {
149 for (int bWidth : {1, 5, 32}) {
150 for (bool sign : {false, true}) {
151 SCOPED_TRACE(std::format("aWidth={} yWidth={} bWidth={} signed={}", aWidth,
152 yWidth, bWidth, sign));
153 auto design = subtractionDesign(aWidth, bWidth, yWidth, false, sign);
154 onlyModule(design)["cells"].begin().value()["type"] = "$shiftx";
155 const auto legalized = legalizeExpressions(design.dump(), passes);
156 const auto circuit =
157 std::make_shared<Circuit>(SILICON::yosys::deserialize(legalized));
158 const auto inputA = findNamedComponent<Component>(*circuit, "a");
159 const auto inputB = findNamedComponent<Component>(*circuit, "b");
160 const auto output = findNamedComponent<Component>(*circuit, "y");
161 ASSERT_TRUE(inputA);
162 ASSERT_TRUE(inputB);
163 ASSERT_TRUE(output);
164 Simulator simulator(circuit);
165 for (unsigned a : {0u, 1u, 5u, 31u}) {
166 for (unsigned rawB : {0u, 1u, 2u, 3u, 4u, 7u, 15u, 16u, 17u, 30u, 31u,
167 0x80000000u, 0xffffffffu}) {
168 const auto b = rawB & ((std::uint64_t{1} << bWidth) - 1);
169 const std::int64_t offset =
170 sign && (b & (std::uint64_t{1} << (bWidth - 1)))
171 ? static_cast<std::int64_t>(b) - (std::int64_t{1} << bWidth)
172 : static_cast<std::int64_t>(b);
173 BusValue expected(yWidth, State::UNKNOWN);
174 for (int bit = 0; bit < yWidth; ++bit) {
175 const auto index = offset + bit;
176 if (index >= 0 && index < aWidth)
177 expected[bit] = (a & (1u << index)) ? State::HIGH : State::LOW;
178 }
179 SCOPED_TRACE(std::format("a={} offset={}", a, offset));
180 ASSERT_EQ(
181 simulator.setBus(inputA->outputBuses()[0], valueFor(aWidth, a), inputA),
182 Simulator::RunResult::Completed);
183 ASSERT_EQ(
184 simulator.setBus(inputB->outputBuses()[0], valueFor(bWidth, b), inputB),
185 Simulator::RunResult::Completed);
186 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
187 EXPECT_EQ(output->inputBuses()[0].getCurrentValue(), expected);
188 }
189 }
190 EXPECT_EQ(
191 Json::parse(legalizeExpressions(legalized, "silicon_shift")).at("modules"),
192 Json::parse(legalized).at("modules"));
193 }
194 }
195 }
196 }
197}
198
199TEST(YosysLegalizationTest, ZeroMinusOperandLowersToNegWithSubtractionSignedness)
200{
201 for (bool aSigned : {false, true}) {
202 for (bool bSigned : {false, true}) {
203 for (int resultWidth : {2, 3, 6}) {
204 SCOPED_TRACE(std::format("aSigned={} bSigned={} resultWidth={}",
205 aSigned, bSigned, resultWidth));
206 auto source = subtractionDesign(5, 3, resultWidth, aSigned, bSigned);
207 auto& sourceCell = onlyModule(source)["cells"].begin().value();
208 sourceCell["connections"]["A"] = Json::array({"0", "0", "0", "0", "0"});
209 const auto passes = std::format("techmap -map \"{}/silicon_techmap.v\"\n"
210 "silicon_validate", SILICON_TEST_YOSYS_RESOURCE_DIR);
211 const auto mapped = Json::parse(legalizeExpressions(source.dump(), passes));
212 const auto cell = onlyCell(mapped);
213 ASSERT_EQ(cell.at("type"), "$neg");
214 EXPECT_EQ(parameter(cell, "A_SIGNED"), aSigned && bSigned);
215 EXPECT_EQ(parameter(cell, "A_WIDTH"), 3);
216 EXPECT_EQ(parameter(cell, "Y_WIDTH"), resultWidth);
217 EXPECT_EQ(cell.at("connections").at("A"),
218 sourceCell.at("connections").at("B"));
219 EXPECT_EQ(Json::parse(legalizeExpressions(mapped.dump(), passes)).at("modules"),
220 mapped.at("modules"));
221
222 const auto circuit =
223 std::make_shared<Circuit>(SILICON::yosys::deserialize(mapped.dump()));
224 EXPECT_EQ(componentTypes(*circuit).count("Complementer"), 1);
225 EXPECT_EQ(componentTypes(*circuit).count("AdderNBits"), 0);
226 for (unsigned int b = 0; b < 8; ++b) {
227 const int operand = aSigned && bSigned && (b & 4u)
228 ? static_cast<int>(b) - 8 : static_cast<int>(b);
229 EXPECT_EQ(evaluateBinaryCircuit(circuit, 0, b),
230 valueFor(resultWidth, static_cast<unsigned int>(-operand)
231 & ((1u << resultWidth) - 1)));
232 }
233 }
234 }
235 }
236}
237
238TEST(YosysLegalizationTest, SubtractionWithNonzeroOrUnknownMinuendStaysSub)
239{
240 for (const auto& bits : {Json::array({"1", "0", "0"}),
241 Json::array({"x", "0", "0"}),
242 Json::array({2, "0", "0"})}) {
243 auto source = subtractionDesign(3, 3, 3, false, false);
244 onlyModule(source)["cells"].begin().value()["connections"]["A"] = bits;
245 const auto mapped = Json::parse(legalizeExpressions(source.dump(), std::format(
246 "techmap -map \"{}/silicon_techmap.v\"", SILICON_TEST_YOSYS_RESOURCE_DIR)));
247 EXPECT_EQ(onlyCell(mapped).at("type"), "$sub");
248 }
249}
250#endif
251
252TEST(YosysLegalizationEndToEndTest, ImportsComparisonsAndShiftsFromVerilog)
253{
254#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
255 struct Case { const char* expression; const char* component; int a; int b; int y; int width; };
256 const std::array cases{
257 Case{"a == b", "Comparator", 2, 2, 1, 1},
258 Case{"a < b", "Comparator", 2, 3, 1, 1},
259 Case{"a <= b", "Comparator", 2, 3, 1, 1},
260 Case{"a > b", "Comparator", 3, 2, 1, 1},
261 Case{"a >= b", "Comparator", 3, 2, 1, 1},
262 Case{"a << b", "Shifter", 6, 1, 4, 3},
263 Case{"a >> b", "Shifter", 6, 1, 3, 3},
264 Case{"$signed(a) >>> b", "Shifter", 6, 1, 7, 3},
265 };
266 for (const auto& item : cases) {
267 SCOPED_TRACE(item.expression);
268 const auto source = std::format(
269 "module top(input [2:0] a, input [2:0] b, output [{}:0] y); assign y = {}; endmodule",
270 item.width - 1, item.expression);
271 const auto circuit = std::make_shared<Circuit>(importVerilog(source, "top"));
272 EXPECT_EQ(componentTypes(*circuit).count(item.component), 1);
273 EXPECT_EQ(evaluateBinaryCircuit(circuit, item.a, item.b), valueFor(item.width, item.y));
274 }
275#else
276 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
277#endif
278}
279
280TEST(YosysLegalizationEndToEndTest, ImportsInequalityWithMixedWidthsAndSignedness)
281{
282#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
283 for (const auto& [aSigned, bSigned] :
284 {std::pair{false, false}, std::pair{true, true}, std::pair{true, false},
285 std::pair{false, true}}) {
286 for (int resultWidth : {1, 4}) {
287 SCOPED_TRACE(std::format("aSigned={} bSigned={} resultWidth={}", aSigned, bSigned,
288 resultWidth));
289 const auto source =
290 std::format("module top(input {} [2:0] a, input {} [4:0] b, output [{}:0] y); "
291 "assign y = a != b; endmodule",
292 aSigned ? "signed" : "", bSigned ? "signed" : "", resultWidth - 1);
293 const auto circuit = std::make_shared<Circuit>(importVerilog(source, "top"));
294 EXPECT_EQ(componentTypes(*circuit).count("Comparator"), 1);
295 EXPECT_EQ(componentTypes(*circuit).count("NotGate"), 1);
296 for (unsigned int a : {0u, 1u, 4u, 7u}) {
297 for (unsigned int b : {0u, 1u, 4u, 7u, 28u, 31u}) {
298 SCOPED_TRACE(std::format("a={} b={}", a, b));
299 const auto extendedA = aSigned && bSigned && (a & 4u) ? a | 24u : a;
300 EXPECT_EQ(evaluateBinaryCircuit(circuit, a, b),
301 valueFor(resultWidth, extendedA != b));
302 }
303 }
304 }
305 }
306#else
307 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
308#endif
309}
310
311TEST(YosysLegalizationEndToEndTest, ImportsVectorConditionsUsingWholeOperandTruth)
312{
313#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
314 for (int width : {2, 3, 8}) {
315 for (bool sign : {false, true}) {
316 SCOPED_TRACE(std::format("width={} signed={}", width, sign));
317 const auto source =
318 std::format("module top(input {} [{}:0] a, input [3:0] b, output [3:0] y); "
319 "assign y = a ? b : 4'h9; endmodule",
320 sign ? "signed" : "", width - 1);
321 const auto circuit = std::make_shared<Circuit>(importVerilog(source, "top"));
322 EXPECT_GT(componentTypes(*circuit).count("OrGate"), 0);
323 for (unsigned int a = 0; a < (1u << width); ++a) {
324 for (unsigned int b : {0u, 5u, 15u}) {
325 SCOPED_TRACE(std::format("a={} b={}", a, b));
326 EXPECT_EQ(evaluateBinaryCircuit(circuit, a, b), valueFor(4, a ? b : 9));
327 }
328 }
329 }
330 }
331#else
332 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
333#endif
334}
335
336TEST(YosysLegalizationEndToEndTest, ImportsNegationAsTwosComplementWithWidthConversion)
337{
338#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
339 for (bool sign : {false, true}) {
340 for (int resultWidth : {2, 3, 5}) {
341 SCOPED_TRACE(std::format("signed={} resultWidth={}", sign, resultWidth));
342 const auto source = std::format(
343 "module top(input {} [2:0] a, output [{}:0] y); assign y = -a; endmodule",
344 sign ? "signed" : "", resultWidth - 1);
345 const auto circuit = std::make_shared<Circuit>(importVerilog(source, "top"));
346 EXPECT_EQ(componentTypes(*circuit).count("Complementer"), 1);
347 EXPECT_EQ(componentTypes(*circuit).count("AdderNBits"), 0);
348 const auto input = findNamedComponent<DummyBusInputComponent>(*circuit, "a");
349 const auto output = findNamedComponent<DummyBusOutputComponent>(*circuit, "y");
350 ASSERT_TRUE(input);
351 ASSERT_TRUE(output);
352 for (unsigned int a = 0; a < 8; ++a) {
353 SCOPED_TRACE(std::format("a={}", a));
354 input->setBusValue(valueFor(3, a));
355 Simulator simulator(circuit);
356 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
357 const int operand =
358 sign && (a & 4u) ? static_cast<int>(a) - 8 : static_cast<int>(a);
359 const auto expected =
360 static_cast<unsigned int>(-operand) & ((1u << resultWidth) - 1);
361 EXPECT_EQ(output->inputBuses()[0].getCurrentValue(),
362 valueFor(resultWidth, expected));
363 }
364 }
365 }
366#else
367 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
368#endif
369}
370
371TEST(YosysCanonicalImporterTest, ImportsCanonicalExpressionCellsWithoutYosys)
372{
375 struct Case {
376 const char* type;
377 Json parameters;
378 const char* component;
379 };
380 const std::array cases{
381 Case{"SILICON_LOGIC", {{"MODE", SerializationContext::parameter(0)},
382 {"A_WIDTH", SerializationContext::parameter(3)},
383 {"B_WIDTH", SerializationContext::parameter(3)}}, "AndGate"},
384 Case{"SILICON_COMPARE", {{"WIDTH", SerializationContext::parameter(3)},
386 {"SIGNED", SerializationContext::parameter(1)}}, "Comparator"},
387 Case{"SILICON_SHIFT", {{"WIDTH", SerializationContext::parameter(3)},
388 {"B_WIDTH", SerializationContext::parameter(3)},
389 {"DIRECTION", SerializationContext::parameter(1)},
390 {"ARITHMETIC", SerializationContext::parameter(1)}}, "Shifter"},
391 };
392 for (const auto& item : cases) {
393 SCOPED_TRACE(item.type);
394 auto design = expression("$eq", 3, 3, 1);
395 auto& cell = design["modules"]["top"]["cells"]["op"];
396 cell["type"] = item.type;
397 cell["parameters"] = item.parameters;
398 if (std::string_view(item.type) == "SILICON_SHIFT") {
399 auto& y = cell["connections"]["Y"];
400 y.push_back(9);
401 y.push_back(10);
402 }
403 const auto circuit = SILICON::yosys::deserialize(design.dump());
404 EXPECT_EQ(componentTypes(circuit).count(item.component), 1);
405 if (auto comparator = findComponent<Comparator>(circuit)) {
406 EXPECT_EQ(comparator->getPropertyValue<std::string>("mode"), "<=");
407 EXPECT_TRUE(comparator->getPropertyValue<bool>("signed"));
408 }
409 if (auto shifter = findComponent<Shifter>(circuit)) {
410 EXPECT_EQ(shifter->getPropertyValue<std::string>("mode"),
411 std::string(Shifter::RIGHT_MODE));
412 EXPECT_TRUE(shifter->getPropertyValue<bool>("signed"));
413 }
414 }
415}
416
417TEST(YosysLegalizationEndToEndTest, ImportsMultiplyDivideAndModuloFromVerilog)
418{
419#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
420 for (const bool sign : {false, true}) {
421 for (const auto op : {"*", "/", "%"}) {
422 SCOPED_TRACE(std::format("{} signed={}", op, sign));
423 const auto source =
424 std::format("module top(input {} [3:0] a, input {} [3:0] b, output [3:0] y); "
425 "assign y = a {} b; endmodule",
426 sign ? "signed" : "", sign ? "signed" : "", op);
427 const auto circuit = std::make_shared<Circuit>(importVerilog(source, "top"));
428 const bool multiplication = std::string_view(op) == "*";
429 EXPECT_EQ(componentTypes(*circuit).count(multiplication ? "Multiplier" : "Divider"),
430 1);
431 const int lhs = sign ? -7 : 9;
432 const int expected = multiplication ? lhs * 2
433 : std::string_view(op) == "/" ? lhs / 2
434 : lhs % 2;
435 EXPECT_EQ(evaluateBinaryCircuit(circuit, 9, 2), valueFor(4, expected & 15));
436 if (!multiplication) {
437 EXPECT_EQ(evaluateBinaryCircuit(circuit, 9, 0), BusValue(4, State::UNKNOWN));
438 }
439 }
440 }
441#else
442 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
443#endif
444}
445
446TEST(YosysLegalizationEndToEndTest,
447 ImportsMultiplyDivideAndModuloWithMixedWidthsAndSignedness)
448{
449#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
450 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
451#endif
452 for (const auto type : {"$mul", "$div", "$mod"}) {
453 for (const bool aSigned : {false, true}) {
454 for (const bool bSigned : {false, true}) {
455 for (const int yWidth : {2, 6}) {
456 const auto op = std::string_view(type) == "$mul" ? "*"
457 : std::string_view(type) == "$div" ? "/" : "%";
458 const auto source = std::format(
459 "module top(input {} [2:0] a, input {} [4:0] b, output [{}:0] y); "
460 "assign y = a {} b; endmodule", aSigned ? "signed" : "",
461 bSigned ? "signed" : "", yWidth - 1, op);
462 const auto mapped = nlohmann::json::parse(SILICON::yosys::elaborateHierarchy(
463 SILICON::verilog::read(source)));
464 const auto circuit = std::make_shared<Circuit>(
465 SILICON::yosys::deserialize(mapped.dump(), "top"));
466 const bool multiplication = std::string_view(type) == "$mul";
467 const auto& cell = mapped.at("modules").at("top").at("cells").begin().value();
468 EXPECT_EQ(cell.at("type"),
469 multiplication ? "SILICON_MULTIPLIER" : "SILICON_DIVIDER");
470 EXPECT_EQ(std::stoi(cell.at("parameters").at("SIGNED").get<std::string>(),
471 nullptr, 2),
472 aSigned && bSigned);
473 EXPECT_FALSE(cell.at("parameters").contains("A_SIGNED"));
474 EXPECT_FALSE(cell.at("parameters").contains("B_SIGNED"));
475 const auto component =
476 multiplication
477 ? std::static_pointer_cast<Component>(
478 findComponent<Multiplier>(*circuit))
479 : std::static_pointer_cast<Component>(findComponent<Divider>(*circuit));
480 ASSERT_TRUE(component);
481 EXPECT_EQ(component->getPropertyValue<bool>("signed"), aSigned && bSigned);
482 for (const unsigned a : {0u, 1u, 3u, 7u}) {
483 for (const unsigned b : {0u, 1u, 3u, 16u, 31u}) {
484 SCOPED_TRACE(std::format("{} {} {} {}: {}, {}", type, aSigned, bSigned,
485 yWidth, a, b));
486 const auto actual = evaluateBinaryCircuit(circuit, a, b);
487 if (!multiplication && b == 0) {
488 EXPECT_EQ(actual, BusValue(yWidth, State::UNKNOWN));
489 continue;
490 }
491 const int lhs = aSigned && bSigned && a >= 4 ? static_cast<int>(a) - 8 : a;
492 const int rhs =
493 aSigned && bSigned && b >= 16 ? static_cast<int>(b) - 32 : b;
494 const int expected = multiplication ? lhs * rhs
495 : std::string_view(type) == "$div" ? lhs / rhs
496 : lhs % rhs;
497 EXPECT_EQ(actual, valueFor(yWidth, expected & ((1u << yWidth) - 1)));
498 }
499 }
500 // Export and re-import preserve the observable result, including truncation.
501 const auto roundTripped = std::make_shared<Circuit>(
503 EXPECT_EQ(evaluateBinaryCircuit(roundTripped, 7, 3),
504 evaluateBinaryCircuit(circuit, 7, 3));
505 }
506 }
507 }
508 }
509}
510
511TEST(YosysLegalizationEndToEndTest, PreservesUnmappedArithmeticWidths)
512{
513#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
514 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
515#endif
516 for (const auto type : {"$add", "$sub"}) {
517 auto design = subtractionDesign(3, 5, 4, false, false);
518 onlyModule(design)["cells"].begin().value()["type"] = type;
519 const auto mapped =
520 nlohmann::json::parse(SILICON::yosys::elaborateHierarchy(design.dump()));
521 const auto& cell = mapped.at("modules").at("top").at("cells").begin().value();
522 EXPECT_EQ(cell.at("type"), type);
523 const auto circuit =
524 std::make_shared<Circuit>(SILICON::yosys::deserialize(mapped.dump(), "top"));
525 EXPECT_EQ(evaluateBinaryCircuit(circuit, 2, 5),
526 valueFor(4, std::string_view(type) == "$add" ? 7 : 13));
527 }
528}
529
530TEST(YosysLegalizationEndToEndTest, PreservesScalarAsyncEnableStorage)
531{
532#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
533 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
534#endif
535 for (const bool positiveClock : {false, true}) {
536 const auto source =
537 std::format("module top(input clk, input rst, input en, input d, output reg q); "
538 "always @({} clk or posedge rst) "
539 "if (rst) q <= 1'b0; else if (en) q <= d; endmodule",
540 positiveClock ? "posedge" : "negedge");
541 const auto mapped = nlohmann::json::parse(
543 const auto& cell = mapped.at("modules").at("top").at("cells").begin().value();
544 EXPECT_EQ(cell.at("type"), "$adffe");
545 const auto circuit = SILICON::yosys::deserialize(mapped.dump(), "top");
546 const auto flipFlop = findComponent<EFlipFlop>(circuit);
547 ASSERT_TRUE(flipFlop);
548 EXPECT_EQ(flipFlop->getPropertyValue<std::string>("triggerEdge"),
549 positiveClock ? "PET" : "NET");
550 }
551}
552
553#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
554TEST(YosysLegalizationTest, ShiftxKeepSurvivesOptCleanOnOnlyFinalMux)
555{
556 using Json = nlohmann::json;
557 for (bool signedOffset : {false, true})
558 for (int dataWidth : {1, 5})
559 for (int outputWidth : {1, 8})
560 for (bool keep : {false, true}) {
561 Json source =
562 expression("$shiftx", dataWidth, 3, outputWidth, false, signedOffset);
563 auto& module = onlyModule(source);
564 auto& cell = module["cells"]["op"];
565 cell["attributes"] = {{"keep", keep ? "1" : "0"},
566 {"source_marker", "original"}};
567 for (const auto name : {"A", "B"})
568 module["ports"][name] = {{"direction", "input"},
569 {"bits", cell["connections"][name]}};
570 module["netnames"]["unused_result"] = {{"hide_name", 0},
571 {"bits", cell["connections"]["Y"]}};
572 const auto lowered =
573 Json::parse(legalizeExpressions(source.dump(), "silicon_shift"));
574 unsigned protectedCells = 0;
575 for (const auto& replacement : onlyModule(lowered).at("cells")) {
576 const auto attributes = replacement.value("attributes", Json::object());
577 EXPECT_FALSE(attributes.contains("source_marker"));
578 if (attributes.contains("keep")) {
579 ++protectedCells;
580 EXPECT_EQ(replacement.at("type"), "$mux");
581 EXPECT_EQ(replacement.at("connections").at("Y").at(0),
582 onlyModule(lowered)
583 .at("netnames")
584 .at("unused_result")
585 .at("bits")
586 .at(0));
587 }
588 }
589 EXPECT_EQ(protectedCells, keep ? 1u : 0u);
590 const auto cleaned =
591 Json::parse(legalizeExpressions(source.dump(), "silicon_shift\nopt_clean"));
592 EXPECT_EQ(onlyModule(cleaned).at("cells").empty(), !keep);
593 if (keep) {
594 unsigned remainingKeep = 0;
595 for (const auto& replacement : onlyModule(cleaned).at("cells"))
596 remainingKeep +=
597 replacement.value("attributes", Json::object()).contains("keep");
598 EXPECT_EQ(remainingKeep, 1u);
599 }
600 }
601}
602#endif
std::multiset< std::string > componentTypes(const Circuit &circuit)
static constexpr std::string_view RIGHT_MODE
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
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::partial_ordering compare(const BusValue &lhs, const BusValue &rhs, const Signedness signedness)
Definition wire.cpp:289
std::vector< State > BusValue
Definition wire.hpp:120
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.
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(YosysLegalizationEndToEndTest, ImportsComparisonsAndShiftsFromVerilog)