36f2fafc35abc9cd3ccceaa868e2a4483b7d1852
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} -v; &save; &load; "\
29 "&st; &if -g -K 6; &dch -f; &if {W} -v; &save; &load; "\
30 "&st; &if -g -K 6; &synch2; &if {W} -v; &save; &load; "\
33 #define ABC_COMMAND_LUT "&st; &scorr; &sweep; &dc2; &st; &dch -f; &ps; &if {W} {D} -v; &mfs; &ps -l"
37 #define ABC_FAST_COMMAND_LUT "&st; &if {W} {D}"
39 #include "kernel/register.h"
40 #include "kernel/sigtools.h"
41 #include "kernel/celltypes.h"
42 #include "kernel/cost.h"
43 #include "kernel/log.h"
56 #include "frontends/aiger/aigerparse.h"
57 #include "kernel/utils.h"
60 extern "C" int Abc_RealMain(int argc
, char *argv
[]);
64 PRIVATE_NAMESPACE_BEGIN
69 RTLIL::Module
*module
;
71 bool clk_polarity
, en_polarity
;
72 RTLIL::SigSpec clk_sig
, en_sig
;
74 std::string
remap_name(RTLIL::IdString abc_name
)
76 std::stringstream sstr
;
77 sstr
<< "$abc$" << map_autoidx
<< "$" << abc_name
.substr(1);
81 void handle_loops(RTLIL::Design
*design
)
83 Pass::call(design
, "scc -set_attr abc_scc_id {}");
85 dict
<IdString
, vector
<IdString
>> abc_scc_break
;
87 // For every unique SCC found, (arbitrarily) find the first
88 // cell in the component, and select (and mark) all its output
90 pool
<RTLIL::Const
> ids_seen
;
91 for (auto cell
: module
->cells()) {
92 auto it
= cell
->attributes
.find("\\abc_scc_id");
93 if (it
!= cell
->attributes
.end()) {
94 auto r
= ids_seen
.insert(it
->second
);
96 for (auto &c
: cell
->connections_
) {
97 if (c
.second
.is_fully_const()) continue;
98 if (cell
->output(c
.first
)) {
99 SigBit b
= c
.second
.as_bit();
101 log_assert(!w
->port_input
);
102 w
->port_input
= true;
103 w
= module
->wire(stringf("%s.abci", w
->name
.c_str()));
105 w
= module
->addWire(stringf("%s.abci", b
.wire
->name
.c_str()), GetSize(b
.wire
));
106 w
->port_output
= true;
109 log_assert(w
->port_input
);
110 log_assert(b
.offset
< GetSize(w
));
112 w
->set_bool_attribute("\\abc_scc_break");
113 module
->swap_names(b
.wire
, w
);
114 c
.second
= RTLIL::SigBit(w
, b
.offset
);
118 cell
->attributes
.erase(it
);
121 auto jt
= abc_scc_break
.find(cell
->type
);
122 if (jt
== abc_scc_break
.end()) {
123 std::vector
<IdString
> ports
;
124 RTLIL::Module
* box_module
= design
->module(cell
->type
);
126 auto ports_csv
= box_module
->attributes
.at("\\abc_scc_break", RTLIL::Const::from_string("")).decode_string();
127 for (const auto &port_name
: split_tokens(ports_csv
, ",")) {
128 auto port_id
= RTLIL::escape_id(port_name
);
129 auto kt
= cell
->connections_
.find(port_id
);
130 if (kt
== cell
->connections_
.end())
131 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
));
132 ports
.push_back(port_id
);
135 jt
= abc_scc_break
.insert(std::make_pair(cell
->type
, std::move(ports
))).first
;
138 for (auto port_name
: jt
->second
) {
140 auto &rhs
= cell
->connections_
.at(port_name
);
144 w
->port_output
= true;
145 w
->set_bool_attribute("\\abc_scc_break");
146 w
= module
->wire(stringf("%s.abci", w
->name
.c_str()));
148 w
= module
->addWire(stringf("%s.abci", b
.wire
->name
.c_str()), GetSize(b
.wire
));
149 w
->port_input
= true;
152 log_assert(b
.offset
< GetSize(w
));
153 log_assert(w
->port_input
);
155 sig
.append(RTLIL::SigBit(w
, b
.offset
));
161 module
->fixup_ports();
164 std::string
add_echos_to_abc_cmd(std::string str
)
166 std::string new_str
, token
;
167 for (size_t i
= 0; i
< str
.size(); i
++) {
170 while (i
+1 < str
.size() && str
[i
+1] == ' ')
172 new_str
+= "echo + " + token
+ " " + token
+ " ";
177 if (!token
.empty()) {
178 if (!new_str
.empty())
179 new_str
+= "echo + " + token
+ "; ";
186 std::string
fold_abc_cmd(std::string str
)
188 std::string token
, new_str
= " ";
189 int char_counter
= 10;
191 for (size_t i
= 0; i
<= str
.size(); i
++) {
194 if (i
== str
.size() || str
[i
] == ';') {
195 if (char_counter
+ token
.size() > 75)
196 new_str
+= "\n ", char_counter
= 14;
197 new_str
+= token
, char_counter
+= token
.size();
205 std::string
replace_tempdir(std::string text
, std::string tempdir_name
, bool show_tempdir
)
211 size_t pos
= text
.find(tempdir_name
);
212 if (pos
== std::string::npos
)
214 text
= text
.substr(0, pos
) + "<abc-temp-dir>" + text
.substr(pos
+ GetSize(tempdir_name
));
217 std::string selfdir_name
= proc_self_dirname();
218 if (selfdir_name
!= "/") {
220 size_t pos
= text
.find(selfdir_name
);
221 if (pos
== std::string::npos
)
223 text
= text
.substr(0, pos
) + "<yosys-exe-dir>/" + text
.substr(pos
+ GetSize(selfdir_name
));
230 struct abc_output_filter
233 int escape_seq_state
;
235 std::string tempdir_name
;
238 abc_output_filter(std::string tempdir_name
, bool show_tempdir
) : tempdir_name(tempdir_name
), show_tempdir(show_tempdir
)
241 escape_seq_state
= 0;
244 void next_char(char ch
)
246 if (escape_seq_state
== 0 && ch
== '\033') {
247 escape_seq_state
= 1;
250 if (escape_seq_state
== 1) {
251 escape_seq_state
= ch
== '[' ? 2 : 0;
254 if (escape_seq_state
== 2) {
255 if ((ch
< '0' || '9' < ch
) && ch
!= ';')
256 escape_seq_state
= 0;
259 escape_seq_state
= 0;
265 log("ABC: %s\n", replace_tempdir(linebuf
, tempdir_name
, show_tempdir
).c_str());
266 got_cr
= false, linebuf
.clear();
270 got_cr
= false, linebuf
.clear();
274 void next_line(const std::string
&line
)
277 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
278 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
279 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
280 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
289 void abc9_module(RTLIL::Design
*design
, RTLIL::Module
*current_module
, std::string script_file
, std::string exe_file
,
290 bool cleanup
, vector
<int> lut_costs
, bool dff_mode
, std::string clk_str
,
291 bool /*keepff*/, std::string delay_target
, std::string
/*lutin_shared*/, bool fast_mode
,
292 bool show_tempdir
, std::string box_file
, std::string lut_file
,
293 std::string wire_delay
)
295 module
= current_module
;
296 map_autoidx
= autoidx
++;
301 clk_sig
= RTLIL::SigSpec();
304 en_sig
= RTLIL::SigSpec();
307 if (!clk_str
.empty() && clk_str
!= "$")
309 if (clk_str
.find(',') != std::string::npos
) {
310 int pos
= clk_str
.find(',');
311 std::string en_str
= clk_str
.substr(pos
+1);
312 clk_str
= clk_str
.substr(0, pos
);
313 if (en_str
[0] == '!') {
315 en_str
= en_str
.substr(1);
317 if (module
->wires_
.count(RTLIL::escape_id(en_str
)) != 0)
318 en_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(en_str
)), 0));
320 if (clk_str
[0] == '!') {
321 clk_polarity
= false;
322 clk_str
= clk_str
.substr(1);
324 if (module
->wires_
.count(RTLIL::escape_id(clk_str
)) != 0)
325 clk_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(clk_str
)), 0));
328 if (dff_mode
&& clk_sig
.empty())
329 log_cmd_error("Clock domain %s not found.\n", clk_str
.c_str());
331 std::string tempdir_name
= "/tmp/yosys-abc-XXXXXX";
333 tempdir_name
[0] = tempdir_name
[4] = '_';
334 tempdir_name
= make_temp_dir(tempdir_name
);
335 log_header(design
, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
336 module
->name
.c_str(), replace_tempdir(tempdir_name
, tempdir_name
, show_tempdir
).c_str());
338 std::string abc_script
;
340 if (!lut_costs
.empty()) {
341 abc_script
+= stringf("read_lut %s/lutdefs.txt; ", tempdir_name
.c_str());
342 if (!box_file
.empty())
343 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
346 if (!lut_file
.empty()) {
347 abc_script
+= stringf("read_lut %s; ", lut_file
.c_str());
348 if (!box_file
.empty())
349 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
354 abc_script
+= stringf("&read %s/input.xaig; &ps; ", tempdir_name
.c_str());
356 if (!script_file
.empty()) {
357 if (script_file
[0] == '+') {
358 for (size_t i
= 1; i
< script_file
.size(); i
++)
359 if (script_file
[i
] == '\'')
360 abc_script
+= "'\\''";
361 else if (script_file
[i
] == ',')
364 abc_script
+= script_file
[i
];
366 abc_script
+= stringf("source %s", script_file
.c_str());
367 } else if (!lut_costs
.empty() || !lut_file
.empty()) {
368 //bool all_luts_cost_same = true;
369 //for (int this_cost : lut_costs)
370 // if (this_cost != lut_costs.front())
371 // all_luts_cost_same = false;
372 abc_script
+= fast_mode
? ABC_FAST_COMMAND_LUT
: ABC_COMMAND_LUT
;
373 //if (all_luts_cost_same && !fast_mode)
374 // abc_script += "; lutpack {S}";
378 //if (script_file.empty() && !delay_target.empty())
379 // for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
380 // abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
382 for (size_t pos
= abc_script
.find("{D}"); pos
!= std::string::npos
; pos
= abc_script
.find("{D}", pos
))
383 abc_script
= abc_script
.substr(0, pos
) + delay_target
+ abc_script
.substr(pos
+3);
385 //for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
386 // abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
388 for (size_t pos
= abc_script
.find("{W}"); pos
!= std::string::npos
; pos
= abc_script
.find("{W}", pos
))
389 abc_script
= abc_script
.substr(0, pos
) + wire_delay
+ abc_script
.substr(pos
+3);
391 abc_script
+= stringf("; &write %s/output.aig", tempdir_name
.c_str());
392 abc_script
= add_echos_to_abc_cmd(abc_script
);
394 for (size_t i
= 0; i
+1 < abc_script
.size(); i
++)
395 if (abc_script
[i
] == ';' && abc_script
[i
+1] == ' ')
396 abc_script
[i
+1] = '\n';
398 FILE *f
= fopen(stringf("%s/abc.script", tempdir_name
.c_str()).c_str(), "wt");
399 fprintf(f
, "%s\n", abc_script
.c_str());
402 if (dff_mode
|| !clk_str
.empty())
404 if (clk_sig
.size() == 0)
405 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str
.empty() ? "" : " matching");
407 log("Found%s %s clock domain: %s", clk_str
.empty() ? "" : " matching", clk_polarity
? "posedge" : "negedge", log_signal(clk_sig
));
408 if (en_sig
.size() != 0)
409 log(", enabled by %s%s", en_polarity
? "" : "!", log_signal(en_sig
));
414 bool count_output
= false;
415 for (auto port_name
: module
->ports
) {
416 RTLIL::Wire
*port_wire
= module
->wire(port_name
);
417 log_assert(port_wire
);
418 if (port_wire
->port_output
) {
428 design
->selection_stack
.emplace_back(false);
429 RTLIL::Selection
& sel
= design
->selection_stack
.back();
432 Pass::call(design
, "aigmap");
434 handle_loops(design
);
436 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
437 // count_gates, GetSize(signal_list), count_input, count_output);
439 Pass::call(design
, stringf("write_xaiger -map %s/input.sym %s/input.xaig", tempdir_name
.c_str(), tempdir_name
.c_str()));
444 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.xaig");
447 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
448 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
449 log_assert(!design
->module("$__abc9__"));
451 AigerReader
reader(design
, ifs
, "$__abc9__", "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
452 reader
.parse_xaiger();
455 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
456 design
->remove(design
->module("$__abc9__"));
459 design
->selection_stack
.pop_back();
461 // Now 'unexpose' those wires by undoing
462 // the expose operation -- remove them from PO/PI
463 // and re-connecting them back together
464 for (auto wire
: module
->wires()) {
465 auto it
= wire
->attributes
.find("\\abc_scc_break");
466 if (it
!= wire
->attributes
.end()) {
467 wire
->attributes
.erase(it
);
468 log_assert(wire
->port_output
);
469 wire
->port_output
= false;
470 RTLIL::Wire
*i_wire
= module
->wire(wire
->name
.str() + ".abci");
472 log_assert(i_wire
->port_input
);
473 i_wire
->port_input
= false;
474 module
->connect(i_wire
, wire
);
477 module
->fixup_ports();
480 log_header(design
, "Executing ABC9.\n");
482 if (!lut_costs
.empty()) {
483 buffer
= stringf("%s/lutdefs.txt", tempdir_name
.c_str());
484 f
= fopen(buffer
.c_str(), "wt");
486 log_error("Opening %s for writing failed: %s\n", buffer
.c_str(), strerror(errno
));
487 for (int i
= 0; i
< GetSize(lut_costs
); i
++)
488 fprintf(f
, "%d %d.00 1.00\n", i
+1, lut_costs
.at(i
));
492 buffer
= stringf("%s -s -f %s/abc.script 2>&1", exe_file
.c_str(), tempdir_name
.c_str());
493 log("Running ABC command: %s\n", replace_tempdir(buffer
, tempdir_name
, show_tempdir
).c_str());
495 #ifndef YOSYS_LINK_ABC
496 abc_output_filter
filt(tempdir_name
, show_tempdir
);
497 int ret
= run_command(buffer
, std::bind(&abc_output_filter::next_line
, filt
, std::placeholders::_1
));
499 // These needs to be mutable, supposedly due to getopt
501 string tmp_script_name
= stringf("%s/abc.script", tempdir_name
.c_str());
502 abc_argv
[0] = strdup(exe_file
.c_str());
503 abc_argv
[1] = strdup("-s");
504 abc_argv
[2] = strdup("-f");
505 abc_argv
[3] = strdup(tmp_script_name
.c_str());
507 int ret
= Abc_RealMain(4, abc_argv
);
514 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer
.c_str(), ret
);
516 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "output.aig");
519 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
521 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
522 log_assert(!design
->module("$__abc9__"));
523 AigerReader
reader(design
, ifs
, "$__abc9__", "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
524 reader
.parse_xaiger();
528 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
531 log_header(design
, "Re-integrating ABC9 results.\n");
532 RTLIL::Module
*mapped_mod
= design
->module("$__abc9__");
533 if (mapped_mod
== NULL
)
534 log_error("ABC output file does not contain a module `$__abc9__'.\n");
536 pool
<RTLIL::SigBit
> output_bits
;
537 for (auto &it
: mapped_mod
->wires_
) {
538 RTLIL::Wire
*w
= it
.second
;
539 RTLIL::Wire
*remap_wire
= module
->addWire(remap_name(w
->name
), GetSize(w
));
540 if (markgroups
) remap_wire
->attributes
["\\abcgroup"] = map_autoidx
;
541 if (w
->port_output
) {
542 RTLIL::Wire
*wire
= module
->wire(w
->name
);
544 for (int i
= 0; i
< GetSize(w
); i
++)
545 output_bits
.insert({wire
, i
});
549 for (auto &it
: module
->connections_
) {
550 auto &signal
= it
.first
;
551 auto bits
= signal
.bits();
553 if (output_bits
.count(b
))
554 b
= module
->addWire(NEW_ID
);
555 signal
= std::move(bits
);
558 dict
<IdString
, bool> abc_box
;
559 vector
<RTLIL::Cell
*> boxes
;
560 for (const auto &it
: module
->cells_
) {
561 auto cell
= it
.second
;
562 if (cell
->type
.in("$_AND_", "$_NOT_")) {
563 module
->remove(cell
);
566 auto jt
= abc_box
.find(cell
->type
);
567 if (jt
== abc_box
.end()) {
568 RTLIL::Module
* box_module
= design
->module(cell
->type
);
569 jt
= abc_box
.insert(std::make_pair(cell
->type
, box_module
&& box_module
->attributes
.count("\\abc_box_id"))).first
;
572 boxes
.emplace_back(cell
);
575 dict
<SigBit
, pool
<IdString
>> bit_drivers
, bit_users
;
576 TopoSort
<IdString
, RTLIL::sort_by_id_str
> toposort
;
577 dict
<RTLIL::Cell
*,RTLIL::Cell
*> not2drivers
;
578 dict
<SigBit
, std::vector
<RTLIL::Cell
*>> bit2sinks
;
580 std::map
<std::string
, int> cell_stats
;
581 for (auto c
: mapped_mod
->cells())
583 toposort
.node(c
->name
);
585 RTLIL::Cell
*cell
= nullptr;
586 if (c
->type
== "$_NOT_") {
587 RTLIL::SigBit a_bit
= c
->getPort("\\A");
588 RTLIL::SigBit y_bit
= c
->getPort("\\Y");
589 bit_users
[a_bit
].insert(c
->name
);
590 bit_drivers
[y_bit
].insert(c
->name
);
593 c
->setPort("\\Y", module
->addWire(NEW_ID
));
594 RTLIL::Wire
*wire
= module
->wire(remap_name(y_bit
.wire
->name
));
596 module
->connect(RTLIL::SigBit(wire
, y_bit
.offset
), RTLIL::S1
);
598 else if (!lut_costs
.empty() || !lut_file
.empty()) {
599 RTLIL::Cell
* driver_lut
= nullptr;
600 // ABC can return NOT gates that drive POs
601 if (!a_bit
.wire
->port_input
) {
602 // If it's not a NOT gate that that comes from a PI directly,
603 // find the driver LUT and clone that to guarantee that we won't
604 // increase the max logic depth
605 // (TODO: Optimise by not cloning unless will increase depth)
606 RTLIL::IdString driver_name
;
607 if (GetSize(a_bit
.wire
) == 1)
608 driver_name
= stringf("%s$lut", a_bit
.wire
->name
.c_str());
610 driver_name
= stringf("%s[%d]$lut", a_bit
.wire
->name
.c_str(), a_bit
.offset
);
611 driver_lut
= mapped_mod
->cell(driver_name
);
615 // If a driver couldn't be found (could be from PI or box CI)
616 // then implement using a LUT
617 cell
= module
->addLut(remap_name(stringf("%s$lut", c
->name
.c_str())),
618 RTLIL::SigBit(module
->wires_
.at(remap_name(a_bit
.wire
->name
)), a_bit
.offset
),
619 RTLIL::SigBit(module
->wires_
.at(remap_name(y_bit
.wire
->name
)), y_bit
.offset
),
620 RTLIL::Const::from_string("01"));
621 bit2sinks
[cell
->getPort("\\A")].push_back(cell
);
622 cell_stats
["$lut"]++;
625 not2drivers
[c
] = driver_lut
;
630 if (cell
&& markgroups
) cell
->attributes
["\\abcgroup"] = map_autoidx
;
633 cell_stats
[RTLIL::unescape_id(c
->type
)]++;
635 RTLIL::Cell
*existing_cell
= nullptr;
636 if (c
->type
== "$lut") {
637 if (GetSize(c
->getPort("\\A")) == 1 && c
->getParam("\\LUT") == RTLIL::Const::from_string("01")) {
638 SigSpec my_a
= module
->wires_
.at(remap_name(c
->getPort("\\A").as_wire()->name
));
639 SigSpec my_y
= module
->wires_
.at(remap_name(c
->getPort("\\Y").as_wire()->name
));
640 module
->connect(my_y
, my_a
);
641 if (markgroups
) c
->attributes
["\\abcgroup"] = map_autoidx
;
645 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
648 existing_cell
= module
->cell(c
->name
);
649 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
650 module
->swap_names(cell
, existing_cell
);
653 if (markgroups
) cell
->attributes
["\\abcgroup"] = map_autoidx
;
655 cell
->parameters
= existing_cell
->parameters
;
656 cell
->attributes
= existing_cell
->attributes
;
659 cell
->parameters
= c
->parameters
;
660 cell
->attributes
= c
->attributes
;
662 for (auto &conn
: c
->connections()) {
663 RTLIL::SigSpec newsig
;
664 for (auto c
: conn
.second
.chunks()) {
667 //log_assert(c.width == 1);
669 c
.wire
= module
->wires_
.at(remap_name(c
.wire
->name
));
672 cell
->setPort(conn
.first
, newsig
);
674 if (cell
->input(conn
.first
)) {
675 for (auto i
: newsig
)
676 bit2sinks
[i
].push_back(cell
);
677 for (auto i
: conn
.second
)
678 bit_users
[i
].insert(c
->name
);
680 if (cell
->output(conn
.first
))
681 for (auto i
: conn
.second
)
682 bit_drivers
[i
].insert(c
->name
);
686 for (auto cell
: boxes
)
687 module
->remove(cell
);
689 // Copy connections (and rename) from mapped_mod to module
690 for (auto conn
: mapped_mod
->connections()) {
691 if (!conn
.first
.is_fully_const()) {
692 auto chunks
= conn
.first
.chunks();
693 for (auto &c
: chunks
)
694 c
.wire
= module
->wires_
.at(remap_name(c
.wire
->name
));
695 conn
.first
= std::move(chunks
);
697 if (!conn
.second
.is_fully_const()) {
698 auto chunks
= conn
.second
.chunks();
699 for (auto &c
: chunks
)
701 c
.wire
= module
->wires_
.at(remap_name(c
.wire
->name
));
702 conn
.second
= std::move(chunks
);
704 module
->connect(conn
);
707 for (auto &it
: cell_stats
)
708 log("ABC RESULTS: %15s cells: %8d\n", it
.first
.c_str(), it
.second
);
709 int in_wires
= 0, out_wires
= 0;
711 // Stitch in mapped_mod's inputs/outputs into module
712 for (auto &it
: mapped_mod
->wires_
) {
713 RTLIL::Wire
*w
= it
.second
;
714 if (!w
->port_input
&& !w
->port_output
)
716 RTLIL::Wire
*wire
= module
->wire(w
->name
);
718 RTLIL::Wire
*remap_wire
= module
->wire(remap_name(w
->name
));
719 RTLIL::SigSpec signal
= RTLIL::SigSpec(wire
, 0, GetSize(remap_wire
));
720 log_assert(GetSize(signal
) >= GetSize(remap_wire
));
722 log_assert(w
->port_input
|| w
->port_output
);
725 conn
.first
= remap_wire
;
726 conn
.second
= signal
;
728 module
->connect(conn
);
730 if (w
->port_output
) {
732 conn
.second
= remap_wire
;
734 module
->connect(conn
);
738 for (auto &it
: bit_users
)
739 if (bit_drivers
.count(it
.first
))
740 for (auto driver_cell
: bit_drivers
.at(it
.first
))
741 for (auto user_cell
: it
.second
)
742 toposort
.edge(driver_cell
, user_cell
);
743 bool no_loops
= toposort
.sort();
744 log_assert(no_loops
);
746 for (auto ii
= toposort
.sorted
.rbegin(); ii
!= toposort
.sorted
.rend(); ii
++) {
747 RTLIL::Cell
*not_cell
= mapped_mod
->cell(*ii
);
748 log_assert(not_cell
);
749 if (not_cell
->type
!= "$_NOT_")
751 auto it
= not2drivers
.find(not_cell
);
752 if (it
== not2drivers
.end())
754 RTLIL::Cell
*driver_lut
= it
->second
;
755 RTLIL::SigBit a_bit
= not_cell
->getPort("\\A");
756 RTLIL::SigBit y_bit
= not_cell
->getPort("\\Y");
757 RTLIL::Const driver_mask
;
759 a_bit
.wire
= module
->wires_
.at(remap_name(a_bit
.wire
->name
));
760 y_bit
.wire
= module
->wires_
.at(remap_name(y_bit
.wire
->name
));
762 auto jt
= bit2sinks
.find(a_bit
);
763 if (jt
== bit2sinks
.end())
766 for (auto sink_cell
: jt
->second
)
767 if (sink_cell
->type
!= "$lut")
770 // Push downstream LUTs past inverter
771 for (auto sink_cell
: jt
->second
) {
772 SigSpec A
= sink_cell
->getPort("\\A");
773 RTLIL::Const mask
= sink_cell
->getParam("\\LUT");
775 for (; index
< GetSize(A
); index
++)
776 if (A
[index
] == a_bit
)
778 log_assert(index
< GetSize(A
));
780 while (i
< GetSize(mask
)) {
781 for (int j
= 0; j
< (1 << index
); j
++)
782 std::swap(mask
[i
+j
], mask
[i
+j
+(1 << index
)]);
786 sink_cell
->setPort("\\A", A
);
787 sink_cell
->setParam("\\LUT", mask
);
791 driver_mask
= driver_lut
->getParam("\\LUT");
792 for (auto &b
: driver_mask
.bits
) {
793 if (b
== RTLIL::State::S0
) b
= RTLIL::State::S1
;
794 else if (b
== RTLIL::State::S1
) b
= RTLIL::State::S0
;
796 auto cell
= module
->addLut(NEW_ID
,
797 driver_lut
->getPort("\\A"),
800 for (auto &bit
: cell
->connections_
.at("\\A")) {
801 bit
.wire
= module
->wires_
.at(remap_name(bit
.wire
->name
));
802 bit2sinks
[bit
].push_back(cell
);
806 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
807 log("ABC RESULTS: input signals: %8d\n", in_wires
);
808 log("ABC RESULTS: output signals: %8d\n", out_wires
);
810 design
->remove(mapped_mod
);
814 log("Don't call ABC as there is nothing to map.\n");
819 log("Removing temp directory.\n");
820 remove_directory(tempdir_name
);
826 struct Abc9Pass
: public Pass
{
827 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
828 void help() YS_OVERRIDE
830 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
832 log(" abc9 [options] [selection]\n");
834 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
835 log("library to a target architecture.\n");
837 log(" -exe <command>\n");
839 log(" use the specified command instead of \"" ABCEXTERNAL
"\" to execute ABC.\n");
841 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
843 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
845 log(" -script <file>\n");
846 log(" use the specified ABC script file instead of the default script.\n");
848 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
849 log(" string is interpreted as the command string to be passed to ABC. The\n");
850 log(" leading plus sign is removed and all commas (,) in the string are\n");
851 log(" replaced with blanks before the string is passed to ABC.\n");
853 log(" if no -script parameter is given, the following scripts are used:\n");
855 log(" for -lut/-luts (only one LUT size):\n");
856 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
/*"; lutpack {S}"*/).c_str());
858 log(" for -lut/-luts (different LUT sizes):\n");
859 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
).c_str());
862 log(" use different default scripts that are slightly faster (at the cost\n");
863 log(" of output quality):\n");
865 log(" for -lut/-luts:\n");
866 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT
).c_str());
868 log(" -D <picoseconds>\n");
869 log(" set delay target. the string {D} in the default scripts above is\n");
870 log(" replaced by this option when used, and an empty string otherwise\n");
871 log(" (indicating best possible delay).\n");
872 // log(" This also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
873 // log(" default scripts above.\n");
875 // log(" -S <num>\n");
876 // log(" maximum number of LUT inputs shared.\n");
877 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
879 log(" -lut <width>\n");
880 log(" generate netlist using luts of (max) the specified width.\n");
882 log(" -lut <w1>:<w2>\n");
883 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
884 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
885 log(" the area cost doubles with each additional input bit. the delay cost\n");
886 log(" is still constant for all lut widths.\n");
888 log(" -lut <file>\n");
889 log(" pass this file with lut library to ABC.\n");
891 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
892 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
893 log(" 2, 3, .. inputs.\n");
896 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
897 // log(" clock domains are automatically partitioned in clock domains and each\n");
898 // log(" domain is passed through ABC independently.\n");
900 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
901 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
902 // log(" cells that belong to the specified clock domain are used.\n");
904 // log(" -keepff\n");
905 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
906 // log(" them, for example for equivalence checking.)\n");
908 log(" -nocleanup\n");
909 log(" when this option is used, the temporary files created by this pass\n");
910 log(" are not removed. this is useful for debugging.\n");
913 log(" print the temp dir name in log. usually this is suppressed so that the\n");
914 log(" command output is identical across runs.\n");
916 log(" -markgroups\n");
917 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
918 log(" this attribute is a unique integer for each ABC process started. This\n");
919 log(" is useful for debugging the partitioning of clock domains.\n");
921 log(" -box <file>\n");
922 log(" pass this file with box library to ABC. Use with -lut.\n");
924 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
925 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
926 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
927 log("output when passing an ABC script that writes a file. Instead write your full\n");
928 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
929 log("you want to use ABC to convert your design into another format.\n");
931 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
934 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
936 log_header(design
, "Executing ABC9 pass (technology mapping using ABC9).\n");
942 std::string exe_file
= ABCEXTERNAL
;
944 std::string exe_file
= proc_self_dirname() + "yosys-abc";
946 std::string script_file
, clk_str
, box_file
, lut_file
;
947 std::string delay_target
, lutin_shared
= "-S 1", wire_delay
;
948 bool fast_mode
= false, dff_mode
= false, keepff
= false, cleanup
= true;
949 bool show_tempdir
= false;
950 vector
<int> lut_costs
;
960 if (!check_file_exists(exe_file
+ ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
961 exe_file
= proc_self_dirname() + "..\\yosys-abc";
967 if (!getcwd(pwd
, sizeof(pwd
))) {
968 log_cmd_error("getcwd failed: %s\n", strerror(errno
));
971 for (argidx
= 1; argidx
< args
.size(); argidx
++) {
972 std::string arg
= args
[argidx
];
973 if (arg
== "-exe" && argidx
+1 < args
.size()) {
974 exe_file
= args
[++argidx
];
977 if (arg
== "-script" && argidx
+1 < args
.size()) {
978 script_file
= args
[++argidx
];
979 rewrite_filename(script_file
);
980 if (!script_file
.empty() && !is_absolute_path(script_file
) && script_file
[0] != '+')
981 script_file
= std::string(pwd
) + "/" + script_file
;
984 if (arg
== "-D" && argidx
+1 < args
.size()) {
985 delay_target
= "-D " + args
[++argidx
];
988 //if (arg == "-S" && argidx+1 < args.size()) {
989 // lutin_shared = "-S " + args[++argidx];
992 if (arg
== "-lut" && argidx
+1 < args
.size()) {
993 string arg
= args
[++argidx
];
994 size_t pos
= arg
.find_first_of(':');
995 int lut_mode
= 0, lut_mode2
= 0;
996 if (pos
!= string::npos
) {
997 lut_mode
= atoi(arg
.substr(0, pos
).c_str());
998 lut_mode2
= atoi(arg
.substr(pos
+1).c_str());
1000 pos
= arg
.find_first_of('.');
1001 if (pos
!= string::npos
) {
1003 rewrite_filename(lut_file
);
1004 if (!lut_file
.empty() && !is_absolute_path(lut_file
))
1005 lut_file
= std::string(pwd
) + "/" + lut_file
;
1008 lut_mode
= atoi(arg
.c_str());
1009 lut_mode2
= lut_mode
;
1013 for (int i
= 0; i
< lut_mode
; i
++)
1014 lut_costs
.push_back(1);
1015 for (int i
= lut_mode
; i
< lut_mode2
; i
++)
1016 lut_costs
.push_back(2 << (i
- lut_mode
));
1019 if (arg
== "-luts" && argidx
+1 < args
.size()) {
1021 for (auto &tok
: split_tokens(args
[++argidx
], ",")) {
1022 auto parts
= split_tokens(tok
, ":");
1023 if (GetSize(parts
) == 0 && !lut_costs
.empty())
1024 lut_costs
.push_back(lut_costs
.back());
1025 else if (GetSize(parts
) == 1)
1026 lut_costs
.push_back(atoi(parts
.at(0).c_str()));
1027 else if (GetSize(parts
) == 2)
1028 while (GetSize(lut_costs
) < atoi(parts
.at(0).c_str()))
1029 lut_costs
.push_back(atoi(parts
.at(1).c_str()));
1031 log_cmd_error("Invalid -luts syntax.\n");
1035 if (arg
== "-fast") {
1039 //if (arg == "-dff") {
1043 //if (arg == "-clk" && argidx+1 < args.size()) {
1044 // clk_str = args[++argidx];
1048 //if (arg == "-keepff") {
1052 if (arg
== "-nocleanup") {
1056 if (arg
== "-showtmp") {
1057 show_tempdir
= true;
1060 if (arg
== "-markgroups") {
1064 if (arg
== "-box" && argidx
+1 < args
.size()) {
1065 box_file
= args
[++argidx
];
1066 rewrite_filename(box_file
);
1067 if (!box_file
.empty() && !is_absolute_path(box_file
))
1068 box_file
= std::string(pwd
) + "/" + box_file
;
1071 if (arg
== "-W" && argidx
+1 < args
.size()) {
1072 wire_delay
= "-W " + args
[++argidx
];
1077 extra_args(args
, argidx
, design
);
1079 for (auto mod
: design
->selected_modules())
1081 if (mod
->attributes
.count("\\abc_box_id"))
1084 if (mod
->processes
.size() > 0) {
1085 log("Skipping module %s as it contains processes.\n", log_id(mod
));
1089 assign_map
.set(mod
);
1091 if (!dff_mode
|| !clk_str
.empty()) {
1092 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, dff_mode
, clk_str
, keepff
,
1093 delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1094 box_file
, lut_file
, wire_delay
);
1098 CellTypes
ct(design
);
1100 std::vector
<RTLIL::Cell
*> all_cells
= mod
->selected_cells();
1101 std::set
<RTLIL::Cell
*> unassigned_cells(all_cells
.begin(), all_cells
.end());
1103 std::set
<RTLIL::Cell
*> expand_queue
, next_expand_queue
;
1104 std::set
<RTLIL::Cell
*> expand_queue_up
, next_expand_queue_up
;
1105 std::set
<RTLIL::Cell
*> expand_queue_down
, next_expand_queue_down
;
1107 typedef tuple
<bool, RTLIL::SigSpec
, bool, RTLIL::SigSpec
> clkdomain_t
;
1108 std::map
<clkdomain_t
, std::vector
<RTLIL::Cell
*>> assigned_cells
;
1109 std::map
<RTLIL::Cell
*, clkdomain_t
> assigned_cells_reverse
;
1111 std::map
<RTLIL::Cell
*, std::set
<RTLIL::SigBit
>> cell_to_bit
, cell_to_bit_up
, cell_to_bit_down
;
1112 std::map
<RTLIL::SigBit
, std::set
<RTLIL::Cell
*>> bit_to_cell
, bit_to_cell_up
, bit_to_cell_down
;
1114 for (auto cell
: all_cells
)
1118 for (auto &conn
: cell
->connections())
1119 for (auto bit
: conn
.second
) {
1120 bit
= assign_map(bit
);
1121 if (bit
.wire
!= nullptr) {
1122 cell_to_bit
[cell
].insert(bit
);
1123 bit_to_cell
[bit
].insert(cell
);
1124 if (ct
.cell_input(cell
->type
, conn
.first
)) {
1125 cell_to_bit_up
[cell
].insert(bit
);
1126 bit_to_cell_down
[bit
].insert(cell
);
1128 if (ct
.cell_output(cell
->type
, conn
.first
)) {
1129 cell_to_bit_down
[cell
].insert(bit
);
1130 bit_to_cell_up
[bit
].insert(cell
);
1135 if (cell
->type
== "$_DFF_N_" || cell
->type
== "$_DFF_P_")
1137 key
= clkdomain_t(cell
->type
== "$_DFF_P_", assign_map(cell
->getPort("\\C")), true, RTLIL::SigSpec());
1140 if (cell
->type
== "$_DFFE_NN_" || cell
->type
== "$_DFFE_NP_" || cell
->type
== "$_DFFE_PN_" || cell
->type
== "$_DFFE_PP_")
1142 bool this_clk_pol
= cell
->type
== "$_DFFE_PN_" || cell
->type
== "$_DFFE_PP_";
1143 bool this_en_pol
= cell
->type
== "$_DFFE_NP_" || cell
->type
== "$_DFFE_PP_";
1144 key
= clkdomain_t(this_clk_pol
, assign_map(cell
->getPort("\\C")), this_en_pol
, assign_map(cell
->getPort("\\E")));
1149 unassigned_cells
.erase(cell
);
1150 expand_queue
.insert(cell
);
1151 expand_queue_up
.insert(cell
);
1152 expand_queue_down
.insert(cell
);
1154 assigned_cells
[key
].push_back(cell
);
1155 assigned_cells_reverse
[cell
] = key
;
1158 while (!expand_queue_up
.empty() || !expand_queue_down
.empty())
1160 if (!expand_queue_up
.empty())
1162 RTLIL::Cell
*cell
= *expand_queue_up
.begin();
1163 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1164 expand_queue_up
.erase(cell
);
1166 for (auto bit
: cell_to_bit_up
[cell
])
1167 for (auto c
: bit_to_cell_up
[bit
])
1168 if (unassigned_cells
.count(c
)) {
1169 unassigned_cells
.erase(c
);
1170 next_expand_queue_up
.insert(c
);
1171 assigned_cells
[key
].push_back(c
);
1172 assigned_cells_reverse
[c
] = key
;
1173 expand_queue
.insert(c
);
1177 if (!expand_queue_down
.empty())
1179 RTLIL::Cell
*cell
= *expand_queue_down
.begin();
1180 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1181 expand_queue_down
.erase(cell
);
1183 for (auto bit
: cell_to_bit_down
[cell
])
1184 for (auto c
: bit_to_cell_down
[bit
])
1185 if (unassigned_cells
.count(c
)) {
1186 unassigned_cells
.erase(c
);
1187 next_expand_queue_up
.insert(c
);
1188 assigned_cells
[key
].push_back(c
);
1189 assigned_cells_reverse
[c
] = key
;
1190 expand_queue
.insert(c
);
1194 if (expand_queue_up
.empty() && expand_queue_down
.empty()) {
1195 expand_queue_up
.swap(next_expand_queue_up
);
1196 expand_queue_down
.swap(next_expand_queue_down
);
1200 while (!expand_queue
.empty())
1202 RTLIL::Cell
*cell
= *expand_queue
.begin();
1203 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1204 expand_queue
.erase(cell
);
1206 for (auto bit
: cell_to_bit
.at(cell
)) {
1207 for (auto c
: bit_to_cell
[bit
])
1208 if (unassigned_cells
.count(c
)) {
1209 unassigned_cells
.erase(c
);
1210 next_expand_queue
.insert(c
);
1211 assigned_cells
[key
].push_back(c
);
1212 assigned_cells_reverse
[c
] = key
;
1214 bit_to_cell
[bit
].clear();
1217 if (expand_queue
.empty())
1218 expand_queue
.swap(next_expand_queue
);
1221 clkdomain_t
key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1222 for (auto cell
: unassigned_cells
) {
1223 assigned_cells
[key
].push_back(cell
);
1224 assigned_cells_reverse
[cell
] = key
;
1227 log_header(design
, "Summary of detected clock domains:\n");
1228 for (auto &it
: assigned_cells
)
1229 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it
.second
),
1230 std::get
<0>(it
.first
) ? "" : "!", log_signal(std::get
<1>(it
.first
)),
1231 std::get
<2>(it
.first
) ? "" : "!", log_signal(std::get
<3>(it
.first
)));
1233 for (auto &it
: assigned_cells
) {
1234 clk_polarity
= std::get
<0>(it
.first
);
1235 clk_sig
= assign_map(std::get
<1>(it
.first
));
1236 en_polarity
= std::get
<2>(it
.first
);
1237 en_sig
= assign_map(std::get
<3>(it
.first
));
1238 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, !clk_sig
.empty(), "$",
1239 keepff
, delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1240 box_file
, lut_file
, wire_delay
);
1241 assign_map
.set(mod
);
1245 Pass::call(design
, "clean");
1253 PRIVATE_NAMESPACE_END