Renamed enum entry.
[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 "preprocessor.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_timing.h"
74 #include "driver/firm_machine.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 "help.h"
82 #include "mangle.h"
83 #include "printer.h"
84
85 #ifndef PREPROCESSOR
86 #ifndef __WIN32__
87 #define PREPROCESSOR "gcc -E -U__STRICT_ANSI__"
88 #else
89 #define PREPROCESSOR "cpp -U__STRICT_ANSI__"
90 #endif
91 #endif
92
93 #ifndef LINKER
94 #define LINKER    "gcc"
95 #endif
96
97 #ifndef ASSEMBLER
98 #define ASSEMBLER "gcc -c -xassembler"
99 #endif
100
101 unsigned int        c_mode                    = _C89 | _C99 | _GNUC;
102 bool                byte_order_big_endian     = false;
103 bool                strict_mode               = false;
104 bool                enable_main_collect2_hack = false;
105 bool                freestanding              = false;
106 unsigned            architecture_modulo_shift = 0;
107
108 static bool               char_is_signed      = true;
109 static atomic_type_kind_t wchar_atomic_kind   = ATOMIC_TYPE_INT;
110
111 static machine_triple_t *target_machine;
112 static const char       *target_triple;
113 static int               verbose;
114 static struct obstack    cppflags_obst;
115 static struct obstack    ldflags_obst;
116 static struct obstack    asflags_obst;
117 static char              dep_target[1024];
118 static const char       *outname;
119 static bool              define_intmax_types;
120 static const char       *input_encoding;
121
122 typedef enum lang_standard_t {
123         STANDARD_DEFAULT, /* gnu99 (for C, GCC does gnu89) or gnu++98 (for C++) */
124         STANDARD_C89,     /* ISO C90 (sic) */
125         STANDARD_C89AMD1, /* ISO C90 as modified in amendment 1 */
126         STANDARD_C99,     /* ISO C99 */
127         STANDARD_GNU89,   /* ISO C90 plus GNU extensions (including some C99) */
128         STANDARD_GNU99,   /* ISO C99 plus GNU extensions */
129         STANDARD_CXX98,   /* ISO C++ 1998 plus amendments */
130         STANDARD_GNUXX98  /* ISO C++ 1998 plus amendments and GNU extensions */
131 } lang_standard_t;
132
133 typedef struct file_list_entry_t file_list_entry_t;
134
135 typedef enum filetype_t {
136         FILETYPE_AUTODETECT,
137         FILETYPE_C,
138         FILETYPE_PREPROCESSED_C,
139         FILETYPE_CXX,
140         FILETYPE_PREPROCESSED_CXX,
141         FILETYPE_ASSEMBLER,
142         FILETYPE_PREPROCESSED_ASSEMBLER,
143         FILETYPE_OBJECT,
144         FILETYPE_IR,
145         FILETYPE_UNKNOWN
146 } filetype_t;
147
148 struct file_list_entry_t {
149         const char  *name; /**< filename or NULL for stdin */
150         filetype_t   type;
151         file_list_entry_t *next;
152 };
153
154 static file_list_entry_t *temp_files;
155
156 static void get_output_name(char *buf, size_t buflen, const char *inputname,
157                             const char *newext)
158 {
159         if (inputname == NULL)
160                 inputname = "a";
161
162         char const *const last_slash = strrchr(inputname, '/');
163         char const *const filename   =
164                 last_slash != NULL ? last_slash + 1 : inputname;
165         char const *const last_dot   = strrchr(filename, '.');
166         char const *const name_end   =
167                 last_dot != NULL ? last_dot : strchr(filename, '\0');
168
169         int const len = snprintf(buf, buflen, "%.*s%s",
170                         (int)(name_end - filename), filename, newext);
171 #ifdef _WIN32
172         if (len < 0 || buflen <= (size_t)len)
173 #else
174         if (buflen <= (size_t)len)
175 #endif
176                 panic("filename too long");
177 }
178
179 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
180 {
181         start_parsing();
182
183         switch_input(in, input_name);
184         parse();
185         translation_unit_t *unit = finish_parsing();
186         close_input();
187
188         return unit;
189 }
190
191 static void lextest(FILE *in, const char *fname)
192 {
193         switch_input(in, fname);
194         do {
195                 next_preprocessing_token();
196                 print_token(stdout, &pp_token);
197                 putchar('\n');
198         } while (pp_token.kind != T_EOF);
199         close_input();
200 }
201
202 static void add_flag(struct obstack *obst, const char *format, ...)
203 {
204         char buf[65536];
205         va_list ap;
206
207         va_start(ap, format);
208 #ifdef _WIN32
209         int len =
210 #endif
211                 vsnprintf(buf, sizeof(buf), format, ap);
212         va_end(ap);
213
214         obstack_1grow(obst, ' ');
215 #ifdef _WIN32
216         obstack_1grow(obst, '"');
217         obstack_grow(obst, buf, len);
218         obstack_1grow(obst, '"');
219 #else
220         /* escape stuff... */
221         for (char *c = buf; *c != '\0'; ++c) {
222                 switch(*c) {
223                 case ' ':
224                 case '"':
225                 case '$':
226                 case '&':
227                 case '(':
228                 case ')':
229                 case ';':
230                 case '<':
231                 case '>':
232                 case '\'':
233                 case '\\':
234                 case '\n':
235                 case '\r':
236                 case '\t':
237                 case '`':
238                 case '|':
239                         obstack_1grow(obst, '\\');
240                         /* FALLTHROUGH */
241                 default:
242                         obstack_1grow(obst, *c);
243                         break;
244                 }
245         }
246 #endif
247 }
248
249 static const char *type_to_string(type_t *type)
250 {
251         assert(type->kind == TYPE_ATOMIC);
252         return get_atomic_kind_name(type->atomic.akind);
253 }
254
255 static FILE *preprocess(const char *fname, filetype_t filetype,
256                         lang_standard_t standard)
257 {
258         static const char *common_flags = NULL;
259
260         if (common_flags == NULL) {
261                 obstack_1grow(&cppflags_obst, '\0');
262                 const char *flags = obstack_finish(&cppflags_obst);
263
264                 /* setup default defines */
265                 add_flag(&cppflags_obst, "-U__WCHAR_TYPE__");
266                 add_flag(&cppflags_obst, "-D__WCHAR_TYPE__=%s", type_to_string(type_wchar_t));
267                 add_flag(&cppflags_obst, "-U__SIZE_TYPE__");
268                 add_flag(&cppflags_obst, "-D__SIZE_TYPE__=%s", type_to_string(type_size_t));
269
270                 add_flag(&cppflags_obst, "-U__VERSION__");
271                 add_flag(&cppflags_obst, "-D__VERSION__=\"%s\"", cparser_REVISION);
272
273                 if (define_intmax_types) {
274                         add_flag(&cppflags_obst, "-U__INTMAX_TYPE__");
275                         add_flag(&cppflags_obst, "-D__INTMAX_TYPE__=%s", type_to_string(type_intmax_t));
276                         add_flag(&cppflags_obst, "-U__UINTMAX_TYPE__");
277                         add_flag(&cppflags_obst, "-D__UINTMAX_TYPE__=%s", type_to_string(type_uintmax_t));
278                 }
279
280                 if (flags[0] != '\0') {
281                         size_t len = strlen(flags);
282                         obstack_1grow(&cppflags_obst, ' ');
283                         obstack_grow(&cppflags_obst, flags, len);
284                 }
285                 obstack_1grow(&cppflags_obst, '\0');
286                 common_flags = obstack_finish(&cppflags_obst);
287         }
288
289         assert(obstack_object_size(&cppflags_obst) == 0);
290
291         const char *preprocessor = getenv("CPARSER_PP");
292         if (preprocessor != NULL) {
293                 obstack_printf(&cppflags_obst, "%s ", preprocessor);
294         } else {
295                 if (target_triple != NULL)
296                         obstack_printf(&cppflags_obst, "%s-", target_triple);
297                 obstack_printf(&cppflags_obst, PREPROCESSOR);
298         }
299
300         char const *lang;
301         switch (filetype) {
302         case FILETYPE_C:         lang = "c";                  break;
303         case FILETYPE_CXX:       lang = "c++";                break;
304         case FILETYPE_ASSEMBLER: lang = "assembler-with-cpp"; break;
305         default:                 lang = NULL;                 break;
306         }
307         if (lang)
308                 add_flag(&cppflags_obst, "-x%s", lang);
309
310         char const *std = NULL;
311         switch (standard) {
312         case STANDARD_C89:     std = "-std=c89";            break;
313         case STANDARD_C89AMD1: std = "-std=iso9899:199409"; break;
314         case STANDARD_C99:     std = "-std=c99";            break;
315         case STANDARD_GNU89:   std = "-std=gnu89";          break;
316         case STANDARD_GNU99:   std = "-std=gnu99";          break;
317         case STANDARD_CXX98:   std = "-std=c++98";          break;
318         case STANDARD_GNUXX98: std = "-std=gnu++98";        break;
319         case STANDARD_DEFAULT: panic("invalid standard");
320         }
321         if (std)
322             add_flag(&cppflags_obst, std);
323
324         obstack_printf(&cppflags_obst, "%s", common_flags);
325
326         /* handle dependency generation */
327         if (dep_target[0] != '\0') {
328                 add_flag(&cppflags_obst, "-MF");
329                 add_flag(&cppflags_obst, dep_target);
330                 if (outname != NULL) {
331                         add_flag(&cppflags_obst, "-MQ");
332                         add_flag(&cppflags_obst, outname);
333                 }
334         }
335         add_flag(&cppflags_obst, fname);
336         obstack_1grow(&cppflags_obst, '\0');
337
338         char *commandline = obstack_finish(&cppflags_obst);
339         if (verbose) {
340                 puts(commandline);
341         }
342         FILE *f = popen(commandline, "r");
343         if (f == NULL) {
344                 fprintf(stderr, "invoking preprocessor failed\n");
345                 exit(EXIT_FAILURE);
346         }
347         /* we do not really need that anymore */
348         obstack_free(&cppflags_obst, commandline);
349
350         return f;
351 }
352
353 static void assemble(const char *out, const char *in)
354 {
355         obstack_1grow(&asflags_obst, '\0');
356         const char *flags = obstack_finish(&asflags_obst);
357
358         const char *assembler = getenv("CPARSER_AS");
359         if (assembler != NULL) {
360                 obstack_printf(&asflags_obst, "%s", assembler);
361         } else {
362                 if (target_triple != NULL)
363                         obstack_printf(&asflags_obst, "%s-", target_triple);
364                 obstack_printf(&asflags_obst, "%s", ASSEMBLER);
365         }
366         if (flags[0] != '\0')
367                 obstack_printf(&asflags_obst, " %s", flags);
368
369         obstack_printf(&asflags_obst, " %s -o %s", in, out);
370         obstack_1grow(&asflags_obst, '\0');
371
372         char *commandline = obstack_finish(&asflags_obst);
373         if (verbose) {
374                 puts(commandline);
375         }
376         int err = system(commandline);
377         if (err != EXIT_SUCCESS) {
378                 fprintf(stderr, "assembler reported an error\n");
379                 exit(EXIT_FAILURE);
380         }
381         obstack_free(&asflags_obst, commandline);
382 }
383
384 static void print_file_name(const char *file)
385 {
386         add_flag(&ldflags_obst, "-print-file-name=%s", file);
387
388         obstack_1grow(&ldflags_obst, '\0');
389         const char *flags = obstack_finish(&ldflags_obst);
390
391         /* construct commandline */
392         const char *linker = getenv("CPARSER_LINK");
393         if (linker != NULL) {
394                 obstack_printf(&ldflags_obst, "%s ", linker);
395         } else {
396                 if (target_triple != NULL)
397                         obstack_printf(&ldflags_obst, "%s-", target_triple);
398                 obstack_printf(&ldflags_obst, "%s ", LINKER);
399         }
400         obstack_printf(&ldflags_obst, "%s ", linker);
401         obstack_printf(&ldflags_obst, "%s", flags);
402         obstack_1grow(&ldflags_obst, '\0');
403
404         char *commandline = obstack_finish(&ldflags_obst);
405         if (verbose) {
406                 puts(commandline);
407         }
408         int err = system(commandline);
409         if (err != EXIT_SUCCESS) {
410                 fprintf(stderr, "linker reported an error\n");
411                 exit(EXIT_FAILURE);
412         }
413         obstack_free(&ldflags_obst, commandline);
414 }
415
416 static const char *try_dir(const char *dir)
417 {
418         if (dir == NULL)
419                 return dir;
420         if (access(dir, R_OK | W_OK | X_OK) == 0)
421                 return dir;
422         return NULL;
423 }
424
425 static const char *get_tempdir(void)
426 {
427         static const char *tmpdir = NULL;
428
429         if (tmpdir != NULL)
430                 return tmpdir;
431
432         if (tmpdir == NULL)
433                 tmpdir = try_dir(getenv("TMPDIR"));
434         if (tmpdir == NULL)
435                 tmpdir = try_dir(getenv("TMP"));
436         if (tmpdir == NULL)
437                 tmpdir = try_dir(getenv("TEMP"));
438
439 #ifdef P_tmpdir
440         if (tmpdir == NULL)
441                 tmpdir = try_dir(P_tmpdir);
442 #endif
443
444         if (tmpdir == NULL)
445                 tmpdir = try_dir("/var/tmp");
446         if (tmpdir == NULL)
447                 tmpdir = try_dir("/usr/tmp");
448         if (tmpdir == NULL)
449                 tmpdir = try_dir("/tmp");
450
451         if (tmpdir == NULL)
452                 tmpdir = ".";
453
454         return tmpdir;
455 }
456
457 #ifndef HAVE_MKSTEMP
458 /* cheap and nasty mkstemp replacement */
459 static int mkstemp(char *templ)
460 {
461         mktemp(templ);
462         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
463 }
464 #endif
465
466 /**
467  * an own version of tmpnam, which: writes in a buffer, emits no warnings
468  * during linking (like glibc/gnu ld do for tmpnam)...
469  */
470 static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix)
471 {
472         const char *tempdir = get_tempdir();
473
474         snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix);
475
476         int fd = mkstemp(buffer);
477         if (fd == -1) {
478                 fprintf(stderr, "could not create temporary file: %s\n",
479                         strerror(errno));
480                 exit(EXIT_FAILURE);
481         }
482         FILE *out = fdopen(fd, "w");
483         if (out == NULL) {
484                 fprintf(stderr, "could not create temporary file FILE*\n");
485                 exit(EXIT_FAILURE);
486         }
487
488         file_list_entry_t *entry = xmalloc(sizeof(*entry));
489         memset(entry, 0, sizeof(*entry));
490
491         size_t  name_len = strlen(buffer) + 1;
492         char   *name     = malloc(name_len);
493         memcpy(name, buffer, name_len);
494         entry->name      = name;
495
496         entry->next = temp_files;
497         temp_files  = entry;
498
499         return out;
500 }
501
502 static void free_temp_files(void)
503 {
504         file_list_entry_t *entry = temp_files;
505         file_list_entry_t *next;
506         for ( ; entry != NULL; entry = next) {
507                 next = entry->next;
508
509                 unlink(entry->name);
510                 free((char*) entry->name);
511                 free(entry);
512         }
513         temp_files = NULL;
514 }
515
516 typedef enum compile_mode_t {
517         BenchmarkParser,
518         PreprocessOnly,
519         ParseOnly,
520         Compile,
521         CompileDump,
522         CompileExportIR,
523         CompileAssemble,
524         CompileAssembleLink,
525         LexTest,
526         PrintAst,
527         PrintFluffy,
528         PrintJna
529 } compile_mode_t;
530
531 static void usage(const char *argv0)
532 {
533         fprintf(stderr, "Usage %s [options] input [-o output]\n", argv0);
534 }
535
536 static void print_cparser_version(void)
537 {
538         printf("cparser (%s) using libFirm (%u.%u",
539                cparser_REVISION, ir_get_version_major(),
540                ir_get_version_minor());
541
542         const char *revision = ir_get_version_revision();
543         if (revision[0] != 0) {
544                 putchar('-');
545                 fputs(revision, stdout);
546         }
547
548         const char *build = ir_get_version_build();
549         if (build[0] != 0) {
550                 putchar(' ');
551                 fputs(build, stdout);
552         }
553         puts(")");
554         puts("This is free software; see the source for copying conditions.  There is NO\n"
555              "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
556 }
557
558 static void print_cparser_version_short(void)
559 {
560         puts(cparser_REVISION);
561 }
562
563 static void print_help_basic(const char *argv0)
564 {
565         usage(argv0);
566         puts("");
567         put_help("--help",                   "Display this information");
568         put_help("--version",                "Display compiler version");
569         put_help("--help-parser",            "Display information about parser options");
570         put_help("--help-warnings",          "Display information about warning options");
571         put_help("--help-codegen",           "Display information about code-generation options");
572         put_help("--help-optimization",      "Display information about optimization options");
573         put_help("--help-linker",            "Display information about linker options");
574         put_help("--help-language-tools",    "Display information about language tools options");
575         put_help("--help-debug",             "Display information about compiler debugging options");
576         put_help("--help-firm",              "Display information about direct firm options");
577         put_help("--help-all",               "Display information about all options");
578         put_help("-c",                       "Compile and assemble but do not link");
579         put_help("-E",                       "Preprocess only");
580         put_help("-S",                       "Compile but do not assembler or link");
581         put_help("-o",                       "Specify output file");
582         put_help("-v",                       "Verbose output (show invocation of sub-processes)");
583         put_help("-x",                       "Force input language:");
584         put_choice("c",                      "C");
585         put_choice("c++",                    "C++");
586         put_choice("assembler",              "Assembler (no preprocessing)");
587         put_choice("assembler-with-cpp",     "Assembler with preprocessing");
588         put_choice("none",                   "Autodetection");
589         put_help("-pipe",                    "Ignored (gcc compatibility)");
590 }
591
592 static void print_help_preprocessor(void)
593 {
594         put_help("-nostdinc",                "Do not search standard system include directories");
595         put_help("-trigraphs",               "Support ISO C trigraphs");
596         put_help("-isystem",                 "");
597         put_help("-include",                 "");
598         put_help("-I PATH",                  "");
599         put_help("-D SYMBOL[=value]",        "");
600         put_help("-U SYMBOL",                "");
601         put_help("-Wp,OPTION",               "Pass option directly to preprocessor");
602         put_help("-M",                       "");
603         put_help("-MD",                      "");
604         put_help("-MMD",                     "");
605         put_help("-MM",                      "");
606         put_help("-MP",                      "");
607         put_help("-MT",                      "");
608         put_help("-MQ",                      "");
609         put_help("-MF",                      "");
610 }
611
612 static void print_help_parser(void)
613 {
614         put_help("-finput-charset=CHARSET",  "Select encoding of input files");
615         put_help("-fmessage-length=LEN",     "Ignored (gcc compatibility)");
616         put_help("-fshort-wchar",            "Type \"wchar_t\" is unsigned short instead of int");
617         put_help("-fshow-column",            "Show the column number in diagnostic messages");
618         put_help("-fsigned-char",            "Type \"char\" is a signed type");
619         put_help("-funsigned-char",          "Type \"char\" is an unsigned type");
620         put_help("--ms",                     "Enable msvc extensions");
621         put_help("--no-ms",                  "Disable msvc extensions");
622         put_help("--gcc",                    "Enable gcc extensions");
623         put_help("--no-gcc",                 "Disable gcc extensions");
624         put_help("-std=STANDARD",            "Specify language standard:");
625         put_choice("c99",                    "ISO C99 standard");
626         put_choice("c89",                    "ISO C89 standard");
627         put_choice("c9x",                    "Deprecated");
628         put_choice("c++",                    "ISO C++ 98");
629         put_choice("c++98",                  "ISO C++ 98");
630         put_choice("gnu99",                  "ISO C99 + GNU extensions (default)");
631         put_choice("gnu89",                  "ISO C89 + GNU extensions");
632         put_choice("gnu9x",                  "Deprecated");
633         put_choice("iso9899:1990",           "ISO C89");
634         put_choice("iso9899:199409",         "ISO C90");
635         put_choice("iso9899:1999",           "ISO C99");
636         put_choice("iso9899:199x",           "Deprecated");
637         put_help("-pedantic",                "Ignored (gcc compatibility)");
638         put_help("-ansi",                    "Ignored (gcc compatibility)");
639         put_help("--strict",                 "Enable strict conformance checking");
640 }
641
642 static void print_help_warnings(void)
643 {
644         put_help("-f[no-]diagnostics-show-option", "Show the switch, which controls a warning, after each warning");
645         put_help("-w",                             "Disable all warnings");
646         put_help("-Wno-trigraphs",                 "Warn if input contains trigraphs");
647         put_help("-Wundef",                        "Warn if an undefined macro is used in an #if");
648         put_help("-Wmissing-include-dirs",         "Warn about missing user-specified include directories");
649         put_help("-Wendif-labels",                 "Warn about stray text after #elif and #endif");
650         put_help("-Winit-self",                    "Ignored (gcc compatibility)");
651         put_help("-Wformat-y2k",                   "Ignored (gcc compatibility)");
652         put_help("-Wformat-security",              "Ignored (gcc compatibility)");
653         put_help("-Wold-style-declaration",        "Ignored (gcc compatibility)");
654         put_help("-Wtype-limits",                  "Ignored (gcc compatibility)");
655         print_warning_opt_help();
656 }
657
658 static void print_help_optimization(void)
659 {
660         put_help("-O LEVEL",                 "Select optimization level (0-4)");
661         firm_option_help(put_help);
662         put_help("-fexpensive-optimizations","Ignored (gcc compatibility)");
663 }
664
665 static void print_help_codegeneration(void)
666 {
667         put_help("-g",                       "Generate debug information");
668         put_help("-pg",                      "Instrument code for gnu gprof");
669         put_help("-fomit-frame-pointer",     "Produce code without frame pointer where possible");
670         put_help("-ffreestanding",           "Compile in freestanding mode (see ISO C standard)");
671         put_help("-fhosted",                 "Compile in hosted (not freestanding) mode");
672         put_help("-fprofile-generate",       "Generate instrumented code to collect profile information");
673         put_help("-fprofile-use",            "Use profile information generated by instrumented binaries");
674         put_help("-ffp-precise",             "Precise floating point model");
675         put_help("-ffp-fast",                "Imprecise floating point model");
676         put_help("-ffp-strict",              "Strict floating point model");
677         put_help("-pthread",                 "Use pthread threading library");
678         put_help("-mtarget=TARGET",          "Specify target architecture as CPU-manufacturer-OS triple");
679         put_help("-mtriple=TARGET",          "Alias for -mtarget (clang compatibility)");
680         put_help("-march=ARCH",              "");
681         put_help("-mtune=ARCH",              "");
682         put_help("-mcpu=CPU",                "");
683         put_help("-mfpmath=",                "");
684         put_help("-mpreferred-stack-boundary=", "");
685         put_help("-mrtd",                    "");
686         put_help("-mregparm=",               "Not supported yet");
687         put_help("-msoft-float",             "Not supported yet");
688         put_help("-m32",                     "Generate 32bit code");
689         put_help("-m64",                     "Generate 64bit code");
690         put_help("-fverbose-asm",            "Ignored (gcc compatibility)");
691         put_help("-fjump-tables",            "Ignored (gcc compatibility)");
692         put_help("-fcommon",                 "Ignored (gcc compatibility)");
693         put_help("-foptimize-sibling-calls", "Ignored (gcc compatibility)");
694         put_help("-falign-loops",            "Ignored (gcc compatibility)");
695         put_help("-falign-jumps",            "Ignored (gcc compatibility)");
696         put_help("-falign-functions",        "Ignored (gcc compatibility)");
697         put_help("-fPIC",                    "Ignored (gcc compatibility)");
698         put_help("-ffast-math",              "Same as -ffp-fast (gcc compatibility)");
699         puts("");
700         puts("\tMost of these options can be used with a no- prefix to disable them");
701         puts("\te.g. -fno-omit-frame-pointer");
702 }
703
704 static void print_help_linker(void)
705 {
706         put_help("-l LIBRARY",               "");
707         put_help("-L PATH",                  "");
708         put_help("-s",                       "Do not produce symbol table and relocation information");
709         put_help("-shared",                  "Produce a shared library");
710         put_help("-static",                  "Produce statically linked binary");
711         put_help("-Wl,OPTION",               "Pass option directly to linker");
712 }
713
714 static void print_help_debug(void)
715 {
716         put_help("--lextest",                "Preprocess and tokenize only");
717         put_help("--print-ast",              "Preprocess, parse and print AST");
718         put_help("--print-implicit-cast",    "");
719         put_help("--print-parenthesis",      "");
720         put_help("--benchmark",              "Preprocess and parse, produces no output");
721         put_help("--time",                   "Measure time of compiler passes");
722         put_help("--dump-function func",     "Preprocess, parse and output vcg graph of func");
723         put_help("--export-ir",              "Preprocess, parse and output compiler intermediate representation");
724 }
725
726 static void print_help_language_tools(void)
727 {
728         put_help("--print-fluffy",           "Preprocess, parse and generate declarations for the fluffy language");
729         put_help("--print-jna",              "Preprocess, parse and generate declarations for JNA");
730         put_help("--jna-limit filename",     "");
731         put_help("--jna-libname name",       "");
732 }
733
734 static void print_help_firm(void)
735 {
736         put_help("-bOPTION",                 "Directly pass option to libFirm backend");
737         int res = be_parse_arg("help");
738         (void) res;
739         assert(res);
740 }
741
742 typedef enum {
743         HELP_NONE          = 0,
744         HELP_BASIC         = 1 << 0,
745         HELP_PREPROCESSOR  = 1 << 1,
746         HELP_PARSER        = 1 << 2,
747         HELP_WARNINGS      = 1 << 3,
748         HELP_OPTIMIZATION  = 1 << 4,
749         HELP_CODEGEN       = 1 << 5,
750         HELP_LINKER        = 1 << 6,
751         HELP_LANGUAGETOOLS = 1 << 7,
752         HELP_DEBUG         = 1 << 8,
753         HELP_FIRM          = 1 << 9,
754
755         HELP_ALL           = -1
756 } help_sections_t;
757
758 static void print_help(const char *argv0, help_sections_t sections)
759 {
760         if (sections & HELP_BASIC)         print_help_basic(argv0);
761         if (sections & HELP_PREPROCESSOR)  print_help_preprocessor();
762         if (sections & HELP_PARSER)        print_help_parser();
763         if (sections & HELP_WARNINGS)      print_help_warnings();
764         if (sections & HELP_OPTIMIZATION)  print_help_optimization();
765         if (sections & HELP_CODEGEN)       print_help_codegeneration();
766         if (sections & HELP_LINKER)        print_help_linker();
767         if (sections & HELP_LANGUAGETOOLS) print_help_language_tools();
768         if (sections & HELP_DEBUG)         print_help_debug();
769         if (sections & HELP_FIRM)          print_help_firm();
770 }
771
772 static void set_be_option(const char *arg)
773 {
774         int res = be_parse_arg(arg);
775         (void) res;
776         assert(res);
777 }
778
779 static void copy_file(FILE *dest, FILE *input)
780 {
781         char buf[16384];
782
783         while (!feof(input) && !ferror(dest)) {
784                 size_t read = fread(buf, 1, sizeof(buf), input);
785                 if (fwrite(buf, 1, read, dest) != read) {
786                         perror("could not write output");
787                 }
788         }
789 }
790
791 static FILE *open_file(const char *filename)
792 {
793         if (streq(filename, "-")) {
794                 return stdin;
795         }
796
797         FILE *in = fopen(filename, "r");
798         if (in == NULL) {
799                 fprintf(stderr, "Could not open '%s': %s\n", filename,
800                                 strerror(errno));
801                 exit(EXIT_FAILURE);
802         }
803
804         return in;
805 }
806
807 static filetype_t get_filetype_from_string(const char *string)
808 {
809         if (streq(string, "c") || streq(string, "c-header"))
810                 return FILETYPE_C;
811         if (streq(string, "c++") || streq(string, "c++-header"))
812                 return FILETYPE_CXX;
813         if (streq(string, "assembler"))
814                 return FILETYPE_PREPROCESSED_ASSEMBLER;
815         if (streq(string, "assembler-with-cpp"))
816                 return FILETYPE_ASSEMBLER;
817         if (streq(string, "none"))
818                 return FILETYPE_AUTODETECT;
819
820         return FILETYPE_UNKNOWN;
821 }
822
823 static bool init_os_support(void)
824 {
825         wchar_atomic_kind         = ATOMIC_TYPE_INT;
826         enable_main_collect2_hack = false;
827         define_intmax_types       = false;
828
829         if (firm_is_unixish_os(target_machine)) {
830                 set_create_ld_ident(create_name_linux_elf);
831         } else if (firm_is_darwin_os(target_machine)) {
832                 set_create_ld_ident(create_name_macho);
833                 define_intmax_types = true;
834         } else if (firm_is_windows_os(target_machine)) {
835                 wchar_atomic_kind         = ATOMIC_TYPE_USHORT;
836                 enable_main_collect2_hack = true;
837                 set_create_ld_ident(create_name_win32);
838         } else {
839                 return false;
840         }
841
842         return true;
843 }
844
845 static bool parse_target_triple(const char *arg)
846 {
847         machine_triple_t *triple = firm_parse_machine_triple(arg);
848         if (triple == NULL) {
849                 fprintf(stderr, "Target-triple is not in the form 'cpu_type-manufacturer-operating_system'\n");
850                 return false;
851         }
852         target_machine = triple;
853         return true;
854 }
855
856 static unsigned decide_modulo_shift(unsigned type_size)
857 {
858         if (architecture_modulo_shift == 0)
859                 return 0;
860         if (type_size < architecture_modulo_shift)
861                 return architecture_modulo_shift;
862         return type_size;
863 }
864
865 static bool is_ia32_cpu(const char *architecture)
866 {
867         return streq(architecture, "i386")
868             || streq(architecture, "i486")
869             || streq(architecture, "i586")
870             || streq(architecture, "i686")
871             || streq(architecture, "i786");
872 }
873
874 static const char *setup_isa_from_tripel(const machine_triple_t *machine)
875 {
876         const char *cpu = machine->cpu_type;
877
878         if (is_ia32_cpu(cpu)) {
879                 return "ia32";
880         } else if (streq(cpu, "x86_64")) {
881                 return "amd64";
882         } else if (streq(cpu, "sparc")) {
883                 return "sparc";
884         } else if (streq(cpu, "arm")) {
885                 return "arm";
886         } else {
887                 fprintf(stderr, "Unknown cpu '%s' in target-triple\n", cpu);
888                 return NULL;
889         }
890 }
891
892 static const char *setup_target_machine(void)
893 {
894         if (!setup_firm_for_machine(target_machine))
895                 exit(1);
896
897         const char *isa = setup_isa_from_tripel(target_machine);
898
899         if (isa == NULL)
900                 exit(1);
901
902         init_os_support();
903
904         return isa;
905 }
906
907 /**
908  * initialize cparser type properties based on a firm type
909  */
910 static void set_typeprops_type(atomic_type_properties_t* props, ir_type *type)
911 {
912         props->size             = get_type_size_bytes(type);
913         props->alignment        = get_type_alignment_bytes(type);
914         props->struct_alignment = props->alignment;
915 }
916
917 /**
918  * Copy atomic type properties except the integer conversion rank
919  */
920 static void copy_typeprops(atomic_type_properties_t *dest,
921                            const atomic_type_properties_t *src)
922 {
923         dest->size             = src->size;
924         dest->alignment        = src->alignment;
925         dest->struct_alignment = src->struct_alignment;
926         dest->flags            = src->flags;
927 }
928
929 static void init_types_and_adjust(void)
930 {
931         const backend_params *be_params = be_get_backend_param();
932         unsigned machine_size = be_params->machine_size;
933         init_types(machine_size);
934
935         atomic_type_properties_t *props = atomic_type_properties;
936
937         /* adjust types as requested by target architecture */
938         ir_type *type_long_double = be_params->type_long_double;
939         if (type_long_double != NULL) {
940                 set_typeprops_type(&props[ATOMIC_TYPE_LONG_DOUBLE], type_long_double);
941                 atomic_modes[ATOMIC_TYPE_LONG_DOUBLE] = get_type_mode(type_long_double);
942         }
943
944         ir_type *type_long_long = be_params->type_long_long;
945         if (type_long_long != NULL)
946                 set_typeprops_type(&props[ATOMIC_TYPE_LONGLONG], type_long_long);
947
948         ir_type *type_unsigned_long_long = be_params->type_unsigned_long_long;
949         if (type_unsigned_long_long != NULL)
950                 set_typeprops_type(&props[ATOMIC_TYPE_ULONGLONG], type_unsigned_long_long);
951
952         /* operating system ABI specifics */
953         if (firm_is_darwin_os(target_machine)) {
954                 if (machine_size == 32) {
955                         props[ATOMIC_TYPE_LONGLONG].struct_alignment    =  4;
956                         props[ATOMIC_TYPE_ULONGLONG].struct_alignment   =  4;
957                         props[ATOMIC_TYPE_DOUBLE].struct_alignment      =  4;
958                         props[ATOMIC_TYPE_LONG_DOUBLE].size             = 16;
959                         props[ATOMIC_TYPE_LONG_DOUBLE].alignment        = 16;
960                         props[ATOMIC_TYPE_LONG_DOUBLE].struct_alignment = 16;
961                 }
962         } else if (firm_is_windows_os(target_machine)) {
963                 if (machine_size == 64) {
964                         /* to ease porting of old c-code microsoft decided to use 32bits
965                          * even for long */
966                         props[ATOMIC_TYPE_LONG]  = props[ATOMIC_TYPE_INT];
967                         props[ATOMIC_TYPE_ULONG] = props[ATOMIC_TYPE_UINT];
968                 }
969
970                 /* on windows long double is not supported */
971                 props[ATOMIC_TYPE_LONG_DOUBLE] = props[ATOMIC_TYPE_DOUBLE];
972         } else if (firm_is_unixish_os(target_machine)) {
973                 if (is_ia32_cpu(target_machine->cpu_type)) {
974                         /* System V has a broken alignment for double so we have to add
975                          * a hack here */
976                         props[ATOMIC_TYPE_DOUBLE].struct_alignment    = 4;
977                         props[ATOMIC_TYPE_LONGLONG].struct_alignment  = 4;
978                         props[ATOMIC_TYPE_ULONGLONG].struct_alignment = 4;
979                 }
980         }
981
982         /* stuff decided after processing operating system specifics and
983          * commandline flags */
984         if (char_is_signed) {
985                 props[ATOMIC_TYPE_CHAR].flags |= ATOMIC_TYPE_FLAG_SIGNED;
986         } else {
987                 props[ATOMIC_TYPE_CHAR].flags &= ~ATOMIC_TYPE_FLAG_SIGNED;
988         }
989         /* copy over wchar_t properties (including rank) */
990         props[ATOMIC_TYPE_WCHAR_T] = props[wchar_atomic_kind];
991
992         /* initialize defaults for unsupported types */
993         if (type_long_long == NULL) {
994                 copy_typeprops(&props[ATOMIC_TYPE_LONGLONG], &props[ATOMIC_TYPE_LONG]);
995         }
996         if (type_unsigned_long_long == NULL) {
997                 copy_typeprops(&props[ATOMIC_TYPE_ULONGLONG],
998                                &props[ATOMIC_TYPE_ULONG]);
999         }
1000         if (type_long_double == NULL) {
1001                 copy_typeprops(&props[ATOMIC_TYPE_LONG_DOUBLE],
1002                                &props[ATOMIC_TYPE_DOUBLE]);
1003         }
1004
1005         /* initialize firm pointer modes */
1006         char               name[64];
1007         unsigned           bit_size     = machine_size;
1008         unsigned           modulo_shift = decide_modulo_shift(bit_size);
1009
1010         snprintf(name, sizeof(name), "p%u", machine_size);
1011         ir_mode *ptr_mode = new_reference_mode(name, irma_twos_complement, bit_size, modulo_shift);
1012
1013         if (machine_size == 16) {
1014                 set_reference_mode_signed_eq(ptr_mode, mode_Hs);
1015                 set_reference_mode_unsigned_eq(ptr_mode, mode_Hu);
1016         } else if (machine_size == 32) {
1017                 set_reference_mode_signed_eq(ptr_mode, mode_Is);
1018                 set_reference_mode_unsigned_eq(ptr_mode, mode_Iu);
1019         } else if (machine_size == 64) {
1020                 set_reference_mode_signed_eq(ptr_mode, mode_Ls);
1021                 set_reference_mode_unsigned_eq(ptr_mode, mode_Lu);
1022         } else {
1023                 panic("strange machine_size when determining pointer modes");
1024         }
1025
1026         /* Hmm, pointers should be machine size */
1027         set_modeP_data(ptr_mode);
1028         set_modeP_code(ptr_mode);
1029
1030         byte_order_big_endian = be_params->byte_order_big_endian;
1031         if (be_params->modulo_shift_efficient) {
1032                 architecture_modulo_shift = machine_size;
1033         } else {
1034                 architecture_modulo_shift = 0;
1035         }
1036 }
1037
1038 int main(int argc, char **argv)
1039 {
1040         const char        *dumpfunction         = NULL;
1041         const char        *print_file_name_file = NULL;
1042         compile_mode_t     mode                 = CompileAssembleLink;
1043         int                opt_level            = 1;
1044         int                result               = EXIT_SUCCESS;
1045         char               cpu_arch[16]         = "ia32";
1046         file_list_entry_t *files                = NULL;
1047         file_list_entry_t *last_file            = NULL;
1048         bool               construct_dep_target = false;
1049         bool               do_timing            = false;
1050         bool               profile_generate     = false;
1051         bool               profile_use          = false;
1052         struct obstack     file_obst;
1053
1054         atexit(free_temp_files);
1055
1056         /* hack for now... */
1057         if (strstr(argv[0], "pptest") != NULL) {
1058                 extern int pptest_main(int argc, char **argv);
1059                 return pptest_main(argc, argv);
1060         }
1061
1062         obstack_init(&cppflags_obst);
1063         obstack_init(&ldflags_obst);
1064         obstack_init(&asflags_obst);
1065         obstack_init(&file_obst);
1066
1067 #define GET_ARG_AFTER(def, args)                                             \
1068         do {                                                                     \
1069         def = &arg[sizeof(args)-1];                                              \
1070         if (def[0] == '\0') {                                                    \
1071                 ++i;                                                                 \
1072                 if (i >= argc) {                                                     \
1073                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
1074                         argument_errors = true;                                          \
1075                         break;                                                           \
1076                 }                                                                    \
1077                 def = argv[i];                                                       \
1078                 if (def[0] == '-' && def[1] != '\0') {                               \
1079                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
1080                         argument_errors = true;                                          \
1081                         continue;                                                        \
1082                 }                                                                    \
1083         }                                                                        \
1084         } while (0)
1085
1086 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
1087
1088         /* initialize this early because it has to parse options */
1089         gen_firm_init();
1090
1091         /* early options parsing (find out optimization level and OS) */
1092         for (int i = 1; i < argc; ++i) {
1093                 const char *arg = argv[i];
1094                 if (arg[0] != '-')
1095                         continue;
1096
1097                 const char *option = &arg[1];
1098                 if (option[0] == 'O') {
1099                         sscanf(&option[1], "%d", &opt_level);
1100                 }
1101         }
1102
1103         if (target_machine == NULL) {
1104                 target_machine = firm_get_host_machine();
1105         }
1106         choose_optimization_pack(opt_level);
1107         setup_target_machine();
1108
1109         /* parse rest of options */
1110         lang_standard_t standard        = STANDARD_DEFAULT;
1111         unsigned        features_on     = 0;
1112         unsigned        features_off    = 0;
1113         filetype_t      forced_filetype = FILETYPE_AUTODETECT;
1114         help_sections_t help            = HELP_NONE;
1115         bool            argument_errors = false;
1116         for (int i = 1; i < argc; ++i) {
1117                 const char *arg = argv[i];
1118                 if (arg[0] == '-' && arg[1] != '\0') {
1119                         /* an option */
1120                         const char *option = &arg[1];
1121                         if (option[0] == 'o') {
1122                                 GET_ARG_AFTER(outname, "-o");
1123                         } else if (option[0] == 'g') {
1124                                 /* TODO: parse -gX with 0<=x<=3... */
1125                                 set_be_option("debug=frameinfo");
1126                                 set_be_option("ia32-nooptcc=yes");
1127                         } else if (SINGLE_OPTION('c')) {
1128                                 mode = CompileAssemble;
1129                         } else if (SINGLE_OPTION('E')) {
1130                                 mode = PreprocessOnly;
1131                         } else if (SINGLE_OPTION('s')) {
1132                                 add_flag(&ldflags_obst, "-s");
1133                         } else if (SINGLE_OPTION('S')) {
1134                                 mode = Compile;
1135                         } else if (option[0] == 'O') {
1136                                 continue;
1137                         } else if (option[0] == 'I') {
1138                                 const char *opt;
1139                                 GET_ARG_AFTER(opt, "-I");
1140                                 add_flag(&cppflags_obst, "-I%s", opt);
1141                         } else if (option[0] == 'D') {
1142                                 const char *opt;
1143                                 GET_ARG_AFTER(opt, "-D");
1144                                 add_flag(&cppflags_obst, "-D%s", opt);
1145                         } else if (option[0] == 'U') {
1146                                 const char *opt;
1147                                 GET_ARG_AFTER(opt, "-U");
1148                                 add_flag(&cppflags_obst, "-U%s", opt);
1149                         } else if (option[0] == 'l') {
1150                                 const char *opt;
1151                                 GET_ARG_AFTER(opt, "-l");
1152                                 add_flag(&ldflags_obst, "-l%s", opt);
1153                         } else if (option[0] == 'L') {
1154                                 const char *opt;
1155                                 GET_ARG_AFTER(opt, "-L");
1156                                 add_flag(&ldflags_obst, "-L%s", opt);
1157                         } else if (SINGLE_OPTION('v')) {
1158                                 verbose = 1;
1159                         } else if (SINGLE_OPTION('w')) {
1160                                 add_flag(&cppflags_obst, "-w");
1161                                 disable_all_warnings();
1162                         } else if (option[0] == 'x') {
1163                                 const char *opt;
1164                                 GET_ARG_AFTER(opt, "-x");
1165                                 forced_filetype = get_filetype_from_string(opt);
1166                                 if (forced_filetype == FILETYPE_UNKNOWN) {
1167                                         fprintf(stderr, "Unknown language '%s'\n", opt);
1168                                         argument_errors = true;
1169                                 }
1170                         } else if (streq(option, "M")) {
1171                                 mode = PreprocessOnly;
1172                                 add_flag(&cppflags_obst, "-M");
1173                         } else if (streq(option, "MMD") ||
1174                                    streq(option, "MD")) {
1175                             construct_dep_target = true;
1176                                 add_flag(&cppflags_obst, "-%s", option);
1177                         } else if (streq(option, "MM")  ||
1178                                    streq(option, "MP")) {
1179                                 add_flag(&cppflags_obst, "-%s", option);
1180                         } else if (streq(option, "MT") ||
1181                                    streq(option, "MQ") ||
1182                                    streq(option, "MF")) {
1183                                 const char *opt;
1184                                 GET_ARG_AFTER(opt, "-MT");
1185                                 add_flag(&cppflags_obst, "-%s", option);
1186                                 add_flag(&cppflags_obst, "%s", opt);
1187                         } else if (streq(option, "include")) {
1188                                 const char *opt;
1189                                 GET_ARG_AFTER(opt, "-include");
1190                                 add_flag(&cppflags_obst, "-include");
1191                                 add_flag(&cppflags_obst, "%s", opt);
1192                         } else if (streq(option, "isystem")) {
1193                                 const char *opt;
1194                                 GET_ARG_AFTER(opt, "-isystem");
1195                                 add_flag(&cppflags_obst, "-isystem");
1196                                 add_flag(&cppflags_obst, "%s", opt);
1197 #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__CYGWIN__)
1198                         } else if (streq(option, "pthread")) {
1199                                 /* set flags for the preprocessor */
1200                                 add_flag(&cppflags_obst, "-D_REENTRANT");
1201                                 /* set flags for the linker */
1202                                 add_flag(&ldflags_obst, "-lpthread");
1203 #endif
1204                         } else if (streq(option, "nostdinc")
1205                                         || streq(option, "trigraphs")) {
1206                                 /* pass these through to the preprocessor */
1207                                 add_flag(&cppflags_obst, "%s", arg);
1208                         } else if (streq(option, "pipe")) {
1209                                 /* here for gcc compatibility */
1210                         } else if (streq(option, "static")) {
1211                                 add_flag(&ldflags_obst, "-static");
1212                         } else if (streq(option, "shared")) {
1213                                 add_flag(&ldflags_obst, "-shared");
1214                         } else if (option[0] == 'f') {
1215                                 char const *orig_opt;
1216                                 GET_ARG_AFTER(orig_opt, "-f");
1217
1218                                 if (strstart(orig_opt, "input-charset=")) {
1219                                         char const* const encoding = strchr(orig_opt, '=') + 1;
1220                                         input_encoding = encoding;
1221                                 } else if (strstart(orig_opt, "align-loops=") ||
1222                                            strstart(orig_opt, "align-jumps=") ||
1223                                            strstart(orig_opt, "align-functions=")) {
1224                                         fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
1225                                 } else if (strstart(orig_opt, "visibility=")) {
1226                                         const char *val = strchr(orig_opt, '=')+1;
1227                                         elf_visibility_tag_t visibility
1228                                                 = get_elf_visibility_from_string(val);
1229                                         if (visibility == ELF_VISIBILITY_ERROR) {
1230                                                 fprintf(stderr, "invalid visibility '%s' specified\n",
1231                                                         val);
1232                                                 argument_errors = true;
1233                                         } else {
1234                                                 set_default_visibility(visibility);
1235                                         }
1236                                 } else if (strstart(orig_opt, "message-length=")) {
1237                                         /* ignore: would only affect error message format */
1238                                 } else if (streq(orig_opt, "fast-math") ||
1239                                            streq(orig_opt, "fp-fast")) {
1240                                         firm_fp_model = fp_model_fast;
1241                                 } else if (streq(orig_opt, "fp-precise")) {
1242                                         firm_fp_model = fp_model_precise;
1243                                 } else if (streq(orig_opt, "fp-strict")) {
1244                                         firm_fp_model = fp_model_strict;
1245                                 } else if (streq(orig_opt, "help")) {
1246                                         fprintf(stderr, "warning: -fhelp is deprecated\n");
1247                                         help |= HELP_OPTIMIZATION;
1248                                 } else {
1249                                         /* -f options which have an -fno- variant */
1250                                         char const *opt         = orig_opt;
1251                                         bool        truth_value = true;
1252                                         if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
1253                                                 truth_value = false;
1254                                                 opt += 3;
1255                                         }
1256
1257                                         if (streq(opt, "diagnostics-show-option")) {
1258                                                 diagnostics_show_option = truth_value;
1259                                         } else if (streq(opt, "dollars-in-identifiers")) {
1260                                                 allow_dollar_in_symbol = truth_value;
1261                                         } else if (streq(opt, "omit-frame-pointer")) {
1262                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
1263                                         } else if (streq(opt, "short-wchar")) {
1264                                                 wchar_atomic_kind = truth_value ? ATOMIC_TYPE_USHORT
1265                                                         : ATOMIC_TYPE_INT;
1266                                         } else if (streq(opt, "show-column")) {
1267                                                 show_column = truth_value;
1268                                         } else if (streq(opt, "signed-char")) {
1269                                                 char_is_signed = truth_value;
1270                                         } else if (streq(opt, "strength-reduce")) {
1271                                                 /* does nothing, for gcc compatibility (even gcc does
1272                                                  * nothing for this switch anymore) */
1273                                         } else if (streq(opt, "syntax-only")) {
1274                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
1275                                         } else if (streq(opt, "unsigned-char")) {
1276                                                 char_is_signed = !truth_value;
1277                                         } else if (streq(opt, "freestanding")) {
1278                                                 freestanding = truth_value;
1279                                         } else if (streq(opt, "hosted")) {
1280                                                 freestanding = !truth_value;
1281                                         } else if (streq(opt, "profile-generate")) {
1282                                                 profile_generate = truth_value;
1283                                         } else if (streq(opt, "profile-use")) {
1284                                                 profile_use = truth_value;
1285                                         } else if (!truth_value &&
1286                                                    streq(opt, "asynchronous-unwind-tables")) {
1287                                             /* nothing todo, a gcc feature which we do not support
1288                                              * anyway was deactivated */
1289                                         } else if (streq(opt, "verbose-asm")) {
1290                                                 /* ignore: we always print verbose assembler */
1291                                         } else if (streq(opt, "jump-tables")             ||
1292                                                    streq(opt, "expensive-optimizations") ||
1293                                                    streq(opt, "common")                  ||
1294                                                    streq(opt, "optimize-sibling-calls")  ||
1295                                                    streq(opt, "align-loops")             ||
1296                                                    streq(opt, "align-jumps")             ||
1297                                                    streq(opt, "align-functions")         ||
1298                                                    streq(opt, "unroll-loops")            ||
1299                                                    streq(opt, "PIC")                     ||
1300                                                    streq(opt, "stack-protector")         ||
1301                                                    streq(opt, "stack-protector-all")) {
1302                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
1303                                         } else {
1304                                                 int res = firm_option(orig_opt);
1305                                                 if (res == 0) {
1306                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
1307                                                                 orig_opt);
1308                                                         argument_errors = true;
1309                                                         continue;
1310                                                 }
1311                                         }
1312                                 }
1313                         } else if (option[0] == 'b') {
1314                                 const char *opt;
1315                                 GET_ARG_AFTER(opt, "-b");
1316
1317                                 if (streq(opt, "help")) {
1318                                         fprintf(stderr, "warning: -bhelp is deprecated (use --help-firm)\n");
1319                                         help |= HELP_FIRM;
1320                                 } else {
1321                                         int res = be_parse_arg(opt);
1322                                         if (res == 0) {
1323                                                 fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
1324                                                                 opt);
1325                                                 argument_errors = true;
1326                                         } else if (strstart(opt, "isa=")) {
1327                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
1328                                         }
1329                                 }
1330                         } else if (option[0] == 'W') {
1331                                 if (strstart(option + 1, "p,")) {
1332                                         // pass options directly to the preprocessor
1333                                         const char *opt;
1334                                         GET_ARG_AFTER(opt, "-Wp,");
1335                                         add_flag(&cppflags_obst, "-Wp,%s", opt);
1336                                 } else if (strstart(option + 1, "l,")) {
1337                                         // pass options directly to the linker
1338                                         const char *opt;
1339                                         GET_ARG_AFTER(opt, "-Wl,");
1340                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
1341                                 } else if (streq(option + 1, "no-trigraphs")
1342                                                         || streq(option + 1, "undef")
1343                                                         || streq(option + 1, "missing-include-dirs")
1344                                                         || streq(option + 1, "endif-labels")) {
1345                                         add_flag(&cppflags_obst, "%s", arg);
1346                                 } else if (streq(option+1, "init-self")) {
1347                                         /* ignored (same as gcc does) */
1348                                 } else if (streq(option+1, "format-y2k")
1349                                            || streq(option+1, "format-security")
1350                                            || streq(option+1, "old-style-declaration")
1351                                            || streq(option+1, "type-limits")) {
1352                                     /* ignore (gcc compatibility) */
1353                                 } else {
1354                                         set_warning_opt(&option[1]);
1355                                 }
1356                         } else if (option[0] == 'm') {
1357                                 /* -m options */
1358                                 const char *opt;
1359                                 char arch_opt[64];
1360
1361                                 GET_ARG_AFTER(opt, "-m");
1362                                 if (strstart(opt, "target=")) {
1363                                         GET_ARG_AFTER(opt, "-mtarget=");
1364                                         if (!parse_target_triple(opt)) {
1365                                                 argument_errors = true;
1366                                         } else {
1367                                                 const char *isa = setup_target_machine();
1368                                                 strncpy(cpu_arch, isa, sizeof(cpu_arch));
1369                                                 target_triple = opt;
1370                                         }
1371                                 } else if (strstart(opt, "triple=")) {
1372                                         GET_ARG_AFTER(opt, "-mtriple=");
1373                                         if (!parse_target_triple(opt)) {
1374                                                 argument_errors = true;
1375                                         } else {
1376                                                 const char *isa = setup_target_machine();
1377                                                 strncpy(cpu_arch, isa, sizeof(cpu_arch));
1378                                                 target_triple = opt;
1379                                         }
1380                                 } else if (strstart(opt, "arch=")) {
1381                                         GET_ARG_AFTER(opt, "-march=");
1382                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
1383                                         int res = be_parse_arg(arch_opt);
1384                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
1385                                         res &= be_parse_arg(arch_opt);
1386
1387                                         if (res == 0) {
1388                                                 fprintf(stderr, "Unknown architecture '%s'\n", arch_opt);
1389                                                 argument_errors = true;
1390                                         }
1391                                 } else if (strstart(opt, "tune=")) {
1392                                         GET_ARG_AFTER(opt, "-mtune=");
1393                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
1394                                         int res = be_parse_arg(arch_opt);
1395                                         if (res == 0)
1396                                                 argument_errors = true;
1397                                 } else if (strstart(opt, "cpu=")) {
1398                                         GET_ARG_AFTER(opt, "-mcpu=");
1399                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
1400                                         int res = be_parse_arg(arch_opt);
1401                                         if (res == 0)
1402                                                 argument_errors = true;
1403                                 } else if (strstart(opt, "fpmath=")) {
1404                                         GET_ARG_AFTER(opt, "-mfpmath=");
1405                                         if (streq(opt, "387"))
1406                                                 opt = "x87";
1407                                         else if (streq(opt, "sse"))
1408                                                 opt = "sse2";
1409                                         else {
1410                                                 fprintf(stderr, "error: option -mfpmath supports only 387 or sse\n");
1411                                                 argument_errors = true;
1412                                         }
1413                                         if (!argument_errors) {
1414                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
1415                                                 int res = be_parse_arg(arch_opt);
1416                                                 if (res == 0)
1417                                                         argument_errors = true;
1418                                         }
1419                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
1420                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
1421                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
1422                                         int res = be_parse_arg(arch_opt);
1423                                         if (res == 0)
1424                                                 argument_errors = true;
1425                                 } else if (streq(opt, "rtd")) {
1426                                         default_calling_convention = CC_STDCALL;
1427                                 } else if (strstart(opt, "regparm=")) {
1428                                         fprintf(stderr, "error: regparm convention not supported yet\n");
1429                                         argument_errors = true;
1430                                 } else if (streq(opt, "soft-float")) {
1431                                         add_flag(&ldflags_obst, "-msoft-float");
1432                                         snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=softfloat", cpu_arch);
1433                                         int res = be_parse_arg(arch_opt);
1434                                         if (res == 0)
1435                                                 argument_errors = true;
1436                                 } else if (streq(opt, "sse2")) {
1437                                         /* ignore for now, our x86 backend always uses sse when
1438                                          * sse is requested */
1439                                 } else {
1440                                         long int value = strtol(opt, NULL, 10);
1441                                         if (value == 0) {
1442                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
1443                                                 argument_errors = true;
1444                                         } else if (value != 16 && value != 32 && value != 64) {
1445                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
1446                                                 argument_errors = true;
1447                                         } else {
1448                                                 unsigned machine_size = (unsigned)value;
1449                                                 /* TODO: choose/change backend based on this */
1450                                                 add_flag(&cppflags_obst, "-m%u", machine_size);
1451                                                 add_flag(&asflags_obst, "-m%u", machine_size);
1452                                                 add_flag(&ldflags_obst, "-m%u", machine_size);
1453                                         }
1454                                 }
1455                         } else if (streq(option, "pg")) {
1456                                 set_be_option("gprof");
1457                                 add_flag(&ldflags_obst, "-pg");
1458                         } else if (streq(option, "ansi")) {
1459                                 add_flag(&cppflags_obst, "-ansi");
1460                         } else if (streq(option, "pedantic")) {
1461                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
1462                         } else if (strstart(option, "std=")) {
1463                                 const char *const o = &option[4];
1464                                 standard =
1465                                         streq(o, "c++")            ? STANDARD_CXX98   :
1466                                         streq(o, "c++98")          ? STANDARD_CXX98   :
1467                                         streq(o, "c89")            ? STANDARD_C89     :
1468                                         streq(o, "c99")            ? STANDARD_C99     :
1469                                         streq(o, "c9x")            ? STANDARD_C99     : // deprecated
1470                                         streq(o, "gnu++98")        ? STANDARD_GNUXX98 :
1471                                         streq(o, "gnu89")          ? STANDARD_GNU89   :
1472                                         streq(o, "gnu99")          ? STANDARD_GNU99   :
1473                                         streq(o, "gnu9x")          ? STANDARD_GNU99   : // deprecated
1474                                         streq(o, "iso9899:1990")   ? STANDARD_C89     :
1475                                         streq(o, "iso9899:199409") ? STANDARD_C89AMD1 :
1476                                         streq(o, "iso9899:1999")   ? STANDARD_C99     :
1477                                         streq(o, "iso9899:199x")   ? STANDARD_C99     : // deprecated
1478                                         (fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg), standard);
1479                         } else if (streq(option, "version")) {
1480                                 print_cparser_version();
1481                                 return EXIT_SUCCESS;
1482                         } else if (streq(option, "dumpversion")) {
1483                                 /* gcc compatibility option */
1484                                 print_cparser_version_short();
1485                                 return EXIT_SUCCESS;
1486                         } else if (strstart(option, "print-file-name=")) {
1487                                 GET_ARG_AFTER(print_file_name_file, "-print-file-name=");
1488                         } else if (option[0] == '-') {
1489                                 /* double dash option */
1490                                 ++option;
1491                                 if (streq(option, "gcc")) {
1492                                         features_on  |=  _GNUC;
1493                                         features_off &= ~_GNUC;
1494                                 } else if (streq(option, "no-gcc")) {
1495                                         features_on  &= ~_GNUC;
1496                                         features_off |=  _GNUC;
1497                                 } else if (streq(option, "ms")) {
1498                                         features_on  |=  _MS;
1499                                         features_off &= ~_MS;
1500                                 } else if (streq(option, "no-ms")) {
1501                                         features_on  &= ~_MS;
1502                                         features_off |=  _MS;
1503                                 } else if (streq(option, "strict")) {
1504                                         strict_mode = true;
1505                                 } else if (streq(option, "lextest")) {
1506                                         mode = LexTest;
1507                                 } else if (streq(option, "benchmark")) {
1508                                         mode = BenchmarkParser;
1509                                 } else if (streq(option, "print-ast")) {
1510                                         mode = PrintAst;
1511                                 } else if (streq(option, "print-implicit-cast")) {
1512                                         print_implicit_casts = true;
1513                                 } else if (streq(option, "print-parenthesis")) {
1514                                         print_parenthesis = true;
1515                                 } else if (streq(option, "print-fluffy")) {
1516                                         mode = PrintFluffy;
1517                                 } else if (streq(option, "print-jna")) {
1518                                         mode = PrintJna;
1519                                 } else if (streq(option, "jna-limit")) {
1520                                         ++i;
1521                                         if (i >= argc) {
1522                                                 fprintf(stderr, "error: "
1523                                                         "expected argument after '--jna-limit'\n");
1524                                                 argument_errors = true;
1525                                                 break;
1526                                         }
1527                                         jna_limit_output(argv[i]);
1528                                 } else if (streq(option, "jna-libname")) {
1529                                         ++i;
1530                                         if (i >= argc) {
1531                                                 fprintf(stderr, "error: "
1532                                                         "expected argument after '--jna-libname'\n");
1533                                                 argument_errors = true;
1534                                                 break;
1535                                         }
1536                                         jna_set_libname(argv[i]);
1537                                 } else if (streq(option, "time")) {
1538                                         do_timing = true;
1539                                 } else if (streq(option, "version")) {
1540                                         print_cparser_version();
1541                                         return EXIT_SUCCESS;
1542                                 } else if (streq(option, "help")) {
1543                                         help |= HELP_BASIC;
1544                                 } else if (streq(option, "help-parser")) {
1545                                         help |= HELP_PARSER;
1546                                 } else if (streq(option, "help-warnings")) {
1547                                         help |= HELP_WARNINGS;
1548                                 } else if (streq(option, "help-codegen")) {
1549                                         help |= HELP_CODEGEN;
1550                                 } else if (streq(option, "help-linker")) {
1551                                         help |= HELP_LINKER;
1552                                 } else if (streq(option, "help-optimization")) {
1553                                         help |= HELP_OPTIMIZATION;
1554                                 } else if (streq(option, "help-language-tools")) {
1555                                         help |= HELP_LANGUAGETOOLS;
1556                                 } else if (streq(option, "help-debug")) {
1557                                         help |= HELP_DEBUG;
1558                                 } else if (streq(option, "help-firm")) {
1559                                         help |= HELP_FIRM;
1560                                 } else if (streq(option, "help-all")) {
1561                                         help |= HELP_ALL;
1562                                 } else if (streq(option, "dump-function")) {
1563                                         ++i;
1564                                         if (i >= argc) {
1565                                                 fprintf(stderr, "error: "
1566                                                         "expected argument after '--dump-function'\n");
1567                                                 argument_errors = true;
1568                                                 break;
1569                                         }
1570                                         dumpfunction = argv[i];
1571                                         mode         = CompileDump;
1572                                 } else if (streq(option, "export-ir")) {
1573                                         mode = CompileExportIR;
1574                                 } else if (streq(option, "unroll-loops")) {
1575                                         /* ignore (gcc compatibility) */
1576                                 } else {
1577                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
1578                                         argument_errors = true;
1579                                 }
1580                         } else {
1581                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
1582                                 argument_errors = true;
1583                         }
1584                 } else {
1585                         filetype_t type = forced_filetype;
1586                         if (type == FILETYPE_AUTODETECT) {
1587                                 if (streq(arg, "-")) {
1588                                         /* - implicitly means C source file */
1589                                         type = FILETYPE_C;
1590                                 } else {
1591                                         const char *suffix = strrchr(arg, '.');
1592                                         /* Ensure there is at least one char before the suffix */
1593                                         if (suffix != NULL && suffix != arg) {
1594                                                 ++suffix;
1595                                                 type =
1596                                                         streq(suffix, "S")   ? FILETYPE_ASSEMBLER              :
1597                                                         streq(suffix, "a")   ? FILETYPE_OBJECT                 :
1598                                                         streq(suffix, "c")   ? FILETYPE_C                      :
1599                                                         streq(suffix, "i")   ? FILETYPE_PREPROCESSED_C         :
1600                                                         streq(suffix, "C")   ? FILETYPE_CXX                    :
1601                                                         streq(suffix, "cc")  ? FILETYPE_CXX                    :
1602                                                         streq(suffix, "cp")  ? FILETYPE_CXX                    :
1603                                                         streq(suffix, "cpp") ? FILETYPE_CXX                    :
1604                                                         streq(suffix, "CPP") ? FILETYPE_CXX                    :
1605                                                         streq(suffix, "cxx") ? FILETYPE_CXX                    :
1606                                                         streq(suffix, "c++") ? FILETYPE_CXX                    :
1607                                                         streq(suffix, "ii")  ? FILETYPE_PREPROCESSED_CXX       :
1608                                                         streq(suffix, "h")   ? FILETYPE_C                      :
1609                                                         streq(suffix, "ir")  ? FILETYPE_IR                     :
1610                                                         streq(suffix, "o")   ? FILETYPE_OBJECT                 :
1611                                                         streq(suffix, "s")   ? FILETYPE_PREPROCESSED_ASSEMBLER :
1612                                                         streq(suffix, "so")  ? FILETYPE_OBJECT                 :
1613                                                         FILETYPE_OBJECT; /* gcc behavior: unknown file extension means object file */
1614                                         }
1615                                 }
1616                         }
1617
1618                         file_list_entry_t *entry
1619                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
1620                         memset(entry, 0, sizeof(entry[0]));
1621                         entry->name = arg;
1622                         entry->type = type;
1623
1624                         if (last_file != NULL) {
1625                                 last_file->next = entry;
1626                         } else {
1627                                 files = entry;
1628                         }
1629                         last_file = entry;
1630                 }
1631         }
1632
1633         if (help != HELP_NONE) {
1634                 print_help(argv[0], help);
1635                 return !argument_errors;
1636         }
1637
1638         if (print_file_name_file != NULL) {
1639                 print_file_name(print_file_name_file);
1640                 return EXIT_SUCCESS;
1641         }
1642         if (files == NULL) {
1643                 fprintf(stderr, "error: no input files specified\n");
1644                 argument_errors = true;
1645         }
1646
1647         if (argument_errors) {
1648                 usage(argv[0]);
1649                 return EXIT_FAILURE;
1650         }
1651
1652         /* apply some effects from switches */
1653         c_mode |= features_on;
1654         c_mode &= ~features_off;
1655         if (profile_generate) {
1656                 add_flag(&ldflags_obst, "-lfirmprof");
1657                 set_be_option("profilegenerate");
1658         }
1659         if (profile_use) {
1660                 set_be_option("profileuse");
1661         }
1662
1663         init_symbol_table();
1664         init_types_and_adjust();
1665         init_typehash();
1666         init_basic_types();
1667         if (wchar_atomic_kind == ATOMIC_TYPE_INT)
1668                 init_wchar_types(type_int);
1669         else if (wchar_atomic_kind == ATOMIC_TYPE_USHORT)
1670                 init_wchar_types(type_short);
1671         else
1672                 panic("unexpected wchar type");
1673         init_preprocessor();
1674         init_ast();
1675         init_parser();
1676         init_ast2firm();
1677         init_mangle();
1678
1679         if (do_timing)
1680                 timer_init();
1681
1682         if (construct_dep_target) {
1683                 if (outname != 0 && strlen(outname) >= 2) {
1684                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
1685                 } else {
1686                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
1687                 }
1688         } else {
1689                 dep_target[0] = '\0';
1690         }
1691
1692         char outnamebuf[4096];
1693         if (outname == NULL) {
1694                 const char *filename = files->name;
1695
1696                 switch(mode) {
1697                 case BenchmarkParser:
1698                 case PrintAst:
1699                 case PrintFluffy:
1700                 case PrintJna:
1701                 case LexTest:
1702                 case PreprocessOnly:
1703                 case ParseOnly:
1704                         outname = "-";
1705                         break;
1706                 case Compile:
1707                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
1708                         outname = outnamebuf;
1709                         break;
1710                 case CompileAssemble:
1711                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
1712                         outname = outnamebuf;
1713                         break;
1714                 case CompileDump:
1715                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
1716                                         ".vcg");
1717                         outname = outnamebuf;
1718                         break;
1719                 case CompileExportIR:
1720                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".ir");
1721                         outname = outnamebuf;
1722                         break;
1723                 case CompileAssembleLink:
1724 #ifdef _WIN32
1725                         outname = "a.exe";
1726 #else
1727                         outname = "a.out";
1728 #endif
1729                         break;
1730                 }
1731         }
1732
1733         assert(outname != NULL);
1734
1735         FILE *out;
1736         if (streq(outname, "-")) {
1737                 out = stdout;
1738         } else {
1739                 out = fopen(outname, "w");
1740                 if (out == NULL) {
1741                         fprintf(stderr, "Could not open '%s' for writing: %s\n", outname,
1742                                         strerror(errno));
1743                         return EXIT_FAILURE;
1744                 }
1745         }
1746
1747         file_list_entry_t *file;
1748         bool               already_constructed_firm = false;
1749         for (file = files; file != NULL; file = file->next) {
1750                 char            asm_tempfile[1024];
1751                 const char     *filename = file->name;
1752                 filetype_t      filetype = file->type;
1753                 lang_standard_t file_standard = standard;
1754
1755                 if (filetype == FILETYPE_OBJECT)
1756                         continue;
1757                 if (file_standard == STANDARD_DEFAULT) {
1758                         switch (filetype) {
1759                         case FILETYPE_C:
1760                         case FILETYPE_PREPROCESSED_C:
1761                                 file_standard = STANDARD_GNU99;
1762                                 break;
1763                         case FILETYPE_CXX:
1764                         case FILETYPE_PREPROCESSED_CXX:
1765                                 file_standard = STANDARD_GNUXX98;
1766                                 break;
1767                         default:
1768                                 break;
1769                         }
1770                 }
1771
1772                 FILE *in = NULL;
1773                 if (mode == LexTest) {
1774                         if (in == NULL)
1775                                 in = open_file(filename);
1776                         lextest(in, filename);
1777                         fclose(in);
1778                         return EXIT_SUCCESS;
1779                 }
1780
1781                 FILE *preprocessed_in = NULL;
1782                 filetype_t next_filetype = filetype;
1783                 switch (filetype) {
1784                         case FILETYPE_C:
1785                                 next_filetype = FILETYPE_PREPROCESSED_C;
1786                                 goto preprocess;
1787                         case FILETYPE_CXX:
1788                                 next_filetype = FILETYPE_PREPROCESSED_CXX;
1789                                 goto preprocess;
1790                         case FILETYPE_ASSEMBLER:
1791                                 next_filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1792                                 goto preprocess;
1793 preprocess:
1794                                 /* no support for input on FILE* yet */
1795                                 if (in != NULL)
1796                                         panic("internal compiler error: in for preprocessor != NULL");
1797
1798                                 preprocessed_in = preprocess(filename, filetype,
1799                                                              file_standard);
1800                                 if (mode == PreprocessOnly) {
1801                                         copy_file(out, preprocessed_in);
1802                                         int pp_result = pclose(preprocessed_in);
1803                                         fclose(out);
1804                                         /* remove output file in case of error */
1805                                         if (out != stdout && pp_result != EXIT_SUCCESS) {
1806                                                 unlink(outname);
1807                                         }
1808                                         return pp_result;
1809                                 }
1810
1811                                 in = preprocessed_in;
1812                                 filetype = next_filetype;
1813                                 break;
1814
1815                         default:
1816                                 break;
1817                 }
1818
1819                 FILE *asm_out;
1820                 if (mode == Compile) {
1821                         asm_out = out;
1822                 } else {
1823                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "ccs");
1824                 }
1825
1826                 if (in == NULL)
1827                         in = open_file(filename);
1828
1829                 /* preprocess and compile */
1830                 if (filetype == FILETYPE_PREPROCESSED_C) {
1831                         char const* invalid_mode;
1832                         switch (file_standard) {
1833                         case STANDARD_C89:     c_mode = _C89;                break;
1834                         /* TODO determine difference between these two */
1835                         case STANDARD_C89AMD1: c_mode = _C89;                break;
1836                         case STANDARD_C99:     c_mode = _C89 | _C99;         break;
1837                         case STANDARD_GNU89:   c_mode = _C89 |        _GNUC; break;
1838
1839 default_c_warn:
1840                                 fprintf(stderr,
1841                                                 "warning: command line option \"-std=%s\" is not valid for C\n",
1842                                                 invalid_mode);
1843                                 /* FALLTHROUGH */
1844                         case STANDARD_GNU99:   c_mode = _C89 | _C99 | _GNUC; break;
1845
1846                         case STANDARD_CXX98:   invalid_mode = "c++98"; goto default_c_warn;
1847                         case STANDARD_GNUXX98: invalid_mode = "gnu98"; goto default_c_warn;
1848                         case STANDARD_DEFAULT: panic("invalid standard");
1849                         }
1850                         goto do_parsing;
1851                 } else if (filetype == FILETYPE_PREPROCESSED_CXX) {
1852                         char const* invalid_mode;
1853                         switch (file_standard) {
1854                         case STANDARD_C89:     invalid_mode = "c89";   goto default_cxx_warn;
1855                         case STANDARD_C89AMD1: invalid_mode = "c90";   goto default_cxx_warn;
1856                         case STANDARD_C99:     invalid_mode = "c99";   goto default_cxx_warn;
1857                         case STANDARD_GNU89:   invalid_mode = "gnu89"; goto default_cxx_warn;
1858                         case STANDARD_GNU99:   invalid_mode = "gnu99"; goto default_cxx_warn;
1859
1860                         case STANDARD_CXX98: c_mode = _CXX; break;
1861
1862 default_cxx_warn:
1863                                 fprintf(stderr,
1864                                                 "warning: command line option \"-std=%s\" is not valid for C++\n",
1865                                                 invalid_mode);
1866                         case STANDARD_GNUXX98: c_mode = _CXX | _GNUC; break;
1867                         case STANDARD_DEFAULT: panic("invalid standard");
1868                         }
1869
1870 do_parsing:
1871                         c_mode |= features_on;
1872                         c_mode &= ~features_off;
1873
1874                         /* do the actual parsing */
1875                         ir_timer_t *t_parsing = ir_timer_new();
1876                         timer_register(t_parsing, "Frontend: Parsing");
1877                         timer_push(t_parsing);
1878                         init_tokens();
1879                         translation_unit_t *const unit = do_parsing(in, filename);
1880                         timer_pop(t_parsing);
1881
1882                         /* prints the AST even if errors occurred */
1883                         if (mode == PrintAst) {
1884                                 print_to_file(out);
1885                                 print_ast(unit);
1886                         }
1887
1888                         if (error_count > 0) {
1889                                 /* parsing failed because of errors */
1890                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1891                                         warning_count);
1892                                 result = EXIT_FAILURE;
1893                                 continue;
1894                         } else if (warning_count > 0) {
1895                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1896                         }
1897
1898                         if (in == preprocessed_in) {
1899                                 int pp_result = pclose(preprocessed_in);
1900                                 if (pp_result != EXIT_SUCCESS) {
1901                                         /* remove output file */
1902                                         if (out != stdout)
1903                                                 unlink(outname);
1904                                         return EXIT_FAILURE;
1905                                 }
1906                         }
1907
1908                         if (mode == BenchmarkParser) {
1909                                 return result;
1910                         } else if (mode == PrintFluffy) {
1911                                 write_fluffy_decls(out, unit);
1912                                 continue;
1913                         } else if (mode == PrintJna) {
1914                                 write_jna_decls(out, unit);
1915                                 continue;
1916                         }
1917
1918                         /* build the firm graph */
1919                         ir_timer_t *t_construct = ir_timer_new();
1920                         timer_register(t_construct, "Frontend: Graph construction");
1921                         timer_push(t_construct);
1922                         if (already_constructed_firm) {
1923                                 panic("compiling multiple files/translation units not possible");
1924                         }
1925                         init_implicit_optimizations();
1926                         translation_unit_to_firm(unit);
1927                         already_constructed_firm = true;
1928                         timer_pop(t_construct);
1929
1930 graph_built:
1931                         if (mode == ParseOnly) {
1932                                 continue;
1933                         }
1934
1935                         if (mode == CompileDump) {
1936                                 /* find irg */
1937                                 ident    *id     = new_id_from_str(dumpfunction);
1938                                 ir_graph *irg    = NULL;
1939                                 int       n_irgs = get_irp_n_irgs();
1940                                 for (int i = 0; i < n_irgs; ++i) {
1941                                         ir_graph *tirg   = get_irp_irg(i);
1942                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1943                                         if (irg_id == id) {
1944                                                 irg = tirg;
1945                                                 break;
1946                                         }
1947                                 }
1948
1949                                 if (irg == NULL) {
1950                                         fprintf(stderr, "No graph for function '%s' found\n",
1951                                                 dumpfunction);
1952                                         return EXIT_FAILURE;
1953                                 }
1954
1955                                 dump_ir_graph_file(out, irg);
1956                                 fclose(out);
1957                                 return EXIT_SUCCESS;
1958                         }
1959
1960                         if (mode == CompileExportIR) {
1961                                 ir_export_file(out);
1962                                 if (ferror(out) != 0) {
1963                                         fprintf(stderr, "Error while writing to output\n");
1964                                         return EXIT_FAILURE;
1965                                 }
1966                                 return EXIT_SUCCESS;
1967                         }
1968
1969                         generate_code(asm_out, filename);
1970                         if (asm_out != out) {
1971                                 fclose(asm_out);
1972                         }
1973                 } else if (filetype == FILETYPE_IR) {
1974                         fclose(in);
1975                         int res = ir_import(filename);
1976                         if (res != 0) {
1977                                 fprintf(stderr, "Firm-Program import failed\n");
1978                                 return EXIT_FAILURE;
1979                         }
1980                         goto graph_built;
1981                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1982                         copy_file(asm_out, in);
1983                         if (in == preprocessed_in) {
1984                                 int pp_result = pclose(preprocessed_in);
1985                                 if (pp_result != EXIT_SUCCESS) {
1986                                         /* remove output in error case */
1987                                         if (out != stdout)
1988                                                 unlink(outname);
1989                                         return pp_result;
1990                                 }
1991                         }
1992                         if (asm_out != out) {
1993                                 fclose(asm_out);
1994                         }
1995                 }
1996
1997                 if (mode == Compile)
1998                         continue;
1999
2000                 /* if we're here then we have preprocessed assembly */
2001                 filename = asm_tempfile;
2002                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
2003
2004                 /* assemble */
2005                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
2006                         char        temp[1024];
2007                         const char *filename_o;
2008                         if (mode == CompileAssemble) {
2009                                 fclose(out);
2010                                 filename_o = outname;
2011                         } else {
2012                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
2013                                 fclose(tempf);
2014                                 filename_o = temp;
2015                         }
2016
2017                         assemble(filename_o, filename);
2018
2019                         size_t len = strlen(filename_o) + 1;
2020                         filename = obstack_copy(&file_obst, filename_o, len);
2021                         filetype = FILETYPE_OBJECT;
2022                 }
2023
2024                 /* ok we're done here, process next file */
2025                 file->name = filename;
2026                 file->type = filetype;
2027         }
2028
2029         if (result != EXIT_SUCCESS) {
2030                 if (out != stdout)
2031                         unlink(outname);
2032                 return result;
2033         }
2034
2035         /* link program file */
2036         if (mode == CompileAssembleLink) {
2037                 obstack_1grow(&ldflags_obst, '\0');
2038                 const char *flags = obstack_finish(&ldflags_obst);
2039
2040                 /* construct commandline */
2041                 const char *linker = getenv("CPARSER_LINK");
2042                 if (linker != NULL) {
2043                         obstack_printf(&file_obst, "%s ", linker);
2044                 } else {
2045                         if (target_triple != NULL)
2046                                 obstack_printf(&file_obst, "%s-", target_triple);
2047                         obstack_printf(&file_obst, "%s ", LINKER);
2048                 }
2049
2050                 for (file_list_entry_t *entry = files; entry != NULL;
2051                                 entry = entry->next) {
2052                         if (entry->type != FILETYPE_OBJECT)
2053                                 continue;
2054
2055                         add_flag(&file_obst, "%s", entry->name);
2056                 }
2057
2058                 add_flag(&file_obst, "-o");
2059                 add_flag(&file_obst, outname);
2060                 obstack_printf(&file_obst, "%s", flags);
2061                 obstack_1grow(&file_obst, '\0');
2062
2063                 char *commandline = obstack_finish(&file_obst);
2064
2065                 if (verbose) {
2066                         puts(commandline);
2067                 }
2068                 int err = system(commandline);
2069                 if (err != EXIT_SUCCESS) {
2070                         fprintf(stderr, "linker reported an error\n");
2071                         return EXIT_FAILURE;
2072                 }
2073         }
2074
2075         if (do_timing)
2076                 timer_term(stderr);
2077
2078         obstack_free(&cppflags_obst, NULL);
2079         obstack_free(&ldflags_obst, NULL);
2080         obstack_free(&asflags_obst, NULL);
2081         obstack_free(&file_obst, NULL);
2082
2083         gen_firm_finish();
2084         exit_mangle();
2085         exit_ast2firm();
2086         exit_parser();
2087         exit_ast();
2088         exit_preprocessor();
2089         exit_typehash();
2090         exit_types();
2091         exit_tokens();
2092         exit_symbol_table();
2093         return EXIT_SUCCESS;
2094 }