c24b293fca968819bd5d91f95fb059e1ebd323d1
[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 <stdio.h>
21 #include <readline/readline.h>
22 #include <readline/history.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <libgen.h>
26 #include <dlfcn.h>
27
28 #include "kernel/rtlil.h"
29 #include "kernel/register.h"
30 #include "kernel/log.h"
31
32 bool fgetline(FILE *f, std::string &buffer)
33 {
34 buffer = "";
35 char block[4096];
36 while (1) {
37 if (fgets(block, 4096, f) == NULL)
38 return false;
39 buffer += block;
40 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
41 return true;
42 }
43 }
44
45 static void run_frontend(std::string filename, std::string command, RTLIL::Design *design, std::string *backend_command)
46 {
47 if (command == "auto") {
48 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
49 command = "verilog";
50 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
51 command = "ilang";
52 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
53 command = "script";
54 else if (filename == "-")
55 command = "script";
56 else
57 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
58 }
59
60 if (command == "script") {
61 log("\n-- Executing script file `%s' --\n", filename.c_str());
62 FILE *f = stdin;
63 if (filename != "-")
64 f = fopen(filename.c_str(), "r");
65 if (f == NULL)
66 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
67 std::string command;
68 while (fgetline(f, command)) {
69 Pass::call(design, command);
70 design->check();
71 }
72 if (!command.empty()) {
73 Pass::call(design, command);
74 design->check();
75 }
76 if (filename != "-")
77 fclose(f);
78 if (backend_command != NULL && *backend_command == "auto")
79 *backend_command = "";
80 return;
81 }
82
83 if (filename == "-") {
84 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
85 } else {
86 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
87 }
88
89 Frontend::frontend_call(design, NULL, filename, command);
90 design->check();
91 }
92
93 static void run_pass(std::string command, RTLIL::Design *design)
94 {
95 log("\n-- Running pass `%s' --\n", command.c_str());
96
97 Pass::call(design, command);
98 design->check();
99 }
100
101 static void run_backend(std::string filename, std::string command, RTLIL::Design *design)
102 {
103 if (command == "auto") {
104 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
105 command = "verilog";
106 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
107 command = "ilang";
108 else if (filename == "-")
109 command = "ilang";
110 else if (filename.empty())
111 return;
112 else
113 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
114 }
115
116 if (filename.empty())
117 filename = "-";
118
119 if (filename == "-") {
120 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
121 } else {
122 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
123 }
124
125 Backend::backend_call(design, NULL, filename, command);
126 design->check();
127 }
128
129 static char *readline_cmd_generator(const char *text, int state)
130 {
131 static std::map<std::string, Pass*>::iterator it;
132 static int len;
133
134 if (!state) {
135 it = REGISTER_INTERN::pass_register.begin();
136 len = strlen(text);
137 }
138
139 for (; it != REGISTER_INTERN::pass_register.end(); it++) {
140 if (it->first.substr(0, len) == text)
141 return strdup((it++)->first.c_str());
142 }
143 return NULL;
144 }
145
146 static char **readline_completion(const char *text, int start, int)
147 {
148 if (start == 0)
149 return rl_completion_matches(text, readline_cmd_generator);
150 return NULL;
151 }
152
153 static const char *create_prompt(RTLIL::Design *design, int recursion_counter)
154 {
155 static char buffer[100];
156 std::string str = "\n";
157 if (recursion_counter > 1)
158 str += stringf("(%d) ", recursion_counter);
159 str += "yosys";
160 if (!design->selected_active_module.empty())
161 str += stringf(" [%s]", design->selected_active_module.c_str());
162 if (!design->selection_stack.back().full_selection) {
163 if (design->selected_active_module.empty())
164 str += "*";
165 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
166 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
167 str += "*";
168 }
169 snprintf(buffer, 100, "%s> ", str.c_str());
170 return buffer;
171 }
172
173 static void shell(RTLIL::Design *design)
174 {
175 static int recursion_counter = 0;
176
177 recursion_counter++;
178 log_cmd_error_throw = true;
179
180 rl_readline_name = "yosys";
181 rl_attempted_completion_function = readline_completion;
182
183 char *command = NULL;
184 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
185 {
186 if (command[strspn(command, " \t\r\n")] == 0)
187 continue;
188 add_history(command);
189
190 char *p = command + strspn(command, " \t\r\n");
191 if (!strncmp(p, "exit", 4)) {
192 p += 4;
193 p += strspn(p, " \t\r\n");
194 if (*p == 0)
195 break;
196 }
197
198 try {
199 assert(design->selection_stack.size() == 1);
200 Pass::call(design, command);
201 } catch (int) {
202 while (design->selection_stack.size() > 1)
203 design->selection_stack.pop_back();
204 log_reset_stack();
205 }
206 }
207 if (command == NULL)
208 printf("exit\n");
209
210 recursion_counter--;
211 log_cmd_error_throw = false;
212 }
213
214 struct ShellPass : public Pass {
215 ShellPass() : Pass("shell", "enter interactive command mode") { }
216 virtual void help() {
217 log("\n");
218 log(" shell\n");
219 log("\n");
220 log("This command enters the interactive command mode. This can be useful\n");
221 log("in a script to interrupt the script at a certain point and allow for\n");
222 log("interactive inspection or manual synthesis of the design at this point.\n");
223 log("\n");
224 log("The command prompt of the interactive shell indicates the current\n");
225 log("selection (see 'help select'):\n");
226 log("\n");
227 log(" yosys>\n");
228 log(" the entire design is selected\n");
229 log("\n");
230 log(" yosys*>\n");
231 log(" only part of the design is selected\n");
232 log("\n");
233 log(" yosys [modname]>\n");
234 log(" the entire module 'modname' is selected using 'select -module modname'\n");
235 log("\n");
236 log(" yosys [modname]*>\n");
237 log(" only part of current module 'modname' is selected\n");
238 log("\n");
239 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
240 log("do not terminate yosys but return to the command prompt.\n");
241 log("\n");
242 log("This command is the default action if nothing else has been specified\n");
243 log("on the command line.\n");
244 log("\n");
245 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
246 log("\n");
247 }
248 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
249 extra_args(args, 1, design, false);
250 shell(design);
251 }
252 } ShellPass;
253
254 struct ScriptPass : public Pass {
255 ScriptPass() : Pass("script", "execute commands from script file") { }
256 virtual void help() {
257 log("\n");
258 log(" script <filename>\n");
259 log("\n");
260 log("This command executes the yosys commands in the specified file.\n");
261 log("\n");
262 }
263 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
264 if (args.size() < 2)
265 log_cmd_error("Missing script file.\n");
266 if (args.size() > 2)
267 extra_args(args, 1, design, false);
268 run_frontend(args[1], "script", design, NULL);
269 }
270 } ScriptPass;
271
272 #ifdef YOSYS_ENABLE_TCL
273 static Tcl_Interp *yosys_tcl_interp = NULL;
274 static RTLIL::Design *yosys_tcl_design = NULL;
275
276 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
277 {
278 std::vector<std::string> args;
279 for (int i = 1; i < argc; i++)
280 args.push_back(argv[i]);
281
282 if (args.size() >= 1 && args[0] == "-import") {
283 for (auto &it : REGISTER_INTERN::pass_register) {
284 std::string tcl_command_name = it.first;
285 if (tcl_command_name == "proc")
286 tcl_command_name = "procs";
287 Tcl_CmdInfo info;
288 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
289 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
290 } else {
291 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
292 Tcl_Eval(interp, tcl_script.c_str());
293 }
294 }
295 return TCL_OK;
296 }
297
298 if (args.size() == 1) {
299 Pass::call(yosys_tcl_design, args[0]);
300 return TCL_OK;
301 }
302
303 Pass::call(yosys_tcl_design, args);
304 return TCL_OK;
305 }
306
307 extern Tcl_Interp *yosys_get_tcl_interp()
308 {
309 if (yosys_tcl_interp == NULL) {
310 yosys_tcl_interp = Tcl_CreateInterp();
311 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
312 }
313 return yosys_tcl_interp;
314 }
315
316 extern RTLIL::Design *yosys_get_tcl_design()
317 {
318 return yosys_tcl_design;
319 }
320
321 struct TclPass : public Pass {
322 TclPass() : Pass("tcl", "execute a TCL script file") { }
323 virtual void help() {
324 log("\n");
325 log(" tcl <filename>\n");
326 log("\n");
327 log("This command executes the tcl commands in the specified file.\n");
328 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
329 log("\n");
330 log("The tcl command 'yosys -import' can be used to import all yosys\n");
331 log("commands directly as tcl commands to the tcl shell. The yosys\n");
332 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
333 log("to avoid a name collision with the tcl builting command 'proc'.\n");
334 log("\n");
335 }
336 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
337 if (args.size() < 2)
338 log_cmd_error("Missing script file.\n");
339 if (args.size() > 2)
340 extra_args(args, 1, design, false);
341 if (Tcl_EvalFile(yosys_get_tcl_interp(), args[1].c_str()) != TCL_OK)
342 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
343 }
344 } TclPass;
345 #endif
346
347 std::string rewrite_yosys_exe(std::string exe)
348 {
349 char buffer[1024];
350 ssize_t buflen = readlink("/proc/self/exe", buffer, sizeof(buffer)-1);
351
352 if (buflen < 0)
353 return exe;
354
355 buffer[buflen] = 0;
356 std::string newexe = stringf("%s/%s", dirname(buffer), exe.c_str());
357 if (access(newexe.c_str(), X_OK) == 0)
358 return newexe;
359
360 return exe;
361 }
362
363 int main(int argc, char **argv)
364 {
365 std::string frontend_command = "auto";
366 std::string backend_command = "auto";
367 std::vector<std::string> passes_commands;
368 std::vector<void*> loaded_modules;
369 std::string output_filename = "";
370 std::string scriptfile = "";
371 bool scriptfile_tcl = false;
372 bool got_output_filename = false;
373
374 int opt;
375 while ((opt = getopt(argc, argv, "Sm:f:b:o:p:l:qts:c:")) != -1)
376 {
377 switch (opt)
378 {
379 case 'S':
380 backend_command = "verilog -noattr";
381 passes_commands.push_back("hierarchy");
382 passes_commands.push_back("proc");
383 passes_commands.push_back("opt");
384 passes_commands.push_back("memory");
385 passes_commands.push_back("techmap");
386 passes_commands.push_back("opt");
387 break;
388 case 'm':
389 loaded_modules.push_back(dlopen(optarg, RTLD_LAZY|RTLD_GLOBAL));
390 if (loaded_modules.back() == NULL) {
391 fprintf(stderr, "Can't load module `%s': %s\n", optarg, dlerror());
392 exit(1);
393 }
394 break;
395 case 'f':
396 frontend_command = optarg;
397 break;
398 case 'b':
399 backend_command = optarg;
400 break;
401 case 'p':
402 passes_commands.push_back(optarg);
403 break;
404 case 'o':
405 output_filename = optarg;
406 got_output_filename = true;
407 break;
408 case 'l':
409 log_files.push_back(fopen(optarg, "wt"));
410 if (log_files.back() == NULL) {
411 fprintf(stderr, "Can't open log file `%s' for writing!\n", optarg);
412 exit(1);
413 }
414 break;
415 case 'q':
416 log_errfile = stderr;
417 break;
418 case 't':
419 log_time = true;
420 break;
421 case 's':
422 scriptfile = optarg;
423 scriptfile_tcl = false;
424 break;
425 case 'c':
426 scriptfile = optarg;
427 scriptfile_tcl = true;
428 break;
429 default:
430 fprintf(stderr, "\n");
431 fprintf(stderr, "Usage: %s [-S] [-q] [-t] [-l logfile] [-o <outfile>] [-f <frontend>] [{-s|-c} <scriptfile>]\n", argv[0]);
432 fprintf(stderr, " %*s[-p <pass> [-p ..]] [-b <backend>] [-m <module_file>] [<infile> [..]]\n", int(strlen(argv[0])+1), "");
433 fprintf(stderr, "\n");
434 fprintf(stderr, " -q\n");
435 fprintf(stderr, " quiet operation. only write error messages to console\n");
436 fprintf(stderr, "\n");
437 fprintf(stderr, " -t\n");
438 fprintf(stderr, " annotate all log messages with a time stamp\n");
439 fprintf(stderr, "\n");
440 fprintf(stderr, " -l logfile\n");
441 fprintf(stderr, " write log messages to the specified file\n");
442 fprintf(stderr, "\n");
443 fprintf(stderr, " -o outfile\n");
444 fprintf(stderr, " write the design to the specified file on exit\n");
445 fprintf(stderr, "\n");
446 fprintf(stderr, " -b backend\n");
447 fprintf(stderr, " use this backend for the output file specified on the command line\n");
448 fprintf(stderr, "\n");
449 fprintf(stderr, " -f backend\n");
450 fprintf(stderr, " use the specified front for the input files on the command line\n");
451 fprintf(stderr, "\n");
452 fprintf(stderr, " -s scriptfile\n");
453 fprintf(stderr, " execute the commands in the script file\n");
454 fprintf(stderr, "\n");
455 fprintf(stderr, " -c tcl_scriptfile\n");
456 fprintf(stderr, " execute the commands in the tcl script file (see 'help tcl' for details)\n");
457 fprintf(stderr, "\n");
458 fprintf(stderr, " -p command\n");
459 fprintf(stderr, " execute the commands\n");
460 fprintf(stderr, "\n");
461 fprintf(stderr, " -m module_file\n");
462 fprintf(stderr, " load the specified module (aka plugin)\n");
463 fprintf(stderr, "\n");
464 fprintf(stderr, "The option -S is an alias for the following options that perform a simple\n");
465 fprintf(stderr, "transformation of the input to a gate-level netlist. This can be helpful when\n");
466 fprintf(stderr, "e.g. using yosys as a pre-processor for a tool that can't understand full verilog.\n");
467 fprintf(stderr, "\n");
468 fprintf(stderr, " -b 'verilog -noattr' -p hierarchy -p proc -p opt -p memory -p techmap -p opt\n");
469 fprintf(stderr, "\n");
470 fprintf(stderr, "For more complex synthesis jobs it is recommended to use the read_* and write_*\n");
471 fprintf(stderr, "commands in a script file instead of specifying input and output files on the\n");
472 fprintf(stderr, "command line.\n");
473 fprintf(stderr, "\n");
474 fprintf(stderr, "When no commands, script files and input files are specified on the command\n");
475 fprintf(stderr, "line, yosys automatically enters the interactive command mode. Use the 'help'\n");
476 fprintf(stderr, "command to get information on the individual commands.\n");
477 fprintf(stderr, "\n");
478 exit(1);
479 }
480 }
481
482 if (log_errfile == NULL)
483 log_files.push_back(stderr);
484
485 log("\n");
486 log(" /-----------------------------------------------------------------------------\\\n");
487 log(" | |\n");
488 log(" | yosys -- Yosys Open SYnthesis Suite |\n");
489 log(" | |\n");
490 log(" | Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> |\n");
491 log(" | |\n");
492 log(" | Permission to use, copy, modify, and/or distribute this software for any |\n");
493 log(" | purpose with or without fee is hereby granted, provided that the above |\n");
494 log(" | copyright notice and this permission notice appear in all copies. |\n");
495 log(" | |\n");
496 log(" | THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |\n");
497 log(" | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |\n");
498 log(" | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |\n");
499 log(" | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |\n");
500 log(" | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |\n");
501 log(" | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |\n");
502 log(" | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |\n");
503 log(" | |\n");
504 log(" \\-----------------------------------------------------------------------------/\n");
505 log("\n");
506
507 Pass::init_register();
508
509 RTLIL::Design *design = new RTLIL::Design;
510 design->selection_stack.push_back(RTLIL::Selection());
511 log_push();
512
513 #ifdef YOSYS_ENABLE_TCL
514 yosys_tcl_design = design;
515 #endif
516
517 if (optind == argc && passes_commands.size() == 0 && scriptfile.empty()) {
518 if (!got_output_filename)
519 backend_command = "";
520 shell(design);
521 }
522
523 while (optind < argc)
524 run_frontend(argv[optind++], frontend_command, design, output_filename == "-" ? &backend_command : NULL);
525
526 if (!scriptfile.empty()) {
527 if (scriptfile_tcl) {
528 #ifdef YOSYS_ENABLE_TCL
529 if (Tcl_EvalFile(yosys_get_tcl_interp(), scriptfile.c_str()) != TCL_OK)
530 log_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
531 #else
532 log_error("Can't exectue TCL script: this version of yosys is not built with TCL support enabled.\n");
533 #endif
534 } else
535 run_frontend(scriptfile, "script", design, output_filename == "-" ? &backend_command : NULL);
536 }
537
538 for (auto it = passes_commands.begin(); it != passes_commands.end(); it++)
539 run_pass(*it, design);
540
541 if (!backend_command.empty())
542 run_backend(output_filename, backend_command, design);
543
544 delete design;
545
546 #ifdef YOSYS_ENABLE_TCL
547 yosys_tcl_design = NULL;
548 #endif
549
550 log("\nREADY.\n");
551 log_pop();
552
553 for (auto f : log_files)
554 if (f != stderr)
555 fclose(f);
556 log_errfile = NULL;
557 log_files.clear();
558
559 Pass::done_register();
560
561 for (auto mod : loaded_modules)
562 dlclose(mod);
563
564 #ifdef YOSYS_ENABLE_TCL
565 if (yosys_tcl_interp != NULL) {
566 Tcl_DeleteInterp(yosys_tcl_interp);
567 Tcl_Finalize();
568 yosys_tcl_interp = NULL;
569 }
570 #endif
571
572 return 0;
573 }
574