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