Added emscripten (emcc) support to build system and some build fixes
[yosys.git] / kernel / yosys.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
22 #ifdef YOSYS_ENABLE_READLINE
23 # include <readline/readline.h>
24 # include <readline/history.h>
25 #endif
26
27 #include <dlfcn.h>
28 #include <unistd.h>
29 #include <limits.h>
30 #include <errno.h>
31
32 YOSYS_NAMESPACE_BEGIN
33
34 int autoidx = 1;
35 RTLIL::Design *yosys_design = NULL;
36
37 #ifdef YOSYS_ENABLE_TCL
38 Tcl_Interp *yosys_tcl_interp = NULL;
39 #endif
40
41 std::string stringf(const char *fmt, ...)
42 {
43 std::string string;
44 va_list ap;
45
46 va_start(ap, fmt);
47 string = vstringf(fmt, ap);
48 va_end(ap);
49
50 return string;
51 }
52
53 std::string vstringf(const char *fmt, va_list ap)
54 {
55 std::string string;
56 char *str = NULL;
57
58 if (vasprintf(&str, fmt, ap) < 0)
59 str = NULL;
60
61 if (str != NULL) {
62 string = str;
63 free(str);
64 }
65
66 return string;
67 }
68
69 int SIZE(RTLIL::Wire *wire)
70 {
71 return wire->width;
72 }
73
74 void yosys_setup()
75 {
76 Pass::init_register();
77
78 yosys_design = new RTLIL::Design;
79 yosys_design->selection_stack.push_back(RTLIL::Selection());
80 log_push();
81 }
82
83 void yosys_shutdown()
84 {
85 log_pop();
86
87 delete yosys_design;
88 yosys_design = NULL;
89
90 for (auto f : log_files)
91 if (f != stderr)
92 fclose(f);
93 log_errfile = NULL;
94 log_files.clear();
95
96 Pass::done_register();
97
98 #ifdef YOSYS_ENABLE_TCL
99 if (yosys_tcl_interp != NULL) {
100 Tcl_DeleteInterp(yosys_tcl_interp);
101 Tcl_Finalize();
102 yosys_tcl_interp = NULL;
103 }
104 #endif
105
106 for (auto &it : loaded_plugins)
107 dlclose(it.second);
108
109 loaded_plugins.clear();
110 loaded_plugin_aliases.clear();
111 }
112
113 RTLIL::IdString new_id(std::string file, int line, std::string func)
114 {
115 std::string str = "$auto$";
116 size_t pos = file.find_last_of('/');
117 str += pos != std::string::npos ? file.substr(pos+1) : file;
118 str += stringf(":%d:%s$%d", line, func.c_str(), autoidx++);
119 return str;
120 }
121
122 RTLIL::Design *yosys_get_design()
123 {
124 return yosys_design;
125 }
126
127 const char *create_prompt(RTLIL::Design *design, int recursion_counter)
128 {
129 static char buffer[100];
130 std::string str = "\n";
131 if (recursion_counter > 1)
132 str += stringf("(%d) ", recursion_counter);
133 str += "yosys";
134 if (!design->selected_active_module.empty())
135 str += stringf(" [%s]", RTLIL::unescape_id(design->selected_active_module).c_str());
136 if (!design->selection_stack.empty() && !design->selection_stack.back().full_selection) {
137 if (design->selected_active_module.empty())
138 str += "*";
139 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
140 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
141 str += "*";
142 }
143 snprintf(buffer, 100, "%s> ", str.c_str());
144 return buffer;
145 }
146
147 #ifdef YOSYS_ENABLE_TCL
148 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
149 {
150 std::vector<std::string> args;
151 for (int i = 1; i < argc; i++)
152 args.push_back(argv[i]);
153
154 if (args.size() >= 1 && args[0] == "-import") {
155 for (auto &it : pass_register) {
156 std::string tcl_command_name = it.first;
157 if (tcl_command_name == "proc")
158 tcl_command_name = "procs";
159 Tcl_CmdInfo info;
160 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
161 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
162 } else {
163 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
164 Tcl_Eval(interp, tcl_script.c_str());
165 }
166 }
167 return TCL_OK;
168 }
169
170 if (args.size() == 1) {
171 Pass::call(yosys_get_design(), args[0]);
172 return TCL_OK;
173 }
174
175 Pass::call(yosys_get_design(), args);
176 return TCL_OK;
177 }
178
179 extern Tcl_Interp *yosys_get_tcl_interp()
180 {
181 if (yosys_tcl_interp == NULL) {
182 yosys_tcl_interp = Tcl_CreateInterp();
183 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
184 }
185 return yosys_tcl_interp;
186 }
187
188 struct TclPass : public Pass {
189 TclPass() : Pass("tcl", "execute a TCL script file") { }
190 virtual void help() {
191 log("\n");
192 log(" tcl <filename>\n");
193 log("\n");
194 log("This command executes the tcl commands in the specified file.\n");
195 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
196 log("\n");
197 log("The tcl command 'yosys -import' can be used to import all yosys\n");
198 log("commands directly as tcl commands to the tcl shell. The yosys\n");
199 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
200 log("to avoid a name collision with the tcl builting command 'proc'.\n");
201 log("\n");
202 }
203 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
204 if (args.size() < 2)
205 log_cmd_error("Missing script file.\n");
206 if (args.size() > 2)
207 extra_args(args, 1, design, false);
208 if (Tcl_EvalFile(yosys_get_tcl_interp(), args[1].c_str()) != TCL_OK)
209 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
210 }
211 } TclPass;
212 #endif
213
214 #if defined(__linux__)
215 std::string proc_self_dirname ()
216 {
217 char path [PATH_MAX];
218 ssize_t buflen = readlink("/proc/self/exe", path, sizeof(path));
219 if (buflen < 0) {
220 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno));
221 }
222 while (buflen > 0 && path[buflen-1] != '/')
223 buflen--;
224 return std::string(path, buflen);
225 }
226 #elif defined(__APPLE__)
227 #include <mach-o/dyld.h>
228 std::string proc_self_dirname ()
229 {
230 char * path = NULL;
231 uint32_t buflen = 0;
232 while (_NSGetExecutablePath(path, &buflen) != 0)
233 path = (char *) realloc((void *) path, buflen);
234 while (buflen > 0 && path[buflen-1] != '/')
235 buflen--;
236 return std::string(path, buflen);
237 }
238 #elif defined(EMSCRIPTEN)
239 std::string proc_self_dirname ()
240 {
241 return "/";
242 }
243 #else
244 #error Dont know how to determine process executable base path!
245 #endif
246
247 std::string proc_share_dirname ()
248 {
249 std::string proc_self_path = proc_self_dirname();
250 std::string proc_share_path = proc_self_path + "share/";
251 if (access(proc_share_path.c_str(), X_OK) == 0)
252 return proc_share_path;
253 proc_share_path = proc_self_path + "../share/yosys/";
254 if (access(proc_share_path.c_str(), X_OK) == 0)
255 return proc_share_path;
256 log_error("proc_share_dirname: unable to determine share/ directory!\n");
257 }
258
259 bool fgetline(FILE *f, std::string &buffer)
260 {
261 buffer = "";
262 char block[4096];
263 while (1) {
264 if (fgets(block, 4096, f) == NULL)
265 return false;
266 buffer += block;
267 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r')) {
268 while (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
269 buffer.resize(buffer.size()-1);
270 return true;
271 }
272 }
273 }
274
275 static void handle_label(std::string &command, bool &from_to_active, const std::string &run_from, const std::string &run_to)
276 {
277 int pos = 0;
278 std::string label;
279
280 while (pos < SIZE(command) && (command[pos] == ' ' || command[pos] == '\t'))
281 pos++;
282
283 while (pos < SIZE(command) && command[pos] != ' ' && command[pos] != '\t' && command[pos] != '\r' && command[pos] != '\n')
284 label += command[pos++];
285
286 if (label.back() == ':' && SIZE(label) > 1)
287 {
288 label = label.substr(0, SIZE(label)-1);
289 command = command.substr(pos);
290
291 if (label == run_from)
292 from_to_active = true;
293 else if (label == run_to || (run_from == run_to && !run_from.empty()))
294 from_to_active = false;
295 }
296 }
297
298 void run_frontend(std::string filename, std::string command, RTLIL::Design *design, std::string *backend_command, std::string *from_to_label)
299 {
300 if (command == "auto") {
301 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
302 command = "verilog";
303 else if (filename.size() > 2 && filename.substr(filename.size()-3) == ".sv")
304 command = "verilog -sv";
305 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
306 command = "ilang";
307 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
308 command = "script";
309 else if (filename == "-")
310 command = "script";
311 else
312 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
313 }
314
315 if (command == "script")
316 {
317 std::string run_from, run_to;
318 bool from_to_active = true;
319
320 if (from_to_label != NULL) {
321 size_t pos = from_to_label->find(':');
322 if (pos == std::string::npos) {
323 run_from = *from_to_label;
324 run_to = *from_to_label;
325 } else {
326 run_from = from_to_label->substr(0, pos);
327 run_to = from_to_label->substr(pos+1);
328 }
329 from_to_active = run_from.empty();
330 }
331
332 log("\n-- Executing script file `%s' --\n", filename.c_str());
333
334 FILE *f = stdin;
335
336 if (filename != "-")
337 f = fopen(filename.c_str(), "r");
338
339 if (f == NULL)
340 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
341
342 FILE *backup_script_file = Frontend::current_script_file;
343 Frontend::current_script_file = f;
344
345 try {
346 std::string command;
347 while (fgetline(f, command)) {
348 while (!command.empty() && command[command.size()-1] == '\\') {
349 std::string next_line;
350 if (!fgetline(f, next_line))
351 break;
352 command.resize(command.size()-1);
353 command += next_line;
354 }
355 handle_label(command, from_to_active, run_from, run_to);
356 if (from_to_active)
357 Pass::call(design, command);
358 }
359
360 if (!command.empty()) {
361 handle_label(command, from_to_active, run_from, run_to);
362 if (from_to_active)
363 Pass::call(design, command);
364 }
365 }
366 catch (log_cmd_error_expection) {
367 Frontend::current_script_file = backup_script_file;
368 throw log_cmd_error_expection();
369 }
370
371 Frontend::current_script_file = backup_script_file;
372
373 if (filename != "-")
374 fclose(f);
375
376 if (backend_command != NULL && *backend_command == "auto")
377 *backend_command = "";
378
379 return;
380 }
381
382 if (filename == "-") {
383 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
384 } else {
385 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
386 }
387
388 Frontend::frontend_call(design, NULL, filename, command);
389 }
390
391 void run_pass(std::string command, RTLIL::Design *design)
392 {
393 log("\n-- Running pass `%s' --\n", command.c_str());
394
395 Pass::call(design, command);
396 }
397
398 void run_backend(std::string filename, std::string command, RTLIL::Design *design)
399 {
400 if (command == "auto") {
401 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
402 command = "verilog";
403 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
404 command = "ilang";
405 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".blif")
406 command = "blif";
407 else if (filename == "-")
408 command = "ilang";
409 else if (filename.empty())
410 return;
411 else
412 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename.c_str());
413 }
414
415 if (filename.empty())
416 filename = "-";
417
418 if (filename == "-") {
419 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
420 } else {
421 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
422 }
423
424 Backend::backend_call(design, NULL, filename, command);
425 }
426
427 #ifdef YOSYS_ENABLE_READLINE
428 static char *readline_cmd_generator(const char *text, int state)
429 {
430 static std::map<std::string, Pass*>::iterator it;
431 static int len;
432
433 if (!state) {
434 it = pass_register.begin();
435 len = strlen(text);
436 }
437
438 for (; it != pass_register.end(); it++) {
439 if (it->first.substr(0, len) == text)
440 return strdup((it++)->first.c_str());
441 }
442 return NULL;
443 }
444
445 static char *readline_obj_generator(const char *text, int state)
446 {
447 static std::vector<char*> obj_names;
448 static size_t idx;
449
450 if (!state)
451 {
452 idx = 0;
453 obj_names.clear();
454
455 RTLIL::Design *design = yosys_get_design();
456 int len = strlen(text);
457
458 if (design->selected_active_module.empty())
459 {
460 for (auto &it : design->modules_)
461 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
462 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
463 }
464 else
465 if (design->modules_.count(design->selected_active_module) > 0)
466 {
467 RTLIL::Module *module = design->modules_.at(design->selected_active_module);
468
469 for (auto &it : module->wires_)
470 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
471 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
472
473 for (auto &it : module->memories)
474 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
475 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
476
477 for (auto &it : module->cells_)
478 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
479 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
480
481 for (auto &it : module->processes)
482 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
483 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
484 }
485
486 std::sort(obj_names.begin(), obj_names.end());
487 }
488
489 if (idx < obj_names.size())
490 return strdup(obj_names[idx++]);
491
492 idx = 0;
493 obj_names.clear();
494 return NULL;
495 }
496
497 static char **readline_completion(const char *text, int start, int)
498 {
499 if (start == 0)
500 return rl_completion_matches(text, readline_cmd_generator);
501 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
502 return rl_completion_matches(text, readline_obj_generator);
503 return NULL;
504 }
505 #endif
506
507 void shell(RTLIL::Design *design)
508 {
509 static int recursion_counter = 0;
510
511 recursion_counter++;
512 log_cmd_error_throw = true;
513
514 #ifdef YOSYS_ENABLE_READLINE
515 rl_readline_name = "yosys";
516 rl_attempted_completion_function = readline_completion;
517 rl_basic_word_break_characters = " \t\n";
518 #endif
519
520 char *command = NULL;
521 #ifdef YOSYS_ENABLE_READLINE
522 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
523 #else
524 char command_buffer[4096];
525 while ((command = fgets(command_buffer, 4096, stdin)) != NULL)
526 #endif
527 {
528 if (command[strspn(command, " \t\r\n")] == 0)
529 continue;
530 #ifdef YOSYS_ENABLE_READLINE
531 add_history(command);
532 #endif
533
534 char *p = command + strspn(command, " \t\r\n");
535 if (!strncmp(p, "exit", 4)) {
536 p += 4;
537 p += strspn(p, " \t\r\n");
538 if (*p == 0)
539 break;
540 }
541
542 try {
543 log_assert(design->selection_stack.size() == 1);
544 Pass::call(design, command);
545 } catch (log_cmd_error_expection) {
546 while (design->selection_stack.size() > 1)
547 design->selection_stack.pop_back();
548 log_reset_stack();
549 }
550 }
551 if (command == NULL)
552 printf("exit\n");
553
554 recursion_counter--;
555 log_cmd_error_throw = false;
556 }
557
558 struct ShellPass : public Pass {
559 ShellPass() : Pass("shell", "enter interactive command mode") { }
560 virtual void help() {
561 log("\n");
562 log(" shell\n");
563 log("\n");
564 log("This command enters the interactive command mode. This can be useful\n");
565 log("in a script to interrupt the script at a certain point and allow for\n");
566 log("interactive inspection or manual synthesis of the design at this point.\n");
567 log("\n");
568 log("The command prompt of the interactive shell indicates the current\n");
569 log("selection (see 'help select'):\n");
570 log("\n");
571 log(" yosys>\n");
572 log(" the entire design is selected\n");
573 log("\n");
574 log(" yosys*>\n");
575 log(" only part of the design is selected\n");
576 log("\n");
577 log(" yosys [modname]>\n");
578 log(" the entire module 'modname' is selected using 'select -module modname'\n");
579 log("\n");
580 log(" yosys [modname]*>\n");
581 log(" only part of current module 'modname' is selected\n");
582 log("\n");
583 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
584 log("do not terminate yosys but return to the command prompt.\n");
585 log("\n");
586 log("This command is the default action if nothing else has been specified\n");
587 log("on the command line.\n");
588 log("\n");
589 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
590 log("\n");
591 }
592 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
593 extra_args(args, 1, design, false);
594 shell(design);
595 }
596 } ShellPass;
597
598 #ifdef YOSYS_ENABLE_READLINE
599 struct HistoryPass : public Pass {
600 HistoryPass() : Pass("history", "show last interactive commands") { }
601 virtual void help() {
602 log("\n");
603 log(" history\n");
604 log("\n");
605 log("This command prints all commands in the shell history buffer. This are\n");
606 log("all commands executed in an interactive session, but not the commands\n");
607 log("from executed scripts.\n");
608 log("\n");
609 }
610 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
611 extra_args(args, 1, design, false);
612 for(HIST_ENTRY **list = history_list(); *list != NULL; list++)
613 log("%s\n", (*list)->line);
614 }
615 } HistoryPass;
616 #endif
617
618 struct ScriptPass : public Pass {
619 ScriptPass() : Pass("script", "execute commands from script file") { }
620 virtual void help() {
621 log("\n");
622 log(" script <filename> [<from_label>:<to_label>]\n");
623 log("\n");
624 log("This command executes the yosys commands in the specified file.\n");
625 log("\n");
626 log("The 2nd argument can be used to only execute the section of the\n");
627 log("file between the specified labels. An empty from label is synonymous\n");
628 log("for the beginning of the file and an empty to label is synonymous\n");
629 log("for the end of the file.\n");
630 log("\n");
631 log("If only one label is specified (without ':') then only the block\n");
632 log("marked with that label (until the next label) is executed.\n");
633 log("\n");
634 }
635 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
636 if (args.size() < 2)
637 log_cmd_error("Missing script file.\n");
638 else if (args.size() == 2)
639 run_frontend(args[1], "script", design, NULL, NULL);
640 else if (args.size() == 3)
641 run_frontend(args[1], "script", design, NULL, &args[2]);
642 else
643 extra_args(args, 2, design, false);
644 }
645 } ScriptPass;
646
647 YOSYS_NAMESPACE_END
648