more cases where we have to count declarations
[cparser] / main.c
1 #include <config.h>
2
3 #define _GNU_SOURCE
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include <errno.h>
9 #include <string.h>
10 #include <assert.h>
11
12 #ifdef _WIN32
13
14 #include <fcntl.h>
15 #include <io.h>
16
17 /* no eXecute on Win32 */
18 #define X_OK 0
19 #define W_OK 2
20 #define R_OK 4
21
22 #define O_RDWR          _O_RDWR
23 #define O_CREAT         _O_CREAT
24 #define O_EXCL          _O_EXCL
25 #define O_BINARY        _O_BINARY
26
27 /* remap some names, we are not in the POSIX world */
28 #define access(fname, mode)      _access(fname, mode)
29 #define mktemp(tmpl)             _mktemp(tmpl)
30 #define open(fname, oflag, mode) _open(fname, oflag, mode)
31 #define fdopen(fd, mode)         _fdopen(fd, mode)
32 #define popen(cmd, mode)         _popen(cmd, mode)
33 #define pclose(file)             _pclose(file)
34
35 #else
36 #include <unistd.h>
37 #define HAVE_MKSTEMP
38 #endif
39
40 #ifndef WITH_LIBCORE
41 #define WITH_LIBCORE
42 #endif
43
44 #include <libfirm/firm.h>
45 #include <libfirm/be.h>
46
47 #include "lexer.h"
48 #include "token_t.h"
49 #include "type_hash.h"
50 #include "parser.h"
51 #include "ast2firm.h"
52 #include "lang_features.h"
53 #include "driver/firm_opt.h"
54 #include "driver/firm_cmdline.h"
55 #include "adt/error.h"
56 #include "write_fluffy.h"
57 #include "revision.h"
58
59 #ifndef PREPROCESSOR
60 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int"
61 #endif
62
63 #ifndef LINKER
64 #define LINKER    "gcc -m32"
65 #endif
66
67 #ifndef ASSEMBLER
68 #define ASSEMBLER "as --32"
69 #endif
70
71 /** The current c mode/dialect. */
72 unsigned int c_mode = _C99|_GNUC;
73
74 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
75 unsigned int machine_size = 32;
76
77 /** true if the char type is signed. */
78 bool char_is_signed = true;
79
80 static int            verbose;
81 static struct obstack cppflags_obst;
82
83 #if defined(_DEBUG) || defined(FIRM_DEBUG)
84 /**
85  * Debug printf implementation.
86  *
87  * @param fmt  printf style format parameter
88  */
89 void dbg_printf(const char *fmt, ...)
90 {
91         va_list list;
92
93         if (firm_dump.debug_print) {
94                 va_start(list, fmt);
95                 vprintf(fmt, list);
96                 va_end(list);
97         }  /* if */
98 }
99 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
100
101 static void initialize_firm(void)
102 {
103         firm_early_init();
104
105         dump_consts_local(1);
106         dump_keepalive_edges(1);
107 }
108
109 static void get_output_name(char *buf, size_t buflen, const char *inputname,
110                             const char *newext)
111 {
112         size_t last_dot = 0xffffffff;
113         size_t i = 0;
114
115         if(inputname == NULL) {
116                 snprintf(buf, buflen, "a%s", newext);
117                 return;
118         }
119
120         for(const char *c = inputname; *c != 0; ++c) {
121                 if(*c == '.')
122                         last_dot = i;
123                 ++i;
124         }
125         if(last_dot == 0xffffffff)
126                 last_dot = i;
127
128         if(last_dot >= buflen)
129                 panic("filename too long");
130         memcpy(buf, inputname, last_dot);
131
132         size_t extlen = strlen(newext) + 1;
133         if(extlen + last_dot >= buflen)
134                 panic("filename too long");
135         memcpy(buf+last_dot, newext, extlen);
136 }
137
138 static translation_unit_t *do_parsing(FILE *const in, const char *const input)
139 {
140         lexer_open_stream(in, input);
141         translation_unit_t *unit = parse();
142         return unit;
143 }
144
145 static void lextest(FILE *in, const char *fname)
146 {
147         lexer_open_stream(in, fname);
148
149         do {
150                 lexer_next_preprocessing_token();
151                 print_token(stdout, &lexer_token);
152                 puts("");
153         } while(lexer_token.type != T_EOF);
154 }
155
156 static FILE* preprocess(FILE* in, const char *fname)
157 {
158         char buf[4096];
159         const char *flags = obstack_finish(&cppflags_obst);
160
161         if(in != stdin) {
162                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s %s", flags, fname);
163         } else {
164                 /* read from stdin */
165                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s -", flags);
166         }
167
168         if(verbose) {
169                 puts(buf);
170         }
171         FILE* f = popen(buf, "r");
172         if (f == NULL) {
173                 fprintf(stderr, "invoking preprocessor failed\n");
174                 exit(1);
175         }
176         return f;
177 }
178
179 static void do_link(const char *out, const char *in)
180 {
181         char buf[4096];
182
183         snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out);
184         if(verbose) {
185                 puts(buf);
186         }
187         int err = system(buf);
188         if(err != 0) {
189                 fprintf(stderr, "linker reported an error\n");
190                 exit(1);
191         }
192 }
193
194 static void assemble(const char *out, const char *in)
195 {
196         char buf[4096];
197
198         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
199         if(verbose) {
200                 puts(buf);
201         }
202
203         int err = system(buf);
204         if(err != 0) {
205                 fprintf(stderr, "assembler reported an error\n");
206                 exit(1);
207         }
208 }
209
210 static const char *try_dir(const char *dir)
211 {
212         if(dir == NULL)
213                 return dir;
214         if(access(dir, R_OK | W_OK | X_OK) == 0)
215                 return dir;
216         return NULL;
217 }
218
219 static const char *get_tempdir(void)
220 {
221         static const char *tmpdir = NULL;
222
223         if(tmpdir != NULL)
224                 return tmpdir;
225
226         if(tmpdir == NULL)
227                 tmpdir = try_dir(getenv("TMPDIR"));
228         if(tmpdir == NULL)
229                 tmpdir = try_dir(getenv("TMP"));
230         if(tmpdir == NULL)
231                 tmpdir = try_dir(getenv("TEMP"));
232
233 #ifdef P_tmpdir
234         if(tmpdir == NULL)
235                 tmpdir = try_dir(P_tmpdir);
236 #endif
237
238         if(tmpdir == NULL)
239                 tmpdir = try_dir("/var/tmp");
240         if(tmpdir == NULL)
241                 tmpdir = try_dir("/usr/tmp");
242         if(tmpdir == NULL)
243                 tmpdir = try_dir("/tmp");
244
245         if(tmpdir == NULL)
246                 tmpdir = ".";
247
248         return tmpdir;
249 }
250
251 #ifndef HAVE_MKSTEMP
252 /* cheap and nasty mkstemp replacement */
253 static int mkstemp(char *templ)
254 {
255         mktemp(templ);
256         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
257 }
258 #endif
259
260 /**
261  * an own version of tmpnam, which: writes in a buffer, appends a user specified
262  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
263  */
264 static FILE *make_temp_file(char *buffer, size_t buflen,
265                             const char *prefix, const char *suffix)
266 {
267         const char *tempdir = get_tempdir();
268
269         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
270         (void) suffix;
271         suffix = "";
272
273         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
274
275         int fd = mkstemp(buffer);
276         if(fd == -1) {
277                 fprintf(stderr, "couldn't create temporary file: %s\n",
278                         strerror(errno));
279                 exit(1);
280         }
281         FILE *out = fdopen(fd, "w");
282         if(out == NULL) {
283                 fprintf(stderr, "couldn't create temporary file FILE*\n");
284                 exit(1);
285         }
286
287         return out;
288 }
289
290 /**
291  * Do the necessary lowering for compound parameters.
292  */
293 void lower_compound_params(void)
294 {
295         lower_params_t params;
296
297         params.def_ptr_alignment    = 4;
298         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
299         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
300         params.find_pointer_type    = NULL;
301         params.ret_compound_in_regs = NULL;
302         lower_calls_with_compounds(&params);
303 }
304
305 typedef enum compile_mode_t {
306         ParseOnly,
307         Compile,
308         CompileDump,
309         CompileAssemble,
310         CompileAssembleLink,
311         LexTest,
312         PrintAst,
313         PrintFluffy
314 } compile_mode_t;
315
316 static void usage(const char *argv0)
317 {
318         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
319 }
320
321 int main(int argc, char **argv)
322 {
323         initialize_firm();
324
325         const char     *input        = NULL;
326         const char     *outname      = NULL;
327         const char     *dumpfunction = NULL;
328         compile_mode_t  mode         = CompileAssembleLink;
329
330         obstack_init(&cppflags_obst);
331
332 #define GET_ARG_AFTER(def, args)                                             \
333         def = &arg[sizeof(args)-1];                                              \
334         if(def[0] == '\0') {                                                     \
335                 ++i;                                                                 \
336                 if(i >= argc) {                                                      \
337                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
338                         argument_errors = true;                                          \
339                         break;                                                           \
340                 }                                                                    \
341                 def = argv[i];                                                       \
342                 if(def[0] == '-' && def[1] != '\0') {                                \
343                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
344                         argument_errors = true;                                          \
345                         continue;                                                        \
346                 }                                                                    \
347         }
348
349         bool help_displayed  = false;
350         bool argument_errors = false;
351         for(int i = 1; i < argc; ++i) {
352                 const char *arg = argv[i];
353                 if(strncmp(arg, "-o", 2) == 0) {
354                         GET_ARG_AFTER(outname, "-o");
355                 } else if(strcmp(arg, "-c") == 0) {
356                         mode = CompileAssemble;
357                 } else if(strcmp(arg, "-S") == 0) {
358                         mode = Compile;
359                 } else if(strcmp(arg, "--gcc") == 0) {
360                         c_mode |= _GNUC;
361                 } else if(strcmp(arg, "--no-gcc") == 0) {
362                         c_mode &= ~_GNUC;
363                 } else if(strcmp(arg, "--ms") == 0) {
364                         c_mode |= _MS;
365                 } else if(strcmp(arg, "--signed-chars") == 0) {
366                         char_is_signed = true;
367                 } else if(strcmp(arg, "--unsigned-chars") == 0) {
368                         char_is_signed = false;
369                 } else if(strcmp(arg, "--no-ms") == 0) {
370                         c_mode &= ~_MS;
371                 } else if(strcmp(arg, "--lextest") == 0) {
372                         mode = LexTest;
373                 } else if(strcmp(arg, "--print-ast") == 0) {
374                         mode = PrintAst;
375                 } else if(strcmp(arg, "--print-fluffy") == 0) {
376                         mode = PrintFluffy;
377                 } else if(strcmp(arg, "--version") == 0) {
378                         firm_version_t ver;
379                         firm_get_version(&ver);
380                         printf("cparser (%d.%d %s) using libFirm (%d.%d", 0, 1, cparser_REVISION, ver.major, ver.minor);
381                         if(ver.revision[0] != 0) {
382                                 putchar(' ');
383                                 fputs(ver.revision, stdout);
384                         }
385                         if(ver.build[0] != 0) {
386                                 putchar(' ');
387                                 fputs(ver.build, stdout);
388                         }
389                         puts(")\n");
390                         exit(EXIT_SUCCESS);
391                 } else if(strcmp(arg, "-fsyntax-only") == 0) {
392                         mode = ParseOnly;
393                 } else if(strncmp(arg, "-I", 2) == 0) {
394                         const char *opt;
395                         GET_ARG_AFTER(opt, "-I");
396                         obstack_printf(&cppflags_obst, " -I%s", opt);
397                 } else if(strncmp(arg, "-D", 2) == 0) {
398                         const char *opt;
399                         GET_ARG_AFTER(opt, "-D");
400                         obstack_printf(&cppflags_obst, " -D%s", opt);
401                 } else if(strcmp(arg, "--dump-function") == 0) {
402                         ++i;
403                         if(i >= argc) {
404                                 fprintf(stderr, "error: "
405                                         "expected argument after '--dump-function'\n");
406                                 argument_errors = true;
407                                 break;
408                         }
409                         dumpfunction = argv[i];
410                         mode         = CompileDump;
411                 } else if(strcmp(arg, "-v") == 0) {
412                         verbose = 1;
413                 } else if(arg[0] == '-' && arg[1] == 'f') {
414                         const char *opt;
415                         GET_ARG_AFTER(opt, "-f");
416
417                         if(strcmp(opt, "omit-frame-pointer") == 0) {
418                                 firm_be_option("omitfp");
419                         } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
420                                 firm_be_option("omitfp=no");
421                         } else {
422                                 int res = firm_option(opt);
423                                 if (res == 0) {
424                                         fprintf(stderr, "error: unknown Firm option '-f %s'\n",
425                                                 opt);
426                                         argument_errors = true;
427                                         continue;
428                                 } else if (res == -1) {
429                                         help_displayed = true;
430                                 }
431                         }
432                 } else if(arg[0] == '-' && arg[1] == 'b') {
433                         const char *opt;
434                         GET_ARG_AFTER(opt, "-b");
435                         int res = firm_be_option(opt);
436                         if (res == 0) {
437                                 fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
438                                         opt);
439                                 argument_errors = true;
440                         } else if (res == -1) {
441                                 help_displayed = true;
442                         }
443                 } else if(arg[0] == '-' && arg[1] == 'm') {
444                         const char *opt;
445                         GET_ARG_AFTER(opt, "-m");
446                         char *endptr;
447                         long int value = strtol(opt, &endptr, 10);
448                         if (*endptr != '\0') {
449                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
450                                 argument_errors = true;
451                         }
452                         if (value != 16 && value != 32 && value != 64) {
453                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
454                                 argument_errors = true;
455                         } else {
456                                 machine_size = (unsigned int)value;
457                         }
458                 } else if(arg[0] == '-') {
459                         if (arg[1] == '\0') {
460                                 if(input != NULL) {
461                                         fprintf(stderr, "error: multiple input files specified\n");
462                                         argument_errors = true;
463                                 } else {
464                                         input = arg;
465                                 }
466                         } else if(strcmp(arg, "-pedantic") == 0) {
467                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
468                         } else if(arg[1] == 'O' ||
469                                         arg[1] == 'W' ||
470                                         arg[1] == 'g' ||
471                                         strncmp(arg + 1, "std=", 4) == 0) {
472                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
473                         } else {
474                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
475                                 argument_errors = true;
476                         }
477                 } else {
478                         if(input != NULL) {
479                                 fprintf(stderr, "error: multiple input files specified\n");
480                                 argument_errors = true;
481                         } else {
482                                 input = arg;
483                         }
484                 }
485         }
486
487         if(help_displayed) {
488                 return !argument_errors;
489         }
490         if(argument_errors) {
491                 usage(argv[0]);
492                 return 1;
493         }
494
495         gen_firm_init();
496         init_symbol_table();
497         init_tokens();
498         init_types();
499         init_typehash();
500         init_lexer();
501         init_ast();
502         init_parser();
503         init_ast2firm();
504
505         FILE *out;
506         char  outnamebuf[4096];
507         if(outname == NULL) {
508                 switch(mode) {
509                 case PrintAst:
510                 case PrintFluffy:
511                 case LexTest:
512                         if(outname == NULL)
513                                 outname = "-";
514                         break;
515                 case ParseOnly:
516                         break;
517                 case Compile:
518                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
519                         outname = outnamebuf;
520                         break;
521                 case CompileAssemble:
522                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
523                         outname = outnamebuf;
524                         break;
525                 case CompileDump:
526                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
527                                         ".vcg");
528                         outname = outnamebuf;
529                         break;
530                 case CompileAssembleLink:
531                         outname = "a.out";
532                         break;
533                 }
534         }
535
536         if(outname != NULL) {
537                 if(strcmp(outname, "-") == 0) {
538                         out = stdout;
539                 } else {
540                         out = fopen(outname, "w");
541                         if(out == NULL) {
542                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
543                                         strerror(errno));
544                                 return 1;
545                         }
546                 }
547         }
548
549         FILE *in;
550         if(input == NULL) {
551                 fprintf(stderr, "%s: no input files\n", argv[0]);
552                 return 1;
553         } else if(strcmp(input, "-") == 0) {
554                 in    = stdin;
555                 input = "<stdin>";
556         } else {
557                 in = fopen(input, "r");
558                 if(in == NULL) {
559                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
560                         return 1;
561                 }
562         }
563
564         if(mode == LexTest) {
565                 lextest(in, input);
566                 fclose(in);
567                 return 0;
568         }
569
570         FILE *preprocessed_in = preprocess(in, input);
571         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
572         pclose(preprocessed_in);
573         if(unit == NULL)
574                 return 1;
575
576         if(mode == PrintAst) {
577                 type_set_output(out);
578                 ast_set_output(out);
579                 print_ast(unit);
580                 return 0;
581         }
582         if(mode == PrintFluffy) {
583                 type_set_output(out);
584                 ast_set_output(out);
585                 write_fluffy_decls(out, unit);
586         }
587
588         translation_unit_to_firm(unit);
589
590         if(mode == ParseOnly) {
591                 return 0;
592         }
593
594         FILE *asm_out;
595         char  asm_tempfile[1024];
596         if(mode == CompileDump) {
597                 asm_out = NULL;
598                 firm_be_opt.selection = BE_NONE;
599         } else if(mode == Compile) {
600                 asm_out = out;
601         } else {
602                 asm_out
603                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
604         }
605         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
606
607         if(mode == CompileDump) {
608                 /* find irg */
609                 ident    *id     = new_id_from_str(dumpfunction);
610                 ir_graph *irg    = NULL;
611                 int       n_irgs = get_irp_n_irgs();
612                 for(int i = 0; i < n_irgs; ++i) {
613                         ir_graph *tirg   = get_irp_irg(i);
614                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
615                         if(irg_id == id) {
616                                 irg = tirg;
617                                 break;
618                         }
619                 }
620
621                 if(irg == NULL) {
622                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
623                         return 1;
624                 }
625
626                 dump_ir_block_graph_file(irg, out);
627                 fclose(out);
628                 return 0;
629         }
630
631         fclose(asm_out);
632
633         /* assemble assembler and create object file */
634         char obj_tfile[1024];
635         if(mode == CompileAssemble || mode == CompileAssembleLink) {
636                 const char *obj_outfile;
637                 if(mode == CompileAssemble) {
638                         fclose(out);
639                         obj_outfile = outname;
640                 } else {
641                         FILE *tempf
642                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
643                         fclose(tempf);
644                         obj_outfile = obj_tfile;
645                 }
646
647                 assemble(obj_outfile, asm_tempfile);
648         }
649
650         /* link object file */
651         if(mode == CompileAssembleLink) {
652                 do_link(outname, obj_tfile);
653         }
654
655         obstack_free(&cppflags_obst, NULL);
656
657         exit_ast2firm();
658         exit_parser();
659         exit_ast();
660         exit_lexer();
661         exit_typehash();
662         exit_types();
663         exit_tokens();
664         exit_symbol_table();
665         return 0;
666 }