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 inline std::string
remap_name(RTLIL::IdString abc_name
)
76 return stringf("$abc$%d$%s", map_autoidx
, abc_name
.c_str()+1);
79 void handle_loops(RTLIL::Design
*design
)
81 Pass::call(design
, "scc -set_attr abc_scc_id {}");
83 // For every unique SCC found, (arbitrarily) find the first
84 // cell in the component, and select (and mark) all its output
86 pool
<RTLIL::Const
> ids_seen
;
87 for (auto cell
: module
->cells()) {
88 auto it
= cell
->attributes
.find(ID(abc_scc_id
));
89 if (it
!= cell
->attributes
.end()) {
90 auto r
= ids_seen
.insert(it
->second
);
92 for (auto &c
: cell
->connections_
) {
93 if (c
.second
.is_fully_const()) continue;
94 if (cell
->output(c
.first
)) {
95 SigBit b
= c
.second
.as_bit();
97 log_assert(!w
->port_input
);
99 w
= module
->wire(stringf("%s.abci", w
->name
.c_str()));
101 w
= module
->addWire(stringf("%s.abci", b
.wire
->name
.c_str()), GetSize(b
.wire
));
102 w
->port_output
= true;
105 log_assert(w
->port_input
);
106 log_assert(b
.offset
< GetSize(w
));
108 w
->set_bool_attribute(ID(abc_scc_break
));
109 module
->swap_names(b
.wire
, w
);
110 c
.second
= RTLIL::SigBit(w
, b
.offset
);
114 cell
->attributes
.erase(it
);
118 module
->fixup_ports();
121 std::string
add_echos_to_abc_cmd(std::string str
)
123 std::string new_str
, token
;
124 for (size_t i
= 0; i
< str
.size(); i
++) {
127 while (i
+1 < str
.size() && str
[i
+1] == ' ')
129 new_str
+= "echo + " + token
+ " " + token
+ " ";
134 if (!token
.empty()) {
135 if (!new_str
.empty())
136 new_str
+= "echo + " + token
+ "; ";
143 std::string
fold_abc_cmd(std::string str
)
145 std::string token
, new_str
= " ";
146 int char_counter
= 10;
148 for (size_t i
= 0; i
<= str
.size(); i
++) {
151 if (i
== str
.size() || str
[i
] == ';') {
152 if (char_counter
+ token
.size() > 75)
153 new_str
+= "\n ", char_counter
= 14;
154 new_str
+= token
, char_counter
+= token
.size();
162 std::string
replace_tempdir(std::string text
, std::string tempdir_name
, bool show_tempdir
)
168 size_t pos
= text
.find(tempdir_name
);
169 if (pos
== std::string::npos
)
171 text
= text
.substr(0, pos
) + "<abc-temp-dir>" + text
.substr(pos
+ GetSize(tempdir_name
));
174 std::string selfdir_name
= proc_self_dirname();
175 if (selfdir_name
!= "/") {
177 size_t pos
= text
.find(selfdir_name
);
178 if (pos
== std::string::npos
)
180 text
= text
.substr(0, pos
) + "<yosys-exe-dir>/" + text
.substr(pos
+ GetSize(selfdir_name
));
187 struct abc_output_filter
190 int escape_seq_state
;
192 std::string tempdir_name
;
195 abc_output_filter(std::string tempdir_name
, bool show_tempdir
) : tempdir_name(tempdir_name
), show_tempdir(show_tempdir
)
198 escape_seq_state
= 0;
201 void next_char(char ch
)
203 if (escape_seq_state
== 0 && ch
== '\033') {
204 escape_seq_state
= 1;
207 if (escape_seq_state
== 1) {
208 escape_seq_state
= ch
== '[' ? 2 : 0;
211 if (escape_seq_state
== 2) {
212 if ((ch
< '0' || '9' < ch
) && ch
!= ';')
213 escape_seq_state
= 0;
216 escape_seq_state
= 0;
222 log("ABC: %s\n", replace_tempdir(linebuf
, tempdir_name
, show_tempdir
).c_str());
223 got_cr
= false, linebuf
.clear();
227 got_cr
= false, linebuf
.clear();
231 void next_line(const std::string
&line
)
234 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
235 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
236 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
237 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
246 void abc9_module(RTLIL::Design
*design
, RTLIL::Module
*current_module
, std::string script_file
, std::string exe_file
,
247 bool cleanup
, vector
<int> lut_costs
, bool dff_mode
, std::string clk_str
,
248 bool /*keepff*/, std::string delay_target
, std::string
/*lutin_shared*/, bool fast_mode
,
249 bool show_tempdir
, std::string box_file
, std::string lut_file
,
250 std::string wire_delay
, const dict
<int,IdString
> &box_lookup
253 module
= current_module
;
254 map_autoidx
= autoidx
++;
259 clk_sig
= RTLIL::SigSpec();
262 en_sig
= RTLIL::SigSpec();
265 if (!clk_str
.empty() && clk_str
!= "$")
267 if (clk_str
.find(',') != std::string::npos
) {
268 int pos
= clk_str
.find(',');
269 std::string en_str
= clk_str
.substr(pos
+1);
270 clk_str
= clk_str
.substr(0, pos
);
271 if (en_str
[0] == '!') {
273 en_str
= en_str
.substr(1);
275 if (module
->wires_
.count(RTLIL::escape_id(en_str
)) != 0)
276 en_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(en_str
)), 0));
278 if (clk_str
[0] == '!') {
279 clk_polarity
= false;
280 clk_str
= clk_str
.substr(1);
282 if (module
->wires_
.count(RTLIL::escape_id(clk_str
)) != 0)
283 clk_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(clk_str
)), 0));
286 if (dff_mode
&& clk_sig
.empty())
287 log_cmd_error("Clock domain %s not found.\n", clk_str
.c_str());
289 std::string tempdir_name
= "/tmp/yosys-abc-XXXXXX";
291 tempdir_name
[0] = tempdir_name
[4] = '_';
292 tempdir_name
= make_temp_dir(tempdir_name
);
293 log_header(design
, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
294 module
->name
.c_str(), replace_tempdir(tempdir_name
, tempdir_name
, show_tempdir
).c_str());
296 std::string abc_script
;
298 if (!lut_costs
.empty()) {
299 abc_script
+= stringf("read_lut %s/lutdefs.txt; ", tempdir_name
.c_str());
300 if (!box_file
.empty())
301 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
304 if (!lut_file
.empty()) {
305 abc_script
+= stringf("read_lut %s; ", lut_file
.c_str());
306 if (!box_file
.empty())
307 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
312 abc_script
+= stringf("&read %s/input.xaig; &ps; ", tempdir_name
.c_str());
314 if (!script_file
.empty()) {
315 if (script_file
[0] == '+') {
316 for (size_t i
= 1; i
< script_file
.size(); i
++)
317 if (script_file
[i
] == '\'')
318 abc_script
+= "'\\''";
319 else if (script_file
[i
] == ',')
322 abc_script
+= script_file
[i
];
324 abc_script
+= stringf("source %s", script_file
.c_str());
325 } else if (!lut_costs
.empty() || !lut_file
.empty()) {
326 //bool all_luts_cost_same = true;
327 //for (int this_cost : lut_costs)
328 // if (this_cost != lut_costs.front())
329 // all_luts_cost_same = false;
330 abc_script
+= fast_mode
? ABC_FAST_COMMAND_LUT
: ABC_COMMAND_LUT
;
331 //if (all_luts_cost_same && !fast_mode)
332 // abc_script += "; lutpack {S}";
336 //if (script_file.empty() && !delay_target.empty())
337 // for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
338 // abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
340 for (size_t pos
= abc_script
.find("{D}"); pos
!= std::string::npos
; pos
= abc_script
.find("{D}", pos
))
341 abc_script
= abc_script
.substr(0, pos
) + delay_target
+ abc_script
.substr(pos
+3);
343 //for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
344 // abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
346 for (size_t pos
= abc_script
.find("{W}"); pos
!= std::string::npos
; pos
= abc_script
.find("{W}", pos
))
347 abc_script
= abc_script
.substr(0, pos
) + wire_delay
+ abc_script
.substr(pos
+3);
349 abc_script
+= stringf("; &write %s/output.aig", tempdir_name
.c_str());
350 abc_script
= add_echos_to_abc_cmd(abc_script
);
352 for (size_t i
= 0; i
+1 < abc_script
.size(); i
++)
353 if (abc_script
[i
] == ';' && abc_script
[i
+1] == ' ')
354 abc_script
[i
+1] = '\n';
356 FILE *f
= fopen(stringf("%s/abc.script", tempdir_name
.c_str()).c_str(), "wt");
357 fprintf(f
, "%s\n", abc_script
.c_str());
360 if (dff_mode
|| !clk_str
.empty())
362 if (clk_sig
.size() == 0)
363 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str
.empty() ? "" : " matching");
365 log("Found%s %s clock domain: %s", clk_str
.empty() ? "" : " matching", clk_polarity
? "posedge" : "negedge", log_signal(clk_sig
));
366 if (en_sig
.size() != 0)
367 log(", enabled by %s%s", en_polarity
? "" : "!", log_signal(en_sig
));
372 bool count_output
= false;
373 for (auto port_name
: module
->ports
) {
374 RTLIL::Wire
*port_wire
= module
->wire(port_name
);
375 log_assert(port_wire
);
376 if (port_wire
->port_output
) {
386 design
->selection_stack
.emplace_back(false);
387 RTLIL::Selection
& sel
= design
->selection_stack
.back();
390 handle_loops(design
);
392 Pass::call(design
, "aigmap");
394 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
395 // count_gates, GetSize(signal_list), count_input, count_output);
397 Pass::call(design
, stringf("write_xaiger -map %s/input.sym %s/input.xaig", tempdir_name
.c_str(), tempdir_name
.c_str()));
402 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.xaig");
405 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
406 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
407 log_assert(!design
->module(ID($__abc9__
)));
409 AigerReader
reader(design
, ifs
, ID($__abc9__
), "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
410 reader
.parse_xaiger();
413 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
414 design
->remove(design
->module(ID($__abc9__
)));
417 design
->selection_stack
.pop_back();
419 // Now 'unexpose' those wires by undoing
420 // the expose operation -- remove them from PO/PI
421 // and re-connecting them back together
422 for (auto wire
: module
->wires()) {
423 auto it
= wire
->attributes
.find(ID(abc_scc_break
));
424 if (it
!= wire
->attributes
.end()) {
425 wire
->attributes
.erase(it
);
426 log_assert(wire
->port_output
);
427 wire
->port_output
= false;
428 RTLIL::Wire
*i_wire
= module
->wire(wire
->name
.str() + ".abci");
430 log_assert(i_wire
->port_input
);
431 i_wire
->port_input
= false;
432 module
->connect(i_wire
, wire
);
435 module
->fixup_ports();
437 log_header(design
, "Executing ABC9.\n");
439 if (!lut_costs
.empty()) {
440 buffer
= stringf("%s/lutdefs.txt", tempdir_name
.c_str());
441 f
= fopen(buffer
.c_str(), "wt");
443 log_error("Opening %s for writing failed: %s\n", buffer
.c_str(), strerror(errno
));
444 for (int i
= 0; i
< GetSize(lut_costs
); i
++)
445 fprintf(f
, "%d %d.00 1.00\n", i
+1, lut_costs
.at(i
));
449 buffer
= stringf("%s -s -f %s/abc.script 2>&1", exe_file
.c_str(), tempdir_name
.c_str());
450 log("Running ABC command: %s\n", replace_tempdir(buffer
, tempdir_name
, show_tempdir
).c_str());
452 #ifndef YOSYS_LINK_ABC
453 abc_output_filter
filt(tempdir_name
, show_tempdir
);
454 int ret
= run_command(buffer
, std::bind(&abc_output_filter::next_line
, filt
, std::placeholders::_1
));
456 // These needs to be mutable, supposedly due to getopt
458 string tmp_script_name
= stringf("%s/abc.script", tempdir_name
.c_str());
459 abc_argv
[0] = strdup(exe_file
.c_str());
460 abc_argv
[1] = strdup("-s");
461 abc_argv
[2] = strdup("-f");
462 abc_argv
[3] = strdup(tmp_script_name
.c_str());
464 int ret
= Abc_RealMain(4, abc_argv
);
471 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer
.c_str(), ret
);
473 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "output.aig");
476 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
478 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
479 log_assert(!design
->module(ID($__abc9__
)));
481 AigerReader
reader(design
, ifs
, ID($__abc9__
), "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
482 reader
.parse_xaiger(box_lookup
);
486 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
489 log_header(design
, "Re-integrating ABC9 results.\n");
490 RTLIL::Module
*mapped_mod
= design
->module(ID($__abc9__
));
491 if (mapped_mod
== NULL
)
492 log_error("ABC output file does not contain a module `$__abc9__'.\n");
494 pool
<RTLIL::SigBit
> output_bits
;
495 for (auto &it
: mapped_mod
->wires_
) {
496 RTLIL::Wire
*w
= it
.second
;
497 RTLIL::Wire
*remap_wire
= module
->addWire(remap_name(w
->name
), GetSize(w
));
498 if (markgroups
) remap_wire
->attributes
[ID(abcgroup
)] = map_autoidx
;
499 if (w
->port_output
) {
500 RTLIL::Wire
*wire
= module
->wire(w
->name
);
502 for (int i
= 0; i
< GetSize(w
); i
++)
503 output_bits
.insert({wire
, i
});
507 for (auto &it
: module
->connections_
) {
508 auto &signal
= it
.first
;
509 auto bits
= signal
.bits();
511 if (output_bits
.count(b
))
512 b
= module
->addWire(NEW_ID
);
513 signal
= std::move(bits
);
516 dict
<IdString
, bool> abc_box
;
517 vector
<RTLIL::Cell
*> boxes
;
518 for (const auto &it
: module
->cells_
) {
519 auto cell
= it
.second
;
520 if (cell
->type
.in(ID($_AND_
), ID($_NOT_
))) {
521 module
->remove(cell
);
524 auto jt
= abc_box
.find(cell
->type
);
525 if (jt
== abc_box
.end()) {
526 RTLIL::Module
* box_module
= design
->module(cell
->type
);
527 jt
= abc_box
.insert(std::make_pair(cell
->type
, box_module
&& box_module
->attributes
.count(ID(abc_box_id
)))).first
;
530 boxes
.emplace_back(cell
);
533 dict
<SigBit
, pool
<IdString
>> bit_drivers
, bit_users
;
534 TopoSort
<IdString
, RTLIL::sort_by_id_str
> toposort
;
535 dict
<RTLIL::Cell
*,RTLIL::Cell
*> not2drivers
;
536 dict
<SigBit
, std::vector
<RTLIL::Cell
*>> bit2sinks
;
538 std::map
<IdString
, int> cell_stats
;
539 for (auto c
: mapped_mod
->cells())
541 toposort
.node(c
->name
);
543 RTLIL::Cell
*cell
= nullptr;
544 if (c
->type
== ID($_NOT_
)) {
545 RTLIL::SigBit a_bit
= c
->getPort(ID::A
);
546 RTLIL::SigBit y_bit
= c
->getPort(ID::Y
);
547 bit_users
[a_bit
].insert(c
->name
);
548 bit_drivers
[y_bit
].insert(c
->name
);
551 c
->setPort(ID::Y
, module
->addWire(NEW_ID
));
552 RTLIL::Wire
*wire
= module
->wire(remap_name(y_bit
.wire
->name
));
554 module
->connect(RTLIL::SigBit(wire
, y_bit
.offset
), State::S1
);
556 else if (!lut_costs
.empty() || !lut_file
.empty()) {
557 RTLIL::Cell
* driver_lut
= nullptr;
558 // ABC can return NOT gates that drive POs
559 if (!a_bit
.wire
->port_input
) {
560 // If it's not a NOT gate that that comes from a PI directly,
561 // find the driver LUT and clone that to guarantee that we won't
562 // increase the max logic depth
563 // (TODO: Optimise by not cloning unless will increase depth)
564 RTLIL::IdString driver_name
;
565 if (GetSize(a_bit
.wire
) == 1)
566 driver_name
= stringf("%s$lut", a_bit
.wire
->name
.c_str());
568 driver_name
= stringf("%s[%d]$lut", a_bit
.wire
->name
.c_str(), a_bit
.offset
);
569 driver_lut
= mapped_mod
->cell(driver_name
);
573 // If a driver couldn't be found (could be from PI or box CI)
574 // then implement using a LUT
575 cell
= module
->addLut(remap_name(stringf("%s$lut", c
->name
.c_str())),
576 RTLIL::SigBit(module
->wires_
.at(remap_name(a_bit
.wire
->name
)), a_bit
.offset
),
577 RTLIL::SigBit(module
->wires_
.at(remap_name(y_bit
.wire
->name
)), y_bit
.offset
),
578 RTLIL::Const::from_string("01"));
579 bit2sinks
[cell
->getPort(ID::A
)].push_back(cell
);
580 cell_stats
[ID($lut
)]++;
583 not2drivers
[c
] = driver_lut
;
588 if (cell
&& markgroups
) cell
->attributes
[ID(abcgroup
)] = map_autoidx
;
591 cell_stats
[c
->type
]++;
593 RTLIL::Cell
*existing_cell
= nullptr;
594 if (c
->type
== ID($lut
)) {
595 if (GetSize(c
->getPort(ID::A
)) == 1 && c
->getParam(ID(LUT
)) == RTLIL::Const::from_string("01")) {
596 SigSpec my_a
= module
->wires_
.at(remap_name(c
->getPort(ID::A
).as_wire()->name
));
597 SigSpec my_y
= module
->wires_
.at(remap_name(c
->getPort(ID::Y
).as_wire()->name
));
598 module
->connect(my_y
, my_a
);
599 if (markgroups
) c
->attributes
[ID(abcgroup
)] = map_autoidx
;
603 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
606 existing_cell
= module
->cell(c
->name
);
607 log_assert(existing_cell
);
608 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
611 if (markgroups
) cell
->attributes
[ID(abcgroup
)] = map_autoidx
;
613 cell
->parameters
= existing_cell
->parameters
;
614 cell
->attributes
= existing_cell
->attributes
;
617 cell
->parameters
= c
->parameters
;
618 cell
->attributes
= c
->attributes
;
620 for (auto &conn
: c
->connections()) {
621 RTLIL::SigSpec newsig
;
622 for (auto c
: conn
.second
.chunks()) {
625 //log_assert(c.width == 1);
627 c
.wire
= module
->wires_
.at(remap_name(c
.wire
->name
));
630 cell
->setPort(conn
.first
, newsig
);
632 if (cell
->input(conn
.first
)) {
633 for (auto i
: newsig
)
634 bit2sinks
[i
].push_back(cell
);
635 for (auto i
: conn
.second
)
636 bit_users
[i
].insert(c
->name
);
638 if (cell
->output(conn
.first
))
639 for (auto i
: conn
.second
)
640 bit_drivers
[i
].insert(c
->name
);
644 for (auto existing_cell
: boxes
) {
645 Cell
*cell
= module
->cell(remap_name(existing_cell
->name
));
647 for (auto &conn
: existing_cell
->connections()) {
648 if (!conn
.second
.is_wire())
650 Wire
*wire
= conn
.second
.as_wire();
651 if (!wire
->get_bool_attribute(ID(abc_padding
)))
653 cell
->unsetPort(conn
.first
);
654 log_debug("Dropping padded port connection for %s (%s) .%s (%s )\n", log_id(cell
), cell
->type
.c_str(), log_id(conn
.first
), log_signal(conn
.second
));
656 module
->swap_names(cell
, existing_cell
);
658 module
->remove(existing_cell
);
661 // Copy connections (and rename) from mapped_mod to module
662 for (auto conn
: mapped_mod
->connections()) {
663 if (!conn
.first
.is_fully_const()) {
664 auto chunks
= conn
.first
.chunks();
665 for (auto &c
: chunks
)
666 c
.wire
= module
->wires_
.at(remap_name(c
.wire
->name
));
667 conn
.first
= std::move(chunks
);
669 if (!conn
.second
.is_fully_const()) {
670 auto chunks
= conn
.second
.chunks();
671 for (auto &c
: chunks
)
673 c
.wire
= module
->wires_
.at(remap_name(c
.wire
->name
));
674 conn
.second
= std::move(chunks
);
676 module
->connect(conn
);
679 for (auto &it
: cell_stats
)
680 log("ABC RESULTS: %15s cells: %8d\n", it
.first
.c_str(), it
.second
);
681 int in_wires
= 0, out_wires
= 0;
683 // Stitch in mapped_mod's inputs/outputs into module
684 for (auto port
: mapped_mod
->ports
) {
685 RTLIL::Wire
*w
= mapped_mod
->wire(port
);
686 RTLIL::Wire
*wire
= module
->wire(port
);
688 RTLIL::Wire
*remap_wire
= module
->wire(remap_name(port
));
689 RTLIL::SigSpec signal
= RTLIL::SigSpec(wire
, 0, GetSize(remap_wire
));
690 log_assert(GetSize(signal
) >= GetSize(remap_wire
));
693 if (w
->port_output
) {
695 conn
.second
= remap_wire
;
697 module
->connect(conn
);
699 else if (w
->port_input
) {
700 conn
.first
= remap_wire
;
701 conn
.second
= signal
;
703 module
->connect(conn
);
707 for (auto &it
: bit_users
)
708 if (bit_drivers
.count(it
.first
))
709 for (auto driver_cell
: bit_drivers
.at(it
.first
))
710 for (auto user_cell
: it
.second
)
711 toposort
.edge(driver_cell
, user_cell
);
712 bool no_loops
YS_ATTRIBUTE(unused
) = toposort
.sort();
713 log_assert(no_loops
);
715 for (auto ii
= toposort
.sorted
.rbegin(); ii
!= toposort
.sorted
.rend(); ii
++) {
716 RTLIL::Cell
*not_cell
= mapped_mod
->cell(*ii
);
717 log_assert(not_cell
);
718 if (not_cell
->type
!= ID($_NOT_
))
720 auto it
= not2drivers
.find(not_cell
);
721 if (it
== not2drivers
.end())
723 RTLIL::Cell
*driver_lut
= it
->second
;
724 RTLIL::SigBit a_bit
= not_cell
->getPort(ID::A
);
725 RTLIL::SigBit y_bit
= not_cell
->getPort(ID::Y
);
726 RTLIL::Const driver_mask
;
728 a_bit
.wire
= module
->wires_
.at(remap_name(a_bit
.wire
->name
));
729 y_bit
.wire
= module
->wires_
.at(remap_name(y_bit
.wire
->name
));
731 auto jt
= bit2sinks
.find(a_bit
);
732 if (jt
== bit2sinks
.end())
735 for (auto sink_cell
: jt
->second
)
736 if (sink_cell
->type
!= ID($lut
))
739 // Push downstream LUTs past inverter
740 for (auto sink_cell
: jt
->second
) {
741 SigSpec A
= sink_cell
->getPort(ID::A
);
742 RTLIL::Const mask
= sink_cell
->getParam(ID(LUT
));
744 for (; index
< GetSize(A
); index
++)
745 if (A
[index
] == a_bit
)
747 log_assert(index
< GetSize(A
));
749 while (i
< GetSize(mask
)) {
750 for (int j
= 0; j
< (1 << index
); j
++)
751 std::swap(mask
[i
+j
], mask
[i
+j
+(1 << index
)]);
755 sink_cell
->setPort(ID::A
, A
);
756 sink_cell
->setParam(ID(LUT
), mask
);
759 // Since we have rewritten all sinks (which we know
760 // to be only LUTs) to be after the inverter, we can
761 // go ahead and clone the LUT with the expectation
762 // that the original driving LUT will become dangling
763 // and get cleaned away
765 driver_mask
= driver_lut
->getParam(ID(LUT
));
766 for (auto &b
: driver_mask
.bits
) {
767 if (b
== RTLIL::State::S0
) b
= RTLIL::State::S1
;
768 else if (b
== RTLIL::State::S1
) b
= RTLIL::State::S0
;
770 auto cell
= module
->addLut(NEW_ID
,
771 driver_lut
->getPort(ID::A
),
774 for (auto &bit
: cell
->connections_
.at(ID::A
)) {
775 bit
.wire
= module
->wires_
.at(remap_name(bit
.wire
->name
));
776 bit2sinks
[bit
].push_back(cell
);
780 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
781 log("ABC RESULTS: input signals: %8d\n", in_wires
);
782 log("ABC RESULTS: output signals: %8d\n", out_wires
);
784 design
->remove(mapped_mod
);
788 log("Don't call ABC as there is nothing to map.\n");
793 log("Removing temp directory.\n");
794 remove_directory(tempdir_name
);
800 struct Abc9Pass
: public Pass
{
801 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
802 void help() YS_OVERRIDE
804 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
806 log(" abc9 [options] [selection]\n");
808 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
809 log("library to a target architecture.\n");
811 log(" -exe <command>\n");
813 log(" use the specified command instead of \"" ABCEXTERNAL
"\" to execute ABC.\n");
815 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
817 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
819 log(" -script <file>\n");
820 log(" use the specified ABC script file instead of the default script.\n");
822 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
823 log(" string is interpreted as the command string to be passed to ABC. The\n");
824 log(" leading plus sign is removed and all commas (,) in the string are\n");
825 log(" replaced with blanks before the string is passed to ABC.\n");
827 log(" if no -script parameter is given, the following scripts are used:\n");
829 log(" for -lut/-luts (only one LUT size):\n");
830 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
/*"; lutpack {S}"*/).c_str());
832 log(" for -lut/-luts (different LUT sizes):\n");
833 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
).c_str());
836 log(" use different default scripts that are slightly faster (at the cost\n");
837 log(" of output quality):\n");
839 log(" for -lut/-luts:\n");
840 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT
).c_str());
842 log(" -D <picoseconds>\n");
843 log(" set delay target. the string {D} in the default scripts above is\n");
844 log(" replaced by this option when used, and an empty string otherwise\n");
845 log(" (indicating best possible delay).\n");
846 // log(" This also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
847 // log(" default scripts above.\n");
849 // log(" -S <num>\n");
850 // log(" maximum number of LUT inputs shared.\n");
851 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
853 log(" -lut <width>\n");
854 log(" generate netlist using luts of (max) the specified width.\n");
856 log(" -lut <w1>:<w2>\n");
857 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
858 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
859 log(" the area cost doubles with each additional input bit. the delay cost\n");
860 log(" is still constant for all lut widths.\n");
862 log(" -lut <file>\n");
863 log(" pass this file with lut library to ABC.\n");
865 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
866 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
867 log(" 2, 3, .. inputs.\n");
870 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
871 // log(" clock domains are automatically partitioned in clock domains and each\n");
872 // log(" domain is passed through ABC independently.\n");
874 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
875 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
876 // log(" cells that belong to the specified clock domain are used.\n");
878 // log(" -keepff\n");
879 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
880 // log(" them, for example for equivalence checking.)\n");
882 log(" -nocleanup\n");
883 log(" when this option is used, the temporary files created by this pass\n");
884 log(" are not removed. this is useful for debugging.\n");
887 log(" print the temp dir name in log. usually this is suppressed so that the\n");
888 log(" command output is identical across runs.\n");
890 log(" -markgroups\n");
891 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
892 log(" this attribute is a unique integer for each ABC process started. This\n");
893 log(" is useful for debugging the partitioning of clock domains.\n");
895 log(" -box <file>\n");
896 log(" pass this file with box library to ABC. Use with -lut.\n");
898 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
899 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
900 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
901 log("output when passing an ABC script that writes a file. Instead write your full\n");
902 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
903 log("you want to use ABC to convert your design into another format.\n");
905 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
908 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
910 log_header(design
, "Executing ABC9 pass (technology mapping using ABC9).\n");
916 std::string exe_file
= ABCEXTERNAL
;
918 std::string exe_file
= proc_self_dirname() + "yosys-abc";
920 std::string script_file
, clk_str
, box_file
, lut_file
;
921 std::string delay_target
, lutin_shared
= "-S 1", wire_delay
;
922 bool fast_mode
= false, dff_mode
= false, keepff
= false, cleanup
= true;
923 bool show_tempdir
= false;
924 vector
<int> lut_costs
;
934 if (!check_file_exists(exe_file
+ ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
935 exe_file
= proc_self_dirname() + "..\\yosys-abc";
941 if (!getcwd(pwd
, sizeof(pwd
))) {
942 log_cmd_error("getcwd failed: %s\n", strerror(errno
));
945 for (argidx
= 1; argidx
< args
.size(); argidx
++) {
946 std::string arg
= args
[argidx
];
947 if (arg
== "-exe" && argidx
+1 < args
.size()) {
948 exe_file
= args
[++argidx
];
951 if (arg
== "-script" && argidx
+1 < args
.size()) {
952 script_file
= args
[++argidx
];
953 rewrite_filename(script_file
);
954 if (!script_file
.empty() && !is_absolute_path(script_file
) && script_file
[0] != '+')
955 script_file
= std::string(pwd
) + "/" + script_file
;
958 if (arg
== "-D" && argidx
+1 < args
.size()) {
959 delay_target
= "-D " + args
[++argidx
];
962 //if (arg == "-S" && argidx+1 < args.size()) {
963 // lutin_shared = "-S " + args[++argidx];
966 if (arg
== "-lut" && argidx
+1 < args
.size()) {
967 string arg
= args
[++argidx
];
968 size_t pos
= arg
.find_first_of(':');
969 int lut_mode
= 0, lut_mode2
= 0;
970 if (pos
!= string::npos
) {
971 lut_mode
= atoi(arg
.substr(0, pos
).c_str());
972 lut_mode2
= atoi(arg
.substr(pos
+1).c_str());
974 pos
= arg
.find_first_of('.');
975 if (pos
!= string::npos
) {
977 rewrite_filename(lut_file
);
978 if (!lut_file
.empty() && !is_absolute_path(lut_file
))
979 lut_file
= std::string(pwd
) + "/" + lut_file
;
982 lut_mode
= atoi(arg
.c_str());
983 lut_mode2
= lut_mode
;
987 for (int i
= 0; i
< lut_mode
; i
++)
988 lut_costs
.push_back(1);
989 for (int i
= lut_mode
; i
< lut_mode2
; i
++)
990 lut_costs
.push_back(2 << (i
- lut_mode
));
993 if (arg
== "-luts" && argidx
+1 < args
.size()) {
995 for (auto &tok
: split_tokens(args
[++argidx
], ",")) {
996 auto parts
= split_tokens(tok
, ":");
997 if (GetSize(parts
) == 0 && !lut_costs
.empty())
998 lut_costs
.push_back(lut_costs
.back());
999 else if (GetSize(parts
) == 1)
1000 lut_costs
.push_back(atoi(parts
.at(0).c_str()));
1001 else if (GetSize(parts
) == 2)
1002 while (GetSize(lut_costs
) < atoi(parts
.at(0).c_str()))
1003 lut_costs
.push_back(atoi(parts
.at(1).c_str()));
1005 log_cmd_error("Invalid -luts syntax.\n");
1009 if (arg
== "-fast") {
1013 //if (arg == "-dff") {
1017 //if (arg == "-clk" && argidx+1 < args.size()) {
1018 // clk_str = args[++argidx];
1022 //if (arg == "-keepff") {
1026 if (arg
== "-nocleanup") {
1030 if (arg
== "-showtmp") {
1031 show_tempdir
= true;
1034 if (arg
== "-markgroups") {
1038 if (arg
== "-box" && argidx
+1 < args
.size()) {
1039 box_file
= args
[++argidx
];
1042 if (arg
== "-W" && argidx
+1 < args
.size()) {
1043 wire_delay
= "-W " + args
[++argidx
];
1048 extra_args(args
, argidx
, design
);
1050 // ABC expects a box file for XAIG
1051 if (box_file
.empty())
1052 box_file
= "+/dummy.box";
1054 rewrite_filename(box_file
);
1055 if (!box_file
.empty() && !is_absolute_path(box_file
))
1056 box_file
= std::string(pwd
) + "/" + box_file
;
1058 dict
<int,IdString
> box_lookup
;
1059 for (auto m
: design
->modules()) {
1060 auto it
= m
->attributes
.find(ID(abc_box_id
));
1061 if (it
== m
->attributes
.end())
1063 if (m
->name
.begins_with("$paramod"))
1065 auto id
= it
->second
.as_int();
1066 auto r
= box_lookup
.insert(std::make_pair(id
, m
->name
));
1068 log_error("Module '%s' has the same abc_box_id = %d value as '%s'.\n",
1069 log_id(m
), id
, log_id(r
.first
->second
));
1070 log_assert(r
.second
);
1072 RTLIL::Wire
*carry_in
= nullptr, *carry_out
= nullptr;
1073 for (auto p
: m
->ports
) {
1074 auto w
= m
->wire(p
);
1076 if (w
->attributes
.count(ID(abc_carry
))) {
1077 if (w
->port_input
) {
1079 log_error("Module '%s' contains more than one 'abc_carry' input port.\n", log_id(m
));
1082 else if (w
->port_output
) {
1084 log_error("Module '%s' contains more than one 'abc_carry' input port.\n", log_id(m
));
1089 if (carry_in
|| carry_out
) {
1090 if (carry_in
&& !carry_out
)
1091 log_error("Module '%s' contains an 'abc_carry' input port but no output port.\n", log_id(m
));
1092 if (!carry_in
&& carry_out
)
1093 log_error("Module '%s' contains an 'abc_carry' output port but no input port.\n", log_id(m
));
1094 // Make carry_in the last PI, and carry_out the last PO
1095 // since ABC requires it this way
1096 auto &ports
= m
->ports
;
1097 for (auto it
= ports
.begin(); it
!= ports
.end(); ) {
1098 RTLIL::Wire
* w
= m
->wire(*it
);
1100 if (w
== carry_in
|| w
== carry_out
) {
1101 it
= ports
.erase(it
);
1104 if (w
->port_id
> carry_in
->port_id
)
1106 if (w
->port_id
> carry_out
->port_id
)
1108 log_assert(w
->port_input
|| w
->port_output
);
1109 log_assert(ports
[w
->port_id
-1] == w
->name
);
1112 ports
.push_back(carry_in
->name
);
1113 carry_in
->port_id
= ports
.size();
1114 ports
.push_back(carry_out
->name
);
1115 carry_out
->port_id
= ports
.size();
1119 for (auto mod
: design
->selected_modules())
1121 if (mod
->attributes
.count(ID(abc_box_id
)))
1124 if (mod
->processes
.size() > 0) {
1125 log("Skipping module %s as it contains processes.\n", log_id(mod
));
1129 assign_map
.set(mod
);
1131 if (!dff_mode
|| !clk_str
.empty()) {
1132 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, dff_mode
, clk_str
, keepff
,
1133 delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1134 box_file
, lut_file
, wire_delay
, box_lookup
);
1138 CellTypes
ct(design
);
1140 std::vector
<RTLIL::Cell
*> all_cells
= mod
->selected_cells();
1141 std::set
<RTLIL::Cell
*> unassigned_cells(all_cells
.begin(), all_cells
.end());
1143 std::set
<RTLIL::Cell
*> expand_queue
, next_expand_queue
;
1144 std::set
<RTLIL::Cell
*> expand_queue_up
, next_expand_queue_up
;
1145 std::set
<RTLIL::Cell
*> expand_queue_down
, next_expand_queue_down
;
1147 typedef tuple
<bool, RTLIL::SigSpec
, bool, RTLIL::SigSpec
> clkdomain_t
;
1148 std::map
<clkdomain_t
, std::vector
<RTLIL::Cell
*>> assigned_cells
;
1149 std::map
<RTLIL::Cell
*, clkdomain_t
> assigned_cells_reverse
;
1151 std::map
<RTLIL::Cell
*, std::set
<RTLIL::SigBit
>> cell_to_bit
, cell_to_bit_up
, cell_to_bit_down
;
1152 std::map
<RTLIL::SigBit
, std::set
<RTLIL::Cell
*>> bit_to_cell
, bit_to_cell_up
, bit_to_cell_down
;
1154 for (auto cell
: all_cells
)
1158 for (auto &conn
: cell
->connections())
1159 for (auto bit
: conn
.second
) {
1160 bit
= assign_map(bit
);
1161 if (bit
.wire
!= nullptr) {
1162 cell_to_bit
[cell
].insert(bit
);
1163 bit_to_cell
[bit
].insert(cell
);
1164 if (ct
.cell_input(cell
->type
, conn
.first
)) {
1165 cell_to_bit_up
[cell
].insert(bit
);
1166 bit_to_cell_down
[bit
].insert(cell
);
1168 if (ct
.cell_output(cell
->type
, conn
.first
)) {
1169 cell_to_bit_down
[cell
].insert(bit
);
1170 bit_to_cell_up
[bit
].insert(cell
);
1175 if (cell
->type
.in(ID($_DFF_N_
), ID($_DFF_P_
)))
1177 key
= clkdomain_t(cell
->type
== ID($_DFF_P_
), assign_map(cell
->getPort(ID(C
))), true, RTLIL::SigSpec());
1180 if (cell
->type
.in(ID($_DFFE_NN_
), ID($_DFFE_NP_
), ID($_DFFE_PN_
), ID($_DFFE_PP_
)))
1182 bool this_clk_pol
= cell
->type
.in(ID($_DFFE_PN_
), ID($_DFFE_PP_
));
1183 bool this_en_pol
= cell
->type
.in(ID($_DFFE_NP_
), ID($_DFFE_PP_
));
1184 key
= clkdomain_t(this_clk_pol
, assign_map(cell
->getPort(ID(C
))), this_en_pol
, assign_map(cell
->getPort(ID(E
))));
1189 unassigned_cells
.erase(cell
);
1190 expand_queue
.insert(cell
);
1191 expand_queue_up
.insert(cell
);
1192 expand_queue_down
.insert(cell
);
1194 assigned_cells
[key
].push_back(cell
);
1195 assigned_cells_reverse
[cell
] = key
;
1198 while (!expand_queue_up
.empty() || !expand_queue_down
.empty())
1200 if (!expand_queue_up
.empty())
1202 RTLIL::Cell
*cell
= *expand_queue_up
.begin();
1203 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1204 expand_queue_up
.erase(cell
);
1206 for (auto bit
: cell_to_bit_up
[cell
])
1207 for (auto c
: bit_to_cell_up
[bit
])
1208 if (unassigned_cells
.count(c
)) {
1209 unassigned_cells
.erase(c
);
1210 next_expand_queue_up
.insert(c
);
1211 assigned_cells
[key
].push_back(c
);
1212 assigned_cells_reverse
[c
] = key
;
1213 expand_queue
.insert(c
);
1217 if (!expand_queue_down
.empty())
1219 RTLIL::Cell
*cell
= *expand_queue_down
.begin();
1220 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1221 expand_queue_down
.erase(cell
);
1223 for (auto bit
: cell_to_bit_down
[cell
])
1224 for (auto c
: bit_to_cell_down
[bit
])
1225 if (unassigned_cells
.count(c
)) {
1226 unassigned_cells
.erase(c
);
1227 next_expand_queue_up
.insert(c
);
1228 assigned_cells
[key
].push_back(c
);
1229 assigned_cells_reverse
[c
] = key
;
1230 expand_queue
.insert(c
);
1234 if (expand_queue_up
.empty() && expand_queue_down
.empty()) {
1235 expand_queue_up
.swap(next_expand_queue_up
);
1236 expand_queue_down
.swap(next_expand_queue_down
);
1240 while (!expand_queue
.empty())
1242 RTLIL::Cell
*cell
= *expand_queue
.begin();
1243 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1244 expand_queue
.erase(cell
);
1246 for (auto bit
: cell_to_bit
.at(cell
)) {
1247 for (auto c
: bit_to_cell
[bit
])
1248 if (unassigned_cells
.count(c
)) {
1249 unassigned_cells
.erase(c
);
1250 next_expand_queue
.insert(c
);
1251 assigned_cells
[key
].push_back(c
);
1252 assigned_cells_reverse
[c
] = key
;
1254 bit_to_cell
[bit
].clear();
1257 if (expand_queue
.empty())
1258 expand_queue
.swap(next_expand_queue
);
1261 clkdomain_t
key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1262 for (auto cell
: unassigned_cells
) {
1263 assigned_cells
[key
].push_back(cell
);
1264 assigned_cells_reverse
[cell
] = key
;
1267 log_header(design
, "Summary of detected clock domains:\n");
1268 for (auto &it
: assigned_cells
)
1269 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it
.second
),
1270 std::get
<0>(it
.first
) ? "" : "!", log_signal(std::get
<1>(it
.first
)),
1271 std::get
<2>(it
.first
) ? "" : "!", log_signal(std::get
<3>(it
.first
)));
1273 for (auto &it
: assigned_cells
) {
1274 clk_polarity
= std::get
<0>(it
.first
);
1275 clk_sig
= assign_map(std::get
<1>(it
.first
));
1276 en_polarity
= std::get
<2>(it
.first
);
1277 en_sig
= assign_map(std::get
<3>(it
.first
));
1278 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, !clk_sig
.empty(), "$",
1279 keepff
, delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1280 box_file
, lut_file
, wire_delay
, box_lookup
);
1281 assign_map
.set(mod
);
1291 PRIVATE_NAMESPACE_END