Add and use SigSpec::reverse()
[yosys.git] / kernel / driver.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/yosys.h"
21 #include "libs/sha1/sha1.h"
22
23 #ifdef YOSYS_ENABLE_READLINE
24 # include <readline/readline.h>
25 # include <readline/history.h>
26 #endif
27
28 #ifdef YOSYS_ENABLE_EDITLINE
29 # include <editline/readline.h>
30 #endif
31
32 #include <stdio.h>
33 #include <string.h>
34 #include <limits.h>
35 #include <errno.h>
36
37 #if defined (__linux__) || defined(__FreeBSD__)
38 # include <sys/resource.h>
39 # include <sys/types.h>
40 # include <unistd.h>
41 #endif
42
43 #ifdef __FreeBSD__
44 # include <sys/sysctl.h>
45 # include <sys/user.h>
46 #endif
47
48 #if !defined(_WIN32) || defined(__MINGW32__)
49 # include <unistd.h>
50 #else
51 char *optarg;
52 int optind = 1, optcur = 1;
53 int getopt(int argc, char **argv, const char *optstring)
54 {
55 if (optind >= argc || argv[optind][0] != '-')
56 return -1;
57
58 bool takes_arg = false;
59 int opt = argv[optind][optcur];
60 for (int i = 0; optstring[i]; i++)
61 if (opt == optstring[i] && optstring[i + 1] == ':')
62 takes_arg = true;
63
64 if (!takes_arg) {
65 if (argv[optind][++optcur] == 0)
66 optind++, optcur = 1;
67 return opt;
68 }
69
70 if (argv[optind][++optcur]) {
71 optarg = argv[optind++] + optcur;
72 optcur = 1;
73 return opt;
74 }
75
76 optarg = argv[++optind];
77 optind++, optcur = 1;
78 return opt;
79 }
80 #endif
81
82
83 USING_YOSYS_NAMESPACE
84
85 #ifdef EMSCRIPTEN
86 # include <sys/stat.h>
87 # include <sys/types.h>
88 # include <emscripten.h>
89
90 extern "C" int main(int, char**);
91 extern "C" void run(const char*);
92 extern "C" const char *errmsg();
93 extern "C" const char *prompt();
94
95 int main(int argc, char **argv)
96 {
97 EM_ASM(
98 if (ENVIRONMENT_IS_NODE)
99 {
100 FS.mkdir('/hostcwd');
101 FS.mount(NODEFS, { root: '.' }, '/hostcwd');
102 FS.mkdir('/hostfs');
103 FS.mount(NODEFS, { root: '/' }, '/hostfs');
104 }
105 );
106
107 mkdir("/work", 0777);
108 chdir("/work");
109 log_files.push_back(stdout);
110 log_error_stderr = true;
111 yosys_banner();
112 yosys_setup();
113 #ifdef WITH_PYTHON
114 PyRun_SimpleString(("sys.path.append(\""+proc_self_dirname()+"\")").c_str());
115 PyRun_SimpleString(("sys.path.append(\""+proc_share_dirname()+"plugins\")").c_str());
116 #endif
117
118 if (argc == 2)
119 {
120 // Run the first argument as a script file
121 run_frontend(argv[1], "script", 0, 0, 0);
122 }
123 }
124
125 void run(const char *command)
126 {
127 int selSize = GetSize(yosys_get_design()->selection_stack);
128 try {
129 log_last_error = "Internal error (see JavaScript console for details)";
130 run_pass(command);
131 log_last_error = "";
132 } catch (...) {
133 while (GetSize(yosys_get_design()->selection_stack) > selSize)
134 yosys_get_design()->selection_stack.pop_back();
135 throw;
136 }
137 }
138
139 const char *errmsg()
140 {
141 return log_last_error.c_str();
142 }
143
144 const char *prompt()
145 {
146 const char *p = create_prompt(yosys_get_design(), 0);
147 while (*p == '\n') p++;
148 return p;
149 }
150
151 #else /* EMSCRIPTEN */
152
153 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
154 int yosys_history_offset = 0;
155 std::string yosys_history_file;
156 #endif
157
158 void yosys_atexit()
159 {
160 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
161 if (!yosys_history_file.empty()) {
162 #if defined(YOSYS_ENABLE_READLINE)
163 if (yosys_history_offset > 0) {
164 history_truncate_file(yosys_history_file.c_str(), 100);
165 append_history(where_history() - yosys_history_offset, yosys_history_file.c_str());
166 } else
167 write_history(yosys_history_file.c_str());
168 #else
169 write_history(yosys_history_file.c_str());
170 #endif
171 }
172
173 clear_history();
174 #if defined(YOSYS_ENABLE_READLINE)
175 HIST_ENTRY **hist_list = history_list();
176 if (hist_list != NULL)
177 free(hist_list);
178 #endif
179 #endif
180 }
181
182 int main(int argc, char **argv)
183 {
184 std::string frontend_command = "auto";
185 std::string backend_command = "auto";
186 std::vector<std::string> vlog_defines;
187 std::vector<std::string> passes_commands;
188 std::vector<std::string> plugin_filenames;
189 std::string output_filename = "";
190 std::string scriptfile = "";
191 std::string depsfile = "";
192 bool scriptfile_tcl = false;
193 bool got_output_filename = false;
194 bool print_banner = true;
195 bool print_stats = true;
196 bool call_abort = false;
197 bool timing_details = false;
198 bool mode_v = false;
199 bool mode_q = false;
200
201 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
202 if (getenv("HOME") != NULL) {
203 yosys_history_file = stringf("%s/.yosys_history", getenv("HOME"));
204 read_history(yosys_history_file.c_str());
205 yosys_history_offset = where_history();
206 }
207 #endif
208
209 if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-help") || !strcmp(argv[1], "--help")))
210 {
211 printf("\n");
212 printf("Usage: %s [options] [<infile> [..]]\n", argv[0]);
213 printf("\n");
214 printf(" -Q\n");
215 printf(" suppress printing of banner (copyright, disclaimer, version)\n");
216 printf("\n");
217 printf(" -T\n");
218 printf(" suppress printing of footer (log hash, version, timing statistics)\n");
219 printf("\n");
220 printf(" -q\n");
221 printf(" quiet operation. only write warnings and error messages to console\n");
222 printf(" use this option twice to also quiet warning messages\n");
223 printf("\n");
224 printf(" -v <level>\n");
225 printf(" print log headers up to level <level> to the console. (this\n");
226 printf(" implies -q for everything except the 'End of script.' message.)\n");
227 printf("\n");
228 printf(" -t\n");
229 printf(" annotate all log messages with a time stamp\n");
230 printf("\n");
231 printf(" -d\n");
232 printf(" print more detailed timing stats at exit\n");
233 printf("\n");
234 printf(" -l logfile\n");
235 printf(" write log messages to the specified file\n");
236 printf("\n");
237 printf(" -L logfile\n");
238 printf(" like -l but open log file in line buffered mode\n");
239 printf("\n");
240 printf(" -o outfile\n");
241 printf(" write the design to the specified file on exit\n");
242 printf("\n");
243 printf(" -b backend\n");
244 printf(" use this backend for the output file specified on the command line\n");
245 printf("\n");
246 printf(" -f frontend\n");
247 printf(" use the specified frontend for the input files on the command line\n");
248 printf("\n");
249 printf(" -H\n");
250 printf(" print the command list\n");
251 printf("\n");
252 printf(" -h command\n");
253 printf(" print the help message for the specified command\n");
254 printf("\n");
255 printf(" -s scriptfile\n");
256 printf(" execute the commands in the script file\n");
257 printf("\n");
258 printf(" -c tcl_scriptfile\n");
259 printf(" execute the commands in the tcl script file (see 'help tcl' for details)\n");
260 printf("\n");
261 printf(" -p command\n");
262 printf(" execute the commands\n");
263 printf("\n");
264 printf(" -m module_file\n");
265 printf(" load the specified module (aka plugin)\n");
266 printf("\n");
267 printf(" -X\n");
268 printf(" enable tracing of core data structure changes. for debugging\n");
269 printf("\n");
270 printf(" -M\n");
271 printf(" will slightly randomize allocated pointer addresses. for debugging\n");
272 printf("\n");
273 printf(" -A\n");
274 printf(" will call abort() at the end of the script. for debugging\n");
275 printf("\n");
276 printf(" -D <macro>[=<value>]\n");
277 printf(" set the specified Verilog define (via \"read -define\")\n");
278 printf("\n");
279 printf(" -P <header_id>[:<filename>]\n");
280 printf(" dump the design when printing the specified log header to a file.\n");
281 printf(" yosys_dump_<header_id>.il is used as filename if none is specified.\n");
282 printf(" Use 'ALL' as <header_id> to dump at every header.\n");
283 printf("\n");
284 printf(" -W regex\n");
285 printf(" print a warning for all log messages matching the regex.\n");
286 printf("\n");
287 printf(" -w regex\n");
288 printf(" if a warning message matches the regex, it is printed as regular\n");
289 printf(" message instead.\n");
290 printf("\n");
291 printf(" -e regex\n");
292 printf(" if a warning message matches the regex, it is printed as error\n");
293 printf(" message instead and the tool terminates with a nonzero return code.\n");
294 printf("\n");
295 printf(" -E <depsfile>\n");
296 printf(" write a Makefile dependencies file with in- and output file names\n");
297 printf("\n");
298 printf(" -g\n");
299 printf(" globally enable debug log messages\n");
300 printf("\n");
301 printf(" -V\n");
302 printf(" print version information and exit\n");
303 printf("\n");
304 printf("The option -S is an shortcut for calling the \"synth\" command, a default\n");
305 printf("script for transforming the Verilog input to a gate-level netlist. For example:\n");
306 printf("\n");
307 printf(" yosys -o output.blif -S input.v\n");
308 printf("\n");
309 printf("For more complex synthesis jobs it is recommended to use the read_* and write_*\n");
310 printf("commands in a script file instead of specifying input and output files on the\n");
311 printf("command line.\n");
312 printf("\n");
313 printf("When no commands, script files or input files are specified on the command\n");
314 printf("line, yosys automatically enters the interactive command mode. Use the 'help'\n");
315 printf("command to get information on the individual commands.\n");
316 printf("\n");
317 exit(0);
318 }
319
320 if (argc == 2 && (!strcmp(argv[1], "-V") || !strcmp(argv[1], "-version") || !strcmp(argv[1], "--version")))
321 {
322 printf("%s\n", yosys_version_str);
323 exit(0);
324 }
325
326 int opt;
327 while ((opt = getopt(argc, argv, "MXAQTVSgm:f:Hh:b:o:p:l:L:qv:tds:c:W:w:e:D:P:E:")) != -1)
328 {
329 switch (opt)
330 {
331 case 'M':
332 memhasher_on();
333 break;
334 case 'X':
335 yosys_xtrace++;
336 break;
337 case 'A':
338 call_abort = true;
339 break;
340 case 'Q':
341 print_banner = false;
342 break;
343 case 'T':
344 print_stats = false;
345 break;
346 case 'V':
347 printf("%s\n", yosys_version_str);
348 exit(0);
349 case 'S':
350 passes_commands.push_back("synth");
351 break;
352 case 'g':
353 log_force_debug++;
354 break;
355 case 'm':
356 plugin_filenames.push_back(optarg);
357 break;
358 case 'f':
359 frontend_command = optarg;
360 break;
361 case 'H':
362 passes_commands.push_back("help");
363 break;
364 case 'h':
365 passes_commands.push_back(stringf("help %s", optarg));
366 break;
367 case 'b':
368 backend_command = optarg;
369 break;
370 case 'p':
371 passes_commands.push_back(optarg);
372 break;
373 case 'o':
374 output_filename = optarg;
375 got_output_filename = true;
376 break;
377 case 'l':
378 case 'L':
379 log_files.push_back(fopen(optarg, "wt"));
380 if (log_files.back() == NULL) {
381 fprintf(stderr, "Can't open log file `%s' for writing!\n", optarg);
382 exit(1);
383 }
384 if (opt == 'L')
385 setvbuf(log_files.back(), NULL, _IOLBF, 0);
386 break;
387 case 'q':
388 mode_q = true;
389 if (log_errfile == stderr)
390 log_quiet_warnings = true;
391 log_errfile = stderr;
392 break;
393 case 'v':
394 mode_v = true;
395 log_errfile = stderr;
396 log_verbose_level = atoi(optarg);
397 break;
398 case 't':
399 log_time = true;
400 break;
401 case 'd':
402 timing_details = true;
403 break;
404 case 's':
405 scriptfile = optarg;
406 scriptfile_tcl = false;
407 break;
408 case 'c':
409 scriptfile = optarg;
410 scriptfile_tcl = true;
411 break;
412 case 'W':
413 log_warn_regexes.push_back(std::regex(optarg,
414 std::regex_constants::nosubs |
415 std::regex_constants::optimize |
416 std::regex_constants::egrep));
417 break;
418 case 'w':
419 log_nowarn_regexes.push_back(std::regex(optarg,
420 std::regex_constants::nosubs |
421 std::regex_constants::optimize |
422 std::regex_constants::egrep));
423 break;
424 case 'e':
425 log_werror_regexes.push_back(std::regex(optarg,
426 std::regex_constants::nosubs |
427 std::regex_constants::optimize |
428 std::regex_constants::egrep));
429 break;
430 case 'D':
431 vlog_defines.push_back(optarg);
432 break;
433 case 'P':
434 {
435 auto args = split_tokens(optarg, ":");
436 if (!args.empty() && args[0] == "ALL") {
437 if (GetSize(args) != 1) {
438 fprintf(stderr, "Invalid number of tokens in -D ALL.\n");
439 exit(1);
440 }
441 log_hdump_all = true;
442 } else {
443 if (!args.empty() && !args[0].empty() && args[0].back() == '.')
444 args[0].pop_back();
445 if (GetSize(args) == 1)
446 args.push_back("yosys_dump_" + args[0] + ".il");
447 if (GetSize(args) != 2) {
448 fprintf(stderr, "Invalid number of tokens in -D.\n");
449 exit(1);
450 }
451 log_hdump[args[0]].insert(args[1]);
452 }
453 }
454 break;
455 case 'E':
456 depsfile = optarg;
457 break;
458 default:
459 fprintf(stderr, "Run '%s -h' for help.\n", argv[0]);
460 exit(1);
461 }
462 }
463
464 if (log_errfile == NULL) {
465 log_files.push_back(stdout);
466 log_error_stderr = true;
467 }
468
469 if (print_banner)
470 yosys_banner();
471
472 if (print_stats)
473 log_hasher = new SHA1;
474
475 #if defined(__linux__)
476 // set stack size to >= 128 MB
477 {
478 struct rlimit rl;
479 const rlim_t stack_size = 128L * 1024L * 1024L;
480 if (getrlimit(RLIMIT_STACK, &rl) == 0 && rl.rlim_cur < stack_size) {
481 rl.rlim_cur = stack_size;
482 setrlimit(RLIMIT_STACK, &rl);
483 }
484 }
485 #endif
486
487 yosys_setup();
488 #ifdef WITH_PYTHON
489 PyRun_SimpleString(("sys.path.append(\""+proc_self_dirname()+"\")").c_str());
490 PyRun_SimpleString(("sys.path.append(\""+proc_share_dirname()+"plugins\")").c_str());
491 #endif
492 log_error_atexit = yosys_atexit;
493
494 for (auto &fn : plugin_filenames)
495 load_plugin(fn, {});
496
497 if (optind == argc && passes_commands.size() == 0 && scriptfile.empty()) {
498 if (!got_output_filename)
499 backend_command = "";
500 shell(yosys_design);
501 }
502
503 if (!vlog_defines.empty()) {
504 std::string vdef_cmd = "read -define";
505 for (auto vdef : vlog_defines)
506 vdef_cmd += " " + vdef;
507 run_pass(vdef_cmd);
508 }
509
510 while (optind < argc)
511 run_frontend(argv[optind++], frontend_command, output_filename == "-" ? &backend_command : NULL);
512
513 if (!scriptfile.empty()) {
514 if (scriptfile_tcl) {
515 #ifdef YOSYS_ENABLE_TCL
516 if (Tcl_EvalFile(yosys_get_tcl_interp(), scriptfile.c_str()) != TCL_OK)
517 log_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
518 #else
519 log_error("Can't exectue TCL script: this version of yosys is not built with TCL support enabled.\n");
520 #endif
521 } else
522 run_frontend(scriptfile, "script", output_filename == "-" ? &backend_command : NULL);
523 }
524
525 for (auto it = passes_commands.begin(); it != passes_commands.end(); it++)
526 run_pass(*it);
527
528 if (!backend_command.empty())
529 run_backend(output_filename, backend_command);
530
531 yosys_design->check();
532 for (auto it : saved_designs)
533 it.second->check();
534 for (auto it : pushed_designs)
535 it->check();
536
537 if (!depsfile.empty())
538 {
539 FILE *f = fopen(depsfile.c_str(), "wt");
540 if (f == nullptr)
541 log_error("Can't open dependencies file for writing: %s\n", strerror(errno));
542 bool first = true;
543 for (auto fn : yosys_output_files) {
544 fprintf(f, "%s%s", first ? "" : " ", escape_filename_spaces(fn).c_str());
545 first = false;
546 }
547 fprintf(f, ":");
548 for (auto fn : yosys_input_files) {
549 if (yosys_output_files.count(fn) == 0)
550 fprintf(f, " %s", escape_filename_spaces(fn).c_str());
551 }
552 fprintf(f, "\n");
553 }
554
555 if (print_stats)
556 {
557 std::string hash = log_hasher->final().substr(0, 10);
558 delete log_hasher;
559 log_hasher = nullptr;
560
561 log_time = false;
562 yosys_xtrace = 0;
563 log_spacer();
564
565 if (mode_v && !mode_q)
566 log_files.push_back(stderr);
567
568 if (log_warnings_count)
569 log("Warnings: %d unique messages, %d total\n", GetSize(log_warnings), log_warnings_count);
570 #ifdef _WIN32
571 log("End of script. Logfile hash: %s\n", hash.c_str());
572 #else
573 std::string meminfo;
574 std::string stats_divider = ", ";
575
576 struct rusage ru_buffer;
577 getrusage(RUSAGE_SELF, &ru_buffer);
578 if (yosys_design->scratchpad_get_bool("print_stats.include_children")) {
579 struct rusage ru_buffer_children;
580 getrusage(RUSAGE_CHILDREN, &ru_buffer_children);
581 ru_buffer.ru_utime.tv_sec += ru_buffer_children.ru_utime.tv_sec;
582 ru_buffer.ru_utime.tv_usec += ru_buffer_children.ru_utime.tv_usec;
583 ru_buffer.ru_stime.tv_sec += ru_buffer_children.ru_stime.tv_sec;
584 ru_buffer.ru_stime.tv_usec += ru_buffer_children.ru_stime.tv_usec;
585 ru_buffer.ru_maxrss = std::max(ru_buffer.ru_maxrss, ru_buffer_children.ru_maxrss);
586 }
587 # if defined(__linux__) || defined(__FreeBSD__)
588 meminfo = stringf(", MEM: %.2f MB peak",
589 ru_buffer.ru_maxrss / 1024.0);
590 #endif
591 log("End of script. Logfile hash: %s%sCPU: user %.2fs system %.2fs%s\n", hash.c_str(),
592 stats_divider.c_str(), ru_buffer.ru_utime.tv_sec + 1e-6 * ru_buffer.ru_utime.tv_usec,
593 ru_buffer.ru_stime.tv_sec + 1e-6 * ru_buffer.ru_stime.tv_usec, meminfo.c_str());
594 #endif
595 log("%s\n", yosys_version_str);
596
597 int64_t total_ns = 0;
598 std::set<tuple<int64_t, int, std::string>> timedat;
599
600 for (auto &it : pass_register)
601 if (it.second->call_counter) {
602 total_ns += it.second->runtime_ns + 1;
603 timedat.insert(make_tuple(it.second->runtime_ns + 1, it.second->call_counter, it.first));
604 }
605
606 if (timing_details)
607 {
608 log("Time spent:\n");
609 for (auto it = timedat.rbegin(); it != timedat.rend(); it++) {
610 log("%5d%% %5d calls %8.3f sec %s\n", int(100*std::get<0>(*it) / total_ns),
611 std::get<1>(*it), std::get<0>(*it) / 1000000000.0, std::get<2>(*it).c_str());
612 }
613 }
614 else
615 {
616 int out_count = 0;
617 log("Time spent:");
618 for (auto it = timedat.rbegin(); it != timedat.rend() && out_count < 4; it++, out_count++) {
619 if (out_count >= 2 && (std::get<0>(*it) < 1000000000 || int(100*std::get<0>(*it) / total_ns) < 20)) {
620 log(", ...");
621 break;
622 }
623 log("%s %d%% %dx %s (%d sec)", out_count ? "," : "", int(100*std::get<0>(*it) / total_ns),
624 std::get<1>(*it), std::get<2>(*it).c_str(), int(std::get<0>(*it) / 1000000000));
625 }
626 log("%s\n", out_count ? "" : " no commands executed");
627 }
628 }
629
630 #if defined(YOSYS_ENABLE_COVER) && (defined(__linux__) || defined(__FreeBSD__))
631 if (getenv("YOSYS_COVER_DIR") || getenv("YOSYS_COVER_FILE"))
632 {
633 string filename;
634 FILE *f;
635
636 if (getenv("YOSYS_COVER_DIR")) {
637 filename = stringf("%s/yosys_cover_%d_XXXXXX.txt", getenv("YOSYS_COVER_DIR"), getpid());
638 filename = make_temp_file(filename);
639 } else {
640 filename = getenv("YOSYS_COVER_FILE");
641 }
642
643 f = fopen(filename.c_str(), "a+");
644
645 if (f == NULL)
646 log_error("Can't create coverage file `%s'.\n", filename.c_str());
647
648 log("<writing coverage file \"%s\">\n", filename.c_str());
649
650 for (auto &it : get_coverage_data())
651 fprintf(f, "%-60s %10d %s\n", it.second.first.c_str(), it.second.second, it.first.c_str());
652
653 fclose(f);
654 }
655 #endif
656
657 yosys_atexit();
658
659 memhasher_off();
660 if (call_abort)
661 abort();
662
663 log_flush();
664 #if defined(_MSC_VER)
665 _exit(0);
666 #elif defined(_WIN32)
667 _Exit(0);
668 #endif
669
670 yosys_shutdown();
671
672 return 0;
673 }
674
675 #endif /* EMSCRIPTEN */
676