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