SILICON
Loading...
Searching...
No Matches
verilog.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "verilog.hpp"
19
20#include <algorithm>
21#include <cctype>
22#include <format>
23#include <optional>
24#include <ranges>
25#include <string>
26#include <unordered_map>
27#include <unordered_set>
28#include <vector>
29
30#include <core/circuit.hpp>
33
35namespace {
36 [[nodiscard]] bool isVerilogIdentifier(const std::string_view identifier)
37 {
38 if (identifier.empty())
39 return false;
40 const auto isLetter = [](const char character) {
41 return (character >= 'a' && character <= 'z')
42 || (character >= 'A' && character <= 'Z') || character == '_';
43 };
44 const auto isDigit = [](const char character) {
45 return character >= '0' && character <= '9';
46 };
47 if (!isLetter(identifier.front()))
48 return false;
49 for (const char character : identifier.substr(1))
50 if (!isLetter(character) && !isDigit(character) && character != '$')
51 return false;
52 return true;
53 }
54
55 [[nodiscard]] std::string_view trim(const std::string_view value)
56 {
57 const auto first = value.find_first_not_of(" \t\r");
58 if (first == std::string_view::npos)
59 return {};
60 const auto last = value.find_last_not_of(" \t\r");
61 return value.substr(first, last - first + 1);
62 }
63
64 struct PortDeclaration {
65 std::string name;
66 std::string ansi;
67 };
68
69 [[nodiscard]] std::optional<PortDeclaration>
70 parsePortDeclaration(const std::string_view line)
71 {
72 const auto value = trim(line);
73 for (const std::string_view direction : {"input", "output", "inout"}) {
74 const auto prefix = std::format("{} ", direction);
75 if (!value.starts_with(prefix) || !value.ends_with(';'))
76 continue;
77
78 const auto body =
79 trim(value.substr(prefix.size(), value.size() - prefix.size() - 1));
80 const auto separator = body.find_last_of(" \t");
81 const auto name =
82 separator == std::string_view::npos ? body : trim(body.substr(separator + 1));
83 if (!isVerilogIdentifier(name))
84 return std::nullopt;
85 return PortDeclaration{std::string(name), std::format("{} {}", direction, body)};
86 }
87 return std::nullopt;
88 }
89
90 [[nodiscard]] std::optional<std::string>
91 parseNetDeclarationName(const std::string_view line, const std::string_view kind)
92 {
93 const auto prefix = std::format("{} ", kind);
94 const auto value = trim(line);
95 if (!value.starts_with(prefix) || !value.ends_with(';'))
96 return std::nullopt;
97
98 const auto body = trim(value.substr(prefix.size(), value.size() - prefix.size() - 1));
99 const auto separator = body.find_last_of(" \t");
100 const auto name =
101 separator == std::string_view::npos ? body : trim(body.substr(separator + 1));
102 if (!isVerilogIdentifier(name))
103 return std::nullopt;
104 return std::string(name);
105 }
106
107 [[nodiscard]] std::vector<std::string> splitLines(const std::string_view source)
108 {
109 std::vector<std::string> lines;
110 for (std::size_t begin = 0; begin < source.size();) {
111 const auto end = source.find('\n', begin);
112 if (end == std::string_view::npos) {
113 lines.emplace_back(source.substr(begin));
114 break;
115 }
116 lines.emplace_back(source.substr(begin, end - begin));
117 begin = end + 1;
118 }
119 return lines;
120 }
121
122 struct ContinuousAssignment {
123 std::string lhs;
124 std::string rhs;
125 };
126
127 [[nodiscard]] std::optional<ContinuousAssignment>
128 parseContinuousAssignment(const std::string_view line)
129 {
130 const auto value = trim(line);
131 if (!value.starts_with("assign ") || !value.ends_with(';'))
132 return std::nullopt;
133 const auto equal = value.find(" = ", std::string_view("assign ").size());
134 if (equal == std::string_view::npos)
135 return std::nullopt;
136 const auto lhs = trim(value.substr(std::string_view("assign ").size(),
137 equal - std::string_view("assign ").size()));
138 if (!isVerilogIdentifier(lhs))
139 return std::nullopt;
140 return ContinuousAssignment{
141 std::string(lhs),
142 std::string(trim(value.substr(equal + 3, value.size() - equal - 4)))};
143 }
144
145 [[nodiscard]] bool isGeneratedIdentifier(const std::string_view identifier)
146 {
147 return identifier.size() > 2 && identifier.front() == '_' && identifier.back() == '_'
148 && std::ranges::all_of(
149 identifier.substr(1, identifier.size() - 2), [](const char value) {
150 return std::isdigit(static_cast<unsigned char>(value)) != 0;
151 });
152 }
153
154 template <typename Callback>
155 void forEachIdentifier(const std::string_view value, Callback&& callback)
156 {
157 const auto isIdentifierCharacter = [](const char character) {
158 const auto value = static_cast<unsigned char>(character);
159 return std::isalnum(value) != 0 || character == '_' || character == '$';
160 };
161 for (std::size_t begin = 0; begin < value.size();) {
162 if (!std::isalpha(static_cast<unsigned char>(value[begin]))
163 && value[begin] != '_') {
164 ++begin;
165 continue;
166 }
167 auto end = begin + 1;
168 while (end < value.size() && isIdentifierCharacter(value[end]))
169 ++end;
170 callback(value.substr(begin, end - begin));
171 begin = end;
172 }
173 }
174
175 [[nodiscard]] std::optional<char> associativeOperator(const std::string_view expression)
176 {
177 unsigned nesting = 0;
178 std::optional<char> result;
179 for (std::size_t index = 0; index < expression.size(); ++index) {
180 const char character = expression[index];
181 if (character == '(' || character == '[' || character == '{') {
182 ++nesting;
183 continue;
184 }
185 if (character == ')' || character == ']' || character == '}') {
186 if (nesting != 0)
187 --nesting;
188 continue;
189 }
190 if (nesting != 0 || (character != '&' && character != '|' && character != '^'))
191 continue;
192 if (index == 0)
193 return std::nullopt;
194 const auto previous = expression.find_last_not_of(" \t", index - 1);
195 const auto next = expression.find_first_not_of(" \t", index + 1);
196 if (previous == std::string_view::npos || next == std::string_view::npos
197 || expression[previous] == character || expression[next] == character)
198 return std::nullopt;
199 if (result && *result != character)
200 return std::nullopt;
201 result = character;
202 }
203 return result;
204 }
205
211 [[nodiscard]] std::string
212 inlineGeneratedCombinationalNets(const std::string_view source)
213 {
214 auto lines = splitLines(source);
215
216 std::unordered_map<std::string, std::size_t, core::TransparentStringHash,
218 declarations;
219 for (std::size_t line = 0; line < lines.size(); ++line) {
220 const auto name = parseNetDeclarationName(lines[line], "wire");
221 if (name && isGeneratedIdentifier(*name)
222 && trim(lines[line]) == std::format("wire {};", *name))
223 declarations.emplace(*name, line);
224 }
225
226 struct Driver {
227 std::size_t line;
228 std::string expression;
229 };
230 std::unordered_map<std::string, Driver, core::TransparentStringHash,
232 drivers;
233 std::unordered_map<std::string, std::size_t> uses;
234 std::unordered_set<std::string> unsafe;
235 for (std::size_t line = 0; line < lines.size(); ++line) {
236 if (const auto assignment = parseContinuousAssignment(lines[line])) {
237 if (declarations.contains(assignment->lhs)) {
238 if (!drivers.emplace(assignment->lhs, Driver{line, std::move(assignment->rhs)})
239 .second)
240 unsafe.insert(assignment->lhs);
241 }
242 forEachIdentifier(assignment->rhs, [&](const std::string_view identifier) {
243 if (declarations.contains(identifier))
244 ++uses[std::string(identifier)];
245 });
246 continue;
247 }
248
249 bool declarationLine = false;
250 for (const auto& [name, declaration] : declarations) {
251 if (declaration == line) {
252 declarationLine = true;
253 break;
254 }
255 }
256 if (declarationLine)
257 continue;
258 forEachIdentifier(lines[line], [&](const std::string_view identifier) {
259 if (declarations.contains(identifier))
260 unsafe.insert(std::string(identifier));
261 });
262 }
263
264 using IdentifierSet = std::unordered_set<std::string, core::TransparentStringHash,
266 IdentifierSet inlineable;
267 for (const auto& [name, declaration] : declarations) {
268 (void)declaration;
269 if (drivers.contains(name) && uses[name] == 1 && !unsafe.contains(name))
270 inlineable.insert(name);
271 }
272
273 const auto expand = [&](this const auto& self, const std::string_view expression,
274 IdentifierSet& active) -> std::string {
275 std::string result;
276 std::size_t copied = 0;
277 const auto parentOperator = associativeOperator(expression);
278 forEachIdentifier(expression, [&](const std::string_view identifier) {
279 const auto begin = expression.find(identifier, copied);
280 result.append(expression.substr(copied, begin - copied));
281 if (inlineable.contains(identifier) && !active.contains(identifier)) {
282 active.emplace(identifier);
283 const auto& child = drivers.find(identifier)->second.expression;
284 const auto expandedChild = self(child, active);
285 if (parentOperator && associativeOperator(child) == parentOperator)
286 result += expandedChild;
287 else
288 result += '(' + expandedChild + ')';
289 active.erase(active.find(identifier));
290 } else {
291 result += identifier;
292 }
293 copied = begin + identifier.size();
294 });
295 result.append(expression.substr(copied));
296 return result;
297 };
298
299 std::vector<bool> removed(lines.size(), false);
300 for (const auto& name : inlineable) {
301 removed[declarations.at(name)] = true;
302 removed[drivers.at(name).line] = true;
303 }
304 for (std::size_t line = 0; line < lines.size(); ++line) {
305 if (removed[line])
306 continue;
307 const auto assignment = parseContinuousAssignment(lines[line]);
308 if (!assignment)
309 continue;
310 IdentifierSet active;
311 const auto indent = lines[line].substr(0, lines[line].find_first_not_of(" \t"));
312 lines[line] = std::format("{}assign {} = {};", indent, assignment->lhs,
313 expand(assignment->rhs, active));
314 }
315
316 std::string result;
317 for (std::size_t line = 0; line < lines.size(); ++line) {
318 if (!removed[line])
319 result += lines[line] + '\n';
320 }
321 return result;
322 }
323
324 [[nodiscard]] std::string cleanProcessVerilog(const std::string_view source)
325 {
326 auto lines = splitLines(source);
327 std::unordered_set<std::string> backendGuards;
328 std::vector<bool> removed(lines.size(), false);
329
330 for (std::size_t line = 0; line < lines.size(); ++line) {
331 const auto value = trim(lines[line]);
332 if (!value.starts_with("reg \\$auto$verilog_backend.cc:")
333 || value.find(":dump_module$") == std::string_view::npos)
334 continue;
335
336 const auto begin = value.find('\\');
337 const auto end = value.find_first_of(" \t", begin);
338 if (begin != std::string_view::npos && end != std::string_view::npos) {
339 backendGuards.emplace(value.substr(begin, end - begin));
340 removed[line] = true;
341 }
342 }
343
344 for (std::size_t line = 0; line < lines.size(); ++line) {
345 for (const auto& guard : backendGuards) {
346 if (lines[line].find("if (" + guard + " ) begin end") != std::string::npos) {
347 removed[line] = true;
348 break;
349 }
350 }
351
352 const auto casePosition = lines[line].find("casez (");
353 if (casePosition != std::string::npos)
354 lines[line].replace(casePosition, std::string_view("casez").size(), "case");
355 }
356
357 std::string result;
358 for (std::size_t line = 0; line < lines.size(); ++line) {
359 if (removed[line])
360 continue;
361 result += lines[line];
362 result += '\n';
363 }
364 return result;
365 }
366
373 [[nodiscard]] std::string useAnsiPortDeclarations(const std::string_view source)
374 {
375 auto lines = splitLines(source);
376 std::vector<bool> removed(lines.size(), false);
377 for (std::size_t moduleLine = 0; moduleLine < lines.size(); ++moduleLine) {
378 const auto header = trim(lines[moduleLine]);
379 if (!header.starts_with("module ") || !header.ends_with(");"))
380 continue;
381
382 const auto open = header.find('(');
383 if (open == std::string_view::npos)
384 continue;
385 const auto portList = header.substr(open + 1, header.size() - open - 3);
386
387 std::vector<std::string> ports;
388 for (std::size_t begin = 0; begin <= portList.size();) {
389 const auto end = portList.find(',', begin);
390 const auto port = trim(portList.substr(begin, end == std::string_view::npos
391 ? portList.size() - begin
392 : end - begin));
393 if (!isVerilogIdentifier(port)) {
394 ports.clear();
395 break;
396 }
397 ports.emplace_back(port);
398 if (end == std::string_view::npos)
399 break;
400 begin = end + 1;
401 }
402 if (ports.empty())
403 continue;
404
405 std::size_t endModule = moduleLine + 1;
406 while (endModule < lines.size() && trim(lines[endModule]) != "endmodule")
407 ++endModule;
408 if (endModule == lines.size())
409 continue;
410
411 std::unordered_map<std::string, std::string> declarations;
412 std::unordered_set<std::size_t> removableLines;
413 for (std::size_t line = moduleLine + 1; line < endModule; ++line) {
414 if (const auto declaration = parsePortDeclaration(lines[line])) {
415 declarations[declaration->name] = declaration->ansi;
416 removableLines.insert(line);
417 }
418 }
419 if (declarations.size() != ports.size())
420 continue;
421 if (std::ranges::any_of(ports, [&declarations](const auto& port) {
422 return !declarations.contains(port);
423 }))
424 continue;
425
426 const auto directionRank = [&declarations](const std::string& port) {
427 const auto& declaration = declarations.at(port);
428 if (declaration.starts_with("input "))
429 return 0;
430 if (declaration.starts_with("inout "))
431 return 1;
432 return 2;
433 };
434 std::ranges::sort(ports, [&](const auto& lhs, const auto& rhs) {
435 const auto lhsRank = directionRank(lhs);
436 const auto rhsRank = directionRank(rhs);
437 return lhsRank != rhsRank ? lhsRank < rhsRank : lhs < rhs;
438 });
439
440 for (std::size_t line = moduleLine + 1; line < endModule; ++line) {
441 if (const auto wire = parseNetDeclarationName(lines[line], "wire");
442 wire && declarations.contains(*wire))
443 removableLines.insert(line);
444 if (const auto reg = parseNetDeclarationName(lines[line], "reg");
445 reg && declarations.contains(*reg)
446 && declarations.at(*reg).starts_with("output ")) {
447 declarations.at(*reg).insert(std::string_view("output ").size(), "reg ");
448 removableLines.insert(line);
449 }
450 }
451
452 std::string ansiHeader =
453 lines[moduleLine].substr(0, lines[moduleLine].find('(') + 1);
454 for (std::size_t port = 0; port < ports.size(); ++port) {
455 if (port != 0)
456 ansiHeader += ", ";
457 ansiHeader += declarations.at(ports[port]);
458 }
459 lines[moduleLine] = ansiHeader + ");";
460 for (const auto line : removableLines)
461 removed[line] = true;
462 moduleLine = endModule;
463 }
464
465 std::string result;
466 for (std::size_t line = 0; line < lines.size(); ++line) {
467 if (removed[line])
468 continue;
469 result += lines[line];
470 result += '\n';
471 }
472 return result;
473 }
474
475} // namespace
476
477std::string read(const std::string_view source, const yosys::ToolOptions& options)
478{
479 return yosys::readVerilog(source, options);
480}
481
482std::string read(const std::span<const SourceFile> sources,
483 const std::string_view entryPath, const yosys::ToolOptions& options)
484{
485 return yosys::readVerilog(sources, entryPath, options);
486}
487
488std::string postprocess(const std::string_view source)
489{
490 return useAnsiPortDeclarations(
491 inlineGeneratedCombinationalNets(cleanProcessVerilog(source)));
492}
493
494std::string write(const std::string_view yosysJson, const yosys::ToolOptions& options)
495{
496 return postprocess(yosys::writeVerilog(yosysJson, options));
497}
498
499std::string write(const core::Circuit& circuit, const std::string_view moduleName,
500 const yosys::ToolOptions& options)
501{
502 return write(yosys::serialize(circuit, moduleName), options);
503}
504
505} // namespace SILICON::verilog
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
std::string write(const std::string_view yosysJson, const yosys::ToolOptions &options)
Definition verilog.cpp:494
std::string postprocess(const std::string_view source)
Definition verilog.cpp:488
std::string read(const std::string_view source, const yosys::ToolOptions &options)
Definition verilog.cpp:477
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
std::string readVerilog(const std::string_view source, const ToolOptions &options)
Transparent equality functor for string-like keys.
Transparent hash functor for string-like keys.