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