cxxrtl: disambiguate values/wires and their aliases in debug info.
[yosys.git] / backends / cxxrtl / cxxrtl_backend.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2019-2020 whitequark <whitequark@whitequark.org>
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 #include "kernel/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/utils.h"
24 #include "kernel/celltypes.h"
25 #include "kernel/log.h"
26
27 USING_YOSYS_NAMESPACE
28 PRIVATE_NAMESPACE_BEGIN
29
30 // [[CITE]]
31 // Peter Eades; Xuemin Lin; W. F. Smyth, "A Fast Effective Heuristic For The Feedback Arc Set Problem"
32 // Information Processing Letters, Vol. 47, pp 319-323, 1993
33 // https://pdfs.semanticscholar.org/c7ed/d9acce96ca357876540e19664eb9d976637f.pdf
34
35 // A topological sort (on a cell/wire graph) is always possible in a fully flattened RTLIL design without
36 // processes or logic loops where every wire has a single driver. Logic loops are illegal in RTLIL and wires
37 // with multiple drivers can be split by the `splitnets` pass; however, interdependencies between processes
38 // or module instances can create strongly connected components without introducing evaluation nondeterminism.
39 // We wish to support designs with such benign SCCs (as well as designs with multiple drivers per wire), so
40 // we sort the graph in a way that minimizes feedback arcs. If there are no feedback arcs in the sorted graph,
41 // then a more efficient evaluation method is possible, since eval() will always immediately converge.
42 template<class T>
43 struct Scheduler {
44 struct Vertex {
45 T *data;
46 Vertex *prev, *next;
47 pool<Vertex*, hash_ptr_ops> preds, succs;
48
49 Vertex() : data(NULL), prev(this), next(this) {}
50 Vertex(T *data) : data(data), prev(NULL), next(NULL) {}
51
52 bool empty() const
53 {
54 log_assert(data == NULL);
55 if (next == this) {
56 log_assert(prev == next);
57 return true;
58 }
59 return false;
60 }
61
62 void link(Vertex *list)
63 {
64 log_assert(prev == NULL && next == NULL);
65 next = list;
66 prev = list->prev;
67 list->prev->next = this;
68 list->prev = this;
69 }
70
71 void unlink()
72 {
73 log_assert(prev->next == this && next->prev == this);
74 prev->next = next;
75 next->prev = prev;
76 next = prev = NULL;
77 }
78
79 int delta() const
80 {
81 return succs.size() - preds.size();
82 }
83 };
84
85 std::vector<Vertex*> vertices;
86 Vertex *sources = new Vertex;
87 Vertex *sinks = new Vertex;
88 dict<int, Vertex*> bins;
89
90 ~Scheduler()
91 {
92 delete sources;
93 delete sinks;
94 for (auto bin : bins)
95 delete bin.second;
96 for (auto vertex : vertices)
97 delete vertex;
98 }
99
100 Vertex *add(T *data)
101 {
102 Vertex *vertex = new Vertex(data);
103 vertices.push_back(vertex);
104 return vertex;
105 }
106
107 void relink(Vertex *vertex)
108 {
109 if (vertex->succs.empty())
110 vertex->link(sinks);
111 else if (vertex->preds.empty())
112 vertex->link(sources);
113 else {
114 int delta = vertex->delta();
115 if (!bins.count(delta))
116 bins[delta] = new Vertex;
117 vertex->link(bins[delta]);
118 }
119 }
120
121 Vertex *remove(Vertex *vertex)
122 {
123 vertex->unlink();
124 for (auto pred : vertex->preds) {
125 if (pred == vertex)
126 continue;
127 log_assert(pred->succs[vertex]);
128 pred->unlink();
129 pred->succs.erase(vertex);
130 relink(pred);
131 }
132 for (auto succ : vertex->succs) {
133 if (succ == vertex)
134 continue;
135 log_assert(succ->preds[vertex]);
136 succ->unlink();
137 succ->preds.erase(vertex);
138 relink(succ);
139 }
140 vertex->preds.clear();
141 vertex->succs.clear();
142 return vertex;
143 }
144
145 std::vector<Vertex*> schedule()
146 {
147 std::vector<Vertex*> s1, s2r;
148 for (auto vertex : vertices)
149 relink(vertex);
150 bool bins_empty = false;
151 while (!(sinks->empty() && sources->empty() && bins_empty)) {
152 while (!sinks->empty())
153 s2r.push_back(remove(sinks->next));
154 while (!sources->empty())
155 s1.push_back(remove(sources->next));
156 // Choosing u in this implementation isn't O(1), but the paper handwaves which data structure they suggest
157 // using to get O(1) relinking *and* find-max-key ("it is clear"... no it isn't), so this code uses a very
158 // naive implementation of find-max-key.
159 bins_empty = true;
160 bins.template sort<std::greater<int>>();
161 for (auto bin : bins) {
162 if (!bin.second->empty()) {
163 bins_empty = false;
164 s1.push_back(remove(bin.second->next));
165 break;
166 }
167 }
168 }
169 s1.insert(s1.end(), s2r.rbegin(), s2r.rend());
170 return s1;
171 }
172 };
173
174 bool is_input_wire(const RTLIL::Wire *wire)
175 {
176 return wire->port_input && !wire->port_output;
177 }
178
179 bool is_unary_cell(RTLIL::IdString type)
180 {
181 return type.in(
182 ID($not), ID($logic_not), ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool),
183 ID($pos), ID($neg));
184 }
185
186 bool is_binary_cell(RTLIL::IdString type)
187 {
188 return type.in(
189 ID($and), ID($or), ID($xor), ID($xnor), ID($logic_and), ID($logic_or),
190 ID($shl), ID($sshl), ID($shr), ID($sshr), ID($shift), ID($shiftx),
191 ID($eq), ID($ne), ID($eqx), ID($nex), ID($gt), ID($ge), ID($lt), ID($le),
192 ID($add), ID($sub), ID($mul), ID($div), ID($mod));
193 }
194
195 bool is_extending_cell(RTLIL::IdString type)
196 {
197 return !type.in(
198 ID($logic_not), ID($logic_and), ID($logic_or),
199 ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool));
200 }
201
202 bool is_elidable_cell(RTLIL::IdString type)
203 {
204 return is_unary_cell(type) || is_binary_cell(type) || type.in(
205 ID($mux), ID($concat), ID($slice));
206 }
207
208 bool is_sync_ff_cell(RTLIL::IdString type)
209 {
210 return type.in(
211 ID($dff), ID($dffe));
212 }
213
214 bool is_ff_cell(RTLIL::IdString type)
215 {
216 return is_sync_ff_cell(type) || type.in(
217 ID($adff), ID($dffsr), ID($dlatch), ID($dlatchsr), ID($sr));
218 }
219
220 bool is_internal_cell(RTLIL::IdString type)
221 {
222 return type[0] == '$' && !type.begins_with("$paramod");
223 }
224
225 bool is_cxxrtl_blackbox_cell(const RTLIL::Cell *cell)
226 {
227 RTLIL::Module *cell_module = cell->module->design->module(cell->type);
228 log_assert(cell_module != nullptr);
229 return cell_module->get_bool_attribute(ID(cxxrtl_blackbox));
230 }
231
232 enum class CxxrtlPortType {
233 UNKNOWN = 0, // or mixed comb/sync
234 COMB = 1,
235 SYNC = 2,
236 };
237
238 CxxrtlPortType cxxrtl_port_type(const RTLIL::Cell *cell, RTLIL::IdString port)
239 {
240 RTLIL::Module *cell_module = cell->module->design->module(cell->type);
241 if (cell_module == nullptr || !cell_module->get_bool_attribute(ID(cxxrtl_blackbox)))
242 return CxxrtlPortType::UNKNOWN;
243 RTLIL::Wire *cell_output_wire = cell_module->wire(port);
244 log_assert(cell_output_wire != nullptr);
245 bool is_comb = cell_output_wire->get_bool_attribute(ID(cxxrtl_comb));
246 bool is_sync = cell_output_wire->get_bool_attribute(ID(cxxrtl_sync));
247 if (is_comb && is_sync)
248 log_cmd_error("Port `%s.%s' is marked as both `cxxrtl_comb` and `cxxrtl_sync`.\n",
249 log_id(cell_module), log_signal(cell_output_wire));
250 else if (is_comb)
251 return CxxrtlPortType::COMB;
252 else if (is_sync)
253 return CxxrtlPortType::SYNC;
254 return CxxrtlPortType::UNKNOWN;
255 }
256
257 bool is_cxxrtl_comb_port(const RTLIL::Cell *cell, RTLIL::IdString port)
258 {
259 return cxxrtl_port_type(cell, port) == CxxrtlPortType::COMB;
260 }
261
262 bool is_cxxrtl_sync_port(const RTLIL::Cell *cell, RTLIL::IdString port)
263 {
264 return cxxrtl_port_type(cell, port) == CxxrtlPortType::SYNC;
265 }
266
267 struct FlowGraph {
268 struct Node {
269 enum class Type {
270 CONNECT,
271 CELL_SYNC,
272 CELL_EVAL,
273 PROCESS
274 };
275
276 Type type;
277 RTLIL::SigSig connect = {};
278 const RTLIL::Cell *cell = NULL;
279 const RTLIL::Process *process = NULL;
280 };
281
282 std::vector<Node*> nodes;
283 dict<const RTLIL::Wire*, pool<Node*, hash_ptr_ops>> wire_comb_defs, wire_sync_defs, wire_uses;
284 dict<const RTLIL::Wire*, bool> wire_def_elidable, wire_use_elidable;
285
286 ~FlowGraph()
287 {
288 for (auto node : nodes)
289 delete node;
290 }
291
292 void add_defs(Node *node, const RTLIL::SigSpec &sig, bool fully_sync, bool elidable)
293 {
294 for (auto chunk : sig.chunks())
295 if (chunk.wire) {
296 if (fully_sync)
297 wire_sync_defs[chunk.wire].insert(node);
298 else
299 wire_comb_defs[chunk.wire].insert(node);
300 }
301 // Only comb defs of an entire wire in the right order can be elided.
302 if (!fully_sync && sig.is_wire())
303 wire_def_elidable[sig.as_wire()] = elidable;
304 }
305
306 void add_uses(Node *node, const RTLIL::SigSpec &sig)
307 {
308 for (auto chunk : sig.chunks())
309 if (chunk.wire) {
310 wire_uses[chunk.wire].insert(node);
311 // Only a single use of an entire wire in the right order can be elided.
312 // (But the use can include other chunks.)
313 if (!wire_use_elidable.count(chunk.wire))
314 wire_use_elidable[chunk.wire] = true;
315 else
316 wire_use_elidable[chunk.wire] = false;
317 }
318 }
319
320 bool is_elidable(const RTLIL::Wire *wire) const
321 {
322 if (wire_def_elidable.count(wire) && wire_use_elidable.count(wire))
323 return wire_def_elidable.at(wire) && wire_use_elidable.at(wire);
324 return false;
325 }
326
327 // Connections
328 void add_connect_defs_uses(Node *node, const RTLIL::SigSig &conn)
329 {
330 add_defs(node, conn.first, /*fully_sync=*/false, /*elidable=*/true);
331 add_uses(node, conn.second);
332 }
333
334 Node *add_node(const RTLIL::SigSig &conn)
335 {
336 Node *node = new Node;
337 node->type = Node::Type::CONNECT;
338 node->connect = conn;
339 nodes.push_back(node);
340 add_connect_defs_uses(node, conn);
341 return node;
342 }
343
344 // Cells
345 void add_cell_sync_defs(Node *node, const RTLIL::Cell *cell)
346 {
347 // To understand why this node type is necessary and why it produces comb defs, consider a cell
348 // with input \i and sync output \o, used in a design such that \i is connected to \o. This does
349 // not result in a feedback arc because the output is synchronous. However, a naive implementation
350 // of code generation for cells that assigns to inputs, evaluates cells, assigns from outputs
351 // would not be able to immediately converge...
352 //
353 // wire<1> i_tmp;
354 // cell->p_i = i_tmp.curr;
355 // cell->eval();
356 // i_tmp.next = cell->p_o.curr;
357 //
358 // ... since the wire connecting the input and output ports would not be localizable. To solve
359 // this, the cell is split into two scheduling nodes; one exclusively for sync outputs, and
360 // another for inputs and all non-sync outputs. This way the generated code can be rearranged...
361 //
362 // value<1> i_tmp;
363 // i_tmp = cell->p_o.curr;
364 // cell->p_i = i_tmp;
365 // cell->eval();
366 //
367 // eliminating the unnecessary delta cycle. Conceptually, the CELL_SYNC node type is a series of
368 // connections of the form `connect \lhs \cell.\sync_output`; the right-hand side of these is not
369 // expressible as a wire in RTLIL. If it was expressible, then `\cell.\sync_output` would have
370 // a sync def, and this node would be an ordinary CONNECT node, with `\lhs` having a comb def.
371 // Because it isn't, a special node type is used, the right-hand side does not appear anywhere,
372 // and the left-hand side has a comb def.
373 for (auto conn : cell->connections())
374 if (cell->output(conn.first))
375 if (is_cxxrtl_sync_port(cell, conn.first)) {
376 // See note regarding elidability below.
377 add_defs(node, conn.second, /*fully_sync=*/false, /*elidable=*/false);
378 }
379 }
380
381 void add_cell_eval_defs_uses(Node *node, const RTLIL::Cell *cell)
382 {
383 for (auto conn : cell->connections()) {
384 if (cell->output(conn.first)) {
385 if (is_elidable_cell(cell->type))
386 add_defs(node, conn.second, /*fully_sync=*/false, /*elidable=*/true);
387 else if (is_sync_ff_cell(cell->type) || (cell->type == ID($memrd) && cell->getParam(ID::CLK_ENABLE).as_bool()))
388 add_defs(node, conn.second, /*fully_sync=*/true, /*elidable=*/false);
389 else if (is_internal_cell(cell->type))
390 add_defs(node, conn.second, /*fully_sync=*/false, /*elidable=*/false);
391 else if (!is_cxxrtl_sync_port(cell, conn.first)) {
392 // Although at first it looks like outputs of user-defined cells may always be elided, the reality is
393 // more complex. Fully sync outputs produce no defs and so don't participate in elision. Fully comb
394 // outputs are assigned in a different way depending on whether the cell's eval() immediately converged.
395 // Unknown/mixed outputs could be elided, but should be rare in practical designs and don't justify
396 // the infrastructure required to elide outputs of cells with many of them.
397 add_defs(node, conn.second, /*fully_sync=*/false, /*elidable=*/false);
398 }
399 }
400 if (cell->input(conn.first))
401 add_uses(node, conn.second);
402 }
403 }
404
405 Node *add_node(const RTLIL::Cell *cell)
406 {
407 log_assert(cell->known());
408
409 bool has_fully_sync_outputs = false;
410 for (auto conn : cell->connections())
411 if (cell->output(conn.first) && is_cxxrtl_sync_port(cell, conn.first)) {
412 has_fully_sync_outputs = true;
413 break;
414 }
415 if (has_fully_sync_outputs) {
416 Node *node = new Node;
417 node->type = Node::Type::CELL_SYNC;
418 node->cell = cell;
419 nodes.push_back(node);
420 add_cell_sync_defs(node, cell);
421 }
422
423 Node *node = new Node;
424 node->type = Node::Type::CELL_EVAL;
425 node->cell = cell;
426 nodes.push_back(node);
427 add_cell_eval_defs_uses(node, cell);
428 return node;
429 }
430
431 // Processes
432 void add_case_defs_uses(Node *node, const RTLIL::CaseRule *case_)
433 {
434 for (auto &action : case_->actions) {
435 add_defs(node, action.first, /*is_sync=*/false, /*elidable=*/false);
436 add_uses(node, action.second);
437 }
438 for (auto sub_switch : case_->switches) {
439 add_uses(node, sub_switch->signal);
440 for (auto sub_case : sub_switch->cases) {
441 for (auto &compare : sub_case->compare)
442 add_uses(node, compare);
443 add_case_defs_uses(node, sub_case);
444 }
445 }
446 }
447
448 void add_process_defs_uses(Node *node, const RTLIL::Process *process)
449 {
450 add_case_defs_uses(node, &process->root_case);
451 for (auto sync : process->syncs)
452 for (auto action : sync->actions) {
453 if (sync->type == RTLIL::STp || sync->type == RTLIL::STn || sync->type == RTLIL::STe)
454 add_defs(node, action.first, /*is_sync=*/true, /*elidable=*/false);
455 else
456 add_defs(node, action.first, /*is_sync=*/false, /*elidable=*/false);
457 add_uses(node, action.second);
458 }
459 }
460
461 Node *add_node(const RTLIL::Process *process)
462 {
463 Node *node = new Node;
464 node->type = Node::Type::PROCESS;
465 node->process = process;
466 nodes.push_back(node);
467 add_process_defs_uses(node, process);
468 return node;
469 }
470 };
471
472 std::vector<std::string> split_by(const std::string &str, const std::string &sep)
473 {
474 std::vector<std::string> result;
475 size_t prev = 0;
476 while (true) {
477 size_t curr = str.find_first_of(sep, prev);
478 if (curr == std::string::npos) {
479 std::string part = str.substr(prev);
480 if (!part.empty()) result.push_back(part);
481 break;
482 } else {
483 std::string part = str.substr(prev, curr - prev);
484 if (!part.empty()) result.push_back(part);
485 prev = curr + 1;
486 }
487 }
488 return result;
489 }
490
491 std::string escape_cxx_string(const std::string &input)
492 {
493 std::string output = "\"";
494 for (auto c : input) {
495 if (::isprint(c)) {
496 if (c == '\\')
497 output.push_back('\\');
498 output.push_back(c);
499 } else {
500 char l = c & 0xf, h = (c >> 4) & 0xf;
501 output.append("\\x");
502 output.push_back((h < 10 ? '0' + h : 'a' + h - 10));
503 output.push_back((l < 10 ? '0' + l : 'a' + l - 10));
504 }
505 }
506 output.push_back('"');
507 if (output.find('\0') != std::string::npos) {
508 output.insert(0, "std::string {");
509 output.append(stringf(", %zu}", input.size()));
510 }
511 return output;
512 }
513
514 template<class T>
515 std::string get_hdl_name(T *object)
516 {
517 if (object->has_attribute(ID::hdlname))
518 return object->get_string_attribute(ID::hdlname);
519 else
520 return object->name.str().substr(1);
521 }
522
523 struct CxxrtlWorker {
524 bool split_intf = false;
525 std::string intf_filename;
526 std::string design_ns = "cxxrtl_design";
527 std::ostream *impl_f = nullptr;
528 std::ostream *intf_f = nullptr;
529
530 bool run_flatten = false;
531 bool run_proc = false;
532
533 bool unbuffer_internal = false;
534 bool unbuffer_public = false;
535 bool localize_internal = false;
536 bool localize_public = false;
537 bool elide_internal = false;
538 bool elide_public = false;
539
540 bool debug_info = false;
541
542 std::ostringstream f;
543 std::string indent;
544 int temporary = 0;
545
546 dict<const RTLIL::Module*, SigMap> sigmaps;
547 pool<const RTLIL::Wire*> edge_wires;
548 dict<RTLIL::SigBit, RTLIL::SyncType> edge_types;
549 pool<const RTLIL::Memory*> writable_memories;
550 dict<const RTLIL::Cell*, pool<const RTLIL::Cell*>> transparent_for;
551 dict<const RTLIL::Wire*, FlowGraph::Node> elided_wires;
552 dict<const RTLIL::Module*, std::vector<FlowGraph::Node>> schedule;
553 pool<const RTLIL::Wire*> unbuffered_wires;
554 pool<const RTLIL::Wire*> localized_wires;
555 dict<const RTLIL::Wire*, const RTLIL::Wire*> debug_alias_wires;
556 dict<const RTLIL::Wire*, RTLIL::Const> debug_const_wires;
557 dict<const RTLIL::Module*, pool<std::string>> blackbox_specializations;
558 dict<const RTLIL::Module*, bool> eval_converges;
559
560 void inc_indent() {
561 indent += "\t";
562 }
563 void dec_indent() {
564 indent.resize(indent.size() - 1);
565 }
566
567 // RTLIL allows any characters in names other than whitespace. This presents an issue for generating C++ code
568 // because C++ identifiers may be only alphanumeric, cannot clash with C++ keywords, and cannot clash with cxxrtl
569 // identifiers. This issue can be solved with a name mangling scheme. We choose a name mangling scheme that results
570 // in readable identifiers, does not depend on an up-to-date list of C++ keywords, and is easy to apply. Its rules:
571 // 1. All generated identifiers start with `_`.
572 // 1a. Generated identifiers for public names (beginning with `\`) start with `p_`.
573 // 1b. Generated identifiers for internal names (beginning with `$`) start with `i_`.
574 // 2. An underscore is escaped with another underscore, i.e. `__`.
575 // 3. Any other non-alnum character is escaped with underscores around its lowercase hex code, e.g. `@` as `_40_`.
576 std::string mangle_name(const RTLIL::IdString &name)
577 {
578 std::string mangled;
579 bool first = true;
580 for (char c : name.str()) {
581 if (first) {
582 first = false;
583 if (c == '\\')
584 mangled += "p_";
585 else if (c == '$')
586 mangled += "i_";
587 else
588 log_assert(false);
589 } else {
590 if (isalnum(c)) {
591 mangled += c;
592 } else if (c == '_') {
593 mangled += "__";
594 } else {
595 char l = c & 0xf, h = (c >> 4) & 0xf;
596 mangled += '_';
597 mangled += (h < 10 ? '0' + h : 'a' + h - 10);
598 mangled += (l < 10 ? '0' + l : 'a' + l - 10);
599 mangled += '_';
600 }
601 }
602 }
603 return mangled;
604 }
605
606 std::string mangle_module_name(const RTLIL::IdString &name, bool is_blackbox = false)
607 {
608 // Class namespace.
609 if (is_blackbox)
610 return "bb_" + mangle_name(name);
611 return mangle_name(name);
612 }
613
614 std::string mangle_memory_name(const RTLIL::IdString &name)
615 {
616 // Class member namespace.
617 return "memory_" + mangle_name(name);
618 }
619
620 std::string mangle_cell_name(const RTLIL::IdString &name)
621 {
622 // Class member namespace.
623 return "cell_" + mangle_name(name);
624 }
625
626 std::string mangle_wire_name(const RTLIL::IdString &name)
627 {
628 // Class member namespace.
629 return mangle_name(name);
630 }
631
632 std::string mangle(const RTLIL::Module *module)
633 {
634 return mangle_module_name(module->name, /*is_blackbox=*/module->get_bool_attribute(ID(cxxrtl_blackbox)));
635 }
636
637 std::string mangle(const RTLIL::Memory *memory)
638 {
639 return mangle_memory_name(memory->name);
640 }
641
642 std::string mangle(const RTLIL::Cell *cell)
643 {
644 return mangle_cell_name(cell->name);
645 }
646
647 std::string mangle(const RTLIL::Wire *wire)
648 {
649 return mangle_wire_name(wire->name);
650 }
651
652 std::string mangle(RTLIL::SigBit sigbit)
653 {
654 log_assert(sigbit.wire != NULL);
655 if (sigbit.wire->width == 1)
656 return mangle(sigbit.wire);
657 return mangle(sigbit.wire) + "_" + std::to_string(sigbit.offset);
658 }
659
660 std::vector<std::string> template_param_names(const RTLIL::Module *module)
661 {
662 if (!module->has_attribute(ID(cxxrtl_template)))
663 return {};
664
665 if (module->attributes.at(ID(cxxrtl_template)).flags != RTLIL::CONST_FLAG_STRING)
666 log_cmd_error("Attribute `cxxrtl_template' of module `%s' is not a string.\n", log_id(module));
667
668 std::vector<std::string> param_names = split_by(module->get_string_attribute(ID(cxxrtl_template)), " \t");
669 for (const auto &param_name : param_names) {
670 // Various lowercase prefixes (p_, i_, cell_, ...) are used for member variables, so require
671 // parameters to start with an uppercase letter to avoid name conflicts. (This is the convention
672 // in both Verilog and C++, anyway.)
673 if (!isupper(param_name[0]))
674 log_cmd_error("Attribute `cxxrtl_template' of module `%s' includes a parameter `%s', "
675 "which does not start with an uppercase letter.\n",
676 log_id(module), param_name.c_str());
677 }
678 return param_names;
679 }
680
681 std::string template_params(const RTLIL::Module *module, bool is_decl)
682 {
683 std::vector<std::string> param_names = template_param_names(module);
684 if (param_names.empty())
685 return "";
686
687 std::string params = "<";
688 bool first = true;
689 for (const auto &param_name : param_names) {
690 if (!first)
691 params += ", ";
692 first = false;
693 if (is_decl)
694 params += "size_t ";
695 params += param_name;
696 }
697 params += ">";
698 return params;
699 }
700
701 std::string template_args(const RTLIL::Cell *cell)
702 {
703 RTLIL::Module *cell_module = cell->module->design->module(cell->type);
704 log_assert(cell_module != nullptr);
705 if (!cell_module->get_bool_attribute(ID(cxxrtl_blackbox)))
706 return "";
707
708 std::vector<std::string> param_names = template_param_names(cell_module);
709 if (param_names.empty())
710 return "";
711
712 std::string params = "<";
713 bool first = true;
714 for (const auto &param_name : param_names) {
715 if (!first)
716 params += ", ";
717 first = false;
718 params += "/*" + param_name + "=*/";
719 RTLIL::IdString id_param_name = '\\' + param_name;
720 if (!cell->hasParam(id_param_name))
721 log_cmd_error("Cell `%s.%s' does not have a parameter `%s', which is required by the templated module `%s'.\n",
722 log_id(cell->module), log_id(cell), param_name.c_str(), log_id(cell_module));
723 RTLIL::Const param_value = cell->getParam(id_param_name);
724 if (((param_value.flags & ~RTLIL::CONST_FLAG_SIGNED) != 0) || param_value.as_int() < 0)
725 log_cmd_error("Parameter `%s' of cell `%s.%s', which is required by the templated module `%s', "
726 "is not a positive integer.\n",
727 param_name.c_str(), log_id(cell->module), log_id(cell), log_id(cell_module));
728 params += std::to_string(cell->getParam(id_param_name).as_int());
729 }
730 params += ">";
731 return params;
732 }
733
734 std::string fresh_temporary()
735 {
736 return stringf("tmp_%d", temporary++);
737 }
738
739 void dump_attrs(const RTLIL::AttrObject *object)
740 {
741 for (auto attr : object->attributes) {
742 f << indent << "// " << attr.first.str() << ": ";
743 if (attr.second.flags & RTLIL::CONST_FLAG_STRING) {
744 f << attr.second.decode_string();
745 } else {
746 f << attr.second.as_int(/*is_signed=*/attr.second.flags & RTLIL::CONST_FLAG_SIGNED);
747 }
748 f << "\n";
749 }
750 }
751
752 void dump_const_init(const RTLIL::Const &data, int width, int offset = 0, bool fixed_width = false)
753 {
754 const int CHUNK_SIZE = 32;
755 f << "{";
756 while (width > 0) {
757 int chunk_width = min(width, CHUNK_SIZE);
758 uint32_t chunk = data.extract(offset, chunk_width).as_int();
759 if (fixed_width)
760 f << stringf("0x%.*xu", (3 + chunk_width) / 4, chunk);
761 else
762 f << stringf("%#xu", chunk);
763 if (width > CHUNK_SIZE)
764 f << ',';
765 offset += CHUNK_SIZE;
766 width -= CHUNK_SIZE;
767 }
768 f << "}";
769 }
770
771 void dump_const_init(const RTLIL::Const &data)
772 {
773 dump_const_init(data, data.size());
774 }
775
776 void dump_const(const RTLIL::Const &data, int width, int offset = 0, bool fixed_width = false)
777 {
778 f << "value<" << width << ">";
779 dump_const_init(data, width, offset, fixed_width);
780 }
781
782 void dump_const(const RTLIL::Const &data)
783 {
784 dump_const(data, data.size());
785 }
786
787 bool dump_sigchunk(const RTLIL::SigChunk &chunk, bool is_lhs)
788 {
789 if (chunk.wire == NULL) {
790 dump_const(chunk.data, chunk.width, chunk.offset);
791 return false;
792 } else {
793 if (elided_wires.count(chunk.wire)) {
794 log_assert(!is_lhs);
795 const FlowGraph::Node &node = elided_wires[chunk.wire];
796 switch (node.type) {
797 case FlowGraph::Node::Type::CONNECT:
798 dump_connect_elided(node.connect);
799 break;
800 case FlowGraph::Node::Type::CELL_EVAL:
801 log_assert(is_elidable_cell(node.cell->type));
802 dump_cell_elided(node.cell);
803 break;
804 default:
805 log_assert(false);
806 }
807 } else if (unbuffered_wires[chunk.wire] || is_input_wire(chunk.wire)) {
808 f << mangle(chunk.wire);
809 } else {
810 f << mangle(chunk.wire) << (is_lhs ? ".next" : ".curr");
811 }
812 if (chunk.width == chunk.wire->width && chunk.offset == 0)
813 return false;
814 else if (chunk.width == 1)
815 f << ".slice<" << chunk.offset << ">()";
816 else
817 f << ".slice<" << chunk.offset+chunk.width-1 << "," << chunk.offset << ">()";
818 return true;
819 }
820 }
821
822 bool dump_sigspec(const RTLIL::SigSpec &sig, bool is_lhs)
823 {
824 if (sig.empty()) {
825 f << "value<0>()";
826 return false;
827 } else if (sig.is_chunk()) {
828 return dump_sigchunk(sig.as_chunk(), is_lhs);
829 } else {
830 dump_sigchunk(*sig.chunks().rbegin(), is_lhs);
831 for (auto it = sig.chunks().rbegin() + 1; it != sig.chunks().rend(); ++it) {
832 f << ".concat(";
833 dump_sigchunk(*it, is_lhs);
834 f << ")";
835 }
836 return true;
837 }
838 }
839
840 void dump_sigspec_lhs(const RTLIL::SigSpec &sig)
841 {
842 dump_sigspec(sig, /*is_lhs=*/true);
843 }
844
845 void dump_sigspec_rhs(const RTLIL::SigSpec &sig)
846 {
847 // In the contexts where we want template argument deduction to occur for `template<size_t Bits> ... value<Bits>`,
848 // it is necessary to have the argument to already be a `value<N>`, since template argument deduction and implicit
849 // type conversion are mutually exclusive. In these contexts, we use dump_sigspec_rhs() to emit an explicit
850 // type conversion, but only if the expression needs it.
851 bool is_complex = dump_sigspec(sig, /*is_lhs=*/false);
852 if (is_complex)
853 f << ".val()";
854 }
855
856 void collect_sigspec_rhs(const RTLIL::SigSpec &sig, std::vector<RTLIL::IdString> &cells)
857 {
858 for (auto chunk : sig.chunks()) {
859 if (!chunk.wire || !elided_wires.count(chunk.wire))
860 continue;
861
862 const FlowGraph::Node &node = elided_wires[chunk.wire];
863 switch (node.type) {
864 case FlowGraph::Node::Type::CONNECT:
865 collect_connect(node.connect, cells);
866 break;
867 case FlowGraph::Node::Type::CELL_EVAL:
868 collect_cell_eval(node.cell, cells);
869 break;
870 default:
871 log_assert(false);
872 }
873 }
874 }
875
876 void dump_connect_elided(const RTLIL::SigSig &conn)
877 {
878 dump_sigspec_rhs(conn.second);
879 }
880
881 bool is_connect_elided(const RTLIL::SigSig &conn)
882 {
883 return conn.first.is_wire() && elided_wires.count(conn.first.as_wire());
884 }
885
886 void collect_connect(const RTLIL::SigSig &conn, std::vector<RTLIL::IdString> &cells)
887 {
888 if (!is_connect_elided(conn))
889 return;
890
891 collect_sigspec_rhs(conn.second, cells);
892 }
893
894 void dump_connect(const RTLIL::SigSig &conn)
895 {
896 if (is_connect_elided(conn))
897 return;
898
899 f << indent << "// connection\n";
900 f << indent;
901 dump_sigspec_lhs(conn.first);
902 f << " = ";
903 dump_connect_elided(conn);
904 f << ";\n";
905 }
906
907 void dump_cell_sync(const RTLIL::Cell *cell)
908 {
909 const char *access = is_cxxrtl_blackbox_cell(cell) ? "->" : ".";
910 f << indent << "// cell " << cell->name.str() << " syncs\n";
911 for (auto conn : cell->connections())
912 if (cell->output(conn.first))
913 if (is_cxxrtl_sync_port(cell, conn.first)) {
914 f << indent;
915 dump_sigspec_lhs(conn.second);
916 f << " = " << mangle(cell) << access << mangle_wire_name(conn.first) << ".curr;\n";
917 }
918 }
919
920 void dump_cell_elided(const RTLIL::Cell *cell)
921 {
922 // Unary cells
923 if (is_unary_cell(cell->type)) {
924 f << cell->type.substr(1);
925 if (is_extending_cell(cell->type))
926 f << '_' << (cell->getParam(ID::A_SIGNED).as_bool() ? 's' : 'u');
927 f << "<" << cell->getParam(ID::Y_WIDTH).as_int() << ">(";
928 dump_sigspec_rhs(cell->getPort(ID::A));
929 f << ")";
930 // Binary cells
931 } else if (is_binary_cell(cell->type)) {
932 f << cell->type.substr(1);
933 if (is_extending_cell(cell->type))
934 f << '_' << (cell->getParam(ID::A_SIGNED).as_bool() ? 's' : 'u') <<
935 (cell->getParam(ID::B_SIGNED).as_bool() ? 's' : 'u');
936 f << "<" << cell->getParam(ID::Y_WIDTH).as_int() << ">(";
937 dump_sigspec_rhs(cell->getPort(ID::A));
938 f << ", ";
939 dump_sigspec_rhs(cell->getPort(ID::B));
940 f << ")";
941 // Muxes
942 } else if (cell->type == ID($mux)) {
943 f << "(";
944 dump_sigspec_rhs(cell->getPort(ID::S));
945 f << " ? ";
946 dump_sigspec_rhs(cell->getPort(ID::B));
947 f << " : ";
948 dump_sigspec_rhs(cell->getPort(ID::A));
949 f << ")";
950 // Concats
951 } else if (cell->type == ID($concat)) {
952 dump_sigspec_rhs(cell->getPort(ID::B));
953 f << ".concat(";
954 dump_sigspec_rhs(cell->getPort(ID::A));
955 f << ").val()";
956 // Slices
957 } else if (cell->type == ID($slice)) {
958 dump_sigspec_rhs(cell->getPort(ID::A));
959 f << ".slice<";
960 f << cell->getParam(ID::OFFSET).as_int() + cell->getParam(ID::Y_WIDTH).as_int() - 1;
961 f << ",";
962 f << cell->getParam(ID::OFFSET).as_int();
963 f << ">().val()";
964 } else {
965 log_assert(false);
966 }
967 }
968
969 bool is_cell_elided(const RTLIL::Cell *cell)
970 {
971 return is_elidable_cell(cell->type) && cell->hasPort(ID::Y) && cell->getPort(ID::Y).is_wire() &&
972 elided_wires.count(cell->getPort(ID::Y).as_wire());
973 }
974
975 void collect_cell_eval(const RTLIL::Cell *cell, std::vector<RTLIL::IdString> &cells)
976 {
977 if (!is_cell_elided(cell))
978 return;
979
980 cells.push_back(cell->name);
981 for (auto port : cell->connections())
982 if (port.first != ID::Y)
983 collect_sigspec_rhs(port.second, cells);
984 }
985
986 void dump_cell_eval(const RTLIL::Cell *cell)
987 {
988 if (is_cell_elided(cell))
989 return;
990 if (cell->type == ID($meminit))
991 return; // Handled elsewhere.
992
993 std::vector<RTLIL::IdString> elided_cells;
994 if (is_elidable_cell(cell->type)) {
995 for (auto port : cell->connections())
996 if (port.first != ID::Y)
997 collect_sigspec_rhs(port.second, elided_cells);
998 }
999 if (elided_cells.empty()) {
1000 dump_attrs(cell);
1001 f << indent << "// cell " << cell->name.str() << "\n";
1002 } else {
1003 f << indent << "// cells";
1004 for (auto elided_cell : elided_cells)
1005 f << " " << elided_cell.str();
1006 f << "\n";
1007 }
1008
1009 // Elidable cells
1010 if (is_elidable_cell(cell->type)) {
1011 f << indent;
1012 dump_sigspec_lhs(cell->getPort(ID::Y));
1013 f << " = ";
1014 dump_cell_elided(cell);
1015 f << ";\n";
1016 // Parallel (one-hot) muxes
1017 } else if (cell->type == ID($pmux)) {
1018 int width = cell->getParam(ID::WIDTH).as_int();
1019 int s_width = cell->getParam(ID::S_WIDTH).as_int();
1020 bool first = true;
1021 for (int part = 0; part < s_width; part++) {
1022 f << (first ? indent : " else ");
1023 first = false;
1024 f << "if (";
1025 dump_sigspec_rhs(cell->getPort(ID::S).extract(part));
1026 f << ") {\n";
1027 inc_indent();
1028 f << indent;
1029 dump_sigspec_lhs(cell->getPort(ID::Y));
1030 f << " = ";
1031 dump_sigspec_rhs(cell->getPort(ID::B).extract(part * width, width));
1032 f << ";\n";
1033 dec_indent();
1034 f << indent << "}";
1035 }
1036 f << " else {\n";
1037 inc_indent();
1038 f << indent;
1039 dump_sigspec_lhs(cell->getPort(ID::Y));
1040 f << " = ";
1041 dump_sigspec_rhs(cell->getPort(ID::A));
1042 f << ";\n";
1043 dec_indent();
1044 f << indent << "}\n";
1045 // Flip-flops
1046 } else if (is_ff_cell(cell->type)) {
1047 if (cell->hasPort(ID::CLK) && cell->getPort(ID::CLK).is_wire()) {
1048 // Edge-sensitive logic
1049 RTLIL::SigBit clk_bit = cell->getPort(ID::CLK)[0];
1050 clk_bit = sigmaps[clk_bit.wire->module](clk_bit);
1051 f << indent << "if (" << (cell->getParam(ID::CLK_POLARITY).as_bool() ? "posedge_" : "negedge_")
1052 << mangle(clk_bit) << ") {\n";
1053 inc_indent();
1054 if (cell->type == ID($dffe)) {
1055 f << indent << "if (";
1056 dump_sigspec_rhs(cell->getPort(ID::EN));
1057 f << " == value<1> {" << cell->getParam(ID::EN_POLARITY).as_bool() << "u}) {\n";
1058 inc_indent();
1059 }
1060 f << indent;
1061 dump_sigspec_lhs(cell->getPort(ID::Q));
1062 f << " = ";
1063 dump_sigspec_rhs(cell->getPort(ID::D));
1064 f << ";\n";
1065 if (cell->type == ID($dffe)) {
1066 dec_indent();
1067 f << indent << "}\n";
1068 }
1069 dec_indent();
1070 f << indent << "}\n";
1071 } else if (cell->hasPort(ID::EN)) {
1072 // Level-sensitive logic
1073 f << indent << "if (";
1074 dump_sigspec_rhs(cell->getPort(ID::EN));
1075 f << " == value<1> {" << cell->getParam(ID::EN_POLARITY).as_bool() << "u}) {\n";
1076 inc_indent();
1077 f << indent;
1078 dump_sigspec_lhs(cell->getPort(ID::Q));
1079 f << " = ";
1080 dump_sigspec_rhs(cell->getPort(ID::D));
1081 f << ";\n";
1082 dec_indent();
1083 f << indent << "}\n";
1084 }
1085 if (cell->hasPort(ID::ARST)) {
1086 // Asynchronous reset (entire coarse cell at once)
1087 f << indent << "if (";
1088 dump_sigspec_rhs(cell->getPort(ID::ARST));
1089 f << " == value<1> {" << cell->getParam(ID::ARST_POLARITY).as_bool() << "u}) {\n";
1090 inc_indent();
1091 f << indent;
1092 dump_sigspec_lhs(cell->getPort(ID::Q));
1093 f << " = ";
1094 dump_const(cell->getParam(ID::ARST_VALUE));
1095 f << ";\n";
1096 dec_indent();
1097 f << indent << "}\n";
1098 }
1099 if (cell->hasPort(ID::SET)) {
1100 // Asynchronous set (for individual bits)
1101 f << indent;
1102 dump_sigspec_lhs(cell->getPort(ID::Q));
1103 f << " = ";
1104 dump_sigspec_lhs(cell->getPort(ID::Q));
1105 f << ".update(";
1106 dump_const(RTLIL::Const(RTLIL::S1, cell->getParam(ID::WIDTH).as_int()));
1107 f << ", ";
1108 dump_sigspec_rhs(cell->getPort(ID::SET));
1109 f << (cell->getParam(ID::SET_POLARITY).as_bool() ? "" : ".bit_not()") << ");\n";
1110 }
1111 if (cell->hasPort(ID::CLR)) {
1112 // Asynchronous clear (for individual bits; priority over set)
1113 f << indent;
1114 dump_sigspec_lhs(cell->getPort(ID::Q));
1115 f << " = ";
1116 dump_sigspec_lhs(cell->getPort(ID::Q));
1117 f << ".update(";
1118 dump_const(RTLIL::Const(RTLIL::S0, cell->getParam(ID::WIDTH).as_int()));
1119 f << ", ";
1120 dump_sigspec_rhs(cell->getPort(ID::CLR));
1121 f << (cell->getParam(ID::CLR_POLARITY).as_bool() ? "" : ".bit_not()") << ");\n";
1122 }
1123 // Memory ports
1124 } else if (cell->type.in(ID($memrd), ID($memwr))) {
1125 if (cell->getParam(ID::CLK_ENABLE).as_bool()) {
1126 RTLIL::SigBit clk_bit = cell->getPort(ID::CLK)[0];
1127 clk_bit = sigmaps[clk_bit.wire->module](clk_bit);
1128 f << indent << "if (" << (cell->getParam(ID::CLK_POLARITY).as_bool() ? "posedge_" : "negedge_")
1129 << mangle(clk_bit) << ") {\n";
1130 inc_indent();
1131 }
1132 RTLIL::Memory *memory = cell->module->memories[cell->getParam(ID::MEMID).decode_string()];
1133 std::string valid_index_temp = fresh_temporary();
1134 f << indent << "auto " << valid_index_temp << " = memory_index(";
1135 dump_sigspec_rhs(cell->getPort(ID::ADDR));
1136 f << ", " << memory->start_offset << ", " << memory->size << ");\n";
1137 if (cell->type == ID($memrd)) {
1138 bool has_enable = cell->getParam(ID::CLK_ENABLE).as_bool() && !cell->getPort(ID::EN).is_fully_ones();
1139 if (has_enable) {
1140 f << indent << "if (";
1141 dump_sigspec_rhs(cell->getPort(ID::EN));
1142 f << ") {\n";
1143 inc_indent();
1144 }
1145 // The generated code has two bounds checks; one in an assertion, and another that guards the read.
1146 // This is done so that the code does not invoke undefined behavior under any conditions, but nevertheless
1147 // loudly crashes if an illegal condition is encountered. The assert may be turned off with -NDEBUG not
1148 // just for release builds, but also to make sure the simulator (which is presumably embedded in some
1149 // larger program) will never crash the code that calls into it.
1150 //
1151 // If assertions are disabled, out of bounds reads are defined to return zero.
1152 f << indent << "assert(" << valid_index_temp << ".valid && \"out of bounds read\");\n";
1153 f << indent << "if(" << valid_index_temp << ".valid) {\n";
1154 inc_indent();
1155 if (writable_memories[memory]) {
1156 std::string addr_temp = fresh_temporary();
1157 f << indent << "const value<" << cell->getPort(ID::ADDR).size() << "> &" << addr_temp << " = ";
1158 dump_sigspec_rhs(cell->getPort(ID::ADDR));
1159 f << ";\n";
1160 std::string lhs_temp = fresh_temporary();
1161 f << indent << "value<" << memory->width << "> " << lhs_temp << " = "
1162 << mangle(memory) << "[" << valid_index_temp << ".index];\n";
1163 std::vector<const RTLIL::Cell*> memwr_cells(transparent_for[cell].begin(), transparent_for[cell].end());
1164 std::sort(memwr_cells.begin(), memwr_cells.end(),
1165 [](const RTLIL::Cell *a, const RTLIL::Cell *b) {
1166 return a->getParam(ID::PRIORITY).as_int() < b->getParam(ID::PRIORITY).as_int();
1167 });
1168 for (auto memwr_cell : memwr_cells) {
1169 f << indent << "if (" << addr_temp << " == ";
1170 dump_sigspec_rhs(memwr_cell->getPort(ID::ADDR));
1171 f << ") {\n";
1172 inc_indent();
1173 f << indent << lhs_temp << " = " << lhs_temp;
1174 f << ".update(";
1175 dump_sigspec_rhs(memwr_cell->getPort(ID::DATA));
1176 f << ", ";
1177 dump_sigspec_rhs(memwr_cell->getPort(ID::EN));
1178 f << ");\n";
1179 dec_indent();
1180 f << indent << "}\n";
1181 }
1182 f << indent;
1183 dump_sigspec_lhs(cell->getPort(ID::DATA));
1184 f << " = " << lhs_temp << ";\n";
1185 } else {
1186 f << indent;
1187 dump_sigspec_lhs(cell->getPort(ID::DATA));
1188 f << " = " << mangle(memory) << "[" << valid_index_temp << ".index];\n";
1189 }
1190 dec_indent();
1191 f << indent << "} else {\n";
1192 inc_indent();
1193 f << indent;
1194 dump_sigspec_lhs(cell->getPort(ID::DATA));
1195 f << " = value<" << memory->width << "> {};\n";
1196 dec_indent();
1197 f << indent << "}\n";
1198 if (has_enable) {
1199 dec_indent();
1200 f << indent << "}\n";
1201 }
1202 } else /*if (cell->type == ID($memwr))*/ {
1203 log_assert(writable_memories[memory]);
1204 // See above for rationale of having both the assert and the condition.
1205 //
1206 // If assertions are disabled, out of bounds writes are defined to do nothing.
1207 f << indent << "assert(" << valid_index_temp << ".valid && \"out of bounds write\");\n";
1208 f << indent << "if (" << valid_index_temp << ".valid) {\n";
1209 inc_indent();
1210 f << indent << mangle(memory) << ".update(" << valid_index_temp << ".index, ";
1211 dump_sigspec_rhs(cell->getPort(ID::DATA));
1212 f << ", ";
1213 dump_sigspec_rhs(cell->getPort(ID::EN));
1214 f << ", " << cell->getParam(ID::PRIORITY).as_int() << ");\n";
1215 dec_indent();
1216 f << indent << "}\n";
1217 }
1218 if (cell->getParam(ID::CLK_ENABLE).as_bool()) {
1219 dec_indent();
1220 f << indent << "}\n";
1221 }
1222 // Internal cells
1223 } else if (is_internal_cell(cell->type)) {
1224 log_cmd_error("Unsupported internal cell `%s'.\n", cell->type.c_str());
1225 // User cells
1226 } else {
1227 log_assert(cell->known());
1228 const char *access = is_cxxrtl_blackbox_cell(cell) ? "->" : ".";
1229 for (auto conn : cell->connections())
1230 if (cell->input(conn.first) && !cell->output(conn.first)) {
1231 f << indent << mangle(cell) << access << mangle_wire_name(conn.first) << " = ";
1232 dump_sigspec_rhs(conn.second);
1233 f << ";\n";
1234 if (getenv("CXXRTL_VOID_MY_WARRANTY")) {
1235 // Until we have proper clock tree detection, this really awful hack that opportunistically
1236 // propagates prev_* values for clocks can be used to estimate how much faster a design could
1237 // be if only one clock edge was simulated by replacing:
1238 // top.p_clk = value<1>{0u}; top.step();
1239 // top.p_clk = value<1>{1u}; top.step();
1240 // with:
1241 // top.prev_p_clk = value<1>{0u}; top.p_clk = value<1>{1u}; top.step();
1242 // Don't rely on this; it will be removed without warning.
1243 RTLIL::Module *cell_module = cell->module->design->module(cell->type);
1244 if (cell_module != nullptr && cell_module->wire(conn.first) && conn.second.is_wire()) {
1245 RTLIL::Wire *cell_module_wire = cell_module->wire(conn.first);
1246 if (edge_wires[conn.second.as_wire()] && edge_wires[cell_module_wire]) {
1247 f << indent << mangle(cell) << access << "prev_" << mangle(cell_module_wire) << " = ";
1248 f << "prev_" << mangle(conn.second.as_wire()) << ";\n";
1249 }
1250 }
1251 }
1252 } else if (cell->input(conn.first)) {
1253 f << indent << mangle(cell) << access << mangle_wire_name(conn.first) << ".next = ";
1254 dump_sigspec_rhs(conn.second);
1255 f << ";\n";
1256 }
1257 auto assign_from_outputs = [&](bool cell_converged) {
1258 for (auto conn : cell->connections()) {
1259 if (cell->output(conn.first)) {
1260 if (conn.second.empty())
1261 continue; // ignore disconnected ports
1262 if (is_cxxrtl_sync_port(cell, conn.first))
1263 continue; // fully sync ports are handled in CELL_SYNC nodes
1264 f << indent;
1265 dump_sigspec_lhs(conn.second);
1266 f << " = " << mangle(cell) << access << mangle_wire_name(conn.first);
1267 // Similarly to how there is no purpose to buffering cell inputs, there is also no purpose to buffering
1268 // combinatorial cell outputs in case the cell converges within one cycle. (To convince yourself that
1269 // this optimization is valid, consider that, since the cell converged within one cycle, it would not
1270 // have any buffered wires if they were not output ports. Imagine inlining the cell's eval() function,
1271 // and consider the fate of the localized wires that used to be output ports.)
1272 //
1273 // Unlike cell inputs (which are never buffered), it is not possible to know apriori whether the cell
1274 // (which may be late bound) will converge immediately. Because of this, the choice between using .curr
1275 // (appropriate for buffered outputs) and .next (appropriate for unbuffered outputs) is made at runtime.
1276 if (cell_converged && is_cxxrtl_comb_port(cell, conn.first))
1277 f << ".next;\n";
1278 else
1279 f << ".curr;\n";
1280 }
1281 }
1282 };
1283 f << indent << "if (" << mangle(cell) << access << "eval()) {\n";
1284 inc_indent();
1285 assign_from_outputs(/*cell_converged=*/true);
1286 dec_indent();
1287 f << indent << "} else {\n";
1288 inc_indent();
1289 f << indent << "converged = false;\n";
1290 assign_from_outputs(/*cell_converged=*/false);
1291 dec_indent();
1292 f << indent << "}\n";
1293 }
1294 }
1295
1296 void dump_assign(const RTLIL::SigSig &sigsig)
1297 {
1298 f << indent;
1299 dump_sigspec_lhs(sigsig.first);
1300 f << " = ";
1301 dump_sigspec_rhs(sigsig.second);
1302 f << ";\n";
1303 }
1304
1305 void dump_case_rule(const RTLIL::CaseRule *rule)
1306 {
1307 for (auto action : rule->actions)
1308 dump_assign(action);
1309 for (auto switch_ : rule->switches)
1310 dump_switch_rule(switch_);
1311 }
1312
1313 void dump_switch_rule(const RTLIL::SwitchRule *rule)
1314 {
1315 // The switch attributes are printed before the switch condition is captured.
1316 dump_attrs(rule);
1317 std::string signal_temp = fresh_temporary();
1318 f << indent << "const value<" << rule->signal.size() << "> &" << signal_temp << " = ";
1319 dump_sigspec(rule->signal, /*is_lhs=*/false);
1320 f << ";\n";
1321
1322 bool first = true;
1323 for (auto case_ : rule->cases) {
1324 // The case attributes (for nested cases) are printed before the if/else if/else statement.
1325 dump_attrs(rule);
1326 f << indent;
1327 if (!first)
1328 f << "} else ";
1329 first = false;
1330 if (!case_->compare.empty()) {
1331 f << "if (";
1332 bool first = true;
1333 for (auto &compare : case_->compare) {
1334 if (!first)
1335 f << " || ";
1336 first = false;
1337 if (compare.is_fully_def()) {
1338 f << signal_temp << " == ";
1339 dump_sigspec(compare, /*is_lhs=*/false);
1340 } else if (compare.is_fully_const()) {
1341 RTLIL::Const compare_mask, compare_value;
1342 for (auto bit : compare.as_const()) {
1343 switch (bit) {
1344 case RTLIL::S0:
1345 case RTLIL::S1:
1346 compare_mask.bits.push_back(RTLIL::S1);
1347 compare_value.bits.push_back(bit);
1348 break;
1349
1350 case RTLIL::Sx:
1351 case RTLIL::Sz:
1352 case RTLIL::Sa:
1353 compare_mask.bits.push_back(RTLIL::S0);
1354 compare_value.bits.push_back(RTLIL::S0);
1355 break;
1356
1357 default:
1358 log_assert(false);
1359 }
1360 }
1361 f << "and_uu<" << compare.size() << ">(" << signal_temp << ", ";
1362 dump_const(compare_mask);
1363 f << ") == ";
1364 dump_const(compare_value);
1365 } else {
1366 log_assert(false);
1367 }
1368 }
1369 f << ") ";
1370 }
1371 f << "{\n";
1372 inc_indent();
1373 dump_case_rule(case_);
1374 dec_indent();
1375 }
1376 f << indent << "}\n";
1377 }
1378
1379 void dump_process(const RTLIL::Process *proc)
1380 {
1381 dump_attrs(proc);
1382 f << indent << "// process " << proc->name.str() << "\n";
1383 // The case attributes (for root case) are always empty.
1384 log_assert(proc->root_case.attributes.empty());
1385 dump_case_rule(&proc->root_case);
1386 for (auto sync : proc->syncs) {
1387 RTLIL::SigBit sync_bit;
1388 if (!sync->signal.empty()) {
1389 sync_bit = sync->signal[0];
1390 sync_bit = sigmaps[sync_bit.wire->module](sync_bit);
1391 }
1392
1393 pool<std::string> events;
1394 switch (sync->type) {
1395 case RTLIL::STp:
1396 log_assert(sync_bit.wire != nullptr);
1397 events.insert("posedge_" + mangle(sync_bit));
1398 break;
1399 case RTLIL::STn:
1400 log_assert(sync_bit.wire != nullptr);
1401 events.insert("negedge_" + mangle(sync_bit));
1402 break;
1403 case RTLIL::STe:
1404 log_assert(sync_bit.wire != nullptr);
1405 events.insert("posedge_" + mangle(sync_bit));
1406 events.insert("negedge_" + mangle(sync_bit));
1407 break;
1408
1409 case RTLIL::STa:
1410 events.insert("true");
1411 break;
1412
1413 case RTLIL::ST0:
1414 case RTLIL::ST1:
1415 case RTLIL::STg:
1416 case RTLIL::STi:
1417 log_assert(false);
1418 }
1419 if (!events.empty()) {
1420 f << indent << "if (";
1421 bool first = true;
1422 for (auto &event : events) {
1423 if (!first)
1424 f << " || ";
1425 first = false;
1426 f << event;
1427 }
1428 f << ") {\n";
1429 inc_indent();
1430 for (auto action : sync->actions)
1431 dump_assign(action);
1432 dec_indent();
1433 f << indent << "}\n";
1434 }
1435 }
1436 }
1437
1438 void dump_wire(const RTLIL::Wire *wire, bool is_local_context)
1439 {
1440 if (elided_wires.count(wire))
1441 return;
1442
1443 if (unbuffered_wires[wire]) {
1444 if (localized_wires[wire] == is_local_context) {
1445 dump_attrs(wire);
1446 f << indent << "value<" << wire->width << "> " << mangle(wire) << ";\n";
1447 }
1448 } else if (!is_local_context) {
1449 std::string width;
1450 if (wire->module->has_attribute(ID(cxxrtl_blackbox)) && wire->has_attribute(ID(cxxrtl_width))) {
1451 width = wire->get_string_attribute(ID(cxxrtl_width));
1452 } else {
1453 width = std::to_string(wire->width);
1454 }
1455
1456 dump_attrs(wire);
1457 f << indent << (is_input_wire(wire) ? "value" : "wire") << "<" << width << "> " << mangle(wire);
1458 if (wire->has_attribute(ID::init)) {
1459 f << " ";
1460 dump_const_init(wire->attributes.at(ID::init));
1461 }
1462 f << ";\n";
1463 if (edge_wires[wire]) {
1464 if (is_input_wire(wire)) {
1465 f << indent << "value<" << width << "> prev_" << mangle(wire);
1466 if (wire->has_attribute(ID::init)) {
1467 f << " ";
1468 dump_const_init(wire->attributes.at(ID::init));
1469 }
1470 f << ";\n";
1471 }
1472 for (auto edge_type : edge_types) {
1473 if (edge_type.first.wire == wire) {
1474 std::string prev, next;
1475 if (is_input_wire(wire)) {
1476 prev = "prev_" + mangle(edge_type.first.wire);
1477 next = mangle(edge_type.first.wire);
1478 } else {
1479 prev = mangle(edge_type.first.wire) + ".curr";
1480 next = mangle(edge_type.first.wire) + ".next";
1481 }
1482 prev += ".slice<" + std::to_string(edge_type.first.offset) + ">().val()";
1483 next += ".slice<" + std::to_string(edge_type.first.offset) + ">().val()";
1484 if (edge_type.second != RTLIL::STn) {
1485 f << indent << "bool posedge_" << mangle(edge_type.first) << "() const {\n";
1486 inc_indent();
1487 f << indent << "return !" << prev << " && " << next << ";\n";
1488 dec_indent();
1489 f << indent << "}\n";
1490 }
1491 if (edge_type.second != RTLIL::STp) {
1492 f << indent << "bool negedge_" << mangle(edge_type.first) << "() const {\n";
1493 inc_indent();
1494 f << indent << "return " << prev << " && !" << next << ";\n";
1495 dec_indent();
1496 f << indent << "}\n";
1497 }
1498 }
1499 }
1500 }
1501 }
1502 }
1503
1504 void dump_memory(RTLIL::Module *module, const RTLIL::Memory *memory)
1505 {
1506 vector<const RTLIL::Cell*> init_cells;
1507 for (auto cell : module->cells())
1508 if (cell->type == ID($meminit) && cell->getParam(ID::MEMID).decode_string() == memory->name.str())
1509 init_cells.push_back(cell);
1510
1511 std::sort(init_cells.begin(), init_cells.end(), [](const RTLIL::Cell *a, const RTLIL::Cell *b) {
1512 int a_addr = a->getPort(ID::ADDR).as_int(), b_addr = b->getPort(ID::ADDR).as_int();
1513 int a_prio = a->getParam(ID::PRIORITY).as_int(), b_prio = b->getParam(ID::PRIORITY).as_int();
1514 return a_prio > b_prio || (a_prio == b_prio && a_addr < b_addr);
1515 });
1516
1517 dump_attrs(memory);
1518 f << indent << "memory<" << memory->width << "> " << mangle(memory)
1519 << " { " << memory->size << "u";
1520 if (init_cells.empty()) {
1521 f << " };\n";
1522 } else {
1523 f << ",\n";
1524 inc_indent();
1525 for (auto cell : init_cells) {
1526 dump_attrs(cell);
1527 RTLIL::Const data = cell->getPort(ID::DATA).as_const();
1528 size_t width = cell->getParam(ID::WIDTH).as_int();
1529 size_t words = cell->getParam(ID::WORDS).as_int();
1530 f << indent << "memory<" << memory->width << ">::init<" << words << "> { "
1531 << stringf("%#x", cell->getPort(ID::ADDR).as_int()) << ", {";
1532 inc_indent();
1533 for (size_t n = 0; n < words; n++) {
1534 if (n % 4 == 0)
1535 f << "\n" << indent;
1536 else
1537 f << " ";
1538 dump_const(data, width, n * width, /*fixed_width=*/true);
1539 f << ",";
1540 }
1541 dec_indent();
1542 f << "\n" << indent << "}},\n";
1543 }
1544 dec_indent();
1545 f << indent << "};\n";
1546 }
1547 }
1548
1549 void dump_eval_method(RTLIL::Module *module)
1550 {
1551 inc_indent();
1552 f << indent << "bool converged = " << (eval_converges.at(module) ? "true" : "false") << ";\n";
1553 if (!module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1554 for (auto wire : module->wires()) {
1555 if (edge_wires[wire]) {
1556 for (auto edge_type : edge_types) {
1557 if (edge_type.first.wire == wire) {
1558 if (edge_type.second != RTLIL::STn) {
1559 f << indent << "bool posedge_" << mangle(edge_type.first) << " = ";
1560 f << "this->posedge_" << mangle(edge_type.first) << "();\n";
1561 }
1562 if (edge_type.second != RTLIL::STp) {
1563 f << indent << "bool negedge_" << mangle(edge_type.first) << " = ";
1564 f << "this->negedge_" << mangle(edge_type.first) << "();\n";
1565 }
1566 }
1567 }
1568 }
1569 }
1570 for (auto wire : module->wires())
1571 dump_wire(wire, /*is_local_context=*/true);
1572 for (auto node : schedule[module]) {
1573 switch (node.type) {
1574 case FlowGraph::Node::Type::CONNECT:
1575 dump_connect(node.connect);
1576 break;
1577 case FlowGraph::Node::Type::CELL_SYNC:
1578 dump_cell_sync(node.cell);
1579 break;
1580 case FlowGraph::Node::Type::CELL_EVAL:
1581 dump_cell_eval(node.cell);
1582 break;
1583 case FlowGraph::Node::Type::PROCESS:
1584 dump_process(node.process);
1585 break;
1586 }
1587 }
1588 }
1589 f << indent << "return converged;\n";
1590 dec_indent();
1591 }
1592
1593 void dump_commit_method(RTLIL::Module *module)
1594 {
1595 inc_indent();
1596 f << indent << "bool changed = false;\n";
1597 for (auto wire : module->wires()) {
1598 if (elided_wires.count(wire) || unbuffered_wires.count(wire))
1599 continue;
1600 if (is_input_wire(wire)) {
1601 if (edge_wires[wire])
1602 f << indent << "prev_" << mangle(wire) << " = " << mangle(wire) << ";\n";
1603 continue;
1604 }
1605 if (!module->get_bool_attribute(ID(cxxrtl_blackbox)) || wire->port_id != 0)
1606 f << indent << "changed |= " << mangle(wire) << ".commit();\n";
1607 }
1608 if (!module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1609 for (auto memory : module->memories) {
1610 if (!writable_memories[memory.second])
1611 continue;
1612 f << indent << "changed |= " << mangle(memory.second) << ".commit();\n";
1613 }
1614 for (auto cell : module->cells()) {
1615 if (is_internal_cell(cell->type))
1616 continue;
1617 const char *access = is_cxxrtl_blackbox_cell(cell) ? "->" : ".";
1618 f << indent << "changed |= " << mangle(cell) << access << "commit();\n";
1619 }
1620 }
1621 f << indent << "return changed;\n";
1622 dec_indent();
1623 }
1624
1625 void dump_debug_info_method(RTLIL::Module *module)
1626 {
1627 size_t count_public_wires = 0;
1628 size_t count_const_wires = 0;
1629 size_t count_alias_wires = 0;
1630 size_t count_member_wires = 0;
1631 size_t count_skipped_wires = 0;
1632 inc_indent();
1633 f << indent << "assert(path.empty() || path[path.size() - 1] == ' ');\n";
1634 for (auto wire : module->wires()) {
1635 if (wire->name[0] != '\\')
1636 continue;
1637 count_public_wires++;
1638 if (debug_const_wires.count(wire)) {
1639 // Wire tied to a constant
1640 f << indent << "static const value<" << wire->width << "> const_" << mangle(wire) << " = ";
1641 dump_const(debug_const_wires[wire]);
1642 f << ";\n";
1643 f << indent << "items.emplace(path + " << escape_cxx_string(get_hdl_name(wire));
1644 f << ", debug_item(const_" << mangle(wire) << "));\n";
1645 count_const_wires++;
1646 } else if (debug_alias_wires.count(wire)) {
1647 // Alias of a member wire
1648 f << indent << "items.emplace(path + " << escape_cxx_string(get_hdl_name(wire));
1649 f << ", debug_item(debug_alias(), " << mangle(debug_alias_wires[wire]) << "));\n";
1650 count_alias_wires++;
1651 } else if (!localized_wires.count(wire)) {
1652 // Member wire
1653 f << indent << "items.emplace(path + " << escape_cxx_string(get_hdl_name(wire));
1654 f << ", debug_item(" << mangle(wire) << "));\n";
1655 count_member_wires++;
1656 } else {
1657 count_skipped_wires++;
1658 }
1659 }
1660 for (auto &memory_it : module->memories) {
1661 if (memory_it.first[0] != '\\')
1662 continue;
1663 f << indent << "items.emplace(path + " << escape_cxx_string(get_hdl_name(memory_it.second));
1664 f << ", debug_item(" << mangle(memory_it.second) << "));\n";
1665 }
1666 for (auto cell : module->cells()) {
1667 if (is_internal_cell(cell->type))
1668 continue;
1669 const char *access = is_cxxrtl_blackbox_cell(cell) ? "->" : ".";
1670 f << indent << mangle(cell) << access << "debug_info(items, ";
1671 f << "path + " << escape_cxx_string(get_hdl_name(cell) + ' ') << ");\n";
1672 }
1673 dec_indent();
1674
1675 log_debug("Debug information statistics for module `%s':\n", log_id(module));
1676 log_debug(" Public wires: %zu, of which:\n", count_public_wires);
1677 log_debug(" Const wires: %zu\n", count_const_wires);
1678 log_debug(" Alias wires: %zu\n", count_alias_wires);
1679 log_debug(" Member wires: %zu\n", count_member_wires);
1680 log_debug(" Other wires: %zu (no debug information)\n", count_skipped_wires);
1681 }
1682
1683 void dump_metadata_map(const dict<RTLIL::IdString, RTLIL::Const> &metadata_map)
1684 {
1685 if (metadata_map.empty()) {
1686 f << "metadata_map()";
1687 return;
1688 }
1689 f << "metadata_map({\n";
1690 inc_indent();
1691 for (auto metadata_item : metadata_map) {
1692 if (!metadata_item.first.begins_with("\\"))
1693 continue;
1694 f << indent << "{ " << escape_cxx_string(metadata_item.first.str().substr(1)) << ", ";
1695 if (metadata_item.second.flags & RTLIL::CONST_FLAG_REAL) {
1696 f << std::showpoint << std::stod(metadata_item.second.decode_string()) << std::noshowpoint;
1697 } else if (metadata_item.second.flags & RTLIL::CONST_FLAG_STRING) {
1698 f << escape_cxx_string(metadata_item.second.decode_string());
1699 } else {
1700 f << metadata_item.second.as_int(/*is_signed=*/metadata_item.second.flags & RTLIL::CONST_FLAG_SIGNED);
1701 if (!(metadata_item.second.flags & RTLIL::CONST_FLAG_SIGNED))
1702 f << "u";
1703 }
1704 f << " },\n";
1705 }
1706 dec_indent();
1707 f << indent << "})";
1708 }
1709
1710 void dump_module_intf(RTLIL::Module *module)
1711 {
1712 dump_attrs(module);
1713 if (module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1714 if (module->has_attribute(ID(cxxrtl_template)))
1715 f << indent << "template" << template_params(module, /*is_decl=*/true) << "\n";
1716 f << indent << "struct " << mangle(module) << " : public module {\n";
1717 inc_indent();
1718 for (auto wire : module->wires()) {
1719 if (wire->port_id != 0)
1720 dump_wire(wire, /*is_local_context=*/false);
1721 }
1722 f << "\n";
1723 f << indent << "bool eval() override {\n";
1724 dump_eval_method(module);
1725 f << indent << "}\n";
1726 f << "\n";
1727 f << indent << "bool commit() override {\n";
1728 dump_commit_method(module);
1729 f << indent << "}\n";
1730 f << "\n";
1731 if (debug_info) {
1732 f << indent << "void debug_info(debug_items &items, std::string path = \"\") override {\n";
1733 dump_debug_info_method(module);
1734 f << indent << "}\n";
1735 f << "\n";
1736 }
1737 f << indent << "static std::unique_ptr<" << mangle(module);
1738 f << template_params(module, /*is_decl=*/false) << "> ";
1739 f << "create(std::string name, metadata_map parameters, metadata_map attributes);\n";
1740 dec_indent();
1741 f << indent << "}; // struct " << mangle(module) << "\n";
1742 f << "\n";
1743 if (blackbox_specializations.count(module)) {
1744 // If templated black boxes are used, the constructor of any module which includes the black box cell
1745 // (which calls the declared but not defined in the generated code `create` function) may only be used
1746 // if (a) the create function is defined in the same translation unit, or (b) the create function has
1747 // a forward-declared explicit specialization.
1748 //
1749 // Option (b) makes it possible to have the generated code and the black box implementation in different
1750 // translation units, which is convenient. Of course, its downside is that black boxes must predefine
1751 // a specialization for every combination of parameters the generated code may use; but since the main
1752 // purpose of templated black boxes is abstracting over datapath width, it is expected that there would
1753 // be very few such combinations anyway.
1754 for (auto specialization : blackbox_specializations[module]) {
1755 f << indent << "template<>\n";
1756 f << indent << "std::unique_ptr<" << mangle(module) << specialization << "> ";
1757 f << mangle(module) << specialization << "::";
1758 f << "create(std::string name, metadata_map parameters, metadata_map attributes);\n";
1759 f << "\n";
1760 }
1761 }
1762 } else {
1763 f << indent << "struct " << mangle(module) << " : public module {\n";
1764 inc_indent();
1765 for (auto wire : module->wires())
1766 dump_wire(wire, /*is_local_context=*/false);
1767 f << "\n";
1768 bool has_memories = false;
1769 for (auto memory : module->memories) {
1770 dump_memory(module, memory.second);
1771 has_memories = true;
1772 }
1773 if (has_memories)
1774 f << "\n";
1775 bool has_cells = false;
1776 for (auto cell : module->cells()) {
1777 if (is_internal_cell(cell->type))
1778 continue;
1779 dump_attrs(cell);
1780 RTLIL::Module *cell_module = module->design->module(cell->type);
1781 log_assert(cell_module != nullptr);
1782 if (cell_module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1783 f << indent << "std::unique_ptr<" << mangle(cell_module) << template_args(cell) << "> ";
1784 f << mangle(cell) << " = " << mangle(cell_module) << template_args(cell);
1785 f << "::create(" << escape_cxx_string(get_hdl_name(cell)) << ", ";
1786 dump_metadata_map(cell->parameters);
1787 f << ", ";
1788 dump_metadata_map(cell->attributes);
1789 f << ");\n";
1790 } else {
1791 f << indent << mangle(cell_module) << " " << mangle(cell) << ";\n";
1792 }
1793 has_cells = true;
1794 }
1795 if (has_cells)
1796 f << "\n";
1797 f << indent << "bool eval() override;\n";
1798 f << indent << "bool commit() override;\n";
1799 if (debug_info)
1800 f << indent << "void debug_info(debug_items &items, std::string path = \"\") override;\n";
1801 dec_indent();
1802 f << indent << "}; // struct " << mangle(module) << "\n";
1803 f << "\n";
1804 }
1805 }
1806
1807 void dump_module_impl(RTLIL::Module *module)
1808 {
1809 if (module->get_bool_attribute(ID(cxxrtl_blackbox)))
1810 return;
1811 f << indent << "bool " << mangle(module) << "::eval() {\n";
1812 dump_eval_method(module);
1813 f << indent << "}\n";
1814 f << "\n";
1815 f << indent << "bool " << mangle(module) << "::commit() {\n";
1816 dump_commit_method(module);
1817 f << indent << "}\n";
1818 f << "\n";
1819 if (debug_info) {
1820 f << indent << "void " << mangle(module) << "::debug_info(debug_items &items, std::string path) {\n";
1821 dump_debug_info_method(module);
1822 f << indent << "}\n";
1823 f << "\n";
1824 }
1825 }
1826
1827 void dump_design(RTLIL::Design *design)
1828 {
1829 RTLIL::Module *top_module = nullptr;
1830 std::vector<RTLIL::Module*> modules;
1831 TopoSort<RTLIL::Module*> topo_design;
1832 for (auto module : design->modules()) {
1833 if (!design->selected_module(module))
1834 continue;
1835 if (module->get_bool_attribute(ID(cxxrtl_blackbox)))
1836 modules.push_back(module); // cxxrtl blackboxes first
1837 if (module->get_blackbox_attribute() || module->get_bool_attribute(ID(cxxrtl_blackbox)))
1838 continue;
1839 if (module->get_bool_attribute(ID::top))
1840 top_module = module;
1841
1842 topo_design.node(module);
1843 for (auto cell : module->cells()) {
1844 if (is_internal_cell(cell->type) || is_cxxrtl_blackbox_cell(cell))
1845 continue;
1846 RTLIL::Module *cell_module = design->module(cell->type);
1847 log_assert(cell_module != nullptr);
1848 topo_design.edge(cell_module, module);
1849 }
1850 }
1851 log_assert(topo_design.sort());
1852 modules.insert(modules.end(), topo_design.sorted.begin(), topo_design.sorted.end());
1853
1854 if (split_intf) {
1855 // The only thing more depraved than include guards, is mangling filenames to turn them into include guards.
1856 std::string include_guard = design_ns + "_header";
1857 std::transform(include_guard.begin(), include_guard.end(), include_guard.begin(), ::toupper);
1858
1859 f << "#ifndef " << include_guard << "\n";
1860 f << "#define " << include_guard << "\n";
1861 f << "\n";
1862 if (top_module != nullptr && debug_info) {
1863 f << "#include <backends/cxxrtl/cxxrtl_capi.h>\n";
1864 f << "\n";
1865 f << "#ifdef __cplusplus\n";
1866 f << "extern \"C\" {\n";
1867 f << "#endif\n";
1868 f << "\n";
1869 f << "cxxrtl_toplevel " << design_ns << "_create();\n";
1870 f << "\n";
1871 f << "#ifdef __cplusplus\n";
1872 f << "}\n";
1873 f << "#endif\n";
1874 f << "\n";
1875 } else {
1876 f << "// The CXXRTL C API is not available because the design is built without debug information.\n";
1877 f << "\n";
1878 }
1879 f << "#ifdef __cplusplus\n";
1880 f << "\n";
1881 f << "#include <backends/cxxrtl/cxxrtl.h>\n";
1882 f << "\n";
1883 f << "using namespace cxxrtl;\n";
1884 f << "\n";
1885 f << "namespace " << design_ns << " {\n";
1886 f << "\n";
1887 for (auto module : modules)
1888 dump_module_intf(module);
1889 f << "} // namespace " << design_ns << "\n";
1890 f << "\n";
1891 f << "#endif // __cplusplus\n";
1892 f << "\n";
1893 f << "#endif\n";
1894 *intf_f << f.str(); f.str("");
1895 }
1896
1897 if (split_intf)
1898 f << "#include \"" << intf_filename << "\"\n";
1899 else
1900 f << "#include <backends/cxxrtl/cxxrtl.h>\n";
1901 f << "\n";
1902 f << "#if defined(CXXRTL_INCLUDE_CAPI_IMPL) || \\\n";
1903 f << " defined(CXXRTL_INCLUDE_VCD_CAPI_IMPL)\n";
1904 f << "#include <backends/cxxrtl/cxxrtl_capi.cc>\n";
1905 f << "#endif\n";
1906 f << "\n";
1907 f << "#if defined(CXXRTL_INCLUDE_VCD_CAPI_IMPL)\n";
1908 f << "#include <backends/cxxrtl/cxxrtl_vcd_capi.cc>\n";
1909 f << "#endif\n";
1910 f << "\n";
1911 f << "using namespace cxxrtl_yosys;\n";
1912 f << "\n";
1913 f << "namespace " << design_ns << " {\n";
1914 f << "\n";
1915 for (auto module : modules) {
1916 if (!split_intf)
1917 dump_module_intf(module);
1918 dump_module_impl(module);
1919 }
1920 f << "} // namespace " << design_ns << "\n";
1921 f << "\n";
1922 if (top_module != nullptr && debug_info) {
1923 f << "cxxrtl_toplevel " << design_ns << "_create() {\n";
1924 inc_indent();
1925 f << indent << "return new _cxxrtl_toplevel { ";
1926 f << "std::make_unique<" << design_ns << "::" << mangle(top_module) << ">()";
1927 f << " };\n";
1928 dec_indent();
1929 f << "}\n";
1930 }
1931
1932 *impl_f << f.str(); f.str("");
1933 }
1934
1935 // Edge-type sync rules require us to emit edge detectors, which require coordination between
1936 // eval and commit phases. To do this we need to collect them upfront.
1937 //
1938 // Note that the simulator commit phase operates at wire granularity but edge-type sync rules
1939 // operate at wire bit granularity; it is possible to have code similar to:
1940 // wire [3:0] clocks;
1941 // always @(posedge clocks[0]) ...
1942 // To handle this we track edge sensitivity both for wires and wire bits.
1943 void register_edge_signal(SigMap &sigmap, RTLIL::SigSpec signal, RTLIL::SyncType type)
1944 {
1945 signal = sigmap(signal);
1946 log_assert(signal.is_wire() && signal.is_bit());
1947 log_assert(type == RTLIL::STp || type == RTLIL::STn || type == RTLIL::STe);
1948
1949 RTLIL::SigBit sigbit = signal[0];
1950 if (!edge_types.count(sigbit))
1951 edge_types[sigbit] = type;
1952 else if (edge_types[sigbit] != type)
1953 edge_types[sigbit] = RTLIL::STe;
1954 edge_wires.insert(signal.as_wire());
1955 }
1956
1957 void analyze_design(RTLIL::Design *design)
1958 {
1959 bool has_feedback_arcs = false;
1960 bool has_buffered_comb_wires = false;
1961
1962 for (auto module : design->modules()) {
1963 if (!design->selected_module(module))
1964 continue;
1965
1966 SigMap &sigmap = sigmaps[module];
1967 sigmap.set(module);
1968
1969 if (module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1970 for (auto port : module->ports) {
1971 RTLIL::Wire *wire = module->wire(port);
1972 if (wire->has_attribute(ID(cxxrtl_edge))) {
1973 RTLIL::Const edge_attr = wire->attributes[ID(cxxrtl_edge)];
1974 if (!(edge_attr.flags & RTLIL::CONST_FLAG_STRING) || (int)edge_attr.decode_string().size() != GetSize(wire))
1975 log_cmd_error("Attribute `cxxrtl_edge' of port `%s.%s' is not a string with one character per bit.\n",
1976 log_id(module), log_signal(wire));
1977
1978 std::string edges = wire->get_string_attribute(ID(cxxrtl_edge));
1979 for (int i = 0; i < GetSize(wire); i++) {
1980 RTLIL::SigSpec wire_sig = wire;
1981 switch (edges[i]) {
1982 case '-': break;
1983 case 'p': register_edge_signal(sigmap, wire_sig[i], RTLIL::STp); break;
1984 case 'n': register_edge_signal(sigmap, wire_sig[i], RTLIL::STn); break;
1985 case 'a': register_edge_signal(sigmap, wire_sig[i], RTLIL::STe); break;
1986 default:
1987 log_cmd_error("Attribute `cxxrtl_edge' of port `%s.%s' contains specifiers "
1988 "other than '-', 'p', 'n', or 'a'.\n",
1989 log_id(module), log_signal(wire));
1990 }
1991 }
1992 }
1993 }
1994
1995 // Black boxes converge by default, since their implementations are quite unlikely to require
1996 // internal propagation of comb signals.
1997 eval_converges[module] = true;
1998 continue;
1999 }
2000
2001 FlowGraph flow;
2002
2003 for (auto conn : module->connections())
2004 flow.add_node(conn);
2005
2006 dict<const RTLIL::Cell*, FlowGraph::Node*> memrw_cell_nodes;
2007 dict<std::pair<RTLIL::SigBit, const RTLIL::Memory*>,
2008 pool<const RTLIL::Cell*>> memwr_per_domain;
2009 for (auto cell : module->cells()) {
2010 if (!cell->known())
2011 log_cmd_error("Unknown cell `%s'.\n", log_id(cell->type));
2012
2013 RTLIL::Module *cell_module = design->module(cell->type);
2014 if (cell_module &&
2015 cell_module->get_blackbox_attribute() &&
2016 !cell_module->get_bool_attribute(ID(cxxrtl_blackbox)))
2017 log_cmd_error("External blackbox cell `%s' is not marked as a CXXRTL blackbox.\n", log_id(cell->type));
2018
2019 if (cell_module &&
2020 cell_module->get_bool_attribute(ID(cxxrtl_blackbox)) &&
2021 cell_module->get_bool_attribute(ID(cxxrtl_template)))
2022 blackbox_specializations[cell_module].insert(template_args(cell));
2023
2024 FlowGraph::Node *node = flow.add_node(cell);
2025
2026 // Various DFF cells are treated like posedge/negedge processes, see above for details.
2027 if (cell->type.in(ID($dff), ID($dffe), ID($adff), ID($dffsr))) {
2028 if (cell->getPort(ID::CLK).is_wire())
2029 register_edge_signal(sigmap, cell->getPort(ID::CLK),
2030 cell->parameters[ID::CLK_POLARITY].as_bool() ? RTLIL::STp : RTLIL::STn);
2031 }
2032 // Similar for memory port cells.
2033 if (cell->type.in(ID($memrd), ID($memwr))) {
2034 if (cell->getParam(ID::CLK_ENABLE).as_bool()) {
2035 if (cell->getPort(ID::CLK).is_wire())
2036 register_edge_signal(sigmap, cell->getPort(ID::CLK),
2037 cell->parameters[ID::CLK_POLARITY].as_bool() ? RTLIL::STp : RTLIL::STn);
2038 }
2039 memrw_cell_nodes[cell] = node;
2040 }
2041 // Optimize access to read-only memories.
2042 if (cell->type == ID($memwr))
2043 writable_memories.insert(module->memories[cell->getParam(ID::MEMID).decode_string()]);
2044 // Collect groups of memory write ports in the same domain.
2045 if (cell->type == ID($memwr) && cell->getParam(ID::CLK_ENABLE).as_bool() && cell->getPort(ID::CLK).is_wire()) {
2046 RTLIL::SigBit clk_bit = sigmap(cell->getPort(ID::CLK))[0];
2047 const RTLIL::Memory *memory = module->memories[cell->getParam(ID::MEMID).decode_string()];
2048 memwr_per_domain[{clk_bit, memory}].insert(cell);
2049 }
2050 // Handling of packed memories is delegated to the `memory_unpack` pass, so we can rely on the presence
2051 // of RTLIL memory objects and $memrd/$memwr/$meminit cells.
2052 if (cell->type.in(ID($mem)))
2053 log_assert(false);
2054 }
2055 for (auto cell : module->cells()) {
2056 // Collect groups of memory write ports read by every transparent read port.
2057 if (cell->type == ID($memrd) && cell->getParam(ID::CLK_ENABLE).as_bool() && cell->getPort(ID::CLK).is_wire() &&
2058 cell->getParam(ID::TRANSPARENT).as_bool()) {
2059 RTLIL::SigBit clk_bit = sigmap(cell->getPort(ID::CLK))[0];
2060 const RTLIL::Memory *memory = module->memories[cell->getParam(ID::MEMID).decode_string()];
2061 for (auto memwr_cell : memwr_per_domain[{clk_bit, memory}]) {
2062 transparent_for[cell].insert(memwr_cell);
2063 // Our implementation of transparent $memrd cells reads \EN, \ADDR and \DATA from every $memwr cell
2064 // in the same domain, which isn't directly visible in the netlist. Add these uses explicitly.
2065 flow.add_uses(memrw_cell_nodes[cell], memwr_cell->getPort(ID::EN));
2066 flow.add_uses(memrw_cell_nodes[cell], memwr_cell->getPort(ID::ADDR));
2067 flow.add_uses(memrw_cell_nodes[cell], memwr_cell->getPort(ID::DATA));
2068 }
2069 }
2070 }
2071
2072 for (auto proc : module->processes) {
2073 flow.add_node(proc.second);
2074
2075 for (auto sync : proc.second->syncs)
2076 switch (sync->type) {
2077 // Edge-type sync rules require pre-registration.
2078 case RTLIL::STp:
2079 case RTLIL::STn:
2080 case RTLIL::STe:
2081 register_edge_signal(sigmap, sync->signal, sync->type);
2082 break;
2083
2084 // Level-type sync rules require no special handling.
2085 case RTLIL::ST0:
2086 case RTLIL::ST1:
2087 case RTLIL::STa:
2088 break;
2089
2090 case RTLIL::STg:
2091 log_cmd_error("Global clock is not supported.\n");
2092
2093 // Handling of init-type sync rules is delegated to the `proc_init` pass, so we can use the wire
2094 // attribute regardless of input.
2095 case RTLIL::STi:
2096 log_assert(false);
2097 }
2098 }
2099
2100 for (auto wire : module->wires()) {
2101 if (!flow.is_elidable(wire)) continue;
2102 if (wire->port_id != 0) continue;
2103 if (wire->get_bool_attribute(ID::keep)) continue;
2104 if (wire->name.begins_with("$") && !elide_internal) continue;
2105 if (wire->name.begins_with("\\") && !elide_public) continue;
2106 if (edge_wires[wire]) continue;
2107 log_assert(flow.wire_comb_defs[wire].size() == 1);
2108 elided_wires[wire] = **flow.wire_comb_defs[wire].begin();
2109 }
2110
2111 dict<FlowGraph::Node*, pool<const RTLIL::Wire*>, hash_ptr_ops> node_defs;
2112 for (auto wire_comb_def : flow.wire_comb_defs)
2113 for (auto node : wire_comb_def.second)
2114 node_defs[node].insert(wire_comb_def.first);
2115
2116 Scheduler<FlowGraph::Node> scheduler;
2117 dict<FlowGraph::Node*, Scheduler<FlowGraph::Node>::Vertex*, hash_ptr_ops> node_map;
2118 for (auto node : flow.nodes)
2119 node_map[node] = scheduler.add(node);
2120 for (auto node_def : node_defs) {
2121 auto vertex = node_map[node_def.first];
2122 for (auto wire : node_def.second)
2123 for (auto succ_node : flow.wire_uses[wire]) {
2124 auto succ_vertex = node_map[succ_node];
2125 vertex->succs.insert(succ_vertex);
2126 succ_vertex->preds.insert(vertex);
2127 }
2128 }
2129
2130 auto eval_order = scheduler.schedule();
2131 pool<FlowGraph::Node*, hash_ptr_ops> evaluated;
2132 pool<const RTLIL::Wire*> feedback_wires;
2133 for (auto vertex : eval_order) {
2134 auto node = vertex->data;
2135 schedule[module].push_back(*node);
2136 // Any wire that is an output of node vo and input of node vi where vo is scheduled later than vi
2137 // is a feedback wire. Feedback wires indicate apparent logic loops in the design, which may be
2138 // caused by a true logic loop, but usually are a benign result of dependency tracking that works
2139 // on wire, not bit, level. Nevertheless, feedback wires cannot be localized.
2140 evaluated.insert(node);
2141 for (auto wire : node_defs[node])
2142 for (auto succ_node : flow.wire_uses[wire])
2143 if (evaluated[succ_node]) {
2144 feedback_wires.insert(wire);
2145 // Feedback wires may never be elided because feedback requires state, but the point of elision
2146 // (and localization) is to eliminate state.
2147 elided_wires.erase(wire);
2148 }
2149 }
2150
2151 if (!feedback_wires.empty()) {
2152 has_feedback_arcs = true;
2153 log("Module `%s' contains feedback arcs through wires:\n", log_id(module));
2154 for (auto wire : feedback_wires)
2155 log(" %s\n", log_id(wire));
2156 }
2157
2158 for (auto wire : module->wires()) {
2159 if (feedback_wires[wire]) continue;
2160 if (wire->port_id != 0) continue;
2161 if (wire->get_bool_attribute(ID::keep)) continue;
2162 if (wire->name.begins_with("$") && !unbuffer_internal) continue;
2163 if (wire->name.begins_with("\\") && !unbuffer_public) continue;
2164 if (edge_wires[wire]) continue;
2165 if (flow.wire_sync_defs.count(wire) > 0) continue;
2166 unbuffered_wires.insert(wire);
2167 if (wire->name.begins_with("$") && !localize_internal) continue;
2168 if (wire->name.begins_with("\\") && !localize_public) continue;
2169 localized_wires.insert(wire);
2170 }
2171
2172 // For maximum performance, the state of the simulation (which is the same as the set of its double buffered
2173 // wires, since using a singly buffered wire for any kind of state introduces a race condition) should contain
2174 // no wires attached to combinatorial outputs. Feedback wires, by definition, make that impossible. However,
2175 // it is possible that a design with no feedback arcs would end up with doubly buffered wires in such cases
2176 // as a wire with multiple drivers where one of them is combinatorial and the other is synchronous. Such designs
2177 // also require more than one delta cycle to converge.
2178 pool<const RTLIL::Wire*> buffered_comb_wires;
2179 for (auto wire : module->wires()) {
2180 if (flow.wire_comb_defs[wire].size() > 0 && !unbuffered_wires[wire] && !feedback_wires[wire])
2181 buffered_comb_wires.insert(wire);
2182 }
2183 if (!buffered_comb_wires.empty()) {
2184 has_buffered_comb_wires = true;
2185 log("Module `%s' contains buffered combinatorial wires:\n", log_id(module));
2186 for (auto wire : buffered_comb_wires)
2187 log(" %s\n", log_id(wire));
2188 }
2189
2190 eval_converges[module] = feedback_wires.empty() && buffered_comb_wires.empty();
2191
2192 if (debug_info) {
2193 // Find wires that alias other wires or are tied to a constant; debug information can be enriched with these
2194 // at essentially zero additional cost.
2195 //
2196 // Note that the information collected here can't be used for optimizing the netlist: debug information queries
2197 // are pure and run on a design in a stable state, which allows assumptions that do not otherwise hold.
2198 for (auto wire : module->wires()) {
2199 if (wire->name[0] != '\\')
2200 continue;
2201 if (!unbuffered_wires[wire])
2202 continue;
2203 const RTLIL::Wire *wire_it = wire;
2204 while (1) {
2205 if (!(flow.wire_def_elidable.count(wire_it) && flow.wire_def_elidable[wire_it]))
2206 break; // not an alias: complex def
2207 log_assert(flow.wire_comb_defs[wire_it].size() == 1);
2208 FlowGraph::Node *node = *flow.wire_comb_defs[wire_it].begin();
2209 if (node->type != FlowGraph::Node::Type::CONNECT)
2210 break; // not an alias: def by cell
2211 RTLIL::SigSpec rhs_sig = node->connect.second;
2212 if (rhs_sig.is_wire()) {
2213 RTLIL::Wire *rhs_wire = rhs_sig.as_wire();
2214 if (unbuffered_wires[rhs_wire]) {
2215 wire_it = rhs_wire; // maybe an alias
2216 } else {
2217 debug_alias_wires[wire] = rhs_wire; // is an alias
2218 break;
2219 }
2220 } else if (rhs_sig.is_fully_const()) {
2221 debug_const_wires[wire] = rhs_sig.as_const(); // is a const
2222 break;
2223 } else {
2224 break; // not an alias: complex rhs
2225 }
2226 }
2227 }
2228 }
2229 }
2230 if (has_feedback_arcs || has_buffered_comb_wires) {
2231 // Although both non-feedback buffered combinatorial wires and apparent feedback wires may be eliminated
2232 // by optimizing the design, if after `proc; flatten` there are any feedback wires remaining, it is very
2233 // likely that these feedback wires are indicative of a true logic loop, so they get emphasized in the message.
2234 const char *why_pessimistic = nullptr;
2235 if (has_feedback_arcs)
2236 why_pessimistic = "feedback wires";
2237 else if (has_buffered_comb_wires)
2238 why_pessimistic = "buffered combinatorial wires";
2239 log_warning("Design contains %s, which require delta cycles during evaluation.\n", why_pessimistic);
2240 if (!run_flatten)
2241 log("Flattening may eliminate %s from the design.\n", why_pessimistic);
2242 if (!run_proc)
2243 log("Converting processes to netlists may eliminate %s from the design.\n", why_pessimistic);
2244 }
2245 }
2246
2247 void check_design(RTLIL::Design *design, bool &has_sync_init, bool &has_packed_mem)
2248 {
2249 has_sync_init = has_packed_mem = false;
2250
2251 for (auto module : design->modules()) {
2252 if (module->get_blackbox_attribute() && !module->has_attribute(ID(cxxrtl_blackbox)))
2253 continue;
2254
2255 if (!design->selected_whole_module(module))
2256 if (design->selected_module(module))
2257 log_cmd_error("Can't handle partially selected module `%s'!\n", id2cstr(module->name));
2258 if (!design->selected_module(module))
2259 continue;
2260
2261 for (auto proc : module->processes)
2262 for (auto sync : proc.second->syncs)
2263 if (sync->type == RTLIL::STi)
2264 has_sync_init = true;
2265
2266 for (auto cell : module->cells())
2267 if (cell->type == ID($mem))
2268 has_packed_mem = true;
2269 }
2270 }
2271
2272 void prepare_design(RTLIL::Design *design)
2273 {
2274 bool did_anything = false;
2275 bool has_sync_init, has_packed_mem;
2276 log_push();
2277 check_design(design, has_sync_init, has_packed_mem);
2278 if (run_flatten) {
2279 Pass::call(design, "flatten");
2280 did_anything = true;
2281 }
2282 if (run_proc) {
2283 Pass::call(design, "proc");
2284 did_anything = true;
2285 } else if (has_sync_init) {
2286 // We're only interested in proc_init, but it depends on proc_prune and proc_clean, so call those
2287 // in case they weren't already. (This allows `yosys foo.v -o foo.cc` to work.)
2288 Pass::call(design, "proc_prune");
2289 Pass::call(design, "proc_clean");
2290 Pass::call(design, "proc_init");
2291 did_anything = true;
2292 }
2293 if (has_packed_mem) {
2294 Pass::call(design, "memory_unpack");
2295 did_anything = true;
2296 }
2297 // Recheck the design if it was modified.
2298 if (has_sync_init || has_packed_mem)
2299 check_design(design, has_sync_init, has_packed_mem);
2300 log_assert(!(has_sync_init || has_packed_mem));
2301 log_pop();
2302 if (did_anything)
2303 log_spacer();
2304 analyze_design(design);
2305 }
2306 };
2307
2308 struct CxxrtlBackend : public Backend {
2309 static const int DEFAULT_OPT_LEVEL = 6;
2310 static const int OPT_LEVEL_DEBUG = 4;
2311 static const int DEFAULT_DEBUG_LEVEL = 1;
2312
2313 CxxrtlBackend() : Backend("cxxrtl", "convert design to C++ RTL simulation") { }
2314 void help() YS_OVERRIDE
2315 {
2316 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
2317 log("\n");
2318 log(" write_cxxrtl [options] [filename]\n");
2319 log("\n");
2320 log("Write C++ code that simulates the design. The generated code requires a driver\n");
2321 log("that instantiates the design, toggles its clock, and interacts with its ports.\n");
2322 log("\n");
2323 log("The following driver may be used as an example for a design with a single clock\n");
2324 log("driving rising edge triggered flip-flops:\n");
2325 log("\n");
2326 log(" #include \"top.cc\"\n");
2327 log("\n");
2328 log(" int main() {\n");
2329 log(" cxxrtl_design::p_top top;\n");
2330 log(" top.step();\n");
2331 log(" while (1) {\n");
2332 log(" /* user logic */\n");
2333 log(" top.p_clk = value<1> {0u};\n");
2334 log(" top.step();\n");
2335 log(" top.p_clk = value<1> {1u};\n");
2336 log(" top.step();\n");
2337 log(" }\n");
2338 log(" }\n");
2339 log("\n");
2340 log("Note that CXXRTL simulations, just like the hardware they are simulating, are\n");
2341 log("subject to race conditions. If, in the example above, the user logic would run\n");
2342 log("simultaneously with the rising edge of the clock, the design would malfunction.\n");
2343 log("\n");
2344 log("This backend supports replacing parts of the design with black boxes implemented\n");
2345 log("in C++. If a module marked as a CXXRTL black box, its implementation is ignored,\n");
2346 log("and the generated code consists only of an interface and a factory function.\n");
2347 log("The driver must implement the factory function that creates an implementation of\n");
2348 log("the black box, taking into account the parameters it is instantiated with.\n");
2349 log("\n");
2350 log("For example, the following Verilog code defines a CXXRTL black box interface for\n");
2351 log("a synchronous debug sink:\n");
2352 log("\n");
2353 log(" (* cxxrtl_blackbox *)\n");
2354 log(" module debug(...);\n");
2355 log(" (* cxxrtl_edge = \"p\" *) input clk;\n");
2356 log(" input en;\n");
2357 log(" input [7:0] i_data;\n");
2358 log(" (* cxxrtl_sync *) output [7:0] o_data;\n");
2359 log(" endmodule\n");
2360 log("\n");
2361 log("For this HDL interface, this backend will generate the following C++ interface:\n");
2362 log("\n");
2363 log(" struct bb_p_debug : public module {\n");
2364 log(" value<1> p_clk;\n");
2365 log(" bool posedge_p_clk() const { /* ... */ }\n");
2366 log(" value<1> p_en;\n");
2367 log(" value<8> p_i_data;\n");
2368 log(" wire<8> p_o_data;\n");
2369 log("\n");
2370 log(" bool eval() override;\n");
2371 log(" bool commit() override;\n");
2372 log("\n");
2373 log(" static std::unique_ptr<bb_p_debug>\n");
2374 log(" create(std::string name, metadata_map parameters, metadata_map attributes);\n");
2375 log(" };\n");
2376 log("\n");
2377 log("The `create' function must be implemented by the driver. For example, it could\n");
2378 log("always provide an implementation logging the values to standard error stream:\n");
2379 log("\n");
2380 log(" namespace cxxrtl_design {\n");
2381 log("\n");
2382 log(" struct stderr_debug : public bb_p_debug {\n");
2383 log(" bool eval() override {\n");
2384 log(" if (posedge_p_clk() && p_en)\n");
2385 log(" fprintf(stderr, \"debug: %%02x\\n\", p_i_data.data[0]);\n");
2386 log(" p_o_data.next = p_i_data;\n");
2387 log(" return bb_p_debug::eval();\n");
2388 log(" }\n");
2389 log(" };\n");
2390 log("\n");
2391 log(" std::unique_ptr<bb_p_debug>\n");
2392 log(" bb_p_debug::create(std::string name, cxxrtl::metadata_map parameters,\n");
2393 log(" cxxrtl::metadata_map attributes) {\n");
2394 log(" return std::make_unique<stderr_debug>();\n");
2395 log(" }\n");
2396 log("\n");
2397 log(" }\n");
2398 log("\n");
2399 log("For complex applications of black boxes, it is possible to parameterize their\n");
2400 log("port widths. For example, the following Verilog code defines a CXXRTL black box\n");
2401 log("interface for a configurable width debug sink:\n");
2402 log("\n");
2403 log(" (* cxxrtl_blackbox, cxxrtl_template = \"WIDTH\" *)\n");
2404 log(" module debug(...);\n");
2405 log(" parameter WIDTH = 8;\n");
2406 log(" (* cxxrtl_edge = \"p\" *) input clk;\n");
2407 log(" input en;\n");
2408 log(" (* cxxrtl_width = \"WIDTH\" *) input [WIDTH - 1:0] i_data;\n");
2409 log(" (* cxxrtl_width = \"WIDTH\" *) output [WIDTH - 1:0] o_data;\n");
2410 log(" endmodule\n");
2411 log("\n");
2412 log("For this parametric HDL interface, this backend will generate the following C++\n");
2413 log("interface (only the differences are shown):\n");
2414 log("\n");
2415 log(" template<size_t WIDTH>\n");
2416 log(" struct bb_p_debug : public module {\n");
2417 log(" // ...\n");
2418 log(" value<WIDTH> p_i_data;\n");
2419 log(" wire<WIDTH> p_o_data;\n");
2420 log(" // ...\n");
2421 log(" static std::unique_ptr<bb_p_debug<WIDTH>>\n");
2422 log(" create(std::string name, metadata_map parameters, metadata_map attributes);\n");
2423 log(" };\n");
2424 log("\n");
2425 log("The `create' function must be implemented by the driver, specialized for every\n");
2426 log("possible combination of template parameters. (Specialization is necessary to\n");
2427 log("enable separate compilation of generated code and black box implementations.)\n");
2428 log("\n");
2429 log(" template<size_t SIZE>\n");
2430 log(" struct stderr_debug : public bb_p_debug<SIZE> {\n");
2431 log(" // ...\n");
2432 log(" };\n");
2433 log("\n");
2434 log(" template<>\n");
2435 log(" std::unique_ptr<bb_p_debug<8>>\n");
2436 log(" bb_p_debug<8>::create(std::string name, cxxrtl::metadata_map parameters,\n");
2437 log(" cxxrtl::metadata_map attributes) {\n");
2438 log(" return std::make_unique<stderr_debug<8>>();\n");
2439 log(" }\n");
2440 log("\n");
2441 log("The following attributes are recognized by this backend:\n");
2442 log("\n");
2443 log(" cxxrtl_blackbox\n");
2444 log(" only valid on modules. if specified, the module contents are ignored,\n");
2445 log(" and the generated code includes only the module interface and a factory\n");
2446 log(" function, which will be called to instantiate the module.\n");
2447 log("\n");
2448 log(" cxxrtl_edge\n");
2449 log(" only valid on inputs of black boxes. must be one of \"p\", \"n\", \"a\".\n");
2450 log(" if specified on signal `clk`, the generated code includes edge detectors\n");
2451 log(" `posedge_p_clk()` (if \"p\"), `negedge_p_clk()` (if \"n\"), or both (if\n");
2452 log(" \"a\"), simplifying implementation of clocked black boxes.\n");
2453 log("\n");
2454 log(" cxxrtl_template\n");
2455 log(" only valid on black boxes. must contain a space separated sequence of\n");
2456 log(" identifiers that have a corresponding black box parameters. for each\n");
2457 log(" of them, the generated code includes a `size_t` template parameter.\n");
2458 log("\n");
2459 log(" cxxrtl_width\n");
2460 log(" only valid on ports of black boxes. must be a constant expression, which\n");
2461 log(" is directly inserted into generated code.\n");
2462 log("\n");
2463 log(" cxxrtl_comb, cxxrtl_sync\n");
2464 log(" only valid on outputs of black boxes. if specified, indicates that every\n");
2465 log(" bit of the output port is driven, correspondingly, by combinatorial or\n");
2466 log(" synchronous logic. this knowledge is used for scheduling optimizations.\n");
2467 log(" if neither is specified, the output will be pessimistically treated as\n");
2468 log(" driven by both combinatorial and synchronous logic.\n");
2469 log("\n");
2470 log("The following options are supported by this backend:\n");
2471 log("\n");
2472 log(" -header\n");
2473 log(" generate separate interface (.h) and implementation (.cc) files.\n");
2474 log(" if specified, the backend must be called with a filename, and filename\n");
2475 log(" of the interface is derived from filename of the implementation.\n");
2476 log(" otherwise, interface and implementation are generated together.\n");
2477 log("\n");
2478 log(" -namespace <ns-name>\n");
2479 log(" place the generated code into namespace <ns-name>. if not specified,\n");
2480 log(" \"cxxrtl_design\" is used.\n");
2481 log("\n");
2482 log(" -noflatten\n");
2483 log(" don't flatten the design. fully flattened designs can evaluate within\n");
2484 log(" one delta cycle if they have no combinatorial feedback.\n");
2485 log(" note that the debug interface and waveform dumps use full hierarchical\n");
2486 log(" names for all wires even in flattened designs.\n");
2487 log("\n");
2488 log(" -noproc\n");
2489 log(" don't convert processes to netlists. in most designs, converting\n");
2490 log(" processes significantly improves evaluation performance at the cost of\n");
2491 log(" slight increase in compilation time.\n");
2492 log("\n");
2493 log(" -O <level>\n");
2494 log(" set the optimization level. the default is -O%d. higher optimization\n", DEFAULT_OPT_LEVEL);
2495 log(" levels dramatically decrease compile and run time, and highest level\n");
2496 log(" possible for a design should be used.\n");
2497 log("\n");
2498 log(" -O0\n");
2499 log(" no optimization.\n");
2500 log("\n");
2501 log(" -O1\n");
2502 log(" localize internal wires if possible.\n");
2503 log("\n");
2504 log(" -O2\n");
2505 log(" like -O1, and unbuffer internal wires if possible.\n");
2506 log("\n");
2507 log(" -O3\n");
2508 log(" like -O2, and elide internal wires if possible.\n");
2509 log("\n");
2510 log(" -O4\n");
2511 log(" like -O3, and unbuffer public wires not marked (*keep*) if possible.\n");
2512 log("\n");
2513 log(" -O5\n");
2514 log(" like -O4, and localize public wires not marked (*keep*) if possible.\n");
2515 log("\n");
2516 log(" -O6\n");
2517 log(" like -O5, and elide public wires not marked (*keep*) if possible.\n");
2518 log("\n");
2519 log(" -Og\n");
2520 log(" highest optimization level that provides debug information for all\n");
2521 log(" public wires. currently, alias for -O%d.\n", OPT_LEVEL_DEBUG);
2522 log("\n");
2523 log(" -g <level>\n");
2524 log(" set the debug level. the default is -g%d. higher debug levels provide\n", DEFAULT_DEBUG_LEVEL);
2525 log(" more visibility and generate more code, but do not pessimize evaluation.\n");
2526 log("\n");
2527 log(" -g0\n");
2528 log(" no debug information.\n");
2529 log("\n");
2530 log(" -g1\n");
2531 log(" debug information for non-optimized public wires. this also makes it\n");
2532 log(" possible to use the C API.\n");
2533 log("\n");
2534 }
2535
2536 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
2537 {
2538 bool noflatten = false;
2539 bool noproc = false;
2540 int opt_level = DEFAULT_OPT_LEVEL;
2541 int debug_level = DEFAULT_DEBUG_LEVEL;
2542 CxxrtlWorker worker;
2543
2544 log_header(design, "Executing CXXRTL backend.\n");
2545
2546 size_t argidx;
2547 for (argidx = 1; argidx < args.size(); argidx++)
2548 {
2549 if (args[argidx] == "-noflatten") {
2550 noflatten = true;
2551 continue;
2552 }
2553 if (args[argidx] == "-noproc") {
2554 noproc = true;
2555 continue;
2556 }
2557 if (args[argidx] == "-Og") {
2558 opt_level = OPT_LEVEL_DEBUG;
2559 continue;
2560 }
2561 if (args[argidx] == "-O" && argidx+1 < args.size() && args[argidx+1] == "g") {
2562 argidx++;
2563 opt_level = OPT_LEVEL_DEBUG;
2564 continue;
2565 }
2566 if (args[argidx] == "-O" && argidx+1 < args.size()) {
2567 opt_level = std::stoi(args[++argidx]);
2568 continue;
2569 }
2570 if (args[argidx].substr(0, 2) == "-O" && args[argidx].size() == 3 && isdigit(args[argidx][2])) {
2571 opt_level = std::stoi(args[argidx].substr(2));
2572 continue;
2573 }
2574 if (args[argidx] == "-g" && argidx+1 < args.size()) {
2575 debug_level = std::stoi(args[++argidx]);
2576 continue;
2577 }
2578 if (args[argidx].substr(0, 2) == "-g" && args[argidx].size() == 3 && isdigit(args[argidx][2])) {
2579 debug_level = std::stoi(args[argidx].substr(2));
2580 continue;
2581 }
2582 if (args[argidx] == "-header") {
2583 worker.split_intf = true;
2584 continue;
2585 }
2586 if (args[argidx] == "-namespace" && argidx+1 < args.size()) {
2587 worker.design_ns = args[++argidx];
2588 continue;
2589 }
2590 break;
2591 }
2592 extra_args(f, filename, args, argidx);
2593
2594 worker.run_flatten = !noflatten;
2595 worker.run_proc = !noproc;
2596 switch (opt_level) {
2597 // the highest level here must match DEFAULT_OPT_LEVEL
2598 case 6:
2599 worker.elide_public = true;
2600 YS_FALLTHROUGH
2601 case 5:
2602 worker.localize_public = true;
2603 YS_FALLTHROUGH
2604 case 4:
2605 worker.unbuffer_public = true;
2606 YS_FALLTHROUGH
2607 case 3:
2608 worker.elide_internal = true;
2609 YS_FALLTHROUGH
2610 case 2:
2611 worker.localize_internal = true;
2612 YS_FALLTHROUGH
2613 case 1:
2614 worker.unbuffer_internal = true;
2615 YS_FALLTHROUGH
2616 case 0:
2617 break;
2618 default:
2619 log_cmd_error("Invalid optimization level %d.\n", opt_level);
2620 }
2621 switch (debug_level) {
2622 // the highest level here must match DEFAULT_DEBUG_LEVEL
2623 case 1:
2624 worker.debug_info = true;
2625 YS_FALLTHROUGH
2626 case 0:
2627 break;
2628 default:
2629 log_cmd_error("Invalid debug information level %d.\n", debug_level);
2630 }
2631
2632 std::ofstream intf_f;
2633 if (worker.split_intf) {
2634 if (filename == "<stdout>")
2635 log_cmd_error("Option -header must be used with a filename.\n");
2636
2637 worker.intf_filename = filename.substr(0, filename.rfind('.')) + ".h";
2638 intf_f.open(worker.intf_filename, std::ofstream::trunc);
2639 if (intf_f.fail())
2640 log_cmd_error("Can't open file `%s' for writing: %s\n",
2641 worker.intf_filename.c_str(), strerror(errno));
2642
2643 worker.intf_f = &intf_f;
2644 }
2645 worker.impl_f = f;
2646
2647 worker.prepare_design(design);
2648 worker.dump_design(design);
2649 }
2650 } CxxrtlBackend;
2651
2652 PRIVATE_NAMESPACE_END