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