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