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