- 2009 patch
[cparser] / main.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2009 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 #define unlink(filename)         _unlink(filename)
54
55 #else
56 #include <unistd.h>
57 #define HAVE_MKSTEMP
58 #endif
59
60 #include <libfirm/firm.h>
61 #include <libfirm/be.h>
62
63 #include "lexer.h"
64 #include "token_t.h"
65 #include "types.h"
66 #include "type_hash.h"
67 #include "parser.h"
68 #include "type_t.h"
69 #include "ast2firm.h"
70 #include "diagnostic.h"
71 #include "lang_features.h"
72 #include "driver/firm_opt.h"
73 #include "driver/firm_cmdline.h"
74 #include "adt/error.h"
75 #include "wrappergen/write_fluffy.h"
76 #include "wrappergen/write_caml.h"
77 #include "wrappergen/write_jna.h"
78 #include "revision.h"
79 #include "warning.h"
80 #include "mangle.h"
81
82 #ifndef PREPROCESSOR
83 #ifndef __WIN32__
84 #define PREPROCESSOR "gcc -E -std=c99 -m32 -U__STRICT_ANSI__"
85 #else
86 #define PREPROCESSOR "cpp -std=c99 -m32 -U__STRICT_ANSI__"
87 #endif
88 #endif
89
90 #ifndef LINKER
91 #define LINKER    "gcc -m32"
92 #endif
93
94 #ifndef ASSEMBLER
95 #ifdef __APPLE__
96 #define ASSEMBLER "gcc -c -xassembler"
97 #else
98 #define ASSEMBLER "as --32"
99 #endif
100 #endif
101
102 /** The current c mode/dialect. */
103 unsigned int c_mode = _C89 | _ANSI | _C99 | _GNUC;
104
105 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
106 unsigned int machine_size = 32;
107
108 /** true if the char type is signed. */
109 bool char_is_signed = true;
110
111 /** true for strict language checking. */
112 bool strict_mode = false;
113
114 /** use builtins for some libc functions */
115 bool use_builtins = false;
116
117 /** we have extern function with const attribute. */
118 bool have_const_functions = false;
119
120 atomic_type_kind_t wchar_atomic_kind = ATOMIC_TYPE_INT;
121
122 /* to switch on printing of implicit casts */
123 extern bool print_implicit_casts;
124
125 /* to switch on printing of parenthesis to indicate operator precedence */
126 extern bool print_parenthesis;
127
128 static int             verbose;
129 static struct obstack  cppflags_obst, ldflags_obst;
130 static char            dep_target[1024];
131 static const char     *outname;
132
133 typedef struct file_list_entry_t file_list_entry_t;
134
135 typedef enum filetype_t {
136         FILETYPE_AUTODETECT,
137         FILETYPE_C,
138         FILETYPE_PREPROCESSED_C,
139         FILETYPE_CXX,
140         FILETYPE_PREPROCESSED_CXX,
141         FILETYPE_ASSEMBLER,
142         FILETYPE_PREPROCESSED_ASSEMBLER,
143         FILETYPE_OBJECT,
144         FILETYPE_IR,
145         FILETYPE_UNKNOWN
146 } filetype_t;
147
148 struct file_list_entry_t {
149         const char  *name; /**< filename or NULL for stdin */
150         filetype_t   type;
151         file_list_entry_t *next;
152 };
153
154 static file_list_entry_t *temp_files;
155
156 #if defined(_DEBUG) || defined(FIRM_DEBUG)
157 /**
158  * Debug printf implementation.
159  *
160  * @param fmt  printf style format parameter
161  */
162 void dbg_printf(const char *fmt, ...)
163 {
164         va_list list;
165
166         if (firm_dump.debug_print) {
167                 va_start(list, fmt);
168                 vprintf(fmt, list);
169                 va_end(list);
170         }  /* if */
171 }
172 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
173
174 static void initialize_firm(void)
175 {
176         firm_early_init();
177
178         dump_consts_local(1);
179         dump_keepalive_edges(1);
180 }
181
182 static void get_output_name(char *buf, size_t buflen, const char *inputname,
183                             const char *newext)
184 {
185         if (inputname == NULL)
186                 inputname = "a";
187
188         char const *const last_slash = strrchr(inputname, '/');
189         char const *const filename   =
190                 last_slash != NULL ? last_slash + 1 : inputname;
191         char const *const last_dot   = strrchr(filename, '.');
192         char const *const name_end   =
193                 last_dot != NULL ? last_dot : strchr(filename, '\0');
194
195         int const len = snprintf(buf, buflen, "%.*s%s",
196                         (int)(name_end - filename), filename, newext);
197 #ifdef _WIN32
198         if (len < 0 || buflen <= (size_t)len)
199 #else
200         if (buflen <= (size_t)len)
201 #endif
202                 panic("filename too long");
203 }
204
205 #include "builtins.h"
206
207 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
208 {
209         start_parsing();
210
211         if (use_builtins) {
212                 lexer_open_buffer(builtins, sizeof(builtins)-1, "<builtin>");
213                 parse();
214         }
215
216         lexer_open_stream(in, input_name);
217         parse();
218
219         translation_unit_t *unit = finish_parsing();
220         return unit;
221 }
222
223 static void lextest(FILE *in, const char *fname)
224 {
225         lexer_open_stream(in, fname);
226
227         do {
228                 lexer_next_preprocessing_token();
229                 print_token(stdout, &lexer_token);
230                 putchar('\n');
231         } while (lexer_token.type != T_EOF);
232 }
233
234 static void add_flag(struct obstack *obst, const char *format, ...)
235 {
236         char buf[65536];
237         va_list ap;
238
239         va_start(ap, format);
240 #ifdef _WIN32
241         int len =
242 #endif
243                 vsnprintf(buf, sizeof(buf), format, ap);
244         va_end(ap);
245
246         obstack_1grow(obst, ' ');
247 #ifdef _WIN32
248         obstack_1grow(obst, '"');
249         obstack_grow(obst, buf, len);
250         obstack_1grow(obst, '"');
251 #else
252         /* escape stuff... */
253         for (char *c = buf; *c != '\0'; ++c) {
254                 switch(*c) {
255                 case ' ':
256                 case '"':
257                 case '$':
258                 case '&':
259                 case '(':
260                 case ')':
261                 case ';':
262                 case '<':
263                 case '>':
264                 case '\'':
265                 case '\\':
266                 case '\n':
267                 case '\r':
268                 case '\t':
269                 case '`':
270                 case '|':
271                         obstack_1grow(obst, '\\');
272                         /* FALLTHROUGH */
273                 default:
274                         obstack_1grow(obst, *c);
275                         break;
276                 }
277         }
278 #endif
279 }
280
281 static const char *type_to_string(type_t *type)
282 {
283         assert(type->kind == TYPE_ATOMIC);
284         return get_atomic_kind_name(type->atomic.akind);
285 }
286
287 static FILE *preprocess(const char *fname)
288 {
289         obstack_1grow(&cppflags_obst, '\0');
290         const char *flags = obstack_finish(&cppflags_obst);
291
292         obstack_printf(&cppflags_obst, "%s", PREPROCESSOR);
293
294         /* setup default defines */
295         add_flag(&cppflags_obst, "-U__WCHAR_TYPE__");
296         add_flag(&cppflags_obst, "-D__WCHAR_TYPE__=%s", type_to_string(type_wchar_t));
297         add_flag(&cppflags_obst, "-U__SIZE_TYPE__");
298         add_flag(&cppflags_obst, "-D__SIZE_TYPE__=%s", type_to_string(type_size_t));
299
300         /* TODO hack... */
301         add_flag(&cppflags_obst, "-D__builtin_abort=abort");
302         add_flag(&cppflags_obst, "-D__builtin_abs=abs");
303         add_flag(&cppflags_obst, "-D__builtin_exit=exit");
304         add_flag(&cppflags_obst, "-D__builtin_malloc=malloc");
305         add_flag(&cppflags_obst, "-D__builtin_memcmp=memcmp");
306         add_flag(&cppflags_obst, "-D__builtin_memcpy=memcpy");
307         add_flag(&cppflags_obst, "-D__builtin_memset=memset");
308         add_flag(&cppflags_obst, "-D__builtin_strlen=strlen");
309         add_flag(&cppflags_obst, "-D__builtin_strcmp=strcmp");
310         add_flag(&cppflags_obst, "-D__builtin_strcpy=strcpy");
311
312         /* handle dependency generation */
313         if (dep_target[0] != '\0') {
314                 add_flag(&cppflags_obst, "-MF");
315                 add_flag(&cppflags_obst, dep_target);
316                 if (outname != NULL) {
317                                 add_flag(&cppflags_obst, "-MQ");
318                                 add_flag(&cppflags_obst, outname);
319                 }
320         }
321         if (flags[0] != '\0') {
322                 size_t len = strlen(flags);
323                 obstack_1grow(&cppflags_obst, ' ');
324                 obstack_grow(&cppflags_obst, flags, len);
325         }
326         add_flag(&cppflags_obst, fname);
327
328         obstack_1grow(&cppflags_obst, '\0');
329         const char *buf = obstack_finish(&cppflags_obst);
330         if (verbose) {
331                 puts(buf);
332         }
333
334         FILE *f = popen(buf, "r");
335         if (f == NULL) {
336                 fprintf(stderr, "invoking preprocessor failed\n");
337                 exit(1);
338         }
339
340         return f;
341 }
342
343 static void assemble(const char *out, const char *in)
344 {
345         char buf[65536];
346
347         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
348         if (verbose) {
349                 puts(buf);
350         }
351
352         int err = system(buf);
353         if (err != 0) {
354                 fprintf(stderr, "assembler reported an error\n");
355                 exit(1);
356         }
357 }
358
359 static void print_file_name(const char *file)
360 {
361         add_flag(&ldflags_obst, "-print-file-name=%s", file);
362
363         obstack_1grow(&ldflags_obst, '\0');
364         const char *flags = obstack_finish(&ldflags_obst);
365
366         /* construct commandline */
367         obstack_printf(&ldflags_obst, "%s ", LINKER);
368         obstack_printf(&ldflags_obst, "%s", flags);
369         obstack_1grow(&ldflags_obst, '\0');
370
371         char *commandline = obstack_finish(&ldflags_obst);
372
373         if (verbose) {
374                 puts(commandline);
375         }
376         int err = system(commandline);
377         if (err != EXIT_SUCCESS) {
378                 fprintf(stderr, "linker reported an error\n");
379                 exit(1);
380         }
381 }
382
383 static const char *try_dir(const char *dir)
384 {
385         if (dir == NULL)
386                 return dir;
387         if (access(dir, R_OK | W_OK | X_OK) == 0)
388                 return dir;
389         return NULL;
390 }
391
392 static const char *get_tempdir(void)
393 {
394         static const char *tmpdir = NULL;
395
396         if (tmpdir != NULL)
397                 return tmpdir;
398
399         if (tmpdir == NULL)
400                 tmpdir = try_dir(getenv("TMPDIR"));
401         if (tmpdir == NULL)
402                 tmpdir = try_dir(getenv("TMP"));
403         if (tmpdir == NULL)
404                 tmpdir = try_dir(getenv("TEMP"));
405
406 #ifdef P_tmpdir
407         if (tmpdir == NULL)
408                 tmpdir = try_dir(P_tmpdir);
409 #endif
410
411         if (tmpdir == NULL)
412                 tmpdir = try_dir("/var/tmp");
413         if (tmpdir == NULL)
414                 tmpdir = try_dir("/usr/tmp");
415         if (tmpdir == NULL)
416                 tmpdir = try_dir("/tmp");
417
418         if (tmpdir == NULL)
419                 tmpdir = ".";
420
421         return tmpdir;
422 }
423
424 #ifndef HAVE_MKSTEMP
425 /* cheap and nasty mkstemp replacement */
426 static int mkstemp(char *templ)
427 {
428         mktemp(templ);
429         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
430 }
431 #endif
432
433 /**
434  * an own version of tmpnam, which: writes in a buffer, emits no warnings
435  * during linking (like glibc/gnu ld do for tmpnam)...
436  */
437 static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix)
438 {
439         const char *tempdir = get_tempdir();
440
441         snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix);
442
443         int fd = mkstemp(buffer);
444         if (fd == -1) {
445                 fprintf(stderr, "couldn't create temporary file: %s\n",
446                         strerror(errno));
447                 exit(1);
448         }
449         FILE *out = fdopen(fd, "w");
450         if (out == NULL) {
451                 fprintf(stderr, "couldn't create temporary file FILE*\n");
452                 exit(1);
453         }
454
455         file_list_entry_t *entry = xmalloc(sizeof(*entry));
456         memset(entry, 0, sizeof(*entry));
457
458         size_t  name_len = strlen(buffer) + 1;
459         char   *name     = malloc(name_len);
460         memcpy(name, buffer, name_len);
461         entry->name      = name;
462
463         entry->next = temp_files;
464         temp_files  = entry;
465
466         return out;
467 }
468
469 static void free_temp_files(void)
470 {
471         file_list_entry_t *entry = temp_files;
472         file_list_entry_t *next;
473         for ( ; entry != NULL; entry = next) {
474                 next = entry->next;
475
476                 unlink(entry->name);
477                 free((char*) entry->name);
478                 free(entry);
479         }
480         temp_files = NULL;
481 }
482
483 /**
484  * Do the necessary lowering for compound parameters.
485  */
486 void lower_compound_params(void)
487 {
488         lower_params_t params;
489
490         params.def_ptr_alignment    = 4;
491         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
492         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
493         params.find_pointer_type    = NULL;
494         params.ret_compound_in_regs = NULL;
495         lower_calls_with_compounds(&params);
496 }
497
498 typedef enum compile_mode_t {
499         BenchmarkParser,
500         PreprocessOnly,
501         ParseOnly,
502         Compile,
503         CompileDump,
504         CompileExportIR,
505         CompileAssemble,
506         CompileAssembleLink,
507         LexTest,
508         PrintAst,
509         PrintFluffy,
510         PrintCaml,
511         PrintJna
512 } compile_mode_t;
513
514 static void usage(const char *argv0)
515 {
516         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
517 }
518
519 static void print_cparser_version(void)
520 {
521         printf("cparser (%s) using libFirm (%u.%u",
522                cparser_REVISION, ir_get_version_major(),
523                ir_get_version_minor());
524
525         const char *revision = ir_get_version_revision();
526         if (revision[0] != 0) {
527                 putchar(' ');
528                 fputs(revision, stdout);
529         }
530
531         const char *build = ir_get_version_build();
532         if (build[0] != 0) {
533                 putchar(' ');
534                 fputs(build, stdout);
535         }
536         puts(")");
537         puts("This is free software; see the source for copying conditions.  There is NO\n"
538              "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
539 }
540
541 static void set_be_option(const char *arg)
542 {
543         int res = firm_be_option(arg);
544         (void) res;
545         assert(res);
546 }
547
548 static void set_option(const char *arg)
549 {
550         int res = firm_option(arg);
551         (void) res;
552         assert(res);
553 }
554
555 static void copy_file(FILE *dest, FILE *input)
556 {
557         char buf[16384];
558
559         while (!feof(input) && !ferror(dest)) {
560                 size_t read = fread(buf, 1, sizeof(buf), input);
561                 if (fwrite(buf, 1, read, dest) != read) {
562                         perror("couldn't write output");
563                 }
564         }
565 }
566
567 static inline bool streq(char const* a, char const* b)
568 {
569         return strcmp(a, b) == 0;
570 }
571
572 static inline bool strstart(char const* str, char const* start)
573 {
574         do {
575                 if (*start == '\0')
576                         return true;
577         } while (*str++ == *start++);
578         return false;
579 }
580
581 static FILE *open_file(const char *filename)
582 {
583         if (streq(filename, "-")) {
584                 return stdin;
585         }
586
587         FILE *in = fopen(filename, "r");
588         if (in == NULL) {
589                 fprintf(stderr, "Couldn't open '%s': %s\n", filename,
590                                 strerror(errno));
591                 exit(1);
592         }
593
594         return in;
595 }
596
597 static filetype_t get_filetype_from_string(const char *string)
598 {
599         if (streq(string, "c") || streq(string, "c-header"))
600                 return FILETYPE_C;
601         if (streq(string, "c++") || streq(string, "c++-header"))
602                 return FILETYPE_CXX;
603         if (streq(string, "assembler"))
604                 return FILETYPE_PREPROCESSED_ASSEMBLER;
605         if (streq(string, "assembler-with-cpp"))
606                 return FILETYPE_ASSEMBLER;
607         if (streq(string, "none"))
608                 return FILETYPE_AUTODETECT;
609
610         return FILETYPE_UNKNOWN;
611 }
612
613 static void init_os_support(void)
614 {
615         /* OS option must be set to the backend */
616         switch (firm_opt.os_support) {
617         case OS_SUPPORT_MINGW:
618                 set_be_option("ia32-gasmode=mingw");
619                 wchar_atomic_kind = ATOMIC_TYPE_USHORT;
620                 break;
621         case OS_SUPPORT_LINUX:
622                 set_be_option("ia32-gasmode=elf");
623                 break;
624         case OS_SUPPORT_MACHO:
625                 set_be_option("ia32-gasmode=macho");
626                 set_be_option("ia32-stackalign=4");
627                 set_be_option("pic");
628                 break;
629         }
630 }
631
632 typedef enum lang_standard_t {
633         STANDARD_DEFAULT, /* gnu99 (for C, GCC does gnu89) or gnu++98 (for C++) */
634         STANDARD_ANSI,    /* c89 (for C) or c++98 (for C++) */
635         STANDARD_C89,     /* ISO C90 (sic) */
636         STANDARD_C90,     /* ISO C90 as modified in amendment 1 */
637         STANDARD_C99,     /* ISO C99 */
638         STANDARD_GNU89,   /* ISO C90 plus GNU extensions (including some C99) */
639         STANDARD_GNU99,   /* ISO C99 plus GNU extensions */
640         STANDARD_CXX98,   /* ISO C++ 1998 plus amendments */
641         STANDARD_GNUXX98  /* ISO C++ 1998 plus amendments and GNU extensions */
642 } lang_standard_t;
643
644 int main(int argc, char **argv)
645 {
646         initialize_firm();
647
648         const char        *dumpfunction         = NULL;
649         const char        *print_file_name_file = NULL;
650         compile_mode_t     mode                 = CompileAssembleLink;
651         int                opt_level            = 1;
652         int                result               = EXIT_SUCCESS;
653         char               cpu_arch[16]         = "ia32";
654         file_list_entry_t *files                = NULL;
655         file_list_entry_t *last_file            = NULL;
656         bool               construct_dep_target = false;
657         struct obstack     file_obst;
658
659         atexit(free_temp_files);
660
661         /* hack for now... */
662         if (strstr(argv[0], "pptest") != NULL) {
663                 extern int pptest_main(int argc, char **argv);
664                 return pptest_main(argc, argv);
665         }
666
667         obstack_init(&cppflags_obst);
668         obstack_init(&ldflags_obst);
669         obstack_init(&file_obst);
670
671 #define GET_ARG_AFTER(def, args)                                             \
672         def = &arg[sizeof(args)-1];                                              \
673         if (def[0] == '\0') {                                                     \
674                 ++i;                                                                 \
675                 if (i >= argc) {                                                      \
676                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
677                         argument_errors = true;                                          \
678                         break;                                                           \
679                 }                                                                    \
680                 def = argv[i];                                                       \
681                 if (def[0] == '-' && def[1] != '\0') {                                \
682                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
683                         argument_errors = true;                                          \
684                         continue;                                                        \
685                 }                                                                    \
686         }
687
688 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
689
690         /* early options parsing (find out optimisation level and OS) */
691         for (int i = 1; i < argc; ++i) {
692                 const char *arg = argv[i];
693                 if (arg[0] != '-')
694                         continue;
695
696                 const char *option = &arg[1];
697                 if (option[0] == 'O') {
698                         sscanf(&option[1], "%d", &opt_level);
699                 }
700                 if (strcmp(arg, "-fwin32") == 0) {
701                         firm_opt.os_support = OS_SUPPORT_MINGW;
702                 } else if (strcmp(arg, "-fmac") == 0) {
703                         firm_opt.os_support = OS_SUPPORT_MACHO;
704                 } else if (strcmp(arg, "-flinux") == 0) {
705                         firm_opt.os_support = OS_SUPPORT_LINUX;
706                 }
707         }
708
709         /* set target/os specific stuff */
710         init_os_support();
711
712         /* apply optimisation level */
713         switch(opt_level) {
714         case 0:
715                 set_option("no-opt");
716                 break;
717         case 1:
718                 set_option("no-inline");
719                 break;
720         default:
721         case 4:
722                 set_option("strict-aliasing");
723                 /* use_builtins = true; */
724                 /* fallthrough */
725         case 3:
726                 set_option("cond-eval");
727                 set_option("if-conv");
728                 /* fallthrough */
729         case 2:
730                 set_option("inline");
731                 set_option("deconv");
732                 set_be_option("omitfp");
733                 break;
734         }
735
736         /* parse rest of options */
737         lang_standard_t standard        = STANDARD_DEFAULT;
738         unsigned        features_on     = 0;
739         unsigned        features_off    = 0;
740         filetype_t      forced_filetype = FILETYPE_AUTODETECT;
741         bool            help_displayed  = false;
742         bool            argument_errors = false;
743         for (int i = 1; i < argc; ++i) {
744                 const char *arg = argv[i];
745                 if (arg[0] == '-' && arg[1] != '\0') {
746                         /* an option */
747                         const char *option = &arg[1];
748                         if (option[0] == 'o') {
749                                 GET_ARG_AFTER(outname, "-o");
750                         } else if (option[0] == 'g') {
751                                 set_be_option("debuginfo=stabs");
752                                 set_be_option("omitfp=no");
753                                 set_be_option("ia32-nooptcc=yes");
754                         } else if (SINGLE_OPTION('c')) {
755                                 mode = CompileAssemble;
756                         } else if (SINGLE_OPTION('E')) {
757                                 mode = PreprocessOnly;
758                         } else if (SINGLE_OPTION('S')) {
759                                 mode = Compile;
760                         } else if (option[0] == 'O') {
761                                 continue;
762                         } else if (option[0] == 'I') {
763                                 const char *opt;
764                                 GET_ARG_AFTER(opt, "-I");
765                                 add_flag(&cppflags_obst, "-I%s", opt);
766                         } else if (option[0] == 'D') {
767                                 const char *opt;
768                                 GET_ARG_AFTER(opt, "-D");
769                                 add_flag(&cppflags_obst, "-D%s", opt);
770                         } else if (option[0] == 'U') {
771                                 const char *opt;
772                                 GET_ARG_AFTER(opt, "-U");
773                                 add_flag(&cppflags_obst, "-U%s", opt);
774                         } else if (option[0] == 'l') {
775                                 const char *opt;
776                                 GET_ARG_AFTER(opt, "-l");
777                                 add_flag(&ldflags_obst, "-l%s", opt);
778                         } else if (option[0] == 'L') {
779                                 const char *opt;
780                                 GET_ARG_AFTER(opt, "-L");
781                                 add_flag(&ldflags_obst, "-L%s", opt);
782                         } else if (SINGLE_OPTION('v')) {
783                                 verbose = 1;
784                         } else if (SINGLE_OPTION('w')) {
785                                 memset(&warning, 0, sizeof(warning));
786                         } else if (option[0] == 'x') {
787                                 const char *opt;
788                                 GET_ARG_AFTER(opt, "-x");
789                                 forced_filetype = get_filetype_from_string(opt);
790                                 if (forced_filetype == FILETYPE_UNKNOWN) {
791                                         fprintf(stderr, "Unknown language '%s'\n", opt);
792                                         argument_errors = true;
793                                 }
794                         } else if (streq(option, "M")) {
795                                 mode = PreprocessOnly;
796                                 add_flag(&cppflags_obst, "-M");
797                         } else if (streq(option, "MMD") ||
798                                    streq(option, "MD")) {
799                             construct_dep_target = true;
800                                 add_flag(&cppflags_obst, "-%s", option);
801                         } else if (streq(option, "MM")  ||
802                                    streq(option, "MP")) {
803                                 add_flag(&cppflags_obst, "-%s", option);
804                         } else if (streq(option, "MT") ||
805                                    streq(option, "MQ") ||
806                                    streq(option, "MF")) {
807                                 const char *opt;
808                                 GET_ARG_AFTER(opt, "-MT");
809                                 add_flag(&cppflags_obst, "-%s", option);
810                                 add_flag(&cppflags_obst, "%s", opt);
811                         } else if (streq(option, "include")) {
812                                 const char *opt;
813                                 GET_ARG_AFTER(opt, "-include");
814                                 add_flag(&cppflags_obst, "-include");
815                                 add_flag(&cppflags_obst, "%s", opt);
816                         } else if (streq(option, "isystem")) {
817                                 const char *opt;
818                                 GET_ARG_AFTER(opt, "-isystem");
819                                 add_flag(&cppflags_obst, "-isystem");
820                                 add_flag(&cppflags_obst, "%s", opt);
821                         } else if (streq(option, "nostdinc")
822                                         || streq(option, "trigraphs")) {
823                                 /* pass these through to the preprocessor */
824                                 add_flag(&cppflags_obst, "%s", arg);
825                         } else if (streq(option, "pipe")) {
826                                 /* here for gcc compatibility */
827                         } else if (option[0] == 'f') {
828                                 char const *orig_opt;
829                                 GET_ARG_AFTER(orig_opt, "-f");
830
831                                 if (strstart(orig_opt, "align-loops=") ||
832                                     strstart(orig_opt, "align-jumps=") ||
833                                     strstart(orig_opt, "align-functions=")) {
834                                         fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
835                                 } else if (strstart(orig_opt, "input-charset=")) {
836                                         char const* const encoding = strchr(orig_opt, '=') + 1;
837                                         select_input_encoding(encoding);
838                                 } else if (streq(orig_opt, "verbose-asm")) {
839                                         /* ignore: we always print verbose assembler */
840                                 } else {
841                                         char const *opt         = orig_opt;
842                                         bool        truth_value = true;
843                                         if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
844                                                 truth_value = false;
845                                                 opt += 3;
846                                         }
847
848                                         if (streq(opt, "builtins")) {
849                                                 use_builtins = truth_value;
850                                         } else if (streq(opt, "dollars-in-identifiers")) {
851                                                 allow_dollar_in_symbol = truth_value;
852                                         } else if (streq(opt, "omit-frame-pointer")) {
853                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
854                                         } else if (streq(opt, "short-wchar")) {
855                                                 wchar_atomic_kind = truth_value ? ATOMIC_TYPE_USHORT
856                                                         : ATOMIC_TYPE_INT;
857                                         } else if (streq(opt, "signed-char")) {
858                                                 char_is_signed = truth_value;
859                                         } else if (streq(opt, "strength-reduce")) {
860                                                 firm_option(truth_value ? "strength-red" : "no-strength-red");
861                                         } else if (streq(opt, "syntax-only")) {
862                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
863                                         } else if (streq(opt, "unsigned-char")) {
864                                                 char_is_signed = !truth_value;
865                                         } else if (streq(opt, "fast-math")               ||
866                                                    streq(opt, "jump-tables")             ||
867                                                    streq(opt, "unroll-loops")            ||
868                                                    streq(opt, "expensive-optimizations") ||
869                                                    streq(opt, "common")                  ||
870                                                    streq(opt, "PIC")                     ||
871                                                    streq(opt, "align-loops")             ||
872                                                    streq(opt, "align-jumps")             ||
873                                                    streq(opt, "align-functions")) {
874                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
875                                         } else {
876                                                 int res = firm_option(orig_opt);
877                                                 if (res == 0) {
878                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
879                                                                 orig_opt);
880                                                         argument_errors = true;
881                                                         continue;
882                                                 } else if (res == -1) {
883                                                         help_displayed = true;
884                                                 }
885                                         }
886                                 }
887                         } else if (option[0] == 'b') {
888                                 const char *opt;
889                                 GET_ARG_AFTER(opt, "-b");
890                                 int res = firm_be_option(opt);
891                                 if (res == 0) {
892                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
893                                                 opt);
894                                         argument_errors = true;
895                                 } else if (res == -1) {
896                                         help_displayed = true;
897                                 } else if (strstart(opt, "isa=")) {
898                                         strncpy(cpu_arch, opt, sizeof(cpu_arch));
899                                 }
900                         } else if (option[0] == 'W') {
901                                 if (strstart(option + 1, "p,")) {
902                                         // pass options directly to the preprocessor
903                                         const char *opt;
904                                         GET_ARG_AFTER(opt, "-Wp,");
905                                         add_flag(&cppflags_obst, "-Wp,%s", opt);
906                                 } else if (strstart(option + 1, "l,")) {
907                                         // pass options directly to the linker
908                                         const char *opt;
909                                         GET_ARG_AFTER(opt, "-Wl,");
910                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
911                                 } else if (streq(option + 1, "no-trigraphs")
912                                                         || streq(option + 1, "undef")) {
913                                         add_flag(&cppflags_obst, "%s", arg);
914                                 } else {
915                                         set_warning_opt(&option[1]);
916                                 }
917                         } else if (option[0] == 'm') {
918                                 /* -m options */
919                                 const char *opt;
920                                 char arch_opt[64];
921
922                                 GET_ARG_AFTER(opt, "-m");
923                                 if (strstart(opt, "arch=")) {
924                                         GET_ARG_AFTER(opt, "-march=");
925                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
926                                         int res = firm_be_option(arch_opt);
927                                         if (res == 0)
928                                                 argument_errors = true;
929                                         else {
930                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
931                                                 int res = firm_be_option(arch_opt);
932                                                 if (res == 0)
933                                                         argument_errors = true;
934                                         }
935                                 } else if (strstart(opt, "tune=")) {
936                                         GET_ARG_AFTER(opt, "-mtune=");
937                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
938                                         int res = firm_be_option(arch_opt);
939                                         if (res == 0)
940                                                 argument_errors = true;
941                                 } else if (strstart(opt, "cpu=")) {
942                                         GET_ARG_AFTER(opt, "-mcpu=");
943                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
944                                         int res = firm_be_option(arch_opt);
945                                         if (res == 0)
946                                                 argument_errors = true;
947                                 } else if (strstart(opt, "fpmath=")) {
948                                         GET_ARG_AFTER(opt, "-mfpmath=");
949                                         if (streq(opt, "387"))
950                                                 opt = "x87";
951                                         else if (streq(opt, "sse"))
952                                                 opt = "sse2";
953                                         else {
954                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
955                                                 argument_errors = true;
956                                         }
957                                         if (!argument_errors) {
958                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
959                                                 int res = firm_be_option(arch_opt);
960                                                 if (res == 0)
961                                                         argument_errors = true;
962                                         }
963                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
964                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
965                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
966                                         int res = firm_be_option(arch_opt);
967                                         if (res == 0)
968                                                 argument_errors = true;
969                                 } else if (streq(opt, "omit-leaf-frame-pointer")) {
970                                         set_be_option("omitleaffp=1");
971                                 } else if (streq(opt, "no-omit-leaf-frame-pointer")) {
972                                         set_be_option("omitleaffp=0");
973                                 } else if (streq(opt, "rtd")) {
974                                         default_calling_convention = CC_STDCALL;
975                                 } else {
976                                         char *endptr;
977                                         long int value = strtol(opt, &endptr, 10);
978                                         if (*endptr != '\0') {
979                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
980                                                 argument_errors = true;
981                                         }
982                                         if (value != 16 && value != 32 && value != 64) {
983                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
984                                                 argument_errors = true;
985                                         } else {
986                                                 machine_size = (unsigned int)value;
987                                         }
988                                 }
989                         } else if (streq(option, "pg")) {
990                                 set_be_option("gprof");
991                                 add_flag(&ldflags_obst, "-pg");
992                         } else if (streq(option, "pedantic") ||
993                                    streq(option, "ansi")) {
994                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
995                         } else if (streq(option, "shared")) {
996                                 add_flag(&ldflags_obst, "-shared");
997                         } else if (strstart(option, "std=")) {
998                                 const char *const o = &option[4];
999                                 standard =
1000                                         streq(o, "c++")            ? STANDARD_CXX98   :
1001                                         streq(o, "c++98")          ? STANDARD_CXX98   :
1002                                         streq(o, "c89")            ? STANDARD_C89     :
1003                                         streq(o, "c99")            ? STANDARD_C99     :
1004                                         streq(o, "c9x")            ? STANDARD_C99     : // deprecated
1005                                         streq(o, "gnu++98")        ? STANDARD_GNUXX98 :
1006                                         streq(o, "gnu89")          ? STANDARD_GNU89   :
1007                                         streq(o, "gnu99")          ? STANDARD_GNU99   :
1008                                         streq(o, "gnu9x")          ? STANDARD_GNU99   : // deprecated
1009                                         streq(o, "iso9899:1990")   ? STANDARD_C89     :
1010                                         streq(o, "iso9899:199409") ? STANDARD_C90     :
1011                                         streq(o, "iso9899:1999")   ? STANDARD_C99     :
1012                                         streq(o, "iso9899:199x")   ? STANDARD_C99     : // deprecated
1013                                         (fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg), standard);
1014                         } else if (streq(option, "version")) {
1015                                 print_cparser_version();
1016                         } else if (strstart(option, "print-file-name=")) {
1017                                 GET_ARG_AFTER(print_file_name_file, "-print-file-name=");
1018                         } else if (option[0] == '-') {
1019                                 /* double dash option */
1020                                 ++option;
1021                                 if (streq(option, "gcc")) {
1022                                         features_on  |=  _GNUC;
1023                                         features_off &= ~_GNUC;
1024                                 } else if (streq(option, "no-gcc")) {
1025                                         features_on  &= ~_GNUC;
1026                                         features_off |=  _GNUC;
1027                                 } else if (streq(option, "ms")) {
1028                                         features_on  |=  _MS;
1029                                         features_off &= ~_MS;
1030                                 } else if (streq(option, "no-ms")) {
1031                                         features_on  &= ~_MS;
1032                                         features_off |=  _MS;
1033                                 } else if (streq(option, "strict")) {
1034                                         strict_mode = true;
1035                                 } else if (streq(option, "lextest")) {
1036                                         mode = LexTest;
1037                                 } else if (streq(option, "benchmark")) {
1038                                         mode = BenchmarkParser;
1039                                 } else if (streq(option, "print-ast")) {
1040                                         mode = PrintAst;
1041                                 } else if (streq(option, "print-implicit-cast")) {
1042                                         print_implicit_casts = true;
1043                                 } else if (streq(option, "print-parenthesis")) {
1044                                         print_parenthesis = true;
1045                                 } else if (streq(option, "print-fluffy")) {
1046                                         mode = PrintFluffy;
1047                                 } else if (streq(option, "print-caml")) {
1048                                         mode = PrintCaml;
1049                                 } else if (streq(option, "print-jna")) {
1050                                         mode = PrintJna;
1051                                 } else if (streq(option, "version")) {
1052                                         print_cparser_version();
1053                                         exit(EXIT_SUCCESS);
1054                                 } else if (streq(option, "dump-function")) {
1055                                         ++i;
1056                                         if (i >= argc) {
1057                                                 fprintf(stderr, "error: "
1058                                                         "expected argument after '--dump-function'\n");
1059                                                 argument_errors = true;
1060                                                 break;
1061                                         }
1062                                         dumpfunction = argv[i];
1063                                         mode         = CompileDump;
1064                                 } else if (streq(option, "export-ir")) {
1065                                         mode = CompileExportIR;
1066                                 } else {
1067                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
1068                                         argument_errors = true;
1069                                 }
1070                         } else {
1071                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
1072                                 argument_errors = true;
1073                         }
1074                 } else {
1075                         filetype_t type = forced_filetype;
1076                         if (type == FILETYPE_AUTODETECT) {
1077                                 if (streq(arg, "-")) {
1078                                         /* - implicitly means C source file */
1079                                         type = FILETYPE_C;
1080                                 } else {
1081                                         const char *suffix = strrchr(arg, '.');
1082                                         /* Ensure there is at least one char before the suffix */
1083                                         if (suffix != NULL && suffix != arg) {
1084                                                 ++suffix;
1085                                                 type =
1086                                                         streq(suffix, "S")   ? FILETYPE_ASSEMBLER              :
1087                                                         streq(suffix, "a")   ? FILETYPE_OBJECT                 :
1088                                                         streq(suffix, "c")   ? FILETYPE_C                      :
1089                                                         streq(suffix, "cc")  ? FILETYPE_CXX                    :
1090                                                         streq(suffix, "cpp") ? FILETYPE_CXX                    :
1091                                                         streq(suffix, "cxx") ? FILETYPE_CXX                    :
1092                                                         streq(suffix, "h")   ? FILETYPE_C                      :
1093                                                         streq(suffix, "ir")  ? FILETYPE_IR                     :
1094                                                         streq(suffix, "o")   ? FILETYPE_OBJECT                 :
1095                                                         streq(suffix, "s")   ? FILETYPE_PREPROCESSED_ASSEMBLER :
1096                                                         streq(suffix, "so")  ? FILETYPE_OBJECT                 :
1097                                                         FILETYPE_AUTODETECT;
1098                                         }
1099                                 }
1100
1101                                 if (type == FILETYPE_AUTODETECT) {
1102                                         fprintf(stderr, "'%s': file format not recognized\n", arg);
1103                                         continue;
1104                                 }
1105                         }
1106
1107                         file_list_entry_t *entry
1108                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
1109                         memset(entry, 0, sizeof(entry[0]));
1110                         entry->name = arg;
1111                         entry->type = type;
1112
1113                         if (last_file != NULL) {
1114                                 last_file->next = entry;
1115                         } else {
1116                                 files = entry;
1117                         }
1118                         last_file = entry;
1119                 }
1120         }
1121
1122         if (print_file_name_file != NULL) {
1123                 print_file_name(print_file_name_file);
1124                 return 0;
1125         }
1126
1127         if (files == NULL) {
1128                 fprintf(stderr, "error: no input files specified\n");
1129                 argument_errors = true;
1130         }
1131
1132         if (help_displayed) {
1133                 return !argument_errors;
1134         }
1135         if (argument_errors) {
1136                 usage(argv[0]);
1137                 return 1;
1138         }
1139
1140         /* we do the lowering in ast2firm */
1141         firm_opt.lower_bitfields = FALSE;
1142
1143         /* set the c_mode here, types depends on it */
1144         c_mode |= features_on;
1145         c_mode &= ~features_off;
1146
1147         gen_firm_init();
1148         init_symbol_table();
1149         init_types();
1150         init_typehash();
1151         init_basic_types();
1152         init_lexer();
1153         init_ast();
1154         init_parser();
1155         init_ast2firm();
1156         init_mangle();
1157
1158         if (construct_dep_target) {
1159                 if (outname != 0 && strlen(outname) >= 2) {
1160                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
1161                 } else {
1162                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
1163                 }
1164         } else {
1165                 dep_target[0] = '\0';
1166         }
1167
1168         char outnamebuf[4096];
1169         if (outname == NULL) {
1170                 const char *filename = files->name;
1171
1172                 switch(mode) {
1173                 case BenchmarkParser:
1174                 case PrintAst:
1175                 case PrintFluffy:
1176                 case PrintCaml:
1177                 case PrintJna:
1178                 case LexTest:
1179                 case PreprocessOnly:
1180                 case ParseOnly:
1181                         outname = "-";
1182                         break;
1183                 case Compile:
1184                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
1185                         outname = outnamebuf;
1186                         break;
1187                 case CompileAssemble:
1188                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
1189                         outname = outnamebuf;
1190                         break;
1191                 case CompileDump:
1192                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
1193                                         ".vcg");
1194                         outname = outnamebuf;
1195                         break;
1196                 case CompileExportIR:
1197                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".ir");
1198                         outname = outnamebuf;
1199                         break;
1200                 case CompileAssembleLink:
1201 #ifdef _WIN32
1202                         outname = "a.exe";
1203 #else
1204                         outname = "a.out";
1205 #endif
1206                         break;
1207                 }
1208         }
1209
1210         assert(outname != NULL);
1211
1212         FILE *out;
1213         if (streq(outname, "-")) {
1214                 out = stdout;
1215         } else {
1216                 out = fopen(outname, "w");
1217                 if (out == NULL) {
1218                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
1219                                         strerror(errno));
1220                         return 1;
1221                 }
1222         }
1223
1224         file_list_entry_t *file;
1225         for (file = files; file != NULL; file = file->next) {
1226                 char        asm_tempfile[1024];
1227                 const char *filename = file->name;
1228                 filetype_t  filetype = file->type;
1229
1230                 if (filetype == FILETYPE_OBJECT)
1231                         continue;
1232
1233                 FILE *in = NULL;
1234                 if (mode == LexTest) {
1235                         if (in == NULL)
1236                                 in = open_file(filename);
1237                         lextest(in, filename);
1238                         fclose(in);
1239                         exit(EXIT_SUCCESS);
1240                 }
1241
1242                 FILE *preprocessed_in = NULL;
1243                 switch (filetype) {
1244                         case FILETYPE_C:
1245                                 filetype = FILETYPE_PREPROCESSED_C;
1246                                 goto preprocess;
1247                         case FILETYPE_CXX:
1248                                 filetype = FILETYPE_PREPROCESSED_CXX;
1249                                 goto preprocess;
1250                         case FILETYPE_ASSEMBLER:
1251                                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1252                                 add_flag(&cppflags_obst, "-x");
1253                                 add_flag(&cppflags_obst, "assembler-with-cpp");
1254                                 goto preprocess;
1255 preprocess:
1256                                 /* no support for input on FILE* yet */
1257                                 if (in != NULL)
1258                                         panic("internal compiler error: in for preprocessor != NULL");
1259
1260                                 preprocessed_in = preprocess(filename);
1261                                 if (mode == PreprocessOnly) {
1262                                         copy_file(out, preprocessed_in);
1263                                         int result = pclose(preprocessed_in);
1264                                         fclose(out);
1265                                         /* remove output file in case of error */
1266                                         if (out != stdout && result != EXIT_SUCCESS) {
1267                                                 unlink(outname);
1268                                         }
1269                                         return result;
1270                                 }
1271
1272                                 in = preprocessed_in;
1273                                 break;
1274
1275                         default:
1276                                 break;
1277                 }
1278
1279                 FILE *asm_out;
1280                 if (mode == Compile) {
1281                         asm_out = out;
1282                 } else {
1283                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "ccs");
1284                 }
1285
1286                 if (in == NULL)
1287                         in = open_file(filename);
1288
1289                 /* preprocess and compile */
1290                 if (filetype == FILETYPE_PREPROCESSED_C) {
1291                         char const* invalid_mode;
1292                         switch (standard) {
1293                                 case STANDARD_ANSI:
1294                                 case STANDARD_C89:   c_mode = _C89;                break;
1295                                 /* TODO determine difference between these two */
1296                                 case STANDARD_C90:   c_mode = _C89;                break;
1297                                 case STANDARD_C99:   c_mode = _C89 | _C99;         break;
1298                                 case STANDARD_GNU89: c_mode = _C89 |        _GNUC; break;
1299
1300 default_c_warn:
1301                                         fprintf(stderr,
1302                                                         "warning: command line option \"-std=%s\" is not valid for C\n",
1303                                                         invalid_mode);
1304                                         /* FALLTHROUGH */
1305                                 case STANDARD_DEFAULT:
1306                                 case STANDARD_GNU99:   c_mode = _C89 | _C99 | _GNUC; break;
1307
1308                                 case STANDARD_CXX98:   invalid_mode = "c++98"; goto default_c_warn;
1309                                 case STANDARD_GNUXX98: invalid_mode = "gnu98"; goto default_c_warn;
1310                         }
1311                         goto do_parsing;
1312                 } else if (filetype == FILETYPE_PREPROCESSED_CXX) {
1313                         char const* invalid_mode;
1314                         switch (standard) {
1315                                 case STANDARD_C89:   invalid_mode = "c89";   goto default_cxx_warn;
1316                                 case STANDARD_C90:   invalid_mode = "c90";   goto default_cxx_warn;
1317                                 case STANDARD_C99:   invalid_mode = "c99";   goto default_cxx_warn;
1318                                 case STANDARD_GNU89: invalid_mode = "gnu89"; goto default_cxx_warn;
1319                                 case STANDARD_GNU99: invalid_mode = "gnu99"; goto default_cxx_warn;
1320
1321                                 case STANDARD_ANSI:
1322                                 case STANDARD_CXX98: c_mode = _CXX; break;
1323
1324 default_cxx_warn:
1325                                         fprintf(stderr,
1326                                                         "warning: command line option \"-std=%s\" is not valid for C++\n",
1327                                                         invalid_mode);
1328                                 case STANDARD_DEFAULT:
1329                                 case STANDARD_GNUXX98: c_mode = _CXX | _GNUC; break;
1330                         }
1331
1332 do_parsing:
1333                         c_mode |= features_on;
1334                         c_mode &= ~features_off;
1335
1336                         init_tokens();
1337                         translation_unit_t *const unit = do_parsing(in, filename);
1338
1339                         /* prints the AST even if errors occurred */
1340                         if (mode == PrintAst) {
1341                                 type_set_output(out);
1342                                 ast_set_output(out);
1343                                 print_ast(unit);
1344                         }
1345
1346                         if (error_count > 0) {
1347                                 /* parsing failed because of errors */
1348                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1349                                         warning_count);
1350                                 result = EXIT_FAILURE;
1351                                 continue;
1352                         } else if (warning_count > 0) {
1353                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1354                         }
1355
1356                         if (in == preprocessed_in) {
1357                                 int pp_result = pclose(preprocessed_in);
1358                                 if (pp_result != EXIT_SUCCESS) {
1359                                         /* remove output file */
1360                                         if (out != stdout)
1361                                                 unlink(outname);
1362                                         exit(EXIT_FAILURE);
1363                                 }
1364                         }
1365
1366                         if (mode == BenchmarkParser) {
1367                                 return result;
1368                         } else if (mode == PrintFluffy) {
1369                                 write_fluffy_decls(out, unit);
1370                                 continue;
1371                         } else if (mode == PrintCaml) {
1372                                 write_caml_decls(out, unit);
1373                                 continue;
1374                         } else if (mode == PrintJna) {
1375                                 write_jna_decls(out, unit);
1376                                 continue;
1377                         }
1378
1379                         translation_unit_to_firm(unit);
1380
1381 graph_built:
1382                         if (mode == ParseOnly) {
1383                                 continue;
1384                         }
1385
1386                         if (mode == CompileDump) {
1387                                 /* find irg */
1388                                 ident    *id     = new_id_from_str(dumpfunction);
1389                                 ir_graph *irg    = NULL;
1390                                 int       n_irgs = get_irp_n_irgs();
1391                                 for (int i = 0; i < n_irgs; ++i) {
1392                                         ir_graph *tirg   = get_irp_irg(i);
1393                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1394                                         if (irg_id == id) {
1395                                                 irg = tirg;
1396                                                 break;
1397                                         }
1398                                 }
1399
1400                                 if (irg == NULL) {
1401                                         fprintf(stderr, "No graph for function '%s' found\n",
1402                                                 dumpfunction);
1403                                         exit(1);
1404                                 }
1405
1406                                 dump_ir_block_graph_file(irg, out);
1407                                 fclose(out);
1408                                 exit(0);
1409                         }
1410
1411                         if (mode == CompileExportIR) {
1412                                 fclose(out);
1413                                 ir_export(outname);
1414                                 exit(0);
1415                         }
1416
1417                         gen_firm_finish(asm_out, filename, /*c_mode=*/1,
1418                                         have_const_functions);
1419                         if (asm_out != out) {
1420                                 fclose(asm_out);
1421                         }
1422                 } else if (filetype == FILETYPE_IR) {
1423                         fclose(in);
1424                         ir_import(filename);
1425                         goto graph_built;
1426                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1427                         copy_file(asm_out, in);
1428                         if (in == preprocessed_in) {
1429                                 int pp_result = pclose(preprocessed_in);
1430                                 if (pp_result != EXIT_SUCCESS) {
1431                                         /* remove output in error case */
1432                                         if (out != stdout)
1433                                                 unlink(outname);
1434                                         return pp_result;
1435                                 }
1436                         }
1437                         if (asm_out != out) {
1438                                 fclose(asm_out);
1439                         }
1440                 }
1441
1442                 if (mode == Compile)
1443                         continue;
1444
1445                 /* if we're here then we have preprocessed assembly */
1446                 filename = asm_tempfile;
1447                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1448
1449                 /* assemble */
1450                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1451                         char        temp[1024];
1452                         const char *filename_o;
1453                         if (mode == CompileAssemble) {
1454                                 fclose(out);
1455                                 filename_o = outname;
1456                         } else {
1457                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
1458                                 fclose(tempf);
1459                                 filename_o = temp;
1460                         }
1461
1462                         assemble(filename_o, filename);
1463
1464                         size_t len = strlen(filename_o) + 1;
1465                         filename = obstack_copy(&file_obst, filename_o, len);
1466                         filetype = FILETYPE_OBJECT;
1467                 }
1468
1469                 /* ok we're done here, process next file */
1470                 file->name = filename;
1471                 file->type = filetype;
1472         }
1473
1474         if (result != EXIT_SUCCESS) {
1475                 if (out != stdout)
1476                         unlink(outname);
1477                 return result;
1478         }
1479
1480         /* link program file */
1481         if (mode == CompileAssembleLink) {
1482                 obstack_1grow(&ldflags_obst, '\0');
1483                 const char *flags = obstack_finish(&ldflags_obst);
1484
1485                 /* construct commandline */
1486                 obstack_printf(&file_obst, "%s", LINKER);
1487                 for (file_list_entry_t *entry = files; entry != NULL;
1488                                 entry = entry->next) {
1489                         if (entry->type != FILETYPE_OBJECT)
1490                                 continue;
1491
1492                         add_flag(&file_obst, "%s", entry->name);
1493                 }
1494
1495                 add_flag(&file_obst, "-o");
1496                 add_flag(&file_obst, outname);
1497                 obstack_printf(&file_obst, "%s", flags);
1498                 obstack_1grow(&file_obst, '\0');
1499
1500                 char *commandline = obstack_finish(&file_obst);
1501
1502                 if (verbose) {
1503                         puts(commandline);
1504                 }
1505                 int err = system(commandline);
1506                 if (err != EXIT_SUCCESS) {
1507                         fprintf(stderr, "linker reported an error\n");
1508                         exit(1);
1509                 }
1510         }
1511
1512         obstack_free(&cppflags_obst, NULL);
1513         obstack_free(&ldflags_obst, NULL);
1514         obstack_free(&file_obst, NULL);
1515
1516         exit_mangle();
1517         exit_ast2firm();
1518         exit_parser();
1519         exit_ast();
1520         exit_lexer();
1521         exit_typehash();
1522         exit_types();
1523         exit_tokens();
1524         exit_symbol_table();
1525         return 0;
1526 }