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