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