5f448e37a44a0bddfef01846ff3f33ae3d067126
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; &if {W} {D}"
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
>> abc_scc_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
= abc_scc_break
.find(cell
->type
);
120 if (jt
== abc_scc_break
.end()) {
121 std::vector
<IdString
> ports
;
122 RTLIL::Module
* box_module
= design
->module(cell
->type
);
124 auto ports_csv
= box_module
->attributes
.at("\\abc_scc_break", RTLIL::Const::from_string("")).decode_string();
125 for (const auto &port_name
: split_tokens(ports_csv
, ",")) {
126 auto port_id
= RTLIL::escape_id(port_name
);
127 auto kt
= cell
->connections_
.find(port_id
);
128 if (kt
== cell
->connections_
.end())
129 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
));
130 ports
.push_back(port_id
);
133 jt
= abc_scc_break
.insert(std::make_pair(cell
->type
, std::move(ports
))).first
;
136 for (auto port_name
: jt
->second
) {
138 auto &rhs
= cell
->connections_
.at(port_name
);
142 w
->port_output
= true;
143 w
->set_bool_attribute("\\abc_scc_break");
144 w
= module
->wire(stringf("%s.abci", w
->name
.c_str()));
146 w
= module
->addWire(stringf("%s.abci", b
.wire
->name
.c_str()), GetSize(b
.wire
));
147 w
->port_input
= true;
150 log_assert(b
.offset
< GetSize(w
));
151 log_assert(w
->port_input
);
153 sig
.append(RTLIL::SigBit(w
, b
.offset
));
159 module
->fixup_ports();
162 std::string
add_echos_to_abc_cmd(std::string str
)
164 std::string new_str
, token
;
165 for (size_t i
= 0; i
< str
.size(); i
++) {
168 while (i
+1 < str
.size() && str
[i
+1] == ' ')
170 new_str
+= "echo + " + token
+ " " + token
+ " ";
175 if (!token
.empty()) {
176 if (!new_str
.empty())
177 new_str
+= "echo + " + token
+ "; ";
184 std::string
fold_abc_cmd(std::string str
)
186 std::string token
, new_str
= " ";
187 int char_counter
= 10;
189 for (size_t i
= 0; i
<= str
.size(); i
++) {
192 if (i
== str
.size() || str
[i
] == ';') {
193 if (char_counter
+ token
.size() > 75)
194 new_str
+= "\n ", char_counter
= 14;
195 new_str
+= token
, char_counter
+= token
.size();
203 std::string
replace_tempdir(std::string text
, std::string tempdir_name
, bool show_tempdir
)
209 size_t pos
= text
.find(tempdir_name
);
210 if (pos
== std::string::npos
)
212 text
= text
.substr(0, pos
) + "<abc-temp-dir>" + text
.substr(pos
+ GetSize(tempdir_name
));
215 std::string selfdir_name
= proc_self_dirname();
216 if (selfdir_name
!= "/") {
218 size_t pos
= text
.find(selfdir_name
);
219 if (pos
== std::string::npos
)
221 text
= text
.substr(0, pos
) + "<yosys-exe-dir>/" + text
.substr(pos
+ GetSize(selfdir_name
));
228 struct abc_output_filter
231 int escape_seq_state
;
233 std::string tempdir_name
;
236 abc_output_filter(std::string tempdir_name
, bool show_tempdir
) : tempdir_name(tempdir_name
), show_tempdir(show_tempdir
)
239 escape_seq_state
= 0;
242 void next_char(char ch
)
244 if (escape_seq_state
== 0 && ch
== '\033') {
245 escape_seq_state
= 1;
248 if (escape_seq_state
== 1) {
249 escape_seq_state
= ch
== '[' ? 2 : 0;
252 if (escape_seq_state
== 2) {
253 if ((ch
< '0' || '9' < ch
) && ch
!= ';')
254 escape_seq_state
= 0;
257 escape_seq_state
= 0;
263 log("ABC: %s\n", replace_tempdir(linebuf
, tempdir_name
, show_tempdir
).c_str());
264 got_cr
= false, linebuf
.clear();
268 got_cr
= false, linebuf
.clear();
272 void next_line(const std::string
&line
)
275 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
276 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
277 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
278 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
287 void abc9_module(RTLIL::Design
*design
, RTLIL::Module
*current_module
, std::string script_file
, std::string exe_file
,
288 bool cleanup
, vector
<int> lut_costs
, bool dff_mode
, std::string clk_str
,
289 bool /*keepff*/, std::string delay_target
, std::string
/*lutin_shared*/, bool fast_mode
,
290 bool show_tempdir
, std::string box_file
, std::string lut_file
,
291 std::string wire_delay
)
293 module
= current_module
;
294 map_autoidx
= autoidx
++;
299 clk_sig
= RTLIL::SigSpec();
302 en_sig
= RTLIL::SigSpec();
305 if (!clk_str
.empty() && clk_str
!= "$")
307 if (clk_str
.find(',') != std::string::npos
) {
308 int pos
= clk_str
.find(',');
309 std::string en_str
= clk_str
.substr(pos
+1);
310 clk_str
= clk_str
.substr(0, pos
);
311 if (en_str
[0] == '!') {
313 en_str
= en_str
.substr(1);
315 if (module
->wires_
.count(RTLIL::escape_id(en_str
)) != 0)
316 en_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(en_str
)), 0));
318 if (clk_str
[0] == '!') {
319 clk_polarity
= false;
320 clk_str
= clk_str
.substr(1);
322 if (module
->wires_
.count(RTLIL::escape_id(clk_str
)) != 0)
323 clk_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(clk_str
)), 0));
326 if (dff_mode
&& clk_sig
.empty())
327 log_cmd_error("Clock domain %s not found.\n", clk_str
.c_str());
329 std::string tempdir_name
= "/tmp/yosys-abc-XXXXXX";
331 tempdir_name
[0] = tempdir_name
[4] = '_';
332 tempdir_name
= make_temp_dir(tempdir_name
);
333 log_header(design
, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
334 module
->name
.c_str(), replace_tempdir(tempdir_name
, tempdir_name
, show_tempdir
).c_str());
336 std::string abc_script
;
338 if (!lut_costs
.empty()) {
339 abc_script
+= stringf("read_lut %s/lutdefs.txt; ", tempdir_name
.c_str());
340 if (!box_file
.empty())
341 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
344 if (!lut_file
.empty()) {
345 abc_script
+= stringf("read_lut %s; ", lut_file
.c_str());
346 if (!box_file
.empty())
347 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
352 abc_script
+= stringf("&read %s/input.xaig; &ps; ", tempdir_name
.c_str());
354 if (!script_file
.empty()) {
355 if (script_file
[0] == '+') {
356 for (size_t i
= 1; i
< script_file
.size(); i
++)
357 if (script_file
[i
] == '\'')
358 abc_script
+= "'\\''";
359 else if (script_file
[i
] == ',')
362 abc_script
+= script_file
[i
];
364 abc_script
+= stringf("source %s", script_file
.c_str());
365 } else if (!lut_costs
.empty() || !lut_file
.empty()) {
366 //bool all_luts_cost_same = true;
367 //for (int this_cost : lut_costs)
368 // if (this_cost != lut_costs.front())
369 // all_luts_cost_same = false;
370 abc_script
+= fast_mode
? ABC_FAST_COMMAND_LUT
: ABC_COMMAND_LUT
;
371 //if (all_luts_cost_same && !fast_mode)
372 // abc_script += "; lutpack {S}";
376 //if (script_file.empty() && !delay_target.empty())
377 // for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
378 // abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
380 for (size_t pos
= abc_script
.find("{D}"); pos
!= std::string::npos
; pos
= abc_script
.find("{D}", pos
))
381 abc_script
= abc_script
.substr(0, pos
) + delay_target
+ abc_script
.substr(pos
+3);
383 //for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
384 // abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
386 for (size_t pos
= abc_script
.find("{W}"); pos
!= std::string::npos
; pos
= abc_script
.find("{W}", pos
))
387 abc_script
= abc_script
.substr(0, pos
) + wire_delay
+ abc_script
.substr(pos
+3);
389 abc_script
+= stringf("; &write %s/output.aig", tempdir_name
.c_str());
390 abc_script
= add_echos_to_abc_cmd(abc_script
);
392 for (size_t i
= 0; i
+1 < abc_script
.size(); i
++)
393 if (abc_script
[i
] == ';' && abc_script
[i
+1] == ' ')
394 abc_script
[i
+1] = '\n';
396 FILE *f
= fopen(stringf("%s/abc.script", tempdir_name
.c_str()).c_str(), "wt");
397 fprintf(f
, "%s\n", abc_script
.c_str());
400 if (dff_mode
|| !clk_str
.empty())
402 if (clk_sig
.size() == 0)
403 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str
.empty() ? "" : " matching");
405 log("Found%s %s clock domain: %s", clk_str
.empty() ? "" : " matching", clk_polarity
? "posedge" : "negedge", log_signal(clk_sig
));
406 if (en_sig
.size() != 0)
407 log(", enabled by %s%s", en_polarity
? "" : "!", log_signal(en_sig
));
412 bool count_output
= false;
413 for (auto port_name
: module
->ports
) {
414 RTLIL::Wire
*port_wire
= module
->wire(port_name
);
415 log_assert(port_wire
);
416 if (port_wire
->port_output
) {
426 design
->selection_stack
.emplace_back(false);
427 RTLIL::Selection
& sel
= design
->selection_stack
.back();
430 Pass::call(design
, "aigmap");
432 handle_loops(design
);
434 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
435 // count_gates, GetSize(signal_list), count_input, count_output);
437 Pass::call(design
, stringf("write_xaiger -map %s/input.sym %s/input.xaig", tempdir_name
.c_str(), tempdir_name
.c_str()));
442 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.xaig");
445 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
446 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
447 log_assert(!design
->module("$__abc9__"));
449 AigerReader
reader(design
, ifs
, "$__abc9__", "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
450 reader
.parse_xaiger();
453 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
454 design
->remove(design
->module("$__abc9__"));
457 design
->selection_stack
.pop_back();
459 // Now 'unexpose' those wires by undoing
460 // the expose operation -- remove them from PO/PI
461 // and re-connecting them back together
462 for (auto wire
: module
->wires()) {
463 auto it
= wire
->attributes
.find("\\abc_scc_break");
464 if (it
!= wire
->attributes
.end()) {
465 wire
->attributes
.erase(it
);
466 log_assert(wire
->port_output
);
467 wire
->port_output
= false;
468 RTLIL::Wire
*i_wire
= module
->wire(wire
->name
.str() + ".abci");
470 log_assert(i_wire
->port_input
);
471 i_wire
->port_input
= false;
472 module
->connect(i_wire
, wire
);
475 module
->fixup_ports();
478 log_header(design
, "Executing ABC9.\n");
480 if (!lut_costs
.empty()) {
481 buffer
= stringf("%s/lutdefs.txt", tempdir_name
.c_str());
482 f
= fopen(buffer
.c_str(), "wt");
484 log_error("Opening %s for writing failed: %s\n", buffer
.c_str(), strerror(errno
));
485 for (int i
= 0; i
< GetSize(lut_costs
); i
++)
486 fprintf(f
, "%d %d.00 1.00\n", i
+1, lut_costs
.at(i
));
490 buffer
= stringf("%s -s -f %s/abc.script 2>&1", exe_file
.c_str(), tempdir_name
.c_str());
491 log("Running ABC command: %s\n", replace_tempdir(buffer
, tempdir_name
, show_tempdir
).c_str());
493 #ifndef YOSYS_LINK_ABC
494 abc_output_filter
filt(tempdir_name
, show_tempdir
);
495 int ret
= run_command(buffer
, std::bind(&abc_output_filter::next_line
, filt
, std::placeholders::_1
));
497 // These needs to be mutable, supposedly due to getopt
499 string tmp_script_name
= stringf("%s/abc.script", tempdir_name
.c_str());
500 abc_argv
[0] = strdup(exe_file
.c_str());
501 abc_argv
[1] = strdup("-s");
502 abc_argv
[2] = strdup("-f");
503 abc_argv
[3] = strdup(tmp_script_name
.c_str());
505 int ret
= Abc_RealMain(4, abc_argv
);
512 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer
.c_str(), ret
);
514 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "output.aig");
517 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
519 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
520 log_assert(!design
->module("$__abc9__"));
521 AigerReader
reader(design
, ifs
, "$__abc9__", "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
522 reader
.parse_xaiger();
526 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
529 log_header(design
, "Re-integrating ABC9 results.\n");
530 RTLIL::Module
*mapped_mod
= design
->module("$__abc9__");
531 if (mapped_mod
== NULL
)
532 log_error("ABC output file does not contain a module `$__abc9__'.\n");
534 pool
<RTLIL::SigBit
> output_bits
;
535 for (auto &it
: mapped_mod
->wires_
) {
536 RTLIL::Wire
*w
= it
.second
;
537 RTLIL::Wire
*remap_wire
= module
->addWire(remap_name(w
->name
), GetSize(w
));
538 if (markgroups
) remap_wire
->attributes
["\\abcgroup"] = map_autoidx
;
539 if (w
->port_output
) {
540 RTLIL::Wire
*wire
= module
->wire(w
->name
);
542 for (int i
= 0; i
< GetSize(w
); i
++)
543 output_bits
.insert({wire
, i
});
547 for (auto &it
: module
->connections_
) {
548 auto &signal
= it
.first
;
549 auto bits
= signal
.bits();
551 if (output_bits
.count(b
))
552 b
= module
->addWire(NEW_ID
);
553 signal
= std::move(bits
);
556 dict
<IdString
, bool> abc_box
;
557 vector
<RTLIL::Cell
*> boxes
;
558 for (const auto &it
: module
->cells_
) {
559 auto cell
= it
.second
;
560 if (cell
->type
.in("$_AND_", "$_NOT_")) {
561 module
->remove(cell
);
564 auto jt
= abc_box
.find(cell
->type
);
565 if (jt
== abc_box
.end()) {
566 RTLIL::Module
* box_module
= design
->module(cell
->type
);
567 jt
= abc_box
.insert(std::make_pair(cell
->type
, box_module
&& box_module
->attributes
.count("\\abc_box_id"))).first
;
570 boxes
.emplace_back(cell
);
573 std::map
<std::string
, int> cell_stats
;
574 for (auto c
: mapped_mod
->cells())
576 RTLIL::Cell
*cell
= nullptr;
577 if (c
->type
== "$_NOT_") {
578 RTLIL::SigBit a_bit
= c
->getPort("\\A").as_bit();
579 RTLIL::SigBit y_bit
= c
->getPort("\\Y").as_bit();
581 c
->setPort("\\Y", module
->addWire(NEW_ID
));
582 RTLIL::Wire
*wire
= module
->wire(remap_name(y_bit
.wire
->name
));
584 module
->connect(RTLIL::SigBit(wire
, y_bit
.offset
), RTLIL::S1
);
586 else if (!lut_costs
.empty() || !lut_file
.empty()) {
587 RTLIL::Cell
* driving_lut
= nullptr;
588 // ABC can return NOT gates that drive POs
589 if (!a_bit
.wire
->port_input
) {
590 // If it's not a NOT gate that that comes from a PI directly,
591 // find the driving LUT and clone that to guarantee that we won't
592 // increase the max logic depth
593 // (TODO: Optimise by not cloning unless will increase depth)
594 RTLIL::IdString driver_name
;
595 if (GetSize(a_bit
.wire
) == 1)
596 driver_name
= stringf("%s$lut", a_bit
.wire
->name
.c_str());
598 driver_name
= stringf("%s[%d]$lut", a_bit
.wire
->name
.c_str(), a_bit
.offset
);
599 driving_lut
= mapped_mod
->cell(driver_name
);
603 // If a driver couldn't be found (could be from PI,
604 // or from a box) then implement using a LUT
605 cell
= module
->addLut(remap_name(stringf("%s$lut", c
->name
.c_str())),
606 RTLIL::SigBit(module
->wires_
[remap_name(a_bit
.wire
->name
)], a_bit
.offset
),
607 RTLIL::SigBit(module
->wires_
[remap_name(y_bit
.wire
->name
)], y_bit
.offset
),
611 auto driver_a
= driving_lut
->getPort("\\A").chunks();
612 for (auto &chunk
: driver_a
)
613 chunk
.wire
= module
->wires_
[remap_name(chunk
.wire
->name
)];
614 RTLIL::Const driver_lut
= driving_lut
->getParam("\\LUT");
615 for (auto &b
: driver_lut
.bits
) {
616 if (b
== RTLIL::State::S0
) b
= RTLIL::State::S1
;
617 else if (b
== RTLIL::State::S1
) b
= RTLIL::State::S0
;
619 cell
= module
->addLut(remap_name(stringf("%s$lut", c
->name
.c_str())),
621 RTLIL::SigBit(module
->wires_
[remap_name(y_bit
.wire
->name
)], y_bit
.offset
),
626 cell
= module
->addCell(remap_name(c
->name
), "$_NOT_");
627 cell
->setPort("\\A", RTLIL::SigBit(module
->wires_
[remap_name(a_bit
.wire
->name
)], a_bit
.offset
));
628 cell
->setPort("\\Y", RTLIL::SigBit(module
->wires_
[remap_name(y_bit
.wire
->name
)], y_bit
.offset
));
629 cell_stats
[RTLIL::unescape_id(c
->type
)]++;
631 if (cell
&& markgroups
) cell
->attributes
["\\abcgroup"] = map_autoidx
;
634 cell_stats
[RTLIL::unescape_id(c
->type
)]++;
636 RTLIL::Cell
*existing_cell
= nullptr;
637 if (c
->type
== "$lut") {
638 if (GetSize(c
->getPort("\\A")) == 1 && c
->getParam("\\LUT").as_int() == 2) {
639 SigSpec my_a
= module
->wires_
[remap_name(c
->getPort("\\A").as_wire()->name
)];
640 SigSpec my_y
= module
->wires_
[remap_name(c
->getPort("\\Y").as_wire()->name
)];
641 module
->connect(my_y
, my_a
);
642 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_
[remap_name(c
.wire
->name
)];
672 cell
->setPort(conn
.first
, newsig
);
676 for (auto cell
: boxes
)
677 module
->remove(cell
);
679 // Copy connections (and rename) from mapped_mod to module
680 for (auto conn
: mapped_mod
->connections()) {
681 if (!conn
.first
.is_fully_const()) {
682 auto chunks
= conn
.first
.chunks();
683 for (auto &c
: chunks
)
684 c
.wire
= module
->wires_
[remap_name(c
.wire
->name
)];
685 conn
.first
= std::move(chunks
);
687 if (!conn
.second
.is_fully_const()) {
688 auto chunks
= conn
.second
.chunks();
689 for (auto &c
: chunks
)
691 c
.wire
= module
->wires_
[remap_name(c
.wire
->name
)];
692 conn
.second
= std::move(chunks
);
694 module
->connect(conn
);
697 for (auto &it
: cell_stats
)
698 log("ABC RESULTS: %15s cells: %8d\n", it
.first
.c_str(), it
.second
);
699 int in_wires
= 0, out_wires
= 0;
701 // Stitch in mapped_mod's inputs/outputs into module
702 for (auto &it
: mapped_mod
->wires_
) {
703 RTLIL::Wire
*w
= it
.second
;
704 if (!w
->port_input
&& !w
->port_output
)
706 RTLIL::Wire
*wire
= module
->wire(w
->name
);
708 RTLIL::Wire
*remap_wire
= module
->wire(remap_name(w
->name
));
709 RTLIL::SigSpec signal
= RTLIL::SigSpec(wire
, 0, GetSize(remap_wire
));
710 log_assert(GetSize(signal
) >= GetSize(remap_wire
));
712 log_assert(w
->port_input
|| w
->port_output
);
715 conn
.first
= remap_wire
;
716 conn
.second
= signal
;
718 module
->connect(conn
);
720 if (w
->port_output
) {
722 conn
.second
= remap_wire
;
724 module
->connect(conn
);
728 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
729 log("ABC RESULTS: input signals: %8d\n", in_wires
);
730 log("ABC RESULTS: output signals: %8d\n", out_wires
);
732 design
->remove(mapped_mod
);
736 log("Don't call ABC as there is nothing to map.\n");
741 log("Removing temp directory.\n");
742 remove_directory(tempdir_name
);
748 struct Abc9Pass
: public Pass
{
749 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
750 void help() YS_OVERRIDE
752 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
754 log(" abc9 [options] [selection]\n");
756 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
757 log("library to a target architecture.\n");
759 log(" -exe <command>\n");
761 log(" use the specified command instead of \"" ABCEXTERNAL
"\" to execute ABC.\n");
763 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
765 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
767 log(" -script <file>\n");
768 log(" use the specified ABC script file instead of the default script.\n");
770 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
771 log(" string is interpreted as the command string to be passed to ABC. The\n");
772 log(" leading plus sign is removed and all commas (,) in the string are\n");
773 log(" replaced with blanks before the string is passed to ABC.\n");
775 log(" if no -script parameter is given, the following scripts are used:\n");
777 log(" for -lut/-luts (only one LUT size):\n");
778 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
/*"; lutpack {S}"*/).c_str());
780 log(" for -lut/-luts (different LUT sizes):\n");
781 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
).c_str());
784 log(" use different default scripts that are slightly faster (at the cost\n");
785 log(" of output quality):\n");
787 log(" for -lut/-luts:\n");
788 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT
).c_str());
790 log(" -D <picoseconds>\n");
791 log(" set delay target. the string {D} in the default scripts above is\n");
792 log(" replaced by this option when used, and an empty string otherwise\n");
793 log(" (indicating best possible delay).\n");
794 // log(" This also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
795 // log(" default scripts above.\n");
797 // log(" -S <num>\n");
798 // log(" maximum number of LUT inputs shared.\n");
799 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
801 log(" -lut <width>\n");
802 log(" generate netlist using luts of (max) the specified width.\n");
804 log(" -lut <w1>:<w2>\n");
805 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
806 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
807 log(" the area cost doubles with each additional input bit. the delay cost\n");
808 log(" is still constant for all lut widths.\n");
810 log(" -lut <file>\n");
811 log(" pass this file with lut library to ABC.\n");
813 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
814 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
815 log(" 2, 3, .. inputs.\n");
818 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
819 // log(" clock domains are automatically partitioned in clock domains and each\n");
820 // log(" domain is passed through ABC independently.\n");
822 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
823 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
824 // log(" cells that belong to the specified clock domain are used.\n");
826 // log(" -keepff\n");
827 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
828 // log(" them, for example for equivalence checking.)\n");
830 log(" -nocleanup\n");
831 log(" when this option is used, the temporary files created by this pass\n");
832 log(" are not removed. this is useful for debugging.\n");
835 log(" print the temp dir name in log. usually this is suppressed so that the\n");
836 log(" command output is identical across runs.\n");
838 log(" -markgroups\n");
839 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
840 log(" this attribute is a unique integer for each ABC process started. This\n");
841 log(" is useful for debugging the partitioning of clock domains.\n");
843 log(" -box <file>\n");
844 log(" pass this file with box library to ABC. Use with -lut.\n");
846 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
847 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
848 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
849 log("output when passing an ABC script that writes a file. Instead write your full\n");
850 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
851 log("you want to use ABC to convert your design into another format.\n");
853 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
856 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
858 log_header(design
, "Executing ABC9 pass (technology mapping using ABC9).\n");
864 std::string exe_file
= ABCEXTERNAL
;
866 std::string exe_file
= proc_self_dirname() + "yosys-abc";
868 std::string script_file
, clk_str
, box_file
, lut_file
;
869 std::string delay_target
, lutin_shared
= "-S 1", wire_delay
;
870 bool fast_mode
= false, dff_mode
= false, keepff
= false, cleanup
= true;
871 bool show_tempdir
= false;
872 vector
<int> lut_costs
;
882 if (!check_file_exists(exe_file
+ ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
883 exe_file
= proc_self_dirname() + "..\\yosys-abc";
889 if (!getcwd(pwd
, sizeof(pwd
))) {
890 log_cmd_error("getcwd failed: %s\n", strerror(errno
));
893 for (argidx
= 1; argidx
< args
.size(); argidx
++) {
894 std::string arg
= args
[argidx
];
895 if (arg
== "-exe" && argidx
+1 < args
.size()) {
896 exe_file
= args
[++argidx
];
899 if (arg
== "-script" && argidx
+1 < args
.size()) {
900 script_file
= args
[++argidx
];
901 rewrite_filename(script_file
);
902 if (!script_file
.empty() && !is_absolute_path(script_file
) && script_file
[0] != '+')
903 script_file
= std::string(pwd
) + "/" + script_file
;
906 if (arg
== "-D" && argidx
+1 < args
.size()) {
907 delay_target
= "-D " + args
[++argidx
];
910 //if (arg == "-S" && argidx+1 < args.size()) {
911 // lutin_shared = "-S " + args[++argidx];
914 if (arg
== "-lut" && argidx
+1 < args
.size()) {
915 string arg
= args
[++argidx
];
916 size_t pos
= arg
.find_first_of(':');
917 int lut_mode
= 0, lut_mode2
= 0;
918 if (pos
!= string::npos
) {
919 lut_mode
= atoi(arg
.substr(0, pos
).c_str());
920 lut_mode2
= atoi(arg
.substr(pos
+1).c_str());
922 pos
= arg
.find_first_of('.');
923 if (pos
!= string::npos
) {
925 rewrite_filename(lut_file
);
926 if (!lut_file
.empty() && !is_absolute_path(lut_file
))
927 lut_file
= std::string(pwd
) + "/" + lut_file
;
930 lut_mode
= atoi(arg
.c_str());
931 lut_mode2
= lut_mode
;
935 for (int i
= 0; i
< lut_mode
; i
++)
936 lut_costs
.push_back(1);
937 for (int i
= lut_mode
; i
< lut_mode2
; i
++)
938 lut_costs
.push_back(2 << (i
- lut_mode
));
941 if (arg
== "-luts" && argidx
+1 < args
.size()) {
943 for (auto &tok
: split_tokens(args
[++argidx
], ",")) {
944 auto parts
= split_tokens(tok
, ":");
945 if (GetSize(parts
) == 0 && !lut_costs
.empty())
946 lut_costs
.push_back(lut_costs
.back());
947 else if (GetSize(parts
) == 1)
948 lut_costs
.push_back(atoi(parts
.at(0).c_str()));
949 else if (GetSize(parts
) == 2)
950 while (GetSize(lut_costs
) < atoi(parts
.at(0).c_str()))
951 lut_costs
.push_back(atoi(parts
.at(1).c_str()));
953 log_cmd_error("Invalid -luts syntax.\n");
957 if (arg
== "-fast") {
961 //if (arg == "-dff") {
965 //if (arg == "-clk" && argidx+1 < args.size()) {
966 // clk_str = args[++argidx];
970 //if (arg == "-keepff") {
974 if (arg
== "-nocleanup") {
978 if (arg
== "-showtmp") {
982 if (arg
== "-markgroups") {
986 if (arg
== "-box" && argidx
+1 < args
.size()) {
987 box_file
= args
[++argidx
];
988 rewrite_filename(box_file
);
989 if (!box_file
.empty() && !is_absolute_path(box_file
))
990 box_file
= std::string(pwd
) + "/" + box_file
;
993 if (arg
== "-W" && argidx
+1 < args
.size()) {
994 wire_delay
= "-W " + args
[++argidx
];
999 extra_args(args
, argidx
, design
);
1001 for (auto mod
: design
->selected_modules())
1003 if (mod
->attributes
.count("\\abc_box_id"))
1006 if (mod
->processes
.size() > 0) {
1007 log("Skipping module %s as it contains processes.\n", log_id(mod
));
1011 assign_map
.set(mod
);
1013 if (!dff_mode
|| !clk_str
.empty()) {
1014 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, dff_mode
, clk_str
, keepff
,
1015 delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1016 box_file
, lut_file
, wire_delay
);
1020 CellTypes
ct(design
);
1022 std::vector
<RTLIL::Cell
*> all_cells
= mod
->selected_cells();
1023 std::set
<RTLIL::Cell
*> unassigned_cells(all_cells
.begin(), all_cells
.end());
1025 std::set
<RTLIL::Cell
*> expand_queue
, next_expand_queue
;
1026 std::set
<RTLIL::Cell
*> expand_queue_up
, next_expand_queue_up
;
1027 std::set
<RTLIL::Cell
*> expand_queue_down
, next_expand_queue_down
;
1029 typedef tuple
<bool, RTLIL::SigSpec
, bool, RTLIL::SigSpec
> clkdomain_t
;
1030 std::map
<clkdomain_t
, std::vector
<RTLIL::Cell
*>> assigned_cells
;
1031 std::map
<RTLIL::Cell
*, clkdomain_t
> assigned_cells_reverse
;
1033 std::map
<RTLIL::Cell
*, std::set
<RTLIL::SigBit
>> cell_to_bit
, cell_to_bit_up
, cell_to_bit_down
;
1034 std::map
<RTLIL::SigBit
, std::set
<RTLIL::Cell
*>> bit_to_cell
, bit_to_cell_up
, bit_to_cell_down
;
1036 for (auto cell
: all_cells
)
1040 for (auto &conn
: cell
->connections())
1041 for (auto bit
: conn
.second
) {
1042 bit
= assign_map(bit
);
1043 if (bit
.wire
!= nullptr) {
1044 cell_to_bit
[cell
].insert(bit
);
1045 bit_to_cell
[bit
].insert(cell
);
1046 if (ct
.cell_input(cell
->type
, conn
.first
)) {
1047 cell_to_bit_up
[cell
].insert(bit
);
1048 bit_to_cell_down
[bit
].insert(cell
);
1050 if (ct
.cell_output(cell
->type
, conn
.first
)) {
1051 cell_to_bit_down
[cell
].insert(bit
);
1052 bit_to_cell_up
[bit
].insert(cell
);
1057 if (cell
->type
== "$_DFF_N_" || cell
->type
== "$_DFF_P_")
1059 key
= clkdomain_t(cell
->type
== "$_DFF_P_", assign_map(cell
->getPort("\\C")), true, RTLIL::SigSpec());
1062 if (cell
->type
== "$_DFFE_NN_" || cell
->type
== "$_DFFE_NP_" || cell
->type
== "$_DFFE_PN_" || cell
->type
== "$_DFFE_PP_")
1064 bool this_clk_pol
= cell
->type
== "$_DFFE_PN_" || cell
->type
== "$_DFFE_PP_";
1065 bool this_en_pol
= cell
->type
== "$_DFFE_NP_" || cell
->type
== "$_DFFE_PP_";
1066 key
= clkdomain_t(this_clk_pol
, assign_map(cell
->getPort("\\C")), this_en_pol
, assign_map(cell
->getPort("\\E")));
1071 unassigned_cells
.erase(cell
);
1072 expand_queue
.insert(cell
);
1073 expand_queue_up
.insert(cell
);
1074 expand_queue_down
.insert(cell
);
1076 assigned_cells
[key
].push_back(cell
);
1077 assigned_cells_reverse
[cell
] = key
;
1080 while (!expand_queue_up
.empty() || !expand_queue_down
.empty())
1082 if (!expand_queue_up
.empty())
1084 RTLIL::Cell
*cell
= *expand_queue_up
.begin();
1085 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1086 expand_queue_up
.erase(cell
);
1088 for (auto bit
: cell_to_bit_up
[cell
])
1089 for (auto c
: bit_to_cell_up
[bit
])
1090 if (unassigned_cells
.count(c
)) {
1091 unassigned_cells
.erase(c
);
1092 next_expand_queue_up
.insert(c
);
1093 assigned_cells
[key
].push_back(c
);
1094 assigned_cells_reverse
[c
] = key
;
1095 expand_queue
.insert(c
);
1099 if (!expand_queue_down
.empty())
1101 RTLIL::Cell
*cell
= *expand_queue_down
.begin();
1102 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1103 expand_queue_down
.erase(cell
);
1105 for (auto bit
: cell_to_bit_down
[cell
])
1106 for (auto c
: bit_to_cell_down
[bit
])
1107 if (unassigned_cells
.count(c
)) {
1108 unassigned_cells
.erase(c
);
1109 next_expand_queue_up
.insert(c
);
1110 assigned_cells
[key
].push_back(c
);
1111 assigned_cells_reverse
[c
] = key
;
1112 expand_queue
.insert(c
);
1116 if (expand_queue_up
.empty() && expand_queue_down
.empty()) {
1117 expand_queue_up
.swap(next_expand_queue_up
);
1118 expand_queue_down
.swap(next_expand_queue_down
);
1122 while (!expand_queue
.empty())
1124 RTLIL::Cell
*cell
= *expand_queue
.begin();
1125 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1126 expand_queue
.erase(cell
);
1128 for (auto bit
: cell_to_bit
.at(cell
)) {
1129 for (auto c
: bit_to_cell
[bit
])
1130 if (unassigned_cells
.count(c
)) {
1131 unassigned_cells
.erase(c
);
1132 next_expand_queue
.insert(c
);
1133 assigned_cells
[key
].push_back(c
);
1134 assigned_cells_reverse
[c
] = key
;
1136 bit_to_cell
[bit
].clear();
1139 if (expand_queue
.empty())
1140 expand_queue
.swap(next_expand_queue
);
1143 clkdomain_t
key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1144 for (auto cell
: unassigned_cells
) {
1145 assigned_cells
[key
].push_back(cell
);
1146 assigned_cells_reverse
[cell
] = key
;
1149 log_header(design
, "Summary of detected clock domains:\n");
1150 for (auto &it
: assigned_cells
)
1151 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it
.second
),
1152 std::get
<0>(it
.first
) ? "" : "!", log_signal(std::get
<1>(it
.first
)),
1153 std::get
<2>(it
.first
) ? "" : "!", log_signal(std::get
<3>(it
.first
)));
1155 for (auto &it
: assigned_cells
) {
1156 clk_polarity
= std::get
<0>(it
.first
);
1157 clk_sig
= assign_map(std::get
<1>(it
.first
));
1158 en_polarity
= std::get
<2>(it
.first
);
1159 en_sig
= assign_map(std::get
<3>(it
.first
));
1160 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, !clk_sig
.empty(), "$",
1161 keepff
, delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1162 box_file
, lut_file
, wire_delay
);
1163 assign_map
.set(mod
);
1167 Pass::call(design
, "clean");
1175 PRIVATE_NAMESPACE_END