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