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 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(ID(\\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(ID(\\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(ID(\\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(ID(\\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
, const dict
<int,IdString
> &box_lookup
)
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 handle_loops(design
);
432 Pass::call(design
, "aigmap");
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(ID($__abc9__
)));
449 AigerReader
reader(design
, ifs
, ID($__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(ID($__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(ID(\\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();
477 log_header(design
, "Executing ABC9.\n");
479 if (!lut_costs
.empty()) {
480 buffer
= stringf("%s/lutdefs.txt", tempdir_name
.c_str());
481 f
= fopen(buffer
.c_str(), "wt");
483 log_error("Opening %s for writing failed: %s\n", buffer
.c_str(), strerror(errno
));
484 for (int i
= 0; i
< GetSize(lut_costs
); i
++)
485 fprintf(f
, "%d %d.00 1.00\n", i
+1, lut_costs
.at(i
));
489 buffer
= stringf("%s -s -f %s/abc.script 2>&1", exe_file
.c_str(), tempdir_name
.c_str());
490 log("Running ABC command: %s\n", replace_tempdir(buffer
, tempdir_name
, show_tempdir
).c_str());
492 #ifndef YOSYS_LINK_ABC
493 abc_output_filter
filt(tempdir_name
, show_tempdir
);
494 int ret
= run_command(buffer
, std::bind(&abc_output_filter::next_line
, filt
, std::placeholders::_1
));
496 // These needs to be mutable, supposedly due to getopt
498 string tmp_script_name
= stringf("%s/abc.script", tempdir_name
.c_str());
499 abc_argv
[0] = strdup(exe_file
.c_str());
500 abc_argv
[1] = strdup("-s");
501 abc_argv
[2] = strdup("-f");
502 abc_argv
[3] = strdup(tmp_script_name
.c_str());
504 int ret
= Abc_RealMain(4, abc_argv
);
511 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer
.c_str(), ret
);
513 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "output.aig");
516 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
518 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
519 log_assert(!design
->module(ID($__abc9__
)));
521 AigerReader
reader(design
, ifs
, ID($__abc9__
), "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
522 reader
.parse_xaiger(box_lookup
);
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(ID($__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
[ID(\\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(ID($_AND_
), ID($_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(ID(\\abc_box_id
)))).first
;
570 boxes
.emplace_back(cell
);
573 dict
<SigBit
, pool
<IdString
>> bit_drivers
, bit_users
;
574 TopoSort
<IdString
, RTLIL::sort_by_id_str
> toposort
;
575 dict
<RTLIL::Cell
*,RTLIL::Cell
*> not2drivers
;
576 dict
<SigBit
, std::vector
<RTLIL::Cell
*>> bit2sinks
;
578 std::map
<IdString
, int> cell_stats
;
579 for (auto c
: mapped_mod
->cells())
581 toposort
.node(c
->name
);
583 RTLIL::Cell
*cell
= nullptr;
584 if (c
->type
== ID($_NOT_
)) {
585 RTLIL::SigBit a_bit
= c
->getPort(ID(\\A
));
586 RTLIL::SigBit y_bit
= c
->getPort(ID(\\Y
));
587 bit_users
[a_bit
].insert(c
->name
);
588 bit_drivers
[y_bit
].insert(c
->name
);
591 c
->setPort(ID(\\Y
), module
->addWire(NEW_ID
));
592 RTLIL::Wire
*wire
= module
->wire(remap_name(y_bit
.wire
->name
));
594 module
->connect(RTLIL::SigBit(wire
, y_bit
.offset
), State::S1
);
596 else if (!lut_costs
.empty() || !lut_file
.empty()) {
597 RTLIL::Cell
* driver_lut
= nullptr;
598 // ABC can return NOT gates that drive POs
599 if (!a_bit
.wire
->port_input
) {
600 // If it's not a NOT gate that that comes from a PI directly,
601 // find the driver LUT and clone that to guarantee that we won't
602 // increase the max logic depth
603 // (TODO: Optimise by not cloning unless will increase depth)
604 RTLIL::IdString driver_name
;
605 if (GetSize(a_bit
.wire
) == 1)
606 driver_name
= stringf("%s$lut", a_bit
.wire
->name
.c_str());
608 driver_name
= stringf("%s[%d]$lut", a_bit
.wire
->name
.c_str(), a_bit
.offset
);
609 driver_lut
= mapped_mod
->cell(driver_name
);
613 // If a driver couldn't be found (could be from PI or box CI)
614 // then implement using a LUT
615 cell
= module
->addLut(remap_name(stringf("%s$lut", c
->name
.c_str())),
616 RTLIL::SigBit(module
->wires_
.at(remap_name(a_bit
.wire
->name
)), a_bit
.offset
),
617 RTLIL::SigBit(module
->wires_
.at(remap_name(y_bit
.wire
->name
)), y_bit
.offset
),
618 RTLIL::Const::from_string("01"));
619 bit2sinks
[cell
->getPort(ID(\\A
))].push_back(cell
);
620 cell_stats
[ID($lut
)]++;
623 not2drivers
[c
] = driver_lut
;
628 if (cell
&& markgroups
) cell
->attributes
[ID(\\abcgroup
)] = map_autoidx
;
631 cell_stats
[RTLIL::unescape_id(c
->type
)]++;
633 RTLIL::Cell
*existing_cell
= nullptr;
634 if (c
->type
== ID($lut
)) {
635 if (GetSize(c
->getPort(ID(\\A
))) == 1 && c
->getParam(ID(\\LUT
)) == RTLIL::Const::from_string("01")) {
636 SigSpec my_a
= module
->wires_
.at(remap_name(c
->getPort(ID(\\A
)).as_wire()->name
));
637 SigSpec my_y
= module
->wires_
.at(remap_name(c
->getPort(ID(\\Y
)).as_wire()->name
));
638 module
->connect(my_y
, my_a
);
639 if (markgroups
) c
->attributes
[ID(\\abcgroup
)] = map_autoidx
;
643 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
646 existing_cell
= module
->cell(c
->name
);
647 log_assert(existing_cell
);
648 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
649 module
->swap_names(cell
, existing_cell
);
652 if (markgroups
) cell
->attributes
[ID(\\abcgroup
)] = map_autoidx
;
654 cell
->parameters
= existing_cell
->parameters
;
655 cell
->attributes
= existing_cell
->attributes
;
658 cell
->parameters
= c
->parameters
;
659 cell
->attributes
= c
->attributes
;
661 for (auto &conn
: c
->connections()) {
662 RTLIL::SigSpec newsig
;
663 for (auto c
: conn
.second
.chunks()) {
666 //log_assert(c.width == 1);
668 c
.wire
= module
->wires_
.at(remap_name(c
.wire
->name
));
671 cell
->setPort(conn
.first
, newsig
);
673 if (cell
->input(conn
.first
)) {
674 for (auto i
: newsig
)
675 bit2sinks
[i
].push_back(cell
);
676 for (auto i
: conn
.second
)
677 bit_users
[i
].insert(c
->name
);
679 if (cell
->output(conn
.first
))
680 for (auto i
: conn
.second
)
681 bit_drivers
[i
].insert(c
->name
);
685 for (auto cell
: boxes
)
686 module
->remove(cell
);
688 // Copy connections (and rename) from mapped_mod to module
689 for (auto conn
: mapped_mod
->connections()) {
690 if (!conn
.first
.is_fully_const()) {
691 auto chunks
= conn
.first
.chunks();
692 for (auto &c
: chunks
)
693 c
.wire
= module
->wires_
.at(remap_name(c
.wire
->name
));
694 conn
.first
= std::move(chunks
);
696 if (!conn
.second
.is_fully_const()) {
697 auto chunks
= conn
.second
.chunks();
698 for (auto &c
: chunks
)
700 c
.wire
= module
->wires_
.at(remap_name(c
.wire
->name
));
701 conn
.second
= std::move(chunks
);
703 module
->connect(conn
);
706 for (auto &it
: cell_stats
)
707 log("ABC RESULTS: %15s cells: %8d\n", it
.first
.c_str(), it
.second
);
708 int in_wires
= 0, out_wires
= 0;
710 // Stitch in mapped_mod's inputs/outputs into module
711 for (auto &it
: mapped_mod
->wires_
) {
712 RTLIL::Wire
*w
= it
.second
;
713 if (!w
->port_input
&& !w
->port_output
)
715 RTLIL::Wire
*wire
= module
->wire(w
->name
);
717 RTLIL::Wire
*remap_wire
= module
->wire(remap_name(w
->name
));
718 RTLIL::SigSpec signal
= RTLIL::SigSpec(wire
, 0, GetSize(remap_wire
));
719 log_assert(GetSize(signal
) >= GetSize(remap_wire
));
721 log_assert(w
->port_input
|| w
->port_output
);
724 conn
.first
= remap_wire
;
725 conn
.second
= signal
;
727 module
->connect(conn
);
729 if (w
->port_output
) {
731 conn
.second
= remap_wire
;
733 module
->connect(conn
);
737 for (auto &it
: bit_users
)
738 if (bit_drivers
.count(it
.first
))
739 for (auto driver_cell
: bit_drivers
.at(it
.first
))
740 for (auto user_cell
: it
.second
)
741 toposort
.edge(driver_cell
, user_cell
);
742 bool no_loops
= toposort
.sort();
743 log_assert(no_loops
);
745 for (auto ii
= toposort
.sorted
.rbegin(); ii
!= toposort
.sorted
.rend(); ii
++) {
746 RTLIL::Cell
*not_cell
= mapped_mod
->cell(*ii
);
747 log_assert(not_cell
);
748 if (not_cell
->type
!= ID($_NOT_
))
750 auto it
= not2drivers
.find(not_cell
);
751 if (it
== not2drivers
.end())
753 RTLIL::Cell
*driver_lut
= it
->second
;
754 RTLIL::SigBit a_bit
= not_cell
->getPort(ID(\\A
));
755 RTLIL::SigBit y_bit
= not_cell
->getPort(ID(\\Y
));
756 RTLIL::Const driver_mask
;
758 a_bit
.wire
= module
->wires_
.at(remap_name(a_bit
.wire
->name
));
759 y_bit
.wire
= module
->wires_
.at(remap_name(y_bit
.wire
->name
));
761 auto jt
= bit2sinks
.find(a_bit
);
762 if (jt
== bit2sinks
.end())
765 for (auto sink_cell
: jt
->second
)
766 if (sink_cell
->type
!= ID($lut
))
769 // Push downstream LUTs past inverter
770 for (auto sink_cell
: jt
->second
) {
771 SigSpec A
= sink_cell
->getPort(ID(\\A
));
772 RTLIL::Const mask
= sink_cell
->getParam(ID(\\LUT
));
774 for (; index
< GetSize(A
); index
++)
775 if (A
[index
] == a_bit
)
777 log_assert(index
< GetSize(A
));
779 while (i
< GetSize(mask
)) {
780 for (int j
= 0; j
< (1 << index
); j
++)
781 std::swap(mask
[i
+j
], mask
[i
+j
+(1 << index
)]);
785 sink_cell
->setPort(ID(\\A
), A
);
786 sink_cell
->setParam(ID(\\LUT
), mask
);
789 // Since we have rewritten all sinks (which we know
790 // to be only LUTs) to be after the inverter, we can
791 // go ahead and clone the LUT with the expectation
792 // that the original driving LUT will become dangling
793 // and get cleaned away
795 driver_mask
= driver_lut
->getParam(ID(\\LUT
));
796 for (auto &b
: driver_mask
.bits
) {
797 if (b
== RTLIL::State::S0
) b
= RTLIL::State::S1
;
798 else if (b
== RTLIL::State::S1
) b
= RTLIL::State::S0
;
800 auto cell
= module
->addLut(NEW_ID
,
801 driver_lut
->getPort(ID(\\A
)),
804 for (auto &bit
: cell
->connections_
.at(ID(\\A
))) {
805 bit
.wire
= module
->wires_
.at(remap_name(bit
.wire
->name
));
806 bit2sinks
[bit
].push_back(cell
);
810 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
811 log("ABC RESULTS: input signals: %8d\n", in_wires
);
812 log("ABC RESULTS: output signals: %8d\n", out_wires
);
814 design
->remove(mapped_mod
);
818 log("Don't call ABC as there is nothing to map.\n");
823 log("Removing temp directory.\n");
824 remove_directory(tempdir_name
);
830 struct Abc9Pass
: public Pass
{
831 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
832 void help() YS_OVERRIDE
834 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
836 log(" abc9 [options] [selection]\n");
838 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
839 log("library to a target architecture.\n");
841 log(" -exe <command>\n");
843 log(" use the specified command instead of \"" ABCEXTERNAL
"\" to execute ABC.\n");
845 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
847 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
849 log(" -script <file>\n");
850 log(" use the specified ABC script file instead of the default script.\n");
852 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
853 log(" string is interpreted as the command string to be passed to ABC. The\n");
854 log(" leading plus sign is removed and all commas (,) in the string are\n");
855 log(" replaced with blanks before the string is passed to ABC.\n");
857 log(" if no -script parameter is given, the following scripts are used:\n");
859 log(" for -lut/-luts (only one LUT size):\n");
860 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
/*"; lutpack {S}"*/).c_str());
862 log(" for -lut/-luts (different LUT sizes):\n");
863 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
).c_str());
866 log(" use different default scripts that are slightly faster (at the cost\n");
867 log(" of output quality):\n");
869 log(" for -lut/-luts:\n");
870 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT
).c_str());
872 log(" -D <picoseconds>\n");
873 log(" set delay target. the string {D} in the default scripts above is\n");
874 log(" replaced by this option when used, and an empty string otherwise\n");
875 log(" (indicating best possible delay).\n");
876 // log(" This also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
877 // log(" default scripts above.\n");
879 // log(" -S <num>\n");
880 // log(" maximum number of LUT inputs shared.\n");
881 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
883 log(" -lut <width>\n");
884 log(" generate netlist using luts of (max) the specified width.\n");
886 log(" -lut <w1>:<w2>\n");
887 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
888 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
889 log(" the area cost doubles with each additional input bit. the delay cost\n");
890 log(" is still constant for all lut widths.\n");
892 log(" -lut <file>\n");
893 log(" pass this file with lut library to ABC.\n");
895 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
896 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
897 log(" 2, 3, .. inputs.\n");
900 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
901 // log(" clock domains are automatically partitioned in clock domains and each\n");
902 // log(" domain is passed through ABC independently.\n");
904 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
905 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
906 // log(" cells that belong to the specified clock domain are used.\n");
908 // log(" -keepff\n");
909 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
910 // log(" them, for example for equivalence checking.)\n");
912 log(" -nocleanup\n");
913 log(" when this option is used, the temporary files created by this pass\n");
914 log(" are not removed. this is useful for debugging.\n");
917 log(" print the temp dir name in log. usually this is suppressed so that the\n");
918 log(" command output is identical across runs.\n");
920 log(" -markgroups\n");
921 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
922 log(" this attribute is a unique integer for each ABC process started. This\n");
923 log(" is useful for debugging the partitioning of clock domains.\n");
925 log(" -box <file>\n");
926 log(" pass this file with box library to ABC. Use with -lut.\n");
928 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
929 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
930 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
931 log("output when passing an ABC script that writes a file. Instead write your full\n");
932 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
933 log("you want to use ABC to convert your design into another format.\n");
935 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
938 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
940 log_header(design
, "Executing ABC9 pass (technology mapping using ABC9).\n");
946 std::string exe_file
= ABCEXTERNAL
;
948 std::string exe_file
= proc_self_dirname() + "yosys-abc";
950 std::string script_file
, clk_str
, box_file
, lut_file
;
951 std::string delay_target
, lutin_shared
= "-S 1", wire_delay
;
952 bool fast_mode
= false, dff_mode
= false, keepff
= false, cleanup
= true;
953 bool show_tempdir
= false;
954 vector
<int> lut_costs
;
964 if (!check_file_exists(exe_file
+ ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
965 exe_file
= proc_self_dirname() + "..\\yosys-abc";
971 if (!getcwd(pwd
, sizeof(pwd
))) {
972 log_cmd_error("getcwd failed: %s\n", strerror(errno
));
975 for (argidx
= 1; argidx
< args
.size(); argidx
++) {
976 std::string arg
= args
[argidx
];
977 if (arg
== "-exe" && argidx
+1 < args
.size()) {
978 exe_file
= args
[++argidx
];
981 if (arg
== "-script" && argidx
+1 < args
.size()) {
982 script_file
= args
[++argidx
];
983 rewrite_filename(script_file
);
984 if (!script_file
.empty() && !is_absolute_path(script_file
) && script_file
[0] != '+')
985 script_file
= std::string(pwd
) + "/" + script_file
;
988 if (arg
== "-D" && argidx
+1 < args
.size()) {
989 delay_target
= "-D " + args
[++argidx
];
992 //if (arg == "-S" && argidx+1 < args.size()) {
993 // lutin_shared = "-S " + args[++argidx];
996 if (arg
== "-lut" && argidx
+1 < args
.size()) {
997 string arg
= args
[++argidx
];
998 size_t pos
= arg
.find_first_of(':');
999 int lut_mode
= 0, lut_mode2
= 0;
1000 if (pos
!= string::npos
) {
1001 lut_mode
= atoi(arg
.substr(0, pos
).c_str());
1002 lut_mode2
= atoi(arg
.substr(pos
+1).c_str());
1004 pos
= arg
.find_first_of('.');
1005 if (pos
!= string::npos
) {
1007 rewrite_filename(lut_file
);
1008 if (!lut_file
.empty() && !is_absolute_path(lut_file
))
1009 lut_file
= std::string(pwd
) + "/" + lut_file
;
1012 lut_mode
= atoi(arg
.c_str());
1013 lut_mode2
= lut_mode
;
1017 for (int i
= 0; i
< lut_mode
; i
++)
1018 lut_costs
.push_back(1);
1019 for (int i
= lut_mode
; i
< lut_mode2
; i
++)
1020 lut_costs
.push_back(2 << (i
- lut_mode
));
1023 if (arg
== "-luts" && argidx
+1 < args
.size()) {
1025 for (auto &tok
: split_tokens(args
[++argidx
], ",")) {
1026 auto parts
= split_tokens(tok
, ":");
1027 if (GetSize(parts
) == 0 && !lut_costs
.empty())
1028 lut_costs
.push_back(lut_costs
.back());
1029 else if (GetSize(parts
) == 1)
1030 lut_costs
.push_back(atoi(parts
.at(0).c_str()));
1031 else if (GetSize(parts
) == 2)
1032 while (GetSize(lut_costs
) < atoi(parts
.at(0).c_str()))
1033 lut_costs
.push_back(atoi(parts
.at(1).c_str()));
1035 log_cmd_error("Invalid -luts syntax.\n");
1039 if (arg
== "-fast") {
1043 //if (arg == "-dff") {
1047 //if (arg == "-clk" && argidx+1 < args.size()) {
1048 // clk_str = args[++argidx];
1052 //if (arg == "-keepff") {
1056 if (arg
== "-nocleanup") {
1060 if (arg
== "-showtmp") {
1061 show_tempdir
= true;
1064 if (arg
== "-markgroups") {
1068 if (arg
== "-box" && argidx
+1 < args
.size()) {
1069 box_file
= args
[++argidx
];
1070 rewrite_filename(box_file
);
1071 if (!box_file
.empty() && !is_absolute_path(box_file
))
1072 box_file
= std::string(pwd
) + "/" + box_file
;
1075 if (arg
== "-W" && argidx
+1 < args
.size()) {
1076 wire_delay
= "-W " + args
[++argidx
];
1081 extra_args(args
, argidx
, design
);
1083 dict
<int,IdString
> box_lookup
;
1084 for (auto m
: design
->modules()) {
1085 auto it
= m
->attributes
.find(ID(\\abc_box_id
));
1086 if (it
== m
->attributes
.end())
1088 if (m
->name
.begins_with("$paramod"))
1090 auto id
= it
->second
.as_int();
1091 auto r
= box_lookup
.insert(std::make_pair(id
, m
->name
));
1093 log_error("Module '%s' has the same abc_box_id = %d value as '%s'.\n",
1094 log_id(m
), id
, log_id(r
.first
->second
));
1095 log_assert(r
.second
);
1098 for (auto mod
: design
->selected_modules())
1100 if (mod
->attributes
.count(ID(\\abc_box_id
)))
1103 if (mod
->processes
.size() > 0) {
1104 log("Skipping module %s as it contains processes.\n", log_id(mod
));
1108 assign_map
.set(mod
);
1110 if (!dff_mode
|| !clk_str
.empty()) {
1111 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, dff_mode
, clk_str
, keepff
,
1112 delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1113 box_file
, lut_file
, wire_delay
, box_lookup
);
1117 CellTypes
ct(design
);
1119 std::vector
<RTLIL::Cell
*> all_cells
= mod
->selected_cells();
1120 std::set
<RTLIL::Cell
*> unassigned_cells(all_cells
.begin(), all_cells
.end());
1122 std::set
<RTLIL::Cell
*> expand_queue
, next_expand_queue
;
1123 std::set
<RTLIL::Cell
*> expand_queue_up
, next_expand_queue_up
;
1124 std::set
<RTLIL::Cell
*> expand_queue_down
, next_expand_queue_down
;
1126 typedef tuple
<bool, RTLIL::SigSpec
, bool, RTLIL::SigSpec
> clkdomain_t
;
1127 std::map
<clkdomain_t
, std::vector
<RTLIL::Cell
*>> assigned_cells
;
1128 std::map
<RTLIL::Cell
*, clkdomain_t
> assigned_cells_reverse
;
1130 std::map
<RTLIL::Cell
*, std::set
<RTLIL::SigBit
>> cell_to_bit
, cell_to_bit_up
, cell_to_bit_down
;
1131 std::map
<RTLIL::SigBit
, std::set
<RTLIL::Cell
*>> bit_to_cell
, bit_to_cell_up
, bit_to_cell_down
;
1133 for (auto cell
: all_cells
)
1137 for (auto &conn
: cell
->connections())
1138 for (auto bit
: conn
.second
) {
1139 bit
= assign_map(bit
);
1140 if (bit
.wire
!= nullptr) {
1141 cell_to_bit
[cell
].insert(bit
);
1142 bit_to_cell
[bit
].insert(cell
);
1143 if (ct
.cell_input(cell
->type
, conn
.first
)) {
1144 cell_to_bit_up
[cell
].insert(bit
);
1145 bit_to_cell_down
[bit
].insert(cell
);
1147 if (ct
.cell_output(cell
->type
, conn
.first
)) {
1148 cell_to_bit_down
[cell
].insert(bit
);
1149 bit_to_cell_up
[bit
].insert(cell
);
1154 if (cell
->type
.in(ID($_DFF_N_
), ID($_DFF_P_
)))
1156 key
= clkdomain_t(cell
->type
== ID($_DFF_P_
), assign_map(cell
->getPort(ID(\\C
))), true, RTLIL::SigSpec());
1159 if (cell
->type
.in(ID($_DFFE_NN_
), ID($_DFFE_NP_
), ID($_DFFE_PN_
), ID($_DFFE_PP_
)))
1161 bool this_clk_pol
= cell
->type
.in(ID($_DFFE_PN_
), ID($_DFFE_PP_
));
1162 bool this_en_pol
= cell
->type
.in(ID($_DFFE_NP_
), ID($_DFFE_PP_
));
1163 key
= clkdomain_t(this_clk_pol
, assign_map(cell
->getPort(ID(\\C
))), this_en_pol
, assign_map(cell
->getPort(ID(\\E
))));
1168 unassigned_cells
.erase(cell
);
1169 expand_queue
.insert(cell
);
1170 expand_queue_up
.insert(cell
);
1171 expand_queue_down
.insert(cell
);
1173 assigned_cells
[key
].push_back(cell
);
1174 assigned_cells_reverse
[cell
] = key
;
1177 while (!expand_queue_up
.empty() || !expand_queue_down
.empty())
1179 if (!expand_queue_up
.empty())
1181 RTLIL::Cell
*cell
= *expand_queue_up
.begin();
1182 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1183 expand_queue_up
.erase(cell
);
1185 for (auto bit
: cell_to_bit_up
[cell
])
1186 for (auto c
: bit_to_cell_up
[bit
])
1187 if (unassigned_cells
.count(c
)) {
1188 unassigned_cells
.erase(c
);
1189 next_expand_queue_up
.insert(c
);
1190 assigned_cells
[key
].push_back(c
);
1191 assigned_cells_reverse
[c
] = key
;
1192 expand_queue
.insert(c
);
1196 if (!expand_queue_down
.empty())
1198 RTLIL::Cell
*cell
= *expand_queue_down
.begin();
1199 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1200 expand_queue_down
.erase(cell
);
1202 for (auto bit
: cell_to_bit_down
[cell
])
1203 for (auto c
: bit_to_cell_down
[bit
])
1204 if (unassigned_cells
.count(c
)) {
1205 unassigned_cells
.erase(c
);
1206 next_expand_queue_up
.insert(c
);
1207 assigned_cells
[key
].push_back(c
);
1208 assigned_cells_reverse
[c
] = key
;
1209 expand_queue
.insert(c
);
1213 if (expand_queue_up
.empty() && expand_queue_down
.empty()) {
1214 expand_queue_up
.swap(next_expand_queue_up
);
1215 expand_queue_down
.swap(next_expand_queue_down
);
1219 while (!expand_queue
.empty())
1221 RTLIL::Cell
*cell
= *expand_queue
.begin();
1222 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1223 expand_queue
.erase(cell
);
1225 for (auto bit
: cell_to_bit
.at(cell
)) {
1226 for (auto c
: bit_to_cell
[bit
])
1227 if (unassigned_cells
.count(c
)) {
1228 unassigned_cells
.erase(c
);
1229 next_expand_queue
.insert(c
);
1230 assigned_cells
[key
].push_back(c
);
1231 assigned_cells_reverse
[c
] = key
;
1233 bit_to_cell
[bit
].clear();
1236 if (expand_queue
.empty())
1237 expand_queue
.swap(next_expand_queue
);
1240 clkdomain_t
key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1241 for (auto cell
: unassigned_cells
) {
1242 assigned_cells
[key
].push_back(cell
);
1243 assigned_cells_reverse
[cell
] = key
;
1246 log_header(design
, "Summary of detected clock domains:\n");
1247 for (auto &it
: assigned_cells
)
1248 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it
.second
),
1249 std::get
<0>(it
.first
) ? "" : "!", log_signal(std::get
<1>(it
.first
)),
1250 std::get
<2>(it
.first
) ? "" : "!", log_signal(std::get
<3>(it
.first
)));
1252 for (auto &it
: assigned_cells
) {
1253 clk_polarity
= std::get
<0>(it
.first
);
1254 clk_sig
= assign_map(std::get
<1>(it
.first
));
1255 en_polarity
= std::get
<2>(it
.first
);
1256 en_sig
= assign_map(std::get
<3>(it
.first
));
1257 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, !clk_sig
.empty(), "$",
1258 keepff
, delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1259 box_file
, lut_file
, wire_delay
, box_lookup
);
1260 assign_map
.set(mod
);
1266 // The "clean" pass also contains a design->check() call
1267 Pass::call(design
, "clean");
1273 PRIVATE_NAMESPACE_END