add support for -M dependency creation modes
[cparser] / main.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #define _GNU_SOURCE
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdbool.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <assert.h>
30
31 #ifdef _WIN32
32
33 #include <fcntl.h>
34 #include <io.h>
35
36 /* no eXecute on Win32 */
37 #define X_OK 0
38 #define W_OK 2
39 #define R_OK 4
40
41 #define O_RDWR          _O_RDWR
42 #define O_CREAT         _O_CREAT
43 #define O_EXCL          _O_EXCL
44 #define O_BINARY        _O_BINARY
45
46 /* remap some names, we are not in the POSIX world */
47 #define access(fname, mode)      _access(fname, mode)
48 #define mktemp(tmpl)             _mktemp(tmpl)
49 #define open(fname, oflag, mode) _open(fname, oflag, mode)
50 #define fdopen(fd, mode)         _fdopen(fd, mode)
51 #define popen(cmd, mode)         _popen(cmd, mode)
52 #define pclose(file)             _pclose(file)
53
54 #else
55 #include <unistd.h>
56 #define HAVE_MKSTEMP
57 #endif
58
59 #ifndef WITH_LIBCORE
60 #define WITH_LIBCORE
61 #endif
62
63 #include <libfirm/firm.h>
64 #include <libfirm/be.h>
65
66 #include "lexer.h"
67 #include "token_t.h"
68 #include "types.h"
69 #include "type_hash.h"
70 #include "parser.h"
71 #include "ast2firm.h"
72 #include "diagnostic.h"
73 #include "lang_features.h"
74 #include "driver/firm_opt.h"
75 #include "driver/firm_cmdline.h"
76 #include "adt/error.h"
77 #include "write_fluffy.h"
78 #include "write_caml.h"
79 #include "revision.h"
80 #include "warning.h"
81
82 #ifndef PREPROCESSOR
83 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int -U__SIZE_TYPE__ -D__SIZE_TYPE__=__SIZE_TYPE__ -m32"
84 #endif
85
86 #ifndef LINKER
87 #define LINKER    "gcc -m32"
88 #endif
89
90 #ifndef ASSEMBLER
91 #define ASSEMBLER "as --32"
92 #endif
93
94 /** The current c mode/dialect. */
95 unsigned int c_mode = _C89|_C99|_GNUC;
96
97 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
98 unsigned int machine_size = 32;
99
100 /** true if the char type is signed. */
101 bool char_is_signed = true;
102
103 /** true for strict language checking. */
104 bool strict_mode = false;
105
106 /** use builtins for some libc functions */
107 bool use_builtins = false;
108
109 /* to switch on printing of implicit casts */
110 extern bool print_implicit_casts;
111
112 /* to switch on printing of parenthesis to indicate operator precedence */
113 extern bool print_parenthesis;
114
115 static int            verbose;
116 static struct obstack cppflags_obst, ldflags_obst;
117
118 typedef struct file_list_entry_t file_list_entry_t;
119
120 struct file_list_entry_t {
121         const char        *filename;
122         file_list_entry_t *next;
123 };
124
125 #if defined(_DEBUG) || defined(FIRM_DEBUG)
126 /**
127  * Debug printf implementation.
128  *
129  * @param fmt  printf style format parameter
130  */
131 void dbg_printf(const char *fmt, ...)
132 {
133         va_list list;
134
135         if (firm_dump.debug_print) {
136                 va_start(list, fmt);
137                 vprintf(fmt, list);
138                 va_end(list);
139         }  /* if */
140 }
141 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
142
143 static void initialize_firm(void)
144 {
145         firm_early_init();
146
147         dump_consts_local(1);
148         dump_keepalive_edges(1);
149 }
150
151 static void get_output_name(char *buf, size_t buflen, const char *inputname,
152                             const char *newext)
153 {
154         size_t last_dot = 0xffffffff;
155         size_t i = 0;
156
157         if(inputname == NULL) {
158                 snprintf(buf, buflen, "a%s", newext);
159                 return;
160         }
161
162         for(const char *c = inputname; *c != 0; ++c) {
163                 if(*c == '.')
164                         last_dot = i;
165                 ++i;
166         }
167         if(last_dot == 0xffffffff)
168                 last_dot = i;
169
170         if(last_dot >= buflen)
171                 panic("filename too long");
172         memcpy(buf, inputname, last_dot);
173
174         size_t extlen = strlen(newext) + 1;
175         if(extlen + last_dot >= buflen)
176                 panic("filename too long");
177         memcpy(buf+last_dot, newext, extlen);
178 }
179
180 #include "builtins.h"
181
182 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
183 {
184         start_parsing();
185
186         if (use_builtins) {
187                 lexer_open_buffer(builtins, sizeof(builtins)-1, "<builtin>");
188                 parse();
189         }
190
191         lexer_open_stream(in, input_name);
192         parse();
193
194         translation_unit_t *unit = finish_parsing();
195         return unit;
196 }
197
198 static void lextest(FILE *in, const char *fname)
199 {
200         lexer_open_stream(in, fname);
201
202         do {
203                 lexer_next_preprocessing_token();
204                 print_token(stdout, &lexer_token);
205                 puts("");
206         } while(lexer_token.type != T_EOF);
207 }
208
209 static FILE *preprocess(FILE *in, const char *fname)
210 {
211         char buf[4096];
212         obstack_1grow(&cppflags_obst, '\0');
213         const char *flags = obstack_finish(&cppflags_obst);
214
215         if(in != stdin) {
216                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s %s", flags, fname);
217         } else {
218                 /* read from stdin */
219                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s -", flags);
220         }
221
222         if(verbose) {
223                 puts(buf);
224         }
225
226         FILE *f = popen(buf, "r");
227         if(f == NULL) {
228                 fprintf(stderr, "invoking preprocessor failed\n");
229                 exit(1);
230         }
231         return f;
232 }
233
234 static void do_link(const char *out, const char *in)
235 {
236         char buf[4096];
237         obstack_1grow(&ldflags_obst, '\0');
238         const char *flags = obstack_finish(&ldflags_obst);
239
240         snprintf(buf, sizeof(buf), LINKER " %s -o %s %s", flags, out, in);
241         if(verbose) {
242                 puts(buf);
243         }
244         int err = system(buf);
245         if(err != 0) {
246                 fprintf(stderr, "linker reported an error\n");
247                 exit(1);
248         }
249 }
250
251 static void assemble(const char *out, const char *in)
252 {
253         char buf[4096];
254
255         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
256         if(verbose) {
257                 puts(buf);
258         }
259
260         int err = system(buf);
261         if(err != 0) {
262                 fprintf(stderr, "assembler reported an error\n");
263                 exit(1);
264         }
265 }
266
267 static const char *try_dir(const char *dir)
268 {
269         if(dir == NULL)
270                 return dir;
271         if(access(dir, R_OK | W_OK | X_OK) == 0)
272                 return dir;
273         return NULL;
274 }
275
276 static const char *get_tempdir(void)
277 {
278         static const char *tmpdir = NULL;
279
280         if(tmpdir != NULL)
281                 return tmpdir;
282
283         if(tmpdir == NULL)
284                 tmpdir = try_dir(getenv("TMPDIR"));
285         if(tmpdir == NULL)
286                 tmpdir = try_dir(getenv("TMP"));
287         if(tmpdir == NULL)
288                 tmpdir = try_dir(getenv("TEMP"));
289
290 #ifdef P_tmpdir
291         if(tmpdir == NULL)
292                 tmpdir = try_dir(P_tmpdir);
293 #endif
294
295         if(tmpdir == NULL)
296                 tmpdir = try_dir("/var/tmp");
297         if(tmpdir == NULL)
298                 tmpdir = try_dir("/usr/tmp");
299         if(tmpdir == NULL)
300                 tmpdir = try_dir("/tmp");
301
302         if(tmpdir == NULL)
303                 tmpdir = ".";
304
305         return tmpdir;
306 }
307
308 #ifndef HAVE_MKSTEMP
309 /* cheap and nasty mkstemp replacement */
310 static int mkstemp(char *templ)
311 {
312         mktemp(templ);
313         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
314 }
315 #endif
316
317 /**
318  * an own version of tmpnam, which: writes in a buffer, appends a user specified
319  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
320  */
321 static FILE *make_temp_file(char *buffer, size_t buflen,
322                             const char *prefix, const char *suffix)
323 {
324         const char *tempdir = get_tempdir();
325
326         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
327         (void) suffix;
328         suffix = "";
329
330         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
331
332         int fd = mkstemp(buffer);
333         if(fd == -1) {
334                 fprintf(stderr, "couldn't create temporary file: %s\n",
335                         strerror(errno));
336                 exit(1);
337         }
338         FILE *out = fdopen(fd, "w");
339         if(out == NULL) {
340                 fprintf(stderr, "couldn't create temporary file FILE*\n");
341                 exit(1);
342         }
343
344         return out;
345 }
346
347 /**
348  * Do the necessary lowering for compound parameters.
349  */
350 void lower_compound_params(void)
351 {
352         lower_params_t params;
353
354         params.def_ptr_alignment    = 4;
355         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
356         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
357         params.find_pointer_type    = NULL;
358         params.ret_compound_in_regs = NULL;
359         lower_calls_with_compounds(&params);
360 }
361
362 typedef enum compile_mode_t {
363         BenchmarkParser,
364         PreprocessOnly,
365         ParseOnly,
366         Compile,
367         CompileDump,
368         CompileAssemble,
369         CompileAssembleLink,
370         LexTest,
371         PrintAst,
372         PrintFluffy,
373         PrintCaml,
374         Link,
375 } compile_mode_t;
376
377 static void usage(const char *argv0)
378 {
379         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
380 }
381
382 static void print_cparser_version(void) {
383         firm_version_t ver;
384         firm_get_version(&ver);
385
386         printf("cparser (%s) using libFirm (%u.%u",
387                 cparser_REVISION, ver.major, ver.minor);
388         if(ver.revision[0] != 0) {
389                 putchar(' ');
390                 fputs(ver.revision, stdout);
391         }
392         if(ver.build[0] != 0) {
393                 putchar(' ');
394                 fputs(ver.build, stdout);
395         }
396         puts(")\n");
397 }
398
399 static void set_be_option(const char *arg)
400 {
401         int res = firm_be_option(arg);
402         (void) res;
403         assert(res);
404 }
405
406 static void set_option(const char *arg)
407 {
408         int res = firm_option(arg);
409         (void) res;
410         assert(res);
411 }
412
413 static void copy_file(FILE *dest, FILE *input)
414 {
415         char buf[16384];
416
417         while (!feof(input) && !ferror(dest)) {
418                 size_t read = fread(buf, 1, sizeof(buf), input);
419                 if(fwrite(buf, 1, read, dest) != read) {
420                         perror("couldn't write output");
421                 }
422         }
423 }
424
425 int main(int argc, char **argv)
426 {
427         initialize_firm();
428
429         const char        *input        = NULL;
430         const char        *outname      = NULL;
431         const char        *dumpfunction = NULL;
432         compile_mode_t     mode         = CompileAssembleLink;
433         int                opt_level    = 1;
434         int                result       = EXIT_SUCCESS;
435         char               cpu_arch[16] = "ia32";
436         file_list_entry_t *c_files      = NULL;
437         file_list_entry_t *s_files      = NULL;
438         file_list_entry_t *o_files      = NULL;
439         struct obstack     file_obst;
440
441         obstack_init(&cppflags_obst);
442         obstack_init(&ldflags_obst);
443         obstack_init(&file_obst);
444
445 #define GET_ARG_AFTER(def, args)                                             \
446         def = &arg[sizeof(args)-1];                                              \
447         if(def[0] == '\0') {                                                     \
448                 ++i;                                                                 \
449                 if(i >= argc) {                                                      \
450                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
451                         argument_errors = true;                                          \
452                         break;                                                           \
453                 }                                                                    \
454                 def = argv[i];                                                       \
455                 if(def[0] == '-' && def[1] != '\0') {                                \
456                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
457                         argument_errors = true;                                          \
458                         continue;                                                        \
459                 }                                                                    \
460         }
461
462 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
463
464         /* early options parsing (find out optimisation level) */
465         for(int i = 1; i < argc; ++i) {
466                 const char *arg = argv[i];
467                 if(arg[0] != '-')
468                         continue;
469
470                 const char *option = &arg[1];
471                 if(option[0] == 'O') {
472                         sscanf(&option[1], "%d", &opt_level);
473                 }
474         }
475
476         /* apply optimisation level */
477         switch(opt_level) {
478         case 0:
479                 set_option("no-opt");
480                 break;
481         case 1:
482                 set_option("no-inline");
483                 break;
484         default:
485         case 4:
486                 set_option("strict-aliasing");
487                 /* fallthrough */
488         case 3:
489                 set_option("cond-eval");
490                 set_option("if-conv");
491                 use_builtins = true;
492                 /* fallthrough */
493         case 2:
494                 set_option("inline");
495                 set_option("deconv");
496                 set_be_option("omitfp");
497                 break;
498         }
499
500         /* parse rest of options */
501         bool help_displayed  = false;
502         bool argument_errors = false;
503         for(int i = 1; i < argc; ++i) {
504                 const char *arg = argv[i];
505                 if(arg[0] == '-' && arg[1] != 0) {
506                         /* an option */
507                         const char *option = &arg[1];
508                         if(option[0] == 'o') {
509                                 GET_ARG_AFTER(outname, "-o");
510                         } else if(option[0] == 'g') {
511                                 set_be_option("debuginfo=stabs");
512                                 set_be_option("omitfp=no");
513                                 set_be_option("ia32-nooptcc=yes");
514                         } else if(SINGLE_OPTION('c')) {
515                                 mode = CompileAssemble;
516                         } else if(SINGLE_OPTION('E')) {
517                                 mode = PreprocessOnly;
518                         } else if(SINGLE_OPTION('S')) {
519                                 mode = Compile;
520                         } else if(option[0] == 'O') {
521                                 continue;
522                         } else if(option[0] == 'I') {
523                                 const char *opt;
524                                 GET_ARG_AFTER(opt, "-I");
525                                 obstack_printf(&cppflags_obst, " -I%s", opt);
526                         } else if(option[0] == 'D') {
527                                 const char *opt;
528                                 GET_ARG_AFTER(opt, "-D");
529                                 obstack_printf(&cppflags_obst, " -D%s", opt);
530                         } else if(option[0] == 'U') {
531                                 const char *opt;
532                                 GET_ARG_AFTER(opt, "-U");
533                                 obstack_printf(&cppflags_obst, " -U%s", opt);
534                         } else if(option[0] == 'l') {
535                                 const char *opt;
536                                 GET_ARG_AFTER(opt, "-l");
537                                 obstack_printf(&ldflags_obst, " -l%s", opt);
538                         } else if(option[0] == 'L') {
539                                 const char *opt;
540                                 GET_ARG_AFTER(opt, "-L");
541                                 obstack_printf(&ldflags_obst, " -L%s", opt);
542                         } else if(SINGLE_OPTION('v')) {
543                                 verbose = 1;
544                         } else if(SINGLE_OPTION('w')) {
545                                 inhibit_all_warnings = true;
546                         } else if(strcmp(option, "M") == 0) {
547                                 mode = PreprocessOnly;
548                                 obstack_printf(&cppflags_obst, " -M");
549                         } else if(strcmp(option, "MMD") == 0
550                                         || strcmp(option, "MD") == 0
551                                         || strcmp(option, "MM") == 0) {
552                                 obstack_printf(&cppflags_obst, " -%s", option);
553                         } else if(strcmp(option, "MT") == 0
554                                         || strcmp(option, "MQ") == 0
555                                         || strcmp(option, "MF") == 0) {
556                                 const char *opt;
557                                 GET_ARG_AFTER(opt, "-MT");
558                                 obstack_printf(&cppflags_obst, " -%s %s", option, opt);
559                         } else if(strcmp(option, "pipe") == 0) {
560                                 /* here for gcc compatibility */
561                         } else if(option[0] == 'f') {
562                                 const char *opt;
563                                 GET_ARG_AFTER(opt, "-f");
564
565                                 if(strcmp(opt, "syntax-only") == 0) {
566                                         mode = ParseOnly;
567                                 } else if(strcmp(opt, "omit-frame-pointer") == 0) {
568                                         set_be_option("omitfp");
569                                 } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
570                                         set_be_option("omitfp=no");
571                                 } else if(strcmp(opt, "strength-reduce") == 0) {
572                                         firm_option("strength-red");
573                                 } else if(strcmp(opt, "fast-math") == 0
574                                                 || strcmp(opt, "unroll-loops") == 0
575                                                 || strcmp(opt, "expensive-optimizations") == 0
576                                                 || strcmp(opt, "no-common") == 0
577                                                 || strncmp(opt, "align-loops=", sizeof("align-loops=")-1) == 0
578                                                 || strncmp(opt, "align-jumps=", sizeof("align-jumps=")-1) == 0
579                                                 || strncmp(opt, "align-functions=", sizeof("align-functions=")-1) == 0) {
580                                         fprintf(stderr, "ignoring gcc option '-f %s'\n", opt);
581                                 } else {
582                                         int res = firm_option(opt);
583                                         if (res == 0) {
584                                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
585                                                         opt);
586                                                 argument_errors = true;
587                                                 continue;
588                                         } else if (res == -1) {
589                                                 help_displayed = true;
590                                         }
591                                 }
592                         } else if(option[0] == 'b') {
593                                 const char *opt;
594                                 GET_ARG_AFTER(opt, "-b");
595                                 int res = firm_be_option(opt);
596                                 if (res == 0) {
597                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
598                                                 opt);
599                                         argument_errors = true;
600                                 } else if (res == -1) {
601                                         help_displayed = true;
602                                 } else {
603                                         if (strncmp(opt, "isa=", 4) == 0)
604                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
605                                 }
606                         } else if(option[0] == 'W') {
607                                 set_warning_opt(&option[1]);
608                         } else if(option[0] == 'm') {
609                                 /* -m options */
610                                 const char *opt;
611                                 char arch_opt[64];
612
613                                 GET_ARG_AFTER(opt, "-m");
614                                 if(strncmp(opt, "arch=", 5) == 0) {
615                                         GET_ARG_AFTER(opt, "-march=");
616                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
617                                         int res = firm_be_option(arch_opt);
618                                         if (res == 0)
619                                                 argument_errors = true;
620                                         else {
621                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
622                                                 int res = firm_be_option(arch_opt);
623                                                 if (res == 0)
624                                                         argument_errors = true;
625                                         }
626                                 } else if(strncmp(opt, "tune=", 5) == 0) {
627                                         GET_ARG_AFTER(opt, "-mtune=");
628                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
629                                         int res = firm_be_option(arch_opt);
630                                         if (res == 0)
631                                                 argument_errors = true;
632                                 } else if(strncmp(opt, "cpu=", 4) == 0) {
633                                         GET_ARG_AFTER(opt, "-mcpu=");
634                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
635                                         int res = firm_be_option(arch_opt);
636                                         if (res == 0)
637                                                 argument_errors = true;
638                                 } else if(strncmp(opt, "fpmath=", 7) == 0) {
639                                         GET_ARG_AFTER(opt, "-mfpmath=");
640                                         if(strcmp(opt, "387") == 0)
641                                                 opt = "x87";
642                                         else if(strcmp(opt, "sse") == 0)
643                                                 opt = "sse2";
644                                         else {
645                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
646                                                 argument_errors = true;
647                                         }
648                                         if(!argument_errors) {
649                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
650                                                 int res = firm_be_option(arch_opt);
651                                                 if (res == 0)
652                                                         argument_errors = true;
653                                         }
654                                 } else if(strncmp(opt, "preferred-stack-boundary=", 25) == 0) {
655                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
656                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
657                                         int res = firm_be_option(arch_opt);
658                                         if (res == 0)
659                                                 argument_errors = true;
660                                 } else if(strcmp(opt, "omit-leaf-frame-pointer") == 0) {
661                                         set_be_option("omitleaffp=1");
662                                 } else if(strcmp(opt, "no-omit-leaf-frame-pointer") == 0) {
663                                         set_be_option("omitleaffp=0");
664                                 } else {
665                                         char *endptr;
666                                         long int value = strtol(opt, &endptr, 10);
667                                         if (*endptr != '\0') {
668                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
669                                                 argument_errors = true;
670                                         }
671                                         if (value != 16 && value != 32 && value != 64) {
672                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
673                                                 argument_errors = true;
674                                         } else {
675                                                 machine_size = (unsigned int)value;
676                                         }
677                                 }
678                         } else if (option[0] == '\0') {
679                                 if(input != NULL) {
680                                         fprintf(stderr, "error: multiple input files specified\n");
681                                         argument_errors = true;
682                                 } else {
683                                         input = arg;
684                                 }
685                         } else if(strcmp(option, "pg") == 0) {
686                                 set_be_option("gprof");
687                                 obstack_printf(&ldflags_obst, " -pg");
688                         } else if(strcmp(option, "pedantic") == 0) {
689                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
690                         } else if(strncmp(option, "std=", 4) == 0) {
691                                 if(strcmp(&option[4], "c99") == 0) {
692                                         c_mode = _C89|_C99;
693                                 } else if(strcmp(&option[4], "c89") == 0) {
694                                         c_mode = _C89;
695                                 } else if(strcmp(&option[4], "gnu99") == 0) {
696                                         c_mode = _C89|_C99|_GNUC;
697                                 } else if(strcmp(&option[4], "microsoft") == 0) {
698                                         c_mode = _C89|_C99|_MS;
699                                 } else
700                                         fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
701                         } else if(strcmp(option, "version") == 0) {
702                                 print_cparser_version();
703                         } else if (option[0] == '-') {
704                                 /* double dash option */
705                                 ++option;
706                                 if(strcmp(option, "gcc") == 0) {
707                                         c_mode |= _GNUC;
708                                 } else if(strcmp(option, "no-gcc") == 0) {
709                                         c_mode &= ~_GNUC;
710                                 } else if(strcmp(option, "ms") == 0) {
711                                         c_mode |= _MS;
712                                 } else if(strcmp(option, "no-ms") == 0) {
713                                         c_mode &= ~_MS;
714                                 } else if(strcmp(option, "signed-chars") == 0) {
715                                         char_is_signed = true;
716                                 } else if(strcmp(option, "unsigned-chars") == 0) {
717                                         char_is_signed = false;
718                                 } else if(strcmp(option, "strict") == 0) {
719                                         strict_mode = true;
720                                 } else if(strcmp(option, "lextest") == 0) {
721                                         mode = LexTest;
722                                 } else if(strcmp(option, "benchmark") == 0) {
723                                         mode = BenchmarkParser;
724                                 } else if(strcmp(option, "print-ast") == 0) {
725                                         mode = PrintAst;
726                                 } else if(strcmp(option, "print-implicit-cast") == 0) {
727                                         print_implicit_casts = true;
728                                 } else if(strcmp(option, "print-parenthesis") == 0) {
729                                         print_parenthesis = true;
730                                 } else if(strcmp(option, "print-fluffy") == 0) {
731                                         mode = PrintFluffy;
732                                 } else if(strcmp(option, "print-caml") == 0) {
733                                         mode = PrintCaml;
734                                 } else if(strcmp(option, "version") == 0) {
735                                         print_cparser_version();
736                                         exit(EXIT_SUCCESS);
737                                 } else if(strcmp(option, "dump-function") == 0) {
738                                         ++i;
739                                         if(i >= argc) {
740                                                 fprintf(stderr, "error: "
741                                                         "expected argument after '--dump-function'\n");
742                                                 argument_errors = true;
743                                                 break;
744                                         }
745                                         dumpfunction = argv[i];
746                                         mode         = CompileDump;
747                                 } else {
748                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
749                                         argument_errors = true;
750                                 }
751                         } else {
752                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
753                                 argument_errors = true;
754                         }
755                 } else {
756
757                         file_list_entry_t *entry
758                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
759                         entry->filename = arg;
760
761                         size_t len = strlen(arg);
762                         if (len < 2) {
763                                 if (arg[0] == '-') {
764                                         /* exception: '-' as name reads C from stdin */
765                                         entry->next = c_files;
766                                         c_files     = entry;
767                                         continue;
768                                 }
769                                 fprintf(stderr, "'%s': file format not recognized\n", input);
770                                 continue;
771                         }
772
773                         if (strcmp(arg+len-2, ".c") == 0
774                                         || strcmp(arg+len-2, ".h") == 0) {
775                                 entry->next = c_files;
776                                 c_files     = entry;
777                         } else if (strcmp(arg+len-2, ".s") == 0) {
778                                 entry->next = s_files;
779                                 s_files     = entry;
780                         } else if (strcmp(arg+len-2, ".o") == 0) {
781                                 entry->next = o_files;
782                                 o_files     = entry;
783                         } else {
784                                 fprintf(stderr, "'%s': file format not recognized\n", input);
785                         }
786                 }
787         }
788
789         if (c_files == NULL && s_files == NULL && o_files != NULL) {
790                 mode = Link;
791         } else if (c_files != NULL && c_files->next == NULL) {
792                 input = c_files->filename;
793         } else {
794                 if (c_files == NULL) {
795                         fprintf(stderr, "error: no input files specified\n");
796                 } else {
797                         fprintf(stderr, "error: multiple input files specified\n");
798                 }
799                 argument_errors = true;
800         }
801
802         /* we do the lowering in ast2firm */
803         firm_opt.lower_bitfields = FALSE;
804
805         if (help_displayed) {
806                 return !argument_errors;
807         }
808         if (argument_errors) {
809                 usage(argv[0]);
810                 return 1;
811         }
812
813         gen_firm_init();
814         init_symbol_table();
815         init_tokens();
816         init_types();
817         init_typehash();
818         init_basic_types();
819         init_lexer();
820         init_ast();
821         init_parser();
822         init_ast2firm();
823
824         FILE *out = NULL;
825         char  outnamebuf[4096];
826         if(outname == NULL) {
827                 switch(mode) {
828                 case BenchmarkParser:
829                 case PrintAst:
830                 case PrintFluffy:
831                 case PrintCaml:
832                 case LexTest:
833                 case PreprocessOnly:
834                         outname = "-";
835                         break;
836                 case ParseOnly:
837                         break;
838                 case Compile:
839                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
840                         outname = outnamebuf;
841                         break;
842                 case CompileAssemble:
843                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
844                         outname = outnamebuf;
845                         break;
846                 case CompileDump:
847                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
848                                         ".vcg");
849                         outname = outnamebuf;
850                         break;
851                 case Link:
852                 case CompileAssembleLink:
853 #ifdef _WIN32
854                         /* Windows compiler typically derive the output name from
855                            the first source file */
856                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".exe");
857                         outname = outnamebuf;
858 #else
859                         outname = "a.out";
860 #endif
861                         break;
862                 }
863         }
864
865         if (mode == Link) {
866                 obstack_1grow(&ldflags_obst, '\0');
867                 const char *flags = obstack_finish(&ldflags_obst);
868
869                 obstack_printf(&file_obst, "%s", LINKER);
870
871                 for (file_list_entry_t *entry = o_files; entry != NULL;
872                                 entry = entry->next) {
873                         obstack_printf(&file_obst, " %s", entry->filename);
874                 }
875
876                 obstack_printf(&file_obst, " -o %s %s", outname, flags);
877
878                 char *buf = obstack_finish(&file_obst);
879
880                 if(verbose) {
881                         puts(buf);
882                 }
883                 int err = system(buf);
884                 if(err != 0) {
885                         fprintf(stderr, "linker reported an error\n");
886                         exit(1);
887                 }
888                 return 0;
889         }
890
891         if(outname != NULL) {
892                 if(strcmp(outname, "-") == 0) {
893                         out = stdout;
894                 } else {
895                         out = fopen(outname, "w");
896                         if(out == NULL) {
897                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
898                                         strerror(errno));
899                                 return 1;
900                         }
901                 }
902         }
903
904         FILE *in;
905         if(input == NULL) {
906                 fprintf(stderr, "%s: no input files\n", argv[0]);
907                 return 1;
908         } else if(strcmp(input, "-") == 0) {
909                 in    = stdin;
910                 input = "<stdin>";
911         } else {
912                 in = fopen(input, "r");
913                 if(in == NULL) {
914                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
915                         return 1;
916                 }
917         }
918
919         if(mode == LexTest) {
920                 lextest(in, input);
921                 fclose(in);
922                 return 0;
923         }
924
925         FILE *preprocessed_in = preprocess(in, input);
926         if (mode == PreprocessOnly) {
927                 copy_file(out, preprocessed_in);
928                 return pclose(preprocessed_in);
929         }
930
931         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
932         int res = pclose(preprocessed_in);
933         if (res != 0) {
934                 return res;
935         }
936
937         if(error_count > 0) {
938                 /* parsing failed because of errors */
939                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count, warning_count);
940                 result = EXIT_FAILURE;
941         } else if(warning_count > 0) {
942                 fprintf(stderr, "%u warning(s)\n", warning_count);
943         }
944
945         if(mode == BenchmarkParser) {
946                 return result;
947         }
948
949         /* prints the AST even if errors occurred */
950         if(mode == PrintAst) {
951                 type_set_output(out);
952                 ast_set_output(out);
953                 print_ast(unit);
954                 return result;
955         }
956
957         /* cannot handle other modes with errors */
958         if(result != EXIT_SUCCESS)
959                 return result;
960
961         if(mode == PrintFluffy) {
962                 write_fluffy_decls(out, unit);
963         }
964         if (mode == PrintCaml) {
965                 write_caml_decls(out, unit);
966         }
967
968         translation_unit_to_firm(unit);
969
970         if(mode == ParseOnly) {
971                 return 0;
972         }
973
974         FILE *asm_out;
975         char  asm_tempfile[1024];
976         if(mode == CompileDump) {
977                 asm_out = NULL;
978                 firm_be_opt.selection = BE_NONE;
979         } else if(mode == Compile) {
980                 asm_out = out;
981         } else {
982                 asm_out
983                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
984         }
985         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
986
987         if(mode == CompileDump) {
988                 /* find irg */
989                 ident    *id     = new_id_from_str(dumpfunction);
990                 ir_graph *irg    = NULL;
991                 int       n_irgs = get_irp_n_irgs();
992                 for(int i = 0; i < n_irgs; ++i) {
993                         ir_graph *tirg   = get_irp_irg(i);
994                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
995                         if(irg_id == id) {
996                                 irg = tirg;
997                                 break;
998                         }
999                 }
1000
1001                 if(irg == NULL) {
1002                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
1003                         return 1;
1004                 }
1005
1006                 dump_ir_block_graph_file(irg, out);
1007                 fclose(out);
1008                 return 0;
1009         }
1010
1011         fclose(asm_out);
1012
1013         /* assemble assembler and create object file */
1014         char obj_tfile[1024];
1015         if(mode == CompileAssemble || mode == CompileAssembleLink) {
1016                 const char *obj_outfile;
1017                 if(mode == CompileAssemble) {
1018                         fclose(out);
1019                         obj_outfile = outname;
1020                 } else {
1021                         FILE *tempf
1022                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
1023                         fclose(tempf);
1024                         obj_outfile = obj_tfile;
1025                 }
1026
1027                 assemble(obj_outfile, asm_tempfile);
1028         }
1029
1030         /* link object file */
1031         if(mode == CompileAssembleLink) {
1032                 do_link(outname, obj_tfile);
1033         }
1034
1035         obstack_free(&cppflags_obst, NULL);
1036         obstack_free(&ldflags_obst, NULL);
1037         obstack_free(&file_obst, NULL);
1038
1039         exit_ast2firm();
1040         exit_parser();
1041         exit_ast();
1042         exit_lexer();
1043         exit_typehash();
1044         exit_types();
1045         exit_tokens();
1046         exit_symbol_table();
1047         return 0;
1048 }