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