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