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