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