3eb7041e4a03635f2fcfc6d4db6cb33ace07115d
[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
54 #else
55 #include <unistd.h>
56 #define HAVE_MKSTEMP
57 #endif
58
59 #ifndef WITH_LIBCORE
60 #define WITH_LIBCORE
61 #endif
62
63 #include <libfirm/firm.h>
64 #include <libfirm/be.h>
65
66 #include "lexer.h"
67 #include "token_t.h"
68 #include "types.h"
69 #include "type_hash.h"
70 #include "parser.h"
71 #include "ast2firm.h"
72 #include "diagnostic.h"
73 #include "lang_features.h"
74 #include "driver/firm_opt.h"
75 #include "driver/firm_cmdline.h"
76 #include "adt/error.h"
77 #include "write_fluffy.h"
78 #include "write_caml.h"
79 #include "revision.h"
80 #include "warning.h"
81
82 #ifndef PREPROCESSOR
83 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int -U__SIZE_TYPE__ -D__SIZE_TYPE__=__SIZE_TYPE__ -m32 -U__STRICT_ANSI__"
84 #endif
85
86 #ifndef LINKER
87 #define LINKER    "gcc -m32"
88 #endif
89
90 #ifndef ASSEMBLER
91 #define ASSEMBLER "as --32"
92 #endif
93
94 /** The current c mode/dialect. */
95 unsigned int c_mode = _C89|_C99|_GNUC;
96
97 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
98 unsigned int machine_size = 32;
99
100 /** true if the char type is signed. */
101 bool char_is_signed = true;
102
103 /** true for strict language checking. */
104 bool strict_mode = false;
105
106 /** use builtins for some libc functions */
107 bool use_builtins = false;
108
109 /** allow dollar signs in symbols */
110 extern bool allow_dollar_in_symbols;
111
112 /* to switch on printing of implicit casts */
113 extern bool print_implicit_casts;
114
115 /* to switch on printing of parenthesis to indicate operator precedence */
116 extern bool print_parenthesis;
117
118 static int            verbose;
119 static struct obstack cppflags_obst, ldflags_obst;
120
121 typedef struct file_list_entry_t file_list_entry_t;
122
123 typedef enum filetype_t {
124         FILETYPE_AUTODETECT,
125         FILETYPE_C,
126         FILETYPE_PREPROCESSED_C,
127         FILETYPE_ASSEMBLER,
128         FILETYPE_PREPROCESSED_ASSEMBLER,
129         FILETYPE_OBJECT,
130         FILETYPE_UNKNOWN
131 } filetype_t;
132
133 struct file_list_entry_t {
134         const char        *name; /**< filename or NULL for stdin */
135         filetype_t         type;
136         file_list_entry_t *next;
137 };
138
139 #if defined(_DEBUG) || defined(FIRM_DEBUG)
140 /**
141  * Debug printf implementation.
142  *
143  * @param fmt  printf style format parameter
144  */
145 void dbg_printf(const char *fmt, ...)
146 {
147         va_list list;
148
149         if (firm_dump.debug_print) {
150                 va_start(list, fmt);
151                 vprintf(fmt, list);
152                 va_end(list);
153         }  /* if */
154 }
155 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
156
157 static void initialize_firm(void)
158 {
159         firm_early_init();
160
161         dump_consts_local(1);
162         dump_keepalive_edges(1);
163 }
164
165 static void get_output_name(char *buf, size_t buflen, const char *inputname,
166                             const char *newext)
167 {
168         size_t last_dot = 0xffffffff;
169         size_t i = 0;
170
171         if(inputname == NULL) {
172                 snprintf(buf, buflen, "a%s", newext);
173                 return;
174         }
175
176         for(const char *c = inputname; *c != 0; ++c) {
177                 if(*c == '.')
178                         last_dot = i;
179                 ++i;
180         }
181         if(last_dot == 0xffffffff)
182                 last_dot = i;
183
184         if(last_dot >= buflen)
185                 panic("filename too long");
186         memcpy(buf, inputname, last_dot);
187
188         size_t extlen = strlen(newext) + 1;
189         if(extlen + last_dot >= buflen)
190                 panic("filename too long");
191         memcpy(buf+last_dot, newext, extlen);
192 }
193
194 #include "builtins.h"
195
196 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
197 {
198         start_parsing();
199
200         if (use_builtins) {
201                 lexer_open_buffer(builtins, sizeof(builtins)-1, "<builtin>");
202                 parse();
203         }
204
205         lexer_open_stream(in, input_name);
206         parse();
207
208         translation_unit_t *unit = finish_parsing();
209         return unit;
210 }
211
212 static void lextest(FILE *in, const char *fname)
213 {
214         lexer_open_stream(in, fname);
215
216         do {
217                 lexer_next_preprocessing_token();
218                 print_token(stdout, &lexer_token);
219                 puts("");
220         } while(lexer_token.type != T_EOF);
221 }
222
223 static void add_flag(struct obstack *obst, const char *format, ...)
224 {
225         va_list ap;
226         va_start(ap, format);
227
228         char buf[4096];
229         vsnprintf(buf, sizeof(buf), format, ap);
230
231         /* escape stuff... */
232         obstack_1grow(obst, ' ');
233         for (char *c = buf; *c != '\0'; ++c) {
234                 switch(*c) {
235                 case '"':
236                 case '\'':
237                 case '`':
238                 case ' ':
239                 case '\t':
240                 case '\n':
241                 case '\r':
242                 case '\\':
243                 case '$':
244                 case '(':
245                 case ')':
246                         obstack_1grow(obst, '\\');
247                         /* fallthrough */
248                 default:
249                         obstack_1grow(obst, *c);
250                         break;
251                 }
252         }
253
254         va_end(ap);
255 }
256
257 static FILE *preprocess(const char *fname)
258 {
259         char buf[4096];
260         obstack_1grow(&cppflags_obst, '\0');
261         const char *flags = obstack_finish(&cppflags_obst);
262
263         snprintf(buf, sizeof(buf), PREPROCESSOR " %s %s", flags, fname);
264         if(verbose) {
265                 puts(buf);
266         }
267
268         FILE *f = popen(buf, "r");
269         if(f == NULL) {
270                 fprintf(stderr, "invoking preprocessor failed\n");
271                 exit(1);
272         }
273         return f;
274 }
275
276 static void assemble(const char *out, const char *in)
277 {
278         char buf[4096];
279
280         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
281         if(verbose) {
282                 puts(buf);
283         }
284
285         int err = system(buf);
286         if(err != 0) {
287                 fprintf(stderr, "assembler reported an error\n");
288                 exit(1);
289         }
290 }
291
292 static const char *try_dir(const char *dir)
293 {
294         if(dir == NULL)
295                 return dir;
296         if(access(dir, R_OK | W_OK | X_OK) == 0)
297                 return dir;
298         return NULL;
299 }
300
301 static const char *get_tempdir(void)
302 {
303         static const char *tmpdir = NULL;
304
305         if(tmpdir != NULL)
306                 return tmpdir;
307
308         if(tmpdir == NULL)
309                 tmpdir = try_dir(getenv("TMPDIR"));
310         if(tmpdir == NULL)
311                 tmpdir = try_dir(getenv("TMP"));
312         if(tmpdir == NULL)
313                 tmpdir = try_dir(getenv("TEMP"));
314
315 #ifdef P_tmpdir
316         if(tmpdir == NULL)
317                 tmpdir = try_dir(P_tmpdir);
318 #endif
319
320         if(tmpdir == NULL)
321                 tmpdir = try_dir("/var/tmp");
322         if(tmpdir == NULL)
323                 tmpdir = try_dir("/usr/tmp");
324         if(tmpdir == NULL)
325                 tmpdir = try_dir("/tmp");
326
327         if(tmpdir == NULL)
328                 tmpdir = ".";
329
330         return tmpdir;
331 }
332
333 #ifndef HAVE_MKSTEMP
334 /* cheap and nasty mkstemp replacement */
335 static int mkstemp(char *templ)
336 {
337         mktemp(templ);
338         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
339 }
340 #endif
341
342 /**
343  * an own version of tmpnam, which: writes in a buffer, emits no warnings
344  * during linking (like glibc/gnu ld do for tmpnam)...
345  */
346 static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix)
347 {
348         const char *tempdir = get_tempdir();
349
350         snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix);
351
352         int fd = mkstemp(buffer);
353         if(fd == -1) {
354                 fprintf(stderr, "couldn't create temporary file: %s\n",
355                         strerror(errno));
356                 exit(1);
357         }
358         FILE *out = fdopen(fd, "w");
359         if(out == NULL) {
360                 fprintf(stderr, "couldn't create temporary file FILE*\n");
361                 exit(1);
362         }
363
364         return out;
365 }
366
367 /**
368  * Do the necessary lowering for compound parameters.
369  */
370 void lower_compound_params(void)
371 {
372         lower_params_t params;
373
374         params.def_ptr_alignment    = 4;
375         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
376         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
377         params.find_pointer_type    = NULL;
378         params.ret_compound_in_regs = NULL;
379         lower_calls_with_compounds(&params);
380 }
381
382 typedef enum compile_mode_t {
383         BenchmarkParser,
384         PreprocessOnly,
385         ParseOnly,
386         Compile,
387         CompileDump,
388         CompileAssemble,
389         CompileAssembleLink,
390         LexTest,
391         PrintAst,
392         PrintFluffy,
393         PrintCaml
394 } compile_mode_t;
395
396 static void usage(const char *argv0)
397 {
398         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
399 }
400
401 static void print_cparser_version(void) {
402         firm_version_t ver;
403         firm_get_version(&ver);
404
405         printf("cparser (%s) using libFirm (%u.%u",
406                 cparser_REVISION, ver.major, ver.minor);
407         if(ver.revision[0] != 0) {
408                 putchar(' ');
409                 fputs(ver.revision, stdout);
410         }
411         if(ver.build[0] != 0) {
412                 putchar(' ');
413                 fputs(ver.build, stdout);
414         }
415         puts(")\n");
416 }
417
418 static void set_be_option(const char *arg)
419 {
420         int res = firm_be_option(arg);
421         (void) res;
422         assert(res);
423 }
424
425 static void set_option(const char *arg)
426 {
427         int res = firm_option(arg);
428         (void) res;
429         assert(res);
430 }
431
432 static void copy_file(FILE *dest, FILE *input)
433 {
434         char buf[16384];
435
436         while (!feof(input) && !ferror(dest)) {
437                 size_t read = fread(buf, 1, sizeof(buf), input);
438                 if(fwrite(buf, 1, read, dest) != read) {
439                         perror("couldn't write output");
440                 }
441         }
442 }
443
444 static FILE *open_file(const char *filename)
445 {
446         if (strcmp(filename, "-") == 0) {
447                 return stdin;
448         }
449
450         FILE *in = fopen(filename, "r");
451         if(in == NULL) {
452                 fprintf(stderr, "Couldn't open '%s': %s\n", filename,
453                                 strerror(errno));
454                 exit(1);
455         }
456
457         return in;
458 }
459
460 static filetype_t get_filetype_from_string(const char *string)
461 {
462         if (strcmp(string, "c") == 0 || strcmp(string, "c-header") == 0)
463                 return FILETYPE_C;
464         if (strcmp(string, "assembler") == 0)
465                 return FILETYPE_PREPROCESSED_ASSEMBLER;
466         if (strcmp(string, "assembler-with-cpp") == 0)
467                 return FILETYPE_ASSEMBLER;
468         if (strcmp(string, "none") == 0)
469                 return FILETYPE_AUTODETECT;
470
471         return FILETYPE_UNKNOWN;
472 }
473
474 int main(int argc, char **argv)
475 {
476         initialize_firm();
477
478         const char        *outname      = NULL;
479         const char        *dumpfunction = NULL;
480         compile_mode_t     mode         = CompileAssembleLink;
481         int                opt_level    = 1;
482         int                result       = EXIT_SUCCESS;
483         char               cpu_arch[16] = "ia32";
484         file_list_entry_t *files        = NULL;
485         file_list_entry_t *last_file    = NULL;
486         struct obstack     file_obst;
487
488         obstack_init(&cppflags_obst);
489         obstack_init(&ldflags_obst);
490         obstack_init(&file_obst);
491
492 #define GET_ARG_AFTER(def, args)                                             \
493         def = &arg[sizeof(args)-1];                                              \
494         if(def[0] == '\0') {                                                     \
495                 ++i;                                                                 \
496                 if(i >= argc) {                                                      \
497                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
498                         argument_errors = true;                                          \
499                         break;                                                           \
500                 }                                                                    \
501                 def = argv[i];                                                       \
502                 if(def[0] == '-' && def[1] != '\0') {                                \
503                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
504                         argument_errors = true;                                          \
505                         continue;                                                        \
506                 }                                                                    \
507         }
508
509 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
510
511         /* early options parsing (find out optimisation level) */
512         for(int i = 1; i < argc; ++i) {
513                 const char *arg = argv[i];
514                 if(arg[0] != '-')
515                         continue;
516
517                 const char *option = &arg[1];
518                 if(option[0] == 'O') {
519                         sscanf(&option[1], "%d", &opt_level);
520                 }
521         }
522
523         /* apply optimisation level */
524         switch(opt_level) {
525         case 0:
526                 set_option("no-opt");
527                 break;
528         case 1:
529                 set_option("no-inline");
530                 break;
531         default:
532         case 4:
533                 set_option("strict-aliasing");
534                 /* fallthrough */
535         case 3:
536                 set_option("cond-eval");
537                 set_option("if-conv");
538                 use_builtins = true;
539                 /* fallthrough */
540         case 2:
541                 set_option("inline");
542                 set_option("deconv");
543                 set_be_option("omitfp");
544                 break;
545         }
546
547         /* parse rest of options */
548         filetype_t  forced_filetype = FILETYPE_AUTODETECT;
549         bool        help_displayed  = false;
550         bool        argument_errors = false;
551         for(int i = 1; i < argc; ++i) {
552                 const char *arg = argv[i];
553                 if(arg[0] == '-' && arg[1] != 0) {
554                         /* an option */
555                         const char *option = &arg[1];
556                         if(option[0] == 'o') {
557                                 GET_ARG_AFTER(outname, "-o");
558                         } else if(option[0] == 'g') {
559                                 set_be_option("debuginfo=stabs");
560                                 set_be_option("omitfp=no");
561                                 set_be_option("ia32-nooptcc=yes");
562                         } else if(SINGLE_OPTION('c')) {
563                                 mode = CompileAssemble;
564                         } else if(SINGLE_OPTION('E')) {
565                                 mode = PreprocessOnly;
566                         } else if(SINGLE_OPTION('S')) {
567                                 mode = Compile;
568                         } else if(option[0] == 'O') {
569                                 continue;
570                         } else if(option[0] == 'I') {
571                                 const char *opt;
572                                 GET_ARG_AFTER(opt, "-I");
573                                 add_flag(&cppflags_obst, "-I%s", opt);
574                         } else if(option[0] == 'D') {
575                                 const char *opt;
576                                 GET_ARG_AFTER(opt, "-D");
577                                 add_flag(&cppflags_obst, "-D%s", opt);
578                         } else if(option[0] == 'U') {
579                                 const char *opt;
580                                 GET_ARG_AFTER(opt, "-U");
581                                 add_flag(&cppflags_obst, "-U%s", opt);
582                         } else if(option[0] == 'l') {
583                                 const char *opt;
584                                 GET_ARG_AFTER(opt, "-l");
585                                 add_flag(&ldflags_obst, "-l%s", opt);
586                         } else if(option[0] == 'L') {
587                                 const char *opt;
588                                 GET_ARG_AFTER(opt, "-L");
589                                 add_flag(&ldflags_obst, "-L%s", opt);
590                         } else if(SINGLE_OPTION('v')) {
591                                 verbose = 1;
592                         } else if(SINGLE_OPTION('w')) {
593                                 inhibit_all_warnings = true;
594                         } else if(option[0] == 'x') {
595                                 const char *opt;
596                                 GET_ARG_AFTER(opt, "-x");
597                                 forced_filetype = get_filetype_from_string(opt);
598                                 if (forced_filetype == FILETYPE_UNKNOWN) {
599                                         fprintf(stderr, "Unknown language '%s'\n", opt);
600                                         argument_errors = true;
601                                 }
602                         } else if(strcmp(option, "M") == 0) {
603                                 mode = PreprocessOnly;
604                                 add_flag(&cppflags_obst, "-M");
605                         } else if (strcmp(option, "MMD") == 0 ||
606                                    strcmp(option, "MD")  == 0 ||
607                                    strcmp(option, "MM")  == 0 ||
608                                    strcmp(option, "MP")  == 0) {
609                                 add_flag(&cppflags_obst, "-%s", option);
610                         } else if(strcmp(option, "MT") == 0
611                                         || strcmp(option, "MQ") == 0
612                                         || strcmp(option, "MF") == 0) {
613                                 const char *opt;
614                                 GET_ARG_AFTER(opt, "-MT");
615                                 add_flag(&cppflags_obst, "-%s", option);
616                                 add_flag(&cppflags_obst, "%s", opt);
617                         } else if(strcmp(option, "pipe") == 0) {
618                                 /* here for gcc compatibility */
619                         } else if(option[0] == 'f') {
620                                 const char *opt;
621                                 GET_ARG_AFTER(opt, "-f");
622
623                                 if(strcmp(opt, "syntax-only") == 0) {
624                                         mode = ParseOnly;
625                                 } else if(strcmp(opt, "omit-frame-pointer") == 0) {
626                                         set_be_option("omitfp");
627                                 } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
628                                         set_be_option("omitfp=no");
629                                 } else if(strcmp(opt, "strength-reduce") == 0) {
630                                         firm_option("strength-red");
631                                 } else if(strcmp(opt, "fast-math") == 0
632                                                 || strcmp(opt, "unroll-loops") == 0
633                                                 || strcmp(opt, "expensive-optimizations") == 0
634                                                 || strcmp(opt, "no-common") == 0
635                                                 || strcmp(opt, "PIC") == 0
636                                                 || strncmp(opt, "align-loops=", sizeof("align-loops=")-1) == 0
637                                                 || strncmp(opt, "align-jumps=", sizeof("align-jumps=")-1) == 0
638                                                 || strncmp(opt, "align-functions=", sizeof("align-functions=")-1) == 0) {
639                                         fprintf(stderr, "ignoring gcc option '-f %s'\n", opt);
640                                 } else {
641                                         int res = firm_option(opt);
642                                         if (res == 0) {
643                                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
644                                                         opt);
645                                                 argument_errors = true;
646                                                 continue;
647                                         } else if (res == -1) {
648                                                 help_displayed = true;
649                                         }
650                                 }
651                         } else if(option[0] == 'b') {
652                                 const char *opt;
653                                 GET_ARG_AFTER(opt, "-b");
654                                 int res = firm_be_option(opt);
655                                 if (res == 0) {
656                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
657                                                 opt);
658                                         argument_errors = true;
659                                 } else if (res == -1) {
660                                         help_displayed = true;
661                                 } else {
662                                         if (strncmp(opt, "isa=", 4) == 0)
663                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
664                                 }
665                         } else if(option[0] == 'W') {
666                                 if(strncmp(option + 1, "l,", 2) == 0)   // a gcc-style linker option
667                                 {
668                                         const char *opt;
669                                         GET_ARG_AFTER(opt, "-Wl,");
670                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
671                                 }
672                                 else set_warning_opt(&option[1]);
673                         } else if(option[0] == 'm') {
674                                 /* -m options */
675                                 const char *opt;
676                                 char arch_opt[64];
677
678                                 GET_ARG_AFTER(opt, "-m");
679                                 if(strncmp(opt, "arch=", 5) == 0) {
680                                         GET_ARG_AFTER(opt, "-march=");
681                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
682                                         int res = firm_be_option(arch_opt);
683                                         if (res == 0)
684                                                 argument_errors = true;
685                                         else {
686                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
687                                                 int res = firm_be_option(arch_opt);
688                                                 if (res == 0)
689                                                         argument_errors = true;
690                                         }
691                                 } else if(strncmp(opt, "tune=", 5) == 0) {
692                                         GET_ARG_AFTER(opt, "-mtune=");
693                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
694                                         int res = firm_be_option(arch_opt);
695                                         if (res == 0)
696                                                 argument_errors = true;
697                                 } else if(strncmp(opt, "cpu=", 4) == 0) {
698                                         GET_ARG_AFTER(opt, "-mcpu=");
699                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
700                                         int res = firm_be_option(arch_opt);
701                                         if (res == 0)
702                                                 argument_errors = true;
703                                 } else if(strncmp(opt, "fpmath=", 7) == 0) {
704                                         GET_ARG_AFTER(opt, "-mfpmath=");
705                                         if(strcmp(opt, "387") == 0)
706                                                 opt = "x87";
707                                         else if(strcmp(opt, "sse") == 0)
708                                                 opt = "sse2";
709                                         else {
710                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
711                                                 argument_errors = true;
712                                         }
713                                         if(!argument_errors) {
714                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
715                                                 int res = firm_be_option(arch_opt);
716                                                 if (res == 0)
717                                                         argument_errors = true;
718                                         }
719                                 } else if(strncmp(opt, "preferred-stack-boundary=", 25) == 0) {
720                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
721                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
722                                         int res = firm_be_option(arch_opt);
723                                         if (res == 0)
724                                                 argument_errors = true;
725                                 } else if(strcmp(opt, "omit-leaf-frame-pointer") == 0) {
726                                         set_be_option("omitleaffp=1");
727                                 } else if(strcmp(opt, "no-omit-leaf-frame-pointer") == 0) {
728                                         set_be_option("omitleaffp=0");
729                                 } else {
730                                         char *endptr;
731                                         long int value = strtol(opt, &endptr, 10);
732                                         if (*endptr != '\0') {
733                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
734                                                 argument_errors = true;
735                                         }
736                                         if (value != 16 && value != 32 && value != 64) {
737                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
738                                                 argument_errors = true;
739                                         } else {
740                                                 machine_size = (unsigned int)value;
741                                         }
742                                 }
743                         } else if(strcmp(option, "pg") == 0) {
744                                 set_be_option("gprof");
745                                 add_flag(&ldflags_obst, "-pg");
746                         } else if(strcmp(option, "pedantic") == 0
747                                         || strcmp(option, "ansi") == 0) {
748                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
749                         } else if(strcmp(option, "shared") == 0) {
750                                 add_flag(&ldflags_obst, "-shared");
751                         } else if(strncmp(option, "std=", 4) == 0) {
752                                 if(strcmp(&option[4], "c99") == 0) {
753                                         c_mode = _C89|_C99;
754                                 } else if(strcmp(&option[4], "c89") == 0) {
755                                         c_mode = _C89;
756                                 } else if(strcmp(&option[4], "gnu99") == 0) {
757                                         c_mode = _C89|_C99|_GNUC;
758                                 } else if(strcmp(&option[4], "microsoft") == 0) {
759                                         c_mode = _C89|_C99|_MS;
760                                 } else
761                                         fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
762                         } else if(strcmp(option, "version") == 0) {
763                                 print_cparser_version();
764                         } else if (option[0] == '-') {
765                                 /* double dash option */
766                                 ++option;
767                                 if(strcmp(option, "gcc") == 0) {
768                                         c_mode |= _GNUC;
769                                 } else if(strcmp(option, "no-gcc") == 0) {
770                                         c_mode &= ~_GNUC;
771                                 } else if(strcmp(option, "ms") == 0) {
772                                         c_mode |= _MS;
773                                 } else if(strcmp(option, "no-ms") == 0) {
774                                         c_mode &= ~_MS;
775                                 } else if(strcmp(option, "signed-chars") == 0) {
776                                         char_is_signed = true;
777                                 } else if(strcmp(option, "unsigned-chars") == 0) {
778                                         char_is_signed = false;
779                                 } else if(strcmp(option, "strict") == 0) {
780                                         strict_mode = true;
781                                 } else if(strcmp(option, "lextest") == 0) {
782                                         mode = LexTest;
783                                 } else if(strcmp(option, "benchmark") == 0) {
784                                         mode = BenchmarkParser;
785                                 } else if(strcmp(option, "print-ast") == 0) {
786                                         mode = PrintAst;
787                                 } else if(strcmp(option, "print-implicit-cast") == 0) {
788                                         print_implicit_casts = true;
789                                 } else if(strcmp(option, "print-parenthesis") == 0) {
790                                         print_parenthesis = true;
791                                 } else if(strcmp(option, "print-fluffy") == 0) {
792                                         mode = PrintFluffy;
793                                 } else if(strcmp(option, "print-caml") == 0) {
794                                         mode = PrintCaml;
795                                 } else if(strcmp(option, "version") == 0) {
796                                         print_cparser_version();
797                                         exit(EXIT_SUCCESS);
798                                 } else if(strcmp(option, "dump-function") == 0) {
799                                         ++i;
800                                         if(i >= argc) {
801                                                 fprintf(stderr, "error: "
802                                                         "expected argument after '--dump-function'\n");
803                                                 argument_errors = true;
804                                                 break;
805                                         }
806                                         dumpfunction = argv[i];
807                                         mode         = CompileDump;
808                                 } else {
809                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
810                                         argument_errors = true;
811                                 }
812                         } else {
813                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
814                                 argument_errors = true;
815                         }
816                 } else {
817                         filetype_t  type     = forced_filetype;
818                         const char *filename = arg;
819                         if (type == FILETYPE_AUTODETECT) {
820                                 size_t      len      = strlen(arg);
821                                 if (len < 2 && arg[0] == '-') {
822                                         /* - implicitely means C source file */
823                                         type     = FILETYPE_C;
824                                         filename = NULL;
825                                 } else if (len > 2 && arg[len-2] == '.') {
826                                         switch(arg[len-1]) {
827                                         case 'c': type = FILETYPE_C; break;
828                                         case 'h': type = FILETYPE_C; break;
829                                         case 's': type = FILETYPE_PREPROCESSED_ASSEMBLER; break;
830                                         case 'S': type = FILETYPE_ASSEMBLER; break;
831
832                                         case 'a':
833                                         case 'o': type = FILETYPE_OBJECT; break;
834                                         }
835                                 } else if (len > 3 && arg[len-3] == '.') {
836                                         if(strcmp(arg + len - 2, "so") == 0) {
837                                                 type = FILETYPE_OBJECT;
838                                         }
839                                 }
840
841                                 if (type == FILETYPE_AUTODETECT) {
842                                         fprintf(stderr, "'%s': file format not recognized\n", arg);
843                                         continue;
844                                 }
845                         }
846
847                         file_list_entry_t *entry
848                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
849                         memset(entry, 0, sizeof(entry[0]));
850                         entry->name = arg;
851                         entry->type = type;
852
853                         if (last_file != NULL) {
854                                 last_file->next = entry;
855                         } else {
856                                 files = entry;
857                         }
858                         last_file = entry;
859                 }
860         }
861
862         if (files == NULL) {
863                 fprintf(stderr, "error: no input files specified\n");
864                 argument_errors = true;
865         }
866
867         if (help_displayed) {
868                 return !argument_errors;
869         }
870         if (argument_errors) {
871                 usage(argv[0]);
872                 return 1;
873         }
874
875         /* we do the lowering in ast2firm */
876         firm_opt.lower_bitfields = FALSE;
877
878         gen_firm_init();
879         init_symbol_table();
880         init_tokens();
881         init_types();
882         init_typehash();
883         init_basic_types();
884         init_lexer(allow_dollar_in_symbols);
885         init_ast();
886         init_parser();
887         init_ast2firm();
888
889         char outnamebuf[4096];
890         if (outname == NULL) {
891                 const char *filename = files->name;
892
893                 switch(mode) {
894                 case BenchmarkParser:
895                 case PrintAst:
896                 case PrintFluffy:
897                 case PrintCaml:
898                 case LexTest:
899                 case PreprocessOnly:
900                         outname = "-";
901                         break;
902                 case ParseOnly:
903                         break;
904                 case Compile:
905                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
906                         outname = outnamebuf;
907                         break;
908                 case CompileAssemble:
909                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
910                         outname = outnamebuf;
911                         break;
912                 case CompileDump:
913                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
914                                         ".vcg");
915                         outname = outnamebuf;
916                         break;
917                 case CompileAssembleLink:
918 #ifdef _WIN32
919                         outname = "a.exe";
920 #else
921                         outname = "a.out";
922 #endif
923                         break;
924                 }
925         }
926
927         assert(outname != NULL);
928
929         FILE *out;
930         if(strcmp(outname, "-") == 0) {
931                 out = stdout;
932         } else {
933                 out = fopen(outname, "w");
934                 if(out == NULL) {
935                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
936                                         strerror(errno));
937                         return 1;
938                 }
939         }
940
941         file_list_entry_t *file;
942         for (file = files; file != NULL; file = file->next) {
943                 char        asm_tempfile[1024];
944                 const char *filename = file->name;
945                 filetype_t  filetype = file->type;
946
947                 if (file->type == FILETYPE_OBJECT)
948                         continue;
949
950                 FILE *in = NULL;
951                 if (mode == LexTest) {
952                         if (in == NULL)
953                                 in = open_file(filename);
954                         lextest(in, filename);
955                         fclose(in);
956                         exit(EXIT_SUCCESS);
957                 }
958
959                 FILE *preprocessed_in = NULL;
960                 if (filetype == FILETYPE_C || filetype == FILETYPE_ASSEMBLER) {
961                         /* no support for input on FILE* yet */
962                         if (in != NULL)
963                                 panic("internal compiler error: in for preprocessor != NULL");
964
965                         preprocessed_in = preprocess(filename);
966                         if (mode == PreprocessOnly) {
967                                 copy_file(out, preprocessed_in);
968                                 int result = pclose(preprocessed_in);
969                                 fclose(out);
970                                 return result;
971                         }
972
973                         if (filetype == FILETYPE_C) {
974                                 filetype = FILETYPE_PREPROCESSED_C;
975                         } else if (filetype == FILETYPE_ASSEMBLER) {
976                                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
977                         } else {
978                                 panic("internal compiler error: unknown filetype at preproc");
979                         }
980
981                         in = preprocessed_in;
982                 }
983
984                 FILE *asm_out;
985                 if(mode == Compile) {
986                         asm_out = out;
987                 } else {
988                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile),
989                                                  "ccs");
990                 }
991
992                 if (in == NULL)
993                         in = open_file(filename);
994
995                 /* preprocess and compile */
996                 if (filetype == FILETYPE_PREPROCESSED_C) {
997                         translation_unit_t *const unit = do_parsing(in, filename);
998                         if (in == preprocessed_in) {
999                                 int pp_result = pclose(preprocessed_in);
1000                                 if (pp_result != EXIT_SUCCESS) {
1001                                         exit(EXIT_FAILURE);
1002                                 }
1003                         }
1004
1005                         /* prints the AST even if errors occurred */
1006                         if (mode == PrintAst) {
1007                                 type_set_output(out);
1008                                 ast_set_output(out);
1009                                 print_ast(unit);
1010                         }
1011
1012                         if(error_count > 0) {
1013                                 /* parsing failed because of errors */
1014                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1015                                         warning_count);
1016                                 result = EXIT_FAILURE;
1017                                 continue;
1018                         } else if(warning_count > 0) {
1019                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1020                         }
1021
1022                         if(mode == BenchmarkParser) {
1023                                 return result;
1024                         } else if(mode == PrintFluffy) {
1025                                 write_fluffy_decls(out, unit);
1026                                 continue;
1027                         } else if (mode == PrintCaml) {
1028                                 write_caml_decls(out, unit);
1029                                 continue;
1030                         }
1031
1032                         translation_unit_to_firm(unit);
1033
1034                         if (mode == ParseOnly) {
1035                                 continue;
1036                         }
1037
1038                         if (mode == CompileDump) {
1039                                 /* find irg */
1040                                 ident    *id     = new_id_from_str(dumpfunction);
1041                                 ir_graph *irg    = NULL;
1042                                 int       n_irgs = get_irp_n_irgs();
1043                                 for(int i = 0; i < n_irgs; ++i) {
1044                                         ir_graph *tirg   = get_irp_irg(i);
1045                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1046                                         if(irg_id == id) {
1047                                                 irg = tirg;
1048                                                 break;
1049                                         }
1050                                 }
1051
1052                                 if(irg == NULL) {
1053                                         fprintf(stderr, "No graph for function '%s' found\n",
1054                                                 dumpfunction);
1055                                         exit(1);
1056                                 }
1057
1058                                 dump_ir_block_graph_file(irg, out);
1059                                 fclose(out);
1060                                 exit(0);
1061                         }
1062
1063                         gen_firm_finish(asm_out, filename, /*c_mode=*/1,
1064                                         /*firm_const_exists=*/0);
1065                         if (asm_out != out) {
1066                                 fclose(asm_out);
1067                         }
1068
1069                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1070                         copy_file(asm_out, in);
1071                         if (in == preprocessed_in) {
1072                                 int pp_result = pclose(preprocessed_in);
1073                                 if (pp_result != EXIT_SUCCESS) {
1074                                         return pp_result;
1075                                 }
1076                         }
1077                         if(asm_out != out) {
1078                                 fclose(asm_out);
1079                         }
1080                 }
1081
1082                 if (mode == Compile)
1083                         continue;
1084
1085                 /* if we're here then we have preprocessed assembly */
1086                 filename = asm_tempfile;
1087                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1088
1089                 /* assemble */
1090                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1091                         char        temp[1024];
1092                         const char *filename_o;
1093                         if(mode == CompileAssemble) {
1094                                 fclose(out);
1095                                 filename_o = outname;
1096                         } else {
1097                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
1098                                 fclose(tempf);
1099                                 filename_o = temp;
1100                         }
1101
1102                         assemble(filename_o, filename);
1103
1104                         size_t len = strlen(filename_o) + 1;
1105                         filename = obstack_copy(&file_obst, filename_o, len);
1106                         filetype = FILETYPE_OBJECT;
1107                 }
1108
1109                 /* ok we're done here, process next file */
1110                 file->name = filename;
1111                 file->type = filetype;
1112         }
1113
1114         if (result != EXIT_SUCCESS)
1115                 return result;
1116
1117         /* link program file */
1118         if(mode == CompileAssembleLink) {
1119                 obstack_1grow(&ldflags_obst, '\0');
1120                 const char *flags = obstack_finish(&ldflags_obst);
1121
1122                 /* construct commandline */
1123                 obstack_printf(&file_obst, "%s", LINKER);
1124                 for (file_list_entry_t *entry = files; entry != NULL;
1125                                 entry = entry->next) {
1126                         if (entry->type != FILETYPE_OBJECT)
1127                                 continue;
1128
1129                         add_flag(&file_obst, "%s", entry->name);
1130                 }
1131
1132                 add_flag(&file_obst, "-o");
1133                 add_flag(&file_obst, outname);
1134                 obstack_printf(&file_obst, "%s", flags);
1135                 obstack_1grow(&file_obst, '\0');
1136
1137                 char *commandline = obstack_finish(&file_obst);
1138
1139                 if(verbose) {
1140                         puts(commandline);
1141                 }
1142                 int err = system(commandline);
1143                 if(err != EXIT_SUCCESS) {
1144                         fprintf(stderr, "linker reported an error\n");
1145                         exit(1);
1146                 }
1147         }
1148
1149         obstack_free(&cppflags_obst, NULL);
1150         obstack_free(&ldflags_obst, NULL);
1151         obstack_free(&file_obst, NULL);
1152
1153         exit_ast2firm();
1154         exit_parser();
1155         exit_ast();
1156         exit_lexer();
1157         exit_typehash();
1158         exit_types();
1159         exit_tokens();
1160         exit_symbol_table();
1161         return 0;
1162 }