b910ea4f6570e0c7d80e4426606542f7e276ac51
[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, bool to_stdout)
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         if(to_stdout) {
226                 int res = system(buf);
227                 exit(res);
228         } else {
229                 FILE *f = popen(buf, "r");
230                 if(f == NULL) {
231                         fprintf(stderr, "invoking preprocessor failed\n");
232                         exit(1);
233                 }
234                 return f;
235         }
236 }
237
238 static void do_link(const char *out, const char *in)
239 {
240         char buf[4096];
241         obstack_1grow(&ldflags_obst, '\0');
242         const char *flags = obstack_finish(&ldflags_obst);
243
244         snprintf(buf, sizeof(buf), LINKER " %s -o %s %s", flags, out, in);
245         if(verbose) {
246                 puts(buf);
247         }
248         int err = system(buf);
249         if(err != 0) {
250                 fprintf(stderr, "linker reported an error\n");
251                 exit(1);
252         }
253 }
254
255 static void assemble(const char *out, const char *in)
256 {
257         char buf[4096];
258
259         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
260         if(verbose) {
261                 puts(buf);
262         }
263
264         int err = system(buf);
265         if(err != 0) {
266                 fprintf(stderr, "assembler reported an error\n");
267                 exit(1);
268         }
269 }
270
271 static const char *try_dir(const char *dir)
272 {
273         if(dir == NULL)
274                 return dir;
275         if(access(dir, R_OK | W_OK | X_OK) == 0)
276                 return dir;
277         return NULL;
278 }
279
280 static const char *get_tempdir(void)
281 {
282         static const char *tmpdir = NULL;
283
284         if(tmpdir != NULL)
285                 return tmpdir;
286
287         if(tmpdir == NULL)
288                 tmpdir = try_dir(getenv("TMPDIR"));
289         if(tmpdir == NULL)
290                 tmpdir = try_dir(getenv("TMP"));
291         if(tmpdir == NULL)
292                 tmpdir = try_dir(getenv("TEMP"));
293
294 #ifdef P_tmpdir
295         if(tmpdir == NULL)
296                 tmpdir = try_dir(P_tmpdir);
297 #endif
298
299         if(tmpdir == NULL)
300                 tmpdir = try_dir("/var/tmp");
301         if(tmpdir == NULL)
302                 tmpdir = try_dir("/usr/tmp");
303         if(tmpdir == NULL)
304                 tmpdir = try_dir("/tmp");
305
306         if(tmpdir == NULL)
307                 tmpdir = ".";
308
309         return tmpdir;
310 }
311
312 #ifndef HAVE_MKSTEMP
313 /* cheap and nasty mkstemp replacement */
314 static int mkstemp(char *templ)
315 {
316         mktemp(templ);
317         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
318 }
319 #endif
320
321 /**
322  * an own version of tmpnam, which: writes in a buffer, appends a user specified
323  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
324  */
325 static FILE *make_temp_file(char *buffer, size_t buflen,
326                             const char *prefix, const char *suffix)
327 {
328         const char *tempdir = get_tempdir();
329
330         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
331         (void) suffix;
332         suffix = "";
333
334         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
335
336         int fd = mkstemp(buffer);
337         if(fd == -1) {
338                 fprintf(stderr, "couldn't create temporary file: %s\n",
339                         strerror(errno));
340                 exit(1);
341         }
342         FILE *out = fdopen(fd, "w");
343         if(out == NULL) {
344                 fprintf(stderr, "couldn't create temporary file FILE*\n");
345                 exit(1);
346         }
347
348         return out;
349 }
350
351 /**
352  * Do the necessary lowering for compound parameters.
353  */
354 void lower_compound_params(void)
355 {
356         lower_params_t params;
357
358         params.def_ptr_alignment    = 4;
359         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
360         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
361         params.find_pointer_type    = NULL;
362         params.ret_compound_in_regs = NULL;
363         lower_calls_with_compounds(&params);
364 }
365
366 typedef enum compile_mode_t {
367         BenchmarkParser,
368         PreprocessOnly,
369         ParseOnly,
370         Compile,
371         CompileDump,
372         CompileAssemble,
373         CompileAssembleLink,
374         LexTest,
375         PrintAst,
376         PrintFluffy,
377         PrintCaml,
378         Link
379 } compile_mode_t;
380
381 static void usage(const char *argv0)
382 {
383         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
384 }
385
386 static void print_cparser_version(void) {
387         firm_version_t ver;
388         firm_get_version(&ver);
389
390         printf("cparser (%s) using libFirm (%u.%u",
391                 cparser_REVISION, ver.major, ver.minor);
392         if(ver.revision[0] != 0) {
393                 putchar(' ');
394                 fputs(ver.revision, stdout);
395         }
396         if(ver.build[0] != 0) {
397                 putchar(' ');
398                 fputs(ver.build, stdout);
399         }
400         puts(")\n");
401 }
402
403 static void set_be_option(const char *arg)
404 {
405         int res = firm_be_option(arg);
406         (void) res;
407         assert(res);
408 }
409
410 static void set_option(const char *arg)
411 {
412         int res = firm_option(arg);
413         (void) res;
414         assert(res);
415 }
416
417 int main(int argc, char **argv)
418 {
419         initialize_firm();
420
421         const char        *input        = NULL;
422         const char        *outname      = NULL;
423         const char        *dumpfunction = NULL;
424         compile_mode_t     mode         = CompileAssembleLink;
425         int                opt_level    = 1;
426         int                result       = EXIT_SUCCESS;
427         char               cpu_arch[16] = "ia32";
428         file_list_entry_t *c_files      = NULL;
429         file_list_entry_t *s_files      = NULL;
430         file_list_entry_t *o_files      = NULL;
431         struct obstack     file_obst;
432
433         obstack_init(&cppflags_obst);
434         obstack_init(&ldflags_obst);
435         obstack_init(&file_obst);
436
437 #define GET_ARG_AFTER(def, args)                                             \
438         def = &arg[sizeof(args)-1];                                              \
439         if(def[0] == '\0') {                                                     \
440                 ++i;                                                                 \
441                 if(i >= argc) {                                                      \
442                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
443                         argument_errors = true;                                          \
444                         break;                                                           \
445                 }                                                                    \
446                 def = argv[i];                                                       \
447                 if(def[0] == '-' && def[1] != '\0') {                                \
448                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
449                         argument_errors = true;                                          \
450                         continue;                                                        \
451                 }                                                                    \
452         }
453
454 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
455
456         /* early options parsing (find out optimisation level) */
457         for(int i = 1; i < argc; ++i) {
458                 const char *arg = argv[i];
459                 if(arg[0] != '-')
460                         continue;
461
462                 const char *option = &arg[1];
463                 if(option[0] == 'O') {
464                         sscanf(&option[1], "%d", &opt_level);
465                 }
466         }
467
468         /* apply optimisation level */
469         switch(opt_level) {
470         case 0:
471                 set_option("no-opt");
472                 break;
473         case 1:
474                 set_option("no-inline");
475                 break;
476         default:
477         case 4:
478                 set_option("strict-aliasing");
479                 /* fallthrough */
480         case 3:
481                 set_option("cond-eval");
482                 set_option("if-conv");
483                 use_builtins = true;
484                 /* fallthrough */
485         case 2:
486                 set_option("inline");
487                 set_option("deconv");
488                 set_be_option("omitfp");
489                 break;
490         }
491
492         /* parse rest of options */
493         bool help_displayed  = false;
494         bool argument_errors = false;
495         for(int i = 1; i < argc; ++i) {
496                 const char *arg = argv[i];
497                 if(arg[0] == '-' && arg[1] != 0) {
498                         /* an option */
499                         const char *option = &arg[1];
500                         if(option[0] == 'o') {
501                                 GET_ARG_AFTER(outname, "-o");
502                         } else if(option[0] == 'g') {
503                                 set_be_option("debuginfo=stabs");
504                                 set_be_option("omitfp=no");
505                                 set_be_option("ia32-nooptcc=yes");
506                         } else if(SINGLE_OPTION('c')) {
507                                 mode = CompileAssemble;
508                         } else if(SINGLE_OPTION('E')) {
509                                 mode = PreprocessOnly;
510                         } else if(SINGLE_OPTION('S')) {
511                                 mode = Compile;
512                         } else if(option[0] == 'O') {
513                                 continue;
514                         } else if(option[0] == 'I') {
515                                 const char *opt;
516                                 GET_ARG_AFTER(opt, "-I");
517                                 obstack_printf(&cppflags_obst, " -I%s", opt);
518                         } else if(option[0] == 'D') {
519                                 const char *opt;
520                                 GET_ARG_AFTER(opt, "-D");
521                                 obstack_printf(&cppflags_obst, " -D%s", opt);
522                         } else if(option[0] == 'U') {
523                                 const char *opt;
524                                 GET_ARG_AFTER(opt, "-U");
525                                 obstack_printf(&cppflags_obst, " -U%s", opt);
526                         } else if(option[0] == 'l') {
527                                 const char *opt;
528                                 GET_ARG_AFTER(opt, "-l");
529                                 obstack_printf(&ldflags_obst, " -l%s", opt);
530                         } else if(option[0] == 'L') {
531                                 const char *opt;
532                                 GET_ARG_AFTER(opt, "-L");
533                                 obstack_printf(&ldflags_obst, " -L%s", opt);
534                         } else if(SINGLE_OPTION('v')) {
535                                 verbose = 1;
536                         } else if(SINGLE_OPTION('w')) {
537                                 inhibit_all_warnings = true;
538                         } else if(option[0] == 'f') {
539                                 const char *opt;
540                                 GET_ARG_AFTER(opt, "-f");
541
542                                 if(strcmp(opt, "syntax-only") == 0) {
543                                         mode = ParseOnly;
544                                 } else if(strcmp(opt, "omit-frame-pointer") == 0) {
545                                         set_be_option("omitfp");
546                                 } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
547                                         set_be_option("omitfp=no");
548                                 } else if(strcmp(opt, "fast-math") == 0
549                                                 || strcmp(opt, "unroll-loops") == 0
550                                                 || strcmp(opt, "expensive-optimizations") == 0
551                                                 || strcmp(opt, "no-common") == 0) {
552                                         fprintf(stderr, "ignoring gcc option '-f %s'\n", opt);
553                                 } else {
554                                         int res = firm_option(opt);
555                                         if (res == 0) {
556                                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
557                                                         opt);
558                                                 argument_errors = true;
559                                                 continue;
560                                         } else if (res == -1) {
561                                                 help_displayed = true;
562                                         }
563                                 }
564                         } else if(option[0] == 'b') {
565                                 const char *opt;
566                                 GET_ARG_AFTER(opt, "-b");
567                                 int res = firm_be_option(opt);
568                                 if (res == 0) {
569                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
570                                                 opt);
571                                         argument_errors = true;
572                                 } else if (res == -1) {
573                                         help_displayed = true;
574                                 } else {
575                                         if (strncmp(opt, "isa=", 4) == 0)
576                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
577                                 }
578                         } else if(option[0] == 'W') {
579                                 set_warning_opt(&option[1]);
580                         } else if(option[0] == 'm') {
581                                 /* -m options */
582                                 const char *opt;
583                                 char arch_opt[64];
584
585                                 GET_ARG_AFTER(opt, "-m");
586                                 if(strncmp(opt, "arch=", 5) == 0) {
587                                         GET_ARG_AFTER(opt, "-march=");
588                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
589                                         int res = firm_be_option(arch_opt);
590                                         if (res == 0)
591                                                 argument_errors = true;
592                                         else {
593                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
594                                                 int res = firm_be_option(arch_opt);
595                                                 if (res == 0)
596                                                         argument_errors = true;
597                                         }
598                                 } else if(strncmp(opt, "tune=", 5) == 0) {
599                                         GET_ARG_AFTER(opt, "-mtune=");
600                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
601                                         int res = firm_be_option(arch_opt);
602                                         if (res == 0)
603                                                 argument_errors = true;
604                                 } else if(strncmp(opt, "cpu=", 4) == 0) {
605                                         GET_ARG_AFTER(opt, "-mcpu=");
606                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
607                                         int res = firm_be_option(arch_opt);
608                                         if (res == 0)
609                                                 argument_errors = true;
610                                 } else if(strncmp(opt, "fpmath=", 7) == 0) {
611                                         GET_ARG_AFTER(opt, "-mfpmath=");
612                                         if(strcmp(opt, "387") == 0)
613                                                 opt = "x87";
614                                         else if(strcmp(opt, "sse") == 0)
615                                                 opt = "sse2";
616                                         else {
617                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
618                                                 argument_errors = true;
619                                         }
620                                         if(!argument_errors) {
621                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%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, "preferred-stack-boundary=", 25) == 0) {
627                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
628                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
629                                         int res = firm_be_option(arch_opt);
630                                         if (res == 0)
631                                                 argument_errors = true;
632                                 } else if(strcmp(opt, "omit-leaf-frame-pointer") == 0) {
633                                         set_be_option("omitleaffp=1");
634                                 } else if(strcmp(opt, "no-omit-leaf-frame-pointer") == 0) {
635                                         set_be_option("omitleaffp=0");
636                                 } else {
637                                         char *endptr;
638                                         long int value = strtol(opt, &endptr, 10);
639                                         if (*endptr != '\0') {
640                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
641                                                 argument_errors = true;
642                                         }
643                                         if (value != 16 && value != 32 && value != 64) {
644                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
645                                                 argument_errors = true;
646                                         } else {
647                                                 machine_size = (unsigned int)value;
648                                         }
649                                 }
650                         } else if (option[0] == '\0') {
651                                 if(input != NULL) {
652                                         fprintf(stderr, "error: multiple input files specified\n");
653                                         argument_errors = true;
654                                 } else {
655                                         input = arg;
656                                 }
657                         } else if(strcmp(option, "pg") == 0) {
658                                 set_be_option("gprof");
659                                 obstack_printf(&ldflags_obst, " -pg");
660                         } else if(strcmp(option, "pedantic") == 0) {
661                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
662                         } else if(strncmp(option, "std=", 4) == 0) {
663                                 if(strcmp(&option[4], "c99") == 0) {
664                                         c_mode = _C89|_C99;
665                                 } else if(strcmp(&option[4], "c89") == 0) {
666                                         c_mode = _C89;
667                                 } else if(strcmp(&option[4], "gnu99") == 0) {
668                                         c_mode = _C89|_C99|_GNUC;
669                                 } else if(strcmp(&option[4], "microsoft") == 0) {
670                                         c_mode = _C89|_C99|_MS;
671                                 } else
672                                         fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
673                         } else if(strcmp(option, "version") == 0) {
674                                 print_cparser_version();
675                         } else if (option[0] == '-') {
676                                 /* double dash option */
677                                 ++option;
678                                 if(strcmp(option, "gcc") == 0) {
679                                         c_mode |= _GNUC;
680                                 } else if(strcmp(option, "no-gcc") == 0) {
681                                         c_mode &= ~_GNUC;
682                                 } else if(strcmp(option, "ms") == 0) {
683                                         c_mode |= _MS;
684                                 } else if(strcmp(option, "no-ms") == 0) {
685                                         c_mode &= ~_MS;
686                                 } else if(strcmp(option, "signed-chars") == 0) {
687                                         char_is_signed = true;
688                                 } else if(strcmp(option, "unsigned-chars") == 0) {
689                                         char_is_signed = false;
690                                 } else if(strcmp(option, "strict") == 0) {
691                                         strict_mode = true;
692                                 } else if(strcmp(option, "lextest") == 0) {
693                                         mode = LexTest;
694                                 } else if(strcmp(option, "benchmark") == 0) {
695                                         mode = BenchmarkParser;
696                                 } else if(strcmp(option, "print-ast") == 0) {
697                                         mode = PrintAst;
698                                 } else if(strcmp(option, "print-implicit-cast") == 0) {
699                                         print_implicit_casts = true;
700                                 } else if(strcmp(option, "print-parenthesis") == 0) {
701                                         print_parenthesis = true;
702                                 } else if(strcmp(option, "print-fluffy") == 0) {
703                                         mode = PrintFluffy;
704                                 } else if(strcmp(option, "print-caml") == 0) {
705                                         mode = PrintCaml;
706                                 } else if(strcmp(option, "version") == 0) {
707                                         print_cparser_version();
708                                         exit(EXIT_SUCCESS);
709                                 } else if(strcmp(option, "dump-function") == 0) {
710                                         ++i;
711                                         if(i >= argc) {
712                                                 fprintf(stderr, "error: "
713                                                         "expected argument after '--dump-function'\n");
714                                                 argument_errors = true;
715                                                 break;
716                                         }
717                                         dumpfunction = argv[i];
718                                         mode         = CompileDump;
719                                 } else {
720                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
721                                         argument_errors = true;
722                                 }
723                         } else {
724                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
725                                 argument_errors = true;
726                         }
727                 } else {
728
729                         file_list_entry_t *entry
730                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
731                         entry->filename = arg;
732
733                         size_t len = strlen(arg);
734                         if (len < 2) {
735                                 if (arg[0] == '-') {
736                                         /* exception: '-' as name reads C from stdin */
737                                         entry->next = c_files;
738                                         c_files     = entry;
739                                         continue;
740                                 }
741                                 fprintf(stderr, "'%s': file format not recognized\n", input);
742                                 continue;
743                         }
744
745                         if (strcmp(arg+len-2, ".c") == 0
746                                         || strcmp(arg+len-2, ".h") == 0) {
747                                 entry->next = c_files;
748                                 c_files     = entry;
749                         } else if (strcmp(arg+len-2, ".s") == 0) {
750                                 entry->next = s_files;
751                                 s_files     = entry;
752                         } else if (strcmp(arg+len-2, ".o") == 0) {
753                                 entry->next = o_files;
754                                 o_files     = entry;
755                         } else {
756                                 fprintf(stderr, "'%s': file format not recognized\n", input);
757                         }
758                 }
759         }
760
761         if (c_files == NULL && s_files == NULL && o_files != NULL) {
762                 mode = Link;
763         } else if (c_files != NULL && c_files->next == NULL) {
764                 input = c_files->filename;
765         } else {
766                 if (c_files == NULL) {
767                         fprintf(stderr, "error: no input files specified\n");
768                 } else {
769                         fprintf(stderr, "error: multiple input files specified\n");
770                 }
771                 argument_errors = true;
772         }
773
774         /* we do the lowering in ast2firm */
775         firm_opt.lower_bitfields = FALSE;
776
777         if (help_displayed) {
778                 return !argument_errors;
779         }
780         if (argument_errors) {
781                 usage(argv[0]);
782                 return 1;
783         }
784
785         gen_firm_init();
786         init_symbol_table();
787         init_tokens();
788         init_types();
789         init_typehash();
790         init_basic_types();
791         init_lexer();
792         init_ast();
793         init_parser();
794         init_ast2firm();
795
796         FILE *out = NULL;
797         char  outnamebuf[4096];
798         if(outname == NULL) {
799                 switch(mode) {
800                 case BenchmarkParser:
801                 case PrintAst:
802                 case PrintFluffy:
803                 case PrintCaml:
804                 case LexTest:
805                         if(outname == NULL)
806                                 outname = "-";
807                         break;
808                 case PreprocessOnly:
809                         break;
810                 case ParseOnly:
811                         break;
812                 case Compile:
813                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
814                         outname = outnamebuf;
815                         break;
816                 case CompileAssemble:
817                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
818                         outname = outnamebuf;
819                         break;
820                 case CompileDump:
821                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
822                                         ".vcg");
823                         outname = outnamebuf;
824                         break;
825                 case Link:
826                 case CompileAssembleLink:
827 #ifdef _WIN32
828                         /* Windows compiler typically derive the output name from
829                            the first source file */
830                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".exe");
831                         outname = outnamebuf;
832 #else
833                         outname = "a.out";
834 #endif
835                         break;
836                 }
837         }
838
839         if (mode == Link) {
840                 obstack_1grow(&ldflags_obst, '\0');
841                 const char *flags = obstack_finish(&ldflags_obst);
842
843                 obstack_printf(&file_obst, "%s", LINKER);
844
845                 for (file_list_entry_t *entry = o_files; entry != NULL;
846                                 entry = entry->next) {
847                         obstack_printf(&file_obst, " %s", entry->filename);
848                 }
849
850                 obstack_printf(&file_obst, " -o %s %s", outname, flags);
851
852                 char *buf = obstack_finish(&file_obst);
853
854                 if(verbose) {
855                         puts(buf);
856                 }
857                 int err = system(buf);
858                 if(err != 0) {
859                         fprintf(stderr, "linker reported an error\n");
860                         exit(1);
861                 }
862                 return 0;
863         }
864
865         if(outname != NULL) {
866                 if(strcmp(outname, "-") == 0) {
867                         out = stdout;
868                 } else {
869                         out = fopen(outname, "w");
870                         if(out == NULL) {
871                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
872                                         strerror(errno));
873                                 return 1;
874                         }
875                 }
876         }
877
878         FILE *in;
879         if(input == NULL) {
880                 fprintf(stderr, "%s: no input files\n", argv[0]);
881                 return 1;
882         } else if(strcmp(input, "-") == 0) {
883                 in    = stdin;
884                 input = "<stdin>";
885         } else {
886                 in = fopen(input, "r");
887                 if(in == NULL) {
888                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
889                         return 1;
890                 }
891         }
892
893         if(mode == LexTest) {
894                 lextest(in, input);
895                 fclose(in);
896                 return 0;
897         }
898
899         FILE *preprocessed_in = preprocess(in, input, mode == PreprocessOnly);
900         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
901         int res = pclose(preprocessed_in);
902         if(res != 0) {
903                 return res;
904         }
905
906         if(error_count > 0) {
907                 /* parsing failed because of errors */
908                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count, warning_count);
909                 result = EXIT_FAILURE;
910         } else if(warning_count > 0) {
911                 fprintf(stderr, "%u warning(s)\n", warning_count);
912         }
913
914         if(mode == BenchmarkParser) {
915                 return result;
916         }
917
918         /* prints the AST even if errors occurred */
919         if(mode == PrintAst) {
920                 type_set_output(out);
921                 ast_set_output(out);
922                 print_ast(unit);
923                 return result;
924         }
925
926         /* cannot handle other modes with errors */
927         if(result != EXIT_SUCCESS)
928                 return result;
929
930         if(mode == PrintFluffy) {
931                 write_fluffy_decls(out, unit);
932         }
933         if (mode == PrintCaml) {
934                 write_caml_decls(out, unit);
935         }
936
937         translation_unit_to_firm(unit);
938
939         if(mode == ParseOnly) {
940                 return 0;
941         }
942
943         FILE *asm_out;
944         char  asm_tempfile[1024];
945         if(mode == CompileDump) {
946                 asm_out = NULL;
947                 firm_be_opt.selection = BE_NONE;
948         } else if(mode == Compile) {
949                 asm_out = out;
950         } else {
951                 asm_out
952                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
953         }
954         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
955
956         if(mode == CompileDump) {
957                 /* find irg */
958                 ident    *id     = new_id_from_str(dumpfunction);
959                 ir_graph *irg    = NULL;
960                 int       n_irgs = get_irp_n_irgs();
961                 for(int i = 0; i < n_irgs; ++i) {
962                         ir_graph *tirg   = get_irp_irg(i);
963                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
964                         if(irg_id == id) {
965                                 irg = tirg;
966                                 break;
967                         }
968                 }
969
970                 if(irg == NULL) {
971                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
972                         return 1;
973                 }
974
975                 dump_ir_block_graph_file(irg, out);
976                 fclose(out);
977                 return 0;
978         }
979
980         fclose(asm_out);
981
982         /* assemble assembler and create object file */
983         char obj_tfile[1024];
984         if(mode == CompileAssemble || mode == CompileAssembleLink) {
985                 const char *obj_outfile;
986                 if(mode == CompileAssemble) {
987                         fclose(out);
988                         obj_outfile = outname;
989                 } else {
990                         FILE *tempf
991                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
992                         fclose(tempf);
993                         obj_outfile = obj_tfile;
994                 }
995
996                 assemble(obj_outfile, asm_tempfile);
997         }
998
999         /* link object file */
1000         if(mode == CompileAssembleLink) {
1001                 do_link(outname, obj_tfile);
1002         }
1003
1004         obstack_free(&cppflags_obst, NULL);
1005         obstack_free(&ldflags_obst, NULL);
1006         obstack_free(&file_obst, NULL);
1007
1008         exit_ast2firm();
1009         exit_parser();
1010         exit_ast();
1011         exit_lexer();
1012         exit_typehash();
1013         exit_types();
1014         exit_tokens();
1015         exit_symbol_table();
1016         return 0;
1017 }