Fix abc9's scc breaker, also break on abc_scc_break attr
[yosys.git] / passes / techmap / abc9.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * 2019 Eddie Hung <eddie@fpgeh.com>
6 *
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.
10 *
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.
18 *
19 */
20
21 // [[CITE]] ABC
22 // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification
23 // http://www.eecs.berkeley.edu/~alanmi/abc/
24
25 #if 0
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"
31 #else
32 #define ABC_COMMAND_LUT "&st; &scorr; &sweep; &dc2; &st; &dch -f; &ps -l; &if {W} {D} -v; "/*"&mfs; "*/"&ps -l"
33 #endif
34
35
36 #define ABC_FAST_COMMAND_LUT "&st; &retime; &if {W}"
37
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"
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <string.h>
46 #include <cerrno>
47 #include <sstream>
48 #include <climits>
49
50 #ifndef _WIN32
51 # include <unistd.h>
52 # include <dirent.h>
53 #endif
54
55 #include "frontends/aiger/aigerparse.h"
56
57 #ifdef YOSYS_LINK_ABC
58 extern "C" int Abc_RealMain(int argc, char *argv[]);
59 #endif
60
61 USING_YOSYS_NAMESPACE
62 PRIVATE_NAMESPACE_BEGIN
63
64 bool markgroups;
65 int map_autoidx;
66 SigMap assign_map;
67 RTLIL::Module *module;
68
69 bool clk_polarity, en_polarity;
70 RTLIL::SigSpec clk_sig, en_sig;
71
72 std::string remap_name(RTLIL::IdString abc_name)
73 {
74 std::stringstream sstr;
75 sstr << "$abc$" << map_autoidx << "$" << abc_name.substr(1);
76 return sstr.str();
77 }
78
79 void handle_loops(RTLIL::Design *design)
80 {
81 Pass::call(design, "scc -set_attr abc_scc_id {}");
82
83 // For every unique SCC found, (arbitrarily) find the first
84 // cell in the component, and select (and mark) all its output
85 // wires
86 pool<RTLIL::Const> ids_seen;
87 for (auto cell : module->cells()) {
88 auto it = cell->attributes.find("\\abc_scc_id");
89 if (it != cell->attributes.end()) {
90 auto r = ids_seen.insert(it->second);
91 if (r.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();
96 Wire *w = b.wire;
97 log_assert(!w->port_input);
98 w->port_input = true;
99 w = module->wire(stringf("%s.abci", log_id(w->name)));
100 if (!w)
101 w = module->addWire(stringf("%s.abci", log_id(b.wire->name)), GetSize(b.wire));
102 log_assert(b.offset < GetSize(w));
103 w->port_output = true;
104 w->set_bool_attribute("\\abc_scc_break");
105 module->swap_names(b.wire, w);
106 c.second = RTLIL::SigBit(w, b.offset);
107 }
108 }
109 }
110 cell->attributes.erase(it);
111 }
112 RTLIL::Module* box_module = design->module(cell->type);
113 if (box_module) {
114 auto jt = box_module->attributes.find("\\abc_scc_break");
115 if (jt != box_module->attributes.end()) {
116 auto it = cell->connections_.find(RTLIL::escape_id(jt->second.decode_string()));
117 log_assert(it != cell->connections_.end());
118 auto &c = *it;
119 SigBit b = cell->getPort(RTLIL::escape_id(jt->second.decode_string()));
120 Wire *w = b.wire;
121 log_assert(!w->port_output);
122 w->port_output = true;
123 w->set_bool_attribute("\\abc_scc_break");
124 w = module->wire(stringf("%s.abci", log_id(w->name)));
125 if (!w)
126 w = module->addWire(stringf("%s.abci", log_id(b.wire->name)), GetSize(b.wire));
127 log_assert(b.offset < GetSize(w));
128 w->port_input = true;
129 c.second = RTLIL::SigBit(w, b.offset);
130 }
131 }
132 }
133
134 module->fixup_ports();
135 }
136
137 std::string add_echos_to_abc_cmd(std::string str)
138 {
139 std::string new_str, token;
140 for (size_t i = 0; i < str.size(); i++) {
141 token += str[i];
142 if (str[i] == ';') {
143 while (i+1 < str.size() && str[i+1] == ' ')
144 i++;
145 new_str += "echo + " + token + " " + token + " ";
146 token.clear();
147 }
148 }
149
150 if (!token.empty()) {
151 if (!new_str.empty())
152 new_str += "echo + " + token + "; ";
153 new_str += token;
154 }
155
156 return new_str;
157 }
158
159 std::string fold_abc_cmd(std::string str)
160 {
161 std::string token, new_str = " ";
162 int char_counter = 10;
163
164 for (size_t i = 0; i <= str.size(); i++) {
165 if (i < str.size())
166 token += str[i];
167 if (i == str.size() || str[i] == ';') {
168 if (char_counter + token.size() > 75)
169 new_str += "\n ", char_counter = 14;
170 new_str += token, char_counter += token.size();
171 token.clear();
172 }
173 }
174
175 return new_str;
176 }
177
178 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
179 {
180 if (show_tempdir)
181 return text;
182
183 while (1) {
184 size_t pos = text.find(tempdir_name);
185 if (pos == std::string::npos)
186 break;
187 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
188 }
189
190 std::string selfdir_name = proc_self_dirname();
191 if (selfdir_name != "/") {
192 while (1) {
193 size_t pos = text.find(selfdir_name);
194 if (pos == std::string::npos)
195 break;
196 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
197 }
198 }
199
200 return text;
201 }
202
203 struct abc_output_filter
204 {
205 bool got_cr;
206 int escape_seq_state;
207 std::string linebuf;
208 std::string tempdir_name;
209 bool show_tempdir;
210
211 abc_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
212 {
213 got_cr = false;
214 escape_seq_state = 0;
215 }
216
217 void next_char(char ch)
218 {
219 if (escape_seq_state == 0 && ch == '\033') {
220 escape_seq_state = 1;
221 return;
222 }
223 if (escape_seq_state == 1) {
224 escape_seq_state = ch == '[' ? 2 : 0;
225 return;
226 }
227 if (escape_seq_state == 2) {
228 if ((ch < '0' || '9' < ch) && ch != ';')
229 escape_seq_state = 0;
230 return;
231 }
232 escape_seq_state = 0;
233 if (ch == '\r') {
234 got_cr = true;
235 return;
236 }
237 if (ch == '\n') {
238 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
239 got_cr = false, linebuf.clear();
240 return;
241 }
242 if (got_cr)
243 got_cr = false, linebuf.clear();
244 linebuf += ch;
245 }
246
247 void next_line(const std::string &line)
248 {
249 //int pi, po;
250 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
251 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
252 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
253 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
254 // return;
255 //}
256
257 for (char ch : line)
258 next_char(ch);
259 }
260 };
261
262 void abc9_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file,
263 bool cleanup, vector<int> lut_costs, bool dff_mode, std::string clk_str,
264 bool /*keepff*/, std::string delay_target, std::string /*lutin_shared*/, bool fast_mode,
265 bool show_tempdir, std::string box_file, std::string lut_file,
266 std::string wire_delay)
267 {
268 module = current_module;
269 map_autoidx = autoidx++;
270
271 if (clk_str != "$")
272 {
273 clk_polarity = true;
274 clk_sig = RTLIL::SigSpec();
275
276 en_polarity = true;
277 en_sig = RTLIL::SigSpec();
278 }
279
280 if (!clk_str.empty() && clk_str != "$")
281 {
282 if (clk_str.find(',') != std::string::npos) {
283 int pos = clk_str.find(',');
284 std::string en_str = clk_str.substr(pos+1);
285 clk_str = clk_str.substr(0, pos);
286 if (en_str[0] == '!') {
287 en_polarity = false;
288 en_str = en_str.substr(1);
289 }
290 if (module->wires_.count(RTLIL::escape_id(en_str)) != 0)
291 en_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(en_str)), 0));
292 }
293 if (clk_str[0] == '!') {
294 clk_polarity = false;
295 clk_str = clk_str.substr(1);
296 }
297 if (module->wires_.count(RTLIL::escape_id(clk_str)) != 0)
298 clk_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(clk_str)), 0));
299 }
300
301 if (dff_mode && clk_sig.empty())
302 log_cmd_error("Clock domain %s not found.\n", clk_str.c_str());
303
304 std::string tempdir_name = "/tmp/yosys-abc-XXXXXX";
305 if (!cleanup)
306 tempdir_name[0] = tempdir_name[4] = '_';
307 tempdir_name = make_temp_dir(tempdir_name);
308 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
309 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
310
311 std::string abc_script;
312
313 if (!lut_costs.empty()) {
314 abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
315 if (!box_file.empty())
316 abc_script += stringf("read_box -v %s; ", box_file.c_str());
317 }
318 else
319 if (!lut_file.empty()) {
320 abc_script += stringf("read_lut %s; ", lut_file.c_str());
321 if (!box_file.empty())
322 abc_script += stringf("read_box -v %s; ", box_file.c_str());
323 }
324 else
325 log_abort();
326
327 abc_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
328
329 if (!script_file.empty()) {
330 if (script_file[0] == '+') {
331 for (size_t i = 1; i < script_file.size(); i++)
332 if (script_file[i] == '\'')
333 abc_script += "'\\''";
334 else if (script_file[i] == ',')
335 abc_script += " ";
336 else
337 abc_script += script_file[i];
338 } else
339 abc_script += stringf("source %s", script_file.c_str());
340 } else if (!lut_costs.empty() || !lut_file.empty()) {
341 //bool all_luts_cost_same = true;
342 //for (int this_cost : lut_costs)
343 // if (this_cost != lut_costs.front())
344 // all_luts_cost_same = false;
345 abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
346 //if (all_luts_cost_same && !fast_mode)
347 // abc_script += "; lutpack {S}";
348 } else
349 log_abort();
350
351 //if (script_file.empty() && !delay_target.empty())
352 // for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
353 // abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
354
355 for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
356 abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3);
357
358 //for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
359 // abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
360
361 for (size_t pos = abc_script.find("{W}"); pos != std::string::npos; pos = abc_script.find("{W}", pos))
362 abc_script = abc_script.substr(0, pos) + wire_delay + abc_script.substr(pos+3);
363
364 abc_script += stringf("; &write %s/output.aig", tempdir_name.c_str());
365 abc_script = add_echos_to_abc_cmd(abc_script);
366
367 for (size_t i = 0; i+1 < abc_script.size(); i++)
368 if (abc_script[i] == ';' && abc_script[i+1] == ' ')
369 abc_script[i+1] = '\n';
370
371 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
372 fprintf(f, "%s\n", abc_script.c_str());
373 fclose(f);
374
375 if (dff_mode || !clk_str.empty())
376 {
377 if (clk_sig.size() == 0)
378 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching");
379 else {
380 log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
381 if (en_sig.size() != 0)
382 log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig));
383 log("\n");
384 }
385 }
386
387 bool count_output = false;
388 for (auto port_name : module->ports) {
389 RTLIL::Wire *port_wire = module->wire(port_name);
390 log_assert(port_wire);
391 if (port_wire->port_output) {
392 count_output = true;
393 break;
394 }
395 }
396
397 log_push();
398
399 if (count_output)
400 {
401 design->selection_stack.emplace_back(false);
402 RTLIL::Selection& sel = design->selection_stack.back();
403 sel.select(module);
404
405 Pass::call(design, "aigmap");
406
407 handle_loops(design);
408
409 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
410 // count_gates, GetSize(signal_list), count_input, count_output);
411
412 Pass::call(design, stringf("write_xaiger -map %s/input.sym %s/input.xaig", tempdir_name.c_str(), tempdir_name.c_str()));
413
414 std::string buffer;
415 std::ifstream ifs;
416 #if 0
417 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.xaig");
418 ifs.open(buffer);
419 if (ifs.fail())
420 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
421 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
422 log_assert(!design->module("$__abc9__"));
423 {
424 AigerReader reader(design, ifs, "$__abc9__", "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
425 reader.parse_xaiger();
426 }
427 ifs.close();
428 Pass::call(design, stringf("write_verilog -noexpr -norename"));
429 design->remove(design->module("$__abc9__"));
430 #endif
431
432 design->selection_stack.pop_back();
433
434 // Now 'unexpose' those wires by undoing
435 // the expose operation -- remove them from PO/PI
436 // and re-connecting them back together
437 for (auto wire : module->wires()) {
438 auto it = wire->attributes.find("\\abc_scc_break");
439 if (it != wire->attributes.end()) {
440 wire->attributes.erase(it);
441 log_assert(wire->port_output);
442 wire->port_output = false;
443 RTLIL::Wire *i_wire = module->wire(wire->name.str() + ".abci");
444 log_assert(i_wire);
445 log_assert(i_wire->port_input);
446 i_wire->port_input = false;
447 module->connect(i_wire, wire);
448 }
449 }
450 module->fixup_ports();
451
452
453 log_header(design, "Executing ABC9.\n");
454
455 if (!lut_costs.empty()) {
456 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
457 f = fopen(buffer.c_str(), "wt");
458 if (f == NULL)
459 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
460 for (int i = 0; i < GetSize(lut_costs); i++)
461 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
462 fclose(f);
463 }
464
465 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
466 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
467
468 #ifndef YOSYS_LINK_ABC
469 abc_output_filter filt(tempdir_name, show_tempdir);
470 int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1));
471 #else
472 // These needs to be mutable, supposedly due to getopt
473 char *abc_argv[5];
474 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
475 abc_argv[0] = strdup(exe_file.c_str());
476 abc_argv[1] = strdup("-s");
477 abc_argv[2] = strdup("-f");
478 abc_argv[3] = strdup(tmp_script_name.c_str());
479 abc_argv[4] = 0;
480 int ret = Abc_RealMain(4, abc_argv);
481 free(abc_argv[0]);
482 free(abc_argv[1]);
483 free(abc_argv[2]);
484 free(abc_argv[3]);
485 #endif
486 if (ret != 0)
487 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
488
489 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.aig");
490 ifs.open(buffer);
491 if (ifs.fail())
492 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
493
494 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
495 log_assert(!design->module("$__abc9__"));
496 AigerReader reader(design, ifs, "$__abc9__", "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
497 reader.parse_xaiger();
498 ifs.close();
499
500 #if 0
501 Pass::call(design, stringf("write_verilog -noexpr -norename"));
502 #endif
503
504 log_header(design, "Re-integrating ABC9 results.\n");
505 RTLIL::Module *mapped_mod = design->module("$__abc9__");
506 if (mapped_mod == NULL)
507 log_error("ABC output file does not contain a module `$__abc9__'.\n");
508
509 pool<RTLIL::SigBit> output_bits;
510 for (auto &it : mapped_mod->wires_) {
511 RTLIL::Wire *w = it.second;
512 RTLIL::Wire *remap_wire = module->addWire(remap_name(w->name), GetSize(w));
513 if (markgroups) remap_wire->attributes["\\abcgroup"] = map_autoidx;
514 if (w->port_output) {
515 RTLIL::Wire *wire = module->wire(w->name);
516 log_assert(wire);
517 for (int i = 0; i < GetSize(w); i++)
518 output_bits.insert({wire, i});
519 }
520 }
521
522 for (auto &it : module->connections_) {
523 auto &signal = it.first;
524 auto bits = signal.bits();
525 for (auto &b : bits)
526 if (output_bits.count(b))
527 b = module->addWire(NEW_ID);
528 signal = std::move(bits);
529 }
530
531 vector<RTLIL::Cell*> boxes;
532 for (auto it = module->cells_.begin(); it != module->cells_.end(); ) {
533 RTLIL::Cell* cell = it->second;
534 if (cell->type.in("$_AND_", "$_NOT_", "$__ABC_FF_")) {
535 it = module->remove(it);
536 continue;
537 }
538 RTLIL::Module* box_module = design->module(cell->type);
539 if (box_module && box_module->attributes.count("\\abc_box_id"))
540 boxes.emplace_back(it->second);
541 ++it;
542 }
543
544 std::map<std::string, int> cell_stats;
545 for (auto c : mapped_mod->cells())
546 {
547 RTLIL::Cell *cell = nullptr;
548 if (c->type == "$_NOT_") {
549 RTLIL::SigBit a_bit = c->getPort("\\A").as_bit();
550 RTLIL::SigBit y_bit = c->getPort("\\Y").as_bit();
551 if (!a_bit.wire) {
552 c->setPort("\\Y", module->addWire(NEW_ID));
553 RTLIL::Wire *wire = module->wire(remap_name(y_bit.wire->name));
554 log_assert(wire);
555 module->connect(RTLIL::SigBit(wire, y_bit.offset), RTLIL::S1);
556 }
557 else if (!lut_costs.empty() || !lut_file.empty()) {
558 RTLIL::Cell* driving_lut = nullptr;
559 // ABC can return NOT gates that drive POs
560 if (!a_bit.wire->port_input) {
561 // If it's not a NOT gate that that comes from a PI directly,
562 // find the driving LUT and clone that to guarantee that we won't
563 // increase the max logic depth
564 // (TODO: Optimise by not cloning unless will increase depth)
565 RTLIL::IdString driver_name;
566 if (GetSize(a_bit.wire) == 1)
567 driver_name = stringf("%s$lut", a_bit.wire->name.c_str());
568 else
569 driver_name = stringf("%s[%d]$lut", a_bit.wire->name.c_str(), a_bit.offset);
570 driving_lut = mapped_mod->cell(driver_name);
571 }
572
573 if (!driving_lut) {
574 // If a driver couldn't be found (could be from PI,
575 // or from a box) then implement using a LUT
576 cell = module->addLut(remap_name(stringf("%s$lut", c->name.c_str())),
577 RTLIL::SigBit(module->wires_[remap_name(a_bit.wire->name)], a_bit.offset),
578 RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset),
579 1);
580 }
581 else {
582 auto driver_a = driving_lut->getPort("\\A").chunks();
583 for (auto &chunk : driver_a)
584 chunk.wire = module->wires_[remap_name(chunk.wire->name)];
585 RTLIL::Const driver_lut = driving_lut->getParam("\\LUT");
586 for (auto &b : driver_lut.bits) {
587 if (b == RTLIL::State::S0) b = RTLIL::State::S1;
588 else if (b == RTLIL::State::S1) b = RTLIL::State::S0;
589 }
590 cell = module->addLut(remap_name(stringf("%s$lut", c->name.c_str())),
591 driver_a,
592 RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset),
593 driver_lut);
594 }
595 }
596 else {
597 cell = module->addCell(remap_name(c->name), "$_NOT_");
598 cell->setPort("\\A", RTLIL::SigBit(module->wires_[remap_name(a_bit.wire->name)], a_bit.offset));
599 cell->setPort("\\Y", RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset));
600 cell_stats[RTLIL::unescape_id(c->type)]++;
601 }
602 if (cell && markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
603 continue;
604 }
605 cell_stats[RTLIL::unescape_id(c->type)]++;
606
607 RTLIL::Cell *existing_cell = nullptr;
608 if (c->type == "$lut") {
609 if (GetSize(c->getPort("\\A")) == 1 && c->getParam("\\LUT").as_int() == 2) {
610 SigSpec my_a = module->wires_[remap_name(c->getPort("\\A").as_wire()->name)];
611 SigSpec my_y = module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)];
612 module->connect(my_y, my_a);
613 if (markgroups) c->attributes["\\abcgroup"] = map_autoidx;
614 continue;
615 }
616 cell = module->addCell(remap_name(c->name), c->type);
617 }
618 else {
619 existing_cell = module->cell(c->name);
620 cell = module->addCell(remap_name(c->name), c->type);
621 module->swap_names(cell, existing_cell);
622 }
623
624 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
625 if (existing_cell) {
626 cell->parameters = existing_cell->parameters;
627 cell->attributes = existing_cell->attributes;
628 }
629 else {
630 cell->parameters = c->parameters;
631 cell->attributes = c->attributes;
632 }
633 for (auto &conn : c->connections()) {
634 RTLIL::SigSpec newsig;
635 for (auto c : conn.second.chunks()) {
636 if (c.width == 0)
637 continue;
638 //log_assert(c.width == 1);
639 if (c.wire)
640 c.wire = module->wires_[remap_name(c.wire->name)];
641 newsig.append(c);
642 }
643 cell->setPort(conn.first, newsig);
644 }
645 }
646
647 for (auto cell : boxes)
648 module->remove(cell);
649
650 // Copy connections (and rename) from mapped_mod to module
651 for (auto conn : mapped_mod->connections()) {
652 if (!conn.first.is_fully_const()) {
653 auto chunks = conn.first.chunks();
654 for (auto &c : chunks)
655 c.wire = module->wires_[remap_name(c.wire->name)];
656 conn.first = std::move(chunks);
657 }
658 if (!conn.second.is_fully_const()) {
659 auto chunks = conn.second.chunks();
660 for (auto &c : chunks)
661 if (c.wire)
662 c.wire = module->wires_[remap_name(c.wire->name)];
663 conn.second = std::move(chunks);
664 }
665 module->connect(conn);
666 }
667
668 for (auto &it : cell_stats)
669 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
670 int in_wires = 0, out_wires = 0;
671
672 // Stitch in mapped_mod's inputs/outputs into module
673 for (auto &it : mapped_mod->wires_) {
674 RTLIL::Wire *w = it.second;
675 if (!w->port_input && !w->port_output)
676 continue;
677 RTLIL::Wire *wire = module->wire(w->name);
678 log_assert(wire);
679 RTLIL::Wire *remap_wire = module->wire(remap_name(w->name));
680 RTLIL::SigSpec signal = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
681 log_assert(GetSize(signal) >= GetSize(remap_wire));
682
683 log_assert(w->port_input || w->port_output);
684 RTLIL::SigSig conn;
685 if (w->port_input) {
686 conn.first = remap_wire;
687 conn.second = signal;
688 in_wires++;
689 module->connect(conn);
690 }
691 if (w->port_output) {
692 conn.first = signal;
693 conn.second = remap_wire;
694 out_wires++;
695 module->connect(conn);
696 }
697 }
698
699 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
700 log("ABC RESULTS: input signals: %8d\n", in_wires);
701 log("ABC RESULTS: output signals: %8d\n", out_wires);
702
703 design->remove(mapped_mod);
704 }
705 else
706 {
707 log("Don't call ABC as there is nothing to map.\n");
708 }
709
710 if (cleanup)
711 {
712 log("Removing temp directory.\n");
713 remove_directory(tempdir_name);
714 }
715
716 log_pop();
717 }
718
719 struct Abc9Pass : public Pass {
720 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
721 void help() YS_OVERRIDE
722 {
723 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
724 log("\n");
725 log(" abc9 [options] [selection]\n");
726 log("\n");
727 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
728 log("library to a target architecture.\n");
729 log("\n");
730 log(" -exe <command>\n");
731 #ifdef ABCEXTERNAL
732 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
733 #else
734 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
735 #endif
736 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
737 log("\n");
738 log(" -script <file>\n");
739 log(" use the specified ABC script file instead of the default script.\n");
740 log("\n");
741 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
742 log(" string is interpreted as the command string to be passed to ABC. The\n");
743 log(" leading plus sign is removed and all commas (,) in the string are\n");
744 log(" replaced with blanks before the string is passed to ABC.\n");
745 log("\n");
746 log(" if no -script parameter is given, the following scripts are used:\n");
747 log("\n");
748 log(" for -lut/-luts (only one LUT size):\n");
749 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT /*"; lutpack {S}"*/).c_str());
750 log("\n");
751 log(" for -lut/-luts (different LUT sizes):\n");
752 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
753 log("\n");
754 log(" -fast\n");
755 log(" use different default scripts that are slightly faster (at the cost\n");
756 log(" of output quality):\n");
757 log("\n");
758 log(" for -lut/-luts:\n");
759 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
760 log("\n");
761 log(" -D <picoseconds>\n");
762 log(" set delay target. the string {D} in the default scripts above is\n");
763 log(" replaced by this option when used, and an empty string otherwise\n");
764 log(" (indicating best possible delay).\n");
765 // log(" This also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
766 // log(" default scripts above.\n");
767 log("\n");
768 // log(" -S <num>\n");
769 // log(" maximum number of LUT inputs shared.\n");
770 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
771 // log("\n");
772 log(" -lut <width>\n");
773 log(" generate netlist using luts of (max) the specified width.\n");
774 log("\n");
775 log(" -lut <w1>:<w2>\n");
776 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
777 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
778 log(" the area cost doubles with each additional input bit. the delay cost\n");
779 log(" is still constant for all lut widths.\n");
780 log("\n");
781 log(" -lut <file>\n");
782 log(" pass this file with lut library to ABC.\n");
783 log("\n");
784 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
785 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
786 log(" 2, 3, .. inputs.\n");
787 log("\n");
788 // log(" -dff\n");
789 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
790 // log(" clock domains are automatically partitioned in clock domains and each\n");
791 // log(" domain is passed through ABC independently.\n");
792 // log("\n");
793 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
794 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
795 // log(" cells that belong to the specified clock domain are used.\n");
796 // log("\n");
797 // log(" -keepff\n");
798 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
799 // log(" them, for example for equivalence checking.)\n");
800 // log("\n");
801 log(" -nocleanup\n");
802 log(" when this option is used, the temporary files created by this pass\n");
803 log(" are not removed. this is useful for debugging.\n");
804 log("\n");
805 log(" -showtmp\n");
806 log(" print the temp dir name in log. usually this is suppressed so that the\n");
807 log(" command output is identical across runs.\n");
808 log("\n");
809 log(" -markgroups\n");
810 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
811 log(" this attribute is a unique integer for each ABC process started. This\n");
812 log(" is useful for debugging the partitioning of clock domains.\n");
813 log("\n");
814 log(" -box <file>\n");
815 log(" pass this file with box library to ABC. Use with -lut.\n");
816 log("\n");
817 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
818 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
819 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
820 log("output when passing an ABC script that writes a file. Instead write your full\n");
821 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
822 log("you want to use ABC to convert your design into another format.\n");
823 log("\n");
824 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
825 log("\n");
826 }
827 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
828 {
829 log_header(design, "Executing ABC9 pass (technology mapping using ABC9).\n");
830 log_push();
831
832 assign_map.clear();
833
834 #ifdef ABCEXTERNAL
835 std::string exe_file = ABCEXTERNAL;
836 #else
837 std::string exe_file = proc_self_dirname() + "yosys-abc";
838 #endif
839 std::string script_file, clk_str, box_file, lut_file;
840 std::string delay_target, lutin_shared = "-S 1", wire_delay;
841 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
842 bool show_tempdir = false;
843 vector<int> lut_costs;
844 markgroups = false;
845
846 #if 0
847 cleanup = false;
848 show_tempdir = true;
849 #endif
850
851 #ifdef _WIN32
852 #ifndef ABCEXTERNAL
853 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
854 exe_file = proc_self_dirname() + "..\\yosys-abc";
855 #endif
856 #endif
857
858 size_t argidx;
859 char pwd [PATH_MAX];
860 if (!getcwd(pwd, sizeof(pwd))) {
861 log_cmd_error("getcwd failed: %s\n", strerror(errno));
862 log_abort();
863 }
864 for (argidx = 1; argidx < args.size(); argidx++) {
865 std::string arg = args[argidx];
866 if (arg == "-exe" && argidx+1 < args.size()) {
867 exe_file = args[++argidx];
868 continue;
869 }
870 if (arg == "-script" && argidx+1 < args.size()) {
871 script_file = args[++argidx];
872 rewrite_filename(script_file);
873 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
874 script_file = std::string(pwd) + "/" + script_file;
875 continue;
876 }
877 if (arg == "-D" && argidx+1 < args.size()) {
878 delay_target = "-D " + args[++argidx];
879 continue;
880 }
881 //if (arg == "-S" && argidx+1 < args.size()) {
882 // lutin_shared = "-S " + args[++argidx];
883 // continue;
884 //}
885 if (arg == "-lut" && argidx+1 < args.size()) {
886 string arg = args[++argidx];
887 size_t pos = arg.find_first_of(':');
888 int lut_mode = 0, lut_mode2 = 0;
889 if (pos != string::npos) {
890 lut_mode = atoi(arg.substr(0, pos).c_str());
891 lut_mode2 = atoi(arg.substr(pos+1).c_str());
892 } else {
893 pos = arg.find_first_of('.');
894 if (pos != string::npos) {
895 lut_file = arg;
896 rewrite_filename(lut_file);
897 if (!lut_file.empty() && !is_absolute_path(lut_file))
898 lut_file = std::string(pwd) + "/" + lut_file;
899 }
900 else {
901 lut_mode = atoi(arg.c_str());
902 lut_mode2 = lut_mode;
903 }
904 }
905 lut_costs.clear();
906 for (int i = 0; i < lut_mode; i++)
907 lut_costs.push_back(1);
908 for (int i = lut_mode; i < lut_mode2; i++)
909 lut_costs.push_back(2 << (i - lut_mode));
910 continue;
911 }
912 if (arg == "-luts" && argidx+1 < args.size()) {
913 lut_costs.clear();
914 for (auto &tok : split_tokens(args[++argidx], ",")) {
915 auto parts = split_tokens(tok, ":");
916 if (GetSize(parts) == 0 && !lut_costs.empty())
917 lut_costs.push_back(lut_costs.back());
918 else if (GetSize(parts) == 1)
919 lut_costs.push_back(atoi(parts.at(0).c_str()));
920 else if (GetSize(parts) == 2)
921 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
922 lut_costs.push_back(atoi(parts.at(1).c_str()));
923 else
924 log_cmd_error("Invalid -luts syntax.\n");
925 }
926 continue;
927 }
928 if (arg == "-fast") {
929 fast_mode = true;
930 continue;
931 }
932 //if (arg == "-dff") {
933 // dff_mode = true;
934 // continue;
935 //}
936 //if (arg == "-clk" && argidx+1 < args.size()) {
937 // clk_str = args[++argidx];
938 // dff_mode = true;
939 // continue;
940 //}
941 //if (arg == "-keepff") {
942 // keepff = true;
943 // continue;
944 //}
945 if (arg == "-nocleanup") {
946 cleanup = false;
947 continue;
948 }
949 if (arg == "-showtmp") {
950 show_tempdir = true;
951 continue;
952 }
953 if (arg == "-markgroups") {
954 markgroups = true;
955 continue;
956 }
957 if (arg == "-box" && argidx+1 < args.size()) {
958 box_file = args[++argidx];
959 rewrite_filename(box_file);
960 if (!box_file.empty() && !is_absolute_path(box_file))
961 box_file = std::string(pwd) + "/" + box_file;
962 continue;
963 }
964 if (arg == "-W" && argidx+1 < args.size()) {
965 wire_delay = "-W " + args[++argidx];
966 continue;
967 }
968 break;
969 }
970 extra_args(args, argidx, design);
971
972 for (auto mod : design->selected_modules())
973 {
974 if (mod->attributes.count("\\abc_box_id"))
975 continue;
976
977 if (mod->processes.size() > 0) {
978 log("Skipping module %s as it contains processes.\n", log_id(mod));
979 continue;
980 }
981
982 assign_map.set(mod);
983
984 if (!dff_mode || !clk_str.empty()) {
985 abc9_module(design, mod, script_file, exe_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
986 delay_target, lutin_shared, fast_mode, show_tempdir,
987 box_file, lut_file, wire_delay);
988 continue;
989 }
990
991 CellTypes ct(design);
992
993 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
994 std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
995
996 std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
997 std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
998 std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
999
1000 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
1001 std::map<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
1002 std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
1003
1004 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
1005 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
1006
1007 for (auto cell : all_cells)
1008 {
1009 clkdomain_t key;
1010
1011 for (auto &conn : cell->connections())
1012 for (auto bit : conn.second) {
1013 bit = assign_map(bit);
1014 if (bit.wire != nullptr) {
1015 cell_to_bit[cell].insert(bit);
1016 bit_to_cell[bit].insert(cell);
1017 if (ct.cell_input(cell->type, conn.first)) {
1018 cell_to_bit_up[cell].insert(bit);
1019 bit_to_cell_down[bit].insert(cell);
1020 }
1021 if (ct.cell_output(cell->type, conn.first)) {
1022 cell_to_bit_down[cell].insert(bit);
1023 bit_to_cell_up[bit].insert(cell);
1024 }
1025 }
1026 }
1027
1028 if (cell->type == "$_DFF_N_" || cell->type == "$_DFF_P_")
1029 {
1030 key = clkdomain_t(cell->type == "$_DFF_P_", assign_map(cell->getPort("\\C")), true, RTLIL::SigSpec());
1031 }
1032 else
1033 if (cell->type == "$_DFFE_NN_" || cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_")
1034 {
1035 bool this_clk_pol = cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_";
1036 bool this_en_pol = cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PP_";
1037 key = clkdomain_t(this_clk_pol, assign_map(cell->getPort("\\C")), this_en_pol, assign_map(cell->getPort("\\E")));
1038 }
1039 else
1040 continue;
1041
1042 unassigned_cells.erase(cell);
1043 expand_queue.insert(cell);
1044 expand_queue_up.insert(cell);
1045 expand_queue_down.insert(cell);
1046
1047 assigned_cells[key].push_back(cell);
1048 assigned_cells_reverse[cell] = key;
1049 }
1050
1051 while (!expand_queue_up.empty() || !expand_queue_down.empty())
1052 {
1053 if (!expand_queue_up.empty())
1054 {
1055 RTLIL::Cell *cell = *expand_queue_up.begin();
1056 clkdomain_t key = assigned_cells_reverse.at(cell);
1057 expand_queue_up.erase(cell);
1058
1059 for (auto bit : cell_to_bit_up[cell])
1060 for (auto c : bit_to_cell_up[bit])
1061 if (unassigned_cells.count(c)) {
1062 unassigned_cells.erase(c);
1063 next_expand_queue_up.insert(c);
1064 assigned_cells[key].push_back(c);
1065 assigned_cells_reverse[c] = key;
1066 expand_queue.insert(c);
1067 }
1068 }
1069
1070 if (!expand_queue_down.empty())
1071 {
1072 RTLIL::Cell *cell = *expand_queue_down.begin();
1073 clkdomain_t key = assigned_cells_reverse.at(cell);
1074 expand_queue_down.erase(cell);
1075
1076 for (auto bit : cell_to_bit_down[cell])
1077 for (auto c : bit_to_cell_down[bit])
1078 if (unassigned_cells.count(c)) {
1079 unassigned_cells.erase(c);
1080 next_expand_queue_up.insert(c);
1081 assigned_cells[key].push_back(c);
1082 assigned_cells_reverse[c] = key;
1083 expand_queue.insert(c);
1084 }
1085 }
1086
1087 if (expand_queue_up.empty() && expand_queue_down.empty()) {
1088 expand_queue_up.swap(next_expand_queue_up);
1089 expand_queue_down.swap(next_expand_queue_down);
1090 }
1091 }
1092
1093 while (!expand_queue.empty())
1094 {
1095 RTLIL::Cell *cell = *expand_queue.begin();
1096 clkdomain_t key = assigned_cells_reverse.at(cell);
1097 expand_queue.erase(cell);
1098
1099 for (auto bit : cell_to_bit.at(cell)) {
1100 for (auto c : bit_to_cell[bit])
1101 if (unassigned_cells.count(c)) {
1102 unassigned_cells.erase(c);
1103 next_expand_queue.insert(c);
1104 assigned_cells[key].push_back(c);
1105 assigned_cells_reverse[c] = key;
1106 }
1107 bit_to_cell[bit].clear();
1108 }
1109
1110 if (expand_queue.empty())
1111 expand_queue.swap(next_expand_queue);
1112 }
1113
1114 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1115 for (auto cell : unassigned_cells) {
1116 assigned_cells[key].push_back(cell);
1117 assigned_cells_reverse[cell] = key;
1118 }
1119
1120 log_header(design, "Summary of detected clock domains:\n");
1121 for (auto &it : assigned_cells)
1122 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
1123 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
1124 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
1125
1126 for (auto &it : assigned_cells) {
1127 clk_polarity = std::get<0>(it.first);
1128 clk_sig = assign_map(std::get<1>(it.first));
1129 en_polarity = std::get<2>(it.first);
1130 en_sig = assign_map(std::get<3>(it.first));
1131 abc9_module(design, mod, script_file, exe_file, cleanup, lut_costs, !clk_sig.empty(), "$",
1132 keepff, delay_target, lutin_shared, fast_mode, show_tempdir,
1133 box_file, lut_file, wire_delay);
1134 assign_map.set(mod);
1135 }
1136 }
1137
1138 Pass::call(design, "clean");
1139
1140 assign_map.clear();
1141
1142 log_pop();
1143 }
1144 } Abc9Pass;
1145
1146 PRIVATE_NAMESPACE_END