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