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