Fixed "write_verilog -attr2comment" handling of "*/" in strings
[yosys.git] / backends / verilog / verilog_backend.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 * ---
19 *
20 * A simple and straightforward verilog backend.
21 *
22 * Note that RTLIL processes can't always be mapped easily to a Verilog
23 * process. Therefore this frontend should only be used to export a
24 * Verilog netlist (i.e. after the "proc" pass has converted all processes
25 * to logic networks and registers).
26 *
27 */
28
29 #include "kernel/register.h"
30 #include "kernel/celltypes.h"
31 #include "kernel/log.h"
32 #include <string>
33 #include <sstream>
34 #include <set>
35 #include <map>
36
37 USING_YOSYS_NAMESPACE
38 PRIVATE_NAMESPACE_BEGIN
39
40 bool norename, noattr, attr2comment, noexpr;
41 int auto_name_counter, auto_name_offset, auto_name_digits;
42 std::map<RTLIL::IdString, int> auto_name_map;
43 std::set<RTLIL::IdString> reg_wires, reg_ct;
44
45 RTLIL::Module *active_module;
46
47 void reset_auto_counter_id(RTLIL::IdString id, bool may_rename)
48 {
49 const char *str = id.c_str();
50
51 if (*str == '$' && may_rename && !norename)
52 auto_name_map[id] = auto_name_counter++;
53
54 if (str[0] != '\\' || str[1] != '_' || str[2] == 0)
55 return;
56
57 for (int i = 2; str[i] != 0; i++) {
58 if (str[i] == '_' && str[i+1] == 0)
59 continue;
60 if (str[i] < '0' || str[i] > '9')
61 return;
62 }
63
64 int num = atoi(str+2);
65 if (num >= auto_name_offset)
66 auto_name_offset = num + 1;
67 }
68
69 void reset_auto_counter(RTLIL::Module *module)
70 {
71 auto_name_map.clear();
72 auto_name_counter = 0;
73 auto_name_offset = 0;
74
75 reset_auto_counter_id(module->name, false);
76
77 for (auto it = module->wires_.begin(); it != module->wires_.end(); ++it)
78 reset_auto_counter_id(it->second->name, true);
79
80 for (auto it = module->cells_.begin(); it != module->cells_.end(); ++it) {
81 reset_auto_counter_id(it->second->name, true);
82 reset_auto_counter_id(it->second->type, false);
83 }
84
85 for (auto it = module->processes.begin(); it != module->processes.end(); ++it)
86 reset_auto_counter_id(it->second->name, false);
87
88 auto_name_digits = 1;
89 for (size_t i = 10; i < auto_name_offset + auto_name_map.size(); i = i*10)
90 auto_name_digits++;
91
92 for (auto it = auto_name_map.begin(); it != auto_name_map.end(); ++it)
93 log(" renaming `%s' to `_%0*d_'.\n", it->first.c_str(), auto_name_digits, auto_name_offset + it->second);
94 }
95
96 std::string id(RTLIL::IdString internal_id, bool may_rename = true)
97 {
98 const char *str = internal_id.c_str();
99 bool do_escape = false;
100
101 if (may_rename && auto_name_map.count(internal_id) != 0) {
102 char buffer[100];
103 snprintf(buffer, 100, "_%0*d_", auto_name_digits, auto_name_offset + auto_name_map[internal_id]);
104 return std::string(buffer);
105 }
106
107 if (*str == '\\')
108 str++;
109
110 if ('0' <= *str && *str <= '9')
111 do_escape = true;
112
113 for (int i = 0; str[i]; i++)
114 {
115 if ('0' <= str[i] && str[i] <= '9')
116 continue;
117 if ('a' <= str[i] && str[i] <= 'z')
118 continue;
119 if ('A' <= str[i] && str[i] <= 'Z')
120 continue;
121 if (str[i] == '_')
122 continue;
123 do_escape = true;
124 break;
125 }
126
127 if (do_escape)
128 return "\\" + std::string(str) + " ";
129 return std::string(str);
130 }
131
132 bool is_reg_wire(RTLIL::SigSpec sig, std::string &reg_name)
133 {
134 if (!sig.is_chunk() || sig.as_chunk().wire == NULL)
135 return false;
136
137 RTLIL::SigChunk chunk = sig.as_chunk();
138
139 if (reg_wires.count(chunk.wire->name) == 0)
140 return false;
141
142 reg_name = id(chunk.wire->name);
143 if (sig.size() != chunk.wire->width) {
144 if (sig.size() == 1)
145 reg_name += stringf("[%d]", chunk.wire->start_offset + chunk.offset);
146 else
147 reg_name += stringf("[%d:%d]", chunk.wire->start_offset + chunk.offset + chunk.width - 1,
148 chunk.wire->start_offset + chunk.offset);
149 }
150
151 return true;
152 }
153
154 void dump_const(std::ostream &f, const RTLIL::Const &data, int width = -1, int offset = 0, bool no_decimal = false, bool set_signed = false, bool escape_comment = false)
155 {
156 if (width < 0)
157 width = data.bits.size() - offset;
158 if ((data.flags & RTLIL::CONST_FLAG_STRING) == 0 || width != (int)data.bits.size()) {
159 if (width == 32 && !no_decimal) {
160 int32_t val = 0;
161 for (int i = offset+width-1; i >= offset; i--) {
162 log_assert(i < (int)data.bits.size());
163 if (data.bits[i] != RTLIL::S0 && data.bits[i] != RTLIL::S1)
164 goto dump_bits;
165 if (data.bits[i] == RTLIL::S1 && (i - offset) == 31)
166 goto dump_bits;
167 if (data.bits[i] == RTLIL::S1)
168 val |= 1 << (i - offset);
169 }
170 f << stringf("32'%sd %d", set_signed ? "s" : "", val);
171 } else {
172 dump_bits:
173 f << stringf("%d'%sb", width, set_signed ? "s" : "");
174 if (width == 0)
175 f << stringf("0");
176 for (int i = offset+width-1; i >= offset; i--) {
177 log_assert(i < (int)data.bits.size());
178 switch (data.bits[i]) {
179 case RTLIL::S0: f << stringf("0"); break;
180 case RTLIL::S1: f << stringf("1"); break;
181 case RTLIL::Sx: f << stringf("x"); break;
182 case RTLIL::Sz: f << stringf("z"); break;
183 case RTLIL::Sa: f << stringf("z"); break;
184 case RTLIL::Sm: log_error("Found marker state in final netlist.");
185 }
186 }
187 }
188 } else {
189 f << stringf("\"");
190 std::string str = data.decode_string();
191 for (size_t i = 0; i < str.size(); i++) {
192 if (str[i] == '\n')
193 f << stringf("\\n");
194 else if (str[i] == '\t')
195 f << stringf("\\t");
196 else if (str[i] < 32)
197 f << stringf("\\%03o", str[i]);
198 else if (str[i] == '"')
199 f << stringf("\\\"");
200 else if (str[i] == '\\')
201 f << stringf("\\\\");
202 else if (str[i] == '/' && escape_comment && i > 0 && str[i-1] == '*')
203 f << stringf("\\/");
204 else
205 f << str[i];
206 }
207 f << stringf("\"");
208 }
209 }
210
211 void dump_sigchunk(std::ostream &f, const RTLIL::SigChunk &chunk, bool no_decimal = false)
212 {
213 if (chunk.wire == NULL) {
214 dump_const(f, chunk.data, chunk.width, chunk.offset, no_decimal);
215 } else {
216 if (chunk.width == chunk.wire->width && chunk.offset == 0) {
217 f << stringf("%s", id(chunk.wire->name).c_str());
218 } else if (chunk.width == 1) {
219 if (chunk.wire->upto)
220 f << stringf("%s[%d]", id(chunk.wire->name).c_str(), (chunk.wire->width - chunk.offset - 1) + chunk.wire->start_offset);
221 else
222 f << stringf("%s[%d]", id(chunk.wire->name).c_str(), chunk.offset + chunk.wire->start_offset);
223 } else {
224 if (chunk.wire->upto)
225 f << stringf("%s[%d:%d]", id(chunk.wire->name).c_str(),
226 (chunk.wire->width - (chunk.offset + chunk.width - 1) - 1) + chunk.wire->start_offset,
227 (chunk.wire->width - chunk.offset - 1) + chunk.wire->start_offset);
228 else
229 f << stringf("%s[%d:%d]", id(chunk.wire->name).c_str(),
230 (chunk.offset + chunk.width - 1) + chunk.wire->start_offset,
231 chunk.offset + chunk.wire->start_offset);
232 }
233 }
234 }
235
236 void dump_sigspec(std::ostream &f, const RTLIL::SigSpec &sig)
237 {
238 if (sig.is_chunk()) {
239 dump_sigchunk(f, sig.as_chunk());
240 } else {
241 f << stringf("{ ");
242 for (auto it = sig.chunks().rbegin(); it != sig.chunks().rend(); ++it) {
243 if (it != sig.chunks().rbegin())
244 f << stringf(", ");
245 dump_sigchunk(f, *it, true);
246 }
247 f << stringf(" }");
248 }
249 }
250
251 void dump_attributes(std::ostream &f, std::string indent, dict<RTLIL::IdString, RTLIL::Const> &attributes, char term = '\n', bool modattr = false)
252 {
253 if (noattr)
254 return;
255 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
256 f << stringf("%s" "%s %s", indent.c_str(), attr2comment ? "/*" : "(*", id(it->first).c_str());
257 f << stringf(" = ");
258 if (modattr && (it->second == Const(0, 1) || it->second == Const(0)))
259 f << stringf(" 0 ");
260 else if (modattr && (it->second == Const(1, 1) || it->second == Const(1)))
261 f << stringf(" 1 ");
262 else
263 dump_const(f, it->second, -1, 0, false, false, attr2comment);
264 f << stringf(" %s%c", attr2comment ? "*/" : "*)", term);
265 }
266 }
267
268 void dump_wire(std::ostream &f, std::string indent, RTLIL::Wire *wire)
269 {
270 dump_attributes(f, indent, wire->attributes);
271 #if 0
272 if (wire->port_input && !wire->port_output)
273 f << stringf("%s" "input %s", indent.c_str(), reg_wires.count(wire->name) ? "reg " : "");
274 else if (!wire->port_input && wire->port_output)
275 f << stringf("%s" "output %s", indent.c_str(), reg_wires.count(wire->name) ? "reg " : "");
276 else if (wire->port_input && wire->port_output)
277 f << stringf("%s" "inout %s", indent.c_str(), reg_wires.count(wire->name) ? "reg " : "");
278 else
279 f << stringf("%s" "%s ", indent.c_str(), reg_wires.count(wire->name) ? "reg" : "wire");
280 if (wire->width != 1)
281 f << stringf("[%d:%d] ", wire->width - 1 + wire->start_offset, wire->start_offset);
282 f << stringf("%s;\n", id(wire->name).c_str());
283 #else
284 // do not use Verilog-2k "outut reg" syntax in verilog export
285 std::string range = "";
286 if (wire->width != 1) {
287 if (wire->upto)
288 range = stringf(" [%d:%d]", wire->start_offset, wire->width - 1 + wire->start_offset);
289 else
290 range = stringf(" [%d:%d]", wire->width - 1 + wire->start_offset, wire->start_offset);
291 }
292 if (wire->port_input && !wire->port_output)
293 f << stringf("%s" "input%s %s;\n", indent.c_str(), range.c_str(), id(wire->name).c_str());
294 if (!wire->port_input && wire->port_output)
295 f << stringf("%s" "output%s %s;\n", indent.c_str(), range.c_str(), id(wire->name).c_str());
296 if (wire->port_input && wire->port_output)
297 f << stringf("%s" "inout%s %s;\n", indent.c_str(), range.c_str(), id(wire->name).c_str());
298 if (reg_wires.count(wire->name))
299 f << stringf("%s" "reg%s %s;\n", indent.c_str(), range.c_str(), id(wire->name).c_str());
300 else if (!wire->port_input && !wire->port_output)
301 f << stringf("%s" "wire%s %s;\n", indent.c_str(), range.c_str(), id(wire->name).c_str());
302 #endif
303 }
304
305 void dump_memory(std::ostream &f, std::string indent, RTLIL::Memory *memory)
306 {
307 dump_attributes(f, indent, memory->attributes);
308 f << stringf("%s" "reg [%d:0] %s [%d:0];\n", indent.c_str(), memory->width-1, id(memory->name).c_str(), memory->size-1);
309 }
310
311 void dump_cell_expr_port(std::ostream &f, RTLIL::Cell *cell, std::string port, bool gen_signed = true)
312 {
313 if (gen_signed && cell->parameters.count("\\" + port + "_SIGNED") > 0 && cell->parameters["\\" + port + "_SIGNED"].as_bool()) {
314 f << stringf("$signed(");
315 dump_sigspec(f, cell->getPort("\\" + port));
316 f << stringf(")");
317 } else
318 dump_sigspec(f, cell->getPort("\\" + port));
319 }
320
321 std::string cellname(RTLIL::Cell *cell)
322 {
323 if (!norename && cell->name[0] == '$' && reg_ct.count(cell->type) && cell->hasPort("\\Q"))
324 {
325 RTLIL::SigSpec sig = cell->getPort("\\Q");
326 if (GetSize(sig) != 1 || sig.is_fully_const())
327 goto no_special_reg_name;
328
329 RTLIL::Wire *wire = sig[0].wire;
330
331 if (wire->name[0] != '\\')
332 goto no_special_reg_name;
333
334 std::string cell_name = wire->name.str();
335
336 size_t pos = cell_name.find('[');
337 if (pos != std::string::npos)
338 cell_name = cell_name.substr(0, pos) + "_reg" + cell_name.substr(pos);
339 else
340 cell_name = cell_name + "_reg";
341
342 if (wire->width != 1)
343 cell_name += stringf("[%d]", wire->start_offset + sig[0].offset);
344
345 if (active_module && active_module->count_id(cell_name) > 0)
346 goto no_special_reg_name;
347
348 return id(cell_name);
349 }
350 else
351 {
352 no_special_reg_name:
353 return id(cell->name).c_str();
354 }
355 }
356
357 void dump_cell_expr_uniop(std::ostream &f, std::string indent, RTLIL::Cell *cell, std::string op)
358 {
359 f << stringf("%s" "assign ", indent.c_str());
360 dump_sigspec(f, cell->getPort("\\Y"));
361 f << stringf(" = %s ", op.c_str());
362 dump_attributes(f, "", cell->attributes, ' ');
363 dump_cell_expr_port(f, cell, "A", true);
364 f << stringf(";\n");
365 }
366
367 void dump_cell_expr_binop(std::ostream &f, std::string indent, RTLIL::Cell *cell, std::string op)
368 {
369 f << stringf("%s" "assign ", indent.c_str());
370 dump_sigspec(f, cell->getPort("\\Y"));
371 f << stringf(" = ");
372 dump_cell_expr_port(f, cell, "A", true);
373 f << stringf(" %s ", op.c_str());
374 dump_attributes(f, "", cell->attributes, ' ');
375 dump_cell_expr_port(f, cell, "B", true);
376 f << stringf(";\n");
377 }
378
379 bool dump_cell_expr(std::ostream &f, std::string indent, RTLIL::Cell *cell)
380 {
381 if (cell->type == "$_NOT_") {
382 f << stringf("%s" "assign ", indent.c_str());
383 dump_sigspec(f, cell->getPort("\\Y"));
384 f << stringf(" = ");
385 f << stringf("~");
386 dump_attributes(f, "", cell->attributes, ' ');
387 dump_cell_expr_port(f, cell, "A", false);
388 f << stringf(";\n");
389 return true;
390 }
391
392 if (cell->type.in("$_AND_", "$_NAND_", "$_OR_", "$_NOR_", "$_XOR_", "$_XNOR_")) {
393 f << stringf("%s" "assign ", indent.c_str());
394 dump_sigspec(f, cell->getPort("\\Y"));
395 f << stringf(" = ");
396 if (cell->type.in("$_NAND_", "$_NOR_", "$_XNOR_"))
397 f << stringf("~(");
398 dump_cell_expr_port(f, cell, "A", false);
399 f << stringf(" ");
400 if (cell->type.in("$_AND_", "$_NAND_"))
401 f << stringf("&");
402 if (cell->type.in("$_OR_", "$_NOR_"))
403 f << stringf("|");
404 if (cell->type.in("$_XOR_", "$_XNOR_"))
405 f << stringf("^");
406 dump_attributes(f, "", cell->attributes, ' ');
407 f << stringf(" ");
408 dump_cell_expr_port(f, cell, "B", false);
409 if (cell->type.in("$_NAND_", "$_NOR_", "$_XNOR_"))
410 f << stringf(")");
411 f << stringf(";\n");
412 return true;
413 }
414
415 if (cell->type == "$_MUX_") {
416 f << stringf("%s" "assign ", indent.c_str());
417 dump_sigspec(f, cell->getPort("\\Y"));
418 f << stringf(" = ");
419 dump_cell_expr_port(f, cell, "S", false);
420 f << stringf(" ? ");
421 dump_attributes(f, "", cell->attributes, ' ');
422 dump_cell_expr_port(f, cell, "B", false);
423 f << stringf(" : ");
424 dump_cell_expr_port(f, cell, "A", false);
425 f << stringf(";\n");
426 return true;
427 }
428
429 if (cell->type.in("$_AOI3_", "$_OAI3_")) {
430 f << stringf("%s" "assign ", indent.c_str());
431 dump_sigspec(f, cell->getPort("\\Y"));
432 f << stringf(" = ~((");
433 dump_cell_expr_port(f, cell, "A", false);
434 f << stringf(cell->type == "$_AOI3_" ? " & " : " | ");
435 dump_cell_expr_port(f, cell, "B", false);
436 f << stringf(cell->type == "$_AOI3_" ? ") |" : ") &");
437 dump_attributes(f, "", cell->attributes, ' ');
438 f << stringf(" ");
439 dump_cell_expr_port(f, cell, "C", false);
440 f << stringf(");\n");
441 return true;
442 }
443
444 if (cell->type.in("$_AOI4_", "$_OAI4_")) {
445 f << stringf("%s" "assign ", indent.c_str());
446 dump_sigspec(f, cell->getPort("\\Y"));
447 f << stringf(" = ~((");
448 dump_cell_expr_port(f, cell, "A", false);
449 f << stringf(cell->type == "$_AOI4_" ? " & " : " | ");
450 dump_cell_expr_port(f, cell, "B", false);
451 f << stringf(cell->type == "$_AOI4_" ? ") |" : ") &");
452 dump_attributes(f, "", cell->attributes, ' ');
453 f << stringf(" (");
454 dump_cell_expr_port(f, cell, "C", false);
455 f << stringf(cell->type == "$_AOI4_" ? " & " : " | ");
456 dump_cell_expr_port(f, cell, "D", false);
457 f << stringf("));\n");
458 return true;
459 }
460
461 if (cell->type.substr(0, 6) == "$_DFF_")
462 {
463 std::string reg_name = cellname(cell);
464 bool out_is_reg_wire = is_reg_wire(cell->getPort("\\Q"), reg_name);
465
466 if (!out_is_reg_wire)
467 f << stringf("%s" "reg %s;\n", indent.c_str(), reg_name.c_str());
468
469 dump_attributes(f, indent, cell->attributes);
470 f << stringf("%s" "always @(%sedge ", indent.c_str(), cell->type[6] == 'P' ? "pos" : "neg");
471 dump_sigspec(f, cell->getPort("\\C"));
472 if (cell->type[7] != '_') {
473 f << stringf(" or %sedge ", cell->type[7] == 'P' ? "pos" : "neg");
474 dump_sigspec(f, cell->getPort("\\R"));
475 }
476 f << stringf(")\n");
477
478 if (cell->type[7] != '_') {
479 f << stringf("%s" " if (%s", indent.c_str(), cell->type[7] == 'P' ? "" : "!");
480 dump_sigspec(f, cell->getPort("\\R"));
481 f << stringf(")\n");
482 f << stringf("%s" " %s <= %c;\n", indent.c_str(), reg_name.c_str(), cell->type[8]);
483 f << stringf("%s" " else\n", indent.c_str());
484 }
485
486 f << stringf("%s" " %s <= ", indent.c_str(), reg_name.c_str());
487 dump_cell_expr_port(f, cell, "D", false);
488 f << stringf(";\n");
489
490 if (!out_is_reg_wire) {
491 f << stringf("%s" "assign ", indent.c_str());
492 dump_sigspec(f, cell->getPort("\\Q"));
493 f << stringf(" = %s;\n", reg_name.c_str());
494 }
495
496 return true;
497 }
498
499 if (cell->type.substr(0, 8) == "$_DFFSR_")
500 {
501 char pol_c = cell->type[8], pol_s = cell->type[9], pol_r = cell->type[10];
502
503 std::string reg_name = cellname(cell);
504 bool out_is_reg_wire = is_reg_wire(cell->getPort("\\Q"), reg_name);
505
506 if (!out_is_reg_wire)
507 f << stringf("%s" "reg %s;\n", indent.c_str(), reg_name.c_str());
508
509 dump_attributes(f, indent, cell->attributes);
510 f << stringf("%s" "always @(%sedge ", indent.c_str(), pol_c == 'P' ? "pos" : "neg");
511 dump_sigspec(f, cell->getPort("\\C"));
512 f << stringf(" or %sedge ", pol_s == 'P' ? "pos" : "neg");
513 dump_sigspec(f, cell->getPort("\\S"));
514 f << stringf(" or %sedge ", pol_r == 'P' ? "pos" : "neg");
515 dump_sigspec(f, cell->getPort("\\R"));
516 f << stringf(")\n");
517
518 f << stringf("%s" " if (%s", indent.c_str(), pol_r == 'P' ? "" : "!");
519 dump_sigspec(f, cell->getPort("\\R"));
520 f << stringf(")\n");
521 f << stringf("%s" " %s <= 0;\n", indent.c_str(), reg_name.c_str());
522
523 f << stringf("%s" " else if (%s", indent.c_str(), pol_s == 'P' ? "" : "!");
524 dump_sigspec(f, cell->getPort("\\S"));
525 f << stringf(")\n");
526 f << stringf("%s" " %s <= 1;\n", indent.c_str(), reg_name.c_str());
527
528 f << stringf("%s" " else\n", indent.c_str());
529 f << stringf("%s" " %s <= ", indent.c_str(), reg_name.c_str());
530 dump_cell_expr_port(f, cell, "D", false);
531 f << stringf(";\n");
532
533 if (!out_is_reg_wire) {
534 f << stringf("%s" "assign ", indent.c_str());
535 dump_sigspec(f, cell->getPort("\\Q"));
536 f << stringf(" = %s;\n", reg_name.c_str());
537 }
538
539 return true;
540 }
541
542 #define HANDLE_UNIOP(_type, _operator) \
543 if (cell->type ==_type) { dump_cell_expr_uniop(f, indent, cell, _operator); return true; }
544 #define HANDLE_BINOP(_type, _operator) \
545 if (cell->type ==_type) { dump_cell_expr_binop(f, indent, cell, _operator); return true; }
546
547 HANDLE_UNIOP("$not", "~")
548 HANDLE_UNIOP("$pos", "+")
549 HANDLE_UNIOP("$neg", "-")
550
551 HANDLE_BINOP("$and", "&")
552 HANDLE_BINOP("$or", "|")
553 HANDLE_BINOP("$xor", "^")
554 HANDLE_BINOP("$xnor", "~^")
555
556 HANDLE_UNIOP("$reduce_and", "&")
557 HANDLE_UNIOP("$reduce_or", "|")
558 HANDLE_UNIOP("$reduce_xor", "^")
559 HANDLE_UNIOP("$reduce_xnor", "~^")
560 HANDLE_UNIOP("$reduce_bool", "|")
561
562 HANDLE_BINOP("$shl", "<<")
563 HANDLE_BINOP("$shr", ">>")
564 HANDLE_BINOP("$sshl", "<<<")
565 HANDLE_BINOP("$sshr", ">>>")
566
567 HANDLE_BINOP("$lt", "<")
568 HANDLE_BINOP("$le", "<=")
569 HANDLE_BINOP("$eq", "==")
570 HANDLE_BINOP("$ne", "!=")
571 HANDLE_BINOP("$eqx", "===")
572 HANDLE_BINOP("$nex", "!==")
573 HANDLE_BINOP("$ge", ">=")
574 HANDLE_BINOP("$gt", ">")
575
576 HANDLE_BINOP("$add", "+")
577 HANDLE_BINOP("$sub", "-")
578 HANDLE_BINOP("$mul", "*")
579 HANDLE_BINOP("$div", "/")
580 HANDLE_BINOP("$mod", "%")
581 HANDLE_BINOP("$pow", "**")
582
583 HANDLE_UNIOP("$logic_not", "!")
584 HANDLE_BINOP("$logic_and", "&&")
585 HANDLE_BINOP("$logic_or", "||")
586
587 #undef HANDLE_UNIOP
588 #undef HANDLE_BINOP
589
590 if (cell->type == "$mux")
591 {
592 f << stringf("%s" "assign ", indent.c_str());
593 dump_sigspec(f, cell->getPort("\\Y"));
594 f << stringf(" = ");
595 dump_sigspec(f, cell->getPort("\\S"));
596 f << stringf(" ? ");
597 dump_attributes(f, "", cell->attributes, ' ');
598 dump_sigspec(f, cell->getPort("\\B"));
599 f << stringf(" : ");
600 dump_sigspec(f, cell->getPort("\\A"));
601 f << stringf(";\n");
602 return true;
603 }
604
605 if (cell->type == "$pmux" || cell->type == "$pmux_safe")
606 {
607 int width = cell->parameters["\\WIDTH"].as_int();
608 int s_width = cell->getPort("\\S").size();
609 std::string func_name = cellname(cell);
610
611 f << stringf("%s" "function [%d:0] %s;\n", indent.c_str(), width-1, func_name.c_str());
612 f << stringf("%s" " input [%d:0] a;\n", indent.c_str(), width-1);
613 f << stringf("%s" " input [%d:0] b;\n", indent.c_str(), s_width*width-1);
614 f << stringf("%s" " input [%d:0] s;\n", indent.c_str(), s_width-1);
615
616 dump_attributes(f, indent + " ", cell->attributes);
617 if (cell->type != "$pmux_safe" && !noattr)
618 f << stringf("%s" " (* parallel_case *)\n", indent.c_str());
619 f << stringf("%s" " casez (s)", indent.c_str());
620 if (cell->type != "$pmux_safe")
621 f << stringf(noattr ? " // synopsys parallel_case\n" : "\n");
622
623 for (int i = 0; i < s_width; i++)
624 {
625 f << stringf("%s" " %d'b", indent.c_str(), s_width);
626
627 for (int j = s_width-1; j >= 0; j--)
628 f << stringf("%c", j == i ? '1' : cell->type == "$pmux_safe" ? '0' : '?');
629
630 f << stringf(":\n");
631 f << stringf("%s" " %s = b[%d:%d];\n", indent.c_str(), func_name.c_str(), (i+1)*width-1, i*width);
632 }
633
634 f << stringf("%s" " default:\n", indent.c_str());
635 f << stringf("%s" " %s = a;\n", indent.c_str(), func_name.c_str());
636
637 f << stringf("%s" " endcase\n", indent.c_str());
638 f << stringf("%s" "endfunction\n", indent.c_str());
639
640 f << stringf("%s" "assign ", indent.c_str());
641 dump_sigspec(f, cell->getPort("\\Y"));
642 f << stringf(" = %s(", func_name.c_str());
643 dump_sigspec(f, cell->getPort("\\A"));
644 f << stringf(", ");
645 dump_sigspec(f, cell->getPort("\\B"));
646 f << stringf(", ");
647 dump_sigspec(f, cell->getPort("\\S"));
648 f << stringf(");\n");
649 return true;
650 }
651
652 if (cell->type == "$slice")
653 {
654 f << stringf("%s" "assign ", indent.c_str());
655 dump_sigspec(f, cell->getPort("\\Y"));
656 f << stringf(" = ");
657 dump_sigspec(f, cell->getPort("\\A"));
658 f << stringf(" >> %d;\n", cell->parameters.at("\\OFFSET").as_int());
659 return true;
660 }
661
662 if (cell->type == "$concat")
663 {
664 f << stringf("%s" "assign ", indent.c_str());
665 dump_sigspec(f, cell->getPort("\\Y"));
666 f << stringf(" = { ");
667 dump_sigspec(f, cell->getPort("\\B"));
668 f << stringf(" , ");
669 dump_sigspec(f, cell->getPort("\\A"));
670 f << stringf(" };\n");
671 return true;
672 }
673
674 if (cell->type == "$dff" || cell->type == "$adff" || cell->type == "$dffe")
675 {
676 RTLIL::SigSpec sig_clk, sig_arst, sig_en, val_arst;
677 bool pol_clk, pol_arst = false, pol_en = false;
678
679 sig_clk = cell->getPort("\\CLK");
680 pol_clk = cell->parameters["\\CLK_POLARITY"].as_bool();
681
682 if (cell->type == "$adff") {
683 sig_arst = cell->getPort("\\ARST");
684 pol_arst = cell->parameters["\\ARST_POLARITY"].as_bool();
685 val_arst = RTLIL::SigSpec(cell->parameters["\\ARST_VALUE"]);
686 }
687
688 if (cell->type == "$dffe") {
689 sig_en = cell->getPort("\\EN");
690 pol_en = cell->parameters["\\EN_POLARITY"].as_bool();
691 }
692
693 std::string reg_name = cellname(cell);
694 bool out_is_reg_wire = is_reg_wire(cell->getPort("\\Q"), reg_name);
695
696 if (!out_is_reg_wire)
697 f << stringf("%s" "reg [%d:0] %s;\n", indent.c_str(), cell->parameters["\\WIDTH"].as_int()-1, reg_name.c_str());
698
699 f << stringf("%s" "always @(%sedge ", indent.c_str(), pol_clk ? "pos" : "neg");
700 dump_sigspec(f, sig_clk);
701 if (cell->type == "$adff") {
702 f << stringf(" or %sedge ", pol_arst ? "pos" : "neg");
703 dump_sigspec(f, sig_arst);
704 }
705 f << stringf(")\n");
706
707 if (cell->type == "$adff") {
708 f << stringf("%s" " if (%s", indent.c_str(), pol_arst ? "" : "!");
709 dump_sigspec(f, sig_arst);
710 f << stringf(")\n");
711 f << stringf("%s" " %s <= ", indent.c_str(), reg_name.c_str());
712 dump_sigspec(f, val_arst);
713 f << stringf(";\n");
714 f << stringf("%s" " else\n", indent.c_str());
715 }
716
717 if (cell->type == "$dffe") {
718 f << stringf("%s" " if (%s", indent.c_str(), pol_en ? "" : "!");
719 dump_sigspec(f, sig_en);
720 f << stringf(")\n");
721 }
722
723 f << stringf("%s" " %s <= ", indent.c_str(), reg_name.c_str());
724 dump_cell_expr_port(f, cell, "D", false);
725 f << stringf(";\n");
726
727 if (!out_is_reg_wire) {
728 f << stringf("%s" "assign ", indent.c_str());
729 dump_sigspec(f, cell->getPort("\\Q"));
730 f << stringf(" = %s;\n", reg_name.c_str());
731 }
732
733 return true;
734 }
735
736 // FIXME: $_SR_[PN][PN]_, $_DLATCH_[PN]_, $_DLATCHSR_[PN][PN][PN]_
737 // FIXME: $sr, $dffsr, $dlatch, $memrd, $memwr, $mem, $fsm
738
739 return false;
740 }
741
742 void dump_cell(std::ostream &f, std::string indent, RTLIL::Cell *cell)
743 {
744 if (cell->type[0] == '$' && !noexpr) {
745 if (dump_cell_expr(f, indent, cell))
746 return;
747 }
748
749 dump_attributes(f, indent, cell->attributes);
750 f << stringf("%s" "%s", indent.c_str(), id(cell->type, false).c_str());
751
752 if (cell->parameters.size() > 0) {
753 f << stringf(" #(");
754 for (auto it = cell->parameters.begin(); it != cell->parameters.end(); ++it) {
755 if (it != cell->parameters.begin())
756 f << stringf(",");
757 f << stringf("\n%s .%s(", indent.c_str(), id(it->first).c_str());
758 bool is_signed = (it->second.flags & RTLIL::CONST_FLAG_SIGNED) != 0;
759 dump_const(f, it->second, -1, 0, false, is_signed);
760 f << stringf(")");
761 }
762 f << stringf("\n%s" ")", indent.c_str());
763 }
764
765 std::string cell_name = cellname(cell);
766 if (cell_name != id(cell->name))
767 f << stringf(" %s /* %s */ (", cell_name.c_str(), id(cell->name).c_str());
768 else
769 f << stringf(" %s (", cell_name.c_str());
770
771 bool first_arg = true;
772 std::set<RTLIL::IdString> numbered_ports;
773 for (int i = 1; true; i++) {
774 char str[16];
775 snprintf(str, 16, "$%d", i);
776 for (auto it = cell->connections().begin(); it != cell->connections().end(); ++it) {
777 if (it->first != str)
778 continue;
779 if (!first_arg)
780 f << stringf(",");
781 first_arg = false;
782 f << stringf("\n%s ", indent.c_str());
783 dump_sigspec(f, it->second);
784 numbered_ports.insert(it->first);
785 goto found_numbered_port;
786 }
787 break;
788 found_numbered_port:;
789 }
790 for (auto it = cell->connections().begin(); it != cell->connections().end(); ++it) {
791 if (numbered_ports.count(it->first))
792 continue;
793 if (!first_arg)
794 f << stringf(",");
795 first_arg = false;
796 f << stringf("\n%s .%s(", indent.c_str(), id(it->first).c_str());
797 if (it->second.size() > 0)
798 dump_sigspec(f, it->second);
799 f << stringf(")");
800 }
801 f << stringf("\n%s" ");\n", indent.c_str());
802 }
803
804 void dump_conn(std::ostream &f, std::string indent, const RTLIL::SigSpec &left, const RTLIL::SigSpec &right)
805 {
806 f << stringf("%s" "assign ", indent.c_str());
807 dump_sigspec(f, left);
808 f << stringf(" = ");
809 dump_sigspec(f, right);
810 f << stringf(";\n");
811 }
812
813 void dump_proc_switch(std::ostream &f, std::string indent, RTLIL::SwitchRule *sw);
814
815 void dump_case_body(std::ostream &f, std::string indent, RTLIL::CaseRule *cs, bool omit_trailing_begin = false)
816 {
817 int number_of_stmts = cs->switches.size() + cs->actions.size();
818
819 if (!omit_trailing_begin && number_of_stmts >= 2)
820 f << stringf("%s" "begin\n", indent.c_str());
821
822 for (auto it = cs->actions.begin(); it != cs->actions.end(); ++it) {
823 if (it->first.size() == 0)
824 continue;
825 f << stringf("%s ", indent.c_str());
826 dump_sigspec(f, it->first);
827 f << stringf(" = ");
828 dump_sigspec(f, it->second);
829 f << stringf(";\n");
830 }
831
832 for (auto it = cs->switches.begin(); it != cs->switches.end(); ++it)
833 dump_proc_switch(f, indent + " ", *it);
834
835 if (!omit_trailing_begin && number_of_stmts == 0)
836 f << stringf("%s /* empty */;\n", indent.c_str());
837
838 if (omit_trailing_begin || number_of_stmts >= 2)
839 f << stringf("%s" "end\n", indent.c_str());
840 }
841
842 void dump_proc_switch(std::ostream &f, std::string indent, RTLIL::SwitchRule *sw)
843 {
844 if (sw->signal.size() == 0) {
845 f << stringf("%s" "begin\n", indent.c_str());
846 for (auto it = sw->cases.begin(); it != sw->cases.end(); ++it) {
847 if ((*it)->compare.size() == 0)
848 dump_case_body(f, indent + " ", *it);
849 }
850 f << stringf("%s" "end\n", indent.c_str());
851 return;
852 }
853
854 f << stringf("%s" "casez (", indent.c_str());
855 dump_sigspec(f, sw->signal);
856 f << stringf(")\n");
857
858 for (auto it = sw->cases.begin(); it != sw->cases.end(); ++it) {
859 f << stringf("%s ", indent.c_str());
860 if ((*it)->compare.size() == 0)
861 f << stringf("default");
862 else {
863 for (size_t i = 0; i < (*it)->compare.size(); i++) {
864 if (i > 0)
865 f << stringf(", ");
866 dump_sigspec(f, (*it)->compare[i]);
867 }
868 }
869 f << stringf(":\n");
870 dump_case_body(f, indent + " ", *it);
871 }
872
873 f << stringf("%s" "endcase\n", indent.c_str());
874 }
875
876 void case_body_find_regs(RTLIL::CaseRule *cs)
877 {
878 for (auto it = cs->switches.begin(); it != cs->switches.end(); ++it)
879 for (auto it2 = (*it)->cases.begin(); it2 != (*it)->cases.end(); it2++)
880 case_body_find_regs(*it2);
881
882 for (auto it = cs->actions.begin(); it != cs->actions.end(); ++it) {
883 for (auto &c : it->first.chunks())
884 if (c.wire != NULL)
885 reg_wires.insert(c.wire->name);
886 }
887 }
888
889 void dump_process(std::ostream &f, std::string indent, RTLIL::Process *proc, bool find_regs = false)
890 {
891 if (find_regs) {
892 case_body_find_regs(&proc->root_case);
893 for (auto it = proc->syncs.begin(); it != proc->syncs.end(); ++it)
894 for (auto it2 = (*it)->actions.begin(); it2 != (*it)->actions.end(); it2++) {
895 for (auto &c : it2->first.chunks())
896 if (c.wire != NULL)
897 reg_wires.insert(c.wire->name);
898 }
899 return;
900 }
901
902 f << stringf("%s" "always @* begin\n", indent.c_str());
903 dump_case_body(f, indent, &proc->root_case, true);
904
905 std::string backup_indent = indent;
906
907 for (size_t i = 0; i < proc->syncs.size(); i++)
908 {
909 RTLIL::SyncRule *sync = proc->syncs[i];
910 indent = backup_indent;
911
912 if (sync->type == RTLIL::STa) {
913 f << stringf("%s" "always @* begin\n", indent.c_str());
914 } else {
915 f << stringf("%s" "always @(", indent.c_str());
916 if (sync->type == RTLIL::STp || sync->type == RTLIL::ST1)
917 f << stringf("posedge ");
918 if (sync->type == RTLIL::STn || sync->type == RTLIL::ST0)
919 f << stringf("negedge ");
920 dump_sigspec(f, sync->signal);
921 f << stringf(") begin\n");
922 }
923 std::string ends = indent + "end\n";
924 indent += " ";
925
926 if (sync->type == RTLIL::ST0 || sync->type == RTLIL::ST1) {
927 f << stringf("%s" "if (%s", indent.c_str(), sync->type == RTLIL::ST0 ? "!" : "");
928 dump_sigspec(f, sync->signal);
929 f << stringf(") begin\n");
930 ends = indent + "end\n" + ends;
931 indent += " ";
932 }
933
934 if (sync->type == RTLIL::STp || sync->type == RTLIL::STn) {
935 for (size_t j = 0; j < proc->syncs.size(); j++) {
936 RTLIL::SyncRule *sync2 = proc->syncs[j];
937 if (sync2->type == RTLIL::ST0 || sync2->type == RTLIL::ST1) {
938 f << stringf("%s" "if (%s", indent.c_str(), sync2->type == RTLIL::ST1 ? "!" : "");
939 dump_sigspec(f, sync2->signal);
940 f << stringf(") begin\n");
941 ends = indent + "end\n" + ends;
942 indent += " ";
943 }
944 }
945 }
946
947 for (auto it = sync->actions.begin(); it != sync->actions.end(); ++it) {
948 if (it->first.size() == 0)
949 continue;
950 f << stringf("%s ", indent.c_str());
951 dump_sigspec(f, it->first);
952 f << stringf(" <= ");
953 dump_sigspec(f, it->second);
954 f << stringf(";\n");
955 }
956
957 f << stringf("%s", ends.c_str());
958 }
959 }
960
961 void dump_module(std::ostream &f, std::string indent, RTLIL::Module *module)
962 {
963 reg_wires.clear();
964 reset_auto_counter(module);
965 active_module = module;
966
967 f << stringf("\n");
968 for (auto it = module->processes.begin(); it != module->processes.end(); ++it)
969 dump_process(f, indent + " ", it->second, true);
970
971 if (!noexpr)
972 {
973 std::set<std::pair<RTLIL::Wire*,int>> reg_bits;
974 for (auto &it : module->cells_)
975 {
976 RTLIL::Cell *cell = it.second;
977 if (!reg_ct.count(cell->type) || !cell->hasPort("\\Q"))
978 continue;
979
980 RTLIL::SigSpec sig = cell->getPort("\\Q");
981
982 if (sig.is_chunk()) {
983 RTLIL::SigChunk chunk = sig.as_chunk();
984 if (chunk.wire != NULL)
985 for (int i = 0; i < chunk.width; i++)
986 reg_bits.insert(std::pair<RTLIL::Wire*,int>(chunk.wire, chunk.offset+i));
987 }
988 }
989 for (auto &it : module->wires_)
990 {
991 RTLIL::Wire *wire = it.second;
992 for (int i = 0; i < wire->width; i++)
993 if (reg_bits.count(std::pair<RTLIL::Wire*,int>(wire, i)) == 0)
994 goto this_wire_aint_reg;
995 if (wire->width)
996 reg_wires.insert(wire->name);
997 this_wire_aint_reg:;
998 }
999 }
1000
1001 dump_attributes(f, indent, module->attributes, '\n', true);
1002 f << stringf("%s" "module %s(", indent.c_str(), id(module->name, false).c_str());
1003 bool keep_running = true;
1004 for (int port_id = 1; keep_running; port_id++) {
1005 keep_running = false;
1006 for (auto it = module->wires_.begin(); it != module->wires_.end(); ++it) {
1007 RTLIL::Wire *wire = it->second;
1008 if (wire->port_id == port_id) {
1009 if (port_id != 1)
1010 f << stringf(", ");
1011 f << stringf("%s", id(wire->name).c_str());
1012 keep_running = true;
1013 continue;
1014 }
1015 }
1016 }
1017 f << stringf(");\n");
1018
1019 for (auto it = module->wires_.begin(); it != module->wires_.end(); ++it)
1020 dump_wire(f, indent + " ", it->second);
1021
1022 for (auto it = module->memories.begin(); it != module->memories.end(); ++it)
1023 dump_memory(f, indent + " ", it->second);
1024
1025 for (auto it = module->cells_.begin(); it != module->cells_.end(); ++it)
1026 dump_cell(f, indent + " ", it->second);
1027
1028 for (auto it = module->processes.begin(); it != module->processes.end(); ++it)
1029 dump_process(f, indent + " ", it->second);
1030
1031 for (auto it = module->connections().begin(); it != module->connections().end(); ++it)
1032 dump_conn(f, indent + " ", it->first, it->second);
1033
1034 f << stringf("%s" "endmodule\n", indent.c_str());
1035 active_module = NULL;
1036 }
1037
1038 struct VerilogBackend : public Backend {
1039 VerilogBackend() : Backend("verilog", "write design to verilog file") { }
1040 virtual void help()
1041 {
1042 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1043 log("\n");
1044 log(" write_verilog [options] [filename]\n");
1045 log("\n");
1046 log("Write the current design to a verilog file.\n");
1047 log("\n");
1048 log(" -norename\n");
1049 log(" without this option all internal object names (the ones with a dollar\n");
1050 log(" instead of a backslash prefix) are changed to short names in the\n");
1051 log(" format '_<number>_'.\n");
1052 log("\n");
1053 log(" -noattr\n");
1054 log(" with this option no attributes are included in the output\n");
1055 log("\n");
1056 log(" -attr2comment\n");
1057 log(" with this option attributes are included as comments in the output\n");
1058 log("\n");
1059 log(" -noexpr\n");
1060 log(" without this option all internal cells are converted to verilog\n");
1061 log(" expressions.\n");
1062 log("\n");
1063 log(" -blackboxes\n");
1064 log(" usually modules with the 'blackbox' attribute are ignored. with\n");
1065 log(" this option set only the modules with the 'blackbox' attribute\n");
1066 log(" are written to the output file.\n");
1067 log("\n");
1068 log(" -selected\n");
1069 log(" only write selected modules. modules must be selected entirely or\n");
1070 log(" not at all.\n");
1071 log("\n");
1072 }
1073 virtual void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design)
1074 {
1075 log_header("Executing Verilog backend.\n");
1076
1077 norename = false;
1078 noattr = false;
1079 attr2comment = false;
1080 noexpr = false;
1081
1082 bool blackboxes = false;
1083 bool selected = false;
1084
1085 reg_ct.clear();
1086
1087 reg_ct.insert("$dff");
1088 reg_ct.insert("$adff");
1089
1090 reg_ct.insert("$_DFF_N_");
1091 reg_ct.insert("$_DFF_P_");
1092
1093 reg_ct.insert("$_DFF_NN0_");
1094 reg_ct.insert("$_DFF_NN1_");
1095 reg_ct.insert("$_DFF_NP0_");
1096 reg_ct.insert("$_DFF_NP1_");
1097 reg_ct.insert("$_DFF_PN0_");
1098 reg_ct.insert("$_DFF_PN1_");
1099 reg_ct.insert("$_DFF_PP0_");
1100 reg_ct.insert("$_DFF_PP1_");
1101
1102 reg_ct.insert("$_DFFSR_NNN_");
1103 reg_ct.insert("$_DFFSR_NNP_");
1104 reg_ct.insert("$_DFFSR_NPN_");
1105 reg_ct.insert("$_DFFSR_NPP_");
1106 reg_ct.insert("$_DFFSR_PNN_");
1107 reg_ct.insert("$_DFFSR_PNP_");
1108 reg_ct.insert("$_DFFSR_PPN_");
1109 reg_ct.insert("$_DFFSR_PPP_");
1110
1111 size_t argidx;
1112 for (argidx = 1; argidx < args.size(); argidx++) {
1113 std::string arg = args[argidx];
1114 if (arg == "-norename") {
1115 norename = true;
1116 continue;
1117 }
1118 if (arg == "-noattr") {
1119 noattr = true;
1120 continue;
1121 }
1122 if (arg == "-attr2comment") {
1123 attr2comment = true;
1124 continue;
1125 }
1126 if (arg == "-noexpr") {
1127 noexpr = true;
1128 continue;
1129 }
1130 if (arg == "-blackboxes") {
1131 blackboxes = true;
1132 continue;
1133 }
1134 if (arg == "-selected") {
1135 selected = true;
1136 continue;
1137 }
1138 break;
1139 }
1140 extra_args(f, filename, args, argidx);
1141
1142 design->sort();
1143
1144 *f << stringf("/* Generated by %s */\n", yosys_version_str);
1145 for (auto it = design->modules_.begin(); it != design->modules_.end(); ++it) {
1146 if (it->second->get_bool_attribute("\\blackbox") != blackboxes)
1147 continue;
1148 if (selected && !design->selected_whole_module(it->first)) {
1149 if (design->selected_module(it->first))
1150 log_cmd_error("Can't handle partially selected module %s!\n", RTLIL::id2cstr(it->first));
1151 continue;
1152 }
1153 log("Dumping module `%s'.\n", it->first.c_str());
1154 dump_module(*f, "", it->second);
1155 }
1156
1157 reg_ct.clear();
1158 }
1159 } VerilogBackend;
1160
1161 PRIVATE_NAMESPACE_END