-Waggregate-return implemented
[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                 /* fallthrough */
571         case 3:
572                 set_option("cond-eval");
573                 set_option("if-conv");
574                 use_builtins = true;
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                                         } else if (streq(opt, "short-wchar")) {
681                                                 opt_short_wchar_t = truth_value;
682                                         } else if (streq(opt, "syntax-only")) {
683                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
684                                         } else if (streq(opt, "omit-frame-pointer")) {
685                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
686                                         } else if (streq(opt, "strength-reduce")) {
687                                                 firm_option(truth_value ? "strength-red" : "no-strength-red");
688                                         } else if (streq(opt, "fast-math")               ||
689                                                    streq(opt, "jump-tables")             ||
690                                                    streq(opt, "unroll-loops")            ||
691                                                    streq(opt, "expensive-optimizations") ||
692                                                    streq(opt, "common")                  ||
693                                                    streq(opt, "PIC")                     ||
694                                                    streq(opt, "align-loops")             ||
695                                                    streq(opt, "align-jumps")             ||
696                                                    streq(opt, "align-functions")) {
697                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
698                                         } else {
699                                                 int res = firm_option(orig_opt);
700                                                 if (res == 0) {
701                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
702                                                                 orig_opt);
703                                                         argument_errors = true;
704                                                         continue;
705                                                 } else if (res == -1) {
706                                                         help_displayed = true;
707                                                 }
708                                         }
709                                 }
710                         } else if (option[0] == 'b') {
711                                 const char *opt;
712                                 GET_ARG_AFTER(opt, "-b");
713                                 int res = firm_be_option(opt);
714                                 if (res == 0) {
715                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
716                                                 opt);
717                                         argument_errors = true;
718                                 } else if (res == -1) {
719                                         help_displayed = true;
720                                 } else if (strstart(opt, "isa=")) {
721                                         strncpy(cpu_arch, opt, sizeof(cpu_arch));
722                                 }
723                         } else if (option[0] == 'W') {
724                                 if (strstart(option + 1, "l,")) // a gcc-style linker option
725                                 {
726                                         const char *opt;
727                                         GET_ARG_AFTER(opt, "-Wl,");
728                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
729                                 }
730                                 else set_warning_opt(&option[1]);
731                         } else if(option[0] == 'm') {
732                                 /* -m options */
733                                 const char *opt;
734                                 char arch_opt[64];
735
736                                 GET_ARG_AFTER(opt, "-m");
737                                 if (strstart(opt, "arch=")) {
738                                         GET_ARG_AFTER(opt, "-march=");
739                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
740                                         int res = firm_be_option(arch_opt);
741                                         if (res == 0)
742                                                 argument_errors = true;
743                                         else {
744                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
745                                                 int res = firm_be_option(arch_opt);
746                                                 if (res == 0)
747                                                         argument_errors = true;
748                                         }
749                                 } else if (strstart(opt, "tune=")) {
750                                         GET_ARG_AFTER(opt, "-mtune=");
751                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
752                                         int res = firm_be_option(arch_opt);
753                                         if (res == 0)
754                                                 argument_errors = true;
755                                 } else if (strstart(opt, "cpu=")) {
756                                         GET_ARG_AFTER(opt, "-mcpu=");
757                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
758                                         int res = firm_be_option(arch_opt);
759                                         if (res == 0)
760                                                 argument_errors = true;
761                                 } else if (strstart(opt, "fpmath=")) {
762                                         GET_ARG_AFTER(opt, "-mfpmath=");
763                                         if (streq(opt, "387"))
764                                                 opt = "x87";
765                                         else if (streq(opt, "sse"))
766                                                 opt = "sse2";
767                                         else {
768                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
769                                                 argument_errors = true;
770                                         }
771                                         if(!argument_errors) {
772                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
773                                                 int res = firm_be_option(arch_opt);
774                                                 if (res == 0)
775                                                         argument_errors = true;
776                                         }
777                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
778                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
779                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
780                                         int res = firm_be_option(arch_opt);
781                                         if (res == 0)
782                                                 argument_errors = true;
783                                 } else if (streq(opt, "omit-leaf-frame-pointer")) {
784                                         set_be_option("omitleaffp=1");
785                                 } else if (streq(opt, "no-omit-leaf-frame-pointer")) {
786                                         set_be_option("omitleaffp=0");
787                                 } else {
788                                         char *endptr;
789                                         long int value = strtol(opt, &endptr, 10);
790                                         if (*endptr != '\0') {
791                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
792                                                 argument_errors = true;
793                                         }
794                                         if (value != 16 && value != 32 && value != 64) {
795                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
796                                                 argument_errors = true;
797                                         } else {
798                                                 machine_size = (unsigned int)value;
799                                         }
800                                 }
801                         } else if (streq(option, "pg")) {
802                                 set_be_option("gprof");
803                                 add_flag(&ldflags_obst, "-pg");
804                         } else if (streq(option, "pedantic") ||
805                                    streq(option, "ansi")) {
806                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
807                         } else if (streq(option, "shared")) {
808                                 add_flag(&ldflags_obst, "-shared");
809                         } else if (strstart(option, "std=")) {
810                                 if (streq(&option[4], "c99")) {
811                                         c_mode = _C89|_C99;
812                                 } else if (streq(&option[4], "c89")) {
813                                         c_mode = _C89;
814                                 } else if (streq(&option[4], "gnu99")) {
815                                         c_mode = _C89|_C99|_GNUC;
816                                 } else if (streq(&option[4], "microsoft")) {
817                                         c_mode = _C89|_C99|_MS;
818                                 } else
819                                         fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
820                         } else if (streq(option, "version")) {
821                                 print_cparser_version();
822                         } else if (option[0] == '-') {
823                                 /* double dash option */
824                                 ++option;
825                                 if (streq(option, "gcc")) {
826                                         c_mode |= _GNUC;
827                                 } else if (streq(option, "no-gcc")) {
828                                         c_mode &= ~_GNUC;
829                                 } else if (streq(option, "ms")) {
830                                         c_mode |= _MS;
831                                 } else if (streq(option, "no-ms")) {
832                                         c_mode &= ~_MS;
833                                 } else if (streq(option, "signed-chars")) {
834                                         char_is_signed = true;
835                                 } else if (streq(option, "unsigned-chars")) {
836                                         char_is_signed = false;
837                                 } else if (streq(option, "strict")) {
838                                         strict_mode = true;
839                                 } else if (streq(option, "lextest")) {
840                                         mode = LexTest;
841                                 } else if (streq(option, "benchmark")) {
842                                         mode = BenchmarkParser;
843                                 } else if (streq(option, "print-ast")) {
844                                         mode = PrintAst;
845                                 } else if (streq(option, "print-implicit-cast")) {
846                                         print_implicit_casts = true;
847                                 } else if (streq(option, "print-parenthesis")) {
848                                         print_parenthesis = true;
849                                 } else if (streq(option, "print-fluffy")) {
850                                         mode = PrintFluffy;
851                                 } else if (streq(option, "print-caml")) {
852                                         mode = PrintCaml;
853                                 } else if (streq(option, "version")) {
854                                         print_cparser_version();
855                                         exit(EXIT_SUCCESS);
856                                 } else if (streq(option, "dump-function")) {
857                                         ++i;
858                                         if(i >= argc) {
859                                                 fprintf(stderr, "error: "
860                                                         "expected argument after '--dump-function'\n");
861                                                 argument_errors = true;
862                                                 break;
863                                         }
864                                         dumpfunction = argv[i];
865                                         mode         = CompileDump;
866                                 } else {
867                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
868                                         argument_errors = true;
869                                 }
870                         } else {
871                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
872                                 argument_errors = true;
873                         }
874                 } else {
875                         filetype_t  type     = forced_filetype;
876                         const char *filename = arg;
877                         if (type == FILETYPE_AUTODETECT) {
878                                 size_t const len = strlen(arg);
879                                 if (len < 2 && arg[0] == '-') {
880                                         /* - implicitly means C source file */
881                                         type     = FILETYPE_C;
882                                         filename = NULL;
883                                 } else if (len > 2 && arg[len - 2] == '.') {
884                                         switch (arg[len - 1]) {
885                                         case 'c': type = FILETYPE_C;                      break;
886                                         case 'h': type = FILETYPE_C;                      break;
887                                         case 's': type = FILETYPE_PREPROCESSED_ASSEMBLER; break;
888                                         case 'S': type = FILETYPE_ASSEMBLER;              break;
889
890                                         case 'a':
891                                         case 'o': type = FILETYPE_OBJECT;                 break;
892                                         }
893                                 } else if (len > 3 && arg[len - 3] == '.') {
894                                         if (streq(arg + len - 2, "so")) {
895                                                 type = FILETYPE_OBJECT;
896                                         }
897                                 }
898
899                                 if (type == FILETYPE_AUTODETECT) {
900                                         fprintf(stderr, "'%s': file format not recognized\n", arg);
901                                         continue;
902                                 }
903                         }
904
905                         file_list_entry_t *entry
906                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
907                         memset(entry, 0, sizeof(entry[0]));
908                         entry->name = arg;
909                         entry->type = type;
910
911                         if (last_file != NULL) {
912                                 last_file->next = entry;
913                         } else {
914                                 files = entry;
915                         }
916                         last_file = entry;
917                 }
918         }
919
920         if (files == NULL) {
921                 fprintf(stderr, "error: no input files specified\n");
922                 argument_errors = true;
923         }
924
925         if (help_displayed) {
926                 return !argument_errors;
927         }
928         if (argument_errors) {
929                 usage(argv[0]);
930                 return 1;
931         }
932
933         /* we do the lowering in ast2firm */
934         firm_opt.lower_bitfields = FALSE;
935
936         gen_firm_init();
937         init_symbol_table();
938         init_tokens();
939         init_types();
940         init_typehash();
941         init_basic_types();
942         init_lexer();
943         init_ast();
944         init_parser();
945         init_ast2firm();
946
947         if (construct_dep_target) {
948                 if (outname != 0 && strlen(outname) >= 2) {
949                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
950                 } else {
951                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
952                 }
953         } else {
954                 dep_target[0] = '\0';
955         }
956
957         char outnamebuf[4096];
958         if (outname == NULL) {
959                 const char *filename = files->name;
960
961                 switch(mode) {
962                 case BenchmarkParser:
963                 case PrintAst:
964                 case PrintFluffy:
965                 case PrintCaml:
966                 case LexTest:
967                 case PreprocessOnly:
968                         outname = "-";
969                         break;
970                 case ParseOnly:
971                         break;
972                 case Compile:
973                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
974                         outname = outnamebuf;
975                         break;
976                 case CompileAssemble:
977                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
978                         outname = outnamebuf;
979                         break;
980                 case CompileDump:
981                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
982                                         ".vcg");
983                         outname = outnamebuf;
984                         break;
985                 case CompileAssembleLink:
986 #ifdef _WIN32
987                         outname = "a.exe";
988 #else
989                         outname = "a.out";
990 #endif
991                         break;
992                 }
993         }
994
995         assert(outname != NULL);
996
997         FILE *out;
998         if (streq(outname, "-")) {
999                 out = stdout;
1000         } else {
1001                 out = fopen(outname, "w");
1002                 if(out == NULL) {
1003                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
1004                                         strerror(errno));
1005                         return 1;
1006                 }
1007         }
1008
1009         file_list_entry_t *file;
1010         for (file = files; file != NULL; file = file->next) {
1011                 char        asm_tempfile[1024];
1012                 const char *filename = file->name;
1013                 filetype_t  filetype = file->type;
1014
1015                 if (file->type == FILETYPE_OBJECT)
1016                         continue;
1017
1018                 FILE *in = NULL;
1019                 if (mode == LexTest) {
1020                         if (in == NULL)
1021                                 in = open_file(filename);
1022                         lextest(in, filename);
1023                         fclose(in);
1024                         exit(EXIT_SUCCESS);
1025                 }
1026
1027                 FILE *preprocessed_in = NULL;
1028                 if (filetype == FILETYPE_C || filetype == FILETYPE_ASSEMBLER) {
1029                         /* no support for input on FILE* yet */
1030                         if (in != NULL)
1031                                 panic("internal compiler error: in for preprocessor != NULL");
1032
1033                         preprocessed_in = preprocess(filename);
1034                         if (mode == PreprocessOnly) {
1035                                 copy_file(out, preprocessed_in);
1036                                 int result = pclose(preprocessed_in);
1037                                 fclose(out);
1038                                 return result;
1039                         }
1040
1041                         if (filetype == FILETYPE_C) {
1042                                 filetype = FILETYPE_PREPROCESSED_C;
1043                         } else if (filetype == FILETYPE_ASSEMBLER) {
1044                                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1045                         } else {
1046                                 panic("internal compiler error: unknown filetype at preproc");
1047                         }
1048
1049                         in = preprocessed_in;
1050                 }
1051
1052                 FILE *asm_out;
1053                 if(mode == Compile) {
1054                         asm_out = out;
1055                 } else {
1056                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile),
1057                                                  "ccs");
1058                 }
1059
1060                 if (in == NULL)
1061                         in = open_file(filename);
1062
1063                 /* preprocess and compile */
1064                 if (filetype == FILETYPE_PREPROCESSED_C) {
1065                         translation_unit_t *const unit = do_parsing(in, filename);
1066                         if (in == preprocessed_in) {
1067                                 int pp_result = pclose(preprocessed_in);
1068                                 if (pp_result != EXIT_SUCCESS) {
1069                                         exit(EXIT_FAILURE);
1070                                 }
1071                         }
1072
1073                         /* prints the AST even if errors occurred */
1074                         if (mode == PrintAst) {
1075                                 type_set_output(out);
1076                                 ast_set_output(out);
1077                                 print_ast(unit);
1078                         }
1079
1080                         if(error_count > 0) {
1081                                 /* parsing failed because of errors */
1082                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1083                                         warning_count);
1084                                 result = EXIT_FAILURE;
1085                                 continue;
1086                         } else if(warning_count > 0) {
1087                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1088                         }
1089
1090                         if(mode == BenchmarkParser) {
1091                                 return result;
1092                         } else if(mode == PrintFluffy) {
1093                                 write_fluffy_decls(out, unit);
1094                                 continue;
1095                         } else if (mode == PrintCaml) {
1096                                 write_caml_decls(out, unit);
1097                                 continue;
1098                         }
1099
1100                         translation_unit_to_firm(unit);
1101
1102                         if (mode == ParseOnly) {
1103                                 continue;
1104                         }
1105
1106                         if (mode == CompileDump) {
1107                                 /* find irg */
1108                                 ident    *id     = new_id_from_str(dumpfunction);
1109                                 ir_graph *irg    = NULL;
1110                                 int       n_irgs = get_irp_n_irgs();
1111                                 for(int i = 0; i < n_irgs; ++i) {
1112                                         ir_graph *tirg   = get_irp_irg(i);
1113                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1114                                         if(irg_id == id) {
1115                                                 irg = tirg;
1116                                                 break;
1117                                         }
1118                                 }
1119
1120                                 if(irg == NULL) {
1121                                         fprintf(stderr, "No graph for function '%s' found\n",
1122                                                 dumpfunction);
1123                                         exit(1);
1124                                 }
1125
1126                                 dump_ir_block_graph_file(irg, out);
1127                                 fclose(out);
1128                                 exit(0);
1129                         }
1130
1131                         gen_firm_finish(asm_out, filename, /*c_mode=*/1,
1132                                         /*firm_const_exists=*/0);
1133                         if (asm_out != out) {
1134                                 fclose(asm_out);
1135                         }
1136
1137                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1138                         copy_file(asm_out, in);
1139                         if (in == preprocessed_in) {
1140                                 int pp_result = pclose(preprocessed_in);
1141                                 if (pp_result != EXIT_SUCCESS) {
1142                                         return pp_result;
1143                                 }
1144                         }
1145                         if(asm_out != out) {
1146                                 fclose(asm_out);
1147                         }
1148                 }
1149
1150                 if (mode == Compile)
1151                         continue;
1152
1153                 /* if we're here then we have preprocessed assembly */
1154                 filename = asm_tempfile;
1155                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1156
1157                 /* assemble */
1158                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1159                         char        temp[1024];
1160                         const char *filename_o;
1161                         if(mode == CompileAssemble) {
1162                                 fclose(out);
1163                                 filename_o = outname;
1164                         } else {
1165                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
1166                                 fclose(tempf);
1167                                 filename_o = temp;
1168                         }
1169
1170                         assemble(filename_o, filename);
1171
1172                         size_t len = strlen(filename_o) + 1;
1173                         filename = obstack_copy(&file_obst, filename_o, len);
1174                         filetype = FILETYPE_OBJECT;
1175                 }
1176
1177                 /* ok we're done here, process next file */
1178                 file->name = filename;
1179                 file->type = filetype;
1180         }
1181
1182         if (result != EXIT_SUCCESS)
1183                 return result;
1184
1185         /* link program file */
1186         if(mode == CompileAssembleLink) {
1187                 obstack_1grow(&ldflags_obst, '\0');
1188                 const char *flags = obstack_finish(&ldflags_obst);
1189
1190                 /* construct commandline */
1191                 obstack_printf(&file_obst, "%s", LINKER);
1192                 for (file_list_entry_t *entry = files; entry != NULL;
1193                                 entry = entry->next) {
1194                         if (entry->type != FILETYPE_OBJECT)
1195                                 continue;
1196
1197                         add_flag(&file_obst, "%s", entry->name);
1198                 }
1199
1200                 add_flag(&file_obst, "-o");
1201                 add_flag(&file_obst, outname);
1202                 obstack_printf(&file_obst, "%s", flags);
1203                 obstack_1grow(&file_obst, '\0');
1204
1205                 char *commandline = obstack_finish(&file_obst);
1206
1207                 if(verbose) {
1208                         puts(commandline);
1209                 }
1210                 int err = system(commandline);
1211                 if(err != EXIT_SUCCESS) {
1212                         fprintf(stderr, "linker reported an error\n");
1213                         exit(1);
1214                 }
1215         }
1216
1217         obstack_free(&cppflags_obst, NULL);
1218         obstack_free(&ldflags_obst, NULL);
1219         obstack_free(&file_obst, NULL);
1220
1221         exit_ast2firm();
1222         exit_parser();
1223         exit_ast();
1224         exit_lexer();
1225         exit_typehash();
1226         exit_types();
1227         exit_tokens();
1228         exit_symbol_table();
1229         return 0;
1230 }