fix
[cparser] / main.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2009 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 #define unlink(filename)         _unlink(filename)
54
55 #else
56 #include <unistd.h>
57 #define HAVE_MKSTEMP
58 #endif
59
60 #include <libfirm/firm.h>
61 #include <libfirm/be.h>
62
63 #include "lexer.h"
64 #include "token_t.h"
65 #include "types.h"
66 #include "type_hash.h"
67 #include "parser.h"
68 #include "type_t.h"
69 #include "ast2firm.h"
70 #include "diagnostic.h"
71 #include "lang_features.h"
72 #include "driver/firm_opt.h"
73 #include "driver/firm_cmdline.h"
74 #include "driver/firm_timing.h"
75 #include "adt/error.h"
76 #include "wrappergen/write_fluffy.h"
77 #include "wrappergen/write_caml.h"
78 #include "wrappergen/write_jna.h"
79 #include "revision.h"
80 #include "warning.h"
81 #include "mangle.h"
82 #include "printer.h"
83
84 #ifndef PREPROCESSOR
85 #ifndef __WIN32__
86 #define PREPROCESSOR "gcc -E -m32 -U__STRICT_ANSI__"
87 #else
88 #define PREPROCESSOR "cpp -m32 -U__STRICT_ANSI__"
89 #endif
90 #endif
91
92 #ifndef LINKER
93 #define LINKER    "gcc -m32"
94 #endif
95
96 #ifndef ASSEMBLER
97 #ifdef __APPLE__
98 #define ASSEMBLER "gcc -c -xassembler"
99 #else
100 #define ASSEMBLER "as --32"
101 #endif
102 #endif
103
104 /** The current c mode/dialect. */
105 unsigned int c_mode = _C89 | _ANSI | _C99 | _GNUC;
106
107 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
108 unsigned int machine_size = 32;
109
110 /** true if the char type is signed. */
111 bool char_is_signed = true;
112
113 /** true for strict language checking. */
114 bool strict_mode = false;
115
116 /** use builtins for some libc functions */
117 bool use_builtins = false;
118
119 /** we have extern function with const attribute. */
120 bool have_const_functions = false;
121
122 atomic_type_kind_t wchar_atomic_kind = ATOMIC_TYPE_INT;
123
124 /* to switch on printing of implicit casts */
125 extern bool print_implicit_casts;
126
127 /* to switch on printing of parenthesis to indicate operator precedence */
128 extern bool print_parenthesis;
129
130 static int             verbose;
131 static struct obstack  cppflags_obst, ldflags_obst;
132 static char            dep_target[1024];
133 static const char     *outname;
134
135 typedef enum lang_standard_t {
136         STANDARD_DEFAULT, /* gnu99 (for C, GCC does gnu89) or gnu++98 (for C++) */
137         STANDARD_ANSI,    /* c89 (for C) or c++98 (for C++) */
138         STANDARD_C89,     /* ISO C90 (sic) */
139         STANDARD_C90,     /* ISO C90 as modified in amendment 1 */
140         STANDARD_C99,     /* ISO C99 */
141         STANDARD_GNU89,   /* ISO C90 plus GNU extensions (including some C99) */
142         STANDARD_GNU99,   /* ISO C99 plus GNU extensions */
143         STANDARD_CXX98,   /* ISO C++ 1998 plus amendments */
144         STANDARD_GNUXX98  /* ISO C++ 1998 plus amendments and GNU extensions */
145 } lang_standard_t;
146
147 static lang_standard_t standard;
148
149 typedef struct file_list_entry_t file_list_entry_t;
150
151 typedef enum filetype_t {
152         FILETYPE_AUTODETECT,
153         FILETYPE_C,
154         FILETYPE_PREPROCESSED_C,
155         FILETYPE_CXX,
156         FILETYPE_PREPROCESSED_CXX,
157         FILETYPE_ASSEMBLER,
158         FILETYPE_PREPROCESSED_ASSEMBLER,
159         FILETYPE_OBJECT,
160         FILETYPE_IR,
161         FILETYPE_UNKNOWN
162 } filetype_t;
163
164 struct file_list_entry_t {
165         const char  *name; /**< filename or NULL for stdin */
166         filetype_t   type;
167         file_list_entry_t *next;
168 };
169
170 static file_list_entry_t *temp_files;
171
172 #if defined(_DEBUG) || defined(FIRM_DEBUG)
173 /**
174  * Debug printf implementation.
175  *
176  * @param fmt  printf style format parameter
177  */
178 void dbg_printf(const char *fmt, ...)
179 {
180         va_list list;
181
182         if (firm_dump.debug_print) {
183                 va_start(list, fmt);
184                 vprintf(fmt, list);
185                 va_end(list);
186         }  /* if */
187 }
188 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
189
190 static void initialize_firm(void)
191 {
192         firm_early_init();
193
194         dump_consts_local(1);
195         dump_keepalive_edges(1);
196 }
197
198 static void get_output_name(char *buf, size_t buflen, const char *inputname,
199                             const char *newext)
200 {
201         if (inputname == NULL)
202                 inputname = "a";
203
204         char const *const last_slash = strrchr(inputname, '/');
205         char const *const filename   =
206                 last_slash != NULL ? last_slash + 1 : inputname;
207         char const *const last_dot   = strrchr(filename, '.');
208         char const *const name_end   =
209                 last_dot != NULL ? last_dot : strchr(filename, '\0');
210
211         int const len = snprintf(buf, buflen, "%.*s%s",
212                         (int)(name_end - filename), filename, newext);
213 #ifdef _WIN32
214         if (len < 0 || buflen <= (size_t)len)
215 #else
216         if (buflen <= (size_t)len)
217 #endif
218                 panic("filename too long");
219 }
220
221 #include "builtins.h"
222
223 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
224 {
225         start_parsing();
226
227         if (use_builtins) {
228                 lexer_open_buffer(builtins, sizeof(builtins)-1, "<builtin>");
229                 parse();
230         }
231
232         lexer_open_stream(in, input_name);
233         parse();
234
235         translation_unit_t *unit = finish_parsing();
236         return unit;
237 }
238
239 static void lextest(FILE *in, const char *fname)
240 {
241         lexer_open_stream(in, fname);
242
243         do {
244                 lexer_next_preprocessing_token();
245                 print_token(stdout, &lexer_token);
246                 putchar('\n');
247         } while (lexer_token.type != T_EOF);
248 }
249
250 static void add_flag(struct obstack *obst, const char *format, ...)
251 {
252         char buf[65536];
253         va_list ap;
254
255         va_start(ap, format);
256 #ifdef _WIN32
257         int len =
258 #endif
259                 vsnprintf(buf, sizeof(buf), format, ap);
260         va_end(ap);
261
262         obstack_1grow(obst, ' ');
263 #ifdef _WIN32
264         obstack_1grow(obst, '"');
265         obstack_grow(obst, buf, len);
266         obstack_1grow(obst, '"');
267 #else
268         /* escape stuff... */
269         for (char *c = buf; *c != '\0'; ++c) {
270                 switch(*c) {
271                 case ' ':
272                 case '"':
273                 case '$':
274                 case '&':
275                 case '(':
276                 case ')':
277                 case ';':
278                 case '<':
279                 case '>':
280                 case '\'':
281                 case '\\':
282                 case '\n':
283                 case '\r':
284                 case '\t':
285                 case '`':
286                 case '|':
287                         obstack_1grow(obst, '\\');
288                         /* FALLTHROUGH */
289                 default:
290                         obstack_1grow(obst, *c);
291                         break;
292                 }
293         }
294 #endif
295 }
296
297 static const char *type_to_string(type_t *type)
298 {
299         assert(type->kind == TYPE_ATOMIC);
300         return get_atomic_kind_name(type->atomic.akind);
301 }
302
303 static FILE *preprocess(const char *fname, filetype_t filetype)
304 {
305         static const char *common_flags = NULL;
306
307         if (common_flags == NULL) {
308                 obstack_1grow(&cppflags_obst, '\0');
309                 const char *flags = obstack_finish(&cppflags_obst);
310
311                 /* setup default defines */
312                 add_flag(&cppflags_obst, "-U__WCHAR_TYPE__");
313                 add_flag(&cppflags_obst, "-D__WCHAR_TYPE__=%s", type_to_string(type_wchar_t));
314                 add_flag(&cppflags_obst, "-U__SIZE_TYPE__");
315                 add_flag(&cppflags_obst, "-D__SIZE_TYPE__=%s", type_to_string(type_size_t));
316
317                 add_flag(&cppflags_obst, "-U__VERSION__");
318                 add_flag(&cppflags_obst, "-D__VERSION__=\"%s\"", cparser_REVISION);
319
320                 /* TODO hack... */
321                 add_flag(&cppflags_obst, "-D__builtin_abort=abort");
322                 add_flag(&cppflags_obst, "-D__builtin_abs=abs");
323                 add_flag(&cppflags_obst, "-D__builtin_exit=exit");
324                 add_flag(&cppflags_obst, "-D__builtin_malloc=malloc");
325                 add_flag(&cppflags_obst, "-D__builtin_memcmp=memcmp");
326                 add_flag(&cppflags_obst, "-D__builtin_memcpy=memcpy");
327                 add_flag(&cppflags_obst, "-D__builtin_memset=memset");
328                 add_flag(&cppflags_obst, "-D__builtin_strlen=strlen");
329                 add_flag(&cppflags_obst, "-D__builtin_strcmp=strcmp");
330                 add_flag(&cppflags_obst, "-D__builtin_strcpy=strcpy");
331
332                 if (flags[0] != '\0') {
333                         size_t len = strlen(flags);
334                         obstack_1grow(&cppflags_obst, ' ');
335                         obstack_grow(&cppflags_obst, flags, len);
336                 }
337                 obstack_1grow(&cppflags_obst, '\0');
338                 common_flags = obstack_finish(&cppflags_obst);
339         }
340
341         assert(obstack_object_size(&cppflags_obst) == 0);
342
343         const char *preprocessor = getenv("CPARSER_PP");
344         if (preprocessor == NULL)
345                 preprocessor = PREPROCESSOR;
346
347         obstack_printf(&cppflags_obst, "%s ", preprocessor);
348         switch (filetype) {
349         case FILETYPE_C:
350                 add_flag(&cppflags_obst, "-std=c99");
351                 break;
352         case FILETYPE_CXX:
353                 add_flag(&cppflags_obst, "-std=c++98");
354                 break;
355         case FILETYPE_ASSEMBLER:
356                 add_flag(&cppflags_obst, "-x");
357                 add_flag(&cppflags_obst, "assembler-with-cpp");
358                 break;
359         default:
360                 break;
361         }
362         obstack_printf(&cppflags_obst, "%s", common_flags);
363
364         /* handle dependency generation */
365         if (dep_target[0] != '\0') {
366                 add_flag(&cppflags_obst, "-MF");
367                 add_flag(&cppflags_obst, dep_target);
368                 if (outname != NULL) {
369                                 add_flag(&cppflags_obst, "-MQ");
370                                 add_flag(&cppflags_obst, outname);
371                 }
372         }
373         add_flag(&cppflags_obst, fname);
374
375         obstack_1grow(&cppflags_obst, '\0');
376         char *buf = obstack_finish(&cppflags_obst);
377         if (verbose) {
378                 puts(buf);
379         }
380
381         FILE *f = popen(buf, "r");
382         if (f == NULL) {
383                 fprintf(stderr, "invoking preprocessor failed\n");
384                 exit(1);
385         }
386
387         /* we don't really need that anymore */
388         obstack_free(&cppflags_obst, buf);
389
390         return f;
391 }
392
393 static void assemble(const char *out, const char *in)
394 {
395         char buf[65536];
396
397         const char *assembler = getenv("CPARSER_AS");
398         if (assembler == NULL)
399                 assembler = ASSEMBLER;
400
401         snprintf(buf, sizeof(buf), "%s %s -o %s", assembler, in, out);
402         if (verbose) {
403                 puts(buf);
404         }
405
406         int err = system(buf);
407         if (err != 0) {
408                 fprintf(stderr, "assembler reported an error\n");
409                 exit(1);
410         }
411 }
412
413 static void print_file_name(const char *file)
414 {
415         add_flag(&ldflags_obst, "-print-file-name=%s", file);
416
417         obstack_1grow(&ldflags_obst, '\0');
418         const char *flags = obstack_finish(&ldflags_obst);
419
420         /* construct commandline */
421         const char *linker = getenv("CPARSER_LINK");
422         if (linker == NULL)
423                 linker = LINKER;
424         obstack_printf(&ldflags_obst, "%s ", linker);
425         obstack_printf(&ldflags_obst, "%s", flags);
426         obstack_1grow(&ldflags_obst, '\0');
427
428         char *commandline = obstack_finish(&ldflags_obst);
429
430         if (verbose) {
431                 puts(commandline);
432         }
433         int err = system(commandline);
434         if (err != EXIT_SUCCESS) {
435                 fprintf(stderr, "linker reported an error\n");
436                 exit(1);
437         }
438 }
439
440 static const char *try_dir(const char *dir)
441 {
442         if (dir == NULL)
443                 return dir;
444         if (access(dir, R_OK | W_OK | X_OK) == 0)
445                 return dir;
446         return NULL;
447 }
448
449 static const char *get_tempdir(void)
450 {
451         static const char *tmpdir = NULL;
452
453         if (tmpdir != NULL)
454                 return tmpdir;
455
456         if (tmpdir == NULL)
457                 tmpdir = try_dir(getenv("TMPDIR"));
458         if (tmpdir == NULL)
459                 tmpdir = try_dir(getenv("TMP"));
460         if (tmpdir == NULL)
461                 tmpdir = try_dir(getenv("TEMP"));
462
463 #ifdef P_tmpdir
464         if (tmpdir == NULL)
465                 tmpdir = try_dir(P_tmpdir);
466 #endif
467
468         if (tmpdir == NULL)
469                 tmpdir = try_dir("/var/tmp");
470         if (tmpdir == NULL)
471                 tmpdir = try_dir("/usr/tmp");
472         if (tmpdir == NULL)
473                 tmpdir = try_dir("/tmp");
474
475         if (tmpdir == NULL)
476                 tmpdir = ".";
477
478         return tmpdir;
479 }
480
481 #ifndef HAVE_MKSTEMP
482 /* cheap and nasty mkstemp replacement */
483 static int mkstemp(char *templ)
484 {
485         mktemp(templ);
486         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
487 }
488 #endif
489
490 /**
491  * an own version of tmpnam, which: writes in a buffer, emits no warnings
492  * during linking (like glibc/gnu ld do for tmpnam)...
493  */
494 static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix)
495 {
496         const char *tempdir = get_tempdir();
497
498         snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix);
499
500         int fd = mkstemp(buffer);
501         if (fd == -1) {
502                 fprintf(stderr, "couldn't create temporary file: %s\n",
503                         strerror(errno));
504                 exit(1);
505         }
506         FILE *out = fdopen(fd, "w");
507         if (out == NULL) {
508                 fprintf(stderr, "couldn't create temporary file FILE*\n");
509                 exit(1);
510         }
511
512         file_list_entry_t *entry = xmalloc(sizeof(*entry));
513         memset(entry, 0, sizeof(*entry));
514
515         size_t  name_len = strlen(buffer) + 1;
516         char   *name     = malloc(name_len);
517         memcpy(name, buffer, name_len);
518         entry->name      = name;
519
520         entry->next = temp_files;
521         temp_files  = entry;
522
523         return out;
524 }
525
526 static void free_temp_files(void)
527 {
528         file_list_entry_t *entry = temp_files;
529         file_list_entry_t *next;
530         for ( ; entry != NULL; entry = next) {
531                 next = entry->next;
532
533                 unlink(entry->name);
534                 free((char*) entry->name);
535                 free(entry);
536         }
537         temp_files = NULL;
538 }
539
540 /**
541  * Do the necessary lowering for compound parameters.
542  */
543 void lower_compound_params(void)
544 {
545         lower_params_t params;
546
547         params.def_ptr_alignment    = 4;
548         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
549         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
550         params.find_pointer_type    = NULL;
551         params.ret_compound_in_regs = NULL;
552         lower_calls_with_compounds(&params);
553 }
554
555 typedef enum compile_mode_t {
556         BenchmarkParser,
557         PreprocessOnly,
558         ParseOnly,
559         Compile,
560         CompileDump,
561         CompileExportIR,
562         CompileAssemble,
563         CompileAssembleLink,
564         LexTest,
565         PrintAst,
566         PrintFluffy,
567         PrintCaml,
568         PrintJna
569 } compile_mode_t;
570
571 static void usage(const char *argv0)
572 {
573         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
574 }
575
576 static void print_cparser_version(void)
577 {
578         printf("cparser (%s) using libFirm (%u.%u",
579                cparser_REVISION, ir_get_version_major(),
580                ir_get_version_minor());
581
582         const char *revision = ir_get_version_revision();
583         if (revision[0] != 0) {
584                 putchar(' ');
585                 fputs(revision, stdout);
586         }
587
588         const char *build = ir_get_version_build();
589         if (build[0] != 0) {
590                 putchar(' ');
591                 fputs(build, stdout);
592         }
593         puts(")");
594         puts("This is free software; see the source for copying conditions.  There is NO\n"
595              "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
596 }
597
598 static void set_be_option(const char *arg)
599 {
600         int res = firm_be_option(arg);
601         (void) res;
602         assert(res);
603 }
604
605 static void set_option(const char *arg)
606 {
607         int res = firm_option(arg);
608         (void) res;
609         assert(res);
610 }
611
612 static void copy_file(FILE *dest, FILE *input)
613 {
614         char buf[16384];
615
616         while (!feof(input) && !ferror(dest)) {
617                 size_t read = fread(buf, 1, sizeof(buf), input);
618                 if (fwrite(buf, 1, read, dest) != read) {
619                         perror("couldn't write output");
620                 }
621         }
622 }
623
624 static inline bool streq(char const* a, char const* b)
625 {
626         return strcmp(a, b) == 0;
627 }
628
629 static inline bool strstart(char const* str, char const* start)
630 {
631         do {
632                 if (*start == '\0')
633                         return true;
634         } while (*str++ == *start++);
635         return false;
636 }
637
638 static FILE *open_file(const char *filename)
639 {
640         if (streq(filename, "-")) {
641                 return stdin;
642         }
643
644         FILE *in = fopen(filename, "r");
645         if (in == NULL) {
646                 fprintf(stderr, "Couldn't open '%s': %s\n", filename,
647                                 strerror(errno));
648                 exit(1);
649         }
650
651         return in;
652 }
653
654 static filetype_t get_filetype_from_string(const char *string)
655 {
656         if (streq(string, "c") || streq(string, "c-header"))
657                 return FILETYPE_C;
658         if (streq(string, "c++") || streq(string, "c++-header"))
659                 return FILETYPE_CXX;
660         if (streq(string, "assembler"))
661                 return FILETYPE_PREPROCESSED_ASSEMBLER;
662         if (streq(string, "assembler-with-cpp"))
663                 return FILETYPE_ASSEMBLER;
664         if (streq(string, "none"))
665                 return FILETYPE_AUTODETECT;
666
667         return FILETYPE_UNKNOWN;
668 }
669
670 static void init_os_support(void)
671 {
672         /* OS option must be set to the backend */
673         switch (firm_opt.os_support) {
674         case OS_SUPPORT_MINGW:
675                 set_be_option("ia32-gasmode=mingw");
676                 wchar_atomic_kind = ATOMIC_TYPE_USHORT;
677                 break;
678         case OS_SUPPORT_LINUX:
679                 set_be_option("ia32-gasmode=elf");
680                 break;
681         case OS_SUPPORT_MACHO:
682                 set_be_option("ia32-gasmode=macho");
683                 set_be_option("ia32-stackalign=4");
684                 set_be_option("pic");
685                 break;
686         }
687 }
688
689 int main(int argc, char **argv)
690 {
691         initialize_firm();
692
693         const char        *dumpfunction         = NULL;
694         const char        *print_file_name_file = NULL;
695         compile_mode_t     mode                 = CompileAssembleLink;
696         int                opt_level            = 1;
697         int                result               = EXIT_SUCCESS;
698         char               cpu_arch[16]         = "ia32";
699         file_list_entry_t *files                = NULL;
700         file_list_entry_t *last_file            = NULL;
701         bool               construct_dep_target = false;
702         bool               do_timing            = false;
703         struct obstack     file_obst;
704
705         atexit(free_temp_files);
706
707         /* hack for now... */
708         if (strstr(argv[0], "pptest") != NULL) {
709                 extern int pptest_main(int argc, char **argv);
710                 return pptest_main(argc, argv);
711         }
712
713         obstack_init(&cppflags_obst);
714         obstack_init(&ldflags_obst);
715         obstack_init(&file_obst);
716
717 #define GET_ARG_AFTER(def, args)                                             \
718         def = &arg[sizeof(args)-1];                                              \
719         if (def[0] == '\0') {                                                     \
720                 ++i;                                                                 \
721                 if (i >= argc) {                                                      \
722                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
723                         argument_errors = true;                                          \
724                         break;                                                           \
725                 }                                                                    \
726                 def = argv[i];                                                       \
727                 if (def[0] == '-' && def[1] != '\0') {                                \
728                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
729                         argument_errors = true;                                          \
730                         continue;                                                        \
731                 }                                                                    \
732         }
733
734 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
735
736         /* early options parsing (find out optimisation level and OS) */
737         for (int i = 1; i < argc; ++i) {
738                 const char *arg = argv[i];
739                 if (arg[0] != '-')
740                         continue;
741
742                 const char *option = &arg[1];
743                 if (option[0] == 'O') {
744                         sscanf(&option[1], "%d", &opt_level);
745                 }
746                 if (strcmp(arg, "-fwin32") == 0) {
747                         firm_opt.os_support = OS_SUPPORT_MINGW;
748                 } else if (strcmp(arg, "-fmac") == 0) {
749                         firm_opt.os_support = OS_SUPPORT_MACHO;
750                 } else if (strcmp(arg, "-flinux") == 0) {
751                         firm_opt.os_support = OS_SUPPORT_LINUX;
752                 }
753         }
754
755         /* set target/os specific stuff */
756         init_os_support();
757
758         /* apply optimisation level */
759         switch(opt_level) {
760         case 0:
761                 set_option("no-opt");
762                 break;
763         case 1:
764                 set_option("no-inline");
765                 break;
766         default:
767         case 4:
768                 /* use_builtins = true; */
769                 /* fallthrough */
770         case 3:
771                 set_option("thread-jumps");
772                 set_option("if-conversion");
773                 /* fallthrough */
774         case 2:
775                 set_option("strict-aliasing");
776                 set_option("inline");
777                 set_option("deconv");
778                 set_be_option("omitfp");
779                 break;
780         }
781
782         /* parse rest of options */
783         standard                        = STANDARD_DEFAULT;
784         unsigned        features_on     = 0;
785         unsigned        features_off    = 0;
786         filetype_t      forced_filetype = FILETYPE_AUTODETECT;
787         bool            help_displayed  = false;
788         bool            argument_errors = false;
789         for (int i = 1; i < argc; ++i) {
790                 const char *arg = argv[i];
791                 if (arg[0] == '-' && arg[1] != '\0') {
792                         /* an option */
793                         const char *option = &arg[1];
794                         if (option[0] == 'o') {
795                                 GET_ARG_AFTER(outname, "-o");
796                         } else if (option[0] == 'g') {
797                                 set_be_option("debuginfo=stabs");
798                                 set_be_option("omitfp=no");
799                                 set_be_option("ia32-nooptcc=yes");
800                         } else if (SINGLE_OPTION('c')) {
801                                 mode = CompileAssemble;
802                         } else if (SINGLE_OPTION('E')) {
803                                 mode = PreprocessOnly;
804                         } else if (SINGLE_OPTION('S')) {
805                                 mode = Compile;
806                         } else if (option[0] == 'O') {
807                                 continue;
808                         } else if (option[0] == 'I') {
809                                 const char *opt;
810                                 GET_ARG_AFTER(opt, "-I");
811                                 add_flag(&cppflags_obst, "-I%s", opt);
812                         } else if (option[0] == 'D') {
813                                 const char *opt;
814                                 GET_ARG_AFTER(opt, "-D");
815                                 add_flag(&cppflags_obst, "-D%s", opt);
816                         } else if (option[0] == 'U') {
817                                 const char *opt;
818                                 GET_ARG_AFTER(opt, "-U");
819                                 add_flag(&cppflags_obst, "-U%s", opt);
820                         } else if (option[0] == 'l') {
821                                 const char *opt;
822                                 GET_ARG_AFTER(opt, "-l");
823                                 add_flag(&ldflags_obst, "-l%s", opt);
824                         } else if (option[0] == 'L') {
825                                 const char *opt;
826                                 GET_ARG_AFTER(opt, "-L");
827                                 add_flag(&ldflags_obst, "-L%s", opt);
828                         } else if (SINGLE_OPTION('v')) {
829                                 verbose = 1;
830                         } else if (SINGLE_OPTION('w')) {
831                                 memset(&warning, 0, sizeof(warning));
832                         } else if (option[0] == 'x') {
833                                 const char *opt;
834                                 GET_ARG_AFTER(opt, "-x");
835                                 forced_filetype = get_filetype_from_string(opt);
836                                 if (forced_filetype == FILETYPE_UNKNOWN) {
837                                         fprintf(stderr, "Unknown language '%s'\n", opt);
838                                         argument_errors = true;
839                                 }
840                         } else if (streq(option, "M")) {
841                                 mode = PreprocessOnly;
842                                 add_flag(&cppflags_obst, "-M");
843                         } else if (streq(option, "MMD") ||
844                                    streq(option, "MD")) {
845                             construct_dep_target = true;
846                                 add_flag(&cppflags_obst, "-%s", option);
847                         } else if (streq(option, "MM")  ||
848                                    streq(option, "MP")) {
849                                 add_flag(&cppflags_obst, "-%s", option);
850                         } else if (streq(option, "MT") ||
851                                    streq(option, "MQ") ||
852                                    streq(option, "MF")) {
853                                 const char *opt;
854                                 GET_ARG_AFTER(opt, "-MT");
855                                 add_flag(&cppflags_obst, "-%s", option);
856                                 add_flag(&cppflags_obst, "%s", opt);
857                         } else if (streq(option, "include")) {
858                                 const char *opt;
859                                 GET_ARG_AFTER(opt, "-include");
860                                 add_flag(&cppflags_obst, "-include");
861                                 add_flag(&cppflags_obst, "%s", opt);
862                         } else if (streq(option, "isystem")) {
863                                 const char *opt;
864                                 GET_ARG_AFTER(opt, "-isystem");
865                                 add_flag(&cppflags_obst, "-isystem");
866                                 add_flag(&cppflags_obst, "%s", opt);
867                         } else if (streq(option, "nostdinc")
868                                         || streq(option, "trigraphs")) {
869                                 /* pass these through to the preprocessor */
870                                 add_flag(&cppflags_obst, "%s", arg);
871                         } else if (streq(option, "pipe")) {
872                                 /* here for gcc compatibility */
873                         } else if (option[0] == 'f') {
874                                 char const *orig_opt;
875                                 GET_ARG_AFTER(orig_opt, "-f");
876
877                                 if (strstart(orig_opt, "align-loops=") ||
878                                     strstart(orig_opt, "align-jumps=") ||
879                                     strstart(orig_opt, "align-functions=")) {
880                                         fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
881                                 } else if (strstart(orig_opt, "input-charset=")) {
882                                         char const* const encoding = strchr(orig_opt, '=') + 1;
883                                         select_input_encoding(encoding);
884                                 } else if (streq(orig_opt, "verbose-asm")) {
885                                         /* ignore: we always print verbose assembler */
886                                 } else {
887                                         char const *opt         = orig_opt;
888                                         bool        truth_value = true;
889                                         if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
890                                                 truth_value = false;
891                                                 opt += 3;
892                                         }
893
894                                         if (streq(opt, "builtins")) {
895                                                 use_builtins = truth_value;
896                                         } else if (streq(opt, "dollars-in-identifiers")) {
897                                                 allow_dollar_in_symbol = truth_value;
898                                         } else if (streq(opt, "omit-frame-pointer")) {
899                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
900                                         } else if (streq(opt, "short-wchar")) {
901                                                 wchar_atomic_kind = truth_value ? ATOMIC_TYPE_USHORT
902                                                         : ATOMIC_TYPE_INT;
903                                         } else if (streq(opt, "signed-char")) {
904                                                 char_is_signed = truth_value;
905                                         } else if (streq(opt, "strength-reduce")) {
906                                                 firm_option(truth_value ? "strength-red" : "no-strength-red");
907                                         } else if (streq(opt, "syntax-only")) {
908                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
909                                         } else if (streq(opt, "unsigned-char")) {
910                                                 char_is_signed = !truth_value;
911                                         } else if (streq(opt, "fast-math")               ||
912                                                    streq(opt, "jump-tables")             ||
913                                                    streq(opt, "expensive-optimizations") ||
914                                                    streq(opt, "common")                  ||
915                                                    streq(opt, "PIC")                     ||
916                                                    streq(opt, "align-loops")             ||
917                                                    streq(opt, "align-jumps")             ||
918                                                    streq(opt, "align-functions")) {
919                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
920                                         } else {
921                                                 int res = firm_option(orig_opt);
922                                                 if (res == 0) {
923                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
924                                                                 orig_opt);
925                                                         argument_errors = true;
926                                                         continue;
927                                                 } else if (res == -1) {
928                                                         help_displayed = true;
929                                                 }
930                                         }
931                                 }
932                         } else if (option[0] == 'b') {
933                                 const char *opt;
934                                 GET_ARG_AFTER(opt, "-b");
935                                 int res = firm_be_option(opt);
936                                 if (res == 0) {
937                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
938                                                 opt);
939                                         argument_errors = true;
940                                 } else if (res == -1) {
941                                         help_displayed = true;
942                                 } else if (strstart(opt, "isa=")) {
943                                         strncpy(cpu_arch, opt, sizeof(cpu_arch));
944                                 }
945                         } else if (option[0] == 'W') {
946                                 if (strstart(option + 1, "p,")) {
947                                         // pass options directly to the preprocessor
948                                         const char *opt;
949                                         GET_ARG_AFTER(opt, "-Wp,");
950                                         add_flag(&cppflags_obst, "-Wp,%s", opt);
951                                 } else if (strstart(option + 1, "l,")) {
952                                         // pass options directly to the linker
953                                         const char *opt;
954                                         GET_ARG_AFTER(opt, "-Wl,");
955                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
956                                 } else if (streq(option + 1, "no-trigraphs")
957                                                         || streq(option + 1, "undef")) {
958                                         add_flag(&cppflags_obst, "%s", arg);
959                                 } else {
960                                         set_warning_opt(&option[1]);
961                                 }
962                         } else if (option[0] == 'm') {
963                                 /* -m options */
964                                 const char *opt;
965                                 char arch_opt[64];
966
967                                 GET_ARG_AFTER(opt, "-m");
968                                 if (strstart(opt, "arch=")) {
969                                         GET_ARG_AFTER(opt, "-march=");
970                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
971                                         int res = firm_be_option(arch_opt);
972                                         if (res == 0) {
973                                                 fprintf(stderr, "Unknown architecture '%s'\n", arch_opt);
974                                                 argument_errors = true;
975                                         } else {
976                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
977                                                 int res = firm_be_option(arch_opt);
978                                                 if (res == 0)
979                                                         argument_errors = true;
980                                         }
981                                 } else if (strstart(opt, "tune=")) {
982                                         GET_ARG_AFTER(opt, "-mtune=");
983                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
984                                         int res = firm_be_option(arch_opt);
985                                         if (res == 0)
986                                                 argument_errors = true;
987                                 } else if (strstart(opt, "cpu=")) {
988                                         GET_ARG_AFTER(opt, "-mcpu=");
989                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
990                                         int res = firm_be_option(arch_opt);
991                                         if (res == 0)
992                                                 argument_errors = true;
993                                 } else if (strstart(opt, "fpmath=")) {
994                                         GET_ARG_AFTER(opt, "-mfpmath=");
995                                         if (streq(opt, "387"))
996                                                 opt = "x87";
997                                         else if (streq(opt, "sse"))
998                                                 opt = "sse2";
999                                         else {
1000                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
1001                                                 argument_errors = true;
1002                                         }
1003                                         if (!argument_errors) {
1004                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
1005                                                 int res = firm_be_option(arch_opt);
1006                                                 if (res == 0)
1007                                                         argument_errors = true;
1008                                         }
1009                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
1010                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
1011                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
1012                                         int res = firm_be_option(arch_opt);
1013                                         if (res == 0)
1014                                                 argument_errors = true;
1015                                 } else if (streq(opt, "omit-leaf-frame-pointer")) {
1016                                         set_be_option("omitleaffp=1");
1017                                 } else if (streq(opt, "no-omit-leaf-frame-pointer")) {
1018                                         set_be_option("omitleaffp=0");
1019                                 } else if (streq(opt, "rtd")) {
1020                                         default_calling_convention = CC_STDCALL;
1021                                 } else {
1022                                         char *endptr;
1023                                         long int value = strtol(opt, &endptr, 10);
1024                                         if (*endptr != '\0') {
1025                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
1026                                                 argument_errors = true;
1027                                         }
1028                                         if (value != 16 && value != 32 && value != 64) {
1029                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
1030                                                 argument_errors = true;
1031                                         } else {
1032                                                 machine_size = (unsigned int)value;
1033                                         }
1034                                 }
1035                         } else if (streq(option, "pg")) {
1036                                 set_be_option("gprof");
1037                                 add_flag(&ldflags_obst, "-pg");
1038                         } else if (streq(option, "pedantic") ||
1039                                    streq(option, "ansi")) {
1040                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
1041                         } else if (streq(option, "shared")) {
1042                                 add_flag(&ldflags_obst, "-shared");
1043                         } else if (strstart(option, "std=")) {
1044                                 const char *const o = &option[4];
1045                                 standard =
1046                                         streq(o, "c++")            ? STANDARD_CXX98   :
1047                                         streq(o, "c++98")          ? STANDARD_CXX98   :
1048                                         streq(o, "c89")            ? STANDARD_C89     :
1049                                         streq(o, "c99")            ? STANDARD_C99     :
1050                                         streq(o, "c9x")            ? STANDARD_C99     : // deprecated
1051                                         streq(o, "gnu++98")        ? STANDARD_GNUXX98 :
1052                                         streq(o, "gnu89")          ? STANDARD_GNU89   :
1053                                         streq(o, "gnu99")          ? STANDARD_GNU99   :
1054                                         streq(o, "gnu9x")          ? STANDARD_GNU99   : // deprecated
1055                                         streq(o, "iso9899:1990")   ? STANDARD_C89     :
1056                                         streq(o, "iso9899:199409") ? STANDARD_C90     :
1057                                         streq(o, "iso9899:1999")   ? STANDARD_C99     :
1058                                         streq(o, "iso9899:199x")   ? STANDARD_C99     : // deprecated
1059                                         (fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg), standard);
1060                         } else if (streq(option, "version")) {
1061                                 print_cparser_version();
1062                         } else if (strstart(option, "print-file-name=")) {
1063                                 GET_ARG_AFTER(print_file_name_file, "-print-file-name=");
1064                         } else if (option[0] == '-') {
1065                                 /* double dash option */
1066                                 ++option;
1067                                 if (streq(option, "gcc")) {
1068                                         features_on  |=  _GNUC;
1069                                         features_off &= ~_GNUC;
1070                                 } else if (streq(option, "no-gcc")) {
1071                                         features_on  &= ~_GNUC;
1072                                         features_off |=  _GNUC;
1073                                 } else if (streq(option, "ms")) {
1074                                         features_on  |=  _MS;
1075                                         features_off &= ~_MS;
1076                                 } else if (streq(option, "no-ms")) {
1077                                         features_on  &= ~_MS;
1078                                         features_off |=  _MS;
1079                                 } else if (streq(option, "strict")) {
1080                                         strict_mode = true;
1081                                 } else if (streq(option, "lextest")) {
1082                                         mode = LexTest;
1083                                 } else if (streq(option, "benchmark")) {
1084                                         mode = BenchmarkParser;
1085                                 } else if (streq(option, "print-ast")) {
1086                                         mode = PrintAst;
1087                                 } else if (streq(option, "print-implicit-cast")) {
1088                                         print_implicit_casts = true;
1089                                 } else if (streq(option, "print-parenthesis")) {
1090                                         print_parenthesis = true;
1091                                 } else if (streq(option, "print-fluffy")) {
1092                                         mode = PrintFluffy;
1093                                 } else if (streq(option, "print-caml")) {
1094                                         mode = PrintCaml;
1095                                 } else if (streq(option, "print-jna")) {
1096                                         mode = PrintJna;
1097                                 } else if (streq(option, "time")) {
1098                                         do_timing = true;
1099                                 } else if (streq(option, "version")) {
1100                                         print_cparser_version();
1101                                         exit(EXIT_SUCCESS);
1102                                 } else if (streq(option, "dump-function")) {
1103                                         ++i;
1104                                         if (i >= argc) {
1105                                                 fprintf(stderr, "error: "
1106                                                         "expected argument after '--dump-function'\n");
1107                                                 argument_errors = true;
1108                                                 break;
1109                                         }
1110                                         dumpfunction = argv[i];
1111                                         mode         = CompileDump;
1112                                 } else if (streq(option, "export-ir")) {
1113                                         mode = CompileExportIR;
1114                                 } else {
1115                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
1116                                         argument_errors = true;
1117                                 }
1118                         } else {
1119                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
1120                                 argument_errors = true;
1121                         }
1122                 } else {
1123                         filetype_t type = forced_filetype;
1124                         if (type == FILETYPE_AUTODETECT) {
1125                                 if (streq(arg, "-")) {
1126                                         /* - implicitly means C source file */
1127                                         type = FILETYPE_C;
1128                                 } else {
1129                                         const char *suffix = strrchr(arg, '.');
1130                                         /* Ensure there is at least one char before the suffix */
1131                                         if (suffix != NULL && suffix != arg) {
1132                                                 ++suffix;
1133                                                 type =
1134                                                         streq(suffix, "S")   ? FILETYPE_ASSEMBLER              :
1135                                                         streq(suffix, "a")   ? FILETYPE_OBJECT                 :
1136                                                         streq(suffix, "c")   ? FILETYPE_C                      :
1137                                                         streq(suffix, "cc")  ? FILETYPE_CXX                    :
1138                                                         streq(suffix, "cpp") ? FILETYPE_CXX                    :
1139                                                         streq(suffix, "cxx") ? FILETYPE_CXX                    :
1140                                                         streq(suffix, "h")   ? FILETYPE_C                      :
1141                                                         streq(suffix, "ir")  ? FILETYPE_IR                     :
1142                                                         streq(suffix, "o")   ? FILETYPE_OBJECT                 :
1143                                                         streq(suffix, "s")   ? FILETYPE_PREPROCESSED_ASSEMBLER :
1144                                                         streq(suffix, "so")  ? FILETYPE_OBJECT                 :
1145                                                         FILETYPE_AUTODETECT;
1146                                         }
1147                                 }
1148
1149                                 if (type == FILETYPE_AUTODETECT) {
1150                                         fprintf(stderr, "'%s': file format not recognized\n", arg);
1151                                         continue;
1152                                 }
1153                         }
1154
1155                         file_list_entry_t *entry
1156                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
1157                         memset(entry, 0, sizeof(entry[0]));
1158                         entry->name = arg;
1159                         entry->type = type;
1160
1161                         if (last_file != NULL) {
1162                                 last_file->next = entry;
1163                         } else {
1164                                 files = entry;
1165                         }
1166                         last_file = entry;
1167                 }
1168         }
1169
1170         if (print_file_name_file != NULL) {
1171                 print_file_name(print_file_name_file);
1172                 return 0;
1173         }
1174
1175         if (files == NULL) {
1176                 fprintf(stderr, "error: no input files specified\n");
1177                 argument_errors = true;
1178         }
1179
1180         if (help_displayed) {
1181                 return !argument_errors;
1182         }
1183         if (argument_errors) {
1184                 usage(argv[0]);
1185                 return 1;
1186         }
1187
1188         /* we do the lowering in ast2firm */
1189         firm_opt.lower_bitfields = FALSE;
1190
1191         /* set the c_mode here, types depends on it */
1192         c_mode |= features_on;
1193         c_mode &= ~features_off;
1194
1195         gen_firm_init();
1196         init_symbol_table();
1197         init_types();
1198         init_typehash();
1199         init_basic_types();
1200         init_lexer();
1201         init_ast();
1202         init_parser();
1203         init_ast2firm();
1204         init_mangle();
1205
1206         if (do_timing)
1207                 timer_init();
1208
1209         if (construct_dep_target) {
1210                 if (outname != 0 && strlen(outname) >= 2) {
1211                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
1212                 } else {
1213                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
1214                 }
1215         } else {
1216                 dep_target[0] = '\0';
1217         }
1218
1219         char outnamebuf[4096];
1220         if (outname == NULL) {
1221                 const char *filename = files->name;
1222
1223                 switch(mode) {
1224                 case BenchmarkParser:
1225                 case PrintAst:
1226                 case PrintFluffy:
1227                 case PrintCaml:
1228                 case PrintJna:
1229                 case LexTest:
1230                 case PreprocessOnly:
1231                 case ParseOnly:
1232                         outname = "-";
1233                         break;
1234                 case Compile:
1235                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
1236                         outname = outnamebuf;
1237                         break;
1238                 case CompileAssemble:
1239                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
1240                         outname = outnamebuf;
1241                         break;
1242                 case CompileDump:
1243                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
1244                                         ".vcg");
1245                         outname = outnamebuf;
1246                         break;
1247                 case CompileExportIR:
1248                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".ir");
1249                         outname = outnamebuf;
1250                         break;
1251                 case CompileAssembleLink:
1252 #ifdef _WIN32
1253                         outname = "a.exe";
1254 #else
1255                         outname = "a.out";
1256 #endif
1257                         break;
1258                 }
1259         }
1260
1261         assert(outname != NULL);
1262
1263         FILE *out;
1264         if (streq(outname, "-")) {
1265                 out = stdout;
1266         } else {
1267                 out = fopen(outname, "w");
1268                 if (out == NULL) {
1269                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
1270                                         strerror(errno));
1271                         return 1;
1272                 }
1273         }
1274
1275         file_list_entry_t *file;
1276         for (file = files; file != NULL; file = file->next) {
1277                 char        asm_tempfile[1024];
1278                 const char *filename = file->name;
1279                 filetype_t  filetype = file->type;
1280
1281                 if (filetype == FILETYPE_OBJECT)
1282                         continue;
1283
1284                 FILE *in = NULL;
1285                 if (mode == LexTest) {
1286                         if (in == NULL)
1287                                 in = open_file(filename);
1288                         lextest(in, filename);
1289                         fclose(in);
1290                         exit(EXIT_SUCCESS);
1291                 }
1292
1293                 FILE *preprocessed_in = NULL;
1294                 filetype_t next_filetype = filetype;
1295                 switch (filetype) {
1296                         case FILETYPE_C:
1297                                 next_filetype = FILETYPE_PREPROCESSED_C;
1298                                 goto preprocess;
1299                         case FILETYPE_CXX:
1300                                 next_filetype = FILETYPE_PREPROCESSED_CXX;
1301                                 goto preprocess;
1302                         case FILETYPE_ASSEMBLER:
1303                                 next_filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1304                                 goto preprocess;
1305 preprocess:
1306                                 /* no support for input on FILE* yet */
1307                                 if (in != NULL)
1308                                         panic("internal compiler error: in for preprocessor != NULL");
1309
1310                                 preprocessed_in = preprocess(filename, filetype);
1311                                 if (mode == PreprocessOnly) {
1312                                         copy_file(out, preprocessed_in);
1313                                         int result = pclose(preprocessed_in);
1314                                         fclose(out);
1315                                         /* remove output file in case of error */
1316                                         if (out != stdout && result != EXIT_SUCCESS) {
1317                                                 unlink(outname);
1318                                         }
1319                                         return result;
1320                                 }
1321
1322                                 in = preprocessed_in;
1323                                 filetype = next_filetype;
1324                                 break;
1325
1326                         default:
1327                                 break;
1328                 }
1329
1330                 FILE *asm_out;
1331                 if (mode == Compile) {
1332                         asm_out = out;
1333                 } else {
1334                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "ccs");
1335                 }
1336
1337                 if (in == NULL)
1338                         in = open_file(filename);
1339
1340                 /* preprocess and compile */
1341                 if (filetype == FILETYPE_PREPROCESSED_C) {
1342                         char const* invalid_mode;
1343                         switch (standard) {
1344                                 case STANDARD_ANSI:
1345                                 case STANDARD_C89:   c_mode = _C89;                break;
1346                                 /* TODO determine difference between these two */
1347                                 case STANDARD_C90:   c_mode = _C89;                break;
1348                                 case STANDARD_C99:   c_mode = _C89 | _C99;         break;
1349                                 case STANDARD_GNU89: c_mode = _C89 |        _GNUC; break;
1350
1351 default_c_warn:
1352                                         fprintf(stderr,
1353                                                         "warning: command line option \"-std=%s\" is not valid for C\n",
1354                                                         invalid_mode);
1355                                         /* FALLTHROUGH */
1356                                 case STANDARD_DEFAULT:
1357                                 case STANDARD_GNU99:   c_mode = _C89 | _C99 | _GNUC; break;
1358
1359                                 case STANDARD_CXX98:   invalid_mode = "c++98"; goto default_c_warn;
1360                                 case STANDARD_GNUXX98: invalid_mode = "gnu98"; goto default_c_warn;
1361                         }
1362                         goto do_parsing;
1363                 } else if (filetype == FILETYPE_PREPROCESSED_CXX) {
1364                         char const* invalid_mode;
1365                         switch (standard) {
1366                                 case STANDARD_C89:   invalid_mode = "c89";   goto default_cxx_warn;
1367                                 case STANDARD_C90:   invalid_mode = "c90";   goto default_cxx_warn;
1368                                 case STANDARD_C99:   invalid_mode = "c99";   goto default_cxx_warn;
1369                                 case STANDARD_GNU89: invalid_mode = "gnu89"; goto default_cxx_warn;
1370                                 case STANDARD_GNU99: invalid_mode = "gnu99"; goto default_cxx_warn;
1371
1372                                 case STANDARD_ANSI:
1373                                 case STANDARD_CXX98: c_mode = _CXX; break;
1374
1375 default_cxx_warn:
1376                                         fprintf(stderr,
1377                                                         "warning: command line option \"-std=%s\" is not valid for C++\n",
1378                                                         invalid_mode);
1379                                 case STANDARD_DEFAULT:
1380                                 case STANDARD_GNUXX98: c_mode = _CXX | _GNUC; break;
1381                         }
1382
1383 do_parsing:
1384                         c_mode |= features_on;
1385                         c_mode &= ~features_off;
1386
1387                         /* do the actual parsing */
1388                         ir_timer_t *t_parsing = ir_timer_new();
1389                         timer_register(t_parsing, "Frontend: Parsing");
1390                         timer_push(t_parsing);
1391                         init_tokens();
1392                         translation_unit_t *const unit = do_parsing(in, filename);
1393                         timer_pop(t_parsing);
1394
1395                         /* prints the AST even if errors occurred */
1396                         if (mode == PrintAst) {
1397                                 print_to_file(out);
1398                                 print_ast(unit);
1399                         }
1400
1401                         if (error_count > 0) {
1402                                 /* parsing failed because of errors */
1403                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1404                                         warning_count);
1405                                 result = EXIT_FAILURE;
1406                                 continue;
1407                         } else if (warning_count > 0) {
1408                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1409                         }
1410
1411                         if (in == preprocessed_in) {
1412                                 int pp_result = pclose(preprocessed_in);
1413                                 if (pp_result != EXIT_SUCCESS) {
1414                                         /* remove output file */
1415                                         if (out != stdout)
1416                                                 unlink(outname);
1417                                         exit(EXIT_FAILURE);
1418                                 }
1419                         }
1420
1421                         if (mode == BenchmarkParser) {
1422                                 return result;
1423                         } else if (mode == PrintFluffy) {
1424                                 write_fluffy_decls(out, unit);
1425                                 continue;
1426                         } else if (mode == PrintCaml) {
1427                                 write_caml_decls(out, unit);
1428                                 continue;
1429                         } else if (mode == PrintJna) {
1430                                 write_jna_decls(out, unit);
1431                                 continue;
1432                         }
1433
1434                         /* build the firm graph */
1435                         ir_timer_t *t_construct = ir_timer_new();
1436                         timer_register(t_construct, "Frontend: Graph construction");
1437                         timer_push(t_construct);
1438                         translation_unit_to_firm(unit);
1439                         timer_pop(t_construct);
1440
1441 graph_built:
1442                         if (mode == ParseOnly) {
1443                                 continue;
1444                         }
1445
1446                         if (mode == CompileDump) {
1447                                 /* find irg */
1448                                 ident    *id     = new_id_from_str(dumpfunction);
1449                                 ir_graph *irg    = NULL;
1450                                 int       n_irgs = get_irp_n_irgs();
1451                                 for (int i = 0; i < n_irgs; ++i) {
1452                                         ir_graph *tirg   = get_irp_irg(i);
1453                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1454                                         if (irg_id == id) {
1455                                                 irg = tirg;
1456                                                 break;
1457                                         }
1458                                 }
1459
1460                                 if (irg == NULL) {
1461                                         fprintf(stderr, "No graph for function '%s' found\n",
1462                                                 dumpfunction);
1463                                         exit(1);
1464                                 }
1465
1466                                 dump_ir_block_graph_file(irg, out);
1467                                 fclose(out);
1468                                 exit(0);
1469                         }
1470
1471                         if (mode == CompileExportIR) {
1472                                 fclose(out);
1473                                 ir_export(outname);
1474                                 exit(0);
1475                         }
1476
1477                         gen_firm_finish(asm_out, filename, /*c_mode=*/1,
1478                                         have_const_functions);
1479                         if (asm_out != out) {
1480                                 fclose(asm_out);
1481                         }
1482                 } else if (filetype == FILETYPE_IR) {
1483                         fclose(in);
1484                         ir_import(filename);
1485                         goto graph_built;
1486                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1487                         copy_file(asm_out, in);
1488                         if (in == preprocessed_in) {
1489                                 int pp_result = pclose(preprocessed_in);
1490                                 if (pp_result != EXIT_SUCCESS) {
1491                                         /* remove output in error case */
1492                                         if (out != stdout)
1493                                                 unlink(outname);
1494                                         return pp_result;
1495                                 }
1496                         }
1497                         if (asm_out != out) {
1498                                 fclose(asm_out);
1499                         }
1500                 }
1501
1502                 if (mode == Compile)
1503                         continue;
1504
1505                 /* if we're here then we have preprocessed assembly */
1506                 filename = asm_tempfile;
1507                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1508
1509                 /* assemble */
1510                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1511                         char        temp[1024];
1512                         const char *filename_o;
1513                         if (mode == CompileAssemble) {
1514                                 fclose(out);
1515                                 filename_o = outname;
1516                         } else {
1517                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
1518                                 fclose(tempf);
1519                                 filename_o = temp;
1520                         }
1521
1522                         assemble(filename_o, filename);
1523
1524                         size_t len = strlen(filename_o) + 1;
1525                         filename = obstack_copy(&file_obst, filename_o, len);
1526                         filetype = FILETYPE_OBJECT;
1527                 }
1528
1529                 /* ok we're done here, process next file */
1530                 file->name = filename;
1531                 file->type = filetype;
1532         }
1533
1534         if (result != EXIT_SUCCESS) {
1535                 if (out != stdout)
1536                         unlink(outname);
1537                 return result;
1538         }
1539
1540         /* link program file */
1541         if (mode == CompileAssembleLink) {
1542                 obstack_1grow(&ldflags_obst, '\0');
1543                 const char *flags = obstack_finish(&ldflags_obst);
1544
1545                 /* construct commandline */
1546                 const char *linker = getenv("CPARSER_LINK");
1547                 if (linker == NULL)
1548                         linker = LINKER;
1549                 obstack_printf(&file_obst, "%s", linker);
1550                 for (file_list_entry_t *entry = files; entry != NULL;
1551                                 entry = entry->next) {
1552                         if (entry->type != FILETYPE_OBJECT)
1553                                 continue;
1554
1555                         add_flag(&file_obst, "%s", entry->name);
1556                 }
1557
1558                 add_flag(&file_obst, "-o");
1559                 add_flag(&file_obst, outname);
1560                 obstack_printf(&file_obst, "%s", flags);
1561                 obstack_1grow(&file_obst, '\0');
1562
1563                 char *commandline = obstack_finish(&file_obst);
1564
1565                 if (verbose) {
1566                         puts(commandline);
1567                 }
1568                 int err = system(commandline);
1569                 if (err != EXIT_SUCCESS) {
1570                         fprintf(stderr, "linker reported an error\n");
1571                         exit(1);
1572                 }
1573         }
1574
1575         if (do_timing)
1576                 timer_term(stderr);
1577
1578         obstack_free(&cppflags_obst, NULL);
1579         obstack_free(&ldflags_obst, NULL);
1580         obstack_free(&file_obst, NULL);
1581
1582         exit_mangle();
1583         exit_ast2firm();
1584         exit_parser();
1585         exit_ast();
1586         exit_lexer();
1587         exit_typehash();
1588         exit_types();
1589         exit_tokens();
1590         exit_symbol_table();
1591         return 0;
1592 }