2 * yosys -- Yosys Open SYnthesis Suite
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * 2019 Eddie Hung <eddie@fpgeh.com>
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification
23 // http://www.eecs.berkeley.edu/~alanmi/abc/
26 // Based on &flow3 - better QoR but more experimental
27 #define ABC_COMMAND_LUT "&st; &ps -l; "/*"&sweep -v;"*/" &scorr; " \
28 "&st; &if {W}; &save; &st; &syn2; &if {W}; &save; &load; "\
29 "&st; &if -g -K 6; &dch -f; &if {W}; &save; &load; "\
30 "&st; &if -g -K 6; &synch2; &if {W}; &save; &load"
32 #define ABC_COMMAND_LUT "&st; &scorr; &sweep; &dc2; &st; &dch -f; &ps -l; &if {W} {D} -v; "/*"&mfs; "*/"&ps -l"
36 #define ABC_FAST_COMMAND_LUT "&st; &retime; &if {W}"
38 #include "kernel/register.h"
39 #include "kernel/sigtools.h"
40 #include "kernel/celltypes.h"
41 #include "kernel/cost.h"
42 #include "kernel/log.h"
55 #include "frontends/aiger/aigerparse.h"
58 extern "C" int Abc_RealMain(int argc
, char *argv
[]);
62 PRIVATE_NAMESPACE_BEGIN
67 RTLIL::Module
*module
;
69 bool clk_polarity
, en_polarity
;
70 RTLIL::SigSpec clk_sig
, en_sig
;
72 std::string
remap_name(RTLIL::IdString abc_name
)
74 std::stringstream sstr
;
75 sstr
<< "$abc$" << map_autoidx
<< "$" << abc_name
.substr(1);
79 void handle_loops(RTLIL::Design
*design
)
81 Pass::call(design
, "scc -set_attr abc_scc_id {}");
83 dict
<IdString
, vector
<IdString
>> module_break
;
85 // For every unique SCC found, (arbitrarily) find the first
86 // cell in the component, and select (and mark) all its output
88 pool
<RTLIL::Const
> ids_seen
;
89 for (auto cell
: module
->cells()) {
90 auto it
= cell
->attributes
.find("\\abc_scc_id");
91 if (it
!= cell
->attributes
.end()) {
92 auto r
= ids_seen
.insert(it
->second
);
94 for (auto &c
: cell
->connections_
) {
95 if (c
.second
.is_fully_const()) continue;
96 if (cell
->output(c
.first
)) {
97 SigBit b
= c
.second
.as_bit();
99 log_assert(!w
->port_input
);
100 w
->port_input
= true;
101 w
= module
->wire(stringf("%s.abci", w
->name
.c_str()));
103 w
= module
->addWire(stringf("%s.abci", b
.wire
->name
.c_str()), GetSize(b
.wire
));
104 w
->port_output
= true;
107 log_assert(w
->port_input
);
108 log_assert(b
.offset
< GetSize(w
));
110 w
->set_bool_attribute("\\abc_scc_break");
111 module
->swap_names(b
.wire
, w
);
112 c
.second
= RTLIL::SigBit(w
, b
.offset
);
116 cell
->attributes
.erase(it
);
119 auto jt
= module_break
.find(cell
->type
);
120 if (jt
== module_break
.end()) {
121 std::vector
<IdString
> ports
;
122 if (!yosys_celltypes
.cell_known(cell
->type
)) {
123 RTLIL::Module
* box_module
= design
->module(cell
->type
);
124 log_assert(box_module
);
125 auto ports_csv
= box_module
->attributes
.at("\\abc_scc_break", RTLIL::Const::from_string("")).decode_string();
126 for (const auto &port_name
: split_tokens(ports_csv
, ",")) {
127 auto port_id
= RTLIL::escape_id(port_name
);
128 auto kt
= cell
->connections_
.find(port_id
);
129 if (kt
== cell
->connections_
.end())
130 log_error("abc_scc_break attribute value '%s' does not exist as port on module '%s'\n", port_name
.c_str(), log_id(box_module
));
131 ports
.push_back(port_id
);
134 jt
= module_break
.insert(std::make_pair(cell
->type
, std::move(ports
))).first
;
137 for (auto port_name
: jt
->second
) {
139 auto &rhs
= cell
->connections_
.at(port_name
);
143 w
->port_output
= true;
144 w
->set_bool_attribute("\\abc_scc_break");
145 w
= module
->wire(stringf("%s.abci", w
->name
.c_str()));
147 w
= module
->addWire(stringf("%s.abci", b
.wire
->name
.c_str()), GetSize(b
.wire
));
148 w
->port_input
= true;
151 log_assert(b
.offset
< GetSize(w
));
152 log_assert(w
->port_input
);
154 sig
.append(RTLIL::SigBit(w
, b
.offset
));
160 module
->fixup_ports();
163 std::string
add_echos_to_abc_cmd(std::string str
)
165 std::string new_str
, token
;
166 for (size_t i
= 0; i
< str
.size(); i
++) {
169 while (i
+1 < str
.size() && str
[i
+1] == ' ')
171 new_str
+= "echo + " + token
+ " " + token
+ " ";
176 if (!token
.empty()) {
177 if (!new_str
.empty())
178 new_str
+= "echo + " + token
+ "; ";
185 std::string
fold_abc_cmd(std::string str
)
187 std::string token
, new_str
= " ";
188 int char_counter
= 10;
190 for (size_t i
= 0; i
<= str
.size(); i
++) {
193 if (i
== str
.size() || str
[i
] == ';') {
194 if (char_counter
+ token
.size() > 75)
195 new_str
+= "\n ", char_counter
= 14;
196 new_str
+= token
, char_counter
+= token
.size();
204 std::string
replace_tempdir(std::string text
, std::string tempdir_name
, bool show_tempdir
)
210 size_t pos
= text
.find(tempdir_name
);
211 if (pos
== std::string::npos
)
213 text
= text
.substr(0, pos
) + "<abc-temp-dir>" + text
.substr(pos
+ GetSize(tempdir_name
));
216 std::string selfdir_name
= proc_self_dirname();
217 if (selfdir_name
!= "/") {
219 size_t pos
= text
.find(selfdir_name
);
220 if (pos
== std::string::npos
)
222 text
= text
.substr(0, pos
) + "<yosys-exe-dir>/" + text
.substr(pos
+ GetSize(selfdir_name
));
229 struct abc_output_filter
232 int escape_seq_state
;
234 std::string tempdir_name
;
237 abc_output_filter(std::string tempdir_name
, bool show_tempdir
) : tempdir_name(tempdir_name
), show_tempdir(show_tempdir
)
240 escape_seq_state
= 0;
243 void next_char(char ch
)
245 if (escape_seq_state
== 0 && ch
== '\033') {
246 escape_seq_state
= 1;
249 if (escape_seq_state
== 1) {
250 escape_seq_state
= ch
== '[' ? 2 : 0;
253 if (escape_seq_state
== 2) {
254 if ((ch
< '0' || '9' < ch
) && ch
!= ';')
255 escape_seq_state
= 0;
258 escape_seq_state
= 0;
264 log("ABC: %s\n", replace_tempdir(linebuf
, tempdir_name
, show_tempdir
).c_str());
265 got_cr
= false, linebuf
.clear();
269 got_cr
= false, linebuf
.clear();
273 void next_line(const std::string
&line
)
276 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
277 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
278 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
279 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
288 void abc9_module(RTLIL::Design
*design
, RTLIL::Module
*current_module
, std::string script_file
, std::string exe_file
,
289 bool cleanup
, vector
<int> lut_costs
, bool dff_mode
, std::string clk_str
,
290 bool /*keepff*/, std::string delay_target
, std::string
/*lutin_shared*/, bool fast_mode
,
291 bool show_tempdir
, std::string box_file
, std::string lut_file
,
292 std::string wire_delay
)
294 module
= current_module
;
295 map_autoidx
= autoidx
++;
300 clk_sig
= RTLIL::SigSpec();
303 en_sig
= RTLIL::SigSpec();
306 if (!clk_str
.empty() && clk_str
!= "$")
308 if (clk_str
.find(',') != std::string::npos
) {
309 int pos
= clk_str
.find(',');
310 std::string en_str
= clk_str
.substr(pos
+1);
311 clk_str
= clk_str
.substr(0, pos
);
312 if (en_str
[0] == '!') {
314 en_str
= en_str
.substr(1);
316 if (module
->wires_
.count(RTLIL::escape_id(en_str
)) != 0)
317 en_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(en_str
)), 0));
319 if (clk_str
[0] == '!') {
320 clk_polarity
= false;
321 clk_str
= clk_str
.substr(1);
323 if (module
->wires_
.count(RTLIL::escape_id(clk_str
)) != 0)
324 clk_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(clk_str
)), 0));
327 if (dff_mode
&& clk_sig
.empty())
328 log_cmd_error("Clock domain %s not found.\n", clk_str
.c_str());
330 std::string tempdir_name
= "/tmp/yosys-abc-XXXXXX";
332 tempdir_name
[0] = tempdir_name
[4] = '_';
333 tempdir_name
= make_temp_dir(tempdir_name
);
334 log_header(design
, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
335 module
->name
.c_str(), replace_tempdir(tempdir_name
, tempdir_name
, show_tempdir
).c_str());
337 std::string abc_script
;
339 if (!lut_costs
.empty()) {
340 abc_script
+= stringf("read_lut %s/lutdefs.txt; ", tempdir_name
.c_str());
341 if (!box_file
.empty())
342 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
345 if (!lut_file
.empty()) {
346 abc_script
+= stringf("read_lut %s; ", lut_file
.c_str());
347 if (!box_file
.empty())
348 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
353 abc_script
+= stringf("&read %s/input.xaig; &ps; ", tempdir_name
.c_str());
355 if (!script_file
.empty()) {
356 if (script_file
[0] == '+') {
357 for (size_t i
= 1; i
< script_file
.size(); i
++)
358 if (script_file
[i
] == '\'')
359 abc_script
+= "'\\''";
360 else if (script_file
[i
] == ',')
363 abc_script
+= script_file
[i
];
365 abc_script
+= stringf("source %s", script_file
.c_str());
366 } else if (!lut_costs
.empty() || !lut_file
.empty()) {
367 //bool all_luts_cost_same = true;
368 //for (int this_cost : lut_costs)
369 // if (this_cost != lut_costs.front())
370 // all_luts_cost_same = false;
371 abc_script
+= fast_mode
? ABC_FAST_COMMAND_LUT
: ABC_COMMAND_LUT
;
372 //if (all_luts_cost_same && !fast_mode)
373 // abc_script += "; lutpack {S}";
377 //if (script_file.empty() && !delay_target.empty())
378 // for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
379 // abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
381 for (size_t pos
= abc_script
.find("{D}"); pos
!= std::string::npos
; pos
= abc_script
.find("{D}", pos
))
382 abc_script
= abc_script
.substr(0, pos
) + delay_target
+ abc_script
.substr(pos
+3);
384 //for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
385 // abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
387 for (size_t pos
= abc_script
.find("{W}"); pos
!= std::string::npos
; pos
= abc_script
.find("{W}", pos
))
388 abc_script
= abc_script
.substr(0, pos
) + wire_delay
+ abc_script
.substr(pos
+3);
390 abc_script
+= stringf("; &write %s/output.aig", tempdir_name
.c_str());
391 abc_script
= add_echos_to_abc_cmd(abc_script
);
393 for (size_t i
= 0; i
+1 < abc_script
.size(); i
++)
394 if (abc_script
[i
] == ';' && abc_script
[i
+1] == ' ')
395 abc_script
[i
+1] = '\n';
397 FILE *f
= fopen(stringf("%s/abc.script", tempdir_name
.c_str()).c_str(), "wt");
398 fprintf(f
, "%s\n", abc_script
.c_str());
401 if (dff_mode
|| !clk_str
.empty())
403 if (clk_sig
.size() == 0)
404 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str
.empty() ? "" : " matching");
406 log("Found%s %s clock domain: %s", clk_str
.empty() ? "" : " matching", clk_polarity
? "posedge" : "negedge", log_signal(clk_sig
));
407 if (en_sig
.size() != 0)
408 log(", enabled by %s%s", en_polarity
? "" : "!", log_signal(en_sig
));
413 bool count_output
= false;
414 for (auto port_name
: module
->ports
) {
415 RTLIL::Wire
*port_wire
= module
->wire(port_name
);
416 log_assert(port_wire
);
417 if (port_wire
->port_output
) {
427 design
->selection_stack
.emplace_back(false);
428 RTLIL::Selection
& sel
= design
->selection_stack
.back();
431 Pass::call(design
, "aigmap");
433 handle_loops(design
);
435 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
436 // count_gates, GetSize(signal_list), count_input, count_output);
438 Pass::call(design
, stringf("write_xaiger -map %s/input.sym %s/input.xaig", tempdir_name
.c_str(), tempdir_name
.c_str()));
443 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.xaig");
446 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
447 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
448 log_assert(!design
->module("$__abc9__"));
450 AigerReader
reader(design
, ifs
, "$__abc9__", "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
451 reader
.parse_xaiger();
454 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
455 design
->remove(design
->module("$__abc9__"));
458 design
->selection_stack
.pop_back();
460 // Now 'unexpose' those wires by undoing
461 // the expose operation -- remove them from PO/PI
462 // and re-connecting them back together
463 for (auto wire
: module
->wires()) {
464 auto it
= wire
->attributes
.find("\\abc_scc_break");
465 if (it
!= wire
->attributes
.end()) {
466 wire
->attributes
.erase(it
);
467 log_assert(wire
->port_output
);
468 wire
->port_output
= false;
469 RTLIL::Wire
*i_wire
= module
->wire(wire
->name
.str() + ".abci");
471 log_assert(i_wire
->port_input
);
472 i_wire
->port_input
= false;
473 module
->connect(i_wire
, wire
);
476 module
->fixup_ports();
479 log_header(design
, "Executing ABC9.\n");
481 if (!lut_costs
.empty()) {
482 buffer
= stringf("%s/lutdefs.txt", tempdir_name
.c_str());
483 f
= fopen(buffer
.c_str(), "wt");
485 log_error("Opening %s for writing failed: %s\n", buffer
.c_str(), strerror(errno
));
486 for (int i
= 0; i
< GetSize(lut_costs
); i
++)
487 fprintf(f
, "%d %d.00 1.00\n", i
+1, lut_costs
.at(i
));
491 buffer
= stringf("%s -s -f %s/abc.script 2>&1", exe_file
.c_str(), tempdir_name
.c_str());
492 log("Running ABC command: %s\n", replace_tempdir(buffer
, tempdir_name
, show_tempdir
).c_str());
494 #ifndef YOSYS_LINK_ABC
495 abc_output_filter
filt(tempdir_name
, show_tempdir
);
496 int ret
= run_command(buffer
, std::bind(&abc_output_filter::next_line
, filt
, std::placeholders::_1
));
498 // These needs to be mutable, supposedly due to getopt
500 string tmp_script_name
= stringf("%s/abc.script", tempdir_name
.c_str());
501 abc_argv
[0] = strdup(exe_file
.c_str());
502 abc_argv
[1] = strdup("-s");
503 abc_argv
[2] = strdup("-f");
504 abc_argv
[3] = strdup(tmp_script_name
.c_str());
506 int ret
= Abc_RealMain(4, abc_argv
);
513 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer
.c_str(), ret
);
515 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "output.aig");
518 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
520 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
521 log_assert(!design
->module("$__abc9__"));
522 AigerReader
reader(design
, ifs
, "$__abc9__", "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
523 reader
.parse_xaiger();
527 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
530 log_header(design
, "Re-integrating ABC9 results.\n");
531 RTLIL::Module
*mapped_mod
= design
->module("$__abc9__");
532 if (mapped_mod
== NULL
)
533 log_error("ABC output file does not contain a module `$__abc9__'.\n");
535 pool
<RTLIL::SigBit
> output_bits
;
536 for (auto &it
: mapped_mod
->wires_
) {
537 RTLIL::Wire
*w
= it
.second
;
538 RTLIL::Wire
*remap_wire
= module
->addWire(remap_name(w
->name
), GetSize(w
));
539 if (markgroups
) remap_wire
->attributes
["\\abcgroup"] = map_autoidx
;
540 if (w
->port_output
) {
541 RTLIL::Wire
*wire
= module
->wire(w
->name
);
543 for (int i
= 0; i
< GetSize(w
); i
++)
544 output_bits
.insert({wire
, i
});
548 for (auto &it
: module
->connections_
) {
549 auto &signal
= it
.first
;
550 auto bits
= signal
.bits();
552 if (output_bits
.count(b
))
553 b
= module
->addWire(NEW_ID
);
554 signal
= std::move(bits
);
557 vector
<RTLIL::Cell
*> boxes
;
558 for (auto it
= module
->cells_
.begin(); it
!= module
->cells_
.end(); ) {
559 RTLIL::Cell
* cell
= it
->second
;
560 if (cell
->type
.in("$_AND_", "$_NOT_", "$__ABC_FF_")) {
561 it
= module
->remove(it
);
564 RTLIL::Module
* box_module
= design
->module(cell
->type
);
565 if (box_module
&& box_module
->attributes
.count("\\abc_box_id"))
566 boxes
.emplace_back(it
->second
);
570 std::map
<std::string
, int> cell_stats
;
571 for (auto c
: mapped_mod
->cells())
573 RTLIL::Cell
*cell
= nullptr;
574 if (c
->type
== "$_NOT_") {
575 RTLIL::SigBit a_bit
= c
->getPort("\\A").as_bit();
576 RTLIL::SigBit y_bit
= c
->getPort("\\Y").as_bit();
578 c
->setPort("\\Y", module
->addWire(NEW_ID
));
579 RTLIL::Wire
*wire
= module
->wire(remap_name(y_bit
.wire
->name
));
581 module
->connect(RTLIL::SigBit(wire
, y_bit
.offset
), RTLIL::S1
);
583 else if (!lut_costs
.empty() || !lut_file
.empty()) {
584 RTLIL::Cell
* driving_lut
= nullptr;
585 // ABC can return NOT gates that drive POs
586 if (!a_bit
.wire
->port_input
) {
587 // If it's not a NOT gate that that comes from a PI directly,
588 // find the driving LUT and clone that to guarantee that we won't
589 // increase the max logic depth
590 // (TODO: Optimise by not cloning unless will increase depth)
591 RTLIL::IdString driver_name
;
592 if (GetSize(a_bit
.wire
) == 1)
593 driver_name
= stringf("%s$lut", a_bit
.wire
->name
.c_str());
595 driver_name
= stringf("%s[%d]$lut", a_bit
.wire
->name
.c_str(), a_bit
.offset
);
596 driving_lut
= mapped_mod
->cell(driver_name
);
600 // If a driver couldn't be found (could be from PI,
601 // or from a box) then implement using a LUT
602 cell
= module
->addLut(remap_name(stringf("%s$lut", c
->name
.c_str())),
603 RTLIL::SigBit(module
->wires_
[remap_name(a_bit
.wire
->name
)], a_bit
.offset
),
604 RTLIL::SigBit(module
->wires_
[remap_name(y_bit
.wire
->name
)], y_bit
.offset
),
608 auto driver_a
= driving_lut
->getPort("\\A").chunks();
609 for (auto &chunk
: driver_a
)
610 chunk
.wire
= module
->wires_
[remap_name(chunk
.wire
->name
)];
611 RTLIL::Const driver_lut
= driving_lut
->getParam("\\LUT");
612 for (auto &b
: driver_lut
.bits
) {
613 if (b
== RTLIL::State::S0
) b
= RTLIL::State::S1
;
614 else if (b
== RTLIL::State::S1
) b
= RTLIL::State::S0
;
616 cell
= module
->addLut(remap_name(stringf("%s$lut", c
->name
.c_str())),
618 RTLIL::SigBit(module
->wires_
[remap_name(y_bit
.wire
->name
)], y_bit
.offset
),
623 cell
= module
->addCell(remap_name(c
->name
), "$_NOT_");
624 cell
->setPort("\\A", RTLIL::SigBit(module
->wires_
[remap_name(a_bit
.wire
->name
)], a_bit
.offset
));
625 cell
->setPort("\\Y", RTLIL::SigBit(module
->wires_
[remap_name(y_bit
.wire
->name
)], y_bit
.offset
));
626 cell_stats
[RTLIL::unescape_id(c
->type
)]++;
628 if (cell
&& markgroups
) cell
->attributes
["\\abcgroup"] = map_autoidx
;
631 cell_stats
[RTLIL::unescape_id(c
->type
)]++;
633 RTLIL::Cell
*existing_cell
= nullptr;
634 if (c
->type
== "$lut") {
635 if (GetSize(c
->getPort("\\A")) == 1 && c
->getParam("\\LUT").as_int() == 2) {
636 SigSpec my_a
= module
->wires_
[remap_name(c
->getPort("\\A").as_wire()->name
)];
637 SigSpec my_y
= module
->wires_
[remap_name(c
->getPort("\\Y").as_wire()->name
)];
638 module
->connect(my_y
, my_a
);
639 if (markgroups
) c
->attributes
["\\abcgroup"] = map_autoidx
;
642 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
645 existing_cell
= module
->cell(c
->name
);
646 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
647 module
->swap_names(cell
, existing_cell
);
650 if (markgroups
) cell
->attributes
["\\abcgroup"] = map_autoidx
;
652 cell
->parameters
= existing_cell
->parameters
;
653 cell
->attributes
= existing_cell
->attributes
;
656 cell
->parameters
= c
->parameters
;
657 cell
->attributes
= c
->attributes
;
659 for (auto &conn
: c
->connections()) {
660 RTLIL::SigSpec newsig
;
661 for (auto c
: conn
.second
.chunks()) {
664 //log_assert(c.width == 1);
666 c
.wire
= module
->wires_
[remap_name(c
.wire
->name
)];
669 cell
->setPort(conn
.first
, newsig
);
673 for (auto cell
: boxes
)
674 module
->remove(cell
);
676 // Copy connections (and rename) from mapped_mod to module
677 for (auto conn
: mapped_mod
->connections()) {
678 if (!conn
.first
.is_fully_const()) {
679 auto chunks
= conn
.first
.chunks();
680 for (auto &c
: chunks
)
681 c
.wire
= module
->wires_
[remap_name(c
.wire
->name
)];
682 conn
.first
= std::move(chunks
);
684 if (!conn
.second
.is_fully_const()) {
685 auto chunks
= conn
.second
.chunks();
686 for (auto &c
: chunks
)
688 c
.wire
= module
->wires_
[remap_name(c
.wire
->name
)];
689 conn
.second
= std::move(chunks
);
691 module
->connect(conn
);
694 for (auto &it
: cell_stats
)
695 log("ABC RESULTS: %15s cells: %8d\n", it
.first
.c_str(), it
.second
);
696 int in_wires
= 0, out_wires
= 0;
698 // Stitch in mapped_mod's inputs/outputs into module
699 for (auto &it
: mapped_mod
->wires_
) {
700 RTLIL::Wire
*w
= it
.second
;
701 if (!w
->port_input
&& !w
->port_output
)
703 RTLIL::Wire
*wire
= module
->wire(w
->name
);
705 RTLIL::Wire
*remap_wire
= module
->wire(remap_name(w
->name
));
706 RTLIL::SigSpec signal
= RTLIL::SigSpec(wire
, 0, GetSize(remap_wire
));
707 log_assert(GetSize(signal
) >= GetSize(remap_wire
));
709 log_assert(w
->port_input
|| w
->port_output
);
712 conn
.first
= remap_wire
;
713 conn
.second
= signal
;
715 module
->connect(conn
);
717 if (w
->port_output
) {
719 conn
.second
= remap_wire
;
721 module
->connect(conn
);
725 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
726 log("ABC RESULTS: input signals: %8d\n", in_wires
);
727 log("ABC RESULTS: output signals: %8d\n", out_wires
);
729 design
->remove(mapped_mod
);
733 log("Don't call ABC as there is nothing to map.\n");
738 log("Removing temp directory.\n");
739 remove_directory(tempdir_name
);
745 struct Abc9Pass
: public Pass
{
746 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
747 void help() YS_OVERRIDE
749 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
751 log(" abc9 [options] [selection]\n");
753 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
754 log("library to a target architecture.\n");
756 log(" -exe <command>\n");
758 log(" use the specified command instead of \"" ABCEXTERNAL
"\" to execute ABC.\n");
760 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
762 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
764 log(" -script <file>\n");
765 log(" use the specified ABC script file instead of the default script.\n");
767 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
768 log(" string is interpreted as the command string to be passed to ABC. The\n");
769 log(" leading plus sign is removed and all commas (,) in the string are\n");
770 log(" replaced with blanks before the string is passed to ABC.\n");
772 log(" if no -script parameter is given, the following scripts are used:\n");
774 log(" for -lut/-luts (only one LUT size):\n");
775 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
/*"; lutpack {S}"*/).c_str());
777 log(" for -lut/-luts (different LUT sizes):\n");
778 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
).c_str());
781 log(" use different default scripts that are slightly faster (at the cost\n");
782 log(" of output quality):\n");
784 log(" for -lut/-luts:\n");
785 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT
).c_str());
787 log(" -D <picoseconds>\n");
788 log(" set delay target. the string {D} in the default scripts above is\n");
789 log(" replaced by this option when used, and an empty string otherwise\n");
790 log(" (indicating best possible delay).\n");
791 // log(" This also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
792 // log(" default scripts above.\n");
794 // log(" -S <num>\n");
795 // log(" maximum number of LUT inputs shared.\n");
796 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
798 log(" -lut <width>\n");
799 log(" generate netlist using luts of (max) the specified width.\n");
801 log(" -lut <w1>:<w2>\n");
802 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
803 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
804 log(" the area cost doubles with each additional input bit. the delay cost\n");
805 log(" is still constant for all lut widths.\n");
807 log(" -lut <file>\n");
808 log(" pass this file with lut library to ABC.\n");
810 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
811 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
812 log(" 2, 3, .. inputs.\n");
815 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
816 // log(" clock domains are automatically partitioned in clock domains and each\n");
817 // log(" domain is passed through ABC independently.\n");
819 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
820 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
821 // log(" cells that belong to the specified clock domain are used.\n");
823 // log(" -keepff\n");
824 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
825 // log(" them, for example for equivalence checking.)\n");
827 log(" -nocleanup\n");
828 log(" when this option is used, the temporary files created by this pass\n");
829 log(" are not removed. this is useful for debugging.\n");
832 log(" print the temp dir name in log. usually this is suppressed so that the\n");
833 log(" command output is identical across runs.\n");
835 log(" -markgroups\n");
836 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
837 log(" this attribute is a unique integer for each ABC process started. This\n");
838 log(" is useful for debugging the partitioning of clock domains.\n");
840 log(" -box <file>\n");
841 log(" pass this file with box library to ABC. Use with -lut.\n");
843 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
844 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
845 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
846 log("output when passing an ABC script that writes a file. Instead write your full\n");
847 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
848 log("you want to use ABC to convert your design into another format.\n");
850 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
853 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
855 log_header(design
, "Executing ABC9 pass (technology mapping using ABC9).\n");
861 std::string exe_file
= ABCEXTERNAL
;
863 std::string exe_file
= proc_self_dirname() + "yosys-abc";
865 std::string script_file
, clk_str
, box_file
, lut_file
;
866 std::string delay_target
, lutin_shared
= "-S 1", wire_delay
;
867 bool fast_mode
= false, dff_mode
= false, keepff
= false, cleanup
= true;
868 bool show_tempdir
= false;
869 vector
<int> lut_costs
;
879 if (!check_file_exists(exe_file
+ ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
880 exe_file
= proc_self_dirname() + "..\\yosys-abc";
886 if (!getcwd(pwd
, sizeof(pwd
))) {
887 log_cmd_error("getcwd failed: %s\n", strerror(errno
));
890 for (argidx
= 1; argidx
< args
.size(); argidx
++) {
891 std::string arg
= args
[argidx
];
892 if (arg
== "-exe" && argidx
+1 < args
.size()) {
893 exe_file
= args
[++argidx
];
896 if (arg
== "-script" && argidx
+1 < args
.size()) {
897 script_file
= args
[++argidx
];
898 rewrite_filename(script_file
);
899 if (!script_file
.empty() && !is_absolute_path(script_file
) && script_file
[0] != '+')
900 script_file
= std::string(pwd
) + "/" + script_file
;
903 if (arg
== "-D" && argidx
+1 < args
.size()) {
904 delay_target
= "-D " + args
[++argidx
];
907 //if (arg == "-S" && argidx+1 < args.size()) {
908 // lutin_shared = "-S " + args[++argidx];
911 if (arg
== "-lut" && argidx
+1 < args
.size()) {
912 string arg
= args
[++argidx
];
913 size_t pos
= arg
.find_first_of(':');
914 int lut_mode
= 0, lut_mode2
= 0;
915 if (pos
!= string::npos
) {
916 lut_mode
= atoi(arg
.substr(0, pos
).c_str());
917 lut_mode2
= atoi(arg
.substr(pos
+1).c_str());
919 pos
= arg
.find_first_of('.');
920 if (pos
!= string::npos
) {
922 rewrite_filename(lut_file
);
923 if (!lut_file
.empty() && !is_absolute_path(lut_file
))
924 lut_file
= std::string(pwd
) + "/" + lut_file
;
927 lut_mode
= atoi(arg
.c_str());
928 lut_mode2
= lut_mode
;
932 for (int i
= 0; i
< lut_mode
; i
++)
933 lut_costs
.push_back(1);
934 for (int i
= lut_mode
; i
< lut_mode2
; i
++)
935 lut_costs
.push_back(2 << (i
- lut_mode
));
938 if (arg
== "-luts" && argidx
+1 < args
.size()) {
940 for (auto &tok
: split_tokens(args
[++argidx
], ",")) {
941 auto parts
= split_tokens(tok
, ":");
942 if (GetSize(parts
) == 0 && !lut_costs
.empty())
943 lut_costs
.push_back(lut_costs
.back());
944 else if (GetSize(parts
) == 1)
945 lut_costs
.push_back(atoi(parts
.at(0).c_str()));
946 else if (GetSize(parts
) == 2)
947 while (GetSize(lut_costs
) < atoi(parts
.at(0).c_str()))
948 lut_costs
.push_back(atoi(parts
.at(1).c_str()));
950 log_cmd_error("Invalid -luts syntax.\n");
954 if (arg
== "-fast") {
958 //if (arg == "-dff") {
962 //if (arg == "-clk" && argidx+1 < args.size()) {
963 // clk_str = args[++argidx];
967 //if (arg == "-keepff") {
971 if (arg
== "-nocleanup") {
975 if (arg
== "-showtmp") {
979 if (arg
== "-markgroups") {
983 if (arg
== "-box" && argidx
+1 < args
.size()) {
984 box_file
= args
[++argidx
];
985 rewrite_filename(box_file
);
986 if (!box_file
.empty() && !is_absolute_path(box_file
))
987 box_file
= std::string(pwd
) + "/" + box_file
;
990 if (arg
== "-W" && argidx
+1 < args
.size()) {
991 wire_delay
= "-W " + args
[++argidx
];
996 extra_args(args
, argidx
, design
);
998 for (auto mod
: design
->selected_modules())
1000 if (mod
->attributes
.count("\\abc_box_id"))
1003 if (mod
->processes
.size() > 0) {
1004 log("Skipping module %s as it contains processes.\n", log_id(mod
));
1008 assign_map
.set(mod
);
1010 if (!dff_mode
|| !clk_str
.empty()) {
1011 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, dff_mode
, clk_str
, keepff
,
1012 delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1013 box_file
, lut_file
, wire_delay
);
1017 CellTypes
ct(design
);
1019 std::vector
<RTLIL::Cell
*> all_cells
= mod
->selected_cells();
1020 std::set
<RTLIL::Cell
*> unassigned_cells(all_cells
.begin(), all_cells
.end());
1022 std::set
<RTLIL::Cell
*> expand_queue
, next_expand_queue
;
1023 std::set
<RTLIL::Cell
*> expand_queue_up
, next_expand_queue_up
;
1024 std::set
<RTLIL::Cell
*> expand_queue_down
, next_expand_queue_down
;
1026 typedef tuple
<bool, RTLIL::SigSpec
, bool, RTLIL::SigSpec
> clkdomain_t
;
1027 std::map
<clkdomain_t
, std::vector
<RTLIL::Cell
*>> assigned_cells
;
1028 std::map
<RTLIL::Cell
*, clkdomain_t
> assigned_cells_reverse
;
1030 std::map
<RTLIL::Cell
*, std::set
<RTLIL::SigBit
>> cell_to_bit
, cell_to_bit_up
, cell_to_bit_down
;
1031 std::map
<RTLIL::SigBit
, std::set
<RTLIL::Cell
*>> bit_to_cell
, bit_to_cell_up
, bit_to_cell_down
;
1033 for (auto cell
: all_cells
)
1037 for (auto &conn
: cell
->connections())
1038 for (auto bit
: conn
.second
) {
1039 bit
= assign_map(bit
);
1040 if (bit
.wire
!= nullptr) {
1041 cell_to_bit
[cell
].insert(bit
);
1042 bit_to_cell
[bit
].insert(cell
);
1043 if (ct
.cell_input(cell
->type
, conn
.first
)) {
1044 cell_to_bit_up
[cell
].insert(bit
);
1045 bit_to_cell_down
[bit
].insert(cell
);
1047 if (ct
.cell_output(cell
->type
, conn
.first
)) {
1048 cell_to_bit_down
[cell
].insert(bit
);
1049 bit_to_cell_up
[bit
].insert(cell
);
1054 if (cell
->type
== "$_DFF_N_" || cell
->type
== "$_DFF_P_")
1056 key
= clkdomain_t(cell
->type
== "$_DFF_P_", assign_map(cell
->getPort("\\C")), true, RTLIL::SigSpec());
1059 if (cell
->type
== "$_DFFE_NN_" || cell
->type
== "$_DFFE_NP_" || cell
->type
== "$_DFFE_PN_" || cell
->type
== "$_DFFE_PP_")
1061 bool this_clk_pol
= cell
->type
== "$_DFFE_PN_" || cell
->type
== "$_DFFE_PP_";
1062 bool this_en_pol
= cell
->type
== "$_DFFE_NP_" || cell
->type
== "$_DFFE_PP_";
1063 key
= clkdomain_t(this_clk_pol
, assign_map(cell
->getPort("\\C")), this_en_pol
, assign_map(cell
->getPort("\\E")));
1068 unassigned_cells
.erase(cell
);
1069 expand_queue
.insert(cell
);
1070 expand_queue_up
.insert(cell
);
1071 expand_queue_down
.insert(cell
);
1073 assigned_cells
[key
].push_back(cell
);
1074 assigned_cells_reverse
[cell
] = key
;
1077 while (!expand_queue_up
.empty() || !expand_queue_down
.empty())
1079 if (!expand_queue_up
.empty())
1081 RTLIL::Cell
*cell
= *expand_queue_up
.begin();
1082 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1083 expand_queue_up
.erase(cell
);
1085 for (auto bit
: cell_to_bit_up
[cell
])
1086 for (auto c
: bit_to_cell_up
[bit
])
1087 if (unassigned_cells
.count(c
)) {
1088 unassigned_cells
.erase(c
);
1089 next_expand_queue_up
.insert(c
);
1090 assigned_cells
[key
].push_back(c
);
1091 assigned_cells_reverse
[c
] = key
;
1092 expand_queue
.insert(c
);
1096 if (!expand_queue_down
.empty())
1098 RTLIL::Cell
*cell
= *expand_queue_down
.begin();
1099 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1100 expand_queue_down
.erase(cell
);
1102 for (auto bit
: cell_to_bit_down
[cell
])
1103 for (auto c
: bit_to_cell_down
[bit
])
1104 if (unassigned_cells
.count(c
)) {
1105 unassigned_cells
.erase(c
);
1106 next_expand_queue_up
.insert(c
);
1107 assigned_cells
[key
].push_back(c
);
1108 assigned_cells_reverse
[c
] = key
;
1109 expand_queue
.insert(c
);
1113 if (expand_queue_up
.empty() && expand_queue_down
.empty()) {
1114 expand_queue_up
.swap(next_expand_queue_up
);
1115 expand_queue_down
.swap(next_expand_queue_down
);
1119 while (!expand_queue
.empty())
1121 RTLIL::Cell
*cell
= *expand_queue
.begin();
1122 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1123 expand_queue
.erase(cell
);
1125 for (auto bit
: cell_to_bit
.at(cell
)) {
1126 for (auto c
: bit_to_cell
[bit
])
1127 if (unassigned_cells
.count(c
)) {
1128 unassigned_cells
.erase(c
);
1129 next_expand_queue
.insert(c
);
1130 assigned_cells
[key
].push_back(c
);
1131 assigned_cells_reverse
[c
] = key
;
1133 bit_to_cell
[bit
].clear();
1136 if (expand_queue
.empty())
1137 expand_queue
.swap(next_expand_queue
);
1140 clkdomain_t
key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1141 for (auto cell
: unassigned_cells
) {
1142 assigned_cells
[key
].push_back(cell
);
1143 assigned_cells_reverse
[cell
] = key
;
1146 log_header(design
, "Summary of detected clock domains:\n");
1147 for (auto &it
: assigned_cells
)
1148 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it
.second
),
1149 std::get
<0>(it
.first
) ? "" : "!", log_signal(std::get
<1>(it
.first
)),
1150 std::get
<2>(it
.first
) ? "" : "!", log_signal(std::get
<3>(it
.first
)));
1152 for (auto &it
: assigned_cells
) {
1153 clk_polarity
= std::get
<0>(it
.first
);
1154 clk_sig
= assign_map(std::get
<1>(it
.first
));
1155 en_polarity
= std::get
<2>(it
.first
);
1156 en_sig
= assign_map(std::get
<3>(it
.first
));
1157 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, !clk_sig
.empty(), "$",
1158 keepff
, delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1159 box_file
, lut_file
, wire_delay
);
1160 assign_map
.set(mod
);
1164 Pass::call(design
, "clean");
1172 PRIVATE_NAMESPACE_END