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