Merge remote-tracking branch 'origin/master' into xc7mux
[yosys.git] / passes / techmap / abc9.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * Copyright (C) 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 #define ABC_COMMAND_LIB "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put"
26 #define ABC_COMMAND_CTR "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put; buffer; upsize {D}; dnsize {D}; stime -p"
27 //#define ABC_COMMAND_LUT "strash; ifraig; scorr; dc2; dretime; strash; dch -f; if; mfs2"
28 #define ABC_COMMAND_LUT "&st; &sweep; &scorr; "/*"&dc2; */"&retime; &dch -f; &ps -l; &if -W 160 -v; &ps -l"
29 #define ABC_COMMAND_SOP "strash; ifraig; scorr; dc2; dretime; strash; dch -f; cover {I} {P}"
30 #define ABC_COMMAND_DFL "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put"
31
32 #define ABC_FAST_COMMAND_LIB "strash; dretime; map {D}"
33 #define ABC_FAST_COMMAND_CTR "strash; dretime; map {D}; buffer; upsize {D}; dnsize {D}; stime -p"
34 #define ABC_FAST_COMMAND_LUT "&st; &retime; &if"
35 #define ABC_FAST_COMMAND_SOP "strash; dretime; cover -I {I} -P {P}"
36 #define ABC_FAST_COMMAND_DFL "strash; dretime; map"
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 map_mux4;
65 bool map_mux8;
66 bool map_mux16;
67
68 bool markgroups;
69 int map_autoidx;
70 SigMap assign_map;
71 RTLIL::Module *module;
72 std::map<RTLIL::SigBit, int> signal_map;
73 std::map<RTLIL::SigBit, RTLIL::State> signal_init;
74 pool<std::string> enabled_gates;
75 bool recover_init;
76
77 bool clk_polarity, en_polarity;
78 RTLIL::SigSpec clk_sig, en_sig;
79 dict<int, std::string> pi_map, po_map;
80
81 std::string remap_name(RTLIL::IdString abc_name)
82 {
83 std::stringstream sstr;
84 sstr << "$abc$" << map_autoidx << "$" << abc_name.substr(1);
85 return sstr.str();
86 }
87
88 void handle_loops(RTLIL::Design *design)
89 {
90 Pass::call(design, "scc -set_attr abc_scc_id {}");
91
92 design->selection_stack.emplace_back(false);
93 RTLIL::Selection& sel = design->selection_stack.back();
94
95 // For every unique SCC found, (arbitrarily) find the first
96 // cell in the component, and select (and mark) all its output
97 // wires
98 pool<RTLIL::Const> ids_seen;
99 for (auto cell : module->cells()) {
100 auto it = cell->attributes.find("\\abc_scc_id");
101 if (it != cell->attributes.end()) {
102 auto r = ids_seen.insert(it->second);
103 if (r.second) {
104 for (const auto &c : cell->connections()) {
105 if (c.second.is_fully_const()) continue;
106 if (cell->output(c.first)) {
107 SigBit b = c.second.as_bit();
108 Wire *w = b.wire;
109 w->set_bool_attribute("\\abc_scc_break");
110 sel.select(module, w);
111 }
112 }
113 }
114 cell->attributes.erase(it);
115 }
116 }
117
118 // Then cut those selected wires to expose them as new PO/PI
119 Pass::call(design, "expose -cut -sep .abc");
120
121 design->selection_stack.pop_back();
122 }
123
124 std::string add_echos_to_abc_cmd(std::string str)
125 {
126 std::string new_str, token;
127 for (size_t i = 0; i < str.size(); i++) {
128 token += str[i];
129 if (str[i] == ';') {
130 while (i+1 < str.size() && str[i+1] == ' ')
131 i++;
132 new_str += "echo + " + token + " " + token + " ";
133 token.clear();
134 }
135 }
136
137 if (!token.empty()) {
138 if (!new_str.empty())
139 new_str += "echo + " + token + "; ";
140 new_str += token;
141 }
142
143 return new_str;
144 }
145
146 std::string fold_abc_cmd(std::string str)
147 {
148 std::string token, new_str = " ";
149 int char_counter = 10;
150
151 for (size_t i = 0; i <= str.size(); i++) {
152 if (i < str.size())
153 token += str[i];
154 if (i == str.size() || str[i] == ';') {
155 if (char_counter + token.size() > 75)
156 new_str += "\n ", char_counter = 14;
157 new_str += token, char_counter += token.size();
158 token.clear();
159 }
160 }
161
162 return new_str;
163 }
164
165 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
166 {
167 if (show_tempdir)
168 return text;
169
170 while (1) {
171 size_t pos = text.find(tempdir_name);
172 if (pos == std::string::npos)
173 break;
174 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
175 }
176
177 std::string selfdir_name = proc_self_dirname();
178 if (selfdir_name != "/") {
179 while (1) {
180 size_t pos = text.find(selfdir_name);
181 if (pos == std::string::npos)
182 break;
183 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
184 }
185 }
186
187 return text;
188 }
189
190 struct abc_output_filter
191 {
192 bool got_cr;
193 int escape_seq_state;
194 std::string linebuf;
195 std::string tempdir_name;
196 bool show_tempdir;
197
198 abc_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
199 {
200 got_cr = false;
201 escape_seq_state = 0;
202 }
203
204 void next_char(char ch)
205 {
206 if (escape_seq_state == 0 && ch == '\033') {
207 escape_seq_state = 1;
208 return;
209 }
210 if (escape_seq_state == 1) {
211 escape_seq_state = ch == '[' ? 2 : 0;
212 return;
213 }
214 if (escape_seq_state == 2) {
215 if ((ch < '0' || '9' < ch) && ch != ';')
216 escape_seq_state = 0;
217 return;
218 }
219 escape_seq_state = 0;
220 if (ch == '\r') {
221 got_cr = true;
222 return;
223 }
224 if (ch == '\n') {
225 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
226 got_cr = false, linebuf.clear();
227 return;
228 }
229 if (got_cr)
230 got_cr = false, linebuf.clear();
231 linebuf += ch;
232 }
233
234 void next_line(const std::string &line)
235 {
236 int pi, po;
237 if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
238 log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
239 pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
240 po, po_map.count(po) ? po_map.at(po).c_str() : "???");
241 return;
242 }
243
244 for (char ch : line)
245 next_char(ch);
246 }
247 };
248
249 static std::pair<RTLIL::IdString, int> wideports_split(std::string name)
250 {
251 int pos = -1;
252
253 if (name.empty() || name.back() != ']')
254 goto failed;
255
256 for (int i = 0; i+1 < GetSize(name); i++) {
257 if (name[i] == '[')
258 pos = i;
259 else if (name[i] < '0' || name[i] > '9')
260 pos = -1;
261 else if (i == pos+1 && name[i] == '0' && name[i+1] != ']')
262 pos = -1;
263 }
264
265 if (pos >= 0)
266 return std::pair<RTLIL::IdString, int>(RTLIL::escape_id(name.substr(0, pos)), atoi(name.c_str() + pos+1));
267
268 failed:
269 return std::pair<RTLIL::IdString, int>(name, 0);
270 }
271
272 void abc9_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file,
273 std::string liberty_file, std::string constr_file, bool cleanup, vector<int> lut_costs, bool dff_mode, std::string clk_str,
274 bool keepff, std::string delay_target, std::string sop_inputs, std::string sop_products, std::string lutin_shared, bool fast_mode,
275 const std::vector<RTLIL::Cell*> &cells, bool show_tempdir, bool sop_mode, std::string box_file, std::string lut_file)
276 {
277 module = current_module;
278 map_autoidx = autoidx++;
279
280 signal_map.clear();
281 pi_map.clear();
282 po_map.clear();
283 recover_init = false;
284
285 if (clk_str != "$")
286 {
287 clk_polarity = true;
288 clk_sig = RTLIL::SigSpec();
289
290 en_polarity = true;
291 en_sig = RTLIL::SigSpec();
292 }
293
294 if (!clk_str.empty() && clk_str != "$")
295 {
296 if (clk_str.find(',') != std::string::npos) {
297 int pos = clk_str.find(',');
298 std::string en_str = clk_str.substr(pos+1);
299 clk_str = clk_str.substr(0, pos);
300 if (en_str[0] == '!') {
301 en_polarity = false;
302 en_str = en_str.substr(1);
303 }
304 if (module->wires_.count(RTLIL::escape_id(en_str)) != 0)
305 en_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(en_str)), 0));
306 }
307 if (clk_str[0] == '!') {
308 clk_polarity = false;
309 clk_str = clk_str.substr(1);
310 }
311 if (module->wires_.count(RTLIL::escape_id(clk_str)) != 0)
312 clk_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(clk_str)), 0));
313 }
314
315 if (dff_mode && clk_sig.empty())
316 log_cmd_error("Clock domain %s not found.\n", clk_str.c_str());
317
318 std::string tempdir_name = "/tmp/yosys-abc-XXXXXX";
319 if (!cleanup)
320 tempdir_name[0] = tempdir_name[4] = '_';
321 tempdir_name = make_temp_dir(tempdir_name);
322 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
323 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
324
325 std::string abc_script;
326
327 if (!liberty_file.empty()) {
328 abc_script += stringf("read_lib -w %s; ", liberty_file.c_str());
329 if (!constr_file.empty())
330 abc_script += stringf("read_constr -v %s; ", constr_file.c_str());
331 } else
332 if (!lut_costs.empty()) {
333 abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
334 if (!box_file.empty())
335 abc_script += stringf("read_box -v %s; ", box_file.c_str());
336 }
337 else
338 if (!lut_file.empty()) {
339 abc_script += stringf("read_lut %s; ", lut_file.c_str());
340 if (!box_file.empty())
341 abc_script += stringf("read_box -v %s; ", box_file.c_str());
342 }
343 else
344 abc_script += stringf("read_library %s/stdcells.genlib; ", tempdir_name.c_str());
345
346 abc_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
347
348 if (!script_file.empty()) {
349 if (script_file[0] == '+') {
350 for (size_t i = 1; i < script_file.size(); i++)
351 if (script_file[i] == '\'')
352 abc_script += "'\\''";
353 else if (script_file[i] == ',')
354 abc_script += " ";
355 else
356 abc_script += script_file[i];
357 } else
358 abc_script += stringf("source %s", script_file.c_str());
359 } else if (!lut_costs.empty() || !lut_file.empty()) {
360 //bool all_luts_cost_same = true;
361 //for (int this_cost : lut_costs)
362 // if (this_cost != lut_costs.front())
363 // all_luts_cost_same = false;
364 abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
365 //if (all_luts_cost_same && !fast_mode)
366 // abc_script += "; lutpack {S}";
367 } else if (!liberty_file.empty())
368 abc_script += constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR);
369 else if (sop_mode)
370 abc_script += fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP;
371 else
372 abc_script += fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL;
373
374 if (script_file.empty() && !delay_target.empty())
375 for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
376 abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
377
378 for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
379 abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3);
380
381 for (size_t pos = abc_script.find("{I}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
382 abc_script = abc_script.substr(0, pos) + sop_inputs + abc_script.substr(pos+3);
383
384 for (size_t pos = abc_script.find("{P}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
385 abc_script = abc_script.substr(0, pos) + sop_products + abc_script.substr(pos+3);
386
387 for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
388 abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
389
390 abc_script += stringf("; &write %s/output.aig", tempdir_name.c_str());
391 abc_script = add_echos_to_abc_cmd(abc_script);
392
393 for (size_t i = 0; i+1 < abc_script.size(); i++)
394 if (abc_script[i] == ';' && abc_script[i+1] == ' ')
395 abc_script[i+1] = '\n';
396
397 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
398 fprintf(f, "%s\n", abc_script.c_str());
399 fclose(f);
400
401 if (dff_mode || !clk_str.empty())
402 {
403 if (clk_sig.size() == 0)
404 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching");
405 else {
406 log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
407 if (en_sig.size() != 0)
408 log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig));
409 log("\n");
410 }
411 }
412
413 design->selection_stack.emplace_back(false);
414 RTLIL::Selection& sel = design->selection_stack.back();
415 sel.select(module);
416
417 // Behave as for "abc" where BLIF writer implicitly outputs all undef as zero
418 Pass::call(design, "setundef -zero");
419
420 Pass::call(design, "aigmap");
421
422 handle_loops(design);
423
424 Pass::call(design, stringf("write_xaiger -O -map %s/input.sym %s/input.xaig; ", tempdir_name.c_str(), tempdir_name.c_str()));
425
426 #if 0
427 std::string buffer = stringf("%s/%s", tempdir_name.c_str(), "input.xaig");
428 std::ifstream ifs;
429 ifs.open(buffer);
430 if (ifs.fail())
431 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
432 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
433 log_assert(!design->module("$__abc9__"));
434 AigerReader reader(design, ifs, "$__abc9__", "" /* clk_name */, buffer.c_str() /* map_filename */, false /* wideports */);
435 reader.parse_xaiger();
436 ifs.close();
437 Pass::call(design, stringf("write_verilog -noexpr -norename %s/%s", tempdir_name.c_str(), "input.v"));
438 design->remove(design->module("$__abc9__"));
439 #endif
440
441 design->selection_stack.pop_back();
442
443 // Now 'unexpose' those wires by undoing
444 // the expose operation -- remove them from PO/PI
445 // and re-connecting them back together
446 for (auto wire : module->wires()) {
447 auto it = wire->attributes.find("\\abc_scc_break");
448 if (it != wire->attributes.end()) {
449 wire->attributes.erase(it);
450 log_assert(wire->port_output);
451 wire->port_output = false;
452 RTLIL::Wire *i_wire = module->wire(wire->name.str() + ".abci");
453 log_assert(i_wire);
454 log_assert(i_wire->port_input);
455 i_wire->port_input = false;
456 module->connect(i_wire, wire);
457 }
458 }
459 module->fixup_ports();
460
461 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
462 // count_gates, GetSize(signal_list), count_input, count_output);
463
464 log_push();
465
466 //if (count_output > 0)
467 {
468 log_header(design, "Executing ABC9.\n");
469
470 std::string buffer;
471 if (!lut_costs.empty()) {
472 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
473 f = fopen(buffer.c_str(), "wt");
474 if (f == NULL)
475 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
476 for (int i = 0; i < GetSize(lut_costs); i++)
477 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
478 fclose(f);
479 }
480
481 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
482 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
483
484 #ifndef YOSYS_LINK_ABC
485 abc_output_filter filt(tempdir_name, show_tempdir);
486 int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1));
487 #else
488 // These needs to be mutable, supposedly due to getopt
489 char *abc_argv[5];
490 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
491 abc_argv[0] = strdup(exe_file.c_str());
492 abc_argv[1] = strdup("-s");
493 abc_argv[2] = strdup("-f");
494 abc_argv[3] = strdup(tmp_script_name.c_str());
495 abc_argv[4] = 0;
496 int ret = Abc_RealMain(4, abc_argv);
497 free(abc_argv[0]);
498 free(abc_argv[1]);
499 free(abc_argv[2]);
500 free(abc_argv[3]);
501 #endif
502 if (ret != 0)
503 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
504
505 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.aig");
506 std::ifstream ifs;
507 ifs.open(buffer);
508 if (ifs.fail())
509 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
510
511 bool builtin_lib = liberty_file.empty();
512 //parse_blif(mapped_design, ifs, builtin_lib ? "\\DFF" : "\\_dff_", false, sop_mode);
513 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
514 log_assert(!design->module("$__abc9__"));
515 AigerReader reader(design, ifs, "$__abc9__", "" /* clk_name */, buffer.c_str() /* map_filename */, false /* wideports */);
516 reader.parse_xaiger();
517 ifs.close();
518
519 #if 0
520 Pass::call(design, stringf("write_verilog -noexpr -norename %s/%s", tempdir_name.c_str(), "output.v"));
521 #endif
522
523 log_header(design, "Re-integrating ABC9 results.\n");
524 RTLIL::Module *mapped_mod = design->module("$__abc9__");
525 if (mapped_mod == NULL)
526 log_error("ABC output file does not contain a module `$__abc9__'.\n");
527
528 pool<RTLIL::SigBit> output_bits;
529 for (auto &it : mapped_mod->wires_) {
530 RTLIL::Wire *w = it.second;
531 RTLIL::Wire *remap_wire = module->addWire(remap_name(w->name), GetSize(w));
532 if (markgroups) remap_wire->attributes["\\abcgroup"] = map_autoidx;
533 if (w->port_output) {
534 RTLIL::Wire *wire = module->wire(w->name);
535 if (wire) {
536 for (int i = 0; i < GetSize(wire); i++)
537 output_bits.insert({wire, i});
538 }
539 else {
540 // Attempt another wideports_split here because there
541 // exists the possibility that different bits of a port
542 // could be an input and output, therefore parse_xaiger()
543 // could not combine it into a wideport
544 auto r = wideports_split(w->name.str());
545 wire = module->wire(r.first);
546 log_assert(wire);
547 int i = r.second;
548 output_bits.insert({wire, i});
549 }
550 }
551 }
552
553 // Remove all AND, NOT, and ABC box instances
554 // in preparation for stitching mapped_mod in
555 dict<IdString, decltype(RTLIL::Cell::parameters)> erased_boxes;
556 for (auto it = module->cells_.begin(); it != module->cells_.end(); ) {
557 RTLIL::Cell* cell = it->second;
558 if (cell->type.in("$_AND_", "$_NOT_")) {
559 it = module->cells_.erase(it);
560 continue;
561 }
562 RTLIL::Module* box_module = design->module(cell->type);
563 if (box_module && box_module->attributes.count("\\abc_box_id")) {
564 erased_boxes.insert(std::make_pair(it->first, std::move(cell->parameters)));
565 it = module->cells_.erase(it);
566 continue;
567 }
568 ++it;
569 }
570 // Do the same for module connections
571 for (auto &it : module->connections_) {
572 auto &signal = it.first;
573 auto bits = signal.bits();
574 for (auto &b : bits)
575 if (output_bits.count(b))
576 b = module->addWire(NEW_ID);
577 signal = std::move(bits);
578 }
579
580 std::map<std::string, int> cell_stats;
581 for (auto c : mapped_mod->cells())
582 {
583 if (builtin_lib)
584 {
585 if (c->type == "$_NOT_") {
586 RTLIL::Cell *cell;
587 RTLIL::SigBit a_bit = c->getPort("\\A").as_bit();
588 RTLIL::SigBit y_bit = c->getPort("\\Y").as_bit();
589 if (!lut_costs.empty() || !lut_file.empty()) {
590 RTLIL::Cell* driving_lut = nullptr;
591 // ABC can return NOT gates that drive POs
592 if (!a_bit.wire->port_input) {
593 // If it's not a NOT gate that that comes from a PI directly,
594 // find the driving LUT and clone that to guarantee that we won't
595 // increase the max logic depth
596 // (TODO: Optimise by not cloning unless will increase depth)
597 RTLIL::IdString driver_name;
598 if (GetSize(a_bit.wire) == 1)
599 driver_name = stringf("%s$lut", a_bit.wire->name.c_str());
600 else
601 driver_name = stringf("%s[%d]$lut", a_bit.wire->name.c_str(), a_bit.offset);
602 driving_lut = mapped_mod->cell(driver_name);
603 }
604
605 if (!driving_lut) {
606 // If a driver couldn't be found (could be from PI,
607 // or from a box) then implement using a LUT
608 cell = module->addLut(remap_name(stringf("%s$lut", c->name.c_str())),
609 RTLIL::SigBit(module->wires_[remap_name(a_bit.wire->name)], a_bit.offset),
610 RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset),
611 1);
612 }
613 else {
614 auto driver_a = driving_lut->getPort("\\A").chunks();
615 for (auto &chunk : driver_a)
616 chunk.wire = module->wires_[remap_name(chunk.wire->name)];
617 RTLIL::Const driver_lut = driving_lut->getParam("\\LUT");
618 for (auto &b : driver_lut.bits) {
619 if (b == RTLIL::State::S0) b = RTLIL::State::S1;
620 else if (b == RTLIL::State::S1) b = RTLIL::State::S0;
621 }
622 cell = module->addLut(remap_name(stringf("%s$lut", c->name.c_str())),
623 driver_a,
624 RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset),
625 driver_lut);
626 }
627 }
628 else {
629 cell = module->addCell(remap_name(c->name), "$_NOT_");
630 cell->setPort("\\A", RTLIL::SigBit(module->wires_[remap_name(a_bit.wire->name)], a_bit.offset));
631 cell->setPort("\\Y", RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset));
632 cell_stats[RTLIL::unescape_id(c->type)]++;
633 }
634 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
635 continue;
636 }
637 }
638 cell_stats[RTLIL::unescape_id(c->type)]++;
639
640 if (c->type == "$lut") {
641 if (GetSize(c->getPort("\\A")) == 1 && c->getParam("\\LUT").as_int() == 2) {
642 SigSpec my_a = module->wires_[remap_name(c->getPort("\\A").as_wire()->name)];
643 SigSpec my_y = module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)];
644 module->connect(my_y, my_a);
645 continue;
646 }
647 }
648 else {
649 auto it = erased_boxes.find(c->name);
650 log_assert(it != erased_boxes.end());
651 c->parameters = std::move(it->second);
652 }
653
654 RTLIL::Cell* cell = module->addCell(remap_name(c->name), c->type);
655 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
656 cell->parameters = c->parameters;
657 for (auto &conn : c->connections()) {
658 RTLIL::SigSpec newsig;
659 for (auto c : conn.second.chunks()) {
660 if (c.width == 0)
661 continue;
662 //log_assert(c.width == 1);
663 if (c.wire)
664 c.wire = module->wires_[remap_name(c.wire->name)];
665 newsig.append(c);
666 }
667 cell->setPort(conn.first, newsig);
668 }
669 }
670
671 // Copy connections (and rename) from mapped_mod to module
672 for (auto conn : mapped_mod->connections()) {
673 if (!conn.first.is_fully_const()) {
674 auto chunks = conn.first.chunks();
675 for (auto &c : chunks)
676 c.wire = module->wires_[remap_name(c.wire->name)];
677 conn.first = std::move(chunks);
678 }
679 if (!conn.second.is_fully_const()) {
680 auto chunks = conn.second.chunks();
681 for (auto &c : chunks)
682 if (c.wire)
683 c.wire = module->wires_[remap_name(c.wire->name)];
684 conn.second = std::move(chunks);
685 }
686 module->connect(conn);
687 }
688
689 if (recover_init)
690 for (auto wire : mapped_mod->wires()) {
691 if (wire->attributes.count("\\init")) {
692 Wire *w = module->wires_[remap_name(wire->name)];
693 log_assert(w->attributes.count("\\init") == 0);
694 w->attributes["\\init"] = wire->attributes.at("\\init");
695 }
696 }
697
698 for (auto &it : cell_stats)
699 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
700 int in_wires = 0, out_wires = 0;
701
702 // Stitch in mapped_mod's inputs/outputs into module
703 for (auto &it : mapped_mod->wires_) {
704 RTLIL::Wire *w = it.second;
705 if (!w->port_input && !w->port_output)
706 continue;
707 RTLIL::Wire *wire = module->wire(w->name);
708 RTLIL::Wire *remap_wire = module->wire(remap_name(w->name));
709 RTLIL::SigSpec signal;
710 if (wire) {
711 signal = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
712 }
713 else {
714 // Attempt another wideports_split here because there
715 // exists the possibility that different bits of a port
716 // could be an input and output, therefore parse_xaiger()
717 // could not combine it into a wideport
718 auto r = wideports_split(w->name.str());
719 wire = module->wire(r.first);
720 log_assert(wire);
721 int i = r.second;
722 signal = RTLIL::SigSpec(wire, i);
723 }
724 log_assert(GetSize(signal) >= GetSize(remap_wire));
725
726 log_assert(w->port_input || w->port_output);
727 RTLIL::SigSig conn;
728 if (w->port_input) {
729 conn.first = remap_wire;
730 conn.second = signal;
731 in_wires++;
732 module->connect(conn);
733 }
734 if (w->port_output) {
735 conn.first = signal;
736 conn.second = remap_wire;
737 out_wires++;
738 module->connect(conn);
739 }
740 }
741
742 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
743 log("ABC RESULTS: input signals: %8d\n", in_wires);
744 log("ABC RESULTS: output signals: %8d\n", out_wires);
745
746 design->remove(mapped_mod);
747 }
748 //else
749 //{
750 // log("Don't call ABC as there is nothing to map.\n");
751 //}
752
753 if (cleanup)
754 {
755 log("Removing temp directory.\n");
756 remove_directory(tempdir_name);
757 }
758
759 log_pop();
760 }
761
762 struct Abc9Pass : public Pass {
763 Abc9Pass() : Pass("abc9", "use ABC for technology mapping") { }
764 void help() YS_OVERRIDE
765 {
766 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
767 log("\n");
768 log(" abc9 [options] [selection]\n");
769 log("\n");
770 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
771 log("library to a target architecture.\n");
772 log("\n");
773 log(" -exe <command>\n");
774 #ifdef ABCEXTERNAL
775 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
776 #else
777 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
778 #endif
779 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
780 log("\n");
781 log(" -script <file>\n");
782 log(" use the specified ABC script file instead of the default script.\n");
783 log("\n");
784 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
785 log(" string is interpreted as the command string to be passed to ABC. The\n");
786 log(" leading plus sign is removed and all commas (,) in the string are\n");
787 log(" replaced with blanks before the string is passed to ABC.\n");
788 log("\n");
789 log(" if no -script parameter is given, the following scripts are used:\n");
790 log("\n");
791 log(" for -liberty without -constr:\n");
792 log("%s\n", fold_abc_cmd(ABC_COMMAND_LIB).c_str());
793 log("\n");
794 log(" for -liberty with -constr:\n");
795 log("%s\n", fold_abc_cmd(ABC_COMMAND_CTR).c_str());
796 log("\n");
797 log(" for -lut/-luts (only one LUT size):\n");
798 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack {S}").c_str());
799 log("\n");
800 log(" for -lut/-luts (different LUT sizes):\n");
801 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
802 log("\n");
803 log(" for -sop:\n");
804 log("%s\n", fold_abc_cmd(ABC_COMMAND_SOP).c_str());
805 log("\n");
806 log(" otherwise:\n");
807 log("%s\n", fold_abc_cmd(ABC_COMMAND_DFL).c_str());
808 log("\n");
809 log(" -fast\n");
810 log(" use different default scripts that are slightly faster (at the cost\n");
811 log(" of output quality):\n");
812 log("\n");
813 log(" for -liberty without -constr:\n");
814 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LIB).c_str());
815 log("\n");
816 log(" for -liberty with -constr:\n");
817 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_CTR).c_str());
818 log("\n");
819 log(" for -lut/-luts:\n");
820 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
821 log("\n");
822 log(" for -sop:\n");
823 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_SOP).c_str());
824 log("\n");
825 log(" otherwise:\n");
826 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_DFL).c_str());
827 log("\n");
828 log(" -liberty <file>\n");
829 log(" generate netlists for the specified cell library (using the liberty\n");
830 log(" file format).\n");
831 log("\n");
832 log(" -constr <file>\n");
833 log(" pass this file with timing constraints to ABC. Use with -liberty.\n");
834 log("\n");
835 log(" a constr file contains two lines:\n");
836 log(" set_driving_cell <cell_name>\n");
837 log(" set_load <floating_point_number>\n");
838 log("\n");
839 log(" the set_driving_cell statement defines which cell type is assumed to\n");
840 log(" drive the primary inputs and the set_load statement sets the load in\n");
841 log(" femtofarads for each primary output.\n");
842 log("\n");
843 log(" -D <picoseconds>\n");
844 log(" set delay target. the string {D} in the default scripts above is\n");
845 log(" replaced by this option when used, and an empty string otherwise.\n");
846 log(" this also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
847 log(" default scripts above.\n");
848 log("\n");
849 log(" -I <num>\n");
850 log(" maximum number of SOP inputs.\n");
851 log(" (replaces {I} in the default scripts above)\n");
852 log("\n");
853 log(" -P <num>\n");
854 log(" maximum number of SOP products.\n");
855 log(" (replaces {P} in the default scripts above)\n");
856 log("\n");
857 log(" -S <num>\n");
858 log(" maximum number of LUT inputs shared.\n");
859 log(" (replaces {S} in the default scripts above, default: -S 1)\n");
860 log("\n");
861 log(" -lut <width>\n");
862 log(" generate netlist using luts of (max) the specified width.\n");
863 log("\n");
864 log(" -lut <w1>:<w2>\n");
865 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
866 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
867 log(" the area cost doubles with each additional input bit. the delay cost\n");
868 log(" is still constant for all lut widths.\n");
869 log("\n");
870 log(" -lut <file>\n");
871 log(" pass this file with lut library to ABC.\n");
872 log("\n");
873 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
874 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
875 log(" 2, 3, .. inputs.\n");
876 log("\n");
877 log(" -sop\n");
878 log(" map to sum-of-product cells and inverters\n");
879 log("\n");
880 // log(" -mux4, -mux8, -mux16\n");
881 // log(" try to extract 4-input, 8-input, and/or 16-input muxes\n");
882 // log(" (ignored when used with -liberty or -lut)\n");
883 // log("\n");
884 log(" -g type1,type2,...\n");
885 log(" Map to the specified list of gate types. Supported gates types are:\n");
886 log(" AND, NAND, OR, NOR, XOR, XNOR, ANDNOT, ORNOT, MUX, AOI3, OAI3, AOI4, OAI4.\n");
887 log(" (The NOT gate is always added to this list automatically.)\n");
888 log("\n");
889 log(" The following aliases can be used to reference common sets of gate types:\n");
890 log(" simple: AND OR XOR MUX\n");
891 log(" cmos2: NAND NOR\n");
892 log(" cmos3: NAND NOR AOI3 OAI3\n");
893 log(" cmos4: NAND NOR AOI3 OAI3 AOI4 OAI4\n");
894 log(" gates: AND NAND OR NOR XOR XNOR ANDNOT ORNOT\n");
895 log(" aig: AND NAND OR NOR ANDNOT ORNOT\n");
896 log("\n");
897 log(" Prefix a gate type with a '-' to remove it from the list. For example\n");
898 log(" the arguments 'AND,OR,XOR' and 'simple,-MUX' are equivalent.\n");
899 log("\n");
900 log(" -dff\n");
901 log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
902 log(" clock domains are automatically partitioned in clock domains and each\n");
903 log(" domain is passed through ABC independently.\n");
904 log("\n");
905 log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
906 log(" use only the specified clock domain. this is like -dff, but only FF\n");
907 log(" cells that belong to the specified clock domain are used.\n");
908 log("\n");
909 log(" -keepff\n");
910 log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
911 log(" them, for example for equivalence checking.)\n");
912 log("\n");
913 log(" -nocleanup\n");
914 log(" when this option is used, the temporary files created by this pass\n");
915 log(" are not removed. this is useful for debugging.\n");
916 log("\n");
917 log(" -showtmp\n");
918 log(" print the temp dir name in log. usually this is suppressed so that the\n");
919 log(" command output is identical across runs.\n");
920 log("\n");
921 log(" -markgroups\n");
922 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
923 log(" this attribute is a unique integer for each ABC process started. This\n");
924 log(" is useful for debugging the partitioning of clock domains.\n");
925 log("\n");
926 log(" -box <file>\n");
927 log(" pass this file with box library to ABC. Use with -lut.\n");
928 log("\n");
929 log("When neither -liberty nor -lut is used, the Yosys standard cell library is\n");
930 log("loaded into ABC before the ABC script is executed.\n");
931 log("\n");
932 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
933 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
934 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
935 log("output when passing an ABC script that writes a file. Instead write your full\n");
936 log("design as BLIF file with write_blif and the load that into ABC externally if\n");
937 log("you want to use ABC to convert your design into another format.\n");
938 log("\n");
939 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
940 log("\n");
941 }
942 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
943 {
944 log_header(design, "Executing ABC9 pass (technology mapping using ABC).\n");
945 log_push();
946
947 assign_map.clear();
948 signal_map.clear();
949 signal_init.clear();
950 pi_map.clear();
951 po_map.clear();
952
953 #ifdef ABCEXTERNAL
954 std::string exe_file = ABCEXTERNAL;
955 #else
956 std::string exe_file = proc_self_dirname() + "yosys-abc";
957 #endif
958 std::string script_file, liberty_file, constr_file, clk_str, box_file, lut_file;
959 std::string delay_target, sop_inputs, sop_products, lutin_shared = "-S 1";
960 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
961 bool show_tempdir = false, sop_mode = false;
962 vector<int> lut_costs;
963 markgroups = false;
964
965 #if 0
966 cleanup = false;
967 show_tempdir = true;
968 #endif
969
970 map_mux4 = false;
971 map_mux8 = false;
972 map_mux16 = false;
973 enabled_gates.clear();
974
975 #ifdef _WIN32
976 #ifndef ABCEXTERNAL
977 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
978 exe_file = proc_self_dirname() + "..\\yosys-abc";
979 #endif
980 #endif
981
982 size_t argidx;
983 char pwd [PATH_MAX];
984 if (!getcwd(pwd, sizeof(pwd))) {
985 log_cmd_error("getcwd failed: %s\n", strerror(errno));
986 log_abort();
987 }
988 for (argidx = 1; argidx < args.size(); argidx++) {
989 std::string arg = args[argidx];
990 if (arg == "-exe" && argidx+1 < args.size()) {
991 exe_file = args[++argidx];
992 continue;
993 }
994 if (arg == "-script" && argidx+1 < args.size()) {
995 script_file = args[++argidx];
996 rewrite_filename(script_file);
997 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
998 script_file = std::string(pwd) + "/" + script_file;
999 continue;
1000 }
1001 if (arg == "-liberty" && argidx+1 < args.size()) {
1002 liberty_file = args[++argidx];
1003 rewrite_filename(liberty_file);
1004 if (!liberty_file.empty() && !is_absolute_path(liberty_file))
1005 liberty_file = std::string(pwd) + "/" + liberty_file;
1006 continue;
1007 }
1008 if (arg == "-constr" && argidx+1 < args.size()) {
1009 constr_file = args[++argidx];
1010 rewrite_filename(constr_file);
1011 if (!constr_file.empty() && !is_absolute_path(constr_file))
1012 constr_file = std::string(pwd) + "/" + constr_file;
1013 continue;
1014 }
1015 if (arg == "-D" && argidx+1 < args.size()) {
1016 delay_target = "-D " + args[++argidx];
1017 continue;
1018 }
1019 if (arg == "-I" && argidx+1 < args.size()) {
1020 sop_inputs = "-I " + args[++argidx];
1021 continue;
1022 }
1023 if (arg == "-P" && argidx+1 < args.size()) {
1024 sop_products = "-P " + args[++argidx];
1025 continue;
1026 }
1027 if (arg == "-S" && argidx+1 < args.size()) {
1028 lutin_shared = "-S " + args[++argidx];
1029 continue;
1030 }
1031 if (arg == "-lut" && argidx+1 < args.size()) {
1032 string arg = args[++argidx];
1033 size_t pos = arg.find_first_of(':');
1034 int lut_mode = 0, lut_mode2 = 0;
1035 if (pos != string::npos) {
1036 lut_mode = atoi(arg.substr(0, pos).c_str());
1037 lut_mode2 = atoi(arg.substr(pos+1).c_str());
1038 } else {
1039 pos = arg.find_first_of('.');
1040 if (pos != string::npos) {
1041 lut_file = arg;
1042 rewrite_filename(lut_file);
1043 if (!lut_file.empty() && !is_absolute_path(lut_file))
1044 lut_file = std::string(pwd) + "/" + lut_file;
1045 }
1046 else {
1047 lut_mode = atoi(arg.c_str());
1048 lut_mode2 = lut_mode;
1049 }
1050 }
1051 lut_costs.clear();
1052 for (int i = 0; i < lut_mode; i++)
1053 lut_costs.push_back(1);
1054 for (int i = lut_mode; i < lut_mode2; i++)
1055 lut_costs.push_back(2 << (i - lut_mode));
1056 continue;
1057 }
1058 if (arg == "-luts" && argidx+1 < args.size()) {
1059 lut_costs.clear();
1060 for (auto &tok : split_tokens(args[++argidx], ",")) {
1061 auto parts = split_tokens(tok, ":");
1062 if (GetSize(parts) == 0 && !lut_costs.empty())
1063 lut_costs.push_back(lut_costs.back());
1064 else if (GetSize(parts) == 1)
1065 lut_costs.push_back(atoi(parts.at(0).c_str()));
1066 else if (GetSize(parts) == 2)
1067 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
1068 lut_costs.push_back(atoi(parts.at(1).c_str()));
1069 else
1070 log_cmd_error("Invalid -luts syntax.\n");
1071 }
1072 continue;
1073 }
1074 if (arg == "-sop") {
1075 sop_mode = true;
1076 continue;
1077 }
1078 if (arg == "-mux4") {
1079 map_mux4 = true;
1080 continue;
1081 }
1082 if (arg == "-mux8") {
1083 map_mux8 = true;
1084 continue;
1085 }
1086 if (arg == "-mux16") {
1087 map_mux16 = true;
1088 continue;
1089 }
1090 if (arg == "-dress") {
1091 // TODO
1092 //abc_dress = true;
1093 continue;
1094 }
1095 if (arg == "-g" && argidx+1 < args.size()) {
1096 for (auto g : split_tokens(args[++argidx], ",")) {
1097 vector<string> gate_list;
1098 bool remove_gates = false;
1099 if (GetSize(g) > 0 && g[0] == '-') {
1100 remove_gates = true;
1101 g = g.substr(1);
1102 }
1103 if (g == "AND") goto ok_gate;
1104 if (g == "NAND") goto ok_gate;
1105 if (g == "OR") goto ok_gate;
1106 if (g == "NOR") goto ok_gate;
1107 if (g == "XOR") goto ok_gate;
1108 if (g == "XNOR") goto ok_gate;
1109 if (g == "ANDNOT") goto ok_gate;
1110 if (g == "ORNOT") goto ok_gate;
1111 if (g == "MUX") goto ok_gate;
1112 if (g == "AOI3") goto ok_gate;
1113 if (g == "OAI3") goto ok_gate;
1114 if (g == "AOI4") goto ok_gate;
1115 if (g == "OAI4") goto ok_gate;
1116 if (g == "simple") {
1117 gate_list.push_back("AND");
1118 gate_list.push_back("OR");
1119 gate_list.push_back("XOR");
1120 gate_list.push_back("MUX");
1121 goto ok_alias;
1122 }
1123 if (g == "cmos2") {
1124 gate_list.push_back("NAND");
1125 gate_list.push_back("NOR");
1126 goto ok_alias;
1127 }
1128 if (g == "cmos3") {
1129 gate_list.push_back("NAND");
1130 gate_list.push_back("NOR");
1131 gate_list.push_back("AOI3");
1132 gate_list.push_back("OAI3");
1133 goto ok_alias;
1134 }
1135 if (g == "cmos4") {
1136 gate_list.push_back("NAND");
1137 gate_list.push_back("NOR");
1138 gate_list.push_back("AOI3");
1139 gate_list.push_back("OAI3");
1140 gate_list.push_back("AOI4");
1141 gate_list.push_back("OAI4");
1142 goto ok_alias;
1143 }
1144 if (g == "gates") {
1145 gate_list.push_back("AND");
1146 gate_list.push_back("NAND");
1147 gate_list.push_back("OR");
1148 gate_list.push_back("NOR");
1149 gate_list.push_back("XOR");
1150 gate_list.push_back("XNOR");
1151 gate_list.push_back("ANDNOT");
1152 gate_list.push_back("ORNOT");
1153 goto ok_alias;
1154 }
1155 if (g == "aig") {
1156 gate_list.push_back("AND");
1157 gate_list.push_back("NAND");
1158 gate_list.push_back("OR");
1159 gate_list.push_back("NOR");
1160 gate_list.push_back("ANDNOT");
1161 gate_list.push_back("ORNOT");
1162 goto ok_alias;
1163 }
1164 cmd_error(args, argidx, stringf("Unsupported gate type: %s", g.c_str()));
1165 ok_gate:
1166 gate_list.push_back(g);
1167 ok_alias:
1168 for (auto gate : gate_list) {
1169 if (remove_gates)
1170 enabled_gates.erase(gate);
1171 else
1172 enabled_gates.insert(gate);
1173 }
1174 }
1175 continue;
1176 }
1177 if (arg == "-fast") {
1178 fast_mode = true;
1179 continue;
1180 }
1181 if (arg == "-dff") {
1182 dff_mode = true;
1183 continue;
1184 }
1185 if (arg == "-clk" && argidx+1 < args.size()) {
1186 clk_str = args[++argidx];
1187 dff_mode = true;
1188 continue;
1189 }
1190 if (arg == "-keepff") {
1191 keepff = true;
1192 continue;
1193 }
1194 if (arg == "-nocleanup") {
1195 cleanup = false;
1196 continue;
1197 }
1198 if (arg == "-showtmp") {
1199 show_tempdir = true;
1200 continue;
1201 }
1202 if (arg == "-markgroups") {
1203 markgroups = true;
1204 continue;
1205 }
1206 if (arg == "-box" && argidx+1 < args.size()) {
1207 box_file = args[++argidx];
1208 rewrite_filename(box_file);
1209 if (!box_file.empty() && !is_absolute_path(box_file))
1210 box_file = std::string(pwd) + "/" + box_file;
1211 continue;
1212 }
1213 break;
1214 }
1215 extra_args(args, argidx, design);
1216
1217 if ((!lut_costs.empty() || !lut_file.empty()) && !liberty_file.empty())
1218 log_cmd_error("Got -lut and -liberty! This two options are exclusive.\n");
1219 if (!constr_file.empty() && liberty_file.empty())
1220 log_cmd_error("Got -constr but no -liberty!\n");
1221
1222 for (auto mod : design->selected_modules())
1223 {
1224 if (mod->attributes.count("\\abc_box_id"))
1225 continue;
1226
1227 if (mod->processes.size() > 0) {
1228 log("Skipping module %s as it contains processes.\n", log_id(mod));
1229 continue;
1230 }
1231
1232 assign_map.set(mod);
1233 signal_init.clear();
1234
1235 for (Wire *wire : mod->wires())
1236 if (wire->attributes.count("\\init")) {
1237 SigSpec initsig = assign_map(wire);
1238 Const initval = wire->attributes.at("\\init");
1239 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
1240 switch (initval[i]) {
1241 case State::S0:
1242 signal_init[initsig[i]] = State::S0;
1243 break;
1244 case State::S1:
1245 signal_init[initsig[i]] = State::S0;
1246 break;
1247 default:
1248 break;
1249 }
1250 }
1251
1252 if (!dff_mode || !clk_str.empty()) {
1253 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
1254 delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode,
1255 box_file, lut_file);
1256 continue;
1257 }
1258
1259 CellTypes ct(design);
1260
1261 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
1262 std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
1263
1264 std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
1265 std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
1266 std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
1267
1268 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
1269 std::map<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
1270 std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
1271
1272 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
1273 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
1274
1275 for (auto cell : all_cells)
1276 {
1277 clkdomain_t key;
1278
1279 for (auto &conn : cell->connections())
1280 for (auto bit : conn.second) {
1281 bit = assign_map(bit);
1282 if (bit.wire != nullptr) {
1283 cell_to_bit[cell].insert(bit);
1284 bit_to_cell[bit].insert(cell);
1285 if (ct.cell_input(cell->type, conn.first)) {
1286 cell_to_bit_up[cell].insert(bit);
1287 bit_to_cell_down[bit].insert(cell);
1288 }
1289 if (ct.cell_output(cell->type, conn.first)) {
1290 cell_to_bit_down[cell].insert(bit);
1291 bit_to_cell_up[bit].insert(cell);
1292 }
1293 }
1294 }
1295
1296 if (cell->type == "$_DFF_N_" || cell->type == "$_DFF_P_")
1297 {
1298 key = clkdomain_t(cell->type == "$_DFF_P_", assign_map(cell->getPort("\\C")), true, RTLIL::SigSpec());
1299 }
1300 else
1301 if (cell->type == "$_DFFE_NN_" || cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_")
1302 {
1303 bool this_clk_pol = cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_";
1304 bool this_en_pol = cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PP_";
1305 key = clkdomain_t(this_clk_pol, assign_map(cell->getPort("\\C")), this_en_pol, assign_map(cell->getPort("\\E")));
1306 }
1307 else
1308 continue;
1309
1310 unassigned_cells.erase(cell);
1311 expand_queue.insert(cell);
1312 expand_queue_up.insert(cell);
1313 expand_queue_down.insert(cell);
1314
1315 assigned_cells[key].push_back(cell);
1316 assigned_cells_reverse[cell] = key;
1317 }
1318
1319 while (!expand_queue_up.empty() || !expand_queue_down.empty())
1320 {
1321 if (!expand_queue_up.empty())
1322 {
1323 RTLIL::Cell *cell = *expand_queue_up.begin();
1324 clkdomain_t key = assigned_cells_reverse.at(cell);
1325 expand_queue_up.erase(cell);
1326
1327 for (auto bit : cell_to_bit_up[cell])
1328 for (auto c : bit_to_cell_up[bit])
1329 if (unassigned_cells.count(c)) {
1330 unassigned_cells.erase(c);
1331 next_expand_queue_up.insert(c);
1332 assigned_cells[key].push_back(c);
1333 assigned_cells_reverse[c] = key;
1334 expand_queue.insert(c);
1335 }
1336 }
1337
1338 if (!expand_queue_down.empty())
1339 {
1340 RTLIL::Cell *cell = *expand_queue_down.begin();
1341 clkdomain_t key = assigned_cells_reverse.at(cell);
1342 expand_queue_down.erase(cell);
1343
1344 for (auto bit : cell_to_bit_down[cell])
1345 for (auto c : bit_to_cell_down[bit])
1346 if (unassigned_cells.count(c)) {
1347 unassigned_cells.erase(c);
1348 next_expand_queue_up.insert(c);
1349 assigned_cells[key].push_back(c);
1350 assigned_cells_reverse[c] = key;
1351 expand_queue.insert(c);
1352 }
1353 }
1354
1355 if (expand_queue_up.empty() && expand_queue_down.empty()) {
1356 expand_queue_up.swap(next_expand_queue_up);
1357 expand_queue_down.swap(next_expand_queue_down);
1358 }
1359 }
1360
1361 while (!expand_queue.empty())
1362 {
1363 RTLIL::Cell *cell = *expand_queue.begin();
1364 clkdomain_t key = assigned_cells_reverse.at(cell);
1365 expand_queue.erase(cell);
1366
1367 for (auto bit : cell_to_bit.at(cell)) {
1368 for (auto c : bit_to_cell[bit])
1369 if (unassigned_cells.count(c)) {
1370 unassigned_cells.erase(c);
1371 next_expand_queue.insert(c);
1372 assigned_cells[key].push_back(c);
1373 assigned_cells_reverse[c] = key;
1374 }
1375 bit_to_cell[bit].clear();
1376 }
1377
1378 if (expand_queue.empty())
1379 expand_queue.swap(next_expand_queue);
1380 }
1381
1382 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1383 for (auto cell : unassigned_cells) {
1384 assigned_cells[key].push_back(cell);
1385 assigned_cells_reverse[cell] = key;
1386 }
1387
1388 log_header(design, "Summary of detected clock domains:\n");
1389 for (auto &it : assigned_cells)
1390 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
1391 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
1392 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
1393
1394 for (auto &it : assigned_cells) {
1395 clk_polarity = std::get<0>(it.first);
1396 clk_sig = assign_map(std::get<1>(it.first));
1397 en_polarity = std::get<2>(it.first);
1398 en_sig = assign_map(std::get<3>(it.first));
1399 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, !clk_sig.empty(), "$",
1400 keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode,
1401 box_file, lut_file);
1402 assign_map.set(mod);
1403 }
1404 }
1405
1406 Pass::call(design, "clean");
1407
1408 assign_map.clear();
1409 signal_map.clear();
1410 signal_init.clear();
1411 pi_map.clear();
1412 po_map.clear();
1413
1414 log_pop();
1415 }
1416 } Abc9Pass;
1417
1418 PRIVATE_NAMESPACE_END