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