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