abc9_exe: -box to not require -lut
[yosys.git] / passes / techmap / abc9_exe.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/log.h"
41
42 #ifndef _WIN32
43 # include <unistd.h>
44 # include <dirent.h>
45 #endif
46
47 #ifdef YOSYS_LINK_ABC
48 extern "C" int Abc_RealMain(int argc, char *argv[]);
49 #endif
50
51 USING_YOSYS_NAMESPACE
52 PRIVATE_NAMESPACE_BEGIN
53
54 std::string add_echos_to_abc9_cmd(std::string str)
55 {
56 std::string new_str, token;
57 for (size_t i = 0; i < str.size(); i++) {
58 token += str[i];
59 if (str[i] == ';') {
60 while (i+1 < str.size() && str[i+1] == ' ')
61 i++;
62 new_str += "echo + " + token + " " + token + " ";
63 token.clear();
64 }
65 }
66
67 if (!token.empty()) {
68 if (!new_str.empty())
69 new_str += "echo + " + token + "; ";
70 new_str += token;
71 }
72
73 return new_str;
74 }
75
76 std::string fold_abc9_cmd(std::string str)
77 {
78 std::string token, new_str = " ";
79 int char_counter = 10;
80
81 for (size_t i = 0; i <= str.size(); i++) {
82 if (i < str.size())
83 token += str[i];
84 if (i == str.size() || str[i] == ';') {
85 if (char_counter + token.size() > 75)
86 new_str += "\n ", char_counter = 14;
87 new_str += token, char_counter += token.size();
88 token.clear();
89 }
90 }
91
92 return new_str;
93 }
94
95 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
96 {
97 if (show_tempdir)
98 return text;
99
100 while (1) {
101 size_t pos = text.find(tempdir_name);
102 if (pos == std::string::npos)
103 break;
104 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
105 }
106
107 std::string selfdir_name = proc_self_dirname();
108 if (selfdir_name != "/") {
109 while (1) {
110 size_t pos = text.find(selfdir_name);
111 if (pos == std::string::npos)
112 break;
113 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
114 }
115 }
116
117 return text;
118 }
119
120 struct abc9_output_filter
121 {
122 bool got_cr;
123 int escape_seq_state;
124 std::string linebuf;
125 std::string tempdir_name;
126 bool show_tempdir;
127
128 abc9_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
129 {
130 got_cr = false;
131 escape_seq_state = 0;
132 }
133
134 void next_char(char ch)
135 {
136 if (escape_seq_state == 0 && ch == '\033') {
137 escape_seq_state = 1;
138 return;
139 }
140 if (escape_seq_state == 1) {
141 escape_seq_state = ch == '[' ? 2 : 0;
142 return;
143 }
144 if (escape_seq_state == 2) {
145 if ((ch < '0' || '9' < ch) && ch != ';')
146 escape_seq_state = 0;
147 return;
148 }
149 escape_seq_state = 0;
150 if (ch == '\r') {
151 got_cr = true;
152 return;
153 }
154 if (ch == '\n') {
155 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
156 got_cr = false, linebuf.clear();
157 return;
158 }
159 if (got_cr)
160 got_cr = false, linebuf.clear();
161 linebuf += ch;
162 }
163
164 void next_line(const std::string &line)
165 {
166 //int pi, po;
167 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
168 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
169 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
170 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
171 // return;
172 //}
173
174 for (char ch : line)
175 next_char(ch);
176 }
177 };
178
179 void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe_file,
180 vector<int> lut_costs, std::string delay_target, std::string /*lutin_shared*/, bool fast_mode,
181 bool show_tempdir, std::string box_file, std::string lut_file,
182 std::string wire_delay, bool nomfs, std::string tempdir_name
183 )
184 {
185 //FIXME:
186 //log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
187 // module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
188
189 std::string abc9_script;
190
191 if (!lut_costs.empty())
192 abc9_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
193 else
194 if (!lut_file.empty())
195 abc9_script += stringf("read_lut %s; ", lut_file.c_str());
196 else
197 log_abort();
198
199 abc9_script += stringf("read_box %s; ", box_file.c_str());
200 abc9_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
201
202 if (!script_file.empty()) {
203 if (script_file[0] == '+') {
204 for (size_t i = 1; i < script_file.size(); i++)
205 if (script_file[i] == '\'')
206 abc9_script += "'\\''";
207 else if (script_file[i] == ',')
208 abc9_script += " ";
209 else
210 abc9_script += script_file[i];
211 } else
212 abc9_script += stringf("source %s", script_file.c_str());
213 } else if (!lut_costs.empty() || !lut_file.empty()) {
214 abc9_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
215 } else
216 log_abort();
217
218 for (size_t pos = abc9_script.find("{D}"); pos != std::string::npos; pos = abc9_script.find("{D}", pos))
219 abc9_script = abc9_script.substr(0, pos) + delay_target + abc9_script.substr(pos+3);
220
221 //for (size_t pos = abc9_script.find("{S}"); pos != std::string::npos; pos = abc9_script.find("{S}", pos))
222 // abc9_script = abc9_script.substr(0, pos) + lutin_shared + abc9_script.substr(pos+3);
223
224 for (size_t pos = abc9_script.find("{W}"); pos != std::string::npos; pos = abc9_script.find("{W}", pos))
225 abc9_script = abc9_script.substr(0, pos) + wire_delay + abc9_script.substr(pos+3);
226
227 if (nomfs)
228 for (size_t pos = abc9_script.find("&mfs"); pos != std::string::npos; pos = abc9_script.find("&mfs", pos))
229 abc9_script = abc9_script.erase(pos, strlen("&mfs"));
230
231 abc9_script += stringf("; &write -n %s/output.aig", tempdir_name.c_str());
232 abc9_script = add_echos_to_abc9_cmd(abc9_script);
233
234 for (size_t i = 0; i+1 < abc9_script.size(); i++)
235 if (abc9_script[i] == ';' && abc9_script[i+1] == ' ')
236 abc9_script[i+1] = '\n';
237
238 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
239 fprintf(f, "%s\n", abc9_script.c_str());
240 fclose(f);
241
242 std::string buffer;
243
244 log_header(design, "Executing ABC9.\n");
245
246 if (!lut_costs.empty()) {
247 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
248 f = fopen(buffer.c_str(), "wt");
249 if (f == NULL)
250 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
251 for (int i = 0; i < GetSize(lut_costs); i++)
252 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
253 fclose(f);
254 }
255
256 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
257 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
258
259 #ifndef YOSYS_LINK_ABC
260 abc9_output_filter filt(tempdir_name, show_tempdir);
261 int ret = run_command(buffer, std::bind(&abc9_output_filter::next_line, filt, std::placeholders::_1));
262 #else
263 // These needs to be mutable, supposedly due to getopt
264 char *abc9_argv[5];
265 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
266 abc9_argv[0] = strdup(exe_file.c_str());
267 abc9_argv[1] = strdup("-s");
268 abc9_argv[2] = strdup("-f");
269 abc9_argv[3] = strdup(tmp_script_name.c_str());
270 abc9_argv[4] = 0;
271 int ret = Abc_RealMain(4, abc9_argv);
272 free(abc9_argv[0]);
273 free(abc9_argv[1]);
274 free(abc9_argv[2]);
275 free(abc9_argv[3]);
276 #endif
277 if (ret != 0)
278 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
279 }
280
281 struct Abc9ExePass : public Pass {
282 Abc9ExePass() : Pass("abc9_exe", "use ABC9 for technology mapping") { }
283 void help() YS_OVERRIDE
284 {
285 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
286 log("\n");
287 log(" abc9_exe [options] [selection]\n");
288 log("\n");
289 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
290 log("library to a target architecture.\n");
291 log("\n");
292 log(" -exe <command>\n");
293 #ifdef ABCEXTERNAL
294 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
295 #else
296 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
297 #endif
298 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
299 log("\n");
300 log(" -script <file>\n");
301 log(" use the specified ABC script file instead of the default script.\n");
302 log("\n");
303 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
304 log(" string is interpreted as the command string to be passed to ABC. The\n");
305 log(" leading plus sign is removed and all commas (,) in the string are\n");
306 log(" replaced with blanks before the string is passed to ABC.\n");
307 log("\n");
308 log(" if no -script parameter is given, the following scripts are used:\n");
309 log("\n");
310 log(" for -lut/-luts (only one LUT size):\n");
311 log("%s\n", fold_abc9_cmd(ABC_COMMAND_LUT /*"; lutpack {S}"*/).c_str());
312 log("\n");
313 log(" for -lut/-luts (different LUT sizes):\n");
314 log("%s\n", fold_abc9_cmd(ABC_COMMAND_LUT).c_str());
315 log("\n");
316 log(" -fast\n");
317 log(" use different default scripts that are slightly faster (at the cost\n");
318 log(" of output quality):\n");
319 log("\n");
320 log(" for -lut/-luts:\n");
321 log("%s\n", fold_abc9_cmd(ABC_FAST_COMMAND_LUT).c_str());
322 log("\n");
323 log(" -D <picoseconds>\n");
324 log(" set delay target. the string {D} in the default scripts above is\n");
325 log(" replaced by this option when used, and an empty string otherwise\n");
326 log(" (indicating best possible delay).\n");
327 log("\n");
328 // log(" -S <num>\n");
329 // log(" maximum number of LUT inputs shared.\n");
330 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
331 // log("\n");
332 log(" -lut <width>\n");
333 log(" generate netlist using luts of (max) the specified width.\n");
334 log("\n");
335 log(" -lut <w1>:<w2>\n");
336 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
337 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
338 log(" the area cost doubles with each additional input bit. the delay cost\n");
339 log(" is still constant for all lut widths.\n");
340 log("\n");
341 log(" -lut <file>\n");
342 log(" pass this file with lut library to ABC.\n");
343 log("\n");
344 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
345 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
346 log(" 2, 3, .. inputs.\n");
347 log("\n");
348 log(" -showtmp\n");
349 log(" print the temp dir name in log. usually this is suppressed so that the\n");
350 log(" command output is identical across runs.\n");
351 log("\n");
352 log(" -box <file>\n");
353 log(" pass this file with box library to ABC.\n");
354 log("\n");
355 log(" -cwd <dir>\n");
356 log(" use this as the current working directory, inside which the 'input.xaig'\n");
357 log(" file is expected. temporary files will be created in this directory, and\n");
358 log(" the mapped result will be written to 'output.aig'.\n");
359 log("\n");
360 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
361 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
362 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
363 log("output when passing an ABC script that writes a file. Instead write your full\n");
364 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
365 log("you want to use ABC to convert your design into another format.\n");
366 log("\n");
367 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
368 log("\n");
369 }
370 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
371 {
372 log_header(design, "Executing ABC9_MAP pass (technology mapping using ABC9).\n");
373
374 #ifdef ABCEXTERNAL
375 std::string exe_file = ABCEXTERNAL;
376 #else
377 std::string exe_file = proc_self_dirname() + "yosys-abc";
378 #endif
379 std::string script_file, clk_str, box_file, lut_file;
380 std::string delay_target, lutin_shared = "-S 1", wire_delay;
381 std::string tempdir_name;
382 bool fast_mode = false;
383 bool show_tempdir = false;
384 bool nomfs = false;
385 vector<int> lut_costs;
386
387 #if 0
388 cleanup = false;
389 show_tempdir = true;
390 #endif
391
392 #ifdef _WIN32
393 #ifndef ABCEXTERNAL
394 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
395 exe_file = proc_self_dirname() + "..\\yosys-abc";
396 #endif
397 #endif
398
399 std::string lut_arg, luts_arg;
400 exe_file = design->scratchpad_get_string("abc9.exe", exe_file /* inherit default value if not set */);
401 script_file = design->scratchpad_get_string("abc9.script", script_file);
402 if (design->scratchpad.count("abc9.D")) {
403 delay_target = "-D " + design->scratchpad_get_string("abc9.D");
404 }
405 lut_arg = design->scratchpad_get_string("abc9.lut", lut_arg);
406 luts_arg = design->scratchpad_get_string("abc9.luts", luts_arg);
407 fast_mode = design->scratchpad_get_bool("abc9.fast", fast_mode);
408 show_tempdir = design->scratchpad_get_bool("abc9.showtmp", show_tempdir);
409 box_file = design->scratchpad_get_string("abc9.box", box_file);
410 if (design->scratchpad.count("abc9.W")) {
411 wire_delay = "-W " + design->scratchpad_get_string("abc9.W");
412 }
413 nomfs = design->scratchpad_get_bool("abc9.nomfs", nomfs);
414
415 size_t argidx;
416 char pwd [PATH_MAX];
417 if (!getcwd(pwd, sizeof(pwd))) {
418 log_cmd_error("getcwd failed: %s\n", strerror(errno));
419 log_abort();
420 }
421 for (argidx = 1; argidx < args.size(); argidx++) {
422 std::string arg = args[argidx];
423 if (arg == "-exe" && argidx+1 < args.size()) {
424 exe_file = args[++argidx];
425 continue;
426 }
427 if (arg == "-script" && argidx+1 < args.size()) {
428 script_file = args[++argidx];
429 continue;
430 }
431 if (arg == "-D" && argidx+1 < args.size()) {
432 delay_target = "-D " + args[++argidx];
433 continue;
434 }
435 //if (arg == "-S" && argidx+1 < args.size()) {
436 // lutin_shared = "-S " + args[++argidx];
437 // continue;
438 //}
439 if (arg == "-lut" && argidx+1 < args.size()) {
440 lut_arg = args[++argidx];
441 continue;
442 }
443 if (arg == "-luts" && argidx+1 < args.size()) {
444 lut_arg = args[++argidx];
445 continue;
446 }
447 if (arg == "-fast") {
448 fast_mode = true;
449 continue;
450 }
451 if (arg == "-showtmp") {
452 show_tempdir = true;
453 continue;
454 }
455 if (arg == "-box" && argidx+1 < args.size()) {
456 box_file = args[++argidx];
457 continue;
458 }
459 if (arg == "-W" && argidx+1 < args.size()) {
460 wire_delay = "-W " + args[++argidx];
461 continue;
462 }
463 if (arg == "-nomfs") {
464 nomfs = true;
465 continue;
466 }
467 if (arg == "-cwd" && argidx+1 < args.size()) {
468 tempdir_name = args[++argidx];
469 continue;
470 }
471 break;
472 }
473 extra_args(args, argidx, design);
474
475 rewrite_filename(script_file);
476 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
477 script_file = std::string(pwd) + "/" + script_file;
478
479 // handle -lut / -luts args
480 if (!lut_arg.empty()) {
481 string arg = lut_arg;
482 if (arg.find_first_not_of("0123456789:") == std::string::npos) {
483 size_t pos = arg.find_first_of(':');
484 int lut_mode = 0, lut_mode2 = 0;
485 if (pos != string::npos) {
486 lut_mode = atoi(arg.substr(0, pos).c_str());
487 lut_mode2 = atoi(arg.substr(pos+1).c_str());
488 } else {
489 lut_mode = atoi(arg.c_str());
490 lut_mode2 = lut_mode;
491 }
492 lut_costs.clear();
493 for (int i = 0; i < lut_mode; i++)
494 lut_costs.push_back(1);
495 for (int i = lut_mode; i < lut_mode2; i++)
496 lut_costs.push_back(2 << (i - lut_mode));
497 }
498 else {
499 lut_file = arg;
500 rewrite_filename(lut_file);
501 if (!lut_file.empty() && !is_absolute_path(lut_file) && lut_file[0] != '+')
502 lut_file = std::string(pwd) + "/" + lut_file;
503 }
504 }
505 if (!luts_arg.empty()) {
506 lut_costs.clear();
507 for (auto &tok : split_tokens(luts_arg, ",")) {
508 auto parts = split_tokens(tok, ":");
509 if (GetSize(parts) == 0 && !lut_costs.empty())
510 lut_costs.push_back(lut_costs.back());
511 else if (GetSize(parts) == 1)
512 lut_costs.push_back(atoi(parts.at(0).c_str()));
513 else if (GetSize(parts) == 2)
514 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
515 lut_costs.push_back(atoi(parts.at(1).c_str()));
516 else
517 log_cmd_error("Invalid -luts syntax.\n");
518 }
519 }
520
521 // ABC expects a box file for XAIG
522 if (box_file.empty())
523 box_file = "+/dummy.box";
524
525 rewrite_filename(box_file);
526 if (!box_file.empty() && !is_absolute_path(box_file) && box_file[0] != '+')
527 box_file = std::string(pwd) + "/" + box_file;
528
529 if (tempdir_name.empty())
530 log_cmd_error("abc9_exe '-cwd' option is mandatory.\n");
531
532
533 abc9_module(design, script_file, exe_file, lut_costs,
534 delay_target, lutin_shared, fast_mode, show_tempdir,
535 box_file, lut_file, wire_delay, nomfs, tempdir_name);
536 }
537 } Abc9ExePass;
538
539 PRIVATE_NAMESPACE_END