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