Add "#ifdef __FreeBSD__"
[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
89 extern "C" int main(int, char**);
90 extern "C" void run(const char*);
91 extern "C" const char *errmsg();
92 extern "C" const char *prompt();
93
94 int main(int, char**)
95 {
96 mkdir("/work", 0777);
97 chdir("/work");
98 log_files.push_back(stdout);
99 log_error_stderr = true;
100 yosys_banner();
101 yosys_setup();
102 }
103
104 void run(const char *command)
105 {
106 int selSize = GetSize(yosys_get_design()->selection_stack);
107 try {
108 log_last_error = "Internal error (see JavaScript console for details)";
109 run_pass(command);
110 log_last_error = "";
111 } catch (...) {
112 while (GetSize(yosys_get_design()->selection_stack) > selSize)
113 yosys_get_design()->selection_stack.pop_back();
114 throw;
115 }
116 }
117
118 const char *errmsg()
119 {
120 return log_last_error.c_str();
121 }
122
123 const char *prompt()
124 {
125 const char *p = create_prompt(yosys_get_design(), 0);
126 while (*p == '\n') p++;
127 return p;
128 }
129
130 #else /* EMSCRIPTEN */
131
132 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
133 int yosys_history_offset = 0;
134 std::string yosys_history_file;
135 #endif
136
137 void yosys_atexit()
138 {
139 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
140 if (!yosys_history_file.empty()) {
141 #if defined(YOSYS_ENABLE_READLINE)
142 if (yosys_history_offset > 0) {
143 history_truncate_file(yosys_history_file.c_str(), 100);
144 append_history(where_history() - yosys_history_offset, yosys_history_file.c_str());
145 } else
146 write_history(yosys_history_file.c_str());
147 #else
148 write_history(yosys_history_file.c_str());
149 #endif
150 }
151
152 clear_history();
153 #if defined(YOSYS_ENABLE_READLINE)
154 HIST_ENTRY **hist_list = history_list();
155 if (hist_list != NULL)
156 free(hist_list);
157 #endif
158 #endif
159 }
160
161 int main(int argc, char **argv)
162 {
163 std::string frontend_command = "auto";
164 std::string backend_command = "auto";
165 std::vector<std::string> passes_commands;
166 std::vector<std::string> plugin_filenames;
167 std::string output_filename = "";
168 std::string scriptfile = "";
169 std::string depsfile = "";
170 bool scriptfile_tcl = false;
171 bool got_output_filename = false;
172 bool print_banner = true;
173 bool print_stats = true;
174 bool call_abort = false;
175 bool timing_details = false;
176 bool mode_v = false;
177 bool mode_q = false;
178
179 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
180 if (getenv("HOME") != NULL) {
181 yosys_history_file = stringf("%s/.yosys_history", getenv("HOME"));
182 read_history(yosys_history_file.c_str());
183 yosys_history_offset = where_history();
184 }
185 #endif
186
187 if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-help") || !strcmp(argv[1], "--help")))
188 {
189 printf("\n");
190 printf("Usage: %s [options] [<infile> [..]]\n", argv[0]);
191 printf("\n");
192 printf(" -Q\n");
193 printf(" suppress printing of banner (copyright, disclaimer, version)\n");
194 printf("\n");
195 printf(" -T\n");
196 printf(" suppress printing of footer (log hash, version, timing statistics)\n");
197 printf("\n");
198 printf(" -q\n");
199 printf(" quiet operation. only write warnings and error messages to console\n");
200 printf(" use this option twice to also quiet warning messages\n");
201 printf("\n");
202 printf(" -v <level>\n");
203 printf(" print log headers up to level <level> to the console. (this\n");
204 printf(" implies -q for everything except the 'End of script.' message.)\n");
205 printf("\n");
206 printf(" -t\n");
207 printf(" annotate all log messages with a time stamp\n");
208 printf("\n");
209 printf(" -d\n");
210 printf(" print more detailed timing stats at exit\n");
211 printf("\n");
212 printf(" -l logfile\n");
213 printf(" write log messages to the specified file\n");
214 printf("\n");
215 printf(" -L logfile\n");
216 printf(" like -l but open log file in line buffered mode\n");
217 printf("\n");
218 printf(" -o outfile\n");
219 printf(" write the design to the specified file on exit\n");
220 printf("\n");
221 printf(" -b backend\n");
222 printf(" use this backend for the output file specified on the command line\n");
223 printf("\n");
224 printf(" -f frontend\n");
225 printf(" use the specified frontend for the input files on the command line\n");
226 printf("\n");
227 printf(" -H\n");
228 printf(" print the command list\n");
229 printf("\n");
230 printf(" -h command\n");
231 printf(" print the help message for the specified command\n");
232 printf("\n");
233 printf(" -s scriptfile\n");
234 printf(" execute the commands in the script file\n");
235 printf("\n");
236 printf(" -c tcl_scriptfile\n");
237 printf(" execute the commands in the tcl script file (see 'help tcl' for details)\n");
238 printf("\n");
239 printf(" -p command\n");
240 printf(" execute the commands\n");
241 printf("\n");
242 printf(" -m module_file\n");
243 printf(" load the specified module (aka plugin)\n");
244 printf("\n");
245 printf(" -X\n");
246 printf(" enable tracing of core data structure changes. for debugging\n");
247 printf("\n");
248 printf(" -M\n");
249 printf(" will slightly randomize allocated pointer addresses. for debugging\n");
250 printf("\n");
251 printf(" -A\n");
252 printf(" will call abort() at the end of the script. for debugging\n");
253 printf("\n");
254 printf(" -D <header_id>[:<filename>]\n");
255 printf(" dump the design when printing the specified log header to a file.\n");
256 printf(" yosys_dump_<header_id>.il is used as filename if none is specified.\n");
257 printf(" Use 'ALL' as <header_id> to dump at every header.\n");
258 printf("\n");
259 printf(" -W regex\n");
260 printf(" print a warning for all log messages matching the regex.\n");
261 printf("\n");
262 printf(" -w regex\n");
263 printf(" if a warning message matches the regex, it is printed as regular\n");
264 printf(" message instead.\n");
265 printf("\n");
266 printf(" -e regex\n");
267 printf(" if a warning message matches the regex, it is printed as error\n");
268 printf(" message instead and the tool terminates with a nonzero return code.\n");
269 printf("\n");
270 printf(" -E <depsfile>\n");
271 printf(" write a Makefile dependencies file with in- and output file names\n");
272 printf("\n");
273 printf(" -V\n");
274 printf(" print version information and exit\n");
275 printf("\n");
276 printf("The option -S is an shortcut for calling the \"synth\" command, a default\n");
277 printf("script for transforming the Verilog input to a gate-level netlist. For example:\n");
278 printf("\n");
279 printf(" yosys -o output.blif -S input.v\n");
280 printf("\n");
281 printf("For more complex synthesis jobs it is recommended to use the read_* and write_*\n");
282 printf("commands in a script file instead of specifying input and output files on the\n");
283 printf("command line.\n");
284 printf("\n");
285 printf("When no commands, script files or input files are specified on the command\n");
286 printf("line, yosys automatically enters the interactive command mode. Use the 'help'\n");
287 printf("command to get information on the individual commands.\n");
288 printf("\n");
289 exit(0);
290 }
291
292 int opt;
293 while ((opt = getopt(argc, argv, "MXAQTVSm:f:Hh:b:o:p:l:L:qv:tds:c:W:w:e:D:E:")) != -1)
294 {
295 switch (opt)
296 {
297 case 'M':
298 memhasher_on();
299 break;
300 case 'X':
301 yosys_xtrace++;
302 break;
303 case 'A':
304 call_abort = true;
305 break;
306 case 'Q':
307 print_banner = false;
308 break;
309 case 'T':
310 print_stats = false;
311 break;
312 case 'V':
313 printf("%s\n", yosys_version_str);
314 exit(0);
315 case 'S':
316 passes_commands.push_back("synth");
317 break;
318 case 'm':
319 plugin_filenames.push_back(optarg);
320 break;
321 case 'f':
322 frontend_command = optarg;
323 break;
324 case 'H':
325 passes_commands.push_back("help");
326 break;
327 case 'h':
328 passes_commands.push_back(stringf("help %s", optarg));
329 break;
330 case 'b':
331 backend_command = optarg;
332 break;
333 case 'p':
334 passes_commands.push_back(optarg);
335 break;
336 case 'o':
337 output_filename = optarg;
338 got_output_filename = true;
339 break;
340 case 'l':
341 case 'L':
342 log_files.push_back(fopen(optarg, "wt"));
343 if (log_files.back() == NULL) {
344 fprintf(stderr, "Can't open log file `%s' for writing!\n", optarg);
345 exit(1);
346 }
347 if (opt == 'L')
348 setvbuf(log_files.back(), NULL, _IOLBF, 0);
349 break;
350 case 'q':
351 mode_q = true;
352 if (log_errfile == stderr)
353 log_quiet_warnings = true;
354 log_errfile = stderr;
355 break;
356 case 'v':
357 mode_v = true;
358 log_errfile = stderr;
359 log_verbose_level = atoi(optarg);
360 break;
361 case 't':
362 log_time = true;
363 break;
364 case 'd':
365 timing_details = true;
366 break;
367 case 's':
368 scriptfile = optarg;
369 scriptfile_tcl = false;
370 break;
371 case 'c':
372 scriptfile = optarg;
373 scriptfile_tcl = true;
374 break;
375 case 'W':
376 log_warn_regexes.push_back(std::regex(optarg,
377 std::regex_constants::nosubs |
378 std::regex_constants::optimize |
379 std::regex_constants::egrep));
380 break;
381 case 'w':
382 log_nowarn_regexes.push_back(std::regex(optarg,
383 std::regex_constants::nosubs |
384 std::regex_constants::optimize |
385 std::regex_constants::egrep));
386 break;
387 case 'e':
388 log_werror_regexes.push_back(std::regex(optarg,
389 std::regex_constants::nosubs |
390 std::regex_constants::optimize |
391 std::regex_constants::egrep));
392 break;
393 case 'D':
394 {
395 auto args = split_tokens(optarg, ":");
396 if (!args.empty() && args[0] == "ALL") {
397 if (GetSize(args) != 1) {
398 fprintf(stderr, "Invalid number of tokens in -D ALL.\n");
399 exit(1);
400 }
401 log_hdump_all = true;
402 } else {
403 if (!args.empty() && !args[0].empty() && args[0].back() == '.')
404 args[0].pop_back();
405 if (GetSize(args) == 1)
406 args.push_back("yosys_dump_" + args[0] + ".il");
407 if (GetSize(args) != 2) {
408 fprintf(stderr, "Invalid number of tokens in -D.\n");
409 exit(1);
410 }
411 log_hdump[args[0]].insert(args[1]);
412 }
413 }
414 break;
415 case 'E':
416 depsfile = optarg;
417 break;
418 default:
419 fprintf(stderr, "Run '%s -h' for help.\n", argv[0]);
420 exit(1);
421 }
422 }
423
424 if (log_errfile == NULL) {
425 log_files.push_back(stdout);
426 log_error_stderr = true;
427 }
428
429 if (print_banner)
430 yosys_banner();
431
432 if (print_stats)
433 log_hasher = new SHA1;
434
435 #if defined(__linux__)
436 // set stack size to >= 128 MB
437 {
438 struct rlimit rl;
439 const rlim_t stack_size = 128L * 1024L * 1024L;
440 if (getrlimit(RLIMIT_STACK, &rl) == 0 && rl.rlim_cur < stack_size) {
441 rl.rlim_cur = stack_size;
442 setrlimit(RLIMIT_STACK, &rl);
443 }
444 }
445 #endif
446
447 yosys_setup();
448 log_error_atexit = yosys_atexit;
449
450 for (auto &fn : plugin_filenames)
451 load_plugin(fn, {});
452
453 if (optind == argc && passes_commands.size() == 0 && scriptfile.empty()) {
454 if (!got_output_filename)
455 backend_command = "";
456 shell(yosys_design);
457 }
458
459 while (optind < argc)
460 run_frontend(argv[optind++], frontend_command, output_filename == "-" ? &backend_command : NULL);
461
462 if (!scriptfile.empty()) {
463 if (scriptfile_tcl) {
464 #ifdef YOSYS_ENABLE_TCL
465 if (Tcl_EvalFile(yosys_get_tcl_interp(), scriptfile.c_str()) != TCL_OK)
466 log_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
467 #else
468 log_error("Can't exectue TCL script: this version of yosys is not built with TCL support enabled.\n");
469 #endif
470 } else
471 run_frontend(scriptfile, "script", output_filename == "-" ? &backend_command : NULL);
472 }
473
474 for (auto it = passes_commands.begin(); it != passes_commands.end(); it++)
475 run_pass(*it);
476
477 if (!backend_command.empty())
478 run_backend(output_filename, backend_command);
479
480 if (!depsfile.empty())
481 {
482 FILE *f = fopen(depsfile.c_str(), "wt");
483 if (f == nullptr)
484 log_error("Can't open dependencies file for writing: %s\n", strerror(errno));
485 bool first = true;
486 for (auto fn : yosys_output_files) {
487 fprintf(f, "%s%s", first ? "" : " ", fn.c_str());
488 first = false;
489 }
490 fprintf(f, ":");
491 for (auto fn : yosys_input_files) {
492 if (yosys_output_files.count(fn) == 0)
493 fprintf(f, " %s", fn.c_str());
494 }
495 fprintf(f, "\n");
496 }
497
498 if (print_stats)
499 {
500 std::string hash = log_hasher->final().substr(0, 10);
501 delete log_hasher;
502 log_hasher = nullptr;
503
504 log_time = false;
505 yosys_xtrace = 0;
506 log_spacer();
507
508 if (mode_v && !mode_q)
509 log_files.push_back(stderr);
510
511 if (log_warnings_count)
512 log("Warnings: %d unique messages, %d total\n", GetSize(log_warnings), log_warnings_count);
513 #ifdef _WIN32
514 log("End of script. Logfile hash: %s\n", hash.c_str());
515 #else
516 std::string meminfo;
517 std::string stats_divider = ", ";
518 # if defined(__linux__)
519 std::ifstream statm;
520 statm.open(stringf("/proc/%lld/statm", (long long)getpid()));
521 if (statm.is_open()) {
522 int sz_total, sz_resident;
523 statm >> sz_total >> sz_resident;
524 meminfo = stringf(", MEM: %.2f MB total, %.2f MB resident",
525 sz_total * (getpagesize() / 1024.0 / 1024.0),
526 sz_resident * (getpagesize() / 1024.0 / 1024.0));
527 stats_divider = "\n";
528 }
529 # elif defined(__FreeBSD__)
530 pid_t pid = getpid();
531 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)pid};
532 struct kinfo_proc kip;
533 size_t kip_len = sizeof(kip);
534 if (sysctl(mib, 4, &kip, &kip_len, NULL, 0) == 0) {
535 vm_size_t sz_total = kip.ki_size;
536 segsz_t sz_resident = kip.ki_rssize;
537 meminfo = stringf(", MEM: %.2f MB total, %.2f MB resident",
538 (int)sz_total / 1024.0 / 1024.0,
539 (int)sz_resident * (getpagesize() / 1024.0 / 1024.0));
540 stats_divider = "\n";
541 }
542 # endif
543
544 struct rusage ru_buffer;
545 getrusage(RUSAGE_SELF, &ru_buffer);
546 log("End of script. Logfile hash: %s%sCPU: user %.2fs system %.2fs%s\n", hash.c_str(),
547 stats_divider.c_str(), ru_buffer.ru_utime.tv_sec + 1e-6 * ru_buffer.ru_utime.tv_usec,
548 ru_buffer.ru_stime.tv_sec + 1e-6 * ru_buffer.ru_stime.tv_usec, meminfo.c_str());
549 #endif
550 log("%s\n", yosys_version_str);
551
552 int64_t total_ns = 0;
553 std::set<tuple<int64_t, int, std::string>> timedat;
554
555 for (auto &it : pass_register)
556 if (it.second->call_counter) {
557 total_ns += it.second->runtime_ns + 1;
558 timedat.insert(make_tuple(it.second->runtime_ns + 1, it.second->call_counter, it.first));
559 }
560
561 if (timing_details)
562 {
563 log("Time spent:\n");
564 for (auto it = timedat.rbegin(); it != timedat.rend(); it++) {
565 log("%5d%% %5d calls %8.3f sec %s\n", int(100*std::get<0>(*it) / total_ns),
566 std::get<1>(*it), std::get<0>(*it) / 1000000000.0, std::get<2>(*it).c_str());
567 }
568 }
569 else
570 {
571 int out_count = 0;
572 log("Time spent:");
573 for (auto it = timedat.rbegin(); it != timedat.rend() && out_count < 4; it++, out_count++) {
574 if (out_count >= 2 && (std::get<0>(*it) < 1000000000 || int(100*std::get<0>(*it) / total_ns) < 20)) {
575 log(", ...");
576 break;
577 }
578 log("%s %d%% %dx %s (%d sec)", out_count ? "," : "", int(100*std::get<0>(*it) / total_ns),
579 std::get<1>(*it), std::get<2>(*it).c_str(), int(std::get<0>(*it) / 1000000000));
580 }
581 log("%s\n", out_count ? "" : " no commands executed");
582 }
583 }
584
585 #if defined(YOSYS_ENABLE_COVER) && (defined(__linux__) || defined(__FreeBSD__))
586 if (getenv("YOSYS_COVER_DIR") || getenv("YOSYS_COVER_FILE"))
587 {
588 string filename;
589 FILE *f;
590
591 if (getenv("YOSYS_COVER_DIR")) {
592 filename = stringf("%s/yosys_cover_%d_XXXXXX.txt", getenv("YOSYS_COVER_DIR"), getpid());
593 filename = make_temp_file(filename);
594 } else {
595 filename = getenv("YOSYS_COVER_FILE");
596 }
597
598 f = fopen(filename.c_str(), "a+");
599
600 if (f == NULL)
601 log_error("Can't create coverage file `%s'.\n", filename.c_str());
602
603 log("<writing coverage file \"%s\">\n", filename.c_str());
604
605 for (auto &it : get_coverage_data())
606 fprintf(f, "%-60s %10d %s\n", it.second.first.c_str(), it.second.second, it.first.c_str());
607
608 fclose(f);
609 }
610 #endif
611
612 yosys_atexit();
613
614 memhasher_off();
615 if (call_abort)
616 abort();
617
618 log_flush();
619 #if defined(_MSC_VER)
620 _exit(0);
621 #elif defined(_WIN32)
622 _Exit(0);
623 #endif
624
625 yosys_shutdown();
626
627 return 0;
628 }
629
630 #endif /* EMSCRIPTEN */
631