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