correct fix
[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 {
549                                         int res = firm_option(opt);
550                                         if (res == 0) {
551                                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
552                                                         opt);
553                                                 argument_errors = true;
554                                                 continue;
555                                         } else if (res == -1) {
556                                                 help_displayed = true;
557                                         }
558                                 }
559                         } else if(option[0] == 'b') {
560                                 const char *opt;
561                                 GET_ARG_AFTER(opt, "-b");
562                                 int res = firm_be_option(opt);
563                                 if (res == 0) {
564                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
565                                                 opt);
566                                         argument_errors = true;
567                                 } else if (res == -1) {
568                                         help_displayed = true;
569                                 } else {
570                                         if (strncmp(opt, "isa=", 4) == 0)
571                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
572                                 }
573                         } else if(option[0] == 'W') {
574                                 set_warning_opt(&option[1]);
575                         } else if(option[0] == 'm') {
576                                 /* -m options */
577                                 const char *opt;
578                                 char arch_opt[64];
579
580                                 GET_ARG_AFTER(opt, "-m");
581                                 if(strncmp(opt, "arch=", 5) == 0) {
582                                         GET_ARG_AFTER(opt, "-march=");
583                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
584                                         int res = firm_be_option(arch_opt);
585                                         if (res == 0)
586                                                 argument_errors = true;
587                                         else {
588                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
589                                                 int res = firm_be_option(arch_opt);
590                                                 if (res == 0)
591                                                         argument_errors = true;
592                                         }
593                                 } else if(strncmp(opt, "tune=", 5) == 0) {
594                                         GET_ARG_AFTER(opt, "-mtune=");
595                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
596                                         int res = firm_be_option(arch_opt);
597                                         if (res == 0)
598                                                 argument_errors = true;
599                                 } else if(strncmp(opt, "cpu=", 4) == 0) {
600                                         GET_ARG_AFTER(opt, "-mcpu=");
601                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
602                                         int res = firm_be_option(arch_opt);
603                                         if (res == 0)
604                                                 argument_errors = true;
605                                 } else if(strncmp(opt, "fpmath=", 7) == 0) {
606                                         GET_ARG_AFTER(opt, "-mfpmath=");
607                                         if(strcmp(opt, "387") == 0)
608                                                 opt = "x87";
609                                         else if(strcmp(opt, "sse") == 0)
610                                                 opt = "sse2";
611                                         else {
612                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
613                                                 argument_errors = true;
614                                         }
615                                         if(!argument_errors) {
616                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
617                                                 int res = firm_be_option(arch_opt);
618                                                 if (res == 0)
619                                                         argument_errors = true;
620                                         }
621                                 } else if(strncmp(opt, "preferred-stack-boundary=", 25) == 0) {
622                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
623                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
624                                         int res = firm_be_option(arch_opt);
625                                         if (res == 0)
626                                                 argument_errors = true;
627                                 } else if(strcmp(opt, "omit-leaf-frame-pointer") == 0) {
628                                         set_be_option("omitleaffp=1");
629                                 } else if(strcmp(opt, "no-omit-leaf-frame-pointer") == 0) {
630                                         set_be_option("omitleaffp=0");
631                                 } else {
632                                         char *endptr;
633                                         long int value = strtol(opt, &endptr, 10);
634                                         if (*endptr != '\0') {
635                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
636                                                 argument_errors = true;
637                                         }
638                                         if (value != 16 && value != 32 && value != 64) {
639                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
640                                                 argument_errors = true;
641                                         } else {
642                                                 machine_size = (unsigned int)value;
643                                         }
644                                 }
645                         } else if (option[0] == '\0') {
646                                 if(input != NULL) {
647                                         fprintf(stderr, "error: multiple input files specified\n");
648                                         argument_errors = true;
649                                 } else {
650                                         input = arg;
651                                 }
652                         } else if(strcmp(option, "pg") == 0) {
653                                 set_be_option("gprof");
654                                 obstack_printf(&ldflags_obst, " -pg");
655                         } else if(strcmp(option, "pedantic") == 0) {
656                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
657                         } else if(strncmp(option, "std=", 4) == 0) {
658                                 if(strcmp(&option[4], "c99") == 0) {
659                                         c_mode = _C89|_C99;
660                                 } else if(strcmp(&option[4], "c89") == 0) {
661                                         c_mode = _C89;
662                                 } else if(strcmp(&option[4], "gnu99") == 0) {
663                                         c_mode = _C89|_C99|_GNUC;
664                                 } else if(strcmp(&option[4], "microsoft") == 0) {
665                                         c_mode = _C89|_C99|_MS;
666                                 } else
667                                         fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
668                         } else if(strcmp(option, "version") == 0) {
669                                 print_cparser_version();
670                         } else if (option[0] == '-') {
671                                 /* double dash option */
672                                 ++option;
673                                 if(strcmp(option, "gcc") == 0) {
674                                         c_mode |= _GNUC;
675                                 } else if(strcmp(option, "no-gcc") == 0) {
676                                         c_mode &= ~_GNUC;
677                                 } else if(strcmp(option, "ms") == 0) {
678                                         c_mode |= _MS;
679                                 } else if(strcmp(option, "no-ms") == 0) {
680                                         c_mode &= ~_MS;
681                                 } else if(strcmp(option, "signed-chars") == 0) {
682                                         char_is_signed = true;
683                                 } else if(strcmp(option, "unsigned-chars") == 0) {
684                                         char_is_signed = false;
685                                 } else if(strcmp(option, "strict") == 0) {
686                                         strict_mode = true;
687                                 } else if(strcmp(option, "lextest") == 0) {
688                                         mode = LexTest;
689                                 } else if(strcmp(option, "benchmark") == 0) {
690                                         mode = BenchmarkParser;
691                                 } else if(strcmp(option, "print-ast") == 0) {
692                                         mode = PrintAst;
693                                 } else if(strcmp(option, "print-implicit-cast") == 0) {
694                                         print_implicit_casts = true;
695                                 } else if(strcmp(option, "print-parenthesis") == 0) {
696                                         print_parenthesis = true;
697                                 } else if(strcmp(option, "print-fluffy") == 0) {
698                                         mode = PrintFluffy;
699                                 } else if(strcmp(option, "print-caml") == 0) {
700                                         mode = PrintCaml;
701                                 } else if(strcmp(option, "version") == 0) {
702                                         print_cparser_version();
703                                         exit(EXIT_SUCCESS);
704                                 } else if(strcmp(option, "dump-function") == 0) {
705                                         ++i;
706                                         if(i >= argc) {
707                                                 fprintf(stderr, "error: "
708                                                         "expected argument after '--dump-function'\n");
709                                                 argument_errors = true;
710                                                 break;
711                                         }
712                                         dumpfunction = argv[i];
713                                         mode         = CompileDump;
714                                 } else {
715                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
716                                         argument_errors = true;
717                                 }
718                         } else {
719                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
720                                 argument_errors = true;
721                         }
722                 } else {
723
724                         file_list_entry_t *entry
725                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
726                         entry->filename = arg;
727
728                         size_t len = strlen(arg);
729                         if (len < 2) {
730                                 if (arg[0] == '-') {
731                                         /* exception: '-' as name reads C from stdin */
732                                         entry->next = c_files;
733                                         c_files     = entry;
734                                         continue;
735                                 }
736                                 fprintf(stderr, "'%s': file format not recognized\n", input);
737                                 continue;
738                         }
739
740                         if (strcmp(arg+len-2, ".c") == 0
741                                         || strcmp(arg+len-2, ".h") == 0) {
742                                 entry->next = c_files;
743                                 c_files     = entry;
744                         } else if (strcmp(arg+len-2, ".s") == 0) {
745                                 entry->next = s_files;
746                                 s_files     = entry;
747                         } else if (strcmp(arg+len-2, ".o") == 0) {
748                                 entry->next = o_files;
749                                 o_files     = entry;
750                         } else {
751                                 fprintf(stderr, "'%s': file format not recognized\n", input);
752                         }
753                 }
754         }
755
756         if (c_files == NULL && s_files == NULL && o_files != NULL) {
757                 mode = Link;
758         } else if (c_files != NULL && c_files->next == NULL) {
759                 input = c_files->filename;
760         } else {
761                 if (c_files == NULL) {
762                         fprintf(stderr, "error: no input files specified\n");
763                 } else {
764                         fprintf(stderr, "error: multiple input files specified\n");
765                 }
766                 argument_errors = true;
767         }
768
769         /* we do the lowering in ast2firm */
770         firm_opt.lower_bitfields = FALSE;
771
772         if (help_displayed) {
773                 return !argument_errors;
774         }
775         if (argument_errors) {
776                 usage(argv[0]);
777                 return 1;
778         }
779
780         gen_firm_init();
781         init_symbol_table();
782         init_tokens();
783         init_types();
784         init_typehash();
785         init_basic_types();
786         init_lexer();
787         init_ast();
788         init_parser();
789         init_ast2firm();
790
791         FILE *out = NULL;
792         char  outnamebuf[4096];
793         if(outname == NULL) {
794                 switch(mode) {
795                 case BenchmarkParser:
796                 case PrintAst:
797                 case PrintFluffy:
798                 case PrintCaml:
799                 case LexTest:
800                         if(outname == NULL)
801                                 outname = "-";
802                         break;
803                 case PreprocessOnly:
804                         break;
805                 case ParseOnly:
806                         break;
807                 case Compile:
808                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
809                         outname = outnamebuf;
810                         break;
811                 case CompileAssemble:
812                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
813                         outname = outnamebuf;
814                         break;
815                 case CompileDump:
816                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
817                                         ".vcg");
818                         outname = outnamebuf;
819                         break;
820                 case Link:
821                 case CompileAssembleLink:
822 #ifdef _WIN32
823                         /* Windows compiler typically derive the output name from
824                            the first source file */
825                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".exe");
826                         outname = outnamebuf;
827 #else
828                         outname = "a.out";
829 #endif
830                         break;
831                 }
832         }
833
834         if (mode == Link) {
835                 obstack_1grow(&ldflags_obst, '\0');
836                 const char *flags = obstack_finish(&ldflags_obst);
837
838                 obstack_printf(&file_obst, "%s", LINKER);
839
840                 for (file_list_entry_t *entry = o_files; entry != NULL;
841                                 entry = entry->next) {
842                         obstack_printf(&file_obst, " %s", entry->filename);
843                 }
844
845                 obstack_printf(&file_obst, " -o %s %s", outname, flags);
846
847                 char *buf = obstack_finish(&file_obst);
848
849                 if(verbose) {
850                         puts(buf);
851                 }
852                 int err = system(buf);
853                 if(err != 0) {
854                         fprintf(stderr, "linker reported an error\n");
855                         exit(1);
856                 }
857                 return 0;
858         }
859
860         if(outname != NULL) {
861                 if(strcmp(outname, "-") == 0) {
862                         out = stdout;
863                 } else {
864                         out = fopen(outname, "w");
865                         if(out == NULL) {
866                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
867                                         strerror(errno));
868                                 return 1;
869                         }
870                 }
871         }
872
873         FILE *in;
874         if(input == NULL) {
875                 fprintf(stderr, "%s: no input files\n", argv[0]);
876                 return 1;
877         } else if(strcmp(input, "-") == 0) {
878                 in    = stdin;
879                 input = "<stdin>";
880         } else {
881                 in = fopen(input, "r");
882                 if(in == NULL) {
883                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
884                         return 1;
885                 }
886         }
887
888         if(mode == LexTest) {
889                 lextest(in, input);
890                 fclose(in);
891                 return 0;
892         }
893
894         FILE *preprocessed_in = preprocess(in, input, mode == PreprocessOnly);
895         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
896         int res = pclose(preprocessed_in);
897         if(res != 0) {
898                 return res;
899         }
900
901         if(error_count > 0) {
902                 /* parsing failed because of errors */
903                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count, warning_count);
904                 result = EXIT_FAILURE;
905         } else if(warning_count > 0) {
906                 fprintf(stderr, "%u warning(s)\n", warning_count);
907         }
908
909         if(mode == BenchmarkParser) {
910                 return result;
911         }
912
913         /* prints the AST even if errors occurred */
914         if(mode == PrintAst) {
915                 type_set_output(out);
916                 ast_set_output(out);
917                 print_ast(unit);
918                 return result;
919         }
920
921         /* cannot handle other modes with errors */
922         if(result != EXIT_SUCCESS)
923                 return result;
924
925         if(mode == PrintFluffy) {
926                 write_fluffy_decls(out, unit);
927         }
928         if (mode == PrintCaml) {
929                 write_caml_decls(out, unit);
930         }
931
932         translation_unit_to_firm(unit);
933
934         if(mode == ParseOnly) {
935                 return 0;
936         }
937
938         FILE *asm_out;
939         char  asm_tempfile[1024];
940         if(mode == CompileDump) {
941                 asm_out = NULL;
942                 firm_be_opt.selection = BE_NONE;
943         } else if(mode == Compile) {
944                 asm_out = out;
945         } else {
946                 asm_out
947                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
948         }
949         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
950
951         if(mode == CompileDump) {
952                 /* find irg */
953                 ident    *id     = new_id_from_str(dumpfunction);
954                 ir_graph *irg    = NULL;
955                 int       n_irgs = get_irp_n_irgs();
956                 for(int i = 0; i < n_irgs; ++i) {
957                         ir_graph *tirg   = get_irp_irg(i);
958                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
959                         if(irg_id == id) {
960                                 irg = tirg;
961                                 break;
962                         }
963                 }
964
965                 if(irg == NULL) {
966                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
967                         return 1;
968                 }
969
970                 dump_ir_block_graph_file(irg, out);
971                 fclose(out);
972                 return 0;
973         }
974
975         fclose(asm_out);
976
977         /* assemble assembler and create object file */
978         char obj_tfile[1024];
979         if(mode == CompileAssemble || mode == CompileAssembleLink) {
980                 const char *obj_outfile;
981                 if(mode == CompileAssemble) {
982                         fclose(out);
983                         obj_outfile = outname;
984                 } else {
985                         FILE *tempf
986                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
987                         fclose(tempf);
988                         obj_outfile = obj_tfile;
989                 }
990
991                 assemble(obj_outfile, asm_tempfile);
992         }
993
994         /* link object file */
995         if(mode == CompileAssembleLink) {
996                 do_link(outname, obj_tfile);
997         }
998
999         obstack_free(&cppflags_obst, NULL);
1000         obstack_free(&ldflags_obst, NULL);
1001         obstack_free(&file_obst, NULL);
1002
1003         exit_ast2firm();
1004         exit_parser();
1005         exit_ast();
1006         exit_lexer();
1007         exit_typehash();
1008         exit_types();
1009         exit_tokens();
1010         exit_symbol_table();
1011         return 0;
1012 }