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