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