c01feedb69fb842cb31de0061672e9ef9d6eb781
[yosys.git] / passes / techmap / abc9_map.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 int map_autoidx;
67
68 inline std::string remap_name(RTLIL::IdString abc9_name)
69 {
70 return stringf("$abc$%d$%s", map_autoidx, abc9_name.c_str()+1);
71 }
72
73 std::string add_echos_to_abc9_cmd(std::string str)
74 {
75 std::string new_str, token;
76 for (size_t i = 0; i < str.size(); i++) {
77 token += str[i];
78 if (str[i] == ';') {
79 while (i+1 < str.size() && str[i+1] == ' ')
80 i++;
81 new_str += "echo + " + token + " " + token + " ";
82 token.clear();
83 }
84 }
85
86 if (!token.empty()) {
87 if (!new_str.empty())
88 new_str += "echo + " + token + "; ";
89 new_str += token;
90 }
91
92 return new_str;
93 }
94
95 std::string fold_abc9_cmd(std::string str)
96 {
97 std::string token, new_str = " ";
98 int char_counter = 10;
99
100 for (size_t i = 0; i <= str.size(); i++) {
101 if (i < str.size())
102 token += str[i];
103 if (i == str.size() || str[i] == ';') {
104 if (char_counter + token.size() > 75)
105 new_str += "\n ", char_counter = 14;
106 new_str += token, char_counter += token.size();
107 token.clear();
108 }
109 }
110
111 return new_str;
112 }
113
114 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
115 {
116 if (show_tempdir)
117 return text;
118
119 while (1) {
120 size_t pos = text.find(tempdir_name);
121 if (pos == std::string::npos)
122 break;
123 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
124 }
125
126 std::string selfdir_name = proc_self_dirname();
127 if (selfdir_name != "/") {
128 while (1) {
129 size_t pos = text.find(selfdir_name);
130 if (pos == std::string::npos)
131 break;
132 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
133 }
134 }
135
136 return text;
137 }
138
139 struct abc9_output_filter
140 {
141 bool got_cr;
142 int escape_seq_state;
143 std::string linebuf;
144 std::string tempdir_name;
145 bool show_tempdir;
146
147 abc9_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
148 {
149 got_cr = false;
150 escape_seq_state = 0;
151 }
152
153 void next_char(char ch)
154 {
155 if (escape_seq_state == 0 && ch == '\033') {
156 escape_seq_state = 1;
157 return;
158 }
159 if (escape_seq_state == 1) {
160 escape_seq_state = ch == '[' ? 2 : 0;
161 return;
162 }
163 if (escape_seq_state == 2) {
164 if ((ch < '0' || '9' < ch) && ch != ';')
165 escape_seq_state = 0;
166 return;
167 }
168 escape_seq_state = 0;
169 if (ch == '\r') {
170 got_cr = true;
171 return;
172 }
173 if (ch == '\n') {
174 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
175 got_cr = false, linebuf.clear();
176 return;
177 }
178 if (got_cr)
179 got_cr = false, linebuf.clear();
180 linebuf += ch;
181 }
182
183 void next_line(const std::string &line)
184 {
185 //int pi, po;
186 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
187 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
188 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
189 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
190 // return;
191 //}
192
193 for (char ch : line)
194 next_char(ch);
195 }
196 };
197
198 void abc9_module(RTLIL::Design *design, RTLIL::Module *module, std::string script_file, std::string exe_file,
199 vector<int> lut_costs, std::string delay_target, std::string /*lutin_shared*/, bool fast_mode,
200 bool show_tempdir, std::string box_file, std::string lut_file,
201 std::string wire_delay, bool nomfs, std::string tempdir_name
202 )
203 {
204 map_autoidx = autoidx++;
205
206 //FIXME:
207 //log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
208 // module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
209
210 std::string abc9_script;
211
212 if (!lut_costs.empty()) {
213 abc9_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
214 if (!box_file.empty())
215 abc9_script += stringf("read_box %s; ", box_file.c_str());
216 }
217 else
218 if (!lut_file.empty()) {
219 abc9_script += stringf("read_lut %s; ", lut_file.c_str());
220 if (!box_file.empty())
221 abc9_script += stringf("read_box %s; ", box_file.c_str());
222 }
223 else
224 log_abort();
225
226 abc9_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
227
228 if (!script_file.empty()) {
229 if (script_file[0] == '+') {
230 for (size_t i = 1; i < script_file.size(); i++)
231 if (script_file[i] == '\'')
232 abc9_script += "'\\''";
233 else if (script_file[i] == ',')
234 abc9_script += " ";
235 else
236 abc9_script += script_file[i];
237 } else
238 abc9_script += stringf("source %s", script_file.c_str());
239 } else if (!lut_costs.empty() || !lut_file.empty()) {
240 abc9_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
241 } else
242 log_abort();
243
244 for (size_t pos = abc9_script.find("{D}"); pos != std::string::npos; pos = abc9_script.find("{D}", pos))
245 abc9_script = abc9_script.substr(0, pos) + delay_target + abc9_script.substr(pos+3);
246
247 //for (size_t pos = abc9_script.find("{S}"); pos != std::string::npos; pos = abc9_script.find("{S}", pos))
248 // abc9_script = abc9_script.substr(0, pos) + lutin_shared + abc9_script.substr(pos+3);
249
250 for (size_t pos = abc9_script.find("{W}"); pos != std::string::npos; pos = abc9_script.find("{W}", pos))
251 abc9_script = abc9_script.substr(0, pos) + wire_delay + abc9_script.substr(pos+3);
252
253 if (nomfs)
254 for (size_t pos = abc9_script.find("&mfs"); pos != std::string::npos; pos = abc9_script.find("&mfs", pos))
255 abc9_script = abc9_script.erase(pos, strlen("&mfs"));
256
257 abc9_script += stringf("; &write -n %s/output.aig", tempdir_name.c_str());
258 abc9_script = add_echos_to_abc9_cmd(abc9_script);
259
260 for (size_t i = 0; i+1 < abc9_script.size(); i++)
261 if (abc9_script[i] == ';' && abc9_script[i+1] == ' ')
262 abc9_script[i+1] = '\n';
263
264 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
265 fprintf(f, "%s\n", abc9_script.c_str());
266 fclose(f);
267
268 int count_outputs = design->scratchpad_get_int("write_xaiger.num_outputs");
269 log("Extracted %d AND gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
270 design->scratchpad_get_int("write_xaiger.num_ands"),
271 design->scratchpad_get_int("write_xaiger.num_wires"),
272 design->scratchpad_get_int("write_xaiger.num_inputs"),
273 count_outputs);
274
275 if (count_outputs > 0) {
276 std::string buffer;
277 std::ifstream ifs;
278 #if 0
279 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.xaig");
280 ifs.open(buffer);
281 if (ifs.fail())
282 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
283 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
284 log_assert(!design->module(ID($__abc9__)));
285 {
286 AigerReader reader(design, ifs, ID($__abc9__), "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
287 reader.parse_xaiger();
288 }
289 ifs.close();
290 Pass::call_on_module(design, design->module(ID($__abc9__)), stringf("write_verilog -noexpr -norename -selected"));
291 design->remove(design->module(ID($__abc9__)));
292 #endif
293
294 log_header(design, "Executing ABC9.\n");
295
296 if (!lut_costs.empty()) {
297 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
298 f = fopen(buffer.c_str(), "wt");
299 if (f == NULL)
300 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
301 for (int i = 0; i < GetSize(lut_costs); i++)
302 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
303 fclose(f);
304 }
305
306 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
307 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
308
309 #ifndef YOSYS_LINK_ABC
310 abc9_output_filter filt(tempdir_name, show_tempdir);
311 int ret = run_command(buffer, std::bind(&abc9_output_filter::next_line, filt, std::placeholders::_1));
312 #else
313 // These needs to be mutable, supposedly due to getopt
314 char *abc9_argv[5];
315 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
316 abc9_argv[0] = strdup(exe_file.c_str());
317 abc9_argv[1] = strdup("-s");
318 abc9_argv[2] = strdup("-f");
319 abc9_argv[3] = strdup(tmp_script_name.c_str());
320 abc9_argv[4] = 0;
321 int ret = Abc_RealMain(4, abc9_argv);
322 free(abc9_argv[0]);
323 free(abc9_argv[1]);
324 free(abc9_argv[2]);
325 free(abc9_argv[3]);
326 #endif
327 if (ret != 0)
328 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
329
330 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.aig");
331 ifs.open(buffer, std::ifstream::binary);
332 if (ifs.fail())
333 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
334
335 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
336 log_assert(!design->module(ID($__abc9__)));
337
338 AigerReader reader(design, ifs, ID($__abc9__), "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
339 reader.parse_xaiger();
340 ifs.close();
341
342 #if 0
343 Pass::call_on_module(design, design->module(ID($__abc9__)), stringf("write_verilog -noexpr -norename -selected"));
344 #endif
345
346 log_header(design, "Re-integrating ABC9 results.\n");
347 RTLIL::Module *mapped_mod = design->module(ID($__abc9__));
348 if (mapped_mod == NULL)
349 log_error("ABC output file does not contain a module `$__abc9__'.\n");
350
351 for (auto w : mapped_mod->wires())
352 module->addWire(remap_name(w->name), GetSize(w));
353
354 for (auto it = module->cells_.begin(); it != module->cells_.end(); )
355 if (it->second->type.in(ID($_AND_), ID($_NOT_), ID($__ABC9_FF_)))
356 it = module->cells_.erase(it);
357 else
358 ++it;
359
360 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
361 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
362 dict<RTLIL::Cell*,RTLIL::Cell*> not2drivers;
363 dict<SigBit, std::vector<RTLIL::Cell*>> bit2sinks;
364
365 std::map<IdString, int> cell_stats;
366 for (auto mapped_cell : mapped_mod->cells())
367 {
368 toposort.node(mapped_cell->name);
369
370 RTLIL::Cell *cell = nullptr;
371 if (mapped_cell->type == ID($_NOT_)) {
372 RTLIL::SigBit a_bit = mapped_cell->getPort(ID::A);
373 RTLIL::SigBit y_bit = mapped_cell->getPort(ID::Y);
374 bit_users[a_bit].insert(mapped_cell->name);
375 bit_drivers[y_bit].insert(mapped_cell->name);
376
377 if (!a_bit.wire) {
378 mapped_cell->setPort(ID::Y, module->addWire(NEW_ID));
379 RTLIL::Wire *wire = module->wire(remap_name(y_bit.wire->name));
380 log_assert(wire);
381 module->connect(RTLIL::SigBit(wire, y_bit.offset), State::S1);
382 }
383 else if (!lut_costs.empty() || !lut_file.empty()) {
384 RTLIL::Cell* driver_lut = nullptr;
385 // ABC can return NOT gates that drive POs
386 if (!a_bit.wire->port_input) {
387 // If it's not a NOT gate that that comes from a PI directly,
388 // find the driver LUT and clone that to guarantee that we won't
389 // increase the max logic depth
390 // (TODO: Optimise by not cloning unless will increase depth)
391 RTLIL::IdString driver_name;
392 if (GetSize(a_bit.wire) == 1)
393 driver_name = stringf("%s$lut", a_bit.wire->name.c_str());
394 else
395 driver_name = stringf("%s[%d]$lut", a_bit.wire->name.c_str(), a_bit.offset);
396 driver_lut = mapped_mod->cell(driver_name);
397 }
398
399 if (!driver_lut) {
400 // If a driver couldn't be found (could be from PI or box CI)
401 // then implement using a LUT
402 cell = module->addLut(remap_name(stringf("%s$lut", mapped_cell->name.c_str())),
403 RTLIL::SigBit(module->wires_.at(remap_name(a_bit.wire->name)), a_bit.offset),
404 RTLIL::SigBit(module->wires_.at(remap_name(y_bit.wire->name)), y_bit.offset),
405 RTLIL::Const::from_string("01"));
406 bit2sinks[cell->getPort(ID::A)].push_back(cell);
407 cell_stats[ID($lut)]++;
408 }
409 else
410 not2drivers[mapped_cell] = driver_lut;
411 continue;
412 }
413 else
414 log_abort();
415 continue;
416 }
417 cell_stats[mapped_cell->type]++;
418
419 RTLIL::Cell *existing_cell = nullptr;
420 if (mapped_cell->type.in(ID($lut), ID($__ABC9_FF_))) {
421 if (mapped_cell->type == ID($lut) &&
422 GetSize(mapped_cell->getPort(ID::A)) == 1 &&
423 mapped_cell->getParam(ID(LUT)) == RTLIL::Const::from_string("01")) {
424 SigSpec my_a = module->wires_.at(remap_name(mapped_cell->getPort(ID::A).as_wire()->name));
425 SigSpec my_y = module->wires_.at(remap_name(mapped_cell->getPort(ID::Y).as_wire()->name));
426 module->connect(my_y, my_a);
427 log_abort();
428 continue;
429 }
430 cell = module->addCell(remap_name(mapped_cell->name), mapped_cell->type);
431 }
432 else {
433 existing_cell = module->cell(mapped_cell->name);
434 log_assert(existing_cell);
435 cell = module->addCell(remap_name(mapped_cell->name), mapped_cell->type);
436 }
437
438 if (existing_cell) {
439 cell->parameters = existing_cell->parameters;
440 cell->attributes = existing_cell->attributes;
441 }
442 else {
443 cell->parameters = mapped_cell->parameters;
444 cell->attributes = mapped_cell->attributes;
445 }
446
447 auto abc9_box = cell->attributes.erase("\\abc9_box_seq");
448 if (abc9_box) {
449 module->swap_names(cell, existing_cell);
450 module->remove(existing_cell);
451 }
452 RTLIL::Module* box_module = design->module(mapped_cell->type);
453 auto abc9_flop = box_module && box_module->attributes.count("\\abc9_flop");
454 for (auto &conn : mapped_cell->connections()) {
455 // Skip entire box ports composed entirely of padding only
456 if (abc9_box && conn.second.is_wire() && conn.second.as_wire()->get_bool_attribute(ID(abc9_padding)))
457 continue;
458
459 RTLIL::SigSpec newsig;
460 for (auto c : conn.second.chunks()) {
461 if (c.width == 0)
462 continue;
463 //log_assert(c.width == 1);
464 if (c.wire)
465 c.wire = module->wires_.at(remap_name(c.wire->name));
466 newsig.append(c);
467 }
468 cell->setPort(conn.first, newsig);
469
470 if (!abc9_flop) {
471 if (cell->input(conn.first)) {
472 for (auto i : newsig)
473 bit2sinks[i].push_back(cell);
474 for (auto i : conn.second)
475 bit_users[i].insert(mapped_cell->name);
476 }
477 if (cell->output(conn.first))
478 for (auto i : conn.second)
479 bit_drivers[i].insert(mapped_cell->name);
480 }
481 }
482 }
483
484 // Copy connections (and rename) from mapped_mod to module
485 for (auto conn : mapped_mod->connections()) {
486 if (!conn.first.is_fully_const()) {
487 auto chunks = conn.first.chunks();
488 for (auto &c : chunks)
489 c.wire = module->wires_.at(remap_name(c.wire->name));
490 conn.first = std::move(chunks);
491 }
492 if (!conn.second.is_fully_const()) {
493 auto chunks = conn.second.chunks();
494 for (auto &c : chunks)
495 if (c.wire)
496 c.wire = module->wires_.at(remap_name(c.wire->name));
497 conn.second = std::move(chunks);
498 }
499 module->connect(conn);
500 }
501
502 for (auto &it : cell_stats)
503 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
504 int in_wires = 0, out_wires = 0;
505
506 // Stitch in mapped_mod's inputs/outputs into module
507 for (auto port : mapped_mod->ports) {
508 RTLIL::Wire *w = mapped_mod->wire(port);
509 RTLIL::Wire *wire = module->wire(port);
510 log_assert(wire);
511 RTLIL::Wire *remap_wire = module->wire(remap_name(port));
512 RTLIL::SigSpec signal = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
513 log_assert(GetSize(signal) >= GetSize(remap_wire));
514
515 RTLIL::SigSig conn;
516 if (w->port_output) {
517 conn.first = signal;
518 conn.second = remap_wire;
519 out_wires++;
520 module->connect(conn);
521 }
522 else if (w->port_input) {
523 conn.first = remap_wire;
524 conn.second = signal;
525 in_wires++;
526 module->connect(conn);
527 }
528 }
529
530 for (auto &it : bit_users)
531 if (bit_drivers.count(it.first))
532 for (auto driver_cell : bit_drivers.at(it.first))
533 for (auto user_cell : it.second)
534 toposort.edge(driver_cell, user_cell);
535 bool no_loops YS_ATTRIBUTE(unused) = toposort.sort();
536 log_assert(no_loops);
537
538 for (auto ii = toposort.sorted.rbegin(); ii != toposort.sorted.rend(); ii++) {
539 RTLIL::Cell *not_cell = mapped_mod->cell(*ii);
540 log_assert(not_cell);
541 if (not_cell->type != ID($_NOT_))
542 continue;
543 auto it = not2drivers.find(not_cell);
544 if (it == not2drivers.end())
545 continue;
546 RTLIL::Cell *driver_lut = it->second;
547 RTLIL::SigBit a_bit = not_cell->getPort(ID::A);
548 RTLIL::SigBit y_bit = not_cell->getPort(ID::Y);
549 RTLIL::Const driver_mask;
550
551 a_bit.wire = module->wires_.at(remap_name(a_bit.wire->name));
552 y_bit.wire = module->wires_.at(remap_name(y_bit.wire->name));
553
554 auto jt = bit2sinks.find(a_bit);
555 if (jt == bit2sinks.end())
556 goto clone_lut;
557
558 for (auto sink_cell : jt->second)
559 if (sink_cell->type != ID($lut))
560 goto clone_lut;
561
562 // Push downstream LUTs past inverter
563 for (auto sink_cell : jt->second) {
564 SigSpec A = sink_cell->getPort(ID::A);
565 RTLIL::Const mask = sink_cell->getParam(ID(LUT));
566 int index = 0;
567 for (; index < GetSize(A); index++)
568 if (A[index] == a_bit)
569 break;
570 log_assert(index < GetSize(A));
571 int i = 0;
572 while (i < GetSize(mask)) {
573 for (int j = 0; j < (1 << index); j++)
574 std::swap(mask[i+j], mask[i+j+(1 << index)]);
575 i += 1 << (index+1);
576 }
577 A[index] = y_bit;
578 sink_cell->setPort(ID::A, A);
579 sink_cell->setParam(ID(LUT), mask);
580 }
581
582 // Since we have rewritten all sinks (which we know
583 // to be only LUTs) to be after the inverter, we can
584 // go ahead and clone the LUT with the expectation
585 // that the original driving LUT will become dangling
586 // and get cleaned away
587 clone_lut:
588 driver_mask = driver_lut->getParam(ID(LUT));
589 for (auto &b : driver_mask.bits) {
590 if (b == RTLIL::State::S0) b = RTLIL::State::S1;
591 else if (b == RTLIL::State::S1) b = RTLIL::State::S0;
592 }
593 auto cell = module->addLut(NEW_ID,
594 driver_lut->getPort(ID::A),
595 y_bit,
596 driver_mask);
597 for (auto &bit : cell->connections_.at(ID::A)) {
598 bit.wire = module->wires_.at(remap_name(bit.wire->name));
599 bit2sinks[bit].push_back(cell);
600 }
601 }
602
603 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
604 log("ABC RESULTS: input signals: %8d\n", in_wires);
605 log("ABC RESULTS: output signals: %8d\n", out_wires);
606
607 design->remove(mapped_mod);
608 }
609 //else
610 //{
611 // log("Don't call ABC as there is nothing to map.\n");
612 //}
613 }
614
615 struct Abc9MapPass : public Pass {
616 Abc9MapPass() : Pass("abc9_map", "use ABC9 for technology mapping") { }
617 void help() YS_OVERRIDE
618 {
619 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
620 log("\n");
621 log(" abc9_map [options] [selection]\n");
622 log("\n");
623 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
624 log("library to a target architecture.\n");
625 log("\n");
626 log(" -exe <command>\n");
627 #ifdef ABCEXTERNAL
628 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
629 #else
630 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
631 #endif
632 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
633 log("\n");
634 log(" -script <file>\n");
635 log(" use the specified ABC script file instead of the default script.\n");
636 log("\n");
637 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
638 log(" string is interpreted as the command string to be passed to ABC. The\n");
639 log(" leading plus sign is removed and all commas (,) in the string are\n");
640 log(" replaced with blanks before the string is passed to ABC.\n");
641 log("\n");
642 log(" if no -script parameter is given, the following scripts are used:\n");
643 log("\n");
644 log(" for -lut/-luts (only one LUT size):\n");
645 log("%s\n", fold_abc9_cmd(ABC_COMMAND_LUT /*"; lutpack {S}"*/).c_str());
646 log("\n");
647 log(" for -lut/-luts (different LUT sizes):\n");
648 log("%s\n", fold_abc9_cmd(ABC_COMMAND_LUT).c_str());
649 log("\n");
650 log(" -fast\n");
651 log(" use different default scripts that are slightly faster (at the cost\n");
652 log(" of output quality):\n");
653 log("\n");
654 log(" for -lut/-luts:\n");
655 log("%s\n", fold_abc9_cmd(ABC_FAST_COMMAND_LUT).c_str());
656 log("\n");
657 log(" -D <picoseconds>\n");
658 log(" set delay target. the string {D} in the default scripts above is\n");
659 log(" replaced by this option when used, and an empty string otherwise\n");
660 log(" (indicating best possible delay).\n");
661 log("\n");
662 // log(" -S <num>\n");
663 // log(" maximum number of LUT inputs shared.\n");
664 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
665 // log("\n");
666 log(" -lut <width>\n");
667 log(" generate netlist using luts of (max) the specified width.\n");
668 log("\n");
669 log(" -lut <w1>:<w2>\n");
670 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
671 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
672 log(" the area cost doubles with each additional input bit. the delay cost\n");
673 log(" is still constant for all lut widths.\n");
674 log("\n");
675 log(" -lut <file>\n");
676 log(" pass this file with lut library to ABC.\n");
677 log("\n");
678 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
679 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
680 log(" 2, 3, .. inputs.\n");
681 log("\n");
682 log(" -dff\n");
683 log(" also pass $_ABC9_FF_ cells through to ABC. modules with many clock\n");
684 log(" domains are marked as such and automatically partitioned by ABC.\n");
685 log("\n");
686 log(" -showtmp\n");
687 log(" print the temp dir name in log. usually this is suppressed so that the\n");
688 log(" command output is identical across runs.\n");
689 log("\n");
690 log(" -box <file>\n");
691 log(" pass this file with box library to ABC. Use with -lut.\n");
692 log("\n");
693 log(" -tempdir <dir>\n");
694 log(" use this as the temp dir.\n");
695 log("\n");
696 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
697 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
698 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
699 log("output when passing an ABC script that writes a file. Instead write your full\n");
700 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
701 log("you want to use ABC to convert your design into another format.\n");
702 log("\n");
703 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
704 log("\n");
705 }
706 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
707 {
708 log_header(design, "Executing ABC9_MAP pass (technology mapping using ABC9).\n");
709
710 #ifdef ABCEXTERNAL
711 std::string exe_file = ABCEXTERNAL;
712 #else
713 std::string exe_file = proc_self_dirname() + "yosys-abc";
714 #endif
715 std::string script_file, clk_str, box_file, lut_file;
716 std::string delay_target, lutin_shared = "-S 1", wire_delay;
717 std::string tempdir_name;
718 bool fast_mode = false;
719 bool show_tempdir = false;
720 bool nomfs = false;
721 vector<int> lut_costs;
722
723 #if 0
724 cleanup = false;
725 show_tempdir = true;
726 #endif
727
728 #ifdef _WIN32
729 #ifndef ABCEXTERNAL
730 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
731 exe_file = proc_self_dirname() + "..\\yosys-abc";
732 #endif
733 #endif
734
735 std::string lut_arg, luts_arg;
736 exe_file = design->scratchpad_get_string("abc9.exe", exe_file /* inherit default value if not set */);
737 script_file = design->scratchpad_get_string("abc9.script", script_file);
738 if (design->scratchpad.count("abc9.D")) {
739 delay_target = "-D " + design->scratchpad_get_string("abc9.D");
740 }
741 lut_arg = design->scratchpad_get_string("abc9.lut", lut_arg);
742 luts_arg = design->scratchpad_get_string("abc9.luts", luts_arg);
743 fast_mode = design->scratchpad_get_bool("abc9.fast", fast_mode);
744 show_tempdir = design->scratchpad_get_bool("abc9.showtmp", show_tempdir);
745 box_file = design->scratchpad_get_string("abc9.box", box_file);
746 if (design->scratchpad.count("abc9.W")) {
747 wire_delay = "-W " + design->scratchpad_get_string("abc9.W");
748 }
749 nomfs = design->scratchpad_get_bool("abc9.nomfs", nomfs);
750
751 size_t argidx;
752 char pwd [PATH_MAX];
753 if (!getcwd(pwd, sizeof(pwd))) {
754 log_cmd_error("getcwd failed: %s\n", strerror(errno));
755 log_abort();
756 }
757 for (argidx = 1; argidx < args.size(); argidx++) {
758 std::string arg = args[argidx];
759 if (arg == "-exe" && argidx+1 < args.size()) {
760 exe_file = args[++argidx];
761 continue;
762 }
763 if (arg == "-script" && argidx+1 < args.size()) {
764 script_file = args[++argidx];
765 continue;
766 }
767 if (arg == "-D" && argidx+1 < args.size()) {
768 delay_target = "-D " + args[++argidx];
769 continue;
770 }
771 //if (arg == "-S" && argidx+1 < args.size()) {
772 // lutin_shared = "-S " + args[++argidx];
773 // continue;
774 //}
775 if (arg == "-lut" && argidx+1 < args.size()) {
776 lut_arg = args[++argidx];
777 continue;
778 }
779 if (arg == "-luts" && argidx+1 < args.size()) {
780 lut_arg = args[++argidx];
781 continue;
782 }
783 if (arg == "-fast") {
784 fast_mode = true;
785 continue;
786 }
787 if (arg == "-showtmp") {
788 show_tempdir = true;
789 continue;
790 }
791 if (arg == "-box" && argidx+1 < args.size()) {
792 box_file = args[++argidx];
793 continue;
794 }
795 if (arg == "-W" && argidx+1 < args.size()) {
796 wire_delay = "-W " + args[++argidx];
797 continue;
798 }
799 if (arg == "-nomfs") {
800 nomfs = true;
801 continue;
802 }
803 if (arg == "-tempdir" && argidx+1 < args.size()) {
804 tempdir_name = args[++argidx];
805 continue;
806 }
807 break;
808 }
809 extra_args(args, argidx, design);
810
811 rewrite_filename(script_file);
812 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
813 script_file = std::string(pwd) + "/" + script_file;
814
815 // handle -lut / -luts args
816 if (!lut_arg.empty()) {
817 string arg = lut_arg;
818 if (arg.find_first_not_of("0123456789:") == std::string::npos) {
819 size_t pos = arg.find_first_of(':');
820 int lut_mode = 0, lut_mode2 = 0;
821 if (pos != string::npos) {
822 lut_mode = atoi(arg.substr(0, pos).c_str());
823 lut_mode2 = atoi(arg.substr(pos+1).c_str());
824 } else {
825 lut_mode = atoi(arg.c_str());
826 lut_mode2 = lut_mode;
827 }
828 lut_costs.clear();
829 for (int i = 0; i < lut_mode; i++)
830 lut_costs.push_back(1);
831 for (int i = lut_mode; i < lut_mode2; i++)
832 lut_costs.push_back(2 << (i - lut_mode));
833 }
834 else {
835 lut_file = arg;
836 rewrite_filename(lut_file);
837 if (!lut_file.empty() && !is_absolute_path(lut_file) && lut_file[0] != '+')
838 lut_file = std::string(pwd) + "/" + lut_file;
839 }
840 }
841 if (!luts_arg.empty()) {
842 lut_costs.clear();
843 for (auto &tok : split_tokens(luts_arg, ",")) {
844 auto parts = split_tokens(tok, ":");
845 if (GetSize(parts) == 0 && !lut_costs.empty())
846 lut_costs.push_back(lut_costs.back());
847 else if (GetSize(parts) == 1)
848 lut_costs.push_back(atoi(parts.at(0).c_str()));
849 else if (GetSize(parts) == 2)
850 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
851 lut_costs.push_back(atoi(parts.at(1).c_str()));
852 else
853 log_cmd_error("Invalid -luts syntax.\n");
854 }
855 }
856
857 // ABC expects a box file for XAIG
858 if (box_file.empty())
859 box_file = "+/dummy.box";
860
861 rewrite_filename(box_file);
862 if (!box_file.empty() && !is_absolute_path(box_file) && box_file[0] != '+')
863 box_file = std::string(pwd) + "/" + box_file;
864
865 if (tempdir_name.empty())
866 log_cmd_error("abc9_map '-tempdir' option is mandatory.\n");
867
868
869 for (auto mod : design->selected_modules())
870 {
871 if (mod->processes.size() > 0) {
872 log("Skipping module %s as it contains processes.\n", log_id(mod));
873 continue;
874 }
875
876 if (!design->selected_whole_module(mod))
877 log_error("Can't handle partially selected module %s!\n", log_id(mod));
878
879 abc9_module(design, mod, script_file, exe_file, lut_costs,
880 delay_target, lutin_shared, fast_mode, show_tempdir,
881 box_file, lut_file, wire_delay, nomfs, tempdir_name);
882 }
883 }
884 } Abc9MapPass;
885
886 PRIVATE_NAMESPACE_END