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