Merge remote-tracking branch 'origin/master' into eddie/abc9_refactor
[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 if (!box_file.empty())
194 abc9_script += stringf("read_box %s; ", box_file.c_str());
195 }
196 else
197 if (!lut_file.empty()) {
198 abc9_script += stringf("read_lut %s; ", lut_file.c_str());
199 if (!box_file.empty())
200 abc9_script += stringf("read_box %s; ", box_file.c_str());
201 }
202 else
203 log_abort();
204
205 abc9_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
206
207 if (!script_file.empty()) {
208 if (script_file[0] == '+') {
209 for (size_t i = 1; i < script_file.size(); i++)
210 if (script_file[i] == '\'')
211 abc9_script += "'\\''";
212 else if (script_file[i] == ',')
213 abc9_script += " ";
214 else
215 abc9_script += script_file[i];
216 } else
217 abc9_script += stringf("source %s", script_file.c_str());
218 } else if (!lut_costs.empty() || !lut_file.empty()) {
219 abc9_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
220 } else
221 log_abort();
222
223 for (size_t pos = abc9_script.find("{D}"); pos != std::string::npos; pos = abc9_script.find("{D}", pos))
224 abc9_script = abc9_script.substr(0, pos) + delay_target + abc9_script.substr(pos+3);
225
226 //for (size_t pos = abc9_script.find("{S}"); pos != std::string::npos; pos = abc9_script.find("{S}", pos))
227 // abc9_script = abc9_script.substr(0, pos) + lutin_shared + abc9_script.substr(pos+3);
228
229 for (size_t pos = abc9_script.find("{W}"); pos != std::string::npos; pos = abc9_script.find("{W}", pos))
230 abc9_script = abc9_script.substr(0, pos) + wire_delay + abc9_script.substr(pos+3);
231
232 if (nomfs)
233 for (size_t pos = abc9_script.find("&mfs"); pos != std::string::npos; pos = abc9_script.find("&mfs", pos))
234 abc9_script = abc9_script.erase(pos, strlen("&mfs"));
235
236 abc9_script += stringf("; &write -n %s/output.aig", tempdir_name.c_str());
237 abc9_script = add_echos_to_abc9_cmd(abc9_script);
238
239 for (size_t i = 0; i+1 < abc9_script.size(); i++)
240 if (abc9_script[i] == ';' && abc9_script[i+1] == ' ')
241 abc9_script[i+1] = '\n';
242
243 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
244 fprintf(f, "%s\n", abc9_script.c_str());
245 fclose(f);
246
247 std::string buffer;
248
249 log_header(design, "Executing ABC9.\n");
250
251 if (!lut_costs.empty()) {
252 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
253 f = fopen(buffer.c_str(), "wt");
254 if (f == NULL)
255 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
256 for (int i = 0; i < GetSize(lut_costs); i++)
257 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
258 fclose(f);
259 }
260
261 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
262 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
263
264 #ifndef YOSYS_LINK_ABC
265 abc9_output_filter filt(tempdir_name, show_tempdir);
266 int ret = run_command(buffer, std::bind(&abc9_output_filter::next_line, filt, std::placeholders::_1));
267 #else
268 // These needs to be mutable, supposedly due to getopt
269 char *abc9_argv[5];
270 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
271 abc9_argv[0] = strdup(exe_file.c_str());
272 abc9_argv[1] = strdup("-s");
273 abc9_argv[2] = strdup("-f");
274 abc9_argv[3] = strdup(tmp_script_name.c_str());
275 abc9_argv[4] = 0;
276 int ret = Abc_RealMain(4, abc9_argv);
277 free(abc9_argv[0]);
278 free(abc9_argv[1]);
279 free(abc9_argv[2]);
280 free(abc9_argv[3]);
281 #endif
282 if (ret != 0)
283 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
284 }
285
286 struct Abc9ExePass : public Pass {
287 Abc9ExePass() : Pass("abc9_exe", "use ABC9 for technology mapping") { }
288 void help() YS_OVERRIDE
289 {
290 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
291 log("\n");
292 log(" abc9_exe [options] [selection]\n");
293 log("\n");
294 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
295 log("library to a target architecture.\n");
296 log("\n");
297 log(" -exe <command>\n");
298 #ifdef ABCEXTERNAL
299 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
300 #else
301 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
302 #endif
303 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
304 log("\n");
305 log(" -script <file>\n");
306 log(" use the specified ABC script file instead of the default script.\n");
307 log("\n");
308 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
309 log(" string is interpreted as the command string to be passed to ABC. The\n");
310 log(" leading plus sign is removed and all commas (,) in the string are\n");
311 log(" replaced with blanks before the string is passed to ABC.\n");
312 log("\n");
313 log(" if no -script parameter is given, the following scripts are used:\n");
314 log("\n");
315 log(" for -lut/-luts (only one LUT size):\n");
316 log("%s\n", fold_abc9_cmd(ABC_COMMAND_LUT /*"; lutpack {S}"*/).c_str());
317 log("\n");
318 log(" for -lut/-luts (different LUT sizes):\n");
319 log("%s\n", fold_abc9_cmd(ABC_COMMAND_LUT).c_str());
320 log("\n");
321 log(" -fast\n");
322 log(" use different default scripts that are slightly faster (at the cost\n");
323 log(" of output quality):\n");
324 log("\n");
325 log(" for -lut/-luts:\n");
326 log("%s\n", fold_abc9_cmd(ABC_FAST_COMMAND_LUT).c_str());
327 log("\n");
328 log(" -D <picoseconds>\n");
329 log(" set delay target. the string {D} in the default scripts above is\n");
330 log(" replaced by this option when used, and an empty string otherwise\n");
331 log(" (indicating best possible delay).\n");
332 log("\n");
333 // log(" -S <num>\n");
334 // log(" maximum number of LUT inputs shared.\n");
335 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
336 // log("\n");
337 log(" -lut <width>\n");
338 log(" generate netlist using luts of (max) the specified width.\n");
339 log("\n");
340 log(" -lut <w1>:<w2>\n");
341 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
342 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
343 log(" the area cost doubles with each additional input bit. the delay cost\n");
344 log(" is still constant for all lut widths.\n");
345 log("\n");
346 log(" -lut <file>\n");
347 log(" pass this file with lut library to ABC.\n");
348 log("\n");
349 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
350 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
351 log(" 2, 3, .. inputs.\n");
352 log("\n");
353 log(" -showtmp\n");
354 log(" print the temp dir name in log. usually this is suppressed so that the\n");
355 log(" command output is identical across runs.\n");
356 log("\n");
357 log(" -box <file>\n");
358 log(" pass this file with box library to ABC. Use with -lut.\n");
359 log("\n");
360 log(" -cwd <dir>\n");
361 log(" use this as the current working directory, inside which the 'input.xaig'\n");
362 log(" file is expected. temporary files will be created in this directory, and\n");
363 log(" the mapped result will be written to 'output.aig'.\n");
364 log("\n");
365 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
366 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
367 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
368 log("output when passing an ABC script that writes a file. Instead write your full\n");
369 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
370 log("you want to use ABC to convert your design into another format.\n");
371 log("\n");
372 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
373 log("\n");
374 }
375 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
376 {
377 log_header(design, "Executing ABC9_MAP pass (technology mapping using ABC9).\n");
378
379 #ifdef ABCEXTERNAL
380 std::string exe_file = ABCEXTERNAL;
381 #else
382 std::string exe_file = proc_self_dirname() + "yosys-abc";
383 #endif
384 std::string script_file, clk_str, box_file, lut_file;
385 std::string delay_target, lutin_shared = "-S 1", wire_delay;
386 std::string tempdir_name;
387 bool fast_mode = false;
388 bool show_tempdir = false;
389 bool nomfs = false;
390 vector<int> lut_costs;
391
392 #if 0
393 cleanup = false;
394 show_tempdir = true;
395 #endif
396
397 #ifdef _WIN32
398 #ifndef ABCEXTERNAL
399 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
400 exe_file = proc_self_dirname() + "..\\yosys-abc";
401 #endif
402 #endif
403
404 std::string lut_arg, luts_arg;
405 exe_file = design->scratchpad_get_string("abc9.exe", exe_file /* inherit default value if not set */);
406 script_file = design->scratchpad_get_string("abc9.script", script_file);
407 if (design->scratchpad.count("abc9.D")) {
408 delay_target = "-D " + design->scratchpad_get_string("abc9.D");
409 }
410 lut_arg = design->scratchpad_get_string("abc9.lut", lut_arg);
411 luts_arg = design->scratchpad_get_string("abc9.luts", luts_arg);
412 fast_mode = design->scratchpad_get_bool("abc9.fast", fast_mode);
413 show_tempdir = design->scratchpad_get_bool("abc9.showtmp", show_tempdir);
414 box_file = design->scratchpad_get_string("abc9.box", box_file);
415 if (design->scratchpad.count("abc9.W")) {
416 wire_delay = "-W " + design->scratchpad_get_string("abc9.W");
417 }
418 nomfs = design->scratchpad_get_bool("abc9.nomfs", nomfs);
419
420 size_t argidx;
421 char pwd [PATH_MAX];
422 if (!getcwd(pwd, sizeof(pwd))) {
423 log_cmd_error("getcwd failed: %s\n", strerror(errno));
424 log_abort();
425 }
426 for (argidx = 1; argidx < args.size(); argidx++) {
427 std::string arg = args[argidx];
428 if (arg == "-exe" && argidx+1 < args.size()) {
429 exe_file = args[++argidx];
430 continue;
431 }
432 if (arg == "-script" && argidx+1 < args.size()) {
433 script_file = args[++argidx];
434 continue;
435 }
436 if (arg == "-D" && argidx+1 < args.size()) {
437 delay_target = "-D " + args[++argidx];
438 continue;
439 }
440 //if (arg == "-S" && argidx+1 < args.size()) {
441 // lutin_shared = "-S " + args[++argidx];
442 // continue;
443 //}
444 if (arg == "-lut" && argidx+1 < args.size()) {
445 lut_arg = args[++argidx];
446 continue;
447 }
448 if (arg == "-luts" && argidx+1 < args.size()) {
449 lut_arg = args[++argidx];
450 continue;
451 }
452 if (arg == "-fast") {
453 fast_mode = true;
454 continue;
455 }
456 if (arg == "-showtmp") {
457 show_tempdir = true;
458 continue;
459 }
460 if (arg == "-box" && argidx+1 < args.size()) {
461 box_file = args[++argidx];
462 continue;
463 }
464 if (arg == "-W" && argidx+1 < args.size()) {
465 wire_delay = "-W " + args[++argidx];
466 continue;
467 }
468 if (arg == "-nomfs") {
469 nomfs = true;
470 continue;
471 }
472 if (arg == "-cwd" && argidx+1 < args.size()) {
473 tempdir_name = args[++argidx];
474 continue;
475 }
476 break;
477 }
478 extra_args(args, argidx, design);
479
480 rewrite_filename(script_file);
481 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
482 script_file = std::string(pwd) + "/" + script_file;
483
484 // handle -lut / -luts args
485 if (!lut_arg.empty()) {
486 string arg = lut_arg;
487 if (arg.find_first_not_of("0123456789:") == std::string::npos) {
488 size_t pos = arg.find_first_of(':');
489 int lut_mode = 0, lut_mode2 = 0;
490 if (pos != string::npos) {
491 lut_mode = atoi(arg.substr(0, pos).c_str());
492 lut_mode2 = atoi(arg.substr(pos+1).c_str());
493 } else {
494 lut_mode = atoi(arg.c_str());
495 lut_mode2 = lut_mode;
496 }
497 lut_costs.clear();
498 for (int i = 0; i < lut_mode; i++)
499 lut_costs.push_back(1);
500 for (int i = lut_mode; i < lut_mode2; i++)
501 lut_costs.push_back(2 << (i - lut_mode));
502 }
503 else {
504 lut_file = arg;
505 rewrite_filename(lut_file);
506 if (!lut_file.empty() && !is_absolute_path(lut_file) && lut_file[0] != '+')
507 lut_file = std::string(pwd) + "/" + lut_file;
508 }
509 }
510 if (!luts_arg.empty()) {
511 lut_costs.clear();
512 for (auto &tok : split_tokens(luts_arg, ",")) {
513 auto parts = split_tokens(tok, ":");
514 if (GetSize(parts) == 0 && !lut_costs.empty())
515 lut_costs.push_back(lut_costs.back());
516 else if (GetSize(parts) == 1)
517 lut_costs.push_back(atoi(parts.at(0).c_str()));
518 else if (GetSize(parts) == 2)
519 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
520 lut_costs.push_back(atoi(parts.at(1).c_str()));
521 else
522 log_cmd_error("Invalid -luts syntax.\n");
523 }
524 }
525
526 // ABC expects a box file for XAIG
527 if (box_file.empty())
528 box_file = "+/dummy.box";
529
530 rewrite_filename(box_file);
531 if (!box_file.empty() && !is_absolute_path(box_file) && box_file[0] != '+')
532 box_file = std::string(pwd) + "/" + box_file;
533
534 if (tempdir_name.empty())
535 log_cmd_error("abc9_exe '-cwd' option is mandatory.\n");
536
537
538 abc9_module(design, script_file, exe_file, lut_costs,
539 delay_target, lutin_shared, fast_mode, show_tempdir,
540 box_file, lut_file, wire_delay, nomfs, tempdir_name);
541 }
542 } Abc9ExePass;
543
544 PRIVATE_NAMESPACE_END