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