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