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