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