2 * yosys -- Yosys Open SYnthesis Suite
4 * Copyright (C) 2019-2020 whitequark <whitequark@whitequark.org>
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.
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.
20 #include "kernel/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/utils.h"
24 #include "kernel/celltypes.h"
25 #include "kernel/mem.h"
26 #include "kernel/log.h"
29 PRIVATE_NAMESPACE_BEGIN
32 // Peter Eades; Xuemin Lin; W. F. Smyth, "A Fast Effective Heuristic For The Feedback Arc Set Problem"
33 // Information Processing Letters, Vol. 47, pp 319-323, 1993
34 // https://pdfs.semanticscholar.org/c7ed/d9acce96ca357876540e19664eb9d976637f.pdf
36 // A topological sort (on a cell/wire graph) is always possible in a fully flattened RTLIL design without
37 // processes or logic loops where every wire has a single driver. Logic loops are illegal in RTLIL and wires
38 // with multiple drivers can be split by the `splitnets` pass; however, interdependencies between processes
39 // or module instances can create strongly connected components without introducing evaluation nondeterminism.
40 // We wish to support designs with such benign SCCs (as well as designs with multiple drivers per wire), so
41 // we sort the graph in a way that minimizes feedback arcs. If there are no feedback arcs in the sorted graph,
42 // then a more efficient evaluation method is possible, since eval() will always immediately converge.
48 pool
<Vertex
*, hash_ptr_ops
> preds
, succs
;
50 Vertex() : data(NULL
), prev(this), next(this) {}
51 Vertex(T
*data
) : data(data
), prev(NULL
), next(NULL
) {}
55 log_assert(data
== NULL
);
57 log_assert(prev
== next
);
63 void link(Vertex
*list
)
65 log_assert(prev
== NULL
&& next
== NULL
);
68 list
->prev
->next
= this;
74 log_assert(prev
->next
== this && next
->prev
== this);
82 return succs
.size() - preds
.size();
86 std::vector
<Vertex
*> vertices
;
87 Vertex
*sources
= new Vertex
;
88 Vertex
*sinks
= new Vertex
;
89 dict
<int, Vertex
*> bins
;
97 for (auto vertex
: vertices
)
103 Vertex
*vertex
= new Vertex(data
);
104 vertices
.push_back(vertex
);
108 void relink(Vertex
*vertex
)
110 if (vertex
->succs
.empty())
112 else if (vertex
->preds
.empty())
113 vertex
->link(sources
);
115 int delta
= vertex
->delta();
116 if (!bins
.count(delta
))
117 bins
[delta
] = new Vertex
;
118 vertex
->link(bins
[delta
]);
122 Vertex
*remove(Vertex
*vertex
)
125 for (auto pred
: vertex
->preds
) {
128 log_assert(pred
->succs
[vertex
]);
130 pred
->succs
.erase(vertex
);
133 for (auto succ
: vertex
->succs
) {
136 log_assert(succ
->preds
[vertex
]);
138 succ
->preds
.erase(vertex
);
141 vertex
->preds
.clear();
142 vertex
->succs
.clear();
146 std::vector
<Vertex
*> schedule()
148 std::vector
<Vertex
*> s1
, s2r
;
149 for (auto vertex
: vertices
)
151 bool bins_empty
= false;
152 while (!(sinks
->empty() && sources
->empty() && bins_empty
)) {
153 while (!sinks
->empty())
154 s2r
.push_back(remove(sinks
->next
));
155 while (!sources
->empty())
156 s1
.push_back(remove(sources
->next
));
157 // Choosing u in this implementation isn't O(1), but the paper handwaves which data structure they suggest
158 // using to get O(1) relinking *and* find-max-key ("it is clear"... no it isn't), so this code uses a very
159 // naive implementation of find-max-key.
161 bins
.template sort
<std::greater
<int>>();
162 for (auto bin
: bins
) {
163 if (!bin
.second
->empty()) {
165 s1
.push_back(remove(bin
.second
->next
));
170 s1
.insert(s1
.end(), s2r
.rbegin(), s2r
.rend());
175 bool is_unary_cell(RTLIL::IdString type
)
178 ID($
not), ID($logic_not
), ID($reduce_and
), ID($reduce_or
), ID($reduce_xor
), ID($reduce_xnor
), ID($reduce_bool
),
182 bool is_binary_cell(RTLIL::IdString type
)
185 ID($
and), ID($
or), ID($
xor), ID($xnor
), ID($logic_and
), ID($logic_or
),
186 ID($shl
), ID($sshl
), ID($shr
), ID($sshr
), ID($shift
), ID($shiftx
),
187 ID($eq
), ID($ne
), ID($eqx
), ID($nex
), ID($gt
), ID($ge
), ID($lt
), ID($le
),
188 ID($add
), ID($sub
), ID($mul
), ID($div
), ID($mod
));
191 bool is_extending_cell(RTLIL::IdString type
)
194 ID($logic_not
), ID($logic_and
), ID($logic_or
),
195 ID($reduce_and
), ID($reduce_or
), ID($reduce_xor
), ID($reduce_xnor
), ID($reduce_bool
));
198 bool is_elidable_cell(RTLIL::IdString type
)
200 return is_unary_cell(type
) || is_binary_cell(type
) || type
.in(
201 ID($mux
), ID($concat
), ID($slice
), ID($pmux
));
204 bool is_ff_cell(RTLIL::IdString type
)
207 ID($dff
), ID($dffe
), ID($sdff
), ID($sdffe
), ID($sdffce
),
208 ID($adff
), ID($adffe
), ID($dffsr
), ID($dffsre
),
209 ID($dlatch
), ID($adlatch
), ID($dlatchsr
), ID($sr
));
212 bool is_internal_cell(RTLIL::IdString type
)
214 return type
[0] == '$' && !type
.begins_with("$paramod");
217 bool is_cxxrtl_blackbox_cell(const RTLIL::Cell
*cell
)
219 RTLIL::Module
*cell_module
= cell
->module
->design
->module(cell
->type
);
220 log_assert(cell_module
!= nullptr);
221 return cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
));
224 enum class CxxrtlPortType
{
225 UNKNOWN
= 0, // or mixed comb/sync
230 CxxrtlPortType
cxxrtl_port_type(const RTLIL::Cell
*cell
, RTLIL::IdString port
)
232 RTLIL::Module
*cell_module
= cell
->module
->design
->module(cell
->type
);
233 if (cell_module
== nullptr || !cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
234 return CxxrtlPortType::UNKNOWN
;
235 RTLIL::Wire
*cell_output_wire
= cell_module
->wire(port
);
236 log_assert(cell_output_wire
!= nullptr);
237 bool is_comb
= cell_output_wire
->get_bool_attribute(ID(cxxrtl_comb
));
238 bool is_sync
= cell_output_wire
->get_bool_attribute(ID(cxxrtl_sync
));
239 if (is_comb
&& is_sync
)
240 log_cmd_error("Port `%s.%s' is marked as both `cxxrtl_comb` and `cxxrtl_sync`.\n",
241 log_id(cell_module
), log_signal(cell_output_wire
));
243 return CxxrtlPortType::COMB
;
245 return CxxrtlPortType::SYNC
;
246 return CxxrtlPortType::UNKNOWN
;
249 bool is_cxxrtl_comb_port(const RTLIL::Cell
*cell
, RTLIL::IdString port
)
251 return cxxrtl_port_type(cell
, port
) == CxxrtlPortType::COMB
;
254 bool is_cxxrtl_sync_port(const RTLIL::Cell
*cell
, RTLIL::IdString port
)
256 return cxxrtl_port_type(cell
, port
) == CxxrtlPortType::SYNC
;
269 RTLIL::SigSig connect
= {};
270 const RTLIL::Cell
*cell
= NULL
;
271 const RTLIL::Process
*process
= NULL
;
274 std::vector
<Node
*> nodes
;
275 dict
<const RTLIL::Wire
*, pool
<Node
*, hash_ptr_ops
>> wire_comb_defs
, wire_sync_defs
, wire_uses
;
276 dict
<const RTLIL::Wire
*, bool> wire_def_elidable
, wire_use_elidable
;
277 dict
<RTLIL::SigBit
, bool> bit_has_state
;
281 for (auto node
: nodes
)
285 void add_defs(Node
*node
, const RTLIL::SigSpec
&sig
, bool is_ff
, bool elidable
)
287 for (auto chunk
: sig
.chunks())
290 // A sync def means that a wire holds design state because it is driven directly by
291 // a flip-flop output. Such a wire can never be unbuffered.
292 wire_sync_defs
[chunk
.wire
].insert(node
);
294 // A comb def means that a wire doesn't hold design state. It might still be connected,
295 // indirectly, to a flip-flop output.
296 wire_comb_defs
[chunk
.wire
].insert(node
);
299 for (auto bit
: sig
.bits())
300 bit_has_state
[bit
] |= is_ff
;
301 // Only comb defs of an entire wire in the right order can be elided.
302 if (!is_ff
&& sig
.is_wire())
303 wire_def_elidable
[sig
.as_wire()] = elidable
;
306 void add_uses(Node
*node
, const RTLIL::SigSpec
&sig
)
308 for (auto chunk
: sig
.chunks())
310 wire_uses
[chunk
.wire
].insert(node
);
311 // Only a single use of an entire wire in the right order can be elided.
312 // (But the use can include other chunks.)
313 if (!wire_use_elidable
.count(chunk
.wire
))
314 wire_use_elidable
[chunk
.wire
] = true;
316 wire_use_elidable
[chunk
.wire
] = false;
320 bool is_elidable(const RTLIL::Wire
*wire
) const
322 if (wire_def_elidable
.count(wire
) && wire_use_elidable
.count(wire
))
323 return wire_def_elidable
.at(wire
) && wire_use_elidable
.at(wire
);
328 void add_connect_defs_uses(Node
*node
, const RTLIL::SigSig
&conn
)
330 add_defs(node
, conn
.first
, /*is_ff=*/false, /*elidable=*/true);
331 add_uses(node
, conn
.second
);
334 Node
*add_node(const RTLIL::SigSig
&conn
)
336 Node
*node
= new Node
;
337 node
->type
= Node::Type::CONNECT
;
338 node
->connect
= conn
;
339 nodes
.push_back(node
);
340 add_connect_defs_uses(node
, conn
);
345 void add_cell_sync_defs(Node
*node
, const RTLIL::Cell
*cell
)
347 // To understand why this node type is necessary and why it produces comb defs, consider a cell
348 // with input \i and sync output \o, used in a design such that \i is connected to \o. This does
349 // not result in a feedback arc because the output is synchronous. However, a naive implementation
350 // of code generation for cells that assigns to inputs, evaluates cells, assigns from outputs
351 // would not be able to immediately converge...
354 // cell->p_i = i_tmp.curr;
356 // i_tmp.next = cell->p_o.curr;
358 // ... since the wire connecting the input and output ports would not be localizable. To solve
359 // this, the cell is split into two scheduling nodes; one exclusively for sync outputs, and
360 // another for inputs and all non-sync outputs. This way the generated code can be rearranged...
363 // i_tmp = cell->p_o.curr;
364 // cell->p_i = i_tmp;
367 // eliminating the unnecessary delta cycle. Conceptually, the CELL_SYNC node type is a series of
368 // connections of the form `connect \lhs \cell.\sync_output`; the right-hand side of these is not
369 // expressible as a wire in RTLIL. If it was expressible, then `\cell.\sync_output` would have
370 // a sync def, and this node would be an ordinary CONNECT node, with `\lhs` having a comb def.
371 // Because it isn't, a special node type is used, the right-hand side does not appear anywhere,
372 // and the left-hand side has a comb def.
373 for (auto conn
: cell
->connections())
374 if (cell
->output(conn
.first
))
375 if (is_cxxrtl_sync_port(cell
, conn
.first
)) {
376 // See note regarding elidability below.
377 add_defs(node
, conn
.second
, /*is_ff=*/false, /*elidable=*/false);
381 void add_cell_eval_defs_uses(Node
*node
, const RTLIL::Cell
*cell
)
383 for (auto conn
: cell
->connections()) {
384 if (cell
->output(conn
.first
)) {
385 if (is_elidable_cell(cell
->type
))
386 add_defs(node
, conn
.second
, /*is_ff=*/false, /*elidable=*/true);
387 else if (is_ff_cell(cell
->type
) || (cell
->type
== ID($memrd
) && cell
->getParam(ID::CLK_ENABLE
).as_bool()))
388 add_defs(node
, conn
.second
, /*is_ff=*/true, /*elidable=*/false);
389 else if (is_internal_cell(cell
->type
))
390 add_defs(node
, conn
.second
, /*is_ff=*/false, /*elidable=*/false);
391 else if (!is_cxxrtl_sync_port(cell
, conn
.first
)) {
392 // Although at first it looks like outputs of user-defined cells may always be elided, the reality is
393 // more complex. Fully sync outputs produce no defs and so don't participate in elision. Fully comb
394 // outputs are assigned in a different way depending on whether the cell's eval() immediately converged.
395 // Unknown/mixed outputs could be elided, but should be rare in practical designs and don't justify
396 // the infrastructure required to elide outputs of cells with many of them.
397 add_defs(node
, conn
.second
, /*is_ff=*/false, /*elidable=*/false);
400 if (cell
->input(conn
.first
))
401 add_uses(node
, conn
.second
);
405 Node
*add_node(const RTLIL::Cell
*cell
)
407 log_assert(cell
->known());
409 bool has_fully_sync_outputs
= false;
410 for (auto conn
: cell
->connections())
411 if (cell
->output(conn
.first
) && is_cxxrtl_sync_port(cell
, conn
.first
)) {
412 has_fully_sync_outputs
= true;
415 if (has_fully_sync_outputs
) {
416 Node
*node
= new Node
;
417 node
->type
= Node::Type::CELL_SYNC
;
419 nodes
.push_back(node
);
420 add_cell_sync_defs(node
, cell
);
423 Node
*node
= new Node
;
424 node
->type
= Node::Type::CELL_EVAL
;
426 nodes
.push_back(node
);
427 add_cell_eval_defs_uses(node
, cell
);
432 void add_case_defs_uses(Node
*node
, const RTLIL::CaseRule
*case_
)
434 for (auto &action
: case_
->actions
) {
435 add_defs(node
, action
.first
, /*is_ff=*/false, /*elidable=*/false);
436 add_uses(node
, action
.second
);
438 for (auto sub_switch
: case_
->switches
) {
439 add_uses(node
, sub_switch
->signal
);
440 for (auto sub_case
: sub_switch
->cases
) {
441 for (auto &compare
: sub_case
->compare
)
442 add_uses(node
, compare
);
443 add_case_defs_uses(node
, sub_case
);
448 void add_process_defs_uses(Node
*node
, const RTLIL::Process
*process
)
450 add_case_defs_uses(node
, &process
->root_case
);
451 for (auto sync
: process
->syncs
)
452 for (auto action
: sync
->actions
) {
453 if (sync
->type
== RTLIL::STp
|| sync
->type
== RTLIL::STn
|| sync
->type
== RTLIL::STe
)
454 add_defs(node
, action
.first
, /*is_ff=*/true, /*elidable=*/false);
456 add_defs(node
, action
.first
, /*is_ff=*/false, /*elidable=*/false);
457 add_uses(node
, action
.second
);
461 Node
*add_node(const RTLIL::Process
*process
)
463 Node
*node
= new Node
;
464 node
->type
= Node::Type::PROCESS
;
465 node
->process
= process
;
466 nodes
.push_back(node
);
467 add_process_defs_uses(node
, process
);
472 std::vector
<std::string
> split_by(const std::string
&str
, const std::string
&sep
)
474 std::vector
<std::string
> result
;
477 size_t curr
= str
.find_first_of(sep
, prev
);
478 if (curr
== std::string::npos
) {
479 std::string part
= str
.substr(prev
);
480 if (!part
.empty()) result
.push_back(part
);
483 std::string part
= str
.substr(prev
, curr
- prev
);
484 if (!part
.empty()) result
.push_back(part
);
491 std::string
escape_cxx_string(const std::string
&input
)
493 std::string output
= "\"";
494 for (auto c
: input
) {
497 output
.push_back('\\');
500 char l
= c
& 0xf, h
= (c
>> 4) & 0xf;
501 output
.append("\\x");
502 output
.push_back((h
< 10 ? '0' + h
: 'a' + h
- 10));
503 output
.push_back((l
< 10 ? '0' + l
: 'a' + l
- 10));
506 output
.push_back('"');
507 if (output
.find('\0') != std::string::npos
) {
508 output
.insert(0, "std::string {");
509 output
.append(stringf(", %zu}", input
.size()));
515 std::string
get_hdl_name(T
*object
)
517 if (object
->has_attribute(ID::hdlname
))
518 return object
->get_string_attribute(ID::hdlname
);
520 return object
->name
.str().substr(1);
523 struct CxxrtlWorker
{
524 bool split_intf
= false;
525 std::string intf_filename
;
526 std::string design_ns
= "cxxrtl_design";
527 std::ostream
*impl_f
= nullptr;
528 std::ostream
*intf_f
= nullptr;
530 bool run_hierarchy
= false;
531 bool run_flatten
= false;
532 bool run_proc
= false;
534 bool unbuffer_internal
= false;
535 bool unbuffer_public
= false;
536 bool localize_internal
= false;
537 bool localize_public
= false;
538 bool elide_internal
= false;
539 bool elide_public
= false;
541 bool debug_info
= false;
543 std::ostringstream f
;
547 dict
<const RTLIL::Module
*, SigMap
> sigmaps
;
548 pool
<const RTLIL::Wire
*> edge_wires
;
549 dict
<RTLIL::SigBit
, RTLIL::SyncType
> edge_types
;
550 pool
<const RTLIL::Memory
*> writable_memories
;
551 dict
<const RTLIL::Cell
*, pool
<const RTLIL::Cell
*>> transparent_for
;
552 dict
<const RTLIL::Wire
*, FlowGraph::Node
> elided_wires
;
553 dict
<const RTLIL::Module
*, std::vector
<FlowGraph::Node
>> schedule
;
554 pool
<const RTLIL::Wire
*> unbuffered_wires
;
555 pool
<const RTLIL::Wire
*> localized_wires
;
556 dict
<const RTLIL::Wire
*, const RTLIL::Wire
*> debug_alias_wires
;
557 dict
<const RTLIL::Wire
*, RTLIL::Const
> debug_const_wires
;
558 dict
<RTLIL::SigBit
, bool> bit_has_state
;
559 dict
<const RTLIL::Module
*, pool
<std::string
>> blackbox_specializations
;
560 dict
<const RTLIL::Module
*, bool> eval_converges
;
566 indent
.resize(indent
.size() - 1);
569 // RTLIL allows any characters in names other than whitespace. This presents an issue for generating C++ code
570 // because C++ identifiers may be only alphanumeric, cannot clash with C++ keywords, and cannot clash with cxxrtl
571 // identifiers. This issue can be solved with a name mangling scheme. We choose a name mangling scheme that results
572 // in readable identifiers, does not depend on an up-to-date list of C++ keywords, and is easy to apply. Its rules:
573 // 1. All generated identifiers start with `_`.
574 // 1a. Generated identifiers for public names (beginning with `\`) start with `p_`.
575 // 1b. Generated identifiers for internal names (beginning with `$`) start with `i_`.
576 // 2. An underscore is escaped with another underscore, i.e. `__`.
577 // 3. Any other non-alnum character is escaped with underscores around its lowercase hex code, e.g. `@` as `_40_`.
578 std::string
mangle_name(const RTLIL::IdString
&name
)
582 for (char c
: name
.str()) {
594 } else if (c
== '_') {
597 char l
= c
& 0xf, h
= (c
>> 4) & 0xf;
599 mangled
+= (h
< 10 ? '0' + h
: 'a' + h
- 10);
600 mangled
+= (l
< 10 ? '0' + l
: 'a' + l
- 10);
608 std::string
mangle_module_name(const RTLIL::IdString
&name
, bool is_blackbox
= false)
612 return "bb_" + mangle_name(name
);
613 return mangle_name(name
);
616 std::string
mangle_memory_name(const RTLIL::IdString
&name
)
618 // Class member namespace.
619 return "memory_" + mangle_name(name
);
622 std::string
mangle_cell_name(const RTLIL::IdString
&name
)
624 // Class member namespace.
625 return "cell_" + mangle_name(name
);
628 std::string
mangle_wire_name(const RTLIL::IdString
&name
)
630 // Class member namespace.
631 return mangle_name(name
);
634 std::string
mangle(const RTLIL::Module
*module
)
636 return mangle_module_name(module
->name
, /*is_blackbox=*/module
->get_bool_attribute(ID(cxxrtl_blackbox
)));
639 std::string
mangle(const RTLIL::Memory
*memory
)
641 return mangle_memory_name(memory
->name
);
644 std::string
mangle(const RTLIL::Cell
*cell
)
646 return mangle_cell_name(cell
->name
);
649 std::string
mangle(const RTLIL::Wire
*wire
)
651 return mangle_wire_name(wire
->name
);
654 std::string
mangle(RTLIL::SigBit sigbit
)
656 log_assert(sigbit
.wire
!= NULL
);
657 if (sigbit
.wire
->width
== 1)
658 return mangle(sigbit
.wire
);
659 return mangle(sigbit
.wire
) + "_" + std::to_string(sigbit
.offset
);
662 std::vector
<std::string
> template_param_names(const RTLIL::Module
*module
)
664 if (!module
->has_attribute(ID(cxxrtl_template
)))
667 if (module
->attributes
.at(ID(cxxrtl_template
)).flags
!= RTLIL::CONST_FLAG_STRING
)
668 log_cmd_error("Attribute `cxxrtl_template' of module `%s' is not a string.\n", log_id(module
));
670 std::vector
<std::string
> param_names
= split_by(module
->get_string_attribute(ID(cxxrtl_template
)), " \t");
671 for (const auto ¶m_name
: param_names
) {
672 // Various lowercase prefixes (p_, i_, cell_, ...) are used for member variables, so require
673 // parameters to start with an uppercase letter to avoid name conflicts. (This is the convention
674 // in both Verilog and C++, anyway.)
675 if (!isupper(param_name
[0]))
676 log_cmd_error("Attribute `cxxrtl_template' of module `%s' includes a parameter `%s', "
677 "which does not start with an uppercase letter.\n",
678 log_id(module
), param_name
.c_str());
683 std::string
template_params(const RTLIL::Module
*module
, bool is_decl
)
685 std::vector
<std::string
> param_names
= template_param_names(module
);
686 if (param_names
.empty())
689 std::string params
= "<";
691 for (const auto ¶m_name
: param_names
) {
697 params
+= param_name
;
703 std::string
template_args(const RTLIL::Cell
*cell
)
705 RTLIL::Module
*cell_module
= cell
->module
->design
->module(cell
->type
);
706 log_assert(cell_module
!= nullptr);
707 if (!cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
710 std::vector
<std::string
> param_names
= template_param_names(cell_module
);
711 if (param_names
.empty())
714 std::string params
= "<";
716 for (const auto ¶m_name
: param_names
) {
720 params
+= "/*" + param_name
+ "=*/";
721 RTLIL::IdString id_param_name
= '\\' + param_name
;
722 if (!cell
->hasParam(id_param_name
))
723 log_cmd_error("Cell `%s.%s' does not have a parameter `%s', which is required by the templated module `%s'.\n",
724 log_id(cell
->module
), log_id(cell
), param_name
.c_str(), log_id(cell_module
));
725 RTLIL::Const param_value
= cell
->getParam(id_param_name
);
726 if (((param_value
.flags
& ~RTLIL::CONST_FLAG_SIGNED
) != 0) || param_value
.as_int() < 0)
727 log_cmd_error("Parameter `%s' of cell `%s.%s', which is required by the templated module `%s', "
728 "is not a positive integer.\n",
729 param_name
.c_str(), log_id(cell
->module
), log_id(cell
), log_id(cell_module
));
730 params
+= std::to_string(cell
->getParam(id_param_name
).as_int());
736 std::string
fresh_temporary()
738 return stringf("tmp_%d", temporary
++);
741 void dump_attrs(const RTLIL::AttrObject
*object
)
743 for (auto attr
: object
->attributes
) {
744 f
<< indent
<< "// " << attr
.first
.str() << ": ";
745 if (attr
.second
.flags
& RTLIL::CONST_FLAG_STRING
) {
746 f
<< attr
.second
.decode_string();
748 f
<< attr
.second
.as_int(/*is_signed=*/attr
.second
.flags
& RTLIL::CONST_FLAG_SIGNED
);
754 void dump_const_init(const RTLIL::Const
&data
, int width
, int offset
= 0, bool fixed_width
= false)
756 const int CHUNK_SIZE
= 32;
759 int chunk_width
= min(width
, CHUNK_SIZE
);
760 uint32_t chunk
= data
.extract(offset
, chunk_width
).as_int();
762 f
<< stringf("0x%.*xu", (3 + chunk_width
) / 4, chunk
);
764 f
<< stringf("%#xu", chunk
);
765 if (width
> CHUNK_SIZE
)
767 offset
+= CHUNK_SIZE
;
773 void dump_const_init(const RTLIL::Const
&data
)
775 dump_const_init(data
, data
.size());
778 void dump_const(const RTLIL::Const
&data
, int width
, int offset
= 0, bool fixed_width
= false)
780 f
<< "value<" << width
<< ">";
781 dump_const_init(data
, width
, offset
, fixed_width
);
784 void dump_const(const RTLIL::Const
&data
)
786 dump_const(data
, data
.size());
789 bool dump_sigchunk(const RTLIL::SigChunk
&chunk
, bool is_lhs
)
791 if (chunk
.wire
== NULL
) {
792 dump_const(chunk
.data
, chunk
.width
, chunk
.offset
);
795 if (elided_wires
.count(chunk
.wire
)) {
797 const FlowGraph::Node
&node
= elided_wires
[chunk
.wire
];
799 case FlowGraph::Node::Type::CONNECT
:
800 dump_connect_elided(node
.connect
);
802 case FlowGraph::Node::Type::CELL_EVAL
:
803 log_assert(is_elidable_cell(node
.cell
->type
));
804 dump_cell_elided(node
.cell
);
809 } else if (unbuffered_wires
[chunk
.wire
]) {
810 f
<< mangle(chunk
.wire
);
812 f
<< mangle(chunk
.wire
) << (is_lhs
? ".next" : ".curr");
814 if (chunk
.width
== chunk
.wire
->width
&& chunk
.offset
== 0)
816 else if (chunk
.width
== 1)
817 f
<< ".slice<" << chunk
.offset
<< ">()";
819 f
<< ".slice<" << chunk
.offset
+chunk
.width
-1 << "," << chunk
.offset
<< ">()";
824 bool dump_sigspec(const RTLIL::SigSpec
&sig
, bool is_lhs
)
829 } else if (sig
.is_chunk()) {
830 return dump_sigchunk(sig
.as_chunk(), is_lhs
);
832 dump_sigchunk(*sig
.chunks().rbegin(), is_lhs
);
833 for (auto it
= sig
.chunks().rbegin() + 1; it
!= sig
.chunks().rend(); ++it
) {
835 dump_sigchunk(*it
, is_lhs
);
842 void dump_sigspec_lhs(const RTLIL::SigSpec
&sig
)
844 dump_sigspec(sig
, /*is_lhs=*/true);
847 void dump_sigspec_rhs(const RTLIL::SigSpec
&sig
)
849 // In the contexts where we want template argument deduction to occur for `template<size_t Bits> ... value<Bits>`,
850 // it is necessary to have the argument to already be a `value<N>`, since template argument deduction and implicit
851 // type conversion are mutually exclusive. In these contexts, we use dump_sigspec_rhs() to emit an explicit
852 // type conversion, but only if the expression needs it.
853 bool is_complex
= dump_sigspec(sig
, /*is_lhs=*/false);
858 void collect_sigspec_rhs(const RTLIL::SigSpec
&sig
, std::vector
<RTLIL::IdString
> &cells
)
860 for (auto chunk
: sig
.chunks()) {
861 if (!chunk
.wire
|| !elided_wires
.count(chunk
.wire
))
864 const FlowGraph::Node
&node
= elided_wires
[chunk
.wire
];
866 case FlowGraph::Node::Type::CONNECT
:
867 collect_connect(node
.connect
, cells
);
869 case FlowGraph::Node::Type::CELL_EVAL
:
870 collect_cell_eval(node
.cell
, cells
);
878 void dump_connect_elided(const RTLIL::SigSig
&conn
)
880 dump_sigspec_rhs(conn
.second
);
883 bool is_connect_elided(const RTLIL::SigSig
&conn
)
885 return conn
.first
.is_wire() && elided_wires
.count(conn
.first
.as_wire());
888 void collect_connect(const RTLIL::SigSig
&conn
, std::vector
<RTLIL::IdString
> &cells
)
890 if (!is_connect_elided(conn
))
893 collect_sigspec_rhs(conn
.second
, cells
);
896 void dump_connect(const RTLIL::SigSig
&conn
)
898 if (is_connect_elided(conn
))
901 f
<< indent
<< "// connection\n";
903 dump_sigspec_lhs(conn
.first
);
905 dump_connect_elided(conn
);
909 void dump_cell_sync(const RTLIL::Cell
*cell
)
911 const char *access
= is_cxxrtl_blackbox_cell(cell
) ? "->" : ".";
912 f
<< indent
<< "// cell " << cell
->name
.str() << " syncs\n";
913 for (auto conn
: cell
->connections())
914 if (cell
->output(conn
.first
))
915 if (is_cxxrtl_sync_port(cell
, conn
.first
)) {
917 dump_sigspec_lhs(conn
.second
);
918 f
<< " = " << mangle(cell
) << access
<< mangle_wire_name(conn
.first
) << ".curr;\n";
922 void dump_cell_elided(const RTLIL::Cell
*cell
)
925 if (is_unary_cell(cell
->type
)) {
926 f
<< cell
->type
.substr(1);
927 if (is_extending_cell(cell
->type
))
928 f
<< '_' << (cell
->getParam(ID::A_SIGNED
).as_bool() ? 's' : 'u');
929 f
<< "<" << cell
->getParam(ID::Y_WIDTH
).as_int() << ">(";
930 dump_sigspec_rhs(cell
->getPort(ID::A
));
933 } else if (is_binary_cell(cell
->type
)) {
934 f
<< cell
->type
.substr(1);
935 if (is_extending_cell(cell
->type
))
936 f
<< '_' << (cell
->getParam(ID::A_SIGNED
).as_bool() ? 's' : 'u') <<
937 (cell
->getParam(ID::B_SIGNED
).as_bool() ? 's' : 'u');
938 f
<< "<" << cell
->getParam(ID::Y_WIDTH
).as_int() << ">(";
939 dump_sigspec_rhs(cell
->getPort(ID::A
));
941 dump_sigspec_rhs(cell
->getPort(ID::B
));
944 } else if (cell
->type
== ID($mux
)) {
946 dump_sigspec_rhs(cell
->getPort(ID::S
));
948 dump_sigspec_rhs(cell
->getPort(ID::B
));
950 dump_sigspec_rhs(cell
->getPort(ID::A
));
952 // Parallel (one-hot) muxes
953 } else if (cell
->type
== ID($pmux
)) {
954 int width
= cell
->getParam(ID::WIDTH
).as_int();
955 int s_width
= cell
->getParam(ID::S_WIDTH
).as_int();
956 for (int part
= 0; part
< s_width
; part
++) {
958 dump_sigspec_rhs(cell
->getPort(ID::S
).extract(part
));
960 dump_sigspec_rhs(cell
->getPort(ID::B
).extract(part
* width
, width
));
963 dump_sigspec_rhs(cell
->getPort(ID::A
));
964 for (int part
= 0; part
< s_width
; part
++) {
968 } else if (cell
->type
== ID($concat
)) {
969 dump_sigspec_rhs(cell
->getPort(ID::B
));
971 dump_sigspec_rhs(cell
->getPort(ID::A
));
974 } else if (cell
->type
== ID($slice
)) {
975 dump_sigspec_rhs(cell
->getPort(ID::A
));
977 f
<< cell
->getParam(ID::OFFSET
).as_int() + cell
->getParam(ID::Y_WIDTH
).as_int() - 1;
979 f
<< cell
->getParam(ID::OFFSET
).as_int();
986 bool is_cell_elided(const RTLIL::Cell
*cell
)
988 return is_elidable_cell(cell
->type
) && cell
->hasPort(ID::Y
) && cell
->getPort(ID::Y
).is_wire() &&
989 elided_wires
.count(cell
->getPort(ID::Y
).as_wire());
992 void collect_cell_eval(const RTLIL::Cell
*cell
, std::vector
<RTLIL::IdString
> &cells
)
994 if (!is_cell_elided(cell
))
997 cells
.push_back(cell
->name
);
998 for (auto port
: cell
->connections())
999 if (port
.first
!= ID::Y
)
1000 collect_sigspec_rhs(port
.second
, cells
);
1003 void dump_cell_eval(const RTLIL::Cell
*cell
)
1005 if (is_cell_elided(cell
))
1007 if (cell
->type
== ID($meminit
))
1008 return; // Handled elsewhere.
1010 std::vector
<RTLIL::IdString
> elided_cells
;
1011 if (is_elidable_cell(cell
->type
)) {
1012 for (auto port
: cell
->connections())
1013 if (port
.first
!= ID::Y
)
1014 collect_sigspec_rhs(port
.second
, elided_cells
);
1016 if (elided_cells
.empty()) {
1018 f
<< indent
<< "// cell " << cell
->name
.str() << "\n";
1020 f
<< indent
<< "// cells";
1021 for (auto elided_cell
: elided_cells
)
1022 f
<< " " << elided_cell
.str();
1027 if (is_elidable_cell(cell
->type
)) {
1029 dump_sigspec_lhs(cell
->getPort(ID::Y
));
1031 dump_cell_elided(cell
);
1034 } else if (is_ff_cell(cell
->type
)) {
1035 if (cell
->hasPort(ID::CLK
) && cell
->getPort(ID::CLK
).is_wire()) {
1036 // Edge-sensitive logic
1037 RTLIL::SigBit clk_bit
= cell
->getPort(ID::CLK
)[0];
1038 clk_bit
= sigmaps
[clk_bit
.wire
->module
](clk_bit
);
1039 f
<< indent
<< "if (" << (cell
->getParam(ID::CLK_POLARITY
).as_bool() ? "posedge_" : "negedge_")
1040 << mangle(clk_bit
) << ") {\n";
1042 if (cell
->hasPort(ID::EN
)) {
1043 f
<< indent
<< "if (";
1044 dump_sigspec_rhs(cell
->getPort(ID::EN
));
1045 f
<< " == value<1> {" << cell
->getParam(ID::EN_POLARITY
).as_bool() << "u}) {\n";
1049 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1051 dump_sigspec_rhs(cell
->getPort(ID::D
));
1053 if (cell
->hasPort(ID::EN
) && cell
->type
!= ID($sdffce
)) {
1055 f
<< indent
<< "}\n";
1057 if (cell
->hasPort(ID::SRST
)) {
1058 f
<< indent
<< "if (";
1059 dump_sigspec_rhs(cell
->getPort(ID::SRST
));
1060 f
<< " == value<1> {" << cell
->getParam(ID::SRST_POLARITY
).as_bool() << "u}) {\n";
1063 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1065 dump_const(cell
->getParam(ID::SRST_VALUE
));
1068 f
<< indent
<< "}\n";
1070 if (cell
->hasPort(ID::EN
) && cell
->type
== ID($sdffce
)) {
1072 f
<< indent
<< "}\n";
1075 f
<< indent
<< "}\n";
1076 } else if (cell
->hasPort(ID::EN
)) {
1077 // Level-sensitive logic
1078 f
<< indent
<< "if (";
1079 dump_sigspec_rhs(cell
->getPort(ID::EN
));
1080 f
<< " == value<1> {" << cell
->getParam(ID::EN_POLARITY
).as_bool() << "u}) {\n";
1083 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1085 dump_sigspec_rhs(cell
->getPort(ID::D
));
1088 f
<< indent
<< "}\n";
1090 if (cell
->hasPort(ID::ARST
)) {
1091 // Asynchronous reset (entire coarse cell at once)
1092 f
<< indent
<< "if (";
1093 dump_sigspec_rhs(cell
->getPort(ID::ARST
));
1094 f
<< " == value<1> {" << cell
->getParam(ID::ARST_POLARITY
).as_bool() << "u}) {\n";
1097 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1099 dump_const(cell
->getParam(ID::ARST_VALUE
));
1102 f
<< indent
<< "}\n";
1104 if (cell
->hasPort(ID::SET
)) {
1105 // Asynchronous set (for individual bits)
1107 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1109 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1111 dump_const(RTLIL::Const(RTLIL::S1
, cell
->getParam(ID::WIDTH
).as_int()));
1113 dump_sigspec_rhs(cell
->getPort(ID::SET
));
1114 f
<< (cell
->getParam(ID::SET_POLARITY
).as_bool() ? "" : ".bit_not()") << ");\n";
1116 if (cell
->hasPort(ID::CLR
)) {
1117 // Asynchronous clear (for individual bits; priority over set)
1119 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1121 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1123 dump_const(RTLIL::Const(RTLIL::S0
, cell
->getParam(ID::WIDTH
).as_int()));
1125 dump_sigspec_rhs(cell
->getPort(ID::CLR
));
1126 f
<< (cell
->getParam(ID::CLR_POLARITY
).as_bool() ? "" : ".bit_not()") << ");\n";
1129 } else if (cell
->type
.in(ID($memrd
), ID($memwr
))) {
1130 if (cell
->getParam(ID::CLK_ENABLE
).as_bool()) {
1131 RTLIL::SigBit clk_bit
= cell
->getPort(ID::CLK
)[0];
1132 clk_bit
= sigmaps
[clk_bit
.wire
->module
](clk_bit
);
1133 f
<< indent
<< "if (" << (cell
->getParam(ID::CLK_POLARITY
).as_bool() ? "posedge_" : "negedge_")
1134 << mangle(clk_bit
) << ") {\n";
1137 RTLIL::Memory
*memory
= cell
->module
->memories
[cell
->getParam(ID::MEMID
).decode_string()];
1138 std::string valid_index_temp
= fresh_temporary();
1139 f
<< indent
<< "auto " << valid_index_temp
<< " = memory_index(";
1140 dump_sigspec_rhs(cell
->getPort(ID::ADDR
));
1141 f
<< ", " << memory
->start_offset
<< ", " << memory
->size
<< ");\n";
1142 if (cell
->type
== ID($memrd
)) {
1143 bool has_enable
= cell
->getParam(ID::CLK_ENABLE
).as_bool() && !cell
->getPort(ID::EN
).is_fully_ones();
1145 f
<< indent
<< "if (";
1146 dump_sigspec_rhs(cell
->getPort(ID::EN
));
1150 // The generated code has two bounds checks; one in an assertion, and another that guards the read.
1151 // This is done so that the code does not invoke undefined behavior under any conditions, but nevertheless
1152 // loudly crashes if an illegal condition is encountered. The assert may be turned off with -DNDEBUG not
1153 // just for release builds, but also to make sure the simulator (which is presumably embedded in some
1154 // larger program) will never crash the code that calls into it.
1156 // If assertions are disabled, out of bounds reads are defined to return zero.
1157 f
<< indent
<< "assert(" << valid_index_temp
<< ".valid && \"out of bounds read\");\n";
1158 f
<< indent
<< "if(" << valid_index_temp
<< ".valid) {\n";
1160 if (writable_memories
[memory
]) {
1161 std::string lhs_temp
= fresh_temporary();
1162 f
<< indent
<< "value<" << memory
->width
<< "> " << lhs_temp
<< " = "
1163 << mangle(memory
) << "[" << valid_index_temp
<< ".index];\n";
1164 std::vector
<const RTLIL::Cell
*> memwr_cells(transparent_for
[cell
].begin(), transparent_for
[cell
].end());
1165 if (!memwr_cells
.empty()) {
1166 std::string addr_temp
= fresh_temporary();
1167 f
<< indent
<< "const value<" << cell
->getPort(ID::ADDR
).size() << "> &" << addr_temp
<< " = ";
1168 dump_sigspec_rhs(cell
->getPort(ID::ADDR
));
1170 std::sort(memwr_cells
.begin(), memwr_cells
.end(),
1171 [](const RTLIL::Cell
*a
, const RTLIL::Cell
*b
) {
1172 return a
->getParam(ID::PRIORITY
).as_int() < b
->getParam(ID::PRIORITY
).as_int();
1174 for (auto memwr_cell
: memwr_cells
) {
1175 f
<< indent
<< "if (" << addr_temp
<< " == ";
1176 dump_sigspec_rhs(memwr_cell
->getPort(ID::ADDR
));
1179 f
<< indent
<< lhs_temp
<< " = " << lhs_temp
;
1181 dump_sigspec_rhs(memwr_cell
->getPort(ID::DATA
));
1183 dump_sigspec_rhs(memwr_cell
->getPort(ID::EN
));
1186 f
<< indent
<< "}\n";
1190 dump_sigspec_lhs(cell
->getPort(ID::DATA
));
1191 f
<< " = " << lhs_temp
<< ";\n";
1194 dump_sigspec_lhs(cell
->getPort(ID::DATA
));
1195 f
<< " = " << mangle(memory
) << "[" << valid_index_temp
<< ".index];\n";
1198 f
<< indent
<< "} else {\n";
1201 dump_sigspec_lhs(cell
->getPort(ID::DATA
));
1202 f
<< " = value<" << memory
->width
<< "> {};\n";
1204 f
<< indent
<< "}\n";
1207 f
<< indent
<< "}\n";
1209 } else /*if (cell->type == ID($memwr))*/ {
1210 log_assert(writable_memories
[memory
]);
1211 // See above for rationale of having both the assert and the condition.
1213 // If assertions are disabled, out of bounds writes are defined to do nothing.
1214 f
<< indent
<< "assert(" << valid_index_temp
<< ".valid && \"out of bounds write\");\n";
1215 f
<< indent
<< "if (" << valid_index_temp
<< ".valid) {\n";
1217 f
<< indent
<< mangle(memory
) << ".update(" << valid_index_temp
<< ".index, ";
1218 dump_sigspec_rhs(cell
->getPort(ID::DATA
));
1220 dump_sigspec_rhs(cell
->getPort(ID::EN
));
1221 f
<< ", " << cell
->getParam(ID::PRIORITY
).as_int() << ");\n";
1223 f
<< indent
<< "}\n";
1225 if (cell
->getParam(ID::CLK_ENABLE
).as_bool()) {
1227 f
<< indent
<< "}\n";
1230 } else if (is_internal_cell(cell
->type
)) {
1231 log_cmd_error("Unsupported internal cell `%s'.\n", cell
->type
.c_str());
1234 log_assert(cell
->known());
1235 const char *access
= is_cxxrtl_blackbox_cell(cell
) ? "->" : ".";
1236 for (auto conn
: cell
->connections())
1237 if (cell
->input(conn
.first
) && !cell
->output(conn
.first
)) {
1238 f
<< indent
<< mangle(cell
) << access
<< mangle_wire_name(conn
.first
) << " = ";
1239 dump_sigspec_rhs(conn
.second
);
1241 if (getenv("CXXRTL_VOID_MY_WARRANTY")) {
1242 // Until we have proper clock tree detection, this really awful hack that opportunistically
1243 // propagates prev_* values for clocks can be used to estimate how much faster a design could
1244 // be if only one clock edge was simulated by replacing:
1245 // top.p_clk = value<1>{0u}; top.step();
1246 // top.p_clk = value<1>{1u}; top.step();
1248 // top.prev_p_clk = value<1>{0u}; top.p_clk = value<1>{1u}; top.step();
1249 // Don't rely on this; it will be removed without warning.
1250 RTLIL::Module
*cell_module
= cell
->module
->design
->module(cell
->type
);
1251 if (cell_module
!= nullptr && cell_module
->wire(conn
.first
) && conn
.second
.is_wire()) {
1252 RTLIL::Wire
*cell_module_wire
= cell_module
->wire(conn
.first
);
1253 if (edge_wires
[conn
.second
.as_wire()] && edge_wires
[cell_module_wire
]) {
1254 f
<< indent
<< mangle(cell
) << access
<< "prev_" << mangle(cell_module_wire
) << " = ";
1255 f
<< "prev_" << mangle(conn
.second
.as_wire()) << ";\n";
1259 } else if (cell
->input(conn
.first
)) {
1260 f
<< indent
<< mangle(cell
) << access
<< mangle_wire_name(conn
.first
) << ".next = ";
1261 dump_sigspec_rhs(conn
.second
);
1264 auto assign_from_outputs
= [&](bool cell_converged
) {
1265 for (auto conn
: cell
->connections()) {
1266 if (cell
->output(conn
.first
)) {
1267 if (conn
.second
.empty())
1268 continue; // ignore disconnected ports
1269 if (is_cxxrtl_sync_port(cell
, conn
.first
))
1270 continue; // fully sync ports are handled in CELL_SYNC nodes
1272 dump_sigspec_lhs(conn
.second
);
1273 f
<< " = " << mangle(cell
) << access
<< mangle_wire_name(conn
.first
);
1274 // Similarly to how there is no purpose to buffering cell inputs, there is also no purpose to buffering
1275 // combinatorial cell outputs in case the cell converges within one cycle. (To convince yourself that
1276 // this optimization is valid, consider that, since the cell converged within one cycle, it would not
1277 // have any buffered wires if they were not output ports. Imagine inlining the cell's eval() function,
1278 // and consider the fate of the localized wires that used to be output ports.)
1280 // Unlike cell inputs (which are never buffered), it is not possible to know apriori whether the cell
1281 // (which may be late bound) will converge immediately. Because of this, the choice between using .curr
1282 // (appropriate for buffered outputs) and .next (appropriate for unbuffered outputs) is made at runtime.
1283 if (cell_converged
&& is_cxxrtl_comb_port(cell
, conn
.first
))
1290 f
<< indent
<< "if (" << mangle(cell
) << access
<< "eval()) {\n";
1292 assign_from_outputs(/*cell_converged=*/true);
1294 f
<< indent
<< "} else {\n";
1296 f
<< indent
<< "converged = false;\n";
1297 assign_from_outputs(/*cell_converged=*/false);
1299 f
<< indent
<< "}\n";
1303 void dump_assign(const RTLIL::SigSig
&sigsig
)
1306 dump_sigspec_lhs(sigsig
.first
);
1308 dump_sigspec_rhs(sigsig
.second
);
1312 void dump_case_rule(const RTLIL::CaseRule
*rule
)
1314 for (auto action
: rule
->actions
)
1315 dump_assign(action
);
1316 for (auto switch_
: rule
->switches
)
1317 dump_switch_rule(switch_
);
1320 void dump_switch_rule(const RTLIL::SwitchRule
*rule
)
1322 // The switch attributes are printed before the switch condition is captured.
1324 std::string signal_temp
= fresh_temporary();
1325 f
<< indent
<< "const value<" << rule
->signal
.size() << "> &" << signal_temp
<< " = ";
1326 dump_sigspec(rule
->signal
, /*is_lhs=*/false);
1330 for (auto case_
: rule
->cases
) {
1331 // The case attributes (for nested cases) are printed before the if/else if/else statement.
1337 if (!case_
->compare
.empty()) {
1340 for (auto &compare
: case_
->compare
) {
1344 if (compare
.is_fully_def()) {
1345 f
<< signal_temp
<< " == ";
1346 dump_sigspec(compare
, /*is_lhs=*/false);
1347 } else if (compare
.is_fully_const()) {
1348 RTLIL::Const compare_mask
, compare_value
;
1349 for (auto bit
: compare
.as_const()) {
1353 compare_mask
.bits
.push_back(RTLIL::S1
);
1354 compare_value
.bits
.push_back(bit
);
1360 compare_mask
.bits
.push_back(RTLIL::S0
);
1361 compare_value
.bits
.push_back(RTLIL::S0
);
1368 f
<< "and_uu<" << compare
.size() << ">(" << signal_temp
<< ", ";
1369 dump_const(compare_mask
);
1371 dump_const(compare_value
);
1380 dump_case_rule(case_
);
1383 f
<< indent
<< "}\n";
1386 void dump_process(const RTLIL::Process
*proc
)
1389 f
<< indent
<< "// process " << proc
->name
.str() << "\n";
1390 // The case attributes (for root case) are always empty.
1391 log_assert(proc
->root_case
.attributes
.empty());
1392 dump_case_rule(&proc
->root_case
);
1393 for (auto sync
: proc
->syncs
) {
1394 RTLIL::SigBit sync_bit
;
1395 if (!sync
->signal
.empty()) {
1396 sync_bit
= sync
->signal
[0];
1397 sync_bit
= sigmaps
[sync_bit
.wire
->module
](sync_bit
);
1400 pool
<std::string
> events
;
1401 switch (sync
->type
) {
1403 log_assert(sync_bit
.wire
!= nullptr);
1404 events
.insert("posedge_" + mangle(sync_bit
));
1407 log_assert(sync_bit
.wire
!= nullptr);
1408 events
.insert("negedge_" + mangle(sync_bit
));
1411 log_assert(sync_bit
.wire
!= nullptr);
1412 events
.insert("posedge_" + mangle(sync_bit
));
1413 events
.insert("negedge_" + mangle(sync_bit
));
1417 events
.insert("true");
1426 if (!events
.empty()) {
1427 f
<< indent
<< "if (";
1429 for (auto &event
: events
) {
1437 for (auto action
: sync
->actions
)
1438 dump_assign(action
);
1440 f
<< indent
<< "}\n";
1445 void dump_wire(const RTLIL::Wire
*wire
, bool is_local_context
)
1447 if (elided_wires
.count(wire
))
1450 if (localized_wires
[wire
] && is_local_context
) {
1452 f
<< indent
<< "value<" << wire
->width
<< "> " << mangle(wire
) << ";\n";
1454 if (!localized_wires
[wire
] && !is_local_context
) {
1456 if (wire
->module
->has_attribute(ID(cxxrtl_blackbox
)) && wire
->has_attribute(ID(cxxrtl_width
))) {
1457 width
= wire
->get_string_attribute(ID(cxxrtl_width
));
1459 width
= std::to_string(wire
->width
);
1464 if (wire
->port_input
&& wire
->port_output
)
1466 else if (wire
->port_input
)
1468 else if (wire
->port_output
)
1470 f
<< (unbuffered_wires
[wire
] ? "value" : "wire") << "<" << width
<< "> " << mangle(wire
);
1471 if (wire
->has_attribute(ID::init
)) {
1473 dump_const_init(wire
->attributes
.at(ID::init
));
1476 if (edge_wires
[wire
]) {
1477 if (unbuffered_wires
[wire
]) {
1478 f
<< indent
<< "value<" << width
<< "> prev_" << mangle(wire
);
1479 if (wire
->has_attribute(ID::init
)) {
1481 dump_const_init(wire
->attributes
.at(ID::init
));
1485 for (auto edge_type
: edge_types
) {
1486 if (edge_type
.first
.wire
== wire
) {
1487 std::string prev
, next
;
1488 if (unbuffered_wires
[wire
]) {
1489 prev
= "prev_" + mangle(edge_type
.first
.wire
);
1490 next
= mangle(edge_type
.first
.wire
);
1492 prev
= mangle(edge_type
.first
.wire
) + ".curr";
1493 next
= mangle(edge_type
.first
.wire
) + ".next";
1495 prev
+= ".slice<" + std::to_string(edge_type
.first
.offset
) + ">().val()";
1496 next
+= ".slice<" + std::to_string(edge_type
.first
.offset
) + ">().val()";
1497 if (edge_type
.second
!= RTLIL::STn
) {
1498 f
<< indent
<< "bool posedge_" << mangle(edge_type
.first
) << "() const {\n";
1500 f
<< indent
<< "return !" << prev
<< " && " << next
<< ";\n";
1502 f
<< indent
<< "}\n";
1504 if (edge_type
.second
!= RTLIL::STp
) {
1505 f
<< indent
<< "bool negedge_" << mangle(edge_type
.first
) << "() const {\n";
1507 f
<< indent
<< "return " << prev
<< " && !" << next
<< ";\n";
1509 f
<< indent
<< "}\n";
1517 void dump_memory(RTLIL::Module
*module
, const RTLIL::Memory
*memory
)
1519 vector
<const RTLIL::Cell
*> init_cells
;
1520 for (auto cell
: module
->cells())
1521 if (cell
->type
== ID($meminit
) && cell
->getParam(ID::MEMID
).decode_string() == memory
->name
.str())
1522 init_cells
.push_back(cell
);
1524 std::sort(init_cells
.begin(), init_cells
.end(), [](const RTLIL::Cell
*a
, const RTLIL::Cell
*b
) {
1525 int a_addr
= a
->getPort(ID::ADDR
).as_int(), b_addr
= b
->getPort(ID::ADDR
).as_int();
1526 int a_prio
= a
->getParam(ID::PRIORITY
).as_int(), b_prio
= b
->getParam(ID::PRIORITY
).as_int();
1527 return a_prio
> b_prio
|| (a_prio
== b_prio
&& a_addr
< b_addr
);
1531 f
<< indent
<< "memory<" << memory
->width
<< "> " << mangle(memory
)
1532 << " { " << memory
->size
<< "u";
1533 if (init_cells
.empty()) {
1538 for (auto cell
: init_cells
) {
1540 RTLIL::Const data
= cell
->getPort(ID::DATA
).as_const();
1541 size_t width
= cell
->getParam(ID::WIDTH
).as_int();
1542 size_t words
= cell
->getParam(ID::WORDS
).as_int();
1543 f
<< indent
<< "memory<" << memory
->width
<< ">::init<" << words
<< "> { "
1544 << stringf("%#x", cell
->getPort(ID::ADDR
).as_int()) << ", {";
1546 for (size_t n
= 0; n
< words
; n
++) {
1548 f
<< "\n" << indent
;
1551 dump_const(data
, width
, n
* width
, /*fixed_width=*/true);
1555 f
<< "\n" << indent
<< "}},\n";
1558 f
<< indent
<< "};\n";
1562 void dump_eval_method(RTLIL::Module
*module
)
1565 f
<< indent
<< "bool converged = " << (eval_converges
.at(module
) ? "true" : "false") << ";\n";
1566 if (!module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1567 for (auto wire
: module
->wires()) {
1568 if (edge_wires
[wire
]) {
1569 for (auto edge_type
: edge_types
) {
1570 if (edge_type
.first
.wire
== wire
) {
1571 if (edge_type
.second
!= RTLIL::STn
) {
1572 f
<< indent
<< "bool posedge_" << mangle(edge_type
.first
) << " = ";
1573 f
<< "this->posedge_" << mangle(edge_type
.first
) << "();\n";
1575 if (edge_type
.second
!= RTLIL::STp
) {
1576 f
<< indent
<< "bool negedge_" << mangle(edge_type
.first
) << " = ";
1577 f
<< "this->negedge_" << mangle(edge_type
.first
) << "();\n";
1583 for (auto wire
: module
->wires())
1584 dump_wire(wire
, /*is_local_context=*/true);
1585 for (auto node
: schedule
[module
]) {
1586 switch (node
.type
) {
1587 case FlowGraph::Node::Type::CONNECT
:
1588 dump_connect(node
.connect
);
1590 case FlowGraph::Node::Type::CELL_SYNC
:
1591 dump_cell_sync(node
.cell
);
1593 case FlowGraph::Node::Type::CELL_EVAL
:
1594 dump_cell_eval(node
.cell
);
1596 case FlowGraph::Node::Type::PROCESS
:
1597 dump_process(node
.process
);
1602 f
<< indent
<< "return converged;\n";
1606 void dump_commit_method(RTLIL::Module
*module
)
1609 f
<< indent
<< "bool changed = false;\n";
1610 for (auto wire
: module
->wires()) {
1611 if (elided_wires
.count(wire
))
1613 if (unbuffered_wires
[wire
]) {
1614 if (edge_wires
[wire
])
1615 f
<< indent
<< "prev_" << mangle(wire
) << " = " << mangle(wire
) << ";\n";
1618 if (!module
->get_bool_attribute(ID(cxxrtl_blackbox
)) || wire
->port_id
!= 0)
1619 f
<< indent
<< "changed |= " << mangle(wire
) << ".commit();\n";
1621 if (!module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1622 for (auto memory
: module
->memories
) {
1623 if (!writable_memories
[memory
.second
])
1625 f
<< indent
<< "changed |= " << mangle(memory
.second
) << ".commit();\n";
1627 for (auto cell
: module
->cells()) {
1628 if (is_internal_cell(cell
->type
))
1630 const char *access
= is_cxxrtl_blackbox_cell(cell
) ? "->" : ".";
1631 f
<< indent
<< "changed |= " << mangle(cell
) << access
<< "commit();\n";
1634 f
<< indent
<< "return changed;\n";
1638 void dump_debug_info_method(RTLIL::Module
*module
)
1640 size_t count_public_wires
= 0;
1641 size_t count_const_wires
= 0;
1642 size_t count_alias_wires
= 0;
1643 size_t count_member_wires
= 0;
1644 size_t count_skipped_wires
= 0;
1645 size_t count_driven_sync
= 0;
1646 size_t count_driven_comb
= 0;
1647 size_t count_undriven
= 0;
1648 size_t count_mixed_driver
= 0;
1650 f
<< indent
<< "assert(path.empty() || path[path.size() - 1] == ' ');\n";
1651 for (auto wire
: module
->wires()) {
1652 if (wire
->name
[0] != '\\')
1654 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
)) && (wire
->port_id
== 0))
1656 count_public_wires
++;
1657 if (debug_const_wires
.count(wire
)) {
1658 // Wire tied to a constant
1659 f
<< indent
<< "static const value<" << wire
->width
<< "> const_" << mangle(wire
) << " = ";
1660 dump_const(debug_const_wires
[wire
]);
1662 f
<< indent
<< "items.add(path + " << escape_cxx_string(get_hdl_name(wire
));
1663 f
<< ", debug_item(const_" << mangle(wire
) << ", ";
1664 f
<< wire
->start_offset
<< "));\n";
1665 count_const_wires
++;
1666 } else if (debug_alias_wires
.count(wire
)) {
1667 // Alias of a member wire
1668 f
<< indent
<< "items.add(path + " << escape_cxx_string(get_hdl_name(wire
));
1669 f
<< ", debug_item(debug_alias(), " << mangle(debug_alias_wires
[wire
]) << ", ";
1670 f
<< wire
->start_offset
<< "));\n";
1671 count_alias_wires
++;
1672 } else if (!localized_wires
.count(wire
)) {
1674 std::vector
<std::string
> flags
;
1676 if (wire
->port_input
&& wire
->port_output
)
1677 flags
.push_back("INOUT");
1678 else if (wire
->port_input
)
1679 flags
.push_back("INPUT");
1680 else if (wire
->port_output
)
1681 flags
.push_back("OUTPUT");
1683 bool has_driven_sync
= false;
1684 bool has_driven_comb
= false;
1685 bool has_undriven
= false;
1687 for (auto bit
: sig
.bits())
1688 if (!bit_has_state
.count(bit
))
1689 has_undriven
= true;
1690 else if (bit_has_state
[bit
])
1691 has_driven_sync
= true;
1693 has_driven_comb
= true;
1694 if (has_driven_sync
)
1695 flags
.push_back("DRIVEN_SYNC");
1696 if (has_driven_sync
&& !has_driven_comb
&& !has_undriven
)
1697 count_driven_sync
++;
1698 if (has_driven_comb
)
1699 flags
.push_back("DRIVEN_COMB");
1700 if (!has_driven_sync
&& has_driven_comb
&& !has_undriven
)
1701 count_driven_comb
++;
1703 flags
.push_back("UNDRIVEN");
1704 if (!has_driven_sync
&& !has_driven_comb
&& has_undriven
)
1706 if (has_driven_sync
+ has_driven_comb
+ has_undriven
> 1)
1707 count_mixed_driver
++;
1709 f
<< indent
<< "items.add(path + " << escape_cxx_string(get_hdl_name(wire
));
1710 f
<< ", debug_item(" << mangle(wire
) << ", ";
1711 f
<< wire
->start_offset
;
1713 for (auto flag
: flags
) {
1720 f
<< "debug_item::" << flag
;
1723 count_member_wires
++;
1725 count_skipped_wires
++;
1728 if (!module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1729 for (auto &memory_it
: module
->memories
) {
1730 if (memory_it
.first
[0] != '\\')
1732 f
<< indent
<< "items.add(path + " << escape_cxx_string(get_hdl_name(memory_it
.second
));
1733 f
<< ", debug_item(" << mangle(memory_it
.second
) << ", ";
1734 f
<< memory_it
.second
->start_offset
<< "));\n";
1736 for (auto cell
: module
->cells()) {
1737 if (is_internal_cell(cell
->type
))
1739 const char *access
= is_cxxrtl_blackbox_cell(cell
) ? "->" : ".";
1740 f
<< indent
<< mangle(cell
) << access
<< "debug_info(items, ";
1741 f
<< "path + " << escape_cxx_string(get_hdl_name(cell
) + ' ') << ");\n";
1746 log_debug("Debug information statistics for module `%s':\n", log_id(module
));
1747 log_debug(" Public wires: %zu, of which:\n", count_public_wires
);
1748 log_debug(" Const wires: %zu\n", count_const_wires
);
1749 log_debug(" Alias wires: %zu\n", count_alias_wires
);
1750 log_debug(" Member wires: %zu, of which:\n", count_member_wires
);
1751 log_debug(" Driven sync: %zu\n", count_driven_sync
);
1752 log_debug(" Driven comb: %zu\n", count_driven_comb
);
1753 log_debug(" Undriven: %zu\n", count_undriven
);
1754 log_debug(" Mixed driver: %zu\n", count_mixed_driver
);
1755 log_debug(" Other wires: %zu (no debug information)\n", count_skipped_wires
);
1758 void dump_metadata_map(const dict
<RTLIL::IdString
, RTLIL::Const
> &metadata_map
)
1760 if (metadata_map
.empty()) {
1761 f
<< "metadata_map()";
1764 f
<< "metadata_map({\n";
1766 for (auto metadata_item
: metadata_map
) {
1767 if (!metadata_item
.first
.begins_with("\\"))
1769 f
<< indent
<< "{ " << escape_cxx_string(metadata_item
.first
.str().substr(1)) << ", ";
1770 if (metadata_item
.second
.flags
& RTLIL::CONST_FLAG_REAL
) {
1771 f
<< std::showpoint
<< std::stod(metadata_item
.second
.decode_string()) << std::noshowpoint
;
1772 } else if (metadata_item
.second
.flags
& RTLIL::CONST_FLAG_STRING
) {
1773 f
<< escape_cxx_string(metadata_item
.second
.decode_string());
1775 f
<< metadata_item
.second
.as_int(/*is_signed=*/metadata_item
.second
.flags
& RTLIL::CONST_FLAG_SIGNED
);
1776 if (!(metadata_item
.second
.flags
& RTLIL::CONST_FLAG_SIGNED
))
1782 f
<< indent
<< "})";
1785 void dump_module_intf(RTLIL::Module
*module
)
1788 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1789 if (module
->has_attribute(ID(cxxrtl_template
)))
1790 f
<< indent
<< "template" << template_params(module
, /*is_decl=*/true) << "\n";
1791 f
<< indent
<< "struct " << mangle(module
) << " : public module {\n";
1793 for (auto wire
: module
->wires()) {
1794 if (wire
->port_id
!= 0)
1795 dump_wire(wire
, /*is_local_context=*/false);
1798 f
<< indent
<< "bool eval() override {\n";
1799 dump_eval_method(module
);
1800 f
<< indent
<< "}\n";
1802 f
<< indent
<< "bool commit() override {\n";
1803 dump_commit_method(module
);
1804 f
<< indent
<< "}\n";
1807 f
<< indent
<< "void debug_info(debug_items &items, std::string path = \"\") override {\n";
1808 dump_debug_info_method(module
);
1809 f
<< indent
<< "}\n";
1812 f
<< indent
<< "static std::unique_ptr<" << mangle(module
);
1813 f
<< template_params(module
, /*is_decl=*/false) << "> ";
1814 f
<< "create(std::string name, metadata_map parameters, metadata_map attributes);\n";
1816 f
<< indent
<< "}; // struct " << mangle(module
) << "\n";
1818 if (blackbox_specializations
.count(module
)) {
1819 // If templated black boxes are used, the constructor of any module which includes the black box cell
1820 // (which calls the declared but not defined in the generated code `create` function) may only be used
1821 // if (a) the create function is defined in the same translation unit, or (b) the create function has
1822 // a forward-declared explicit specialization.
1824 // Option (b) makes it possible to have the generated code and the black box implementation in different
1825 // translation units, which is convenient. Of course, its downside is that black boxes must predefine
1826 // a specialization for every combination of parameters the generated code may use; but since the main
1827 // purpose of templated black boxes is abstracting over datapath width, it is expected that there would
1828 // be very few such combinations anyway.
1829 for (auto specialization
: blackbox_specializations
[module
]) {
1830 f
<< indent
<< "template<>\n";
1831 f
<< indent
<< "std::unique_ptr<" << mangle(module
) << specialization
<< "> ";
1832 f
<< mangle(module
) << specialization
<< "::";
1833 f
<< "create(std::string name, metadata_map parameters, metadata_map attributes);\n";
1838 f
<< indent
<< "struct " << mangle(module
) << " : public module {\n";
1840 for (auto wire
: module
->wires())
1841 dump_wire(wire
, /*is_local_context=*/false);
1843 bool has_memories
= false;
1844 for (auto memory
: module
->memories
) {
1845 dump_memory(module
, memory
.second
);
1846 has_memories
= true;
1850 bool has_cells
= false;
1851 for (auto cell
: module
->cells()) {
1852 if (is_internal_cell(cell
->type
))
1855 RTLIL::Module
*cell_module
= module
->design
->module(cell
->type
);
1856 log_assert(cell_module
!= nullptr);
1857 if (cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1858 f
<< indent
<< "std::unique_ptr<" << mangle(cell_module
) << template_args(cell
) << "> ";
1859 f
<< mangle(cell
) << " = " << mangle(cell_module
) << template_args(cell
);
1860 f
<< "::create(" << escape_cxx_string(get_hdl_name(cell
)) << ", ";
1861 dump_metadata_map(cell
->parameters
);
1863 dump_metadata_map(cell
->attributes
);
1866 f
<< indent
<< mangle(cell_module
) << " " << mangle(cell
) << ";\n";
1872 f
<< indent
<< mangle(module
) << "() {}\n";
1874 f
<< indent
<< mangle(module
) << "(adopt, " << mangle(module
) << " other) :\n";
1876 for (auto cell
: module
->cells()) {
1877 if (is_internal_cell(cell
->type
))
1884 RTLIL::Module
*cell_module
= module
->design
->module(cell
->type
);
1885 if (cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1886 f
<< indent
<< " " << mangle(cell
) << "(std::move(other." << mangle(cell
) << "))";
1888 f
<< indent
<< " " << mangle(cell
) << "(adopt {}, std::move(other." << mangle(cell
) << "))";
1893 for (auto cell
: module
->cells()) {
1894 if (is_internal_cell(cell
->type
))
1896 RTLIL::Module
*cell_module
= module
->design
->module(cell
->type
);
1897 if (cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
1898 f
<< indent
<< mangle(cell
) << "->reset();\n";
1901 f
<< indent
<< "}\n";
1903 f
<< indent
<< mangle(module
) << "(adopt, " << mangle(module
) << " other) {}\n";
1906 f
<< indent
<< "void reset() override {\n";
1908 f
<< indent
<< "*this = " << mangle(module
) << "(adopt {}, std::move(*this));\n";
1910 f
<< indent
<< "}\n";
1912 f
<< indent
<< "bool eval() override;\n";
1913 f
<< indent
<< "bool commit() override;\n";
1915 f
<< indent
<< "void debug_info(debug_items &items, std::string path = \"\") override;\n";
1917 f
<< indent
<< "}; // struct " << mangle(module
) << "\n";
1922 void dump_module_impl(RTLIL::Module
*module
)
1924 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
1926 f
<< indent
<< "bool " << mangle(module
) << "::eval() {\n";
1927 dump_eval_method(module
);
1928 f
<< indent
<< "}\n";
1930 f
<< indent
<< "bool " << mangle(module
) << "::commit() {\n";
1931 dump_commit_method(module
);
1932 f
<< indent
<< "}\n";
1935 f
<< indent
<< "void " << mangle(module
) << "::debug_info(debug_items &items, std::string path) {\n";
1936 dump_debug_info_method(module
);
1937 f
<< indent
<< "}\n";
1942 void dump_design(RTLIL::Design
*design
)
1944 RTLIL::Module
*top_module
= nullptr;
1945 std::vector
<RTLIL::Module
*> modules
;
1946 TopoSort
<RTLIL::Module
*> topo_design
;
1947 for (auto module
: design
->modules()) {
1948 if (!design
->selected_module(module
))
1950 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
1951 modules
.push_back(module
); // cxxrtl blackboxes first
1952 if (module
->get_blackbox_attribute() || module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
1954 if (module
->get_bool_attribute(ID::top
))
1955 top_module
= module
;
1957 topo_design
.node(module
);
1958 for (auto cell
: module
->cells()) {
1959 if (is_internal_cell(cell
->type
) || is_cxxrtl_blackbox_cell(cell
))
1961 RTLIL::Module
*cell_module
= design
->module(cell
->type
);
1962 log_assert(cell_module
!= nullptr);
1963 topo_design
.edge(cell_module
, module
);
1966 bool no_loops
= topo_design
.sort();
1967 log_assert(no_loops
);
1968 modules
.insert(modules
.end(), topo_design
.sorted
.begin(), topo_design
.sorted
.end());
1971 // The only thing more depraved than include guards, is mangling filenames to turn them into include guards.
1972 std::string include_guard
= design_ns
+ "_header";
1973 std::transform(include_guard
.begin(), include_guard
.end(), include_guard
.begin(), ::toupper
);
1975 f
<< "#ifndef " << include_guard
<< "\n";
1976 f
<< "#define " << include_guard
<< "\n";
1978 if (top_module
!= nullptr && debug_info
) {
1979 f
<< "#include <backends/cxxrtl/cxxrtl_capi.h>\n";
1981 f
<< "#ifdef __cplusplus\n";
1982 f
<< "extern \"C\" {\n";
1985 f
<< "cxxrtl_toplevel " << design_ns
<< "_create();\n";
1987 f
<< "#ifdef __cplusplus\n";
1992 f
<< "// The CXXRTL C API is not available because the design is built without debug information.\n";
1995 f
<< "#ifdef __cplusplus\n";
1997 f
<< "#include <backends/cxxrtl/cxxrtl.h>\n";
1999 f
<< "using namespace cxxrtl;\n";
2001 f
<< "namespace " << design_ns
<< " {\n";
2003 for (auto module
: modules
)
2004 dump_module_intf(module
);
2005 f
<< "} // namespace " << design_ns
<< "\n";
2007 f
<< "#endif // __cplusplus\n";
2010 *intf_f
<< f
.str(); f
.str("");
2014 f
<< "#include \"" << intf_filename
<< "\"\n";
2016 f
<< "#include <backends/cxxrtl/cxxrtl.h>\n";
2018 f
<< "#if defined(CXXRTL_INCLUDE_CAPI_IMPL) || \\\n";
2019 f
<< " defined(CXXRTL_INCLUDE_VCD_CAPI_IMPL)\n";
2020 f
<< "#include <backends/cxxrtl/cxxrtl_capi.cc>\n";
2023 f
<< "#if defined(CXXRTL_INCLUDE_VCD_CAPI_IMPL)\n";
2024 f
<< "#include <backends/cxxrtl/cxxrtl_vcd_capi.cc>\n";
2027 f
<< "using namespace cxxrtl_yosys;\n";
2029 f
<< "namespace " << design_ns
<< " {\n";
2031 for (auto module
: modules
) {
2033 dump_module_intf(module
);
2034 dump_module_impl(module
);
2036 f
<< "} // namespace " << design_ns
<< "\n";
2038 if (top_module
!= nullptr && debug_info
) {
2039 f
<< "extern \"C\"\n";
2040 f
<< "cxxrtl_toplevel " << design_ns
<< "_create() {\n";
2042 std::string top_type
= design_ns
+ "::" + mangle(top_module
);
2043 f
<< indent
<< "return new _cxxrtl_toplevel { ";
2044 f
<< "std::unique_ptr<" << top_type
<< ">(new " + top_type
+ ")";
2050 *impl_f
<< f
.str(); f
.str("");
2053 // Edge-type sync rules require us to emit edge detectors, which require coordination between
2054 // eval and commit phases. To do this we need to collect them upfront.
2056 // Note that the simulator commit phase operates at wire granularity but edge-type sync rules
2057 // operate at wire bit granularity; it is possible to have code similar to:
2058 // wire [3:0] clocks;
2059 // always @(posedge clocks[0]) ...
2060 // To handle this we track edge sensitivity both for wires and wire bits.
2061 void register_edge_signal(SigMap
&sigmap
, RTLIL::SigSpec signal
, RTLIL::SyncType type
)
2063 signal
= sigmap(signal
);
2064 log_assert(signal
.is_wire() && signal
.is_bit());
2065 log_assert(type
== RTLIL::STp
|| type
== RTLIL::STn
|| type
== RTLIL::STe
);
2067 RTLIL::SigBit sigbit
= signal
[0];
2068 if (!edge_types
.count(sigbit
))
2069 edge_types
[sigbit
] = type
;
2070 else if (edge_types
[sigbit
] != type
)
2071 edge_types
[sigbit
] = RTLIL::STe
;
2072 edge_wires
.insert(signal
.as_wire());
2075 void analyze_design(RTLIL::Design
*design
)
2077 bool has_feedback_arcs
= false;
2078 bool has_buffered_comb_wires
= false;
2080 for (auto module
: design
->modules()) {
2081 if (!design
->selected_module(module
))
2084 SigMap
&sigmap
= sigmaps
[module
];
2087 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
2088 for (auto port
: module
->ports
) {
2089 RTLIL::Wire
*wire
= module
->wire(port
);
2090 if (wire
->port_input
&& !wire
->port_output
)
2091 unbuffered_wires
.insert(wire
);
2092 if (wire
->has_attribute(ID(cxxrtl_edge
))) {
2093 RTLIL::Const edge_attr
= wire
->attributes
[ID(cxxrtl_edge
)];
2094 if (!(edge_attr
.flags
& RTLIL::CONST_FLAG_STRING
) || (int)edge_attr
.decode_string().size() != GetSize(wire
))
2095 log_cmd_error("Attribute `cxxrtl_edge' of port `%s.%s' is not a string with one character per bit.\n",
2096 log_id(module
), log_signal(wire
));
2098 std::string edges
= wire
->get_string_attribute(ID(cxxrtl_edge
));
2099 for (int i
= 0; i
< GetSize(wire
); i
++) {
2100 RTLIL::SigSpec wire_sig
= wire
;
2103 case 'p': register_edge_signal(sigmap
, wire_sig
[i
], RTLIL::STp
); break;
2104 case 'n': register_edge_signal(sigmap
, wire_sig
[i
], RTLIL::STn
); break;
2105 case 'a': register_edge_signal(sigmap
, wire_sig
[i
], RTLIL::STe
); break;
2107 log_cmd_error("Attribute `cxxrtl_edge' of port `%s.%s' contains specifiers "
2108 "other than '-', 'p', 'n', or 'a'.\n",
2109 log_id(module
), log_signal(wire
));
2115 // Black boxes converge by default, since their implementations are quite unlikely to require
2116 // internal propagation of comb signals.
2117 eval_converges
[module
] = true;
2123 for (auto conn
: module
->connections())
2124 flow
.add_node(conn
);
2126 dict
<const RTLIL::Cell
*, FlowGraph::Node
*> memrw_cell_nodes
;
2127 dict
<std::pair
<RTLIL::SigBit
, const RTLIL::Memory
*>,
2128 pool
<const RTLIL::Cell
*>> memwr_per_domain
;
2129 for (auto cell
: module
->cells()) {
2131 log_cmd_error("Unknown cell `%s'.\n", log_id(cell
->type
));
2133 RTLIL::Module
*cell_module
= design
->module(cell
->type
);
2135 cell_module
->get_blackbox_attribute() &&
2136 !cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
2137 log_cmd_error("External blackbox cell `%s' is not marked as a CXXRTL blackbox.\n", log_id(cell
->type
));
2140 cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)) &&
2141 cell_module
->get_bool_attribute(ID(cxxrtl_template
)))
2142 blackbox_specializations
[cell_module
].insert(template_args(cell
));
2144 FlowGraph::Node
*node
= flow
.add_node(cell
);
2146 // Various DFF cells are treated like posedge/negedge processes, see above for details.
2147 if (cell
->type
.in(ID($dff
), ID($dffe
), ID($adff
), ID($adffe
), ID($dffsr
), ID($dffsre
), ID($sdff
), ID($sdffe
), ID($sdffce
))) {
2148 if (cell
->getPort(ID::CLK
).is_wire())
2149 register_edge_signal(sigmap
, cell
->getPort(ID::CLK
),
2150 cell
->parameters
[ID::CLK_POLARITY
].as_bool() ? RTLIL::STp
: RTLIL::STn
);
2152 // Similar for memory port cells.
2153 if (cell
->type
.in(ID($memrd
), ID($memwr
))) {
2154 if (cell
->getParam(ID::CLK_ENABLE
).as_bool()) {
2155 if (cell
->getPort(ID::CLK
).is_wire())
2156 register_edge_signal(sigmap
, cell
->getPort(ID::CLK
),
2157 cell
->parameters
[ID::CLK_POLARITY
].as_bool() ? RTLIL::STp
: RTLIL::STn
);
2159 memrw_cell_nodes
[cell
] = node
;
2161 // Optimize access to read-only memories.
2162 if (cell
->type
== ID($memwr
))
2163 writable_memories
.insert(module
->memories
[cell
->getParam(ID::MEMID
).decode_string()]);
2164 // Collect groups of memory write ports in the same domain.
2165 if (cell
->type
== ID($memwr
) && cell
->getParam(ID::CLK_ENABLE
).as_bool() && cell
->getPort(ID::CLK
).is_wire()) {
2166 RTLIL::SigBit clk_bit
= sigmap(cell
->getPort(ID::CLK
))[0];
2167 const RTLIL::Memory
*memory
= module
->memories
[cell
->getParam(ID::MEMID
).decode_string()];
2168 memwr_per_domain
[{clk_bit
, memory
}].insert(cell
);
2170 // Handling of packed memories is delegated to the `memory_unpack` pass, so we can rely on the presence
2171 // of RTLIL memory objects and $memrd/$memwr/$meminit cells.
2172 if (cell
->type
.in(ID($mem
)))
2175 for (auto cell
: module
->cells()) {
2176 // Collect groups of memory write ports read by every transparent read port.
2177 if (cell
->type
== ID($memrd
) && cell
->getParam(ID::CLK_ENABLE
).as_bool() && cell
->getPort(ID::CLK
).is_wire() &&
2178 cell
->getParam(ID::TRANSPARENT
).as_bool()) {
2179 RTLIL::SigBit clk_bit
= sigmap(cell
->getPort(ID::CLK
))[0];
2180 const RTLIL::Memory
*memory
= module
->memories
[cell
->getParam(ID::MEMID
).decode_string()];
2181 for (auto memwr_cell
: memwr_per_domain
[{clk_bit
, memory
}]) {
2182 transparent_for
[cell
].insert(memwr_cell
);
2183 // Our implementation of transparent $memrd cells reads \EN, \ADDR and \DATA from every $memwr cell
2184 // in the same domain, which isn't directly visible in the netlist. Add these uses explicitly.
2185 flow
.add_uses(memrw_cell_nodes
[cell
], memwr_cell
->getPort(ID::EN
));
2186 flow
.add_uses(memrw_cell_nodes
[cell
], memwr_cell
->getPort(ID::ADDR
));
2187 flow
.add_uses(memrw_cell_nodes
[cell
], memwr_cell
->getPort(ID::DATA
));
2192 for (auto proc
: module
->processes
) {
2193 flow
.add_node(proc
.second
);
2195 for (auto sync
: proc
.second
->syncs
)
2196 switch (sync
->type
) {
2197 // Edge-type sync rules require pre-registration.
2201 register_edge_signal(sigmap
, sync
->signal
, sync
->type
);
2204 // Level-type sync rules require no special handling.
2211 log_cmd_error("Global clock is not supported.\n");
2213 // Handling of init-type sync rules is delegated to the `proc_init` pass, so we can use the wire
2214 // attribute regardless of input.
2220 for (auto wire
: module
->wires()) {
2221 if (!flow
.is_elidable(wire
)) continue;
2222 if (wire
->port_id
!= 0) continue;
2223 if (wire
->get_bool_attribute(ID::keep
)) continue;
2224 if (wire
->name
.begins_with("$") && !elide_internal
) continue;
2225 if (wire
->name
.begins_with("\\") && !elide_public
) continue;
2226 if (edge_wires
[wire
]) continue;
2227 if (flow
.wire_comb_defs
[wire
].size() > 1)
2228 log_cmd_error("Wire %s.%s has multiple drivers.\n", log_id(module
), log_id(wire
));
2229 log_assert(flow
.wire_comb_defs
[wire
].size() == 1);
2230 elided_wires
[wire
] = **flow
.wire_comb_defs
[wire
].begin();
2233 dict
<FlowGraph::Node
*, pool
<const RTLIL::Wire
*>, hash_ptr_ops
> node_defs
;
2234 for (auto wire_comb_def
: flow
.wire_comb_defs
)
2235 for (auto node
: wire_comb_def
.second
)
2236 node_defs
[node
].insert(wire_comb_def
.first
);
2238 Scheduler
<FlowGraph::Node
> scheduler
;
2239 dict
<FlowGraph::Node
*, Scheduler
<FlowGraph::Node
>::Vertex
*, hash_ptr_ops
> node_map
;
2240 for (auto node
: flow
.nodes
)
2241 node_map
[node
] = scheduler
.add(node
);
2242 for (auto node_def
: node_defs
) {
2243 auto vertex
= node_map
[node_def
.first
];
2244 for (auto wire
: node_def
.second
)
2245 for (auto succ_node
: flow
.wire_uses
[wire
]) {
2246 auto succ_vertex
= node_map
[succ_node
];
2247 vertex
->succs
.insert(succ_vertex
);
2248 succ_vertex
->preds
.insert(vertex
);
2252 auto eval_order
= scheduler
.schedule();
2253 pool
<FlowGraph::Node
*, hash_ptr_ops
> evaluated
;
2254 pool
<const RTLIL::Wire
*> feedback_wires
;
2255 for (auto vertex
: eval_order
) {
2256 auto node
= vertex
->data
;
2257 schedule
[module
].push_back(*node
);
2258 // Any wire that is an output of node vo and input of node vi where vo is scheduled later than vi
2259 // is a feedback wire. Feedback wires indicate apparent logic loops in the design, which may be
2260 // caused by a true logic loop, but usually are a benign result of dependency tracking that works
2261 // on wire, not bit, level. Nevertheless, feedback wires cannot be localized.
2262 evaluated
.insert(node
);
2263 for (auto wire
: node_defs
[node
])
2264 for (auto succ_node
: flow
.wire_uses
[wire
])
2265 if (evaluated
[succ_node
]) {
2266 feedback_wires
.insert(wire
);
2267 // Feedback wires may never be elided because feedback requires state, but the point of elision
2268 // (and localization) is to eliminate state.
2269 elided_wires
.erase(wire
);
2273 if (!feedback_wires
.empty()) {
2274 has_feedback_arcs
= true;
2275 log("Module `%s' contains feedback arcs through wires:\n", log_id(module
));
2276 for (auto wire
: feedback_wires
)
2277 log(" %s\n", log_id(wire
));
2280 for (auto wire
: module
->wires()) {
2281 if (feedback_wires
[wire
]) continue;
2282 if (wire
->port_output
&& !module
->get_bool_attribute(ID::top
)) continue;
2283 if (wire
->name
.begins_with("$") && !unbuffer_internal
) continue;
2284 if (wire
->name
.begins_with("\\") && !unbuffer_public
) continue;
2285 if (flow
.wire_sync_defs
.count(wire
) > 0) continue;
2286 unbuffered_wires
.insert(wire
);
2287 if (edge_wires
[wire
]) continue;
2288 if (wire
->get_bool_attribute(ID::keep
)) continue;
2289 if (wire
->port_input
|| wire
->port_output
) continue;
2290 if (wire
->name
.begins_with("$") && !localize_internal
) continue;
2291 if (wire
->name
.begins_with("\\") && !localize_public
) continue;
2292 localized_wires
.insert(wire
);
2295 // For maximum performance, the state of the simulation (which is the same as the set of its double buffered
2296 // wires, since using a singly buffered wire for any kind of state introduces a race condition) should contain
2297 // no wires attached to combinatorial outputs. Feedback wires, by definition, make that impossible. However,
2298 // it is possible that a design with no feedback arcs would end up with doubly buffered wires in such cases
2299 // as a wire with multiple drivers where one of them is combinatorial and the other is synchronous. Such designs
2300 // also require more than one delta cycle to converge.
2301 pool
<const RTLIL::Wire
*> buffered_comb_wires
;
2302 for (auto wire
: module
->wires()) {
2303 if (flow
.wire_comb_defs
[wire
].size() > 0 && !unbuffered_wires
[wire
] && !feedback_wires
[wire
])
2304 buffered_comb_wires
.insert(wire
);
2306 if (!buffered_comb_wires
.empty()) {
2307 has_buffered_comb_wires
= true;
2308 log("Module `%s' contains buffered combinatorial wires:\n", log_id(module
));
2309 for (auto wire
: buffered_comb_wires
)
2310 log(" %s\n", log_id(wire
));
2313 eval_converges
[module
] = feedback_wires
.empty() && buffered_comb_wires
.empty();
2315 for (auto item
: flow
.bit_has_state
)
2316 bit_has_state
.insert(item
);
2319 // Find wires that alias other wires or are tied to a constant; debug information can be enriched with these
2320 // at essentially zero additional cost.
2322 // Note that the information collected here can't be used for optimizing the netlist: debug information queries
2323 // are pure and run on a design in a stable state, which allows assumptions that do not otherwise hold.
2324 for (auto wire
: module
->wires()) {
2325 if (wire
->name
[0] != '\\')
2327 if (!unbuffered_wires
[wire
])
2329 const RTLIL::Wire
*wire_it
= wire
;
2331 if (!(flow
.wire_def_elidable
.count(wire_it
) && flow
.wire_def_elidable
[wire_it
]))
2332 break; // not an alias: complex def
2333 log_assert(flow
.wire_comb_defs
[wire_it
].size() == 1);
2334 FlowGraph::Node
*node
= *flow
.wire_comb_defs
[wire_it
].begin();
2335 if (node
->type
!= FlowGraph::Node::Type::CONNECT
)
2336 break; // not an alias: def by cell
2337 RTLIL::SigSpec rhs_sig
= node
->connect
.second
;
2338 if (rhs_sig
.is_wire()) {
2339 RTLIL::Wire
*rhs_wire
= rhs_sig
.as_wire();
2340 if (unbuffered_wires
[rhs_wire
]) {
2341 wire_it
= rhs_wire
; // maybe an alias
2343 debug_alias_wires
[wire
] = rhs_wire
; // is an alias
2346 } else if (rhs_sig
.is_fully_const()) {
2347 debug_const_wires
[wire
] = rhs_sig
.as_const(); // is a const
2350 break; // not an alias: complex rhs
2356 if (has_feedback_arcs
|| has_buffered_comb_wires
) {
2357 // Although both non-feedback buffered combinatorial wires and apparent feedback wires may be eliminated
2358 // by optimizing the design, if after `proc; flatten` there are any feedback wires remaining, it is very
2359 // likely that these feedback wires are indicative of a true logic loop, so they get emphasized in the message.
2360 const char *why_pessimistic
= nullptr;
2361 if (has_feedback_arcs
)
2362 why_pessimistic
= "feedback wires";
2363 else if (has_buffered_comb_wires
)
2364 why_pessimistic
= "buffered combinatorial wires";
2365 log_warning("Design contains %s, which require delta cycles during evaluation.\n", why_pessimistic
);
2367 log("Flattening may eliminate %s from the design.\n", why_pessimistic
);
2369 log("Converting processes to netlists may eliminate %s from the design.\n", why_pessimistic
);
2373 void check_design(RTLIL::Design
*design
, bool &has_top
, bool &has_sync_init
, bool &has_packed_mem
)
2375 has_sync_init
= has_packed_mem
= has_top
= false;
2377 for (auto module
: design
->modules()) {
2378 if (module
->get_blackbox_attribute() && !module
->has_attribute(ID(cxxrtl_blackbox
)))
2381 if (!design
->selected_whole_module(module
))
2382 if (design
->selected_module(module
))
2383 log_cmd_error("Can't handle partially selected module `%s'!\n", id2cstr(module
->name
));
2384 if (!design
->selected_module(module
))
2387 if (module
->get_bool_attribute(ID::top
))
2390 for (auto proc
: module
->processes
)
2391 for (auto sync
: proc
.second
->syncs
)
2392 if (sync
->type
== RTLIL::STi
)
2393 has_sync_init
= true;
2395 // The Mem constructor also checks for well-formedness of $meminit cells, if any.
2396 for (auto &mem
: Mem::get_all_memories(module
))
2398 has_packed_mem
= true;
2402 void prepare_design(RTLIL::Design
*design
)
2404 bool did_anything
= false;
2405 bool has_top
, has_sync_init
, has_packed_mem
;
2407 check_design(design
, has_top
, has_sync_init
, has_packed_mem
);
2408 if (run_hierarchy
&& !has_top
) {
2409 Pass::call(design
, "hierarchy -auto-top");
2410 did_anything
= true;
2413 Pass::call(design
, "flatten");
2414 did_anything
= true;
2417 Pass::call(design
, "proc");
2418 did_anything
= true;
2419 } else if (has_sync_init
) {
2420 // We're only interested in proc_init, but it depends on proc_prune and proc_clean, so call those
2421 // in case they weren't already. (This allows `yosys foo.v -o foo.cc` to work.)
2422 Pass::call(design
, "proc_prune");
2423 Pass::call(design
, "proc_clean");
2424 Pass::call(design
, "proc_init");
2425 did_anything
= true;
2427 if (has_packed_mem
) {
2428 Pass::call(design
, "memory_unpack");
2429 did_anything
= true;
2431 // Recheck the design if it was modified.
2433 check_design(design
, has_top
, has_sync_init
, has_packed_mem
);
2434 log_assert(has_top
&& !has_sync_init
&& !has_packed_mem
);
2438 analyze_design(design
);
2442 struct CxxrtlBackend
: public Backend
{
2443 static const int DEFAULT_OPT_LEVEL
= 6;
2444 static const int OPT_LEVEL_DEBUG
= 4;
2445 static const int DEFAULT_DEBUG_LEVEL
= 1;
2447 CxxrtlBackend() : Backend("cxxrtl", "convert design to C++ RTL simulation") { }
2448 void help() override
2450 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
2452 log(" write_cxxrtl [options] [filename]\n");
2454 log("Write C++ code that simulates the design. The generated code requires a driver\n");
2455 log("that instantiates the design, toggles its clock, and interacts with its ports.\n");
2457 log("The following driver may be used as an example for a design with a single clock\n");
2458 log("driving rising edge triggered flip-flops:\n");
2460 log(" #include \"top.cc\"\n");
2462 log(" int main() {\n");
2463 log(" cxxrtl_design::p_top top;\n");
2464 log(" top.step();\n");
2465 log(" while (1) {\n");
2466 log(" /* user logic */\n");
2467 log(" top.p_clk.set(false);\n");
2468 log(" top.step();\n");
2469 log(" top.p_clk.set(true);\n");
2470 log(" top.step();\n");
2474 log("Note that CXXRTL simulations, just like the hardware they are simulating, are\n");
2475 log("subject to race conditions. If, in the example above, the user logic would run\n");
2476 log("simultaneously with the rising edge of the clock, the design would malfunction.\n");
2478 log("This backend supports replacing parts of the design with black boxes implemented\n");
2479 log("in C++. If a module marked as a CXXRTL black box, its implementation is ignored,\n");
2480 log("and the generated code consists only of an interface and a factory function.\n");
2481 log("The driver must implement the factory function that creates an implementation of\n");
2482 log("the black box, taking into account the parameters it is instantiated with.\n");
2484 log("For example, the following Verilog code defines a CXXRTL black box interface for\n");
2485 log("a synchronous debug sink:\n");
2487 log(" (* cxxrtl_blackbox *)\n");
2488 log(" module debug(...);\n");
2489 log(" (* cxxrtl_edge = \"p\" *) input clk;\n");
2490 log(" input en;\n");
2491 log(" input [7:0] i_data;\n");
2492 log(" (* cxxrtl_sync *) output [7:0] o_data;\n");
2493 log(" endmodule\n");
2495 log("For this HDL interface, this backend will generate the following C++ interface:\n");
2497 log(" struct bb_p_debug : public module {\n");
2498 log(" value<1> p_clk;\n");
2499 log(" bool posedge_p_clk() const { /* ... */ }\n");
2500 log(" value<1> p_en;\n");
2501 log(" value<8> p_i_data;\n");
2502 log(" wire<8> p_o_data;\n");
2504 log(" bool eval() override;\n");
2505 log(" bool commit() override;\n");
2507 log(" static std::unique_ptr<bb_p_debug>\n");
2508 log(" create(std::string name, metadata_map parameters, metadata_map attributes);\n");
2511 log("The `create' function must be implemented by the driver. For example, it could\n");
2512 log("always provide an implementation logging the values to standard error stream:\n");
2514 log(" namespace cxxrtl_design {\n");
2516 log(" struct stderr_debug : public bb_p_debug {\n");
2517 log(" bool eval() override {\n");
2518 log(" if (posedge_p_clk() && p_en)\n");
2519 log(" fprintf(stderr, \"debug: %%02x\\n\", p_i_data.data[0]);\n");
2520 log(" p_o_data.next = p_i_data;\n");
2521 log(" return bb_p_debug::eval();\n");
2525 log(" std::unique_ptr<bb_p_debug>\n");
2526 log(" bb_p_debug::create(std::string name, cxxrtl::metadata_map parameters,\n");
2527 log(" cxxrtl::metadata_map attributes) {\n");
2528 log(" return std::make_unique<stderr_debug>();\n");
2533 log("For complex applications of black boxes, it is possible to parameterize their\n");
2534 log("port widths. For example, the following Verilog code defines a CXXRTL black box\n");
2535 log("interface for a configurable width debug sink:\n");
2537 log(" (* cxxrtl_blackbox, cxxrtl_template = \"WIDTH\" *)\n");
2538 log(" module debug(...);\n");
2539 log(" parameter WIDTH = 8;\n");
2540 log(" (* cxxrtl_edge = \"p\" *) input clk;\n");
2541 log(" input en;\n");
2542 log(" (* cxxrtl_width = \"WIDTH\" *) input [WIDTH - 1:0] i_data;\n");
2543 log(" (* cxxrtl_width = \"WIDTH\" *) output [WIDTH - 1:0] o_data;\n");
2544 log(" endmodule\n");
2546 log("For this parametric HDL interface, this backend will generate the following C++\n");
2547 log("interface (only the differences are shown):\n");
2549 log(" template<size_t WIDTH>\n");
2550 log(" struct bb_p_debug : public module {\n");
2552 log(" value<WIDTH> p_i_data;\n");
2553 log(" wire<WIDTH> p_o_data;\n");
2555 log(" static std::unique_ptr<bb_p_debug<WIDTH>>\n");
2556 log(" create(std::string name, metadata_map parameters, metadata_map attributes);\n");
2559 log("The `create' function must be implemented by the driver, specialized for every\n");
2560 log("possible combination of template parameters. (Specialization is necessary to\n");
2561 log("enable separate compilation of generated code and black box implementations.)\n");
2563 log(" template<size_t SIZE>\n");
2564 log(" struct stderr_debug : public bb_p_debug<SIZE> {\n");
2568 log(" template<>\n");
2569 log(" std::unique_ptr<bb_p_debug<8>>\n");
2570 log(" bb_p_debug<8>::create(std::string name, cxxrtl::metadata_map parameters,\n");
2571 log(" cxxrtl::metadata_map attributes) {\n");
2572 log(" return std::make_unique<stderr_debug<8>>();\n");
2575 log("The following attributes are recognized by this backend:\n");
2577 log(" cxxrtl_blackbox\n");
2578 log(" only valid on modules. if specified, the module contents are ignored,\n");
2579 log(" and the generated code includes only the module interface and a factory\n");
2580 log(" function, which will be called to instantiate the module.\n");
2582 log(" cxxrtl_edge\n");
2583 log(" only valid on inputs of black boxes. must be one of \"p\", \"n\", \"a\".\n");
2584 log(" if specified on signal `clk`, the generated code includes edge detectors\n");
2585 log(" `posedge_p_clk()` (if \"p\"), `negedge_p_clk()` (if \"n\"), or both (if\n");
2586 log(" \"a\"), simplifying implementation of clocked black boxes.\n");
2588 log(" cxxrtl_template\n");
2589 log(" only valid on black boxes. must contain a space separated sequence of\n");
2590 log(" identifiers that have a corresponding black box parameters. for each\n");
2591 log(" of them, the generated code includes a `size_t` template parameter.\n");
2593 log(" cxxrtl_width\n");
2594 log(" only valid on ports of black boxes. must be a constant expression, which\n");
2595 log(" is directly inserted into generated code.\n");
2597 log(" cxxrtl_comb, cxxrtl_sync\n");
2598 log(" only valid on outputs of black boxes. if specified, indicates that every\n");
2599 log(" bit of the output port is driven, correspondingly, by combinatorial or\n");
2600 log(" synchronous logic. this knowledge is used for scheduling optimizations.\n");
2601 log(" if neither is specified, the output will be pessimistically treated as\n");
2602 log(" driven by both combinatorial and synchronous logic.\n");
2604 log("The following options are supported by this backend:\n");
2607 log(" generate separate interface (.h) and implementation (.cc) files.\n");
2608 log(" if specified, the backend must be called with a filename, and filename\n");
2609 log(" of the interface is derived from filename of the implementation.\n");
2610 log(" otherwise, interface and implementation are generated together.\n");
2612 log(" -namespace <ns-name>\n");
2613 log(" place the generated code into namespace <ns-name>. if not specified,\n");
2614 log(" \"cxxrtl_design\" is used.\n");
2616 log(" -nohierarchy\n");
2617 log(" use design hierarchy as-is. in most designs, a top module should be\n");
2618 log(" present as it is exposed through the C API and has unbuffered outputs\n");
2619 log(" for improved performance; it will be determined automatically if absent.\n");
2621 log(" -noflatten\n");
2622 log(" don't flatten the design. fully flattened designs can evaluate within\n");
2623 log(" one delta cycle if they have no combinatorial feedback.\n");
2624 log(" note that the debug interface and waveform dumps use full hierarchical\n");
2625 log(" names for all wires even in flattened designs.\n");
2628 log(" don't convert processes to netlists. in most designs, converting\n");
2629 log(" processes significantly improves evaluation performance at the cost of\n");
2630 log(" slight increase in compilation time.\n");
2632 log(" -O <level>\n");
2633 log(" set the optimization level. the default is -O%d. higher optimization\n", DEFAULT_OPT_LEVEL
);
2634 log(" levels dramatically decrease compile and run time, and highest level\n");
2635 log(" possible for a design should be used.\n");
2638 log(" no optimization.\n");
2641 log(" localize internal wires if possible.\n");
2644 log(" like -O1, and unbuffer internal wires if possible.\n");
2647 log(" like -O2, and elide internal wires if possible.\n");
2650 log(" like -O3, and unbuffer public wires not marked (*keep*) if possible.\n");
2653 log(" like -O4, and localize public wires not marked (*keep*) if possible.\n");
2656 log(" like -O5, and elide public wires not marked (*keep*) if possible.\n");
2659 log(" highest optimization level that provides debug information for all\n");
2660 log(" public wires. currently, alias for -O%d.\n", OPT_LEVEL_DEBUG
);
2662 log(" -g <level>\n");
2663 log(" set the debug level. the default is -g%d. higher debug levels provide\n", DEFAULT_DEBUG_LEVEL
);
2664 log(" more visibility and generate more code, but do not pessimize evaluation.\n");
2667 log(" no debug information.\n");
2670 log(" debug information for non-optimized public wires. this also makes it\n");
2671 log(" possible to use the C API.\n");
2675 void execute(std::ostream
*&f
, std::string filename
, std::vector
<std::string
> args
, RTLIL::Design
*design
) override
2677 bool nohierarchy
= false;
2678 bool noflatten
= false;
2679 bool noproc
= false;
2680 int opt_level
= DEFAULT_OPT_LEVEL
;
2681 int debug_level
= DEFAULT_DEBUG_LEVEL
;
2682 CxxrtlWorker worker
;
2684 log_header(design
, "Executing CXXRTL backend.\n");
2687 for (argidx
= 1; argidx
< args
.size(); argidx
++)
2689 if (args
[argidx
] == "-nohierarchy") {
2693 if (args
[argidx
] == "-noflatten") {
2697 if (args
[argidx
] == "-noproc") {
2701 if (args
[argidx
] == "-Og") {
2702 opt_level
= OPT_LEVEL_DEBUG
;
2705 if (args
[argidx
] == "-O" && argidx
+1 < args
.size() && args
[argidx
+1] == "g") {
2707 opt_level
= OPT_LEVEL_DEBUG
;
2710 if (args
[argidx
] == "-O" && argidx
+1 < args
.size()) {
2711 opt_level
= std::stoi(args
[++argidx
]);
2714 if (args
[argidx
].substr(0, 2) == "-O" && args
[argidx
].size() == 3 && isdigit(args
[argidx
][2])) {
2715 opt_level
= std::stoi(args
[argidx
].substr(2));
2718 if (args
[argidx
] == "-g" && argidx
+1 < args
.size()) {
2719 debug_level
= std::stoi(args
[++argidx
]);
2722 if (args
[argidx
].substr(0, 2) == "-g" && args
[argidx
].size() == 3 && isdigit(args
[argidx
][2])) {
2723 debug_level
= std::stoi(args
[argidx
].substr(2));
2726 if (args
[argidx
] == "-header") {
2727 worker
.split_intf
= true;
2730 if (args
[argidx
] == "-namespace" && argidx
+1 < args
.size()) {
2731 worker
.design_ns
= args
[++argidx
];
2736 extra_args(f
, filename
, args
, argidx
);
2738 worker
.run_hierarchy
= !nohierarchy
;
2739 worker
.run_flatten
= !noflatten
;
2740 worker
.run_proc
= !noproc
;
2741 switch (opt_level
) {
2742 // the highest level here must match DEFAULT_OPT_LEVEL
2744 worker
.elide_public
= true;
2747 worker
.localize_public
= true;
2750 worker
.unbuffer_public
= true;
2753 worker
.elide_internal
= true;
2756 worker
.localize_internal
= true;
2759 worker
.unbuffer_internal
= true;
2764 log_cmd_error("Invalid optimization level %d.\n", opt_level
);
2766 switch (debug_level
) {
2767 // the highest level here must match DEFAULT_DEBUG_LEVEL
2769 worker
.debug_info
= true;
2774 log_cmd_error("Invalid debug information level %d.\n", debug_level
);
2777 std::ofstream intf_f
;
2778 if (worker
.split_intf
) {
2779 if (filename
== "<stdout>")
2780 log_cmd_error("Option -header must be used with a filename.\n");
2782 worker
.intf_filename
= filename
.substr(0, filename
.rfind('.')) + ".h";
2783 intf_f
.open(worker
.intf_filename
, std::ofstream::trunc
);
2785 log_cmd_error("Can't open file `%s' for writing: %s\n",
2786 worker
.intf_filename
.c_str(), strerror(errno
));
2788 worker
.intf_f
= &intf_f
;
2792 worker
.prepare_design(design
);
2793 worker
.dump_design(design
);
2797 PRIVATE_NAMESPACE_END