Make the input encoding selectable via −finput‐charset=. Currently suported are...
[cparser] / main.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 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_cmdline.h"
74 #include "adt/error.h"
75 #include "wrappergen/write_fluffy.h"
76 #include "wrappergen/write_caml.h"
77 #include "wrappergen/write_jna.h"
78 #include "revision.h"
79 #include "warning.h"
80 #include "mangle.h"
81
82 #ifndef PREPROCESSOR
83 #ifndef __WIN32__
84 #define PREPROCESSOR "gcc -E -std=c99 -m32 -U__STRICT_ANSI__"
85 #else
86 #define PREPROCESSOR "cpp -std=c99 -m32 -U__STRICT_ANSI__"
87 #endif
88 #endif
89
90 #ifndef LINKER
91 #define LINKER    "gcc -m32"
92 #endif
93
94 #ifndef ASSEMBLER
95 #ifdef __APPLE__
96 #define ASSEMBLER "gcc -c -xassembler"
97 #else
98 #define ASSEMBLER "as --32"
99 #endif
100 #endif
101
102 /** The current c mode/dialect. */
103 unsigned int c_mode = _C89 | _ANSI | _C99 | _GNUC;
104
105 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
106 unsigned int machine_size = 32;
107
108 /** true if the char type is signed. */
109 bool char_is_signed = true;
110
111 /** true for strict language checking. */
112 bool strict_mode = false;
113
114 /** use builtins for some libc functions */
115 bool use_builtins = false;
116
117 /** we have extern function with const attribute. */
118 bool have_const_functions = false;
119
120 atomic_type_kind_t wchar_atomic_kind = ATOMIC_TYPE_INT;
121
122 /* to switch on printing of implicit casts */
123 extern bool print_implicit_casts;
124
125 /* to switch on printing of parenthesis to indicate operator precedence */
126 extern bool print_parenthesis;
127
128 static int             verbose;
129 static struct obstack  cppflags_obst, ldflags_obst;
130 static char            dep_target[1024];
131 static const char     *outname;
132
133 typedef struct file_list_entry_t file_list_entry_t;
134
135 typedef enum filetype_t {
136         FILETYPE_AUTODETECT,
137         FILETYPE_C,
138         FILETYPE_PREPROCESSED_C,
139         FILETYPE_CXX,
140         FILETYPE_PREPROCESSED_CXX,
141         FILETYPE_ASSEMBLER,
142         FILETYPE_PREPROCESSED_ASSEMBLER,
143         FILETYPE_OBJECT,
144         FILETYPE_UNKNOWN
145 } filetype_t;
146
147 struct file_list_entry_t {
148         const char  *name; /**< filename or NULL for stdin */
149         filetype_t   type;
150         file_list_entry_t *next;
151 };
152
153 static file_list_entry_t *temp_files;
154
155 #if defined(_DEBUG) || defined(FIRM_DEBUG)
156 /**
157  * Debug printf implementation.
158  *
159  * @param fmt  printf style format parameter
160  */
161 void dbg_printf(const char *fmt, ...)
162 {
163         va_list list;
164
165         if (firm_dump.debug_print) {
166                 va_start(list, fmt);
167                 vprintf(fmt, list);
168                 va_end(list);
169         }  /* if */
170 }
171 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
172
173 static void initialize_firm(void)
174 {
175         firm_early_init();
176
177         dump_consts_local(1);
178         dump_keepalive_edges(1);
179 }
180
181 static void get_output_name(char *buf, size_t buflen, const char *inputname,
182                             const char *newext)
183 {
184         size_t last_dot = 0xffffffff;
185         size_t i = 0;
186
187         if (inputname == NULL) {
188                 snprintf(buf, buflen, "a%s", newext);
189                 return;
190         }
191
192         for (const char *c = inputname; *c != 0; ++c) {
193                 if (*c == '.')
194                         last_dot = i;
195                 ++i;
196         }
197         if (last_dot == 0xffffffff)
198                 last_dot = i;
199
200         if (last_dot >= buflen)
201                 panic("filename too long");
202         memcpy(buf, inputname, last_dot);
203
204         size_t extlen = strlen(newext) + 1;
205         if (extlen + last_dot >= buflen)
206                 panic("filename too long");
207         memcpy(buf+last_dot, newext, extlen);
208 }
209
210 #include "builtins.h"
211
212 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
213 {
214         start_parsing();
215
216         if (use_builtins) {
217                 lexer_open_buffer(builtins, sizeof(builtins)-1, "<builtin>");
218                 parse();
219         }
220
221         lexer_open_stream(in, input_name);
222         parse();
223
224         translation_unit_t *unit = finish_parsing();
225         return unit;
226 }
227
228 static void lextest(FILE *in, const char *fname)
229 {
230         lexer_open_stream(in, fname);
231
232         do {
233                 lexer_next_preprocessing_token();
234                 print_token(stdout, &lexer_token);
235                 putchar('\n');
236         } while (lexer_token.type != T_EOF);
237 }
238
239 static void add_flag(struct obstack *obst, const char *format, ...)
240 {
241         char buf[4096];
242         va_list ap;
243
244         va_start(ap, format);
245 #ifdef _WIN32
246         int len =
247 #endif
248                 vsnprintf(buf, sizeof(buf), format, ap);
249         va_end(ap);
250
251         obstack_1grow(obst, ' ');
252 #ifdef _WIN32
253         obstack_1grow(obst, '"');
254         obstack_grow(obst, buf, len);
255         obstack_1grow(obst, '"');
256 #else
257         /* escape stuff... */
258         for (char *c = buf; *c != '\0'; ++c) {
259                 switch(*c) {
260                 case ' ':
261                 case '"':
262                 case '$':
263                 case '&':
264                 case '(':
265                 case ')':
266                 case ';':
267                 case '<':
268                 case '>':
269                 case '\'':
270                 case '\\':
271                 case '\n':
272                 case '\r':
273                 case '\t':
274                 case '`':
275                 case '|':
276                         obstack_1grow(obst, '\\');
277                         /* FALLTHROUGH */
278                 default:
279                         obstack_1grow(obst, *c);
280                         break;
281                 }
282         }
283 #endif
284 }
285
286 static const char *type_to_string(type_t *type)
287 {
288         assert(type->kind == TYPE_ATOMIC);
289         return get_atomic_kind_name(type->atomic.akind);
290 }
291
292 static FILE *preprocess(const char *fname)
293 {
294         obstack_1grow(&cppflags_obst, '\0');
295         const char *flags = obstack_finish(&cppflags_obst);
296
297         obstack_printf(&cppflags_obst, "%s", PREPROCESSOR);
298
299         /* setup default defines */
300         add_flag(&cppflags_obst, "-U__WCHAR_TYPE__");
301         add_flag(&cppflags_obst, "-D__WCHAR_TYPE__=%s", type_to_string(type_wchar_t));
302         add_flag(&cppflags_obst, "-U__SIZE_TYPE__");
303         add_flag(&cppflags_obst, "-D__SIZE_TYPE__=%s", type_to_string(type_size_t));
304
305         /* TODO hack... */
306         add_flag(&cppflags_obst, "-D__builtin_abort=abort");
307         add_flag(&cppflags_obst, "-D__builtin_abs=abs");
308         add_flag(&cppflags_obst, "-D__builtin_exit=exit");
309         add_flag(&cppflags_obst, "-D__builtin_malloc=malloc");
310         add_flag(&cppflags_obst, "-D__builtin_memcmp=memcmp");
311         add_flag(&cppflags_obst, "-D__builtin_memcpy=memcpy");
312         add_flag(&cppflags_obst, "-D__builtin_memset=memset");
313         add_flag(&cppflags_obst, "-D__builtin_strlen=strlen");
314         add_flag(&cppflags_obst, "-D__builtin_strcmp=strcmp");
315         add_flag(&cppflags_obst, "-D__builtin_strcpy=strcpy");
316
317         /* handle dependency generation */
318         if (dep_target[0] != '\0') {
319                 add_flag(&cppflags_obst, "-MF");
320                 add_flag(&cppflags_obst, dep_target);
321                 if (outname != NULL) {
322                                 add_flag(&cppflags_obst, "-MQ");
323                                 add_flag(&cppflags_obst, outname);
324                 }
325         }
326         if (flags[0] != '\0') {
327                 obstack_printf(&cppflags_obst, " %s", flags);
328         }
329         add_flag(&cppflags_obst, fname);
330
331         obstack_1grow(&cppflags_obst, '\0');
332         const char *buf = obstack_finish(&cppflags_obst);
333         if (verbose) {
334                 puts(buf);
335         }
336
337         FILE *f = popen(buf, "r");
338         if (f == NULL) {
339                 fprintf(stderr, "invoking preprocessor failed\n");
340                 exit(1);
341         }
342
343         return f;
344 }
345
346 static void assemble(const char *out, const char *in)
347 {
348         char buf[4096];
349
350         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
351         if (verbose) {
352                 puts(buf);
353         }
354
355         int err = system(buf);
356         if (err != 0) {
357                 fprintf(stderr, "assembler reported an error\n");
358                 exit(1);
359         }
360 }
361
362 static void print_file_name(const char *file)
363 {
364         add_flag(&ldflags_obst, "-print-file-name=%s", file);
365
366         obstack_1grow(&ldflags_obst, '\0');
367         const char *flags = obstack_finish(&ldflags_obst);
368
369         /* construct commandline */
370         obstack_printf(&ldflags_obst, "%s ", LINKER);
371         obstack_printf(&ldflags_obst, "%s", flags);
372         obstack_1grow(&ldflags_obst, '\0');
373
374         char *commandline = obstack_finish(&ldflags_obst);
375
376         if (verbose) {
377                 puts(commandline);
378         }
379         int err = system(commandline);
380         if (err != EXIT_SUCCESS) {
381                 fprintf(stderr, "linker reported an error\n");
382                 exit(1);
383         }
384 }
385
386 static const char *try_dir(const char *dir)
387 {
388         if (dir == NULL)
389                 return dir;
390         if (access(dir, R_OK | W_OK | X_OK) == 0)
391                 return dir;
392         return NULL;
393 }
394
395 static const char *get_tempdir(void)
396 {
397         static const char *tmpdir = NULL;
398
399         if (tmpdir != NULL)
400                 return tmpdir;
401
402         if (tmpdir == NULL)
403                 tmpdir = try_dir(getenv("TMPDIR"));
404         if (tmpdir == NULL)
405                 tmpdir = try_dir(getenv("TMP"));
406         if (tmpdir == NULL)
407                 tmpdir = try_dir(getenv("TEMP"));
408
409 #ifdef P_tmpdir
410         if (tmpdir == NULL)
411                 tmpdir = try_dir(P_tmpdir);
412 #endif
413
414         if (tmpdir == NULL)
415                 tmpdir = try_dir("/var/tmp");
416         if (tmpdir == NULL)
417                 tmpdir = try_dir("/usr/tmp");
418         if (tmpdir == NULL)
419                 tmpdir = try_dir("/tmp");
420
421         if (tmpdir == NULL)
422                 tmpdir = ".";
423
424         return tmpdir;
425 }
426
427 #ifndef HAVE_MKSTEMP
428 /* cheap and nasty mkstemp replacement */
429 static int mkstemp(char *templ)
430 {
431         mktemp(templ);
432         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
433 }
434 #endif
435
436 /**
437  * an own version of tmpnam, which: writes in a buffer, emits no warnings
438  * during linking (like glibc/gnu ld do for tmpnam)...
439  */
440 static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix)
441 {
442         const char *tempdir = get_tempdir();
443
444         snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix);
445
446         int fd = mkstemp(buffer);
447         if (fd == -1) {
448                 fprintf(stderr, "couldn't create temporary file: %s\n",
449                         strerror(errno));
450                 exit(1);
451         }
452         FILE *out = fdopen(fd, "w");
453         if (out == NULL) {
454                 fprintf(stderr, "couldn't create temporary file FILE*\n");
455                 exit(1);
456         }
457
458         file_list_entry_t *entry = xmalloc(sizeof(*entry));
459         memset(entry, 0, sizeof(*entry));
460
461         size_t  name_len = strlen(buffer) + 1;
462         char   *name     = malloc(name_len);
463         memcpy(name, buffer, name_len);
464         entry->name      = name;
465
466         entry->next = temp_files;
467         temp_files  = entry;
468
469         return out;
470 }
471
472 static void free_temp_files(void)
473 {
474         file_list_entry_t *entry = temp_files;
475         file_list_entry_t *next;
476         for ( ; entry != NULL; entry = next) {
477                 next = entry->next;
478
479                 unlink(entry->name);
480                 free((char*) entry->name);
481                 free(entry);
482         }
483         temp_files = NULL;
484 }
485
486 /**
487  * Do the necessary lowering for compound parameters.
488  */
489 void lower_compound_params(void)
490 {
491         lower_params_t params;
492
493         params.def_ptr_alignment    = 4;
494         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
495         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
496         params.find_pointer_type    = NULL;
497         params.ret_compound_in_regs = NULL;
498         lower_calls_with_compounds(&params);
499 }
500
501 typedef enum compile_mode_t {
502         BenchmarkParser,
503         PreprocessOnly,
504         ParseOnly,
505         Compile,
506         CompileDump,
507         CompileAssemble,
508         CompileAssembleLink,
509         LexTest,
510         PrintAst,
511         PrintFluffy,
512         PrintCaml,
513         PrintJna
514 } compile_mode_t;
515
516 static void usage(const char *argv0)
517 {
518         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
519 }
520
521 static void print_cparser_version(void) {
522         printf("cparser (%s) using libFirm (%u.%u",
523                cparser_REVISION, ir_get_version_major(),
524                ir_get_version_minor());
525
526         const char *revision = ir_get_version_revision();
527         if (revision[0] != 0) {
528                 putchar(' ');
529                 fputs(revision, stdout);
530         }
531
532         const char *build = ir_get_version_build();
533         if (build[0] != 0) {
534                 putchar(' ');
535                 fputs(build, stdout);
536         }
537         puts(")\n");
538 }
539
540 static void set_be_option(const char *arg)
541 {
542         int res = firm_be_option(arg);
543         (void) res;
544         assert(res);
545 }
546
547 static void set_option(const char *arg)
548 {
549         int res = firm_option(arg);
550         (void) res;
551         assert(res);
552 }
553
554 static void copy_file(FILE *dest, FILE *input)
555 {
556         char buf[16384];
557
558         while (!feof(input) && !ferror(dest)) {
559                 size_t read = fread(buf, 1, sizeof(buf), input);
560                 if (fwrite(buf, 1, read, dest) != read) {
561                         perror("couldn't write output");
562                 }
563         }
564 }
565
566 static inline bool streq(char const* a, char const* b)
567 {
568         return strcmp(a, b) == 0;
569 }
570
571 static inline bool strstart(char const* str, char const* start)
572 {
573         do {
574                 if (*start == '\0')
575                         return true;
576         } while (*str++ == *start++);
577         return false;
578 }
579
580 static FILE *open_file(const char *filename)
581 {
582         if (streq(filename, "-")) {
583                 return stdin;
584         }
585
586         FILE *in = fopen(filename, "r");
587         if (in == NULL) {
588                 fprintf(stderr, "Couldn't open '%s': %s\n", filename,
589                                 strerror(errno));
590                 exit(1);
591         }
592
593         return in;
594 }
595
596 static filetype_t get_filetype_from_string(const char *string)
597 {
598         if (streq(string, "c") || streq(string, "c-header"))
599                 return FILETYPE_C;
600         if (streq(string, "c++") || streq(string, "c++-header"))
601                 return FILETYPE_CXX;
602         if (streq(string, "assembler"))
603                 return FILETYPE_PREPROCESSED_ASSEMBLER;
604         if (streq(string, "assembler-with-cpp"))
605                 return FILETYPE_ASSEMBLER;
606         if (streq(string, "none"))
607                 return FILETYPE_AUTODETECT;
608
609         return FILETYPE_UNKNOWN;
610 }
611
612 static void init_os_support(void)
613 {
614         /* OS option must be set to the backend */
615         switch (firm_opt.os_support) {
616         case OS_SUPPORT_MINGW:
617                 set_be_option("ia32-gasmode=mingw");
618                 wchar_atomic_kind = ATOMIC_TYPE_USHORT;
619                 break;
620         case OS_SUPPORT_LINUX:
621                 set_be_option("ia32-gasmode=elf");
622                 break;
623         case OS_SUPPORT_MACHO:
624                 set_be_option("ia32-gasmode=macho");
625                 set_be_option("ia32-stackalign=4");
626                 set_be_option("pic");
627                 break;
628         }
629 }
630
631 typedef enum lang_standard_t {
632         STANDARD_DEFAULT, /* gnu99 (for C, GCC does gnu89) or gnu++98 (for C++) */
633         STANDARD_ANSI,    /* c89 (for C) or c++98 (for C++) */
634         STANDARD_C89,     /* ISO C90 (sic) */
635         STANDARD_C90,     /* ISO C90 as modified in amendment 1 */
636         STANDARD_C99,     /* ISO C99 */
637         STANDARD_GNU89,   /* ISO C90 plus GNU extensions (including some C99) */
638         STANDARD_GNU99,   /* ISO C99 plus GNU extensions */
639         STANDARD_CXX98,   /* ISO C++ 1998 plus amendments */
640         STANDARD_GNUXX98  /* ISO C++ 1998 plus amendments and GNU extensions */
641 } lang_standard_t;
642
643 int main(int argc, char **argv)
644 {
645         initialize_firm();
646
647         const char        *dumpfunction         = NULL;
648         const char        *print_file_name_file = NULL;
649         compile_mode_t     mode                 = CompileAssembleLink;
650         int                opt_level            = 1;
651         int                result               = EXIT_SUCCESS;
652         char               cpu_arch[16]         = "ia32";
653         file_list_entry_t *files                = NULL;
654         file_list_entry_t *last_file            = NULL;
655         bool               construct_dep_target = false;
656         struct obstack     file_obst;
657
658         atexit(free_temp_files);
659
660         /* hack for now... */
661         if (strstr(argv[0], "pptest") != NULL) {
662                 extern int pptest_main(int argc, char **argv);
663                 return pptest_main(argc, argv);
664         }
665
666         obstack_init(&cppflags_obst);
667         obstack_init(&ldflags_obst);
668         obstack_init(&file_obst);
669
670 #define GET_ARG_AFTER(def, args)                                             \
671         def = &arg[sizeof(args)-1];                                              \
672         if (def[0] == '\0') {                                                     \
673                 ++i;                                                                 \
674                 if (i >= argc) {                                                      \
675                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
676                         argument_errors = true;                                          \
677                         break;                                                           \
678                 }                                                                    \
679                 def = argv[i];                                                       \
680                 if (def[0] == '-' && def[1] != '\0') {                                \
681                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
682                         argument_errors = true;                                          \
683                         continue;                                                        \
684                 }                                                                    \
685         }
686
687 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
688
689         /* early options parsing (find out optimisation level and OS) */
690         for (int i = 1; i < argc; ++i) {
691                 const char *arg = argv[i];
692                 if (arg[0] != '-')
693                         continue;
694
695                 const char *option = &arg[1];
696                 if (option[0] == 'O') {
697                         sscanf(&option[1], "%d", &opt_level);
698                 }
699                 if (strcmp(arg, "-fwin32") == 0) {
700                         firm_opt.os_support = OS_SUPPORT_MINGW;
701                 } else if (strcmp(arg, "-fmac") == 0) {
702                         firm_opt.os_support = OS_SUPPORT_MACHO;
703                 } else if (strcmp(arg, "-flinux") == 0) {
704                         firm_opt.os_support = OS_SUPPORT_LINUX;
705                 }
706         }
707
708         /* set target/os specific stuff */
709         init_os_support();
710
711         /* apply optimisation level */
712         switch(opt_level) {
713         case 0:
714                 set_option("no-opt");
715                 break;
716         case 1:
717                 set_option("no-inline");
718                 break;
719         default:
720         case 4:
721                 set_option("strict-aliasing");
722                 /* use_builtins = true; */
723                 /* fallthrough */
724         case 3:
725                 set_option("cond-eval");
726                 set_option("if-conv");
727                 /* fallthrough */
728         case 2:
729                 set_option("inline");
730                 set_option("deconv");
731                 set_be_option("omitfp");
732                 break;
733         }
734
735         /* parse rest of options */
736         lang_standard_t standard        = STANDARD_DEFAULT;
737         unsigned        features_on     = 0;
738         unsigned        features_off    = 0;
739         filetype_t      forced_filetype = FILETYPE_AUTODETECT;
740         bool            help_displayed  = false;
741         bool            argument_errors = false;
742         for (int i = 1; i < argc; ++i) {
743                 const char *arg = argv[i];
744                 if (arg[0] == '-' && arg[1] != '\0') {
745                         /* an option */
746                         const char *option = &arg[1];
747                         if (option[0] == 'o') {
748                                 GET_ARG_AFTER(outname, "-o");
749                         } else if (option[0] == 'g') {
750                                 set_be_option("debuginfo=stabs");
751                                 set_be_option("omitfp=no");
752                                 set_be_option("ia32-nooptcc=yes");
753                         } else if (SINGLE_OPTION('c')) {
754                                 mode = CompileAssemble;
755                         } else if (SINGLE_OPTION('E')) {
756                                 mode = PreprocessOnly;
757                         } else if (SINGLE_OPTION('S')) {
758                                 mode = Compile;
759                         } else if (option[0] == 'O') {
760                                 continue;
761                         } else if (option[0] == 'I') {
762                                 const char *opt;
763                                 GET_ARG_AFTER(opt, "-I");
764                                 add_flag(&cppflags_obst, "-I%s", opt);
765                         } else if (option[0] == 'D') {
766                                 const char *opt;
767                                 GET_ARG_AFTER(opt, "-D");
768                                 add_flag(&cppflags_obst, "-D%s", opt);
769                         } else if (option[0] == 'U') {
770                                 const char *opt;
771                                 GET_ARG_AFTER(opt, "-U");
772                                 add_flag(&cppflags_obst, "-U%s", opt);
773                         } else if (option[0] == 'l') {
774                                 const char *opt;
775                                 GET_ARG_AFTER(opt, "-l");
776                                 add_flag(&ldflags_obst, "-l%s", opt);
777                         } else if (option[0] == 'L') {
778                                 const char *opt;
779                                 GET_ARG_AFTER(opt, "-L");
780                                 add_flag(&ldflags_obst, "-L%s", opt);
781                         } else if (SINGLE_OPTION('v')) {
782                                 verbose = 1;
783                         } else if (SINGLE_OPTION('w')) {
784                                 memset(&warning, 0, sizeof(warning));
785                         } else if (option[0] == 'x') {
786                                 const char *opt;
787                                 GET_ARG_AFTER(opt, "-x");
788                                 forced_filetype = get_filetype_from_string(opt);
789                                 if (forced_filetype == FILETYPE_UNKNOWN) {
790                                         fprintf(stderr, "Unknown language '%s'\n", opt);
791                                         argument_errors = true;
792                                 }
793                         } else if (streq(option, "M")) {
794                                 mode = PreprocessOnly;
795                                 add_flag(&cppflags_obst, "-M");
796                         } else if (streq(option, "MMD") ||
797                                    streq(option, "MD")) {
798                             construct_dep_target = true;
799                                 add_flag(&cppflags_obst, "-%s", option);
800                         } else if (streq(option, "MM")  ||
801                                    streq(option, "MP")) {
802                                 add_flag(&cppflags_obst, "-%s", option);
803                         } else if (streq(option, "MT") ||
804                                    streq(option, "MQ") ||
805                                    streq(option, "MF")) {
806                                 const char *opt;
807                                 GET_ARG_AFTER(opt, "-MT");
808                                 add_flag(&cppflags_obst, "-%s", option);
809                                 add_flag(&cppflags_obst, "%s", opt);
810                         } else if (streq(option, "include")) {
811                                 const char *opt;
812                                 GET_ARG_AFTER(opt, "-include");
813                                 add_flag(&cppflags_obst, "-include");
814                                 add_flag(&cppflags_obst, "%s", opt);
815                         } else if (streq(option, "isystem")) {
816                                 const char *opt;
817                                 GET_ARG_AFTER(opt, "-isystem");
818                                 add_flag(&cppflags_obst, "-isystem");
819                                 add_flag(&cppflags_obst, "%s", opt);
820                         } else if (streq(option, "nostdinc")
821                                         || streq(option, "trigraphs")) {
822                                 /* pass these through to the preprocessor */
823                                 add_flag(&cppflags_obst, "%s", arg);
824                         } else if (streq(option, "pipe")) {
825                                 /* here for gcc compatibility */
826                         } else if (option[0] == 'f') {
827                                 char const *orig_opt;
828                                 GET_ARG_AFTER(orig_opt, "-f");
829
830                                 if (strstart(orig_opt, "align-loops=") ||
831                                     strstart(orig_opt, "align-jumps=") ||
832                                     strstart(orig_opt, "align-functions=")) {
833                                         fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
834                                 } else if (strstart(orig_opt, "input-charset=")) {
835                                         char const* const encoding = strchr(orig_opt, '=') + 1;
836                                         select_input_encoding(encoding);
837                                 } else if (streq(orig_opt, "verbose-asm")) {
838                                         /* ignore: we always print verbose assembler */
839                                 } else {
840                                         char const *opt         = orig_opt;
841                                         bool        truth_value = true;
842                                         if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
843                                                 truth_value = false;
844                                                 opt += 3;
845                                         }
846
847                                         if (streq(opt, "dollars-in-identifiers")) {
848                                                 allow_dollar_in_symbol = truth_value;
849                                         } if (streq(opt, "builtins")) {
850                                                 use_builtins = truth_value;
851                                         } else if (streq(opt, "short-wchar")) {
852                                                 wchar_atomic_kind = truth_value ? ATOMIC_TYPE_USHORT
853                                                         : ATOMIC_TYPE_INT;
854                                         } else if (streq(opt, "syntax-only")) {
855                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
856                                         } else if (streq(opt, "omit-frame-pointer")) {
857                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
858                                         } else if (streq(opt, "strength-reduce")) {
859                                                 firm_option(truth_value ? "strength-red" : "no-strength-red");
860                                         } else if (streq(opt, "fast-math")               ||
861                                                    streq(opt, "jump-tables")             ||
862                                                    streq(opt, "unroll-loops")            ||
863                                                    streq(opt, "expensive-optimizations") ||
864                                                    streq(opt, "common")                  ||
865                                                    streq(opt, "PIC")                     ||
866                                                    streq(opt, "align-loops")             ||
867                                                    streq(opt, "align-jumps")             ||
868                                                    streq(opt, "align-functions")) {
869                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
870                                         } else {
871                                                 int res = firm_option(orig_opt);
872                                                 if (res == 0) {
873                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
874                                                                 orig_opt);
875                                                         argument_errors = true;
876                                                         continue;
877                                                 } else if (res == -1) {
878                                                         help_displayed = true;
879                                                 }
880                                         }
881                                 }
882                         } else if (option[0] == 'b') {
883                                 const char *opt;
884                                 GET_ARG_AFTER(opt, "-b");
885                                 int res = firm_be_option(opt);
886                                 if (res == 0) {
887                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
888                                                 opt);
889                                         argument_errors = true;
890                                 } else if (res == -1) {
891                                         help_displayed = true;
892                                 } else if (strstart(opt, "isa=")) {
893                                         strncpy(cpu_arch, opt, sizeof(cpu_arch));
894                                 }
895                         } else if (option[0] == 'W') {
896                                 if (strstart(option + 1, "p,")) {
897                                         // pass options directly to the preprocessor
898                                         const char *opt;
899                                         GET_ARG_AFTER(opt, "-Wp,");
900                                         add_flag(&cppflags_obst, "-Wp,%s", opt);
901                                 } else if (strstart(option + 1, "l,")) {
902                                         // pass options directly to the linker
903                                         const char *opt;
904                                         GET_ARG_AFTER(opt, "-Wl,");
905                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
906                                 } else if (streq(option + 1, "no-trigraphs")
907                                                         || streq(option + 1, "undef")) {
908                                         add_flag(&cppflags_obst, "%s", arg);
909                                 } else {
910                                         set_warning_opt(&option[1]);
911                                 }
912                         } else if (option[0] == 'm') {
913                                 /* -m options */
914                                 const char *opt;
915                                 char arch_opt[64];
916
917                                 GET_ARG_AFTER(opt, "-m");
918                                 if (strstart(opt, "arch=")) {
919                                         GET_ARG_AFTER(opt, "-march=");
920                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
921                                         int res = firm_be_option(arch_opt);
922                                         if (res == 0)
923                                                 argument_errors = true;
924                                         else {
925                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
926                                                 int res = firm_be_option(arch_opt);
927                                                 if (res == 0)
928                                                         argument_errors = true;
929                                         }
930                                 } else if (strstart(opt, "tune=")) {
931                                         GET_ARG_AFTER(opt, "-mtune=");
932                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
933                                         int res = firm_be_option(arch_opt);
934                                         if (res == 0)
935                                                 argument_errors = true;
936                                 } else if (strstart(opt, "cpu=")) {
937                                         GET_ARG_AFTER(opt, "-mcpu=");
938                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
939                                         int res = firm_be_option(arch_opt);
940                                         if (res == 0)
941                                                 argument_errors = true;
942                                 } else if (strstart(opt, "fpmath=")) {
943                                         GET_ARG_AFTER(opt, "-mfpmath=");
944                                         if (streq(opt, "387"))
945                                                 opt = "x87";
946                                         else if (streq(opt, "sse"))
947                                                 opt = "sse2";
948                                         else {
949                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
950                                                 argument_errors = true;
951                                         }
952                                         if (!argument_errors) {
953                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
954                                                 int res = firm_be_option(arch_opt);
955                                                 if (res == 0)
956                                                         argument_errors = true;
957                                         }
958                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
959                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
960                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
961                                         int res = firm_be_option(arch_opt);
962                                         if (res == 0)
963                                                 argument_errors = true;
964                                 } else if (streq(opt, "omit-leaf-frame-pointer")) {
965                                         set_be_option("omitleaffp=1");
966                                 } else if (streq(opt, "no-omit-leaf-frame-pointer")) {
967                                         set_be_option("omitleaffp=0");
968                                 } else {
969                                         char *endptr;
970                                         long int value = strtol(opt, &endptr, 10);
971                                         if (*endptr != '\0') {
972                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
973                                                 argument_errors = true;
974                                         }
975                                         if (value != 16 && value != 32 && value != 64) {
976                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
977                                                 argument_errors = true;
978                                         } else {
979                                                 machine_size = (unsigned int)value;
980                                         }
981                                 }
982                         } else if (streq(option, "pg")) {
983                                 set_be_option("gprof");
984                                 add_flag(&ldflags_obst, "-pg");
985                         } else if (streq(option, "pedantic") ||
986                                    streq(option, "ansi")) {
987                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
988                         } else if (streq(option, "shared")) {
989                                 add_flag(&ldflags_obst, "-shared");
990                         } else if (strstart(option, "std=")) {
991                                 const char *const o = &option[4];
992                                 standard =
993                                         streq(o, "c++")            ? STANDARD_CXX98   :
994                                         streq(o, "c++98")          ? STANDARD_CXX98   :
995                                         streq(o, "c89")            ? STANDARD_C89     :
996                                         streq(o, "c99")            ? STANDARD_C99     :
997                                         streq(o, "c9x")            ? STANDARD_C99     : // deprecated
998                                         streq(o, "gnu++98")        ? STANDARD_GNUXX98 :
999                                         streq(o, "gnu89")          ? STANDARD_GNU89   :
1000                                         streq(o, "gnu99")          ? STANDARD_GNU99   :
1001                                         streq(o, "gnu9x")          ? STANDARD_GNU99   : // deprecated
1002                                         streq(o, "iso9899:1990")   ? STANDARD_C89     :
1003                                         streq(o, "iso9899:199409") ? STANDARD_C90     :
1004                                         streq(o, "iso9899:1999")   ? STANDARD_C99     :
1005                                         streq(o, "iso9899:199x")   ? STANDARD_C99     : // deprecated
1006                                         (fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg), standard);
1007                         } else if (streq(option, "version")) {
1008                                 print_cparser_version();
1009                         } else if (strstart(option, "print-file-name=")) {
1010                                 GET_ARG_AFTER(print_file_name_file, "-print-file-name=");
1011                         } else if (option[0] == '-') {
1012                                 /* double dash option */
1013                                 ++option;
1014                                 if (streq(option, "gcc")) {
1015                                         features_on  |=  _GNUC;
1016                                         features_off &= ~_GNUC;
1017                                 } else if (streq(option, "no-gcc")) {
1018                                         features_on  &= ~_GNUC;
1019                                         features_off |=  _GNUC;
1020                                 } else if (streq(option, "ms")) {
1021                                         features_on  |=  _MS;
1022                                         features_off &= ~_MS;
1023                                 } else if (streq(option, "no-ms")) {
1024                                         features_on  &= ~_MS;
1025                                         features_off |=  _MS;
1026                                 } else if (streq(option, "signed-chars")) {
1027                                         char_is_signed = true;
1028                                 } else if (streq(option, "unsigned-chars")) {
1029                                         char_is_signed = false;
1030                                 } else if (streq(option, "strict")) {
1031                                         strict_mode = true;
1032                                 } else if (streq(option, "lextest")) {
1033                                         mode = LexTest;
1034                                 } else if (streq(option, "benchmark")) {
1035                                         mode = BenchmarkParser;
1036                                 } else if (streq(option, "print-ast")) {
1037                                         mode = PrintAst;
1038                                 } else if (streq(option, "print-implicit-cast")) {
1039                                         print_implicit_casts = true;
1040                                 } else if (streq(option, "print-parenthesis")) {
1041                                         print_parenthesis = true;
1042                                 } else if (streq(option, "print-fluffy")) {
1043                                         mode = PrintFluffy;
1044                                 } else if (streq(option, "print-caml")) {
1045                                         mode = PrintCaml;
1046                                 } else if (streq(option, "print-jna")) {
1047                                         mode = PrintJna;
1048                                 } else if (streq(option, "version")) {
1049                                         print_cparser_version();
1050                                         exit(EXIT_SUCCESS);
1051                                 } else if (streq(option, "dump-function")) {
1052                                         ++i;
1053                                         if (i >= argc) {
1054                                                 fprintf(stderr, "error: "
1055                                                         "expected argument after '--dump-function'\n");
1056                                                 argument_errors = true;
1057                                                 break;
1058                                         }
1059                                         dumpfunction = argv[i];
1060                                         mode         = CompileDump;
1061                                 } else {
1062                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
1063                                         argument_errors = true;
1064                                 }
1065                         } else {
1066                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
1067                                 argument_errors = true;
1068                         }
1069                 } else {
1070                         filetype_t type = forced_filetype;
1071                         if (type == FILETYPE_AUTODETECT) {
1072                                 if (streq(arg, "-")) {
1073                                         /* - implicitly means C source file */
1074                                         type = FILETYPE_C;
1075                                 } else {
1076                                         const char *suffix = strrchr(arg, '.');
1077                                         /* Ensure there is at least one char before the suffix */
1078                                         if (suffix != NULL && suffix != arg) {
1079                                                 ++suffix;
1080                                                 type =
1081                                                         streq(suffix, "S")   ? FILETYPE_ASSEMBLER              :
1082                                                         streq(suffix, "a")   ? FILETYPE_OBJECT                 :
1083                                                         streq(suffix, "c")   ? FILETYPE_C                      :
1084                                                         streq(suffix, "cc")  ? FILETYPE_CXX                    :
1085                                                         streq(suffix, "cpp") ? FILETYPE_CXX                    :
1086                                                         streq(suffix, "cxx") ? FILETYPE_CXX                    :
1087                                                         streq(suffix, "h")   ? FILETYPE_C                      :
1088                                                         streq(suffix, "o")   ? FILETYPE_OBJECT                 :
1089                                                         streq(suffix, "s")   ? FILETYPE_PREPROCESSED_ASSEMBLER :
1090                                                         streq(suffix, "so")  ? FILETYPE_OBJECT                 :
1091                                                         FILETYPE_AUTODETECT;
1092                                         }
1093                                 }
1094
1095                                 if (type == FILETYPE_AUTODETECT) {
1096                                         fprintf(stderr, "'%s': file format not recognized\n", arg);
1097                                         continue;
1098                                 }
1099                         }
1100
1101                         file_list_entry_t *entry
1102                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
1103                         memset(entry, 0, sizeof(entry[0]));
1104                         entry->name = arg;
1105                         entry->type = type;
1106
1107                         if (last_file != NULL) {
1108                                 last_file->next = entry;
1109                         } else {
1110                                 files = entry;
1111                         }
1112                         last_file = entry;
1113                 }
1114         }
1115
1116         if (print_file_name_file != NULL) {
1117                 print_file_name(print_file_name_file);
1118                 return 0;
1119         }
1120
1121         if (files == NULL) {
1122                 fprintf(stderr, "error: no input files specified\n");
1123                 argument_errors = true;
1124         }
1125
1126         if (help_displayed) {
1127                 return !argument_errors;
1128         }
1129         if (argument_errors) {
1130                 usage(argv[0]);
1131                 return 1;
1132         }
1133
1134         /* we do the lowering in ast2firm */
1135         firm_opt.lower_bitfields = FALSE;
1136
1137         gen_firm_init();
1138         init_symbol_table();
1139         init_types();
1140         init_typehash();
1141         init_basic_types();
1142         init_lexer();
1143         init_ast();
1144         init_parser();
1145         init_ast2firm();
1146         init_mangle();
1147
1148         if (construct_dep_target) {
1149                 if (outname != 0 && strlen(outname) >= 2) {
1150                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
1151                 } else {
1152                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
1153                 }
1154         } else {
1155                 dep_target[0] = '\0';
1156         }
1157
1158         char outnamebuf[4096];
1159         if (outname == NULL) {
1160                 const char *filename = files->name;
1161
1162                 switch(mode) {
1163                 case BenchmarkParser:
1164                 case PrintAst:
1165                 case PrintFluffy:
1166                 case PrintCaml:
1167                 case PrintJna:
1168                 case LexTest:
1169                 case PreprocessOnly:
1170                 case ParseOnly:
1171                         outname = "-";
1172                         break;
1173                 case Compile:
1174                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
1175                         outname = outnamebuf;
1176                         break;
1177                 case CompileAssemble:
1178                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
1179                         outname = outnamebuf;
1180                         break;
1181                 case CompileDump:
1182                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
1183                                         ".vcg");
1184                         outname = outnamebuf;
1185                         break;
1186                 case CompileAssembleLink:
1187 #ifdef _WIN32
1188                         outname = "a.exe";
1189 #else
1190                         outname = "a.out";
1191 #endif
1192                         break;
1193                 }
1194         }
1195
1196         assert(outname != NULL);
1197
1198         FILE *out;
1199         if (streq(outname, "-")) {
1200                 out = stdout;
1201         } else {
1202                 out = fopen(outname, "w");
1203                 if (out == NULL) {
1204                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
1205                                         strerror(errno));
1206                         return 1;
1207                 }
1208         }
1209
1210         file_list_entry_t *file;
1211         for (file = files; file != NULL; file = file->next) {
1212                 char        asm_tempfile[1024];
1213                 const char *filename = file->name;
1214                 filetype_t  filetype = file->type;
1215
1216                 if (filetype == FILETYPE_OBJECT)
1217                         continue;
1218
1219                 FILE *in = NULL;
1220                 if (mode == LexTest) {
1221                         if (in == NULL)
1222                                 in = open_file(filename);
1223                         lextest(in, filename);
1224                         fclose(in);
1225                         exit(EXIT_SUCCESS);
1226                 }
1227
1228                 FILE *preprocessed_in = NULL;
1229                 switch (filetype) {
1230                         case FILETYPE_C:
1231                                 filetype = FILETYPE_PREPROCESSED_C;
1232                                 goto preprocess;
1233                         case FILETYPE_CXX:
1234                                 filetype = FILETYPE_PREPROCESSED_CXX;
1235                                 goto preprocess;
1236                         case FILETYPE_ASSEMBLER:
1237                                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1238                                 add_flag(&cppflags_obst, "-x");
1239                                 add_flag(&cppflags_obst, "assembler-with-cpp");
1240                                 goto preprocess;
1241 preprocess:
1242                                 /* no support for input on FILE* yet */
1243                                 if (in != NULL)
1244                                         panic("internal compiler error: in for preprocessor != NULL");
1245
1246                                 preprocessed_in = preprocess(filename);
1247                                 if (mode == PreprocessOnly) {
1248                                         copy_file(out, preprocessed_in);
1249                                         int result = pclose(preprocessed_in);
1250                                         fclose(out);
1251                                         /* remove output file in case of error */
1252                                         if (out != stdout && result != EXIT_SUCCESS) {
1253                                                 unlink(outname);
1254                                         }
1255                                         return result;
1256                                 }
1257
1258                                 in = preprocessed_in;
1259                                 break;
1260
1261                         default:
1262                                 break;
1263                 }
1264
1265                 FILE *asm_out;
1266                 if (mode == Compile) {
1267                         asm_out = out;
1268                 } else {
1269                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "ccs");
1270                 }
1271
1272                 if (in == NULL)
1273                         in = open_file(filename);
1274
1275                 /* preprocess and compile */
1276                 if (filetype == FILETYPE_PREPROCESSED_C) {
1277                         char const* invalid_mode;
1278                         switch (standard) {
1279                                 case STANDARD_ANSI:
1280                                 case STANDARD_C89:   c_mode = _C89;                break;
1281                                 /* TODO ^v determine difference between these two */
1282                                 case STANDARD_C90:   c_mode = _C89;                break;
1283                                 case STANDARD_C99:   c_mode = _C89 | _C99;         break;
1284                                 case STANDARD_GNU89: c_mode = _C89 |        _GNUC; break;
1285
1286 default_c_warn:
1287                                         fprintf(stderr,
1288                                                         "warning: command line option \"-std=%s\" is not valid for C\n",
1289                                                         invalid_mode);
1290                                         /* FALLTHROUGH */
1291                                 case STANDARD_DEFAULT:
1292                                 case STANDARD_GNU99:   c_mode = _C89 | _C99 | _GNUC; break;
1293
1294                                 case STANDARD_CXX98:   invalid_mode = "c++98"; goto default_c_warn;
1295                                 case STANDARD_GNUXX98: invalid_mode = "gnu98"; goto default_c_warn;
1296                         }
1297                         goto do_parsing;
1298                 } else if (filetype == FILETYPE_PREPROCESSED_CXX) {
1299                         char const* invalid_mode;
1300                         switch (standard) {
1301                                 case STANDARD_C89:   invalid_mode = "c89";   goto default_cxx_warn;
1302                                 case STANDARD_C90:   invalid_mode = "c90";   goto default_cxx_warn;
1303                                 case STANDARD_C99:   invalid_mode = "c99";   goto default_cxx_warn;
1304                                 case STANDARD_GNU89: invalid_mode = "gnu89"; goto default_cxx_warn;
1305                                 case STANDARD_GNU99: invalid_mode = "gnu99"; goto default_cxx_warn;
1306
1307                                 case STANDARD_ANSI:
1308                                 case STANDARD_CXX98: c_mode = _CXX; break;
1309
1310 default_cxx_warn:
1311                                         fprintf(stderr,
1312                                                         "warning: command line option \"-std=%s\" is not valid for C++\n",
1313                                                         invalid_mode);
1314                                 case STANDARD_DEFAULT:
1315                                 case STANDARD_GNUXX98: c_mode = _CXX | _GNUC; break;
1316                         }
1317
1318 do_parsing:
1319                         c_mode |= features_on;
1320                         c_mode &= ~features_off;
1321                         init_tokens();
1322                         translation_unit_t *const unit = do_parsing(in, filename);
1323
1324                         /* prints the AST even if errors occurred */
1325                         if (mode == PrintAst) {
1326                                 type_set_output(out);
1327                                 ast_set_output(out);
1328                                 print_ast(unit);
1329                         }
1330
1331                         if (error_count > 0) {
1332                                 /* parsing failed because of errors */
1333                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1334                                         warning_count);
1335                                 result = EXIT_FAILURE;
1336                                 continue;
1337                         } else if (warning_count > 0) {
1338                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1339                         }
1340
1341                         if (in == preprocessed_in) {
1342                                 int pp_result = pclose(preprocessed_in);
1343                                 if (pp_result != EXIT_SUCCESS) {
1344                                         /* remove output file */
1345                                         if (out != stdout)
1346                                                 unlink(outname);
1347                                         exit(EXIT_FAILURE);
1348                                 }
1349                         }
1350
1351                         if (mode == BenchmarkParser) {
1352                                 return result;
1353                         } else if (mode == PrintFluffy) {
1354                                 write_fluffy_decls(out, unit);
1355                                 continue;
1356                         } else if (mode == PrintCaml) {
1357                                 write_caml_decls(out, unit);
1358                                 continue;
1359                         } else if (mode == PrintJna) {
1360                                 write_jna_decls(out, unit);
1361                                 continue;
1362                         }
1363
1364                         translation_unit_to_firm(unit);
1365
1366                         if (mode == ParseOnly) {
1367                                 continue;
1368                         }
1369
1370                         if (mode == CompileDump) {
1371                                 /* find irg */
1372                                 ident    *id     = new_id_from_str(dumpfunction);
1373                                 ir_graph *irg    = NULL;
1374                                 int       n_irgs = get_irp_n_irgs();
1375                                 for (int i = 0; i < n_irgs; ++i) {
1376                                         ir_graph *tirg   = get_irp_irg(i);
1377                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1378                                         if (irg_id == id) {
1379                                                 irg = tirg;
1380                                                 break;
1381                                         }
1382                                 }
1383
1384                                 if (irg == NULL) {
1385                                         fprintf(stderr, "No graph for function '%s' found\n",
1386                                                 dumpfunction);
1387                                         exit(1);
1388                                 }
1389
1390                                 dump_ir_block_graph_file(irg, out);
1391                                 fclose(out);
1392                                 exit(0);
1393                         }
1394
1395                         gen_firm_finish(asm_out, filename, /*c_mode=*/1,
1396                                         have_const_functions);
1397                         if (asm_out != out) {
1398                                 fclose(asm_out);
1399                         }
1400                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1401                         copy_file(asm_out, in);
1402                         if (in == preprocessed_in) {
1403                                 int pp_result = pclose(preprocessed_in);
1404                                 if (pp_result != EXIT_SUCCESS) {
1405                                         /* remove output in error case */
1406                                         if (out != stdout)
1407                                                 unlink(outname);
1408                                         return pp_result;
1409                                 }
1410                         }
1411                         if (asm_out != out) {
1412                                 fclose(asm_out);
1413                         }
1414                 }
1415
1416                 if (mode == Compile)
1417                         continue;
1418
1419                 /* if we're here then we have preprocessed assembly */
1420                 filename = asm_tempfile;
1421                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1422
1423                 /* assemble */
1424                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1425                         char        temp[1024];
1426                         const char *filename_o;
1427                         if (mode == CompileAssemble) {
1428                                 fclose(out);
1429                                 filename_o = outname;
1430                         } else {
1431                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
1432                                 fclose(tempf);
1433                                 filename_o = temp;
1434                         }
1435
1436                         assemble(filename_o, filename);
1437
1438                         size_t len = strlen(filename_o) + 1;
1439                         filename = obstack_copy(&file_obst, filename_o, len);
1440                         filetype = FILETYPE_OBJECT;
1441                 }
1442
1443                 /* ok we're done here, process next file */
1444                 file->name = filename;
1445                 file->type = filetype;
1446         }
1447
1448         if (result != EXIT_SUCCESS) {
1449                 if (out != stdout)
1450                         unlink(outname);
1451                 return result;
1452         }
1453
1454         /* link program file */
1455         if (mode == CompileAssembleLink) {
1456                 obstack_1grow(&ldflags_obst, '\0');
1457                 const char *flags = obstack_finish(&ldflags_obst);
1458
1459                 /* construct commandline */
1460                 obstack_printf(&file_obst, "%s", LINKER);
1461                 for (file_list_entry_t *entry = files; entry != NULL;
1462                                 entry = entry->next) {
1463                         if (entry->type != FILETYPE_OBJECT)
1464                                 continue;
1465
1466                         add_flag(&file_obst, "%s", entry->name);
1467                 }
1468
1469                 add_flag(&file_obst, "-o");
1470                 add_flag(&file_obst, outname);
1471                 obstack_printf(&file_obst, "%s", flags);
1472                 obstack_1grow(&file_obst, '\0');
1473
1474                 char *commandline = obstack_finish(&file_obst);
1475
1476                 if (verbose) {
1477                         puts(commandline);
1478                 }
1479                 int err = system(commandline);
1480                 if (err != EXIT_SUCCESS) {
1481                         fprintf(stderr, "linker reported an error\n");
1482                         exit(1);
1483                 }
1484         }
1485
1486         obstack_free(&cppflags_obst, NULL);
1487         obstack_free(&ldflags_obst, NULL);
1488         obstack_free(&file_obst, NULL);
1489
1490         exit_mangle();
1491         exit_ast2firm();
1492         exit_parser();
1493         exit_ast();
1494         exit_lexer();
1495         exit_typehash();
1496         exit_types();
1497         exit_tokens();
1498         exit_symbol_table();
1499         return 0;
1500 }