- add -f[no-]short-wchar
[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 FILE *open_file(const char *filename)
442 {
443         if (strcmp(filename, "-") == 0) {
444                 return stdin;
445         }
446
447         FILE *in = fopen(filename, "r");
448         if(in == NULL) {
449                 fprintf(stderr, "Couldn't open '%s': %s\n", filename,
450                                 strerror(errno));
451                 exit(1);
452         }
453
454         return in;
455 }
456
457 static filetype_t get_filetype_from_string(const char *string)
458 {
459         if (strcmp(string, "c") == 0 || strcmp(string, "c-header") == 0)
460                 return FILETYPE_C;
461         if (strcmp(string, "assembler") == 0)
462                 return FILETYPE_PREPROCESSED_ASSEMBLER;
463         if (strcmp(string, "assembler-with-cpp") == 0)
464                 return FILETYPE_ASSEMBLER;
465         if (strcmp(string, "none") == 0)
466                 return FILETYPE_AUTODETECT;
467
468         return FILETYPE_UNKNOWN;
469 }
470
471 int main(int argc, char **argv)
472 {
473         initialize_firm();
474
475         const char        *outname      = NULL;
476         const char        *dumpfunction = NULL;
477         compile_mode_t     mode         = CompileAssembleLink;
478         int                opt_level    = 1;
479         int                result       = EXIT_SUCCESS;
480         char               cpu_arch[16] = "ia32";
481         file_list_entry_t *files        = NULL;
482         file_list_entry_t *last_file    = NULL;
483         struct obstack     file_obst;
484
485         obstack_init(&cppflags_obst);
486         obstack_init(&ldflags_obst);
487         obstack_init(&file_obst);
488
489 #define GET_ARG_AFTER(def, args)                                             \
490         def = &arg[sizeof(args)-1];                                              \
491         if(def[0] == '\0') {                                                     \
492                 ++i;                                                                 \
493                 if(i >= argc) {                                                      \
494                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
495                         argument_errors = true;                                          \
496                         break;                                                           \
497                 }                                                                    \
498                 def = argv[i];                                                       \
499                 if(def[0] == '-' && def[1] != '\0') {                                \
500                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
501                         argument_errors = true;                                          \
502                         continue;                                                        \
503                 }                                                                    \
504         }
505
506 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
507
508         /* early options parsing (find out optimisation level) */
509         for(int i = 1; i < argc; ++i) {
510                 const char *arg = argv[i];
511                 if(arg[0] != '-')
512                         continue;
513
514                 const char *option = &arg[1];
515                 if(option[0] == 'O') {
516                         sscanf(&option[1], "%d", &opt_level);
517                 }
518         }
519
520         /* apply optimisation level */
521         switch(opt_level) {
522         case 0:
523                 set_option("no-opt");
524                 break;
525         case 1:
526                 set_option("no-inline");
527                 break;
528         default:
529         case 4:
530                 set_option("strict-aliasing");
531                 /* fallthrough */
532         case 3:
533                 set_option("cond-eval");
534                 set_option("if-conv");
535                 use_builtins = true;
536                 /* fallthrough */
537         case 2:
538                 set_option("inline");
539                 set_option("deconv");
540                 set_be_option("omitfp");
541                 break;
542         }
543
544         /* parse rest of options */
545         filetype_t  forced_filetype = FILETYPE_AUTODETECT;
546         bool        help_displayed  = false;
547         bool        argument_errors = false;
548         for(int i = 1; i < argc; ++i) {
549                 const char *arg = argv[i];
550                 if(arg[0] == '-' && arg[1] != 0) {
551                         /* an option */
552                         const char *option = &arg[1];
553                         if(option[0] == 'o') {
554                                 GET_ARG_AFTER(outname, "-o");
555                         } else if(option[0] == 'g') {
556                                 set_be_option("debuginfo=stabs");
557                                 set_be_option("omitfp=no");
558                                 set_be_option("ia32-nooptcc=yes");
559                         } else if(SINGLE_OPTION('c')) {
560                                 mode = CompileAssemble;
561                         } else if(SINGLE_OPTION('E')) {
562                                 mode = PreprocessOnly;
563                         } else if(SINGLE_OPTION('S')) {
564                                 mode = Compile;
565                         } else if(option[0] == 'O') {
566                                 continue;
567                         } else if(option[0] == 'I') {
568                                 const char *opt;
569                                 GET_ARG_AFTER(opt, "-I");
570                                 add_flag(&cppflags_obst, "-I%s", opt);
571                         } else if(option[0] == 'D') {
572                                 const char *opt;
573                                 GET_ARG_AFTER(opt, "-D");
574                                 add_flag(&cppflags_obst, "-D%s", opt);
575                         } else if(option[0] == 'U') {
576                                 const char *opt;
577                                 GET_ARG_AFTER(opt, "-U");
578                                 add_flag(&cppflags_obst, "-U%s", opt);
579                         } else if(option[0] == 'l') {
580                                 const char *opt;
581                                 GET_ARG_AFTER(opt, "-l");
582                                 add_flag(&ldflags_obst, "-l%s", opt);
583                         } else if(option[0] == 'L') {
584                                 const char *opt;
585                                 GET_ARG_AFTER(opt, "-L");
586                                 add_flag(&ldflags_obst, "-L%s", opt);
587                         } else if(SINGLE_OPTION('v')) {
588                                 verbose = 1;
589                         } else if(SINGLE_OPTION('w')) {
590                                 inhibit_all_warnings = true;
591                         } else if(option[0] == 'x') {
592                                 const char *opt;
593                                 GET_ARG_AFTER(opt, "-x");
594                                 forced_filetype = get_filetype_from_string(opt);
595                                 if (forced_filetype == FILETYPE_UNKNOWN) {
596                                         fprintf(stderr, "Unknown language '%s'\n", opt);
597                                         argument_errors = true;
598                                 }
599                         } else if(strcmp(option, "M") == 0) {
600                                 mode = PreprocessOnly;
601                                 add_flag(&cppflags_obst, "-M");
602                         } else if (strcmp(option, "MMD") == 0 ||
603                                    strcmp(option, "MD")  == 0 ||
604                                    strcmp(option, "MM")  == 0 ||
605                                    strcmp(option, "MP")  == 0) {
606                                 add_flag(&cppflags_obst, "-%s", option);
607                         } else if(strcmp(option, "MT") == 0
608                                         || strcmp(option, "MQ") == 0
609                                         || strcmp(option, "MF") == 0) {
610                                 const char *opt;
611                                 GET_ARG_AFTER(opt, "-MT");
612                                 add_flag(&cppflags_obst, "-%s", option);
613                                 add_flag(&cppflags_obst, "%s", opt);
614                         } else if(strcmp(option, "pipe") == 0) {
615                                 /* here for gcc compatibility */
616                         } else if (option[0] == 'f') {
617                                 bool truth_value = true;
618                                 const char *opt;
619                                 GET_ARG_AFTER(opt, "-f");
620                                 if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
621                                         truth_value = false;
622                                         opt += 3;
623                                 }
624
625                                 if (strcmp(opt, "dollars-in-identifiers") == 0) {
626                                         allow_dollar_in_symbol = truth_value;
627                                 } else if (strcmp(opt, "short-wchar") == 0) {
628                                         opt_short_wchar_t = truth_value;
629                                 } else if (strcmp(opt, "syntax-only") == 0) {
630                                         mode = ParseOnly;
631                                 } else if(strcmp(opt, "omit-frame-pointer") == 0) {
632                                         set_be_option(truth_value ? "omitfp" : "omitfp=no");
633                                 } else if(strcmp(opt, "strength-reduce") == 0) {
634                                         firm_option("strength-red");
635                                 } else if (strcmp(opt, "fast-math") == 0
636                                                 || strcmp(opt, "jump-tables") == 0
637                                                 || strcmp(opt, "unroll-loops") == 0
638                                                 || strcmp(opt, "expensive-optimizations") == 0
639                                                 || strcmp(opt, "no-common") == 0
640                                                 || strcmp(opt, "PIC") == 0
641                                                 || strncmp(opt, "align-loops=", sizeof("align-loops=")-1) == 0
642                                                 || strncmp(opt, "align-jumps=", sizeof("align-jumps=")-1) == 0
643                                                 || strncmp(opt, "align-functions=", sizeof("align-functions=")-1) == 0) {
644                                                         fprintf(stderr, "ignoring gcc option '-f %s'\n", truth_value ? opt : opt - 3);
645                                 } else {
646                                         if (! truth_value)
647                                                 opt -= 3;
648                                         int res = firm_option(opt);
649                                         if (res == 0) {
650                                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
651                                                         opt);
652                                                 argument_errors = true;
653                                                 continue;
654                                         } else if (res == -1) {
655                                                 help_displayed = true;
656                                         }
657                                 }
658                         } else if (option[0] == 'b') {
659                                 const char *opt;
660                                 GET_ARG_AFTER(opt, "-b");
661                                 int res = firm_be_option(opt);
662                                 if (res == 0) {
663                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
664                                                 opt);
665                                         argument_errors = true;
666                                 } else if (res == -1) {
667                                         help_displayed = true;
668                                 } else {
669                                         if (strncmp(opt, "isa=", 4) == 0)
670                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
671                                 }
672                         } else if (option[0] == 'W') {
673                                 if (strncmp(option + 1, "l,", 2) == 0)  // a gcc-style linker option
674                                 {
675                                         const char *opt;
676                                         GET_ARG_AFTER(opt, "-Wl,");
677                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
678                                 }
679                                 else set_warning_opt(&option[1]);
680                         } else if(option[0] == 'm') {
681                                 /* -m options */
682                                 const char *opt;
683                                 char arch_opt[64];
684
685                                 GET_ARG_AFTER(opt, "-m");
686                                 if (strncmp(opt, "arch=", 5) == 0) {
687                                         GET_ARG_AFTER(opt, "-march=");
688                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
689                                         int res = firm_be_option(arch_opt);
690                                         if (res == 0)
691                                                 argument_errors = true;
692                                         else {
693                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
694                                                 int res = firm_be_option(arch_opt);
695                                                 if (res == 0)
696                                                         argument_errors = true;
697                                         }
698                                 } else if(strncmp(opt, "tune=", 5) == 0) {
699                                         GET_ARG_AFTER(opt, "-mtune=");
700                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
701                                         int res = firm_be_option(arch_opt);
702                                         if (res == 0)
703                                                 argument_errors = true;
704                                 } else if(strncmp(opt, "cpu=", 4) == 0) {
705                                         GET_ARG_AFTER(opt, "-mcpu=");
706                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
707                                         int res = firm_be_option(arch_opt);
708                                         if (res == 0)
709                                                 argument_errors = true;
710                                 } else if(strncmp(opt, "fpmath=", 7) == 0) {
711                                         GET_ARG_AFTER(opt, "-mfpmath=");
712                                         if(strcmp(opt, "387") == 0)
713                                                 opt = "x87";
714                                         else if(strcmp(opt, "sse") == 0)
715                                                 opt = "sse2";
716                                         else {
717                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
718                                                 argument_errors = true;
719                                         }
720                                         if(!argument_errors) {
721                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
722                                                 int res = firm_be_option(arch_opt);
723                                                 if (res == 0)
724                                                         argument_errors = true;
725                                         }
726                                 } else if(strncmp(opt, "preferred-stack-boundary=", 25) == 0) {
727                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
728                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
729                                         int res = firm_be_option(arch_opt);
730                                         if (res == 0)
731                                                 argument_errors = true;
732                                 } else if(strcmp(opt, "omit-leaf-frame-pointer") == 0) {
733                                         set_be_option("omitleaffp=1");
734                                 } else if(strcmp(opt, "no-omit-leaf-frame-pointer") == 0) {
735                                         set_be_option("omitleaffp=0");
736                                 } else {
737                                         char *endptr;
738                                         long int value = strtol(opt, &endptr, 10);
739                                         if (*endptr != '\0') {
740                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
741                                                 argument_errors = true;
742                                         }
743                                         if (value != 16 && value != 32 && value != 64) {
744                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
745                                                 argument_errors = true;
746                                         } else {
747                                                 machine_size = (unsigned int)value;
748                                         }
749                                 }
750                         } else if(strcmp(option, "pg") == 0) {
751                                 set_be_option("gprof");
752                                 add_flag(&ldflags_obst, "-pg");
753                         } else if(strcmp(option, "pedantic") == 0
754                                         || strcmp(option, "ansi") == 0) {
755                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
756                         } else if(strcmp(option, "shared") == 0) {
757                                 add_flag(&ldflags_obst, "-shared");
758                         } else if(strncmp(option, "std=", 4) == 0) {
759                                 if(strcmp(&option[4], "c99") == 0) {
760                                         c_mode = _C89|_C99;
761                                 } else if(strcmp(&option[4], "c89") == 0) {
762                                         c_mode = _C89;
763                                 } else if(strcmp(&option[4], "gnu99") == 0) {
764                                         c_mode = _C89|_C99|_GNUC;
765                                 } else if(strcmp(&option[4], "microsoft") == 0) {
766                                         c_mode = _C89|_C99|_MS;
767                                 } else
768                                         fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
769                         } else if(strcmp(option, "version") == 0) {
770                                 print_cparser_version();
771                         } else if (option[0] == '-') {
772                                 /* double dash option */
773                                 ++option;
774                                 if(strcmp(option, "gcc") == 0) {
775                                         c_mode |= _GNUC;
776                                 } else if(strcmp(option, "no-gcc") == 0) {
777                                         c_mode &= ~_GNUC;
778                                 } else if(strcmp(option, "ms") == 0) {
779                                         c_mode |= _MS;
780                                 } else if(strcmp(option, "no-ms") == 0) {
781                                         c_mode &= ~_MS;
782                                 } else if(strcmp(option, "signed-chars") == 0) {
783                                         char_is_signed = true;
784                                 } else if(strcmp(option, "unsigned-chars") == 0) {
785                                         char_is_signed = false;
786                                 } else if(strcmp(option, "strict") == 0) {
787                                         strict_mode = true;
788                                 } else if(strcmp(option, "lextest") == 0) {
789                                         mode = LexTest;
790                                 } else if(strcmp(option, "benchmark") == 0) {
791                                         mode = BenchmarkParser;
792                                 } else if(strcmp(option, "print-ast") == 0) {
793                                         mode = PrintAst;
794                                 } else if(strcmp(option, "print-implicit-cast") == 0) {
795                                         print_implicit_casts = true;
796                                 } else if(strcmp(option, "print-parenthesis") == 0) {
797                                         print_parenthesis = true;
798                                 } else if(strcmp(option, "print-fluffy") == 0) {
799                                         mode = PrintFluffy;
800                                 } else if(strcmp(option, "print-caml") == 0) {
801                                         mode = PrintCaml;
802                                 } else if(strcmp(option, "version") == 0) {
803                                         print_cparser_version();
804                                         exit(EXIT_SUCCESS);
805                                 } else if(strcmp(option, "dump-function") == 0) {
806                                         ++i;
807                                         if(i >= argc) {
808                                                 fprintf(stderr, "error: "
809                                                         "expected argument after '--dump-function'\n");
810                                                 argument_errors = true;
811                                                 break;
812                                         }
813                                         dumpfunction = argv[i];
814                                         mode         = CompileDump;
815                                 } else {
816                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
817                                         argument_errors = true;
818                                 }
819                         } else {
820                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
821                                 argument_errors = true;
822                         }
823                 } else {
824                         filetype_t  type     = forced_filetype;
825                         const char *filename = arg;
826                         if (type == FILETYPE_AUTODETECT) {
827                                 size_t      len      = strlen(arg);
828                                 if (len < 2 && arg[0] == '-') {
829                                         /* - implicitly means C source file */
830                                         type     = FILETYPE_C;
831                                         filename = NULL;
832                                 } else if (len > 2 && arg[len-2] == '.') {
833                                         switch(arg[len-1]) {
834                                         case 'c': type = FILETYPE_C; break;
835                                         case 'h': type = FILETYPE_C; break;
836                                         case 's': type = FILETYPE_PREPROCESSED_ASSEMBLER; break;
837                                         case 'S': type = FILETYPE_ASSEMBLER; break;
838
839                                         case 'a':
840                                         case 'o': type = FILETYPE_OBJECT; break;
841                                         }
842                                 } else if (len > 3 && arg[len-3] == '.') {
843                                         if(strcmp(arg + len - 2, "so") == 0) {
844                                                 type = FILETYPE_OBJECT;
845                                         }
846                                 }
847
848                                 if (type == FILETYPE_AUTODETECT) {
849                                         fprintf(stderr, "'%s': file format not recognized\n", arg);
850                                         continue;
851                                 }
852                         }
853
854                         file_list_entry_t *entry
855                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
856                         memset(entry, 0, sizeof(entry[0]));
857                         entry->name = arg;
858                         entry->type = type;
859
860                         if (last_file != NULL) {
861                                 last_file->next = entry;
862                         } else {
863                                 files = entry;
864                         }
865                         last_file = entry;
866                 }
867         }
868
869         if (files == NULL) {
870                 fprintf(stderr, "error: no input files specified\n");
871                 argument_errors = true;
872         }
873
874         if (help_displayed) {
875                 return !argument_errors;
876         }
877         if (argument_errors) {
878                 usage(argv[0]);
879                 return 1;
880         }
881
882         /* we do the lowering in ast2firm */
883         firm_opt.lower_bitfields = FALSE;
884
885         gen_firm_init();
886         init_symbol_table();
887         init_tokens();
888         init_types();
889         init_typehash();
890         init_basic_types();
891         init_lexer();
892         init_ast();
893         init_parser();
894         init_ast2firm();
895
896         char outnamebuf[4096];
897         if (outname == NULL) {
898                 const char *filename = files->name;
899
900                 switch(mode) {
901                 case BenchmarkParser:
902                 case PrintAst:
903                 case PrintFluffy:
904                 case PrintCaml:
905                 case LexTest:
906                 case PreprocessOnly:
907                         outname = "-";
908                         break;
909                 case ParseOnly:
910                         break;
911                 case Compile:
912                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
913                         outname = outnamebuf;
914                         break;
915                 case CompileAssemble:
916                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
917                         outname = outnamebuf;
918                         break;
919                 case CompileDump:
920                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
921                                         ".vcg");
922                         outname = outnamebuf;
923                         break;
924                 case CompileAssembleLink:
925 #ifdef _WIN32
926                         outname = "a.exe";
927 #else
928                         outname = "a.out";
929 #endif
930                         break;
931                 }
932         }
933
934         assert(outname != NULL);
935
936         FILE *out;
937         if(strcmp(outname, "-") == 0) {
938                 out = stdout;
939         } else {
940                 out = fopen(outname, "w");
941                 if(out == NULL) {
942                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
943                                         strerror(errno));
944                         return 1;
945                 }
946         }
947
948         file_list_entry_t *file;
949         for (file = files; file != NULL; file = file->next) {
950                 char        asm_tempfile[1024];
951                 const char *filename = file->name;
952                 filetype_t  filetype = file->type;
953
954                 if (file->type == FILETYPE_OBJECT)
955                         continue;
956
957                 FILE *in = NULL;
958                 if (mode == LexTest) {
959                         if (in == NULL)
960                                 in = open_file(filename);
961                         lextest(in, filename);
962                         fclose(in);
963                         exit(EXIT_SUCCESS);
964                 }
965
966                 FILE *preprocessed_in = NULL;
967                 if (filetype == FILETYPE_C || filetype == FILETYPE_ASSEMBLER) {
968                         /* no support for input on FILE* yet */
969                         if (in != NULL)
970                                 panic("internal compiler error: in for preprocessor != NULL");
971
972                         preprocessed_in = preprocess(filename);
973                         if (mode == PreprocessOnly) {
974                                 copy_file(out, preprocessed_in);
975                                 int result = pclose(preprocessed_in);
976                                 fclose(out);
977                                 return result;
978                         }
979
980                         if (filetype == FILETYPE_C) {
981                                 filetype = FILETYPE_PREPROCESSED_C;
982                         } else if (filetype == FILETYPE_ASSEMBLER) {
983                                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
984                         } else {
985                                 panic("internal compiler error: unknown filetype at preproc");
986                         }
987
988                         in = preprocessed_in;
989                 }
990
991                 FILE *asm_out;
992                 if(mode == Compile) {
993                         asm_out = out;
994                 } else {
995                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile),
996                                                  "ccs");
997                 }
998
999                 if (in == NULL)
1000                         in = open_file(filename);
1001
1002                 /* preprocess and compile */
1003                 if (filetype == FILETYPE_PREPROCESSED_C) {
1004                         translation_unit_t *const unit = do_parsing(in, filename);
1005                         if (in == preprocessed_in) {
1006                                 int pp_result = pclose(preprocessed_in);
1007                                 if (pp_result != EXIT_SUCCESS) {
1008                                         exit(EXIT_FAILURE);
1009                                 }
1010                         }
1011
1012                         /* prints the AST even if errors occurred */
1013                         if (mode == PrintAst) {
1014                                 type_set_output(out);
1015                                 ast_set_output(out);
1016                                 print_ast(unit);
1017                         }
1018
1019                         if(error_count > 0) {
1020                                 /* parsing failed because of errors */
1021                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1022                                         warning_count);
1023                                 result = EXIT_FAILURE;
1024                                 continue;
1025                         } else if(warning_count > 0) {
1026                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1027                         }
1028
1029                         if(mode == BenchmarkParser) {
1030                                 return result;
1031                         } else if(mode == PrintFluffy) {
1032                                 write_fluffy_decls(out, unit);
1033                                 continue;
1034                         } else if (mode == PrintCaml) {
1035                                 write_caml_decls(out, unit);
1036                                 continue;
1037                         }
1038
1039                         translation_unit_to_firm(unit);
1040
1041                         if (mode == ParseOnly) {
1042                                 continue;
1043                         }
1044
1045                         if (mode == CompileDump) {
1046                                 /* find irg */
1047                                 ident    *id     = new_id_from_str(dumpfunction);
1048                                 ir_graph *irg    = NULL;
1049                                 int       n_irgs = get_irp_n_irgs();
1050                                 for(int i = 0; i < n_irgs; ++i) {
1051                                         ir_graph *tirg   = get_irp_irg(i);
1052                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1053                                         if(irg_id == id) {
1054                                                 irg = tirg;
1055                                                 break;
1056                                         }
1057                                 }
1058
1059                                 if(irg == NULL) {
1060                                         fprintf(stderr, "No graph for function '%s' found\n",
1061                                                 dumpfunction);
1062                                         exit(1);
1063                                 }
1064
1065                                 dump_ir_block_graph_file(irg, out);
1066                                 fclose(out);
1067                                 exit(0);
1068                         }
1069
1070                         gen_firm_finish(asm_out, filename, /*c_mode=*/1,
1071                                         /*firm_const_exists=*/0);
1072                         if (asm_out != out) {
1073                                 fclose(asm_out);
1074                         }
1075
1076                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1077                         copy_file(asm_out, in);
1078                         if (in == preprocessed_in) {
1079                                 int pp_result = pclose(preprocessed_in);
1080                                 if (pp_result != EXIT_SUCCESS) {
1081                                         return pp_result;
1082                                 }
1083                         }
1084                         if(asm_out != out) {
1085                                 fclose(asm_out);
1086                         }
1087                 }
1088
1089                 if (mode == Compile)
1090                         continue;
1091
1092                 /* if we're here then we have preprocessed assembly */
1093                 filename = asm_tempfile;
1094                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1095
1096                 /* assemble */
1097                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1098                         char        temp[1024];
1099                         const char *filename_o;
1100                         if(mode == CompileAssemble) {
1101                                 fclose(out);
1102                                 filename_o = outname;
1103                         } else {
1104                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
1105                                 fclose(tempf);
1106                                 filename_o = temp;
1107                         }
1108
1109                         assemble(filename_o, filename);
1110
1111                         size_t len = strlen(filename_o) + 1;
1112                         filename = obstack_copy(&file_obst, filename_o, len);
1113                         filetype = FILETYPE_OBJECT;
1114                 }
1115
1116                 /* ok we're done here, process next file */
1117                 file->name = filename;
1118                 file->type = filetype;
1119         }
1120
1121         if (result != EXIT_SUCCESS)
1122                 return result;
1123
1124         /* link program file */
1125         if(mode == CompileAssembleLink) {
1126                 obstack_1grow(&ldflags_obst, '\0');
1127                 const char *flags = obstack_finish(&ldflags_obst);
1128
1129                 /* construct commandline */
1130                 obstack_printf(&file_obst, "%s", LINKER);
1131                 for (file_list_entry_t *entry = files; entry != NULL;
1132                                 entry = entry->next) {
1133                         if (entry->type != FILETYPE_OBJECT)
1134                                 continue;
1135
1136                         add_flag(&file_obst, "%s", entry->name);
1137                 }
1138
1139                 add_flag(&file_obst, "-o");
1140                 add_flag(&file_obst, outname);
1141                 obstack_printf(&file_obst, "%s", flags);
1142                 obstack_1grow(&file_obst, '\0');
1143
1144                 char *commandline = obstack_finish(&file_obst);
1145
1146                 if(verbose) {
1147                         puts(commandline);
1148                 }
1149                 int err = system(commandline);
1150                 if(err != EXIT_SUCCESS) {
1151                         fprintf(stderr, "linker reported an error\n");
1152                         exit(1);
1153                 }
1154         }
1155
1156         obstack_free(&cppflags_obst, NULL);
1157         obstack_free(&ldflags_obst, NULL);
1158         obstack_free(&file_obst, NULL);
1159
1160         exit_ast2firm();
1161         exit_parser();
1162         exit_ast();
1163         exit_lexer();
1164         exit_typehash();
1165         exit_types();
1166         exit_tokens();
1167         exit_symbol_table();
1168         return 0;
1169 }