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