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