x86-64: Define make variable TARGET so that test2 and test3 use correct flag.
[tinycc/kirr.git] / tcc.c
blob3901b81ae6d8989a7dc68b871efcf0162d79eb8d
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 #define _GNU_SOURCE
21 #include "config.h"
23 #ifdef CONFIG_TCCBOOT
25 #include "tccboot.h"
26 #define CONFIG_TCC_STATIC
28 #else
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <math.h>
36 #include <signal.h>
37 #include <fcntl.h>
38 #include <setjmp.h>
39 #include <time.h>
41 #ifdef _WIN32
42 #include <windows.h>
43 #include <sys/timeb.h>
44 #ifdef _MSC_VER
45 #define inline __inline
46 #endif
47 #endif
49 #ifndef _WIN32
50 #include <unistd.h>
51 #include <sys/time.h>
52 #include <sys/ucontext.h>
53 #include <sys/mman.h>
54 #endif
56 #endif /* !CONFIG_TCCBOOT */
58 #ifndef PAGESIZE
59 #define PAGESIZE 4096
60 #endif
62 #include "elf.h"
63 #include "stab.h"
65 #ifndef O_BINARY
66 #define O_BINARY 0
67 #endif
69 #include "libtcc.h"
71 /* parser debug */
72 //#define PARSE_DEBUG
73 /* preprocessor debug */
74 //#define PP_DEBUG
75 /* include file debug */
76 //#define INC_DEBUG
78 //#define MEM_DEBUG
80 /* assembler debug */
81 //#define ASM_DEBUG
83 /* target selection */
84 //#define TCC_TARGET_I386 /* i386 code generator */
85 //#define TCC_TARGET_ARM /* ARMv4 code generator */
86 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
87 //#define TCC_TARGET_X86_64 /* x86-64 code generator */
89 /* default target is I386 */
90 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
91 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
92 #define TCC_TARGET_I386
93 #endif
95 #if !defined(_WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
96 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
97 #define CONFIG_TCC_BCHECK /* enable bound checking code */
98 #endif
100 #if defined(_WIN32) && !defined(TCC_TARGET_PE)
101 #define CONFIG_TCC_STATIC
102 #endif
104 /* define it to include assembler support */
105 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67) && \
106 !defined(TCC_TARGET_X86_64)
107 #define CONFIG_TCC_ASM
108 #endif
110 /* object format selection */
111 #if defined(TCC_TARGET_C67)
112 #define TCC_TARGET_COFF
113 #endif
115 #define FALSE 0
116 #define false 0
117 #define TRUE 1
118 #define true 1
119 typedef int BOOL;
121 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
122 executables or dlls */
123 #define CONFIG_TCC_CRT_PREFIX CONFIG_SYSROOT "/usr/lib"
125 #define INCLUDE_STACK_SIZE 32
126 #define IFDEF_STACK_SIZE 64
127 #define VSTACK_SIZE 256
128 #define STRING_MAX_SIZE 1024
129 #define PACK_STACK_SIZE 8
131 #define TOK_HASH_SIZE 8192 /* must be a power of two */
132 #define TOK_ALLOC_INCR 512 /* must be a power of two */
133 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
135 /* token symbol management */
136 typedef struct TokenSym {
137 struct TokenSym *hash_next;
138 struct Sym *sym_define; /* direct pointer to define */
139 struct Sym *sym_label; /* direct pointer to label */
140 struct Sym *sym_struct; /* direct pointer to structure */
141 struct Sym *sym_identifier; /* direct pointer to identifier */
142 int tok; /* token number */
143 int len;
144 char str[1];
145 } TokenSym;
147 #ifdef TCC_TARGET_PE
148 typedef unsigned short nwchar_t;
149 #else
150 typedef int nwchar_t;
151 #endif
153 typedef struct CString {
154 int size; /* size in bytes */
155 void *data; /* either 'char *' or 'nwchar_t *' */
156 int size_allocated;
157 void *data_allocated; /* if non NULL, data has been malloced */
158 } CString;
160 /* type definition */
161 typedef struct CType {
162 int t;
163 struct Sym *ref;
164 } CType;
166 /* constant value */
167 typedef union CValue {
168 long double ld;
169 double d;
170 float f;
171 int i;
172 unsigned int ui;
173 unsigned int ul; /* address (should be unsigned long on 64 bit cpu) */
174 long long ll;
175 unsigned long long ull;
176 struct CString *cstr;
177 void *ptr;
178 int tab[1];
179 } CValue;
181 /* value on stack */
182 typedef struct SValue {
183 CType type; /* type */
184 unsigned short r; /* register + flags */
185 unsigned short r2; /* second register, used for 'long long'
186 type. If not used, set to VT_CONST */
187 CValue c; /* constant, if VT_CONST */
188 struct Sym *sym; /* symbol, if (VT_SYM | VT_CONST) */
189 } SValue;
191 /* symbol management */
192 typedef struct Sym {
193 int v; /* symbol token */
194 long r; /* associated register */
195 long c; /* associated number */
196 CType type; /* associated type */
197 struct Sym *next; /* next related symbol */
198 struct Sym *prev; /* prev symbol in stack */
199 struct Sym *prev_tok; /* previous symbol for this token */
200 } Sym;
202 /* section definition */
203 /* XXX: use directly ELF structure for parameters ? */
204 /* special flag to indicate that the section should not be linked to
205 the other ones */
206 #define SHF_PRIVATE 0x80000000
208 typedef struct Section {
209 unsigned long data_offset; /* current data offset */
210 unsigned char *data; /* section data */
211 unsigned long data_allocated; /* used for realloc() handling */
212 int sh_name; /* elf section name (only used during output) */
213 int sh_num; /* elf section number */
214 int sh_type; /* elf section type */
215 int sh_flags; /* elf section flags */
216 int sh_info; /* elf section info */
217 int sh_addralign; /* elf section alignment */
218 int sh_entsize; /* elf entry size */
219 unsigned long sh_size; /* section size (only used during output) */
220 unsigned long sh_addr; /* address at which the section is relocated */
221 unsigned long sh_offset; /* file offset */
222 int nb_hashed_syms; /* used to resize the hash table */
223 struct Section *link; /* link to another section */
224 struct Section *reloc; /* corresponding section for relocation, if any */
225 struct Section *hash; /* hash table for symbols */
226 struct Section *next;
227 char name[1]; /* section name */
228 } Section;
230 typedef struct DLLReference {
231 int level;
232 void *handle;
233 char name[1];
234 } DLLReference;
236 /* GNUC attribute definition */
237 typedef struct AttributeDef {
238 int aligned;
239 int packed;
240 Section *section;
241 int func_attr; /* calling convention, exports, ... */
242 } AttributeDef;
244 /* -------------------------------------------------- */
245 /* gr: wrappers for casting sym->r for other purposes */
246 typedef struct {
247 unsigned
248 func_call : 8,
249 func_args : 8,
250 func_export : 1;
251 } func_attr_t;
253 #define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call)
254 #define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export)
255 #define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args)
256 #define INLINE_DEF(r) (*(int **)&(r))
257 /* -------------------------------------------------- */
259 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
260 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
261 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
263 /* stored in 'Sym.c' field */
264 #define FUNC_NEW 1 /* ansi function prototype */
265 #define FUNC_OLD 2 /* old function prototype */
266 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
268 /* stored in 'Sym.r' field */
269 #define FUNC_CDECL 0 /* standard c call */
270 #define FUNC_STDCALL 1 /* pascal c call */
271 #define FUNC_FASTCALL1 2 /* first param in %eax */
272 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
273 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
274 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
276 /* field 'Sym.t' for macros */
277 #define MACRO_OBJ 0 /* object like macro */
278 #define MACRO_FUNC 1 /* function like macro */
280 /* field 'Sym.r' for C labels */
281 #define LABEL_DEFINED 0 /* label is defined */
282 #define LABEL_FORWARD 1 /* label is forward defined */
283 #define LABEL_DECLARED 2 /* label is declared but never used */
285 /* type_decl() types */
286 #define TYPE_ABSTRACT 1 /* type without variable */
287 #define TYPE_DIRECT 2 /* type with variable */
289 #define IO_BUF_SIZE 8192
291 typedef struct BufferedFile {
292 uint8_t *buf_ptr;
293 uint8_t *buf_end;
294 int fd;
295 int line_num; /* current line number - here to simplify code */
296 int ifndef_macro; /* #ifndef macro / #endif search */
297 int ifndef_macro_saved; /* saved ifndef_macro */
298 int *ifdef_stack_ptr; /* ifdef_stack value at the start of the file */
299 char inc_type; /* type of include */
300 char inc_filename[512]; /* filename specified by the user */
301 char filename[1024]; /* current filename - here to simplify code */
302 unsigned char buffer[IO_BUF_SIZE + 1]; /* extra size for CH_EOB char */
303 } BufferedFile;
305 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
306 #define CH_EOF (-1) /* end of file */
308 /* parsing state (used to save parser state to reparse part of the
309 source several times) */
310 typedef struct ParseState {
311 int *macro_ptr;
312 int line_num;
313 int tok;
314 CValue tokc;
315 } ParseState;
317 /* used to record tokens */
318 typedef struct TokenString {
319 int *str;
320 int len;
321 int allocated_len;
322 int last_line_num;
323 } TokenString;
325 /* include file cache, used to find files faster and also to eliminate
326 inclusion if the include file is protected by #ifndef ... #endif */
327 typedef struct CachedInclude {
328 int ifndef_macro;
329 int hash_next; /* -1 if none */
330 char type; /* '"' or '>' to give include type */
331 char filename[1]; /* path specified in #include */
332 } CachedInclude;
334 #define CACHED_INCLUDES_HASH_SIZE 512
336 /* parser */
337 static struct BufferedFile *file;
338 static int ch, tok;
339 static CString tok_spaces; /* spaces before current token */
340 static CValue tokc;
341 static CString tokcstr; /* current parsed string, if any */
342 /* additional informations about token */
343 static int tok_flags;
344 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
345 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
346 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
347 #define TOK_FLAG_EOF 0x0008 /* end of file */
349 static int *macro_ptr, *macro_ptr_allocated;
350 static int *unget_saved_macro_ptr;
351 static int unget_saved_buffer[TOK_MAX_SIZE + 1];
352 static int unget_buffer_enabled;
353 static int parse_flags;
354 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
355 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
356 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
357 token. line feed is also
358 returned at eof */
359 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
361 static Section *text_section, *data_section, *bss_section; /* predefined sections */
362 static Section *cur_text_section; /* current section where function code is
363 generated */
364 #ifdef CONFIG_TCC_ASM
365 static Section *last_text_section; /* to handle .previous asm directive */
366 #endif
367 /* bound check related sections */
368 static Section *bounds_section; /* contains global data bound description */
369 static Section *lbounds_section; /* contains local data bound description */
370 /* symbol sections */
371 static Section *symtab_section, *strtab_section;
373 /* debug sections */
374 static Section *stab_section, *stabstr_section;
376 /* loc : local variable index
377 ind : output code index
378 rsym: return symbol
379 anon_sym: anonymous symbol index
381 static int rsym, anon_sym, ind, loc;
382 /* expression generation modifiers */
383 static int const_wanted; /* true if constant wanted */
384 static int nocode_wanted; /* true if no code generation wanted for an expression */
385 static int global_expr; /* true if compound literals must be allocated
386 globally (used during initializers parsing */
387 static CType func_vt; /* current function return type (used by return
388 instruction) */
389 static int func_vc;
390 static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
391 static int tok_ident;
392 static TokenSym **table_ident;
393 static TokenSym *hash_ident[TOK_HASH_SIZE];
394 static char token_buf[STRING_MAX_SIZE + 1];
395 static char *funcname;
396 static Sym *global_stack, *local_stack;
397 static Sym *define_stack;
398 static Sym *global_label_stack, *local_label_stack;
399 /* symbol allocator */
400 #define SYM_POOL_NB (8192 / sizeof(Sym))
401 static Sym *sym_free_first;
402 static void **sym_pools;
403 static int nb_sym_pools;
405 static SValue vstack[VSTACK_SIZE], *vtop;
406 /* some predefined types */
407 static CType char_pointer_type, func_old_type, int_type;
408 /* true if isid(c) || isnum(c) */
409 static unsigned char isidnum_table[256-CH_EOF];
411 /* display some information during compilation */
412 static int verbose = 0;
414 /* compile with debug symbol (and use them if error during execution) */
415 static int do_debug = 0;
417 /* compile with built-in memory and bounds checker */
418 static int do_bounds_check = 0;
420 /* display benchmark infos */
421 #if !defined(LIBTCC)
422 static int do_bench = 0;
423 #endif
424 static int total_lines;
425 static int total_bytes;
427 /* use GNU C extensions */
428 static int gnu_ext = 1;
430 /* use Tiny C extensions */
431 static int tcc_ext = 1;
433 /* max number of callers shown if error */
434 static int num_callers = 6;
435 static const char **rt_bound_error_msg;
437 /* XXX: get rid of this ASAP */
438 static struct TCCState *tcc_state;
440 /* give the path of the tcc libraries */
441 static const char *tcc_lib_path = CONFIG_TCCDIR;
443 struct TCCState {
444 int output_type;
446 BufferedFile **include_stack_ptr;
447 int *ifdef_stack_ptr;
449 /* include file handling */
450 char **include_paths;
451 int nb_include_paths;
452 char **sysinclude_paths;
453 int nb_sysinclude_paths;
454 CachedInclude **cached_includes;
455 int nb_cached_includes;
457 char **library_paths;
458 int nb_library_paths;
460 /* array of all loaded dlls (including those referenced by loaded
461 dlls) */
462 DLLReference **loaded_dlls;
463 int nb_loaded_dlls;
465 /* sections */
466 Section **sections;
467 int nb_sections; /* number of sections, including first dummy section */
469 Section **priv_sections;
470 int nb_priv_sections; /* number of private sections */
472 /* got handling */
473 Section *got;
474 Section *plt;
475 unsigned long *got_offsets;
476 int nb_got_offsets;
477 /* give the correspondance from symtab indexes to dynsym indexes */
478 int *symtab_to_dynsym;
480 /* temporary dynamic symbol sections (for dll loading) */
481 Section *dynsymtab_section;
482 /* exported dynamic symbol section */
483 Section *dynsym;
485 int nostdinc; /* if true, no standard headers are added */
486 int nostdlib; /* if true, no standard libraries are added */
488 int nocommon; /* if true, do not use common symbols for .bss data */
490 /* if true, static linking is performed */
491 int static_link;
493 /* soname as specified on the command line (-soname) */
494 const char *soname;
496 /* if true, all symbols are exported */
497 int rdynamic;
499 /* if true, only link in referenced objects from archive */
500 int alacarte_link;
502 /* address of text section */
503 unsigned long text_addr;
504 int has_text_addr;
506 /* output format, see TCC_OUTPUT_FORMAT_xxx */
507 int output_format;
509 /* C language options */
510 int char_is_unsigned;
511 int leading_underscore;
513 /* warning switches */
514 int warn_write_strings;
515 int warn_unsupported;
516 int warn_error;
517 int warn_none;
518 int warn_implicit_function_declaration;
520 /* error handling */
521 void *error_opaque;
522 void (*error_func)(void *opaque, const char *msg);
523 int error_set_jmp_enabled;
524 jmp_buf error_jmp_buf;
525 int nb_errors;
527 /* tiny assembler state */
528 Sym *asm_labels;
530 /* see include_stack_ptr */
531 BufferedFile *include_stack[INCLUDE_STACK_SIZE];
533 /* see ifdef_stack_ptr */
534 int ifdef_stack[IFDEF_STACK_SIZE];
536 /* see cached_includes */
537 int cached_includes_hash[CACHED_INCLUDES_HASH_SIZE];
539 /* pack stack */
540 int pack_stack[PACK_STACK_SIZE];
541 int *pack_stack_ptr;
543 /* output file for preprocessing */
544 FILE *outfile;
547 /* The current value can be: */
548 #define VT_VALMASK 0x00ff
549 #define VT_CONST 0x00f0 /* constant in vc
550 (must be first non register value) */
551 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
552 #define VT_LOCAL 0x00f2 /* offset on stack */
553 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
554 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
555 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
556 #define VT_LVAL 0x0100 /* var is an lvalue */
557 #define VT_SYM 0x0200 /* a symbol value is added */
558 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
559 char/short stored in integer registers) */
560 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
561 dereferencing value */
562 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
563 bounding function call point is in vc */
564 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
565 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
566 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
567 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
569 /* types */
570 #define VT_INT 0 /* integer type */
571 #define VT_BYTE 1 /* signed byte type */
572 #define VT_SHORT 2 /* short type */
573 #define VT_VOID 3 /* void type */
574 #define VT_PTR 4 /* pointer */
575 #define VT_ENUM 5 /* enum definition */
576 #define VT_FUNC 6 /* function type */
577 #define VT_STRUCT 7 /* struct/union definition */
578 #define VT_FLOAT 8 /* IEEE float */
579 #define VT_DOUBLE 9 /* IEEE double */
580 #define VT_LDOUBLE 10 /* IEEE long double */
581 #define VT_BOOL 11 /* ISOC99 boolean type */
582 #define VT_LLONG 12 /* 64 bit integer */
583 #define VT_LONG 13 /* long integer (NEVER USED as type, only
584 during parsing) */
585 #define VT_BTYPE 0x000f /* mask for basic type */
586 #define VT_UNSIGNED 0x0010 /* unsigned type */
587 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
588 #define VT_BITFIELD 0x0040 /* bitfield modifier */
589 #define VT_CONSTANT 0x0800 /* const modifier */
590 #define VT_VOLATILE 0x1000 /* volatile modifier */
591 #define VT_SIGNED 0x2000 /* signed type */
593 /* storage */
594 #define VT_EXTERN 0x00000080 /* extern definition */
595 #define VT_STATIC 0x00000100 /* static variable */
596 #define VT_TYPEDEF 0x00000200 /* typedef definition */
597 #define VT_INLINE 0x00000400 /* inline definition */
599 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
601 /* type mask (except storage) */
602 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
603 #define VT_TYPE (~(VT_STORAGE))
605 /* token values */
607 /* warning: the following compare tokens depend on i386 asm code */
608 #define TOK_ULT 0x92
609 #define TOK_UGE 0x93
610 #define TOK_EQ 0x94
611 #define TOK_NE 0x95
612 #define TOK_ULE 0x96
613 #define TOK_UGT 0x97
614 #define TOK_Nset 0x98
615 #define TOK_Nclear 0x99
616 #define TOK_LT 0x9c
617 #define TOK_GE 0x9d
618 #define TOK_LE 0x9e
619 #define TOK_GT 0x9f
621 #define TOK_LAND 0xa0
622 #define TOK_LOR 0xa1
624 #define TOK_DEC 0xa2
625 #define TOK_MID 0xa3 /* inc/dec, to void constant */
626 #define TOK_INC 0xa4
627 #define TOK_UDIV 0xb0 /* unsigned division */
628 #define TOK_UMOD 0xb1 /* unsigned modulo */
629 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
630 #define TOK_CINT 0xb3 /* number in tokc */
631 #define TOK_CCHAR 0xb4 /* char constant in tokc */
632 #define TOK_STR 0xb5 /* pointer to string in tokc */
633 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
634 #define TOK_LCHAR 0xb7
635 #define TOK_LSTR 0xb8
636 #define TOK_CFLOAT 0xb9 /* float constant */
637 #define TOK_LINENUM 0xba /* line number info */
638 #define TOK_CDOUBLE 0xc0 /* double constant */
639 #define TOK_CLDOUBLE 0xc1 /* long double constant */
640 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
641 #define TOK_ADDC1 0xc3 /* add with carry generation */
642 #define TOK_ADDC2 0xc4 /* add with carry use */
643 #define TOK_SUBC1 0xc5 /* add with carry generation */
644 #define TOK_SUBC2 0xc6 /* add with carry use */
645 #define TOK_CUINT 0xc8 /* unsigned int constant */
646 #define TOK_CLLONG 0xc9 /* long long constant */
647 #define TOK_CULLONG 0xca /* unsigned long long constant */
648 #define TOK_ARROW 0xcb
649 #define TOK_DOTS 0xcc /* three dots */
650 #define TOK_SHR 0xcd /* unsigned shift right */
651 #define TOK_PPNUM 0xce /* preprocessor number */
653 #define TOK_SHL 0x01 /* shift left */
654 #define TOK_SAR 0x02 /* signed shift right */
656 /* assignement operators : normal operator or 0x80 */
657 #define TOK_A_MOD 0xa5
658 #define TOK_A_AND 0xa6
659 #define TOK_A_MUL 0xaa
660 #define TOK_A_ADD 0xab
661 #define TOK_A_SUB 0xad
662 #define TOK_A_DIV 0xaf
663 #define TOK_A_XOR 0xde
664 #define TOK_A_OR 0xfc
665 #define TOK_A_SHL 0x81
666 #define TOK_A_SAR 0x82
668 #ifndef offsetof
669 #define offsetof(type, field) ((size_t) &((type *)0)->field)
670 #endif
672 #ifndef countof
673 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
674 #endif
676 /* WARNING: the content of this string encodes token numbers */
677 static char tok_two_chars[] = "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
679 #define TOK_EOF (-1) /* end of file */
680 #define TOK_LINEFEED 10 /* line feed */
682 /* all identificators and strings have token above that */
683 #define TOK_IDENT 256
685 /* only used for i386 asm opcodes definitions */
686 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
688 #define DEF_BWL(x) \
689 DEF(TOK_ASM_ ## x ## b, #x "b") \
690 DEF(TOK_ASM_ ## x ## w, #x "w") \
691 DEF(TOK_ASM_ ## x ## l, #x "l") \
692 DEF(TOK_ASM_ ## x, #x)
694 #define DEF_WL(x) \
695 DEF(TOK_ASM_ ## x ## w, #x "w") \
696 DEF(TOK_ASM_ ## x ## l, #x "l") \
697 DEF(TOK_ASM_ ## x, #x)
699 #define DEF_FP1(x) \
700 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
701 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
702 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
703 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
705 #define DEF_FP(x) \
706 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
707 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
708 DEF_FP1(x)
710 #define DEF_ASMTEST(x) \
711 DEF_ASM(x ## o) \
712 DEF_ASM(x ## no) \
713 DEF_ASM(x ## b) \
714 DEF_ASM(x ## c) \
715 DEF_ASM(x ## nae) \
716 DEF_ASM(x ## nb) \
717 DEF_ASM(x ## nc) \
718 DEF_ASM(x ## ae) \
719 DEF_ASM(x ## e) \
720 DEF_ASM(x ## z) \
721 DEF_ASM(x ## ne) \
722 DEF_ASM(x ## nz) \
723 DEF_ASM(x ## be) \
724 DEF_ASM(x ## na) \
725 DEF_ASM(x ## nbe) \
726 DEF_ASM(x ## a) \
727 DEF_ASM(x ## s) \
728 DEF_ASM(x ## ns) \
729 DEF_ASM(x ## p) \
730 DEF_ASM(x ## pe) \
731 DEF_ASM(x ## np) \
732 DEF_ASM(x ## po) \
733 DEF_ASM(x ## l) \
734 DEF_ASM(x ## nge) \
735 DEF_ASM(x ## nl) \
736 DEF_ASM(x ## ge) \
737 DEF_ASM(x ## le) \
738 DEF_ASM(x ## ng) \
739 DEF_ASM(x ## nle) \
740 DEF_ASM(x ## g)
742 #define TOK_ASM_int TOK_INT
744 enum tcc_token {
745 TOK_LAST = TOK_IDENT - 1,
746 #define DEF(id, str) id,
747 #include "tcctok.h"
748 #undef DEF
751 static const char tcc_keywords[] =
752 #define DEF(id, str) str "\0"
753 #include "tcctok.h"
754 #undef DEF
757 #define TOK_UIDENT TOK_DEFINE
759 #ifdef _WIN32
760 #define snprintf _snprintf
761 #define vsnprintf _vsnprintf
762 #ifndef __GNUC__
763 #define strtold (long double)strtod
764 #define strtof (float)strtod
765 #define strtoll (long long)strtol
766 #endif
767 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
768 || defined(__OpenBSD__)
769 /* currently incorrect */
770 long double strtold(const char *nptr, char **endptr)
772 return (long double)strtod(nptr, endptr);
774 float strtof(const char *nptr, char **endptr)
776 return (float)strtod(nptr, endptr);
778 #else
779 /* XXX: need to define this to use them in non ISOC99 context */
780 extern float strtof (const char *__nptr, char **__endptr);
781 extern long double strtold (const char *__nptr, char **__endptr);
782 #endif
784 static char *pstrcpy(char *buf, int buf_size, const char *s);
785 static char *pstrcat(char *buf, int buf_size, const char *s);
786 static char *tcc_basename(const char *name);
787 static char *tcc_fileextension (const char *p);
789 static void next(void);
790 static void next_nomacro(void);
791 static void parse_expr_type(CType *type);
792 static void expr_type(CType *type);
793 static void unary_type(CType *type);
794 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
795 int case_reg, int is_expr);
796 static int expr_const(void);
797 static void expr_eq(void);
798 static void gexpr(void);
799 static void gen_inline_functions(void);
800 static void decl(int l);
801 static void decl_initializer(CType *type, Section *sec, unsigned long c,
802 int first, int size_only);
803 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
804 int has_init, int v, int scope);
805 int gv(int rc);
806 void gv2(int rc1, int rc2);
807 void move_reg(int r, int s);
808 void save_regs(int n);
809 void save_reg(int r);
810 void vpop(void);
811 void vswap(void);
812 void vdup(void);
813 int get_reg(int rc);
814 int get_reg_ex(int rc,int rc2);
816 struct macro_level {
817 struct macro_level *prev;
818 int *p;
821 static void macro_subst(TokenString *tok_str, Sym **nested_list,
822 const int *macro_str, struct macro_level **can_read_stream);
823 void gen_op(int op);
824 void force_charshort_cast(int t);
825 static void gen_cast(CType *type);
826 void vstore(void);
827 static Sym *sym_find(int v);
828 static Sym *sym_push(int v, CType *type, int r, int c);
830 /* type handling */
831 static int type_size(CType *type, int *a);
832 static inline CType *pointed_type(CType *type);
833 static int pointed_size(CType *type);
834 static int lvalue_type(int t);
835 static int parse_btype(CType *type, AttributeDef *ad);
836 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
837 static int compare_types(CType *type1, CType *type2, int unqualified);
838 static int is_compatible_types(CType *type1, CType *type2);
839 static int is_compatible_parameter_types(CType *type1, CType *type2);
841 int ieee_finite(double d);
842 void error(const char *fmt, ...);
843 void vpushi(int v);
844 void vpushll(long long v);
845 void vrott(int n);
846 void vnrott(int n);
847 void lexpand_nr(void);
848 static void vpush_global_sym(CType *type, int v);
849 void vset(CType *type, int r, int v);
850 void type_to_str(char *buf, int buf_size,
851 CType *type, const char *varstr);
852 char *get_tok_str(int v, CValue *cv);
853 static Sym *get_sym_ref(CType *type, Section *sec,
854 unsigned long offset, unsigned long size);
855 static Sym *external_global_sym(int v, CType *type, int r);
857 /* section generation */
858 static void section_realloc(Section *sec, unsigned long new_size);
859 static void *section_ptr_add(Section *sec, unsigned long size);
860 static void put_extern_sym(Sym *sym, Section *section,
861 unsigned long value, unsigned long size);
862 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
863 static int put_elf_str(Section *s, const char *sym);
864 static int put_elf_sym(Section *s,
865 unsigned long value, unsigned long size,
866 int info, int other, int shndx, const char *name);
867 static int add_elf_sym(Section *s, unsigned long value, unsigned long size,
868 int info, int other, int sh_num, const char *name);
869 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
870 int type, int symbol);
871 static void put_stabs(const char *str, int type, int other, int desc,
872 unsigned long value);
873 static void put_stabs_r(const char *str, int type, int other, int desc,
874 unsigned long value, Section *sec, int sym_index);
875 static void put_stabn(int type, int other, int desc, int value);
876 static void put_stabd(int type, int other, int desc);
877 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
879 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
880 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
881 #define AFF_PREPROCESS 0x0004 /* preprocess file */
882 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
884 /* tcccoff.c */
885 int tcc_output_coff(TCCState *s1, FILE *f);
887 /* tccpe.c */
888 void *resolve_sym(TCCState *s1, const char *sym, int type);
889 int pe_load_def_file(struct TCCState *s1, int fd);
890 int pe_test_res_file(void *v, int size);
891 int pe_load_res_file(struct TCCState *s1, int fd);
892 void pe_add_runtime(struct TCCState *s1);
893 void pe_guess_outfile(char *objfilename, int output_type);
894 int pe_output_file(struct TCCState *s1, const char *filename);
896 /* tccasm.c */
898 #ifdef CONFIG_TCC_ASM
900 typedef struct ExprValue {
901 uint32_t v;
902 Sym *sym;
903 } ExprValue;
905 #define MAX_ASM_OPERANDS 30
907 typedef struct ASMOperand {
908 int id; /* GCC 3 optionnal identifier (0 if number only supported */
909 char *constraint;
910 char asm_str[16]; /* computed asm string for operand */
911 SValue *vt; /* C value of the expression */
912 int ref_index; /* if >= 0, gives reference to a output constraint */
913 int input_index; /* if >= 0, gives reference to an input constraint */
914 int priority; /* priority, used to assign registers */
915 int reg; /* if >= 0, register number used for this operand */
916 int is_llong; /* true if double register value */
917 int is_memory; /* true if memory operand */
918 int is_rw; /* for '+' modifier */
919 } ASMOperand;
921 static void asm_expr(TCCState *s1, ExprValue *pe);
922 static int asm_int_expr(TCCState *s1);
923 static int find_constraint(ASMOperand *operands, int nb_operands,
924 const char *name, const char **pp);
926 static int tcc_assemble(TCCState *s1, int do_preprocess);
928 #endif
930 static void asm_instr(void);
931 static void asm_global_instr(void);
933 /* true if float/double/long double type */
934 static inline int is_float(int t)
936 int bt;
937 bt = t & VT_BTYPE;
938 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
941 #ifdef TCC_TARGET_I386
942 #include "i386-gen.c"
943 #endif
945 #ifdef TCC_TARGET_ARM
946 #include "arm-gen.c"
947 #endif
949 #ifdef TCC_TARGET_C67
950 #include "c67-gen.c"
951 #endif
953 #ifdef TCC_TARGET_X86_64
954 #include "x86_64-gen.c"
955 #endif
957 #ifdef CONFIG_TCC_STATIC
959 #define RTLD_LAZY 0x001
960 #define RTLD_NOW 0x002
961 #define RTLD_GLOBAL 0x100
962 #define RTLD_DEFAULT NULL
964 /* dummy function for profiling */
965 void *dlopen(const char *filename, int flag)
967 return NULL;
970 const char *dlerror(void)
972 return "error";
975 typedef struct TCCSyms {
976 char *str;
977 void *ptr;
978 } TCCSyms;
980 #define TCCSYM(a) { #a, &a, },
982 /* add the symbol you want here if no dynamic linking is done */
983 static TCCSyms tcc_syms[] = {
984 #if !defined(CONFIG_TCCBOOT)
985 TCCSYM(printf)
986 TCCSYM(fprintf)
987 TCCSYM(fopen)
988 TCCSYM(fclose)
989 #endif
990 { NULL, NULL },
993 void *resolve_sym(TCCState *s1, const char *symbol, int type)
995 TCCSyms *p;
996 p = tcc_syms;
997 while (p->str != NULL) {
998 if (!strcmp(p->str, symbol))
999 return p->ptr;
1000 p++;
1002 return NULL;
1005 #elif !defined(_WIN32)
1007 #include <dlfcn.h>
1009 void *resolve_sym(TCCState *s1, const char *sym, int type)
1011 return dlsym(RTLD_DEFAULT, sym);
1014 #endif
1016 /********************************************************/
1018 /* we use our own 'finite' function to avoid potential problems with
1019 non standard math libs */
1020 /* XXX: endianness dependent */
1021 int ieee_finite(double d)
1023 int *p = (int *)&d;
1024 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
1027 /* copy a string and truncate it. */
1028 static char *pstrcpy(char *buf, int buf_size, const char *s)
1030 char *q, *q_end;
1031 int c;
1033 if (buf_size > 0) {
1034 q = buf;
1035 q_end = buf + buf_size - 1;
1036 while (q < q_end) {
1037 c = *s++;
1038 if (c == '\0')
1039 break;
1040 *q++ = c;
1042 *q = '\0';
1044 return buf;
1047 /* strcat and truncate. */
1048 static char *pstrcat(char *buf, int buf_size, const char *s)
1050 int len;
1051 len = strlen(buf);
1052 if (len < buf_size)
1053 pstrcpy(buf + len, buf_size - len, s);
1054 return buf;
1057 #ifndef LIBTCC
1058 static int strstart(const char *str, const char *val, const char **ptr)
1060 const char *p, *q;
1061 p = str;
1062 q = val;
1063 while (*q != '\0') {
1064 if (*p != *q)
1065 return 0;
1066 p++;
1067 q++;
1069 if (ptr)
1070 *ptr = p;
1071 return 1;
1073 #endif
1075 #ifdef _WIN32
1076 #define IS_PATHSEP(c) (c == '/' || c == '\\')
1077 #define IS_ABSPATH(p) (IS_PATHSEP(p[0]) || (p[0] && p[1] == ':' && IS_PATHSEP(p[2])))
1078 #define PATHCMP stricmp
1079 #else
1080 #define IS_PATHSEP(c) (c == '/')
1081 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1082 #define PATHCMP strcmp
1083 #endif
1085 /* extract the basename of a file */
1086 static char *tcc_basename(const char *name)
1088 char *p = strchr(name, 0);
1089 while (p > name && !IS_PATHSEP(p[-1]))
1090 --p;
1091 return p;
1094 static char *tcc_fileextension (const char *name)
1096 char *b = tcc_basename(name);
1097 char *e = strrchr(b, '.');
1098 return e ? e : strchr(b, 0);
1101 #ifdef _WIN32
1102 char *normalize_slashes(char *path)
1104 char *p;
1105 for (p = path; *p; ++p)
1106 if (*p == '\\')
1107 *p = '/';
1108 return path;
1111 char *w32_tcc_lib_path(void)
1113 /* on win32, we suppose the lib and includes are at the location
1114 of 'tcc.exe' */
1115 char path[1024], *p;
1116 GetModuleFileNameA(NULL, path, sizeof path);
1117 p = tcc_basename(normalize_slashes(strlwr(path)));
1118 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
1119 p -= 5;
1120 else if (p > path)
1121 p--;
1122 *p = 0;
1123 return strdup(path);
1125 #endif
1127 void set_pages_executable(void *ptr, unsigned long length)
1129 #ifdef _WIN32
1130 unsigned long old_protect;
1131 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
1132 #else
1133 unsigned long start, end;
1134 start = (unsigned long)ptr & ~(PAGESIZE - 1);
1135 end = (unsigned long)ptr + length;
1136 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
1137 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
1138 #endif
1141 /* memory management */
1142 #ifdef MEM_DEBUG
1143 int mem_cur_size;
1144 int mem_max_size;
1145 unsigned malloc_usable_size(void*);
1146 #endif
1148 static inline void tcc_free(void *ptr)
1150 #ifdef MEM_DEBUG
1151 mem_cur_size -= malloc_usable_size(ptr);
1152 #endif
1153 free(ptr);
1156 static void *tcc_malloc(unsigned long size)
1158 void *ptr;
1159 ptr = malloc(size);
1160 if (!ptr && size)
1161 error("memory full");
1162 #ifdef MEM_DEBUG
1163 mem_cur_size += malloc_usable_size(ptr);
1164 if (mem_cur_size > mem_max_size)
1165 mem_max_size = mem_cur_size;
1166 #endif
1167 return ptr;
1170 static void *tcc_mallocz(unsigned long size)
1172 void *ptr;
1173 ptr = tcc_malloc(size);
1174 memset(ptr, 0, size);
1175 return ptr;
1178 static inline void *tcc_realloc(void *ptr, unsigned long size)
1180 void *ptr1;
1181 #ifdef MEM_DEBUG
1182 mem_cur_size -= malloc_usable_size(ptr);
1183 #endif
1184 ptr1 = realloc(ptr, size);
1185 #ifdef MEM_DEBUG
1186 /* NOTE: count not correct if alloc error, but not critical */
1187 mem_cur_size += malloc_usable_size(ptr1);
1188 if (mem_cur_size > mem_max_size)
1189 mem_max_size = mem_cur_size;
1190 #endif
1191 return ptr1;
1194 static char *tcc_strdup(const char *str)
1196 char *ptr;
1197 ptr = tcc_malloc(strlen(str) + 1);
1198 strcpy(ptr, str);
1199 return ptr;
1202 #define free(p) use_tcc_free(p)
1203 #define malloc(s) use_tcc_malloc(s)
1204 #define realloc(p, s) use_tcc_realloc(p, s)
1206 static void dynarray_add(void ***ptab, int *nb_ptr, void *data)
1208 int nb, nb_alloc;
1209 void **pp;
1211 nb = *nb_ptr;
1212 pp = *ptab;
1213 /* every power of two we double array size */
1214 if ((nb & (nb - 1)) == 0) {
1215 if (!nb)
1216 nb_alloc = 1;
1217 else
1218 nb_alloc = nb * 2;
1219 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
1220 if (!pp)
1221 error("memory full");
1222 *ptab = pp;
1224 pp[nb++] = data;
1225 *nb_ptr = nb;
1228 static void dynarray_reset(void *pp, int *n)
1230 void **p;
1231 for (p = *(void***)pp; *n; ++p, --*n)
1232 if (*p)
1233 tcc_free(*p);
1234 tcc_free(*(void**)pp);
1235 *(void**)pp = NULL;
1238 /* symbol allocator */
1239 static Sym *__sym_malloc(void)
1241 Sym *sym_pool, *sym, *last_sym;
1242 int i;
1244 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
1245 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
1247 last_sym = sym_free_first;
1248 sym = sym_pool;
1249 for(i = 0; i < SYM_POOL_NB; i++) {
1250 sym->next = last_sym;
1251 last_sym = sym;
1252 sym++;
1254 sym_free_first = last_sym;
1255 return last_sym;
1258 static inline Sym *sym_malloc(void)
1260 Sym *sym;
1261 sym = sym_free_first;
1262 if (!sym)
1263 sym = __sym_malloc();
1264 sym_free_first = sym->next;
1265 return sym;
1268 static inline void sym_free(Sym *sym)
1270 sym->next = sym_free_first;
1271 sym_free_first = sym;
1274 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
1276 Section *sec;
1278 sec = tcc_mallocz(sizeof(Section) + strlen(name));
1279 strcpy(sec->name, name);
1280 sec->sh_type = sh_type;
1281 sec->sh_flags = sh_flags;
1282 switch(sh_type) {
1283 case SHT_HASH:
1284 case SHT_REL:
1285 case SHT_RELA:
1286 case SHT_DYNSYM:
1287 case SHT_SYMTAB:
1288 case SHT_DYNAMIC:
1289 sec->sh_addralign = 4;
1290 break;
1291 case SHT_STRTAB:
1292 sec->sh_addralign = 1;
1293 break;
1294 default:
1295 sec->sh_addralign = 32; /* default conservative alignment */
1296 break;
1299 if (sh_flags & SHF_PRIVATE) {
1300 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
1301 } else {
1302 sec->sh_num = s1->nb_sections;
1303 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
1306 return sec;
1309 static void free_section(Section *s)
1311 #ifdef TCC_TARGET_X86_64
1312 /* after tcc_relocate(), some sections share the data buffer.
1313 let's check if the data is allocated not to free the shared buffers */
1314 if (s->data_allocated)
1315 #endif
1316 tcc_free(s->data);
1319 /* realloc section and set its content to zero */
1320 static void section_realloc(Section *sec, unsigned long new_size)
1322 unsigned long size;
1323 unsigned char *data;
1325 size = sec->data_allocated;
1326 if (size == 0)
1327 size = 1;
1328 while (size < new_size)
1329 size = size * 2;
1330 data = tcc_realloc(sec->data, size);
1331 if (!data)
1332 error("memory full");
1333 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
1334 sec->data = data;
1335 sec->data_allocated = size;
1338 /* reserve at least 'size' bytes in section 'sec' from
1339 sec->data_offset. */
1340 static void *section_ptr_add(Section *sec, unsigned long size)
1342 unsigned long offset, offset1;
1344 offset = sec->data_offset;
1345 offset1 = offset + size;
1346 if (offset1 > sec->data_allocated)
1347 section_realloc(sec, offset1);
1348 sec->data_offset = offset1;
1349 return sec->data + offset;
1352 /* return a reference to a section, and create it if it does not
1353 exists */
1354 Section *find_section(TCCState *s1, const char *name)
1356 Section *sec;
1357 int i;
1358 for(i = 1; i < s1->nb_sections; i++) {
1359 sec = s1->sections[i];
1360 if (!strcmp(name, sec->name))
1361 return sec;
1363 /* sections are created as PROGBITS */
1364 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
1367 #define SECTION_ABS ((void *)1)
1369 /* update sym->c so that it points to an external symbol in section
1370 'section' with value 'value' */
1371 static void put_extern_sym2(Sym *sym, Section *section,
1372 unsigned long value, unsigned long size,
1373 int can_add_underscore)
1375 int sym_type, sym_bind, sh_num, info, other, attr;
1376 ElfW(Sym) *esym;
1377 const char *name;
1378 char buf1[256];
1380 if (section == NULL)
1381 sh_num = SHN_UNDEF;
1382 else if (section == SECTION_ABS)
1383 sh_num = SHN_ABS;
1384 else
1385 sh_num = section->sh_num;
1387 other = attr = 0;
1389 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
1390 sym_type = STT_FUNC;
1391 #ifdef TCC_TARGET_PE
1392 if (sym->type.ref)
1393 attr = sym->type.ref->r;
1394 if (FUNC_EXPORT(attr))
1395 other |= 1;
1396 if (FUNC_CALL(attr) == FUNC_STDCALL)
1397 other |= 2;
1398 #endif
1399 } else {
1400 sym_type = STT_OBJECT;
1403 if (sym->type.t & VT_STATIC)
1404 sym_bind = STB_LOCAL;
1405 else
1406 sym_bind = STB_GLOBAL;
1408 if (!sym->c) {
1409 name = get_tok_str(sym->v, NULL);
1410 #ifdef CONFIG_TCC_BCHECK
1411 if (do_bounds_check) {
1412 char buf[32];
1414 /* XXX: avoid doing that for statics ? */
1415 /* if bound checking is activated, we change some function
1416 names by adding the "__bound" prefix */
1417 switch(sym->v) {
1418 #if 0
1419 /* XXX: we rely only on malloc hooks */
1420 case TOK_malloc:
1421 case TOK_free:
1422 case TOK_realloc:
1423 case TOK_memalign:
1424 case TOK_calloc:
1425 #endif
1426 case TOK_memcpy:
1427 case TOK_memmove:
1428 case TOK_memset:
1429 case TOK_strlen:
1430 case TOK_strcpy:
1431 case TOK__alloca:
1432 strcpy(buf, "__bound_");
1433 strcat(buf, name);
1434 name = buf;
1435 break;
1438 #endif
1440 #ifdef TCC_TARGET_PE
1441 if ((other & 2) && can_add_underscore) {
1442 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
1443 name = buf1;
1444 } else
1445 #endif
1446 if (tcc_state->leading_underscore && can_add_underscore) {
1447 buf1[0] = '_';
1448 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
1449 name = buf1;
1451 info = ELFW(ST_INFO)(sym_bind, sym_type);
1452 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
1453 } else {
1454 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1455 esym->st_value = value;
1456 esym->st_size = size;
1457 esym->st_shndx = sh_num;
1458 esym->st_other |= other;
1462 static void put_extern_sym(Sym *sym, Section *section,
1463 unsigned long value, unsigned long size)
1465 put_extern_sym2(sym, section, value, size, 1);
1468 /* add a new relocation entry to symbol 'sym' in section 's' */
1469 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
1471 if (!sym->c)
1472 put_extern_sym(sym, NULL, 0, 0);
1473 /* now we can add ELF relocation info */
1474 put_elf_reloc(symtab_section, s, offset, type, sym->c);
1477 static inline int isid(int c)
1479 return (c >= 'a' && c <= 'z') ||
1480 (c >= 'A' && c <= 'Z') ||
1481 c == '_';
1484 static inline int isnum(int c)
1486 return c >= '0' && c <= '9';
1489 static inline int isoct(int c)
1491 return c >= '0' && c <= '7';
1494 static inline int toup(int c)
1496 if (c >= 'a' && c <= 'z')
1497 return c - 'a' + 'A';
1498 else
1499 return c;
1502 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
1504 int len;
1505 len = strlen(buf);
1506 vsnprintf(buf + len, buf_size - len, fmt, ap);
1509 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
1511 va_list ap;
1512 va_start(ap, fmt);
1513 strcat_vprintf(buf, buf_size, fmt, ap);
1514 va_end(ap);
1517 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
1519 char buf[2048];
1520 BufferedFile **f;
1522 buf[0] = '\0';
1523 if (file) {
1524 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
1525 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
1526 (*f)->filename, (*f)->line_num);
1527 if (file->line_num > 0) {
1528 strcat_printf(buf, sizeof(buf),
1529 "%s:%d: ", file->filename, file->line_num);
1530 } else {
1531 strcat_printf(buf, sizeof(buf),
1532 "%s: ", file->filename);
1534 } else {
1535 strcat_printf(buf, sizeof(buf),
1536 "tcc: ");
1538 if (is_warning)
1539 strcat_printf(buf, sizeof(buf), "warning: ");
1540 strcat_vprintf(buf, sizeof(buf), fmt, ap);
1542 if (!s1->error_func) {
1543 /* default case: stderr */
1544 fprintf(stderr, "%s\n", buf);
1545 } else {
1546 s1->error_func(s1->error_opaque, buf);
1548 if (!is_warning || s1->warn_error)
1549 s1->nb_errors++;
1552 #ifdef LIBTCC
1553 void tcc_set_error_func(TCCState *s, void *error_opaque,
1554 void (*error_func)(void *opaque, const char *msg))
1556 s->error_opaque = error_opaque;
1557 s->error_func = error_func;
1559 #endif
1561 /* error without aborting current compilation */
1562 void error_noabort(const char *fmt, ...)
1564 TCCState *s1 = tcc_state;
1565 va_list ap;
1567 va_start(ap, fmt);
1568 error1(s1, 0, fmt, ap);
1569 va_end(ap);
1572 void error(const char *fmt, ...)
1574 TCCState *s1 = tcc_state;
1575 va_list ap;
1577 va_start(ap, fmt);
1578 error1(s1, 0, fmt, ap);
1579 va_end(ap);
1580 /* better than nothing: in some cases, we accept to handle errors */
1581 if (s1->error_set_jmp_enabled) {
1582 longjmp(s1->error_jmp_buf, 1);
1583 } else {
1584 /* XXX: eliminate this someday */
1585 exit(1);
1589 void expect(const char *msg)
1591 error("%s expected", msg);
1594 void warning(const char *fmt, ...)
1596 TCCState *s1 = tcc_state;
1597 va_list ap;
1599 if (s1->warn_none)
1600 return;
1602 va_start(ap, fmt);
1603 error1(s1, 1, fmt, ap);
1604 va_end(ap);
1607 void skip(int c)
1609 if (tok != c)
1610 error("'%c' expected", c);
1611 next();
1614 static void test_lvalue(void)
1616 if (!(vtop->r & VT_LVAL))
1617 expect("lvalue");
1620 /* allocate a new token */
1621 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
1623 TokenSym *ts, **ptable;
1624 int i;
1626 if (tok_ident >= SYM_FIRST_ANOM)
1627 error("memory full");
1629 /* expand token table if needed */
1630 i = tok_ident - TOK_IDENT;
1631 if ((i % TOK_ALLOC_INCR) == 0) {
1632 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
1633 if (!ptable)
1634 error("memory full");
1635 table_ident = ptable;
1638 ts = tcc_malloc(sizeof(TokenSym) + len);
1639 table_ident[i] = ts;
1640 ts->tok = tok_ident++;
1641 ts->sym_define = NULL;
1642 ts->sym_label = NULL;
1643 ts->sym_struct = NULL;
1644 ts->sym_identifier = NULL;
1645 ts->len = len;
1646 ts->hash_next = NULL;
1647 memcpy(ts->str, str, len);
1648 ts->str[len] = '\0';
1649 *pts = ts;
1650 return ts;
1653 #define TOK_HASH_INIT 1
1654 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1656 /* find a token and add it if not found */
1657 static TokenSym *tok_alloc(const char *str, int len)
1659 TokenSym *ts, **pts;
1660 int i;
1661 unsigned int h;
1663 h = TOK_HASH_INIT;
1664 for(i=0;i<len;i++)
1665 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
1666 h &= (TOK_HASH_SIZE - 1);
1668 pts = &hash_ident[h];
1669 for(;;) {
1670 ts = *pts;
1671 if (!ts)
1672 break;
1673 if (ts->len == len && !memcmp(ts->str, str, len))
1674 return ts;
1675 pts = &(ts->hash_next);
1677 return tok_alloc_new(pts, str, len);
1680 /* CString handling */
1682 static void cstr_realloc(CString *cstr, int new_size)
1684 int size;
1685 void *data;
1687 size = cstr->size_allocated;
1688 if (size == 0)
1689 size = 8; /* no need to allocate a too small first string */
1690 while (size < new_size)
1691 size = size * 2;
1692 data = tcc_realloc(cstr->data_allocated, size);
1693 if (!data)
1694 error("memory full");
1695 cstr->data_allocated = data;
1696 cstr->size_allocated = size;
1697 cstr->data = data;
1700 /* add a byte */
1701 static inline void cstr_ccat(CString *cstr, int ch)
1703 int size;
1704 size = cstr->size + 1;
1705 if (size > cstr->size_allocated)
1706 cstr_realloc(cstr, size);
1707 ((unsigned char *)cstr->data)[size - 1] = ch;
1708 cstr->size = size;
1711 static void cstr_cat(CString *cstr, const char *str)
1713 int c;
1714 for(;;) {
1715 c = *str;
1716 if (c == '\0')
1717 break;
1718 cstr_ccat(cstr, c);
1719 str++;
1723 /* add a wide char */
1724 static void cstr_wccat(CString *cstr, int ch)
1726 int size;
1727 size = cstr->size + sizeof(nwchar_t);
1728 if (size > cstr->size_allocated)
1729 cstr_realloc(cstr, size);
1730 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1731 cstr->size = size;
1734 static void cstr_new(CString *cstr)
1736 memset(cstr, 0, sizeof(CString));
1739 /* free string and reset it to NULL */
1740 static void cstr_free(CString *cstr)
1742 tcc_free(cstr->data_allocated);
1743 cstr_new(cstr);
1746 #define cstr_reset(cstr) cstr_free(cstr)
1748 /* XXX: unicode ? */
1749 static void add_char(CString *cstr, int c)
1751 if (c == '\'' || c == '\"' || c == '\\') {
1752 /* XXX: could be more precise if char or string */
1753 cstr_ccat(cstr, '\\');
1755 if (c >= 32 && c <= 126) {
1756 cstr_ccat(cstr, c);
1757 } else {
1758 cstr_ccat(cstr, '\\');
1759 if (c == '\n') {
1760 cstr_ccat(cstr, 'n');
1761 } else {
1762 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1763 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1764 cstr_ccat(cstr, '0' + (c & 7));
1769 /* XXX: buffer overflow */
1770 /* XXX: float tokens */
1771 char *get_tok_str(int v, CValue *cv)
1773 static char buf[STRING_MAX_SIZE + 1];
1774 static CString cstr_buf;
1775 CString *cstr;
1776 unsigned char *q;
1777 char *p;
1778 int i, len;
1780 /* NOTE: to go faster, we give a fixed buffer for small strings */
1781 cstr_reset(&cstr_buf);
1782 cstr_buf.data = buf;
1783 cstr_buf.size_allocated = sizeof(buf);
1784 p = buf;
1786 switch(v) {
1787 case TOK_CINT:
1788 case TOK_CUINT:
1789 /* XXX: not quite exact, but only useful for testing */
1790 sprintf(p, "%u", cv->ui);
1791 break;
1792 case TOK_CLLONG:
1793 case TOK_CULLONG:
1794 /* XXX: not quite exact, but only useful for testing */
1795 sprintf(p, "%Lu", cv->ull);
1796 break;
1797 case TOK_LCHAR:
1798 cstr_ccat(&cstr_buf, 'L');
1799 case TOK_CCHAR:
1800 cstr_ccat(&cstr_buf, '\'');
1801 add_char(&cstr_buf, cv->i);
1802 cstr_ccat(&cstr_buf, '\'');
1803 cstr_ccat(&cstr_buf, '\0');
1804 break;
1805 case TOK_PPNUM:
1806 cstr = cv->cstr;
1807 len = cstr->size - 1;
1808 for(i=0;i<len;i++)
1809 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1810 cstr_ccat(&cstr_buf, '\0');
1811 break;
1812 case TOK_LSTR:
1813 cstr_ccat(&cstr_buf, 'L');
1814 case TOK_STR:
1815 cstr = cv->cstr;
1816 cstr_ccat(&cstr_buf, '\"');
1817 if (v == TOK_STR) {
1818 len = cstr->size - 1;
1819 for(i=0;i<len;i++)
1820 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1821 } else {
1822 len = (cstr->size / sizeof(nwchar_t)) - 1;
1823 for(i=0;i<len;i++)
1824 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
1826 cstr_ccat(&cstr_buf, '\"');
1827 cstr_ccat(&cstr_buf, '\0');
1828 break;
1829 case TOK_LT:
1830 v = '<';
1831 goto addv;
1832 case TOK_GT:
1833 v = '>';
1834 goto addv;
1835 case TOK_DOTS:
1836 return strcpy(p, "...");
1837 case TOK_A_SHL:
1838 return strcpy(p, "<<=");
1839 case TOK_A_SAR:
1840 return strcpy(p, ">>=");
1841 default:
1842 if (v < TOK_IDENT) {
1843 /* search in two bytes table */
1844 q = tok_two_chars;
1845 while (*q) {
1846 if (q[2] == v) {
1847 *p++ = q[0];
1848 *p++ = q[1];
1849 *p = '\0';
1850 return buf;
1852 q += 3;
1854 addv:
1855 *p++ = v;
1856 *p = '\0';
1857 } else if (v < tok_ident) {
1858 return table_ident[v - TOK_IDENT]->str;
1859 } else if (v >= SYM_FIRST_ANOM) {
1860 /* special name for anonymous symbol */
1861 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
1862 } else {
1863 /* should never happen */
1864 return NULL;
1866 break;
1868 return cstr_buf.data;
1871 /* push, without hashing */
1872 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1874 Sym *s;
1875 s = sym_malloc();
1876 s->v = v;
1877 s->type.t = t;
1878 s->c = c;
1879 s->next = NULL;
1880 /* add in stack */
1881 s->prev = *ps;
1882 *ps = s;
1883 return s;
1886 /* find a symbol and return its associated structure. 's' is the top
1887 of the symbol stack */
1888 static Sym *sym_find2(Sym *s, int v)
1890 while (s) {
1891 if (s->v == v)
1892 return s;
1893 s = s->prev;
1895 return NULL;
1898 /* structure lookup */
1899 static inline Sym *struct_find(int v)
1901 v -= TOK_IDENT;
1902 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1903 return NULL;
1904 return table_ident[v]->sym_struct;
1907 /* find an identifier */
1908 static inline Sym *sym_find(int v)
1910 v -= TOK_IDENT;
1911 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1912 return NULL;
1913 return table_ident[v]->sym_identifier;
1916 /* push a given symbol on the symbol stack */
1917 static Sym *sym_push(int v, CType *type, int r, int c)
1919 Sym *s, **ps;
1920 TokenSym *ts;
1922 if (local_stack)
1923 ps = &local_stack;
1924 else
1925 ps = &global_stack;
1926 s = sym_push2(ps, v, type->t, c);
1927 s->type.ref = type->ref;
1928 s->r = r;
1929 /* don't record fields or anonymous symbols */
1930 /* XXX: simplify */
1931 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1932 /* record symbol in token array */
1933 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1934 if (v & SYM_STRUCT)
1935 ps = &ts->sym_struct;
1936 else
1937 ps = &ts->sym_identifier;
1938 s->prev_tok = *ps;
1939 *ps = s;
1941 return s;
1944 /* push a global identifier */
1945 static Sym *global_identifier_push(int v, int t, int c)
1947 Sym *s, **ps;
1948 s = sym_push2(&global_stack, v, t, c);
1949 /* don't record anonymous symbol */
1950 if (v < SYM_FIRST_ANOM) {
1951 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1952 /* modify the top most local identifier, so that
1953 sym_identifier will point to 's' when popped */
1954 while (*ps != NULL)
1955 ps = &(*ps)->prev_tok;
1956 s->prev_tok = NULL;
1957 *ps = s;
1959 return s;
1962 /* pop symbols until top reaches 'b' */
1963 static void sym_pop(Sym **ptop, Sym *b)
1965 Sym *s, *ss, **ps;
1966 TokenSym *ts;
1967 int v;
1969 s = *ptop;
1970 while(s != b) {
1971 ss = s->prev;
1972 v = s->v;
1973 /* remove symbol in token array */
1974 /* XXX: simplify */
1975 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1976 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1977 if (v & SYM_STRUCT)
1978 ps = &ts->sym_struct;
1979 else
1980 ps = &ts->sym_identifier;
1981 *ps = s->prev_tok;
1983 sym_free(s);
1984 s = ss;
1986 *ptop = b;
1989 /* I/O layer */
1991 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1993 int fd;
1994 BufferedFile *bf;
1996 if (strcmp(filename, "-") == 0)
1997 fd = 0, filename = "stdin";
1998 else
1999 fd = open(filename, O_RDONLY | O_BINARY);
2000 if ((verbose == 2 && fd >= 0) || verbose == 3)
2001 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
2002 (s1->include_stack_ptr - s1->include_stack), "", filename);
2003 if (fd < 0)
2004 return NULL;
2005 bf = tcc_malloc(sizeof(BufferedFile));
2006 bf->fd = fd;
2007 bf->buf_ptr = bf->buffer;
2008 bf->buf_end = bf->buffer;
2009 bf->buffer[0] = CH_EOB; /* put eob symbol */
2010 pstrcpy(bf->filename, sizeof(bf->filename), filename);
2011 #ifdef _WIN32
2012 normalize_slashes(bf->filename);
2013 #endif
2014 bf->line_num = 1;
2015 bf->ifndef_macro = 0;
2016 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
2017 // printf("opening '%s'\n", filename);
2018 return bf;
2021 void tcc_close(BufferedFile *bf)
2023 total_lines += bf->line_num;
2024 close(bf->fd);
2025 tcc_free(bf);
2028 /* fill input buffer and peek next char */
2029 static int tcc_peekc_slow(BufferedFile *bf)
2031 int len;
2032 /* only tries to read if really end of buffer */
2033 if (bf->buf_ptr >= bf->buf_end) {
2034 if (bf->fd != -1) {
2035 #if defined(PARSE_DEBUG)
2036 len = 8;
2037 #else
2038 len = IO_BUF_SIZE;
2039 #endif
2040 len = read(bf->fd, bf->buffer, len);
2041 if (len < 0)
2042 len = 0;
2043 } else {
2044 len = 0;
2046 total_bytes += len;
2047 bf->buf_ptr = bf->buffer;
2048 bf->buf_end = bf->buffer + len;
2049 *bf->buf_end = CH_EOB;
2051 if (bf->buf_ptr < bf->buf_end) {
2052 return bf->buf_ptr[0];
2053 } else {
2054 bf->buf_ptr = bf->buf_end;
2055 return CH_EOF;
2059 /* return the current character, handling end of block if necessary
2060 (but not stray) */
2061 static int handle_eob(void)
2063 return tcc_peekc_slow(file);
2066 /* read next char from current input file and handle end of input buffer */
2067 static inline void inp(void)
2069 ch = *(++(file->buf_ptr));
2070 /* end of buffer/file handling */
2071 if (ch == CH_EOB)
2072 ch = handle_eob();
2075 /* handle '\[\r]\n' */
2076 static int handle_stray_noerror(void)
2078 while (ch == '\\') {
2079 inp();
2080 if (ch == '\n') {
2081 file->line_num++;
2082 inp();
2083 } else if (ch == '\r') {
2084 inp();
2085 if (ch != '\n')
2086 goto fail;
2087 file->line_num++;
2088 inp();
2089 } else {
2090 fail:
2091 return 1;
2094 return 0;
2097 static void handle_stray(void)
2099 if (handle_stray_noerror())
2100 error("stray '\\' in program");
2103 /* skip the stray and handle the \\n case. Output an error if
2104 incorrect char after the stray */
2105 static int handle_stray1(uint8_t *p)
2107 int c;
2109 if (p >= file->buf_end) {
2110 file->buf_ptr = p;
2111 c = handle_eob();
2112 p = file->buf_ptr;
2113 if (c == '\\')
2114 goto parse_stray;
2115 } else {
2116 parse_stray:
2117 file->buf_ptr = p;
2118 ch = *p;
2119 handle_stray();
2120 p = file->buf_ptr;
2121 c = *p;
2123 return c;
2126 /* handle just the EOB case, but not stray */
2127 #define PEEKC_EOB(c, p)\
2129 p++;\
2130 c = *p;\
2131 if (c == '\\') {\
2132 file->buf_ptr = p;\
2133 c = handle_eob();\
2134 p = file->buf_ptr;\
2138 /* handle the complicated stray case */
2139 #define PEEKC(c, p)\
2141 p++;\
2142 c = *p;\
2143 if (c == '\\') {\
2144 c = handle_stray1(p);\
2145 p = file->buf_ptr;\
2149 /* input with '\[\r]\n' handling. Note that this function cannot
2150 handle other characters after '\', so you cannot call it inside
2151 strings or comments */
2152 static void minp(void)
2154 inp();
2155 if (ch == '\\')
2156 handle_stray();
2160 /* single line C++ comments */
2161 static uint8_t *parse_line_comment(uint8_t *p)
2163 int c;
2165 p++;
2166 for(;;) {
2167 c = *p;
2168 redo:
2169 if (c == '\n' || c == CH_EOF) {
2170 break;
2171 } else if (c == '\\') {
2172 file->buf_ptr = p;
2173 c = handle_eob();
2174 p = file->buf_ptr;
2175 if (c == '\\') {
2176 PEEKC_EOB(c, p);
2177 if (c == '\n') {
2178 file->line_num++;
2179 PEEKC_EOB(c, p);
2180 } else if (c == '\r') {
2181 PEEKC_EOB(c, p);
2182 if (c == '\n') {
2183 file->line_num++;
2184 PEEKC_EOB(c, p);
2187 } else {
2188 goto redo;
2190 } else {
2191 p++;
2194 return p;
2197 /* C comments */
2198 static uint8_t *parse_comment(uint8_t *p)
2200 int c;
2202 p++;
2203 for(;;) {
2204 /* fast skip loop */
2205 for(;;) {
2206 c = *p;
2207 if (c == '\n' || c == '*' || c == '\\')
2208 break;
2209 p++;
2210 c = *p;
2211 if (c == '\n' || c == '*' || c == '\\')
2212 break;
2213 p++;
2215 /* now we can handle all the cases */
2216 if (c == '\n') {
2217 file->line_num++;
2218 p++;
2219 } else if (c == '*') {
2220 p++;
2221 for(;;) {
2222 c = *p;
2223 if (c == '*') {
2224 p++;
2225 } else if (c == '/') {
2226 goto end_of_comment;
2227 } else if (c == '\\') {
2228 file->buf_ptr = p;
2229 c = handle_eob();
2230 p = file->buf_ptr;
2231 if (c == '\\') {
2232 /* skip '\[\r]\n', otherwise just skip the stray */
2233 while (c == '\\') {
2234 PEEKC_EOB(c, p);
2235 if (c == '\n') {
2236 file->line_num++;
2237 PEEKC_EOB(c, p);
2238 } else if (c == '\r') {
2239 PEEKC_EOB(c, p);
2240 if (c == '\n') {
2241 file->line_num++;
2242 PEEKC_EOB(c, p);
2244 } else {
2245 goto after_star;
2249 } else {
2250 break;
2253 after_star: ;
2254 } else {
2255 /* stray, eob or eof */
2256 file->buf_ptr = p;
2257 c = handle_eob();
2258 p = file->buf_ptr;
2259 if (c == CH_EOF) {
2260 error("unexpected end of file in comment");
2261 } else if (c == '\\') {
2262 p++;
2266 end_of_comment:
2267 p++;
2268 return p;
2271 #define cinp minp
2273 /* space exlcuding newline */
2274 static inline int is_space(int ch)
2276 return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
2279 static inline void skip_spaces(void)
2281 while (is_space(ch))
2282 cinp();
2285 /* parse a string without interpreting escapes */
2286 static uint8_t *parse_pp_string(uint8_t *p,
2287 int sep, CString *str)
2289 int c;
2290 p++;
2291 for(;;) {
2292 c = *p;
2293 if (c == sep) {
2294 break;
2295 } else if (c == '\\') {
2296 file->buf_ptr = p;
2297 c = handle_eob();
2298 p = file->buf_ptr;
2299 if (c == CH_EOF) {
2300 unterminated_string:
2301 /* XXX: indicate line number of start of string */
2302 error("missing terminating %c character", sep);
2303 } else if (c == '\\') {
2304 /* escape : just skip \[\r]\n */
2305 PEEKC_EOB(c, p);
2306 if (c == '\n') {
2307 file->line_num++;
2308 p++;
2309 } else if (c == '\r') {
2310 PEEKC_EOB(c, p);
2311 if (c != '\n')
2312 expect("'\n' after '\r'");
2313 file->line_num++;
2314 p++;
2315 } else if (c == CH_EOF) {
2316 goto unterminated_string;
2317 } else {
2318 if (str) {
2319 cstr_ccat(str, '\\');
2320 cstr_ccat(str, c);
2322 p++;
2325 } else if (c == '\n') {
2326 file->line_num++;
2327 goto add_char;
2328 } else if (c == '\r') {
2329 PEEKC_EOB(c, p);
2330 if (c != '\n') {
2331 if (str)
2332 cstr_ccat(str, '\r');
2333 } else {
2334 file->line_num++;
2335 goto add_char;
2337 } else {
2338 add_char:
2339 if (str)
2340 cstr_ccat(str, c);
2341 p++;
2344 p++;
2345 return p;
2348 /* skip block of text until #else, #elif or #endif. skip also pairs of
2349 #if/#endif */
2350 void preprocess_skip(void)
2352 int a, start_of_line, c, in_warn_or_error;
2353 uint8_t *p;
2355 p = file->buf_ptr;
2356 a = 0;
2357 redo_start:
2358 start_of_line = 1;
2359 in_warn_or_error = 0;
2360 for(;;) {
2361 redo_no_start:
2362 c = *p;
2363 switch(c) {
2364 case ' ':
2365 case '\t':
2366 case '\f':
2367 case '\v':
2368 case '\r':
2369 p++;
2370 goto redo_no_start;
2371 case '\n':
2372 file->line_num++;
2373 p++;
2374 goto redo_start;
2375 case '\\':
2376 file->buf_ptr = p;
2377 c = handle_eob();
2378 if (c == CH_EOF) {
2379 expect("#endif");
2380 } else if (c == '\\') {
2381 ch = file->buf_ptr[0];
2382 handle_stray_noerror();
2384 p = file->buf_ptr;
2385 goto redo_no_start;
2386 /* skip strings */
2387 case '\"':
2388 case '\'':
2389 if (in_warn_or_error)
2390 goto _default;
2391 p = parse_pp_string(p, c, NULL);
2392 break;
2393 /* skip comments */
2394 case '/':
2395 if (in_warn_or_error)
2396 goto _default;
2397 file->buf_ptr = p;
2398 ch = *p;
2399 minp();
2400 p = file->buf_ptr;
2401 if (ch == '*') {
2402 p = parse_comment(p);
2403 } else if (ch == '/') {
2404 p = parse_line_comment(p);
2406 break;
2407 case '#':
2408 p++;
2409 if (start_of_line) {
2410 file->buf_ptr = p;
2411 next_nomacro();
2412 p = file->buf_ptr;
2413 if (a == 0 &&
2414 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
2415 goto the_end;
2416 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
2417 a++;
2418 else if (tok == TOK_ENDIF)
2419 a--;
2420 else if( tok == TOK_ERROR || tok == TOK_WARNING)
2421 in_warn_or_error = 1;
2423 break;
2424 _default:
2425 default:
2426 p++;
2427 break;
2429 start_of_line = 0;
2431 the_end: ;
2432 file->buf_ptr = p;
2435 /* ParseState handling */
2437 /* XXX: currently, no include file info is stored. Thus, we cannot display
2438 accurate messages if the function or data definition spans multiple
2439 files */
2441 /* save current parse state in 's' */
2442 void save_parse_state(ParseState *s)
2444 s->line_num = file->line_num;
2445 s->macro_ptr = macro_ptr;
2446 s->tok = tok;
2447 s->tokc = tokc;
2450 /* restore parse state from 's' */
2451 void restore_parse_state(ParseState *s)
2453 file->line_num = s->line_num;
2454 macro_ptr = s->macro_ptr;
2455 tok = s->tok;
2456 tokc = s->tokc;
2459 /* return the number of additional 'ints' necessary to store the
2460 token */
2461 static inline int tok_ext_size(int t)
2463 switch(t) {
2464 /* 4 bytes */
2465 case TOK_CINT:
2466 case TOK_CUINT:
2467 case TOK_CCHAR:
2468 case TOK_LCHAR:
2469 case TOK_CFLOAT:
2470 case TOK_LINENUM:
2471 return 1;
2472 case TOK_STR:
2473 case TOK_LSTR:
2474 case TOK_PPNUM:
2475 error("unsupported token");
2476 return 1;
2477 case TOK_CDOUBLE:
2478 case TOK_CLLONG:
2479 case TOK_CULLONG:
2480 return 2;
2481 case TOK_CLDOUBLE:
2482 return LDOUBLE_SIZE / 4;
2483 default:
2484 return 0;
2488 /* token string handling */
2490 static inline void tok_str_new(TokenString *s)
2492 s->str = NULL;
2493 s->len = 0;
2494 s->allocated_len = 0;
2495 s->last_line_num = -1;
2498 static void tok_str_free(int *str)
2500 tcc_free(str);
2503 static int *tok_str_realloc(TokenString *s)
2505 int *str, len;
2507 if (s->allocated_len == 0) {
2508 len = 8;
2509 } else {
2510 len = s->allocated_len * 2;
2512 str = tcc_realloc(s->str, len * sizeof(int));
2513 if (!str)
2514 error("memory full");
2515 s->allocated_len = len;
2516 s->str = str;
2517 return str;
2520 static void tok_str_add(TokenString *s, int t)
2522 int len, *str;
2524 len = s->len;
2525 str = s->str;
2526 if (len >= s->allocated_len)
2527 str = tok_str_realloc(s);
2528 str[len++] = t;
2529 s->len = len;
2532 static void tok_str_add2(TokenString *s, int t, CValue *cv)
2534 int len, *str;
2536 len = s->len;
2537 str = s->str;
2539 /* allocate space for worst case */
2540 if (len + TOK_MAX_SIZE > s->allocated_len)
2541 str = tok_str_realloc(s);
2542 str[len++] = t;
2543 switch(t) {
2544 case TOK_CINT:
2545 case TOK_CUINT:
2546 case TOK_CCHAR:
2547 case TOK_LCHAR:
2548 case TOK_CFLOAT:
2549 case TOK_LINENUM:
2550 str[len++] = cv->tab[0];
2551 break;
2552 case TOK_PPNUM:
2553 case TOK_STR:
2554 case TOK_LSTR:
2556 int nb_words;
2557 CString *cstr;
2559 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
2560 while ((len + nb_words) > s->allocated_len)
2561 str = tok_str_realloc(s);
2562 cstr = (CString *)(str + len);
2563 cstr->data = NULL;
2564 cstr->size = cv->cstr->size;
2565 cstr->data_allocated = NULL;
2566 cstr->size_allocated = cstr->size;
2567 memcpy((char *)cstr + sizeof(CString),
2568 cv->cstr->data, cstr->size);
2569 len += nb_words;
2571 break;
2572 case TOK_CDOUBLE:
2573 case TOK_CLLONG:
2574 case TOK_CULLONG:
2575 #if LDOUBLE_SIZE == 8
2576 case TOK_CLDOUBLE:
2577 #endif
2578 str[len++] = cv->tab[0];
2579 str[len++] = cv->tab[1];
2580 break;
2581 #if LDOUBLE_SIZE == 12
2582 case TOK_CLDOUBLE:
2583 str[len++] = cv->tab[0];
2584 str[len++] = cv->tab[1];
2585 str[len++] = cv->tab[2];
2586 #elif LDOUBLE_SIZE == 16
2587 case TOK_CLDOUBLE:
2588 str[len++] = cv->tab[0];
2589 str[len++] = cv->tab[1];
2590 str[len++] = cv->tab[2];
2591 str[len++] = cv->tab[3];
2592 #elif LDOUBLE_SIZE != 8
2593 #error add long double size support
2594 #endif
2595 break;
2596 default:
2597 break;
2599 s->len = len;
2602 /* add the current parse token in token string 's' */
2603 static void tok_str_add_tok(TokenString *s)
2605 CValue cval;
2607 /* save line number info */
2608 if (file->line_num != s->last_line_num) {
2609 s->last_line_num = file->line_num;
2610 cval.i = s->last_line_num;
2611 tok_str_add2(s, TOK_LINENUM, &cval);
2613 tok_str_add2(s, tok, &tokc);
2616 #if LDOUBLE_SIZE == 16
2617 #define LDOUBLE_GET(p, cv) \
2618 cv.tab[0] = p[0]; \
2619 cv.tab[1] = p[1]; \
2620 cv.tab[2] = p[2]; \
2621 cv.tab[3] = p[3];
2622 #elif LDOUBLE_SIZE == 12
2623 #define LDOUBLE_GET(p, cv) \
2624 cv.tab[0] = p[0]; \
2625 cv.tab[1] = p[1]; \
2626 cv.tab[2] = p[2];
2627 #elif LDOUBLE_SIZE == 8
2628 #define LDOUBLE_GET(p, cv) \
2629 cv.tab[0] = p[0]; \
2630 cv.tab[1] = p[1];
2631 #else
2632 #error add long double size support
2633 #endif
2636 /* get a token from an integer array and increment pointer
2637 accordingly. we code it as a macro to avoid pointer aliasing. */
2638 #define TOK_GET(t, p, cv) \
2640 t = *p++; \
2641 switch(t) { \
2642 case TOK_CINT: \
2643 case TOK_CUINT: \
2644 case TOK_CCHAR: \
2645 case TOK_LCHAR: \
2646 case TOK_CFLOAT: \
2647 case TOK_LINENUM: \
2648 cv.tab[0] = *p++; \
2649 break; \
2650 case TOK_STR: \
2651 case TOK_LSTR: \
2652 case TOK_PPNUM: \
2653 cv.cstr = (CString *)p; \
2654 cv.cstr->data = (char *)p + sizeof(CString);\
2655 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2656 break; \
2657 case TOK_CDOUBLE: \
2658 case TOK_CLLONG: \
2659 case TOK_CULLONG: \
2660 cv.tab[0] = p[0]; \
2661 cv.tab[1] = p[1]; \
2662 p += 2; \
2663 break; \
2664 case TOK_CLDOUBLE: \
2665 LDOUBLE_GET(p, cv); \
2666 p += LDOUBLE_SIZE / 4; \
2667 break; \
2668 default: \
2669 break; \
2673 /* defines handling */
2674 static inline void define_push(int v, int macro_type, int *str, Sym *first_arg)
2676 Sym *s;
2678 s = sym_push2(&define_stack, v, macro_type, (long)str);
2679 s->next = first_arg;
2680 table_ident[v - TOK_IDENT]->sym_define = s;
2683 /* undefined a define symbol. Its name is just set to zero */
2684 static void define_undef(Sym *s)
2686 int v;
2687 v = s->v;
2688 if (v >= TOK_IDENT && v < tok_ident)
2689 table_ident[v - TOK_IDENT]->sym_define = NULL;
2690 s->v = 0;
2693 static inline Sym *define_find(int v)
2695 v -= TOK_IDENT;
2696 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2697 return NULL;
2698 return table_ident[v]->sym_define;
2701 /* free define stack until top reaches 'b' */
2702 static void free_defines(Sym *b)
2704 Sym *top, *top1;
2705 int v;
2707 top = define_stack;
2708 while (top != b) {
2709 top1 = top->prev;
2710 /* do not free args or predefined defines */
2711 if (top->c)
2712 tok_str_free((int *)top->c);
2713 v = top->v;
2714 if (v >= TOK_IDENT && v < tok_ident)
2715 table_ident[v - TOK_IDENT]->sym_define = NULL;
2716 sym_free(top);
2717 top = top1;
2719 define_stack = b;
2722 /* label lookup */
2723 static Sym *label_find(int v)
2725 v -= TOK_IDENT;
2726 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2727 return NULL;
2728 return table_ident[v]->sym_label;
2731 static Sym *label_push(Sym **ptop, int v, int flags)
2733 Sym *s, **ps;
2734 s = sym_push2(ptop, v, 0, 0);
2735 s->r = flags;
2736 ps = &table_ident[v - TOK_IDENT]->sym_label;
2737 if (ptop == &global_label_stack) {
2738 /* modify the top most local identifier, so that
2739 sym_identifier will point to 's' when popped */
2740 while (*ps != NULL)
2741 ps = &(*ps)->prev_tok;
2743 s->prev_tok = *ps;
2744 *ps = s;
2745 return s;
2748 /* pop labels until element last is reached. Look if any labels are
2749 undefined. Define symbols if '&&label' was used. */
2750 static void label_pop(Sym **ptop, Sym *slast)
2752 Sym *s, *s1;
2753 for(s = *ptop; s != slast; s = s1) {
2754 s1 = s->prev;
2755 if (s->r == LABEL_DECLARED) {
2756 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
2757 } else if (s->r == LABEL_FORWARD) {
2758 error("label '%s' used but not defined",
2759 get_tok_str(s->v, NULL));
2760 } else {
2761 if (s->c) {
2762 /* define corresponding symbol. A size of
2763 1 is put. */
2764 put_extern_sym(s, cur_text_section, (long)s->next, 1);
2767 /* remove label */
2768 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
2769 sym_free(s);
2771 *ptop = slast;
2774 /* eval an expression for #if/#elif */
2775 static int expr_preprocess(void)
2777 int c, t;
2778 TokenString str;
2780 tok_str_new(&str);
2781 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2782 next(); /* do macro subst */
2783 if (tok == TOK_DEFINED) {
2784 next_nomacro();
2785 t = tok;
2786 if (t == '(')
2787 next_nomacro();
2788 c = define_find(tok) != 0;
2789 if (t == '(')
2790 next_nomacro();
2791 tok = TOK_CINT;
2792 tokc.i = c;
2793 } else if (tok >= TOK_IDENT) {
2794 /* if undefined macro */
2795 tok = TOK_CINT;
2796 tokc.i = 0;
2798 tok_str_add_tok(&str);
2800 tok_str_add(&str, -1); /* simulate end of file */
2801 tok_str_add(&str, 0);
2802 /* now evaluate C constant expression */
2803 macro_ptr = str.str;
2804 next();
2805 c = expr_const();
2806 macro_ptr = NULL;
2807 tok_str_free(str.str);
2808 return c != 0;
2811 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2812 static void tok_print(int *str)
2814 int t;
2815 CValue cval;
2817 while (1) {
2818 TOK_GET(t, str, cval);
2819 if (!t)
2820 break;
2821 printf(" %s", get_tok_str(t, &cval));
2823 printf("\n");
2825 #endif
2827 /* parse after #define */
2828 static void parse_define(void)
2830 Sym *s, *first, **ps;
2831 int v, t, varg, is_vaargs, c;
2832 TokenString str;
2834 v = tok;
2835 if (v < TOK_IDENT)
2836 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
2837 /* XXX: should check if same macro (ANSI) */
2838 first = NULL;
2839 t = MACRO_OBJ;
2840 /* '(' must be just after macro definition for MACRO_FUNC */
2841 c = file->buf_ptr[0];
2842 if (c == '\\')
2843 c = handle_stray1(file->buf_ptr);
2844 if (c == '(') {
2845 next_nomacro();
2846 next_nomacro();
2847 ps = &first;
2848 while (tok != ')') {
2849 varg = tok;
2850 next_nomacro();
2851 is_vaargs = 0;
2852 if (varg == TOK_DOTS) {
2853 varg = TOK___VA_ARGS__;
2854 is_vaargs = 1;
2855 } else if (tok == TOK_DOTS && gnu_ext) {
2856 is_vaargs = 1;
2857 next_nomacro();
2859 if (varg < TOK_IDENT)
2860 error("badly punctuated parameter list");
2861 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
2862 *ps = s;
2863 ps = &s->next;
2864 if (tok != ',')
2865 break;
2866 next_nomacro();
2868 t = MACRO_FUNC;
2870 tok_str_new(&str);
2871 next_nomacro();
2872 /* EOF testing necessary for '-D' handling */
2873 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2874 tok_str_add2(&str, tok, &tokc);
2875 next_nomacro();
2877 tok_str_add(&str, 0);
2878 #ifdef PP_DEBUG
2879 printf("define %s %d: ", get_tok_str(v, NULL), t);
2880 tok_print(str.str);
2881 #endif
2882 define_push(v, t, str.str, first);
2885 static inline int hash_cached_include(int type, const char *filename)
2887 const unsigned char *s;
2888 unsigned int h;
2890 h = TOK_HASH_INIT;
2891 h = TOK_HASH_FUNC(h, type);
2892 s = filename;
2893 while (*s) {
2894 h = TOK_HASH_FUNC(h, *s);
2895 s++;
2897 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
2898 return h;
2901 /* XXX: use a token or a hash table to accelerate matching ? */
2902 static CachedInclude *search_cached_include(TCCState *s1,
2903 int type, const char *filename)
2905 CachedInclude *e;
2906 int i, h;
2907 h = hash_cached_include(type, filename);
2908 i = s1->cached_includes_hash[h];
2909 for(;;) {
2910 if (i == 0)
2911 break;
2912 e = s1->cached_includes[i - 1];
2913 if (e->type == type && !PATHCMP(e->filename, filename))
2914 return e;
2915 i = e->hash_next;
2917 return NULL;
2920 static inline void add_cached_include(TCCState *s1, int type,
2921 const char *filename, int ifndef_macro)
2923 CachedInclude *e;
2924 int h;
2926 if (search_cached_include(s1, type, filename))
2927 return;
2928 #ifdef INC_DEBUG
2929 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
2930 #endif
2931 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
2932 if (!e)
2933 return;
2934 e->type = type;
2935 strcpy(e->filename, filename);
2936 e->ifndef_macro = ifndef_macro;
2937 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
2938 /* add in hash table */
2939 h = hash_cached_include(type, filename);
2940 e->hash_next = s1->cached_includes_hash[h];
2941 s1->cached_includes_hash[h] = s1->nb_cached_includes;
2944 static void pragma_parse(TCCState *s1)
2946 int val;
2948 next();
2949 if (tok == TOK_pack) {
2951 This may be:
2952 #pragma pack(1) // set
2953 #pragma pack() // reset to default
2954 #pragma pack(push,1) // push & set
2955 #pragma pack(pop) // restore previous
2957 next();
2958 skip('(');
2959 if (tok == TOK_ASM_pop) {
2960 next();
2961 if (s1->pack_stack_ptr <= s1->pack_stack) {
2962 stk_error:
2963 error("out of pack stack");
2965 s1->pack_stack_ptr--;
2966 } else {
2967 val = 0;
2968 if (tok != ')') {
2969 if (tok == TOK_ASM_push) {
2970 next();
2971 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
2972 goto stk_error;
2973 s1->pack_stack_ptr++;
2974 skip(',');
2976 if (tok != TOK_CINT) {
2977 pack_error:
2978 error("invalid pack pragma");
2980 val = tokc.i;
2981 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
2982 goto pack_error;
2983 next();
2985 *s1->pack_stack_ptr = val;
2986 skip(')');
2991 /* is_bof is true if first non space token at beginning of file */
2992 static void preprocess(int is_bof)
2994 TCCState *s1 = tcc_state;
2995 int size, i, c, n, saved_parse_flags;
2996 char buf[1024], *q;
2997 char buf1[1024];
2998 BufferedFile *f;
2999 Sym *s;
3000 CachedInclude *e;
3002 saved_parse_flags = parse_flags;
3003 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
3004 PARSE_FLAG_LINEFEED;
3005 next_nomacro();
3006 redo:
3007 switch(tok) {
3008 case TOK_DEFINE:
3009 next_nomacro();
3010 parse_define();
3011 break;
3012 case TOK_UNDEF:
3013 next_nomacro();
3014 s = define_find(tok);
3015 /* undefine symbol by putting an invalid name */
3016 if (s)
3017 define_undef(s);
3018 break;
3019 case TOK_INCLUDE:
3020 case TOK_INCLUDE_NEXT:
3021 ch = file->buf_ptr[0];
3022 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3023 skip_spaces();
3024 if (ch == '<') {
3025 c = '>';
3026 goto read_name;
3027 } else if (ch == '\"') {
3028 c = ch;
3029 read_name:
3030 inp();
3031 q = buf;
3032 while (ch != c && ch != '\n' && ch != CH_EOF) {
3033 if ((q - buf) < sizeof(buf) - 1)
3034 *q++ = ch;
3035 if (ch == '\\') {
3036 if (handle_stray_noerror() == 0)
3037 --q;
3038 } else
3039 inp();
3041 *q = '\0';
3042 minp();
3043 #if 0
3044 /* eat all spaces and comments after include */
3045 /* XXX: slightly incorrect */
3046 while (ch1 != '\n' && ch1 != CH_EOF)
3047 inp();
3048 #endif
3049 } else {
3050 /* computed #include : either we have only strings or
3051 we have anything enclosed in '<>' */
3052 next();
3053 buf[0] = '\0';
3054 if (tok == TOK_STR) {
3055 while (tok != TOK_LINEFEED) {
3056 if (tok != TOK_STR) {
3057 include_syntax:
3058 error("'#include' expects \"FILENAME\" or <FILENAME>");
3060 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
3061 next();
3063 c = '\"';
3064 } else {
3065 int len;
3066 while (tok != TOK_LINEFEED) {
3067 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
3068 next();
3070 len = strlen(buf);
3071 /* check syntax and remove '<>' */
3072 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
3073 goto include_syntax;
3074 memmove(buf, buf + 1, len - 2);
3075 buf[len - 2] = '\0';
3076 c = '>';
3080 e = search_cached_include(s1, c, buf);
3081 if (e && define_find(e->ifndef_macro)) {
3082 /* no need to parse the include because the 'ifndef macro'
3083 is defined */
3084 #ifdef INC_DEBUG
3085 printf("%s: skipping %s\n", file->filename, buf);
3086 #endif
3087 } else {
3088 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
3089 error("#include recursion too deep");
3090 /* push current file in stack */
3091 /* XXX: fix current line init */
3092 *s1->include_stack_ptr++ = file;
3094 /* check absolute include path */
3095 if (IS_ABSPATH(buf)) {
3096 f = tcc_open(s1, buf);
3097 if (f)
3098 goto found;
3100 if (c == '\"') {
3101 /* first search in current dir if "header.h" */
3102 size = tcc_basename(file->filename) - file->filename;
3103 if (size > sizeof(buf1) - 1)
3104 size = sizeof(buf1) - 1;
3105 memcpy(buf1, file->filename, size);
3106 buf1[size] = '\0';
3107 pstrcat(buf1, sizeof(buf1), buf);
3108 f = tcc_open(s1, buf1);
3109 if (f) {
3110 if (tok == TOK_INCLUDE_NEXT)
3111 tok = TOK_INCLUDE;
3112 else
3113 goto found;
3116 /* now search in all the include paths */
3117 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
3118 for(i = 0; i < n; i++) {
3119 const char *path;
3120 if (i < s1->nb_include_paths)
3121 path = s1->include_paths[i];
3122 else
3123 path = s1->sysinclude_paths[i - s1->nb_include_paths];
3124 pstrcpy(buf1, sizeof(buf1), path);
3125 pstrcat(buf1, sizeof(buf1), "/");
3126 pstrcat(buf1, sizeof(buf1), buf);
3127 f = tcc_open(s1, buf1);
3128 if (f) {
3129 if (tok == TOK_INCLUDE_NEXT)
3130 tok = TOK_INCLUDE;
3131 else
3132 goto found;
3135 --s1->include_stack_ptr;
3136 error("include file '%s' not found", buf);
3137 break;
3138 found:
3139 #ifdef INC_DEBUG
3140 printf("%s: including %s\n", file->filename, buf1);
3141 #endif
3142 f->inc_type = c;
3143 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf);
3144 file = f;
3145 /* add include file debug info */
3146 if (do_debug) {
3147 put_stabs(file->filename, N_BINCL, 0, 0, 0);
3149 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
3150 ch = file->buf_ptr[0];
3151 goto the_end;
3153 break;
3154 case TOK_IFNDEF:
3155 c = 1;
3156 goto do_ifdef;
3157 case TOK_IF:
3158 c = expr_preprocess();
3159 goto do_if;
3160 case TOK_IFDEF:
3161 c = 0;
3162 do_ifdef:
3163 next_nomacro();
3164 if (tok < TOK_IDENT)
3165 error("invalid argument for '#if%sdef'", c ? "n" : "");
3166 if (is_bof) {
3167 if (c) {
3168 #ifdef INC_DEBUG
3169 printf("#ifndef %s\n", get_tok_str(tok, NULL));
3170 #endif
3171 file->ifndef_macro = tok;
3174 c = (define_find(tok) != 0) ^ c;
3175 do_if:
3176 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
3177 error("memory full");
3178 *s1->ifdef_stack_ptr++ = c;
3179 goto test_skip;
3180 case TOK_ELSE:
3181 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3182 error("#else without matching #if");
3183 if (s1->ifdef_stack_ptr[-1] & 2)
3184 error("#else after #else");
3185 c = (s1->ifdef_stack_ptr[-1] ^= 3);
3186 goto test_skip;
3187 case TOK_ELIF:
3188 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3189 error("#elif without matching #if");
3190 c = s1->ifdef_stack_ptr[-1];
3191 if (c > 1)
3192 error("#elif after #else");
3193 /* last #if/#elif expression was true: we skip */
3194 if (c == 1)
3195 goto skip;
3196 c = expr_preprocess();
3197 s1->ifdef_stack_ptr[-1] = c;
3198 test_skip:
3199 if (!(c & 1)) {
3200 skip:
3201 preprocess_skip();
3202 is_bof = 0;
3203 goto redo;
3205 break;
3206 case TOK_ENDIF:
3207 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
3208 error("#endif without matching #if");
3209 s1->ifdef_stack_ptr--;
3210 /* '#ifndef macro' was at the start of file. Now we check if
3211 an '#endif' is exactly at the end of file */
3212 if (file->ifndef_macro &&
3213 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
3214 file->ifndef_macro_saved = file->ifndef_macro;
3215 /* need to set to zero to avoid false matches if another
3216 #ifndef at middle of file */
3217 file->ifndef_macro = 0;
3218 while (tok != TOK_LINEFEED)
3219 next_nomacro();
3220 tok_flags |= TOK_FLAG_ENDIF;
3221 goto the_end;
3223 break;
3224 case TOK_LINE:
3225 next();
3226 if (tok != TOK_CINT)
3227 error("#line");
3228 file->line_num = tokc.i - 1; /* the line number will be incremented after */
3229 next();
3230 if (tok != TOK_LINEFEED) {
3231 if (tok != TOK_STR)
3232 error("#line");
3233 pstrcpy(file->filename, sizeof(file->filename),
3234 (char *)tokc.cstr->data);
3236 break;
3237 case TOK_ERROR:
3238 case TOK_WARNING:
3239 c = tok;
3240 ch = file->buf_ptr[0];
3241 skip_spaces();
3242 q = buf;
3243 while (ch != '\n' && ch != CH_EOF) {
3244 if ((q - buf) < sizeof(buf) - 1)
3245 *q++ = ch;
3246 if (ch == '\\') {
3247 if (handle_stray_noerror() == 0)
3248 --q;
3249 } else
3250 inp();
3252 *q = '\0';
3253 if (c == TOK_ERROR)
3254 error("#error %s", buf);
3255 else
3256 warning("#warning %s", buf);
3257 break;
3258 case TOK_PRAGMA:
3259 pragma_parse(s1);
3260 break;
3261 default:
3262 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
3263 /* '!' is ignored to allow C scripts. numbers are ignored
3264 to emulate cpp behaviour */
3265 } else {
3266 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
3267 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
3269 break;
3271 /* ignore other preprocess commands or #! for C scripts */
3272 while (tok != TOK_LINEFEED)
3273 next_nomacro();
3274 the_end:
3275 parse_flags = saved_parse_flags;
3278 /* evaluate escape codes in a string. */
3279 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
3281 int c, n;
3282 const uint8_t *p;
3284 p = buf;
3285 for(;;) {
3286 c = *p;
3287 if (c == '\0')
3288 break;
3289 if (c == '\\') {
3290 p++;
3291 /* escape */
3292 c = *p;
3293 switch(c) {
3294 case '0': case '1': case '2': case '3':
3295 case '4': case '5': case '6': case '7':
3296 /* at most three octal digits */
3297 n = c - '0';
3298 p++;
3299 c = *p;
3300 if (isoct(c)) {
3301 n = n * 8 + c - '0';
3302 p++;
3303 c = *p;
3304 if (isoct(c)) {
3305 n = n * 8 + c - '0';
3306 p++;
3309 c = n;
3310 goto add_char_nonext;
3311 case 'x':
3312 case 'u':
3313 case 'U':
3314 p++;
3315 n = 0;
3316 for(;;) {
3317 c = *p;
3318 if (c >= 'a' && c <= 'f')
3319 c = c - 'a' + 10;
3320 else if (c >= 'A' && c <= 'F')
3321 c = c - 'A' + 10;
3322 else if (isnum(c))
3323 c = c - '0';
3324 else
3325 break;
3326 n = n * 16 + c;
3327 p++;
3329 c = n;
3330 goto add_char_nonext;
3331 case 'a':
3332 c = '\a';
3333 break;
3334 case 'b':
3335 c = '\b';
3336 break;
3337 case 'f':
3338 c = '\f';
3339 break;
3340 case 'n':
3341 c = '\n';
3342 break;
3343 case 'r':
3344 c = '\r';
3345 break;
3346 case 't':
3347 c = '\t';
3348 break;
3349 case 'v':
3350 c = '\v';
3351 break;
3352 case 'e':
3353 if (!gnu_ext)
3354 goto invalid_escape;
3355 c = 27;
3356 break;
3357 case '\'':
3358 case '\"':
3359 case '\\':
3360 case '?':
3361 break;
3362 default:
3363 invalid_escape:
3364 if (c >= '!' && c <= '~')
3365 warning("unknown escape sequence: \'\\%c\'", c);
3366 else
3367 warning("unknown escape sequence: \'\\x%x\'", c);
3368 break;
3371 p++;
3372 add_char_nonext:
3373 if (!is_long)
3374 cstr_ccat(outstr, c);
3375 else
3376 cstr_wccat(outstr, c);
3378 /* add a trailing '\0' */
3379 if (!is_long)
3380 cstr_ccat(outstr, '\0');
3381 else
3382 cstr_wccat(outstr, '\0');
3385 /* we use 64 bit numbers */
3386 #define BN_SIZE 2
3388 /* bn = (bn << shift) | or_val */
3389 void bn_lshift(unsigned int *bn, int shift, int or_val)
3391 int i;
3392 unsigned int v;
3393 for(i=0;i<BN_SIZE;i++) {
3394 v = bn[i];
3395 bn[i] = (v << shift) | or_val;
3396 or_val = v >> (32 - shift);
3400 void bn_zero(unsigned int *bn)
3402 int i;
3403 for(i=0;i<BN_SIZE;i++) {
3404 bn[i] = 0;
3408 /* parse number in null terminated string 'p' and return it in the
3409 current token */
3410 void parse_number(const char *p)
3412 int b, t, shift, frac_bits, s, exp_val, ch;
3413 char *q;
3414 unsigned int bn[BN_SIZE];
3415 double d;
3417 /* number */
3418 q = token_buf;
3419 ch = *p++;
3420 t = ch;
3421 ch = *p++;
3422 *q++ = t;
3423 b = 10;
3424 if (t == '.') {
3425 goto float_frac_parse;
3426 } else if (t == '0') {
3427 if (ch == 'x' || ch == 'X') {
3428 q--;
3429 ch = *p++;
3430 b = 16;
3431 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
3432 q--;
3433 ch = *p++;
3434 b = 2;
3437 /* parse all digits. cannot check octal numbers at this stage
3438 because of floating point constants */
3439 while (1) {
3440 if (ch >= 'a' && ch <= 'f')
3441 t = ch - 'a' + 10;
3442 else if (ch >= 'A' && ch <= 'F')
3443 t = ch - 'A' + 10;
3444 else if (isnum(ch))
3445 t = ch - '0';
3446 else
3447 break;
3448 if (t >= b)
3449 break;
3450 if (q >= token_buf + STRING_MAX_SIZE) {
3451 num_too_long:
3452 error("number too long");
3454 *q++ = ch;
3455 ch = *p++;
3457 if (ch == '.' ||
3458 ((ch == 'e' || ch == 'E') && b == 10) ||
3459 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
3460 if (b != 10) {
3461 /* NOTE: strtox should support that for hexa numbers, but
3462 non ISOC99 libcs do not support it, so we prefer to do
3463 it by hand */
3464 /* hexadecimal or binary floats */
3465 /* XXX: handle overflows */
3466 *q = '\0';
3467 if (b == 16)
3468 shift = 4;
3469 else
3470 shift = 2;
3471 bn_zero(bn);
3472 q = token_buf;
3473 while (1) {
3474 t = *q++;
3475 if (t == '\0') {
3476 break;
3477 } else if (t >= 'a') {
3478 t = t - 'a' + 10;
3479 } else if (t >= 'A') {
3480 t = t - 'A' + 10;
3481 } else {
3482 t = t - '0';
3484 bn_lshift(bn, shift, t);
3486 frac_bits = 0;
3487 if (ch == '.') {
3488 ch = *p++;
3489 while (1) {
3490 t = ch;
3491 if (t >= 'a' && t <= 'f') {
3492 t = t - 'a' + 10;
3493 } else if (t >= 'A' && t <= 'F') {
3494 t = t - 'A' + 10;
3495 } else if (t >= '0' && t <= '9') {
3496 t = t - '0';
3497 } else {
3498 break;
3500 if (t >= b)
3501 error("invalid digit");
3502 bn_lshift(bn, shift, t);
3503 frac_bits += shift;
3504 ch = *p++;
3507 if (ch != 'p' && ch != 'P')
3508 expect("exponent");
3509 ch = *p++;
3510 s = 1;
3511 exp_val = 0;
3512 if (ch == '+') {
3513 ch = *p++;
3514 } else if (ch == '-') {
3515 s = -1;
3516 ch = *p++;
3518 if (ch < '0' || ch > '9')
3519 expect("exponent digits");
3520 while (ch >= '0' && ch <= '9') {
3521 exp_val = exp_val * 10 + ch - '0';
3522 ch = *p++;
3524 exp_val = exp_val * s;
3526 /* now we can generate the number */
3527 /* XXX: should patch directly float number */
3528 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
3529 d = ldexp(d, exp_val - frac_bits);
3530 t = toup(ch);
3531 if (t == 'F') {
3532 ch = *p++;
3533 tok = TOK_CFLOAT;
3534 /* float : should handle overflow */
3535 tokc.f = (float)d;
3536 } else if (t == 'L') {
3537 ch = *p++;
3538 tok = TOK_CLDOUBLE;
3539 /* XXX: not large enough */
3540 tokc.ld = (long double)d;
3541 } else {
3542 tok = TOK_CDOUBLE;
3543 tokc.d = d;
3545 } else {
3546 /* decimal floats */
3547 if (ch == '.') {
3548 if (q >= token_buf + STRING_MAX_SIZE)
3549 goto num_too_long;
3550 *q++ = ch;
3551 ch = *p++;
3552 float_frac_parse:
3553 while (ch >= '0' && ch <= '9') {
3554 if (q >= token_buf + STRING_MAX_SIZE)
3555 goto num_too_long;
3556 *q++ = ch;
3557 ch = *p++;
3560 if (ch == 'e' || ch == 'E') {
3561 if (q >= token_buf + STRING_MAX_SIZE)
3562 goto num_too_long;
3563 *q++ = ch;
3564 ch = *p++;
3565 if (ch == '-' || ch == '+') {
3566 if (q >= token_buf + STRING_MAX_SIZE)
3567 goto num_too_long;
3568 *q++ = ch;
3569 ch = *p++;
3571 if (ch < '0' || ch > '9')
3572 expect("exponent digits");
3573 while (ch >= '0' && ch <= '9') {
3574 if (q >= token_buf + STRING_MAX_SIZE)
3575 goto num_too_long;
3576 *q++ = ch;
3577 ch = *p++;
3580 *q = '\0';
3581 t = toup(ch);
3582 errno = 0;
3583 if (t == 'F') {
3584 ch = *p++;
3585 tok = TOK_CFLOAT;
3586 tokc.f = strtof(token_buf, NULL);
3587 } else if (t == 'L') {
3588 ch = *p++;
3589 tok = TOK_CLDOUBLE;
3590 tokc.ld = strtold(token_buf, NULL);
3591 } else {
3592 tok = TOK_CDOUBLE;
3593 tokc.d = strtod(token_buf, NULL);
3596 } else {
3597 unsigned long long n, n1;
3598 int lcount, ucount;
3600 /* integer number */
3601 *q = '\0';
3602 q = token_buf;
3603 if (b == 10 && *q == '0') {
3604 b = 8;
3605 q++;
3607 n = 0;
3608 while(1) {
3609 t = *q++;
3610 /* no need for checks except for base 10 / 8 errors */
3611 if (t == '\0') {
3612 break;
3613 } else if (t >= 'a') {
3614 t = t - 'a' + 10;
3615 } else if (t >= 'A') {
3616 t = t - 'A' + 10;
3617 } else {
3618 t = t - '0';
3619 if (t >= b)
3620 error("invalid digit");
3622 n1 = n;
3623 n = n * b + t;
3624 /* detect overflow */
3625 /* XXX: this test is not reliable */
3626 if (n < n1)
3627 error("integer constant overflow");
3630 /* XXX: not exactly ANSI compliant */
3631 if ((n & 0xffffffff00000000LL) != 0) {
3632 if ((n >> 63) != 0)
3633 tok = TOK_CULLONG;
3634 else
3635 tok = TOK_CLLONG;
3636 } else if (n > 0x7fffffff) {
3637 tok = TOK_CUINT;
3638 } else {
3639 tok = TOK_CINT;
3641 lcount = 0;
3642 ucount = 0;
3643 for(;;) {
3644 t = toup(ch);
3645 if (t == 'L') {
3646 if (lcount >= 2)
3647 error("three 'l's in integer constant");
3648 lcount++;
3649 if (lcount == 2) {
3650 if (tok == TOK_CINT)
3651 tok = TOK_CLLONG;
3652 else if (tok == TOK_CUINT)
3653 tok = TOK_CULLONG;
3655 ch = *p++;
3656 } else if (t == 'U') {
3657 if (ucount >= 1)
3658 error("two 'u's in integer constant");
3659 ucount++;
3660 if (tok == TOK_CINT)
3661 tok = TOK_CUINT;
3662 else if (tok == TOK_CLLONG)
3663 tok = TOK_CULLONG;
3664 ch = *p++;
3665 } else {
3666 break;
3669 if (tok == TOK_CINT || tok == TOK_CUINT)
3670 tokc.ui = n;
3671 else
3672 tokc.ull = n;
3674 if (ch)
3675 error("invalid number\n");
3679 #define PARSE2(c1, tok1, c2, tok2) \
3680 case c1: \
3681 PEEKC(c, p); \
3682 if (c == c2) { \
3683 p++; \
3684 tok = tok2; \
3685 } else { \
3686 tok = tok1; \
3688 break;
3690 /* return next token without macro substitution */
3691 static inline void next_nomacro1(void)
3693 int t, c, is_long;
3694 TokenSym *ts;
3695 uint8_t *p, *p1;
3696 unsigned int h;
3698 cstr_reset(&tok_spaces);
3699 p = file->buf_ptr;
3700 redo_no_start:
3701 c = *p;
3702 switch(c) {
3703 case ' ':
3704 case '\t':
3705 case '\f':
3706 case '\v':
3707 case '\r':
3708 cstr_ccat(&tok_spaces, c);
3709 p++;
3710 goto redo_no_start;
3712 case '\\':
3713 /* first look if it is in fact an end of buffer */
3714 if (p >= file->buf_end) {
3715 file->buf_ptr = p;
3716 handle_eob();
3717 p = file->buf_ptr;
3718 if (p >= file->buf_end)
3719 goto parse_eof;
3720 else
3721 goto redo_no_start;
3722 } else {
3723 file->buf_ptr = p;
3724 ch = *p;
3725 handle_stray();
3726 p = file->buf_ptr;
3727 goto redo_no_start;
3729 parse_eof:
3731 TCCState *s1 = tcc_state;
3732 if ((parse_flags & PARSE_FLAG_LINEFEED)
3733 && !(tok_flags & TOK_FLAG_EOF)) {
3734 tok_flags |= TOK_FLAG_EOF;
3735 tok = TOK_LINEFEED;
3736 goto keep_tok_flags;
3737 } else if (s1->include_stack_ptr == s1->include_stack ||
3738 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
3739 /* no include left : end of file. */
3740 tok = TOK_EOF;
3741 } else {
3742 tok_flags &= ~TOK_FLAG_EOF;
3743 /* pop include file */
3745 /* test if previous '#endif' was after a #ifdef at
3746 start of file */
3747 if (tok_flags & TOK_FLAG_ENDIF) {
3748 #ifdef INC_DEBUG
3749 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
3750 #endif
3751 add_cached_include(s1, file->inc_type, file->inc_filename,
3752 file->ifndef_macro_saved);
3755 /* add end of include file debug info */
3756 if (do_debug) {
3757 put_stabd(N_EINCL, 0, 0);
3759 /* pop include stack */
3760 tcc_close(file);
3761 s1->include_stack_ptr--;
3762 file = *s1->include_stack_ptr;
3763 p = file->buf_ptr;
3764 goto redo_no_start;
3767 break;
3769 case '\n':
3770 file->line_num++;
3771 tok_flags |= TOK_FLAG_BOL;
3772 p++;
3773 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
3774 goto redo_no_start;
3775 tok = TOK_LINEFEED;
3776 goto keep_tok_flags;
3778 case '#':
3779 /* XXX: simplify */
3780 PEEKC(c, p);
3781 if ((tok_flags & TOK_FLAG_BOL) &&
3782 (parse_flags & PARSE_FLAG_PREPROCESS)) {
3783 file->buf_ptr = p;
3784 preprocess(tok_flags & TOK_FLAG_BOF);
3785 p = file->buf_ptr;
3786 goto redo_no_start;
3787 } else {
3788 if (c == '#') {
3789 p++;
3790 tok = TOK_TWOSHARPS;
3791 } else {
3792 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
3793 p = parse_line_comment(p - 1);
3794 goto redo_no_start;
3795 } else {
3796 tok = '#';
3800 break;
3802 case 'a': case 'b': case 'c': case 'd':
3803 case 'e': case 'f': case 'g': case 'h':
3804 case 'i': case 'j': case 'k': case 'l':
3805 case 'm': case 'n': case 'o': case 'p':
3806 case 'q': case 'r': case 's': case 't':
3807 case 'u': case 'v': case 'w': case 'x':
3808 case 'y': case 'z':
3809 case 'A': case 'B': case 'C': case 'D':
3810 case 'E': case 'F': case 'G': case 'H':
3811 case 'I': case 'J': case 'K':
3812 case 'M': case 'N': case 'O': case 'P':
3813 case 'Q': case 'R': case 'S': case 'T':
3814 case 'U': case 'V': case 'W': case 'X':
3815 case 'Y': case 'Z':
3816 case '_':
3817 parse_ident_fast:
3818 p1 = p;
3819 h = TOK_HASH_INIT;
3820 h = TOK_HASH_FUNC(h, c);
3821 p++;
3822 for(;;) {
3823 c = *p;
3824 if (!isidnum_table[c-CH_EOF])
3825 break;
3826 h = TOK_HASH_FUNC(h, c);
3827 p++;
3829 if (c != '\\') {
3830 TokenSym **pts;
3831 int len;
3833 /* fast case : no stray found, so we have the full token
3834 and we have already hashed it */
3835 len = p - p1;
3836 h &= (TOK_HASH_SIZE - 1);
3837 pts = &hash_ident[h];
3838 for(;;) {
3839 ts = *pts;
3840 if (!ts)
3841 break;
3842 if (ts->len == len && !memcmp(ts->str, p1, len))
3843 goto token_found;
3844 pts = &(ts->hash_next);
3846 ts = tok_alloc_new(pts, p1, len);
3847 token_found: ;
3848 } else {
3849 /* slower case */
3850 cstr_reset(&tokcstr);
3852 while (p1 < p) {
3853 cstr_ccat(&tokcstr, *p1);
3854 p1++;
3856 p--;
3857 PEEKC(c, p);
3858 parse_ident_slow:
3859 while (isidnum_table[c-CH_EOF]) {
3860 cstr_ccat(&tokcstr, c);
3861 PEEKC(c, p);
3863 ts = tok_alloc(tokcstr.data, tokcstr.size);
3865 tok = ts->tok;
3866 break;
3867 case 'L':
3868 t = p[1];
3869 if (t != '\\' && t != '\'' && t != '\"') {
3870 /* fast case */
3871 goto parse_ident_fast;
3872 } else {
3873 PEEKC(c, p);
3874 if (c == '\'' || c == '\"') {
3875 is_long = 1;
3876 goto str_const;
3877 } else {
3878 cstr_reset(&tokcstr);
3879 cstr_ccat(&tokcstr, 'L');
3880 goto parse_ident_slow;
3883 break;
3884 case '0': case '1': case '2': case '3':
3885 case '4': case '5': case '6': case '7':
3886 case '8': case '9':
3888 cstr_reset(&tokcstr);
3889 /* after the first digit, accept digits, alpha, '.' or sign if
3890 prefixed by 'eEpP' */
3891 parse_num:
3892 for(;;) {
3893 t = c;
3894 cstr_ccat(&tokcstr, c);
3895 PEEKC(c, p);
3896 if (!(isnum(c) || isid(c) || c == '.' ||
3897 ((c == '+' || c == '-') &&
3898 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
3899 break;
3901 /* We add a trailing '\0' to ease parsing */
3902 cstr_ccat(&tokcstr, '\0');
3903 tokc.cstr = &tokcstr;
3904 tok = TOK_PPNUM;
3905 break;
3906 case '.':
3907 /* special dot handling because it can also start a number */
3908 PEEKC(c, p);
3909 if (isnum(c)) {
3910 cstr_reset(&tokcstr);
3911 cstr_ccat(&tokcstr, '.');
3912 goto parse_num;
3913 } else if (c == '.') {
3914 PEEKC(c, p);
3915 if (c != '.')
3916 expect("'.'");
3917 PEEKC(c, p);
3918 tok = TOK_DOTS;
3919 } else {
3920 tok = '.';
3922 break;
3923 case '\'':
3924 case '\"':
3925 is_long = 0;
3926 str_const:
3928 CString str;
3929 int sep;
3931 sep = c;
3933 /* parse the string */
3934 cstr_new(&str);
3935 p = parse_pp_string(p, sep, &str);
3936 cstr_ccat(&str, '\0');
3938 /* eval the escape (should be done as TOK_PPNUM) */
3939 cstr_reset(&tokcstr);
3940 parse_escape_string(&tokcstr, str.data, is_long);
3941 cstr_free(&str);
3943 if (sep == '\'') {
3944 int char_size;
3945 /* XXX: make it portable */
3946 if (!is_long)
3947 char_size = 1;
3948 else
3949 char_size = sizeof(nwchar_t);
3950 if (tokcstr.size <= char_size)
3951 error("empty character constant");
3952 if (tokcstr.size > 2 * char_size)
3953 warning("multi-character character constant");
3954 if (!is_long) {
3955 tokc.i = *(int8_t *)tokcstr.data;
3956 tok = TOK_CCHAR;
3957 } else {
3958 tokc.i = *(nwchar_t *)tokcstr.data;
3959 tok = TOK_LCHAR;
3961 } else {
3962 tokc.cstr = &tokcstr;
3963 if (!is_long)
3964 tok = TOK_STR;
3965 else
3966 tok = TOK_LSTR;
3969 break;
3971 case '<':
3972 PEEKC(c, p);
3973 if (c == '=') {
3974 p++;
3975 tok = TOK_LE;
3976 } else if (c == '<') {
3977 PEEKC(c, p);
3978 if (c == '=') {
3979 p++;
3980 tok = TOK_A_SHL;
3981 } else {
3982 tok = TOK_SHL;
3984 } else {
3985 tok = TOK_LT;
3987 break;
3989 case '>':
3990 PEEKC(c, p);
3991 if (c == '=') {
3992 p++;
3993 tok = TOK_GE;
3994 } else if (c == '>') {
3995 PEEKC(c, p);
3996 if (c == '=') {
3997 p++;
3998 tok = TOK_A_SAR;
3999 } else {
4000 tok = TOK_SAR;
4002 } else {
4003 tok = TOK_GT;
4005 break;
4007 case '&':
4008 PEEKC(c, p);
4009 if (c == '&') {
4010 p++;
4011 tok = TOK_LAND;
4012 } else if (c == '=') {
4013 p++;
4014 tok = TOK_A_AND;
4015 } else {
4016 tok = '&';
4018 break;
4020 case '|':
4021 PEEKC(c, p);
4022 if (c == '|') {
4023 p++;
4024 tok = TOK_LOR;
4025 } else if (c == '=') {
4026 p++;
4027 tok = TOK_A_OR;
4028 } else {
4029 tok = '|';
4031 break;
4033 case '+':
4034 PEEKC(c, p);
4035 if (c == '+') {
4036 p++;
4037 tok = TOK_INC;
4038 } else if (c == '=') {
4039 p++;
4040 tok = TOK_A_ADD;
4041 } else {
4042 tok = '+';
4044 break;
4046 case '-':
4047 PEEKC(c, p);
4048 if (c == '-') {
4049 p++;
4050 tok = TOK_DEC;
4051 } else if (c == '=') {
4052 p++;
4053 tok = TOK_A_SUB;
4054 } else if (c == '>') {
4055 p++;
4056 tok = TOK_ARROW;
4057 } else {
4058 tok = '-';
4060 break;
4062 PARSE2('!', '!', '=', TOK_NE)
4063 PARSE2('=', '=', '=', TOK_EQ)
4064 PARSE2('*', '*', '=', TOK_A_MUL)
4065 PARSE2('%', '%', '=', TOK_A_MOD)
4066 PARSE2('^', '^', '=', TOK_A_XOR)
4068 /* comments or operator */
4069 case '/':
4070 PEEKC(c, p);
4071 if (c == '*') {
4072 p = parse_comment(p);
4073 goto redo_no_start;
4074 } else if (c == '/') {
4075 p = parse_line_comment(p);
4076 goto redo_no_start;
4077 } else if (c == '=') {
4078 p++;
4079 tok = TOK_A_DIV;
4080 } else {
4081 tok = '/';
4083 break;
4085 /* simple tokens */
4086 case '(':
4087 case ')':
4088 case '[':
4089 case ']':
4090 case '{':
4091 case '}':
4092 case ',':
4093 case ';':
4094 case ':':
4095 case '?':
4096 case '~':
4097 case '$': /* only used in assembler */
4098 case '@': /* dito */
4099 tok = c;
4100 p++;
4101 break;
4102 default:
4103 error("unrecognized character \\x%02x", c);
4104 break;
4106 tok_flags = 0;
4107 keep_tok_flags:
4108 file->buf_ptr = p;
4109 #if defined(PARSE_DEBUG)
4110 printf("token = %s\n", get_tok_str(tok, &tokc));
4111 #endif
4114 /* return next token without macro substitution. Can read input from
4115 macro_ptr buffer */
4116 static void next_nomacro(void)
4118 if (macro_ptr) {
4119 redo:
4120 tok = *macro_ptr;
4121 if (tok) {
4122 TOK_GET(tok, macro_ptr, tokc);
4123 if (tok == TOK_LINENUM) {
4124 file->line_num = tokc.i;
4125 goto redo;
4128 } else {
4129 next_nomacro1();
4133 /* substitute args in macro_str and return allocated string */
4134 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
4136 int *st, last_tok, t, notfirst;
4137 Sym *s;
4138 CValue cval;
4139 TokenString str;
4140 CString cstr;
4142 tok_str_new(&str);
4143 last_tok = 0;
4144 while(1) {
4145 TOK_GET(t, macro_str, cval);
4146 if (!t)
4147 break;
4148 if (t == '#') {
4149 /* stringize */
4150 TOK_GET(t, macro_str, cval);
4151 if (!t)
4152 break;
4153 s = sym_find2(args, t);
4154 if (s) {
4155 cstr_new(&cstr);
4156 st = (int *)s->c;
4157 notfirst = 0;
4158 while (*st) {
4159 if (notfirst)
4160 cstr_ccat(&cstr, ' ');
4161 TOK_GET(t, st, cval);
4162 cstr_cat(&cstr, get_tok_str(t, &cval));
4163 #ifndef PP_NOSPACES
4164 notfirst = 1;
4165 #endif
4167 cstr_ccat(&cstr, '\0');
4168 #ifdef PP_DEBUG
4169 printf("stringize: %s\n", (char *)cstr.data);
4170 #endif
4171 /* add string */
4172 cval.cstr = &cstr;
4173 tok_str_add2(&str, TOK_STR, &cval);
4174 cstr_free(&cstr);
4175 } else {
4176 tok_str_add2(&str, t, &cval);
4178 } else if (t >= TOK_IDENT) {
4179 s = sym_find2(args, t);
4180 if (s) {
4181 st = (int *)s->c;
4182 /* if '##' is present before or after, no arg substitution */
4183 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
4184 /* special case for var arg macros : ## eats the
4185 ',' if empty VA_ARGS variable. */
4186 /* XXX: test of the ',' is not 100%
4187 reliable. should fix it to avoid security
4188 problems */
4189 if (gnu_ext && s->type.t &&
4190 last_tok == TOK_TWOSHARPS &&
4191 str.len >= 2 && str.str[str.len - 2] == ',') {
4192 if (*st == 0) {
4193 /* suppress ',' '##' */
4194 str.len -= 2;
4195 } else {
4196 /* suppress '##' and add variable */
4197 str.len--;
4198 goto add_var;
4200 } else {
4201 int t1;
4202 add_var:
4203 for(;;) {
4204 TOK_GET(t1, st, cval);
4205 if (!t1)
4206 break;
4207 tok_str_add2(&str, t1, &cval);
4210 } else {
4211 /* NOTE: the stream cannot be read when macro
4212 substituing an argument */
4213 macro_subst(&str, nested_list, st, NULL);
4215 } else {
4216 tok_str_add(&str, t);
4218 } else {
4219 tok_str_add2(&str, t, &cval);
4221 last_tok = t;
4223 tok_str_add(&str, 0);
4224 return str.str;
4227 static char const ab_month_name[12][4] =
4229 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4230 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4233 /* do macro substitution of current token with macro 's' and add
4234 result to (tok_str,tok_len). 'nested_list' is the list of all
4235 macros we got inside to avoid recursing. Return non zero if no
4236 substitution needs to be done */
4237 static int macro_subst_tok(TokenString *tok_str,
4238 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
4240 Sym *args, *sa, *sa1;
4241 int mstr_allocated, parlevel, *mstr, t, t1;
4242 TokenString str;
4243 char *cstrval;
4244 CValue cval;
4245 CString cstr;
4246 char buf[32];
4248 /* if symbol is a macro, prepare substitution */
4249 /* special macros */
4250 if (tok == TOK___LINE__) {
4251 snprintf(buf, sizeof(buf), "%d", file->line_num);
4252 cstrval = buf;
4253 t1 = TOK_PPNUM;
4254 goto add_cstr1;
4255 } else if (tok == TOK___FILE__) {
4256 cstrval = file->filename;
4257 goto add_cstr;
4258 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
4259 time_t ti;
4260 struct tm *tm;
4262 time(&ti);
4263 tm = localtime(&ti);
4264 if (tok == TOK___DATE__) {
4265 snprintf(buf, sizeof(buf), "%s %2d %d",
4266 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
4267 } else {
4268 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
4269 tm->tm_hour, tm->tm_min, tm->tm_sec);
4271 cstrval = buf;
4272 add_cstr:
4273 t1 = TOK_STR;
4274 add_cstr1:
4275 cstr_new(&cstr);
4276 cstr_cat(&cstr, cstrval);
4277 cstr_ccat(&cstr, '\0');
4278 cval.cstr = &cstr;
4279 tok_str_add2(tok_str, t1, &cval);
4280 cstr_free(&cstr);
4281 } else {
4282 mstr = (int *)s->c;
4283 mstr_allocated = 0;
4284 if (s->type.t == MACRO_FUNC) {
4285 /* NOTE: we do not use next_nomacro to avoid eating the
4286 next token. XXX: find better solution */
4287 redo:
4288 if (macro_ptr) {
4289 t = *macro_ptr;
4290 if (t == 0 && can_read_stream) {
4291 /* end of macro stream: we must look at the token
4292 after in the file */
4293 struct macro_level *ml = *can_read_stream;
4294 macro_ptr = NULL;
4295 if (ml)
4297 macro_ptr = ml->p;
4298 ml->p = NULL;
4299 *can_read_stream = ml -> prev;
4301 goto redo;
4303 } else {
4304 /* XXX: incorrect with comments */
4305 ch = file->buf_ptr[0];
4306 while (is_space(ch) || ch == '\n')
4307 cinp();
4308 t = ch;
4310 if (t != '(') /* no macro subst */
4311 return -1;
4313 /* argument macro */
4314 next_nomacro();
4315 next_nomacro();
4316 args = NULL;
4317 sa = s->next;
4318 /* NOTE: empty args are allowed, except if no args */
4319 for(;;) {
4320 /* handle '()' case */
4321 if (!args && !sa && tok == ')')
4322 break;
4323 if (!sa)
4324 error("macro '%s' used with too many args",
4325 get_tok_str(s->v, 0));
4326 tok_str_new(&str);
4327 parlevel = 0;
4328 /* NOTE: non zero sa->t indicates VA_ARGS */
4329 while ((parlevel > 0 ||
4330 (tok != ')' &&
4331 (tok != ',' || sa->type.t))) &&
4332 tok != -1) {
4333 if (tok == '(')
4334 parlevel++;
4335 else if (tok == ')')
4336 parlevel--;
4337 if (tok != TOK_LINEFEED)
4338 tok_str_add2(&str, tok, &tokc);
4339 next_nomacro();
4341 tok_str_add(&str, 0);
4342 sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, (long)str.str);
4343 sa = sa->next;
4344 if (tok == ')') {
4345 /* special case for gcc var args: add an empty
4346 var arg argument if it is omitted */
4347 if (sa && sa->type.t && gnu_ext)
4348 continue;
4349 else
4350 break;
4352 if (tok != ',')
4353 expect(",");
4354 next_nomacro();
4356 if (sa) {
4357 error("macro '%s' used with too few args",
4358 get_tok_str(s->v, 0));
4361 /* now subst each arg */
4362 mstr = macro_arg_subst(nested_list, mstr, args);
4363 /* free memory */
4364 sa = args;
4365 while (sa) {
4366 sa1 = sa->prev;
4367 tok_str_free((int *)sa->c);
4368 sym_free(sa);
4369 sa = sa1;
4371 mstr_allocated = 1;
4373 sym_push2(nested_list, s->v, 0, 0);
4374 macro_subst(tok_str, nested_list, mstr, can_read_stream);
4375 /* pop nested defined symbol */
4376 sa1 = *nested_list;
4377 *nested_list = sa1->prev;
4378 sym_free(sa1);
4379 if (mstr_allocated)
4380 tok_str_free(mstr);
4382 return 0;
4385 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4386 return the resulting string (which must be freed). */
4387 static inline int *macro_twosharps(const int *macro_str)
4389 TokenSym *ts;
4390 const int *macro_ptr1, *start_macro_ptr, *ptr, *saved_macro_ptr;
4391 int t;
4392 const char *p1, *p2;
4393 CValue cval;
4394 TokenString macro_str1;
4395 CString cstr;
4397 start_macro_ptr = macro_str;
4398 /* we search the first '##' */
4399 for(;;) {
4400 macro_ptr1 = macro_str;
4401 TOK_GET(t, macro_str, cval);
4402 /* nothing more to do if end of string */
4403 if (t == 0)
4404 return NULL;
4405 if (*macro_str == TOK_TWOSHARPS)
4406 break;
4409 /* we saw '##', so we need more processing to handle it */
4410 cstr_new(&cstr);
4411 tok_str_new(&macro_str1);
4412 tok = t;
4413 tokc = cval;
4415 /* add all tokens seen so far */
4416 for(ptr = start_macro_ptr; ptr < macro_ptr1;) {
4417 TOK_GET(t, ptr, cval);
4418 tok_str_add2(&macro_str1, t, &cval);
4420 saved_macro_ptr = macro_ptr;
4421 /* XXX: get rid of the use of macro_ptr here */
4422 macro_ptr = (int *)macro_str;
4423 for(;;) {
4424 while (*macro_ptr == TOK_TWOSHARPS) {
4425 macro_ptr++;
4426 macro_ptr1 = macro_ptr;
4427 t = *macro_ptr;
4428 if (t) {
4429 TOK_GET(t, macro_ptr, cval);
4430 /* We concatenate the two tokens if we have an
4431 identifier or a preprocessing number */
4432 cstr_reset(&cstr);
4433 p1 = get_tok_str(tok, &tokc);
4434 cstr_cat(&cstr, p1);
4435 p2 = get_tok_str(t, &cval);
4436 cstr_cat(&cstr, p2);
4437 cstr_ccat(&cstr, '\0');
4439 if ((tok >= TOK_IDENT || tok == TOK_PPNUM) &&
4440 (t >= TOK_IDENT || t == TOK_PPNUM)) {
4441 if (tok == TOK_PPNUM) {
4442 /* if number, then create a number token */
4443 /* NOTE: no need to allocate because
4444 tok_str_add2() does it */
4445 cstr_reset(&tokcstr);
4446 tokcstr = cstr;
4447 cstr_new(&cstr);
4448 tokc.cstr = &tokcstr;
4449 } else {
4450 /* if identifier, we must do a test to
4451 validate we have a correct identifier */
4452 if (t == TOK_PPNUM) {
4453 const char *p;
4454 int c;
4456 p = p2;
4457 for(;;) {
4458 c = *p;
4459 if (c == '\0')
4460 break;
4461 p++;
4462 if (!isnum(c) && !isid(c))
4463 goto error_pasting;
4466 ts = tok_alloc(cstr.data, strlen(cstr.data));
4467 tok = ts->tok; /* modify current token */
4469 } else {
4470 const char *str = cstr.data;
4471 const unsigned char *q;
4473 /* we look for a valid token */
4474 /* XXX: do more extensive checks */
4475 if (!strcmp(str, ">>=")) {
4476 tok = TOK_A_SAR;
4477 } else if (!strcmp(str, "<<=")) {
4478 tok = TOK_A_SHL;
4479 } else if (strlen(str) == 2) {
4480 /* search in two bytes table */
4481 q = tok_two_chars;
4482 for(;;) {
4483 if (!*q)
4484 goto error_pasting;
4485 if (q[0] == str[0] && q[1] == str[1])
4486 break;
4487 q += 3;
4489 tok = q[2];
4490 } else {
4491 error_pasting:
4492 /* NOTE: because get_tok_str use a static buffer,
4493 we must save it */
4494 cstr_reset(&cstr);
4495 p1 = get_tok_str(tok, &tokc);
4496 cstr_cat(&cstr, p1);
4497 cstr_ccat(&cstr, '\0');
4498 p2 = get_tok_str(t, &cval);
4499 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
4500 /* cannot merge tokens: just add them separately */
4501 tok_str_add2(&macro_str1, tok, &tokc);
4502 /* XXX: free associated memory ? */
4503 tok = t;
4504 tokc = cval;
4509 tok_str_add2(&macro_str1, tok, &tokc);
4510 next_nomacro();
4511 if (tok == 0)
4512 break;
4514 macro_ptr = (int *)saved_macro_ptr;
4515 cstr_free(&cstr);
4516 tok_str_add(&macro_str1, 0);
4517 return macro_str1.str;
4521 /* do macro substitution of macro_str and add result to
4522 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4523 inside to avoid recursing. */
4524 static void macro_subst(TokenString *tok_str, Sym **nested_list,
4525 const int *macro_str, struct macro_level ** can_read_stream)
4527 Sym *s;
4528 int *macro_str1;
4529 const int *ptr;
4530 int t, ret;
4531 CValue cval;
4532 struct macro_level ml;
4534 /* first scan for '##' operator handling */
4535 ptr = macro_str;
4536 macro_str1 = macro_twosharps(ptr);
4537 if (macro_str1)
4538 ptr = macro_str1;
4539 while (1) {
4540 /* NOTE: ptr == NULL can only happen if tokens are read from
4541 file stream due to a macro function call */
4542 if (ptr == NULL)
4543 break;
4544 TOK_GET(t, ptr, cval);
4545 if (t == 0)
4546 break;
4547 s = define_find(t);
4548 if (s != NULL) {
4549 /* if nested substitution, do nothing */
4550 if (sym_find2(*nested_list, t))
4551 goto no_subst;
4552 ml.p = macro_ptr;
4553 if (can_read_stream)
4554 ml.prev = *can_read_stream, *can_read_stream = &ml;
4555 macro_ptr = (int *)ptr;
4556 tok = t;
4557 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
4558 ptr = (int *)macro_ptr;
4559 macro_ptr = ml.p;
4560 if (can_read_stream && *can_read_stream == &ml)
4561 *can_read_stream = ml.prev;
4562 if (ret != 0)
4563 goto no_subst;
4564 } else {
4565 no_subst:
4566 tok_str_add2(tok_str, t, &cval);
4569 if (macro_str1)
4570 tok_str_free(macro_str1);
4573 /* return next token with macro substitution */
4574 static void next(void)
4576 Sym *nested_list, *s;
4577 TokenString str;
4578 struct macro_level *ml;
4580 redo:
4581 next_nomacro();
4582 if (!macro_ptr) {
4583 /* if not reading from macro substituted string, then try
4584 to substitute macros */
4585 if (tok >= TOK_IDENT &&
4586 (parse_flags & PARSE_FLAG_PREPROCESS)) {
4587 s = define_find(tok);
4588 if (s) {
4589 /* we have a macro: we try to substitute */
4590 tok_str_new(&str);
4591 nested_list = NULL;
4592 ml = NULL;
4593 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
4594 /* substitution done, NOTE: maybe empty */
4595 tok_str_add(&str, 0);
4596 macro_ptr = str.str;
4597 macro_ptr_allocated = str.str;
4598 goto redo;
4602 } else {
4603 if (tok == 0) {
4604 /* end of macro or end of unget buffer */
4605 if (unget_buffer_enabled) {
4606 macro_ptr = unget_saved_macro_ptr;
4607 unget_buffer_enabled = 0;
4608 } else {
4609 /* end of macro string: free it */
4610 tok_str_free(macro_ptr_allocated);
4611 macro_ptr = NULL;
4613 goto redo;
4617 /* convert preprocessor tokens into C tokens */
4618 if (tok == TOK_PPNUM &&
4619 (parse_flags & PARSE_FLAG_TOK_NUM)) {
4620 parse_number((char *)tokc.cstr->data);
4624 /* push back current token and set current token to 'last_tok'. Only
4625 identifier case handled for labels. */
4626 static inline void unget_tok(int last_tok)
4628 int i, n;
4629 int *q;
4630 unget_saved_macro_ptr = macro_ptr;
4631 unget_buffer_enabled = 1;
4632 q = unget_saved_buffer;
4633 macro_ptr = q;
4634 *q++ = tok;
4635 n = tok_ext_size(tok) - 1;
4636 for(i=0;i<n;i++)
4637 *q++ = tokc.tab[i];
4638 *q = 0; /* end of token string */
4639 tok = last_tok;
4643 void swap(int *p, int *q)
4645 int t;
4646 t = *p;
4647 *p = *q;
4648 *q = t;
4651 void vsetc(CType *type, int r, CValue *vc)
4653 int v;
4655 if (vtop >= vstack + (VSTACK_SIZE - 1))
4656 error("memory full");
4657 /* cannot let cpu flags if other instruction are generated. Also
4658 avoid leaving VT_JMP anywhere except on the top of the stack
4659 because it would complicate the code generator. */
4660 if (vtop >= vstack) {
4661 v = vtop->r & VT_VALMASK;
4662 if (v == VT_CMP || (v & ~1) == VT_JMP)
4663 gv(RC_INT);
4665 vtop++;
4666 vtop->type = *type;
4667 vtop->r = r;
4668 vtop->r2 = VT_CONST;
4669 vtop->c = *vc;
4672 /* push integer constant */
4673 void vpushi(int v)
4675 CValue cval;
4676 cval.i = v;
4677 vsetc(&int_type, VT_CONST, &cval);
4680 /* push long long constant */
4681 void vpushll(long long v)
4683 CValue cval;
4684 CType ctype;
4685 ctype.t = VT_LLONG;
4686 cval.ull = v;
4687 vsetc(&ctype, VT_CONST, &cval);
4690 /* Return a static symbol pointing to a section */
4691 static Sym *get_sym_ref(CType *type, Section *sec,
4692 unsigned long offset, unsigned long size)
4694 int v;
4695 Sym *sym;
4697 v = anon_sym++;
4698 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
4699 sym->type.ref = type->ref;
4700 sym->r = VT_CONST | VT_SYM;
4701 put_extern_sym(sym, sec, offset, size);
4702 return sym;
4705 /* push a reference to a section offset by adding a dummy symbol */
4706 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
4708 CValue cval;
4710 cval.ul = 0;
4711 vsetc(type, VT_CONST | VT_SYM, &cval);
4712 vtop->sym = get_sym_ref(type, sec, offset, size);
4715 /* define a new external reference to a symbol 'v' of type 'u' */
4716 static Sym *external_global_sym(int v, CType *type, int r)
4718 Sym *s;
4720 s = sym_find(v);
4721 if (!s) {
4722 /* push forward reference */
4723 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
4724 s->type.ref = type->ref;
4725 s->r = r | VT_CONST | VT_SYM;
4727 return s;
4730 /* define a new external reference to a symbol 'v' of type 'u' */
4731 static Sym *external_sym(int v, CType *type, int r)
4733 Sym *s;
4735 s = sym_find(v);
4736 if (!s) {
4737 /* push forward reference */
4738 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
4739 s->type.t |= VT_EXTERN;
4740 } else {
4741 if (!is_compatible_types(&s->type, type))
4742 error("incompatible types for redefinition of '%s'",
4743 get_tok_str(v, NULL));
4745 return s;
4748 /* push a reference to global symbol v */
4749 static void vpush_global_sym(CType *type, int v)
4751 Sym *sym;
4752 CValue cval;
4754 sym = external_global_sym(v, type, 0);
4755 cval.ul = 0;
4756 vsetc(type, VT_CONST | VT_SYM, &cval);
4757 vtop->sym = sym;
4760 void vset(CType *type, int r, int v)
4762 CValue cval;
4764 cval.i = v;
4765 vsetc(type, r, &cval);
4768 void vseti(int r, int v)
4770 CType type;
4771 type.t = VT_INT;
4772 vset(&type, r, v);
4775 void vswap(void)
4777 SValue tmp;
4779 tmp = vtop[0];
4780 vtop[0] = vtop[-1];
4781 vtop[-1] = tmp;
4784 void vpushv(SValue *v)
4786 if (vtop >= vstack + (VSTACK_SIZE - 1))
4787 error("memory full");
4788 vtop++;
4789 *vtop = *v;
4792 void vdup(void)
4794 vpushv(vtop);
4797 /* save r to the memory stack, and mark it as being free */
4798 void save_reg(int r)
4800 int l, saved, size, align;
4801 SValue *p, sv;
4802 CType *type;
4804 /* modify all stack values */
4805 saved = 0;
4806 l = 0;
4807 for(p=vstack;p<=vtop;p++) {
4808 if ((p->r & VT_VALMASK) == r ||
4809 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
4810 /* must save value on stack if not already done */
4811 if (!saved) {
4812 /* NOTE: must reload 'r' because r might be equal to r2 */
4813 r = p->r & VT_VALMASK;
4814 /* store register in the stack */
4815 type = &p->type;
4816 if ((p->r & VT_LVAL) ||
4817 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
4818 #ifdef TCC_TARGET_X86_64
4819 type = &char_pointer_type;
4820 #else
4821 type = &int_type;
4822 #endif
4823 size = type_size(type, &align);
4824 loc = (loc - size) & -align;
4825 sv.type.t = type->t;
4826 sv.r = VT_LOCAL | VT_LVAL;
4827 sv.c.ul = loc;
4828 store(r, &sv);
4829 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4830 /* x86 specific: need to pop fp register ST0 if saved */
4831 if (r == TREG_ST0) {
4832 o(0xd9dd); /* fstp %st(1) */
4834 #endif
4835 #ifndef TCC_TARGET_X86_64
4836 /* special long long case */
4837 if ((type->t & VT_BTYPE) == VT_LLONG) {
4838 sv.c.ul += 4;
4839 store(p->r2, &sv);
4841 #endif
4842 l = loc;
4843 saved = 1;
4845 /* mark that stack entry as being saved on the stack */
4846 if (p->r & VT_LVAL) {
4847 /* also clear the bounded flag because the
4848 relocation address of the function was stored in
4849 p->c.ul */
4850 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
4851 } else {
4852 p->r = lvalue_type(p->type.t) | VT_LOCAL;
4854 p->r2 = VT_CONST;
4855 p->c.ul = l;
4860 /* find a register of class 'rc2' with at most one reference on stack.
4861 * If none, call get_reg(rc) */
4862 int get_reg_ex(int rc, int rc2)
4864 int r;
4865 SValue *p;
4867 for(r=0;r<NB_REGS;r++) {
4868 if (reg_classes[r] & rc2) {
4869 int n;
4870 n=0;
4871 for(p = vstack; p <= vtop; p++) {
4872 if ((p->r & VT_VALMASK) == r ||
4873 (p->r2 & VT_VALMASK) == r)
4874 n++;
4876 if (n <= 1)
4877 return r;
4880 return get_reg(rc);
4883 /* find a free register of class 'rc'. If none, save one register */
4884 int get_reg(int rc)
4886 int r;
4887 SValue *p;
4889 /* find a free register */
4890 for(r=0;r<NB_REGS;r++) {
4891 if (reg_classes[r] & rc) {
4892 for(p=vstack;p<=vtop;p++) {
4893 if ((p->r & VT_VALMASK) == r ||
4894 (p->r2 & VT_VALMASK) == r)
4895 goto notfound;
4897 return r;
4899 notfound: ;
4902 /* no register left : free the first one on the stack (VERY
4903 IMPORTANT to start from the bottom to ensure that we don't
4904 spill registers used in gen_opi()) */
4905 for(p=vstack;p<=vtop;p++) {
4906 r = p->r & VT_VALMASK;
4907 if (r < VT_CONST && (reg_classes[r] & rc))
4908 goto save_found;
4909 /* also look at second register (if long long) */
4910 r = p->r2 & VT_VALMASK;
4911 if (r < VT_CONST && (reg_classes[r] & rc)) {
4912 save_found:
4913 save_reg(r);
4914 return r;
4917 /* Should never comes here */
4918 return -1;
4921 /* save registers up to (vtop - n) stack entry */
4922 void save_regs(int n)
4924 int r;
4925 SValue *p, *p1;
4926 p1 = vtop - n;
4927 for(p = vstack;p <= p1; p++) {
4928 r = p->r & VT_VALMASK;
4929 if (r < VT_CONST) {
4930 save_reg(r);
4935 /* move register 's' to 'r', and flush previous value of r to memory
4936 if needed */
4937 void move_reg(int r, int s)
4939 SValue sv;
4941 if (r != s) {
4942 save_reg(r);
4943 sv.type.t = VT_INT;
4944 sv.r = s;
4945 sv.c.ul = 0;
4946 load(r, &sv);
4950 /* get address of vtop (vtop MUST BE an lvalue) */
4951 void gaddrof(void)
4953 vtop->r &= ~VT_LVAL;
4954 /* tricky: if saved lvalue, then we can go back to lvalue */
4955 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
4956 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
4959 #ifdef CONFIG_TCC_BCHECK
4960 /* generate lvalue bound code */
4961 void gbound(void)
4963 int lval_type;
4964 CType type1;
4966 vtop->r &= ~VT_MUSTBOUND;
4967 /* if lvalue, then use checking code before dereferencing */
4968 if (vtop->r & VT_LVAL) {
4969 /* if not VT_BOUNDED value, then make one */
4970 if (!(vtop->r & VT_BOUNDED)) {
4971 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
4972 /* must save type because we must set it to int to get pointer */
4973 type1 = vtop->type;
4974 vtop->type.t = VT_INT;
4975 gaddrof();
4976 vpushi(0);
4977 gen_bounded_ptr_add();
4978 vtop->r |= lval_type;
4979 vtop->type = type1;
4981 /* then check for dereferencing */
4982 gen_bounded_ptr_deref();
4985 #endif
4987 /* store vtop a register belonging to class 'rc'. lvalues are
4988 converted to values. Cannot be used if cannot be converted to
4989 register value (such as structures). */
4990 int gv(int rc)
4992 int r, rc2, bit_pos, bit_size, size, align, i;
4994 /* NOTE: get_reg can modify vstack[] */
4995 if (vtop->type.t & VT_BITFIELD) {
4996 CType type;
4997 int bits = 32;
4998 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4999 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5000 /* remove bit field info to avoid loops */
5001 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
5002 /* cast to int to propagate signedness in following ops */
5003 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5004 type.t = VT_LLONG;
5005 bits = 64;
5006 } else
5007 type.t = VT_INT;
5008 if((vtop->type.t & VT_UNSIGNED) ||
5009 (vtop->type.t & VT_BTYPE) == VT_BOOL)
5010 type.t |= VT_UNSIGNED;
5011 gen_cast(&type);
5012 /* generate shifts */
5013 vpushi(bits - (bit_pos + bit_size));
5014 gen_op(TOK_SHL);
5015 vpushi(bits - bit_size);
5016 /* NOTE: transformed to SHR if unsigned */
5017 gen_op(TOK_SAR);
5018 r = gv(rc);
5019 } else {
5020 if (is_float(vtop->type.t) &&
5021 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5022 Sym *sym;
5023 int *ptr;
5024 unsigned long offset;
5025 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5026 CValue check;
5027 #endif
5029 /* XXX: unify with initializers handling ? */
5030 /* CPUs usually cannot use float constants, so we store them
5031 generically in data segment */
5032 size = type_size(&vtop->type, &align);
5033 offset = (data_section->data_offset + align - 1) & -align;
5034 data_section->data_offset = offset;
5035 /* XXX: not portable yet */
5036 #if defined(__i386__) || defined(__x86_64__)
5037 /* Zero pad x87 tenbyte long doubles */
5038 if (size == LDOUBLE_SIZE)
5039 vtop->c.tab[2] &= 0xffff;
5040 #endif
5041 ptr = section_ptr_add(data_section, size);
5042 size = size >> 2;
5043 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5044 check.d = 1;
5045 if(check.tab[0])
5046 for(i=0;i<size;i++)
5047 ptr[i] = vtop->c.tab[size-1-i];
5048 else
5049 #endif
5050 for(i=0;i<size;i++)
5051 ptr[i] = vtop->c.tab[i];
5052 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
5053 vtop->r |= VT_LVAL | VT_SYM;
5054 vtop->sym = sym;
5055 vtop->c.ul = 0;
5057 #ifdef CONFIG_TCC_BCHECK
5058 if (vtop->r & VT_MUSTBOUND)
5059 gbound();
5060 #endif
5062 r = vtop->r & VT_VALMASK;
5063 rc2 = RC_INT;
5064 if (rc == RC_IRET)
5065 rc2 = RC_LRET;
5066 /* need to reload if:
5067 - constant
5068 - lvalue (need to dereference pointer)
5069 - already a register, but not in the right class */
5070 if (r >= VT_CONST ||
5071 (vtop->r & VT_LVAL) ||
5072 !(reg_classes[r] & rc) ||
5073 ((vtop->type.t & VT_BTYPE) == VT_LLONG &&
5074 !(reg_classes[vtop->r2] & rc2))) {
5075 r = get_reg(rc);
5076 #ifndef TCC_TARGET_X86_64
5077 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5078 int r2;
5079 unsigned long long ll;
5080 /* two register type load : expand to two words
5081 temporarily */
5082 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5083 /* load constant */
5084 ll = vtop->c.ull;
5085 vtop->c.ui = ll; /* first word */
5086 load(r, vtop);
5087 vtop->r = r; /* save register value */
5088 vpushi(ll >> 32); /* second word */
5089 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
5090 (vtop->r & VT_LVAL)) {
5091 /* We do not want to modifier the long long
5092 pointer here, so the safest (and less
5093 efficient) is to save all the other registers
5094 in the stack. XXX: totally inefficient. */
5095 save_regs(1);
5096 /* load from memory */
5097 load(r, vtop);
5098 vdup();
5099 vtop[-1].r = r; /* save register value */
5100 /* increment pointer to get second word */
5101 vtop->type.t = VT_INT;
5102 gaddrof();
5103 vpushi(4);
5104 gen_op('+');
5105 vtop->r |= VT_LVAL;
5106 } else {
5107 /* move registers */
5108 load(r, vtop);
5109 vdup();
5110 vtop[-1].r = r; /* save register value */
5111 vtop->r = vtop[-1].r2;
5113 /* allocate second register */
5114 r2 = get_reg(rc2);
5115 load(r2, vtop);
5116 vpop();
5117 /* write second register */
5118 vtop->r2 = r2;
5119 } else
5120 #endif
5121 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
5122 int t1, t;
5123 /* lvalue of scalar type : need to use lvalue type
5124 because of possible cast */
5125 t = vtop->type.t;
5126 t1 = t;
5127 /* compute memory access type */
5128 if (vtop->r & VT_LVAL_BYTE)
5129 t = VT_BYTE;
5130 else if (vtop->r & VT_LVAL_SHORT)
5131 t = VT_SHORT;
5132 if (vtop->r & VT_LVAL_UNSIGNED)
5133 t |= VT_UNSIGNED;
5134 vtop->type.t = t;
5135 load(r, vtop);
5136 /* restore wanted type */
5137 vtop->type.t = t1;
5138 } else {
5139 /* one register type load */
5140 load(r, vtop);
5143 vtop->r = r;
5144 #ifdef TCC_TARGET_C67
5145 /* uses register pairs for doubles */
5146 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
5147 vtop->r2 = r+1;
5148 #endif
5150 return r;
5153 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5154 void gv2(int rc1, int rc2)
5156 int v;
5158 /* generate more generic register first. But VT_JMP or VT_CMP
5159 values must be generated first in all cases to avoid possible
5160 reload errors */
5161 v = vtop[0].r & VT_VALMASK;
5162 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
5163 vswap();
5164 gv(rc1);
5165 vswap();
5166 gv(rc2);
5167 /* test if reload is needed for first register */
5168 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
5169 vswap();
5170 gv(rc1);
5171 vswap();
5173 } else {
5174 gv(rc2);
5175 vswap();
5176 gv(rc1);
5177 vswap();
5178 /* test if reload is needed for first register */
5179 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
5180 gv(rc2);
5185 /* wrapper around RC_FRET to return a register by type */
5186 int rc_fret(int t)
5188 #ifdef TCC_TARGET_X86_64
5189 if (t == VT_LDOUBLE) {
5190 return RC_ST0;
5192 #endif
5193 return RC_FRET;
5196 /* wrapper around REG_FRET to return a register by type */
5197 int reg_fret(int t)
5199 #ifdef TCC_TARGET_X86_64
5200 if (t == VT_LDOUBLE) {
5201 return TREG_ST0;
5203 #endif
5204 return REG_FRET;
5207 /* expand long long on stack in two int registers */
5208 void lexpand(void)
5210 int u;
5212 u = vtop->type.t & VT_UNSIGNED;
5213 gv(RC_INT);
5214 vdup();
5215 vtop[0].r = vtop[-1].r2;
5216 vtop[0].r2 = VT_CONST;
5217 vtop[-1].r2 = VT_CONST;
5218 vtop[0].type.t = VT_INT | u;
5219 vtop[-1].type.t = VT_INT | u;
5222 #ifdef TCC_TARGET_ARM
5223 /* expand long long on stack */
5224 void lexpand_nr(void)
5226 int u,v;
5228 u = vtop->type.t & VT_UNSIGNED;
5229 vdup();
5230 vtop->r2 = VT_CONST;
5231 vtop->type.t = VT_INT | u;
5232 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
5233 if (v == VT_CONST) {
5234 vtop[-1].c.ui = vtop->c.ull;
5235 vtop->c.ui = vtop->c.ull >> 32;
5236 vtop->r = VT_CONST;
5237 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
5238 vtop->c.ui += 4;
5239 vtop->r = vtop[-1].r;
5240 } else if (v > VT_CONST) {
5241 vtop--;
5242 lexpand();
5243 } else
5244 vtop->r = vtop[-1].r2;
5245 vtop[-1].r2 = VT_CONST;
5246 vtop[-1].type.t = VT_INT | u;
5248 #endif
5250 /* build a long long from two ints */
5251 void lbuild(int t)
5253 gv2(RC_INT, RC_INT);
5254 vtop[-1].r2 = vtop[0].r;
5255 vtop[-1].type.t = t;
5256 vpop();
5259 /* rotate n first stack elements to the bottom
5260 I1 ... In -> I2 ... In I1 [top is right]
5262 void vrotb(int n)
5264 int i;
5265 SValue tmp;
5267 tmp = vtop[-n + 1];
5268 for(i=-n+1;i!=0;i++)
5269 vtop[i] = vtop[i+1];
5270 vtop[0] = tmp;
5273 /* rotate n first stack elements to the top
5274 I1 ... In -> In I1 ... I(n-1) [top is right]
5276 void vrott(int n)
5278 int i;
5279 SValue tmp;
5281 tmp = vtop[0];
5282 for(i = 0;i < n - 1; i++)
5283 vtop[-i] = vtop[-i - 1];
5284 vtop[-n + 1] = tmp;
5287 #ifdef TCC_TARGET_ARM
5288 /* like vrott but in other direction
5289 In ... I1 -> I(n-1) ... I1 In [top is right]
5291 void vnrott(int n)
5293 int i;
5294 SValue tmp;
5296 tmp = vtop[-n + 1];
5297 for(i = n - 1; i > 0; i--)
5298 vtop[-i] = vtop[-i + 1];
5299 vtop[0] = tmp;
5301 #endif
5303 /* pop stack value */
5304 void vpop(void)
5306 int v;
5307 v = vtop->r & VT_VALMASK;
5308 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5309 /* for x86, we need to pop the FP stack */
5310 if (v == TREG_ST0 && !nocode_wanted) {
5311 o(0xd9dd); /* fstp %st(1) */
5312 } else
5313 #endif
5314 if (v == VT_JMP || v == VT_JMPI) {
5315 /* need to put correct jump if && or || without test */
5316 gsym(vtop->c.ul);
5318 vtop--;
5321 /* convert stack entry to register and duplicate its value in another
5322 register */
5323 void gv_dup(void)
5325 int rc, t, r, r1;
5326 SValue sv;
5328 t = vtop->type.t;
5329 if ((t & VT_BTYPE) == VT_LLONG) {
5330 lexpand();
5331 gv_dup();
5332 vswap();
5333 vrotb(3);
5334 gv_dup();
5335 vrotb(4);
5336 /* stack: H L L1 H1 */
5337 lbuild(t);
5338 vrotb(3);
5339 vrotb(3);
5340 vswap();
5341 lbuild(t);
5342 vswap();
5343 } else {
5344 /* duplicate value */
5345 rc = RC_INT;
5346 sv.type.t = VT_INT;
5347 if (is_float(t)) {
5348 rc = RC_FLOAT;
5349 #ifdef TCC_TARGET_X86_64
5350 if ((t & VT_BTYPE) == VT_LDOUBLE) {
5351 rc = RC_ST0;
5353 #endif
5354 sv.type.t = t;
5356 r = gv(rc);
5357 r1 = get_reg(rc);
5358 sv.r = r;
5359 sv.c.ul = 0;
5360 load(r1, &sv); /* move r to r1 */
5361 vdup();
5362 /* duplicates value */
5363 vtop->r = r1;
5367 #ifndef TCC_TARGET_X86_64
5368 /* generate CPU independent (unsigned) long long operations */
5369 void gen_opl(int op)
5371 int t, a, b, op1, c, i;
5372 int func;
5373 unsigned short reg_iret = REG_IRET;
5374 unsigned short reg_lret = REG_LRET;
5375 SValue tmp;
5377 switch(op) {
5378 case '/':
5379 case TOK_PDIV:
5380 func = TOK___divdi3;
5381 goto gen_func;
5382 case TOK_UDIV:
5383 func = TOK___udivdi3;
5384 goto gen_func;
5385 case '%':
5386 func = TOK___moddi3;
5387 goto gen_mod_func;
5388 case TOK_UMOD:
5389 func = TOK___umoddi3;
5390 gen_mod_func:
5391 #ifdef TCC_ARM_EABI
5392 reg_iret = TREG_R2;
5393 reg_lret = TREG_R3;
5394 #endif
5395 gen_func:
5396 /* call generic long long function */
5397 vpush_global_sym(&func_old_type, func);
5398 vrott(3);
5399 gfunc_call(2);
5400 vpushi(0);
5401 vtop->r = reg_iret;
5402 vtop->r2 = reg_lret;
5403 break;
5404 case '^':
5405 case '&':
5406 case '|':
5407 case '*':
5408 case '+':
5409 case '-':
5410 t = vtop->type.t;
5411 vswap();
5412 lexpand();
5413 vrotb(3);
5414 lexpand();
5415 /* stack: L1 H1 L2 H2 */
5416 tmp = vtop[0];
5417 vtop[0] = vtop[-3];
5418 vtop[-3] = tmp;
5419 tmp = vtop[-2];
5420 vtop[-2] = vtop[-3];
5421 vtop[-3] = tmp;
5422 vswap();
5423 /* stack: H1 H2 L1 L2 */
5424 if (op == '*') {
5425 vpushv(vtop - 1);
5426 vpushv(vtop - 1);
5427 gen_op(TOK_UMULL);
5428 lexpand();
5429 /* stack: H1 H2 L1 L2 ML MH */
5430 for(i=0;i<4;i++)
5431 vrotb(6);
5432 /* stack: ML MH H1 H2 L1 L2 */
5433 tmp = vtop[0];
5434 vtop[0] = vtop[-2];
5435 vtop[-2] = tmp;
5436 /* stack: ML MH H1 L2 H2 L1 */
5437 gen_op('*');
5438 vrotb(3);
5439 vrotb(3);
5440 gen_op('*');
5441 /* stack: ML MH M1 M2 */
5442 gen_op('+');
5443 gen_op('+');
5444 } else if (op == '+' || op == '-') {
5445 /* XXX: add non carry method too (for MIPS or alpha) */
5446 if (op == '+')
5447 op1 = TOK_ADDC1;
5448 else
5449 op1 = TOK_SUBC1;
5450 gen_op(op1);
5451 /* stack: H1 H2 (L1 op L2) */
5452 vrotb(3);
5453 vrotb(3);
5454 gen_op(op1 + 1); /* TOK_xxxC2 */
5455 } else {
5456 gen_op(op);
5457 /* stack: H1 H2 (L1 op L2) */
5458 vrotb(3);
5459 vrotb(3);
5460 /* stack: (L1 op L2) H1 H2 */
5461 gen_op(op);
5462 /* stack: (L1 op L2) (H1 op H2) */
5464 /* stack: L H */
5465 lbuild(t);
5466 break;
5467 case TOK_SAR:
5468 case TOK_SHR:
5469 case TOK_SHL:
5470 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5471 t = vtop[-1].type.t;
5472 vswap();
5473 lexpand();
5474 vrotb(3);
5475 /* stack: L H shift */
5476 c = (int)vtop->c.i;
5477 /* constant: simpler */
5478 /* NOTE: all comments are for SHL. the other cases are
5479 done by swaping words */
5480 vpop();
5481 if (op != TOK_SHL)
5482 vswap();
5483 if (c >= 32) {
5484 /* stack: L H */
5485 vpop();
5486 if (c > 32) {
5487 vpushi(c - 32);
5488 gen_op(op);
5490 if (op != TOK_SAR) {
5491 vpushi(0);
5492 } else {
5493 gv_dup();
5494 vpushi(31);
5495 gen_op(TOK_SAR);
5497 vswap();
5498 } else {
5499 vswap();
5500 gv_dup();
5501 /* stack: H L L */
5502 vpushi(c);
5503 gen_op(op);
5504 vswap();
5505 vpushi(32 - c);
5506 if (op == TOK_SHL)
5507 gen_op(TOK_SHR);
5508 else
5509 gen_op(TOK_SHL);
5510 vrotb(3);
5511 /* stack: L L H */
5512 vpushi(c);
5513 if (op == TOK_SHL)
5514 gen_op(TOK_SHL);
5515 else
5516 gen_op(TOK_SHR);
5517 gen_op('|');
5519 if (op != TOK_SHL)
5520 vswap();
5521 lbuild(t);
5522 } else {
5523 /* XXX: should provide a faster fallback on x86 ? */
5524 switch(op) {
5525 case TOK_SAR:
5526 func = TOK___ashrdi3;
5527 goto gen_func;
5528 case TOK_SHR:
5529 func = TOK___lshrdi3;
5530 goto gen_func;
5531 case TOK_SHL:
5532 func = TOK___ashldi3;
5533 goto gen_func;
5536 break;
5537 default:
5538 /* compare operations */
5539 t = vtop->type.t;
5540 vswap();
5541 lexpand();
5542 vrotb(3);
5543 lexpand();
5544 /* stack: L1 H1 L2 H2 */
5545 tmp = vtop[-1];
5546 vtop[-1] = vtop[-2];
5547 vtop[-2] = tmp;
5548 /* stack: L1 L2 H1 H2 */
5549 /* compare high */
5550 op1 = op;
5551 /* when values are equal, we need to compare low words. since
5552 the jump is inverted, we invert the test too. */
5553 if (op1 == TOK_LT)
5554 op1 = TOK_LE;
5555 else if (op1 == TOK_GT)
5556 op1 = TOK_GE;
5557 else if (op1 == TOK_ULT)
5558 op1 = TOK_ULE;
5559 else if (op1 == TOK_UGT)
5560 op1 = TOK_UGE;
5561 a = 0;
5562 b = 0;
5563 gen_op(op1);
5564 if (op1 != TOK_NE) {
5565 a = gtst(1, 0);
5567 if (op != TOK_EQ) {
5568 /* generate non equal test */
5569 /* XXX: NOT PORTABLE yet */
5570 if (a == 0) {
5571 b = gtst(0, 0);
5572 } else {
5573 #if defined(TCC_TARGET_I386)
5574 b = psym(0x850f, 0);
5575 #elif defined(TCC_TARGET_ARM)
5576 b = ind;
5577 o(0x1A000000 | encbranch(ind, 0, 1));
5578 #elif defined(TCC_TARGET_C67)
5579 error("not implemented");
5580 #else
5581 #error not supported
5582 #endif
5585 /* compare low. Always unsigned */
5586 op1 = op;
5587 if (op1 == TOK_LT)
5588 op1 = TOK_ULT;
5589 else if (op1 == TOK_LE)
5590 op1 = TOK_ULE;
5591 else if (op1 == TOK_GT)
5592 op1 = TOK_UGT;
5593 else if (op1 == TOK_GE)
5594 op1 = TOK_UGE;
5595 gen_op(op1);
5596 a = gtst(1, a);
5597 gsym(b);
5598 vseti(VT_JMPI, a);
5599 break;
5602 #endif
5604 /* handle integer constant optimizations and various machine
5605 independent opt */
5606 void gen_opic(int op)
5608 int c1, c2, t1, t2, n;
5609 SValue *v1, *v2;
5610 long long l1, l2;
5611 typedef unsigned long long U;
5613 v1 = vtop - 1;
5614 v2 = vtop;
5615 t1 = v1->type.t & VT_BTYPE;
5616 t2 = v2->type.t & VT_BTYPE;
5618 if (t1 == VT_LLONG)
5619 l1 = v1->c.ll;
5620 else if (v1->type.t & VT_UNSIGNED)
5621 l1 = v1->c.ui;
5622 else
5623 l1 = v1->c.i;
5625 if (t2 == VT_LLONG)
5626 l2 = v2->c.ll;
5627 else if (v2->type.t & VT_UNSIGNED)
5628 l2 = v2->c.ui;
5629 else
5630 l2 = v2->c.i;
5632 /* currently, we cannot do computations with forward symbols */
5633 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5634 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5635 if (c1 && c2) {
5636 switch(op) {
5637 case '+': l1 += l2; break;
5638 case '-': l1 -= l2; break;
5639 case '&': l1 &= l2; break;
5640 case '^': l1 ^= l2; break;
5641 case '|': l1 |= l2; break;
5642 case '*': l1 *= l2; break;
5644 case TOK_PDIV:
5645 case '/':
5646 case '%':
5647 case TOK_UDIV:
5648 case TOK_UMOD:
5649 /* if division by zero, generate explicit division */
5650 if (l2 == 0) {
5651 if (const_wanted)
5652 error("division by zero in constant");
5653 goto general_case;
5655 switch(op) {
5656 default: l1 /= l2; break;
5657 case '%': l1 %= l2; break;
5658 case TOK_UDIV: l1 = (U)l1 / l2; break;
5659 case TOK_UMOD: l1 = (U)l1 % l2; break;
5661 break;
5662 case TOK_SHL: l1 <<= l2; break;
5663 case TOK_SHR: l1 = (U)l1 >> l2; break;
5664 case TOK_SAR: l1 >>= l2; break;
5665 /* tests */
5666 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
5667 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
5668 case TOK_EQ: l1 = l1 == l2; break;
5669 case TOK_NE: l1 = l1 != l2; break;
5670 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
5671 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
5672 case TOK_LT: l1 = l1 < l2; break;
5673 case TOK_GE: l1 = l1 >= l2; break;
5674 case TOK_LE: l1 = l1 <= l2; break;
5675 case TOK_GT: l1 = l1 > l2; break;
5676 /* logical */
5677 case TOK_LAND: l1 = l1 && l2; break;
5678 case TOK_LOR: l1 = l1 || l2; break;
5679 default:
5680 goto general_case;
5682 v1->c.ll = l1;
5683 vtop--;
5684 } else {
5685 /* if commutative ops, put c2 as constant */
5686 if (c1 && (op == '+' || op == '&' || op == '^' ||
5687 op == '|' || op == '*')) {
5688 vswap();
5689 c2 = c1; //c = c1, c1 = c2, c2 = c;
5690 l2 = l1; //l = l1, l1 = l2, l2 = l;
5692 /* Filter out NOP operations like x*1, x-0, x&-1... */
5693 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
5694 op == TOK_PDIV) &&
5695 l2 == 1) ||
5696 ((op == '+' || op == '-' || op == '|' || op == '^' ||
5697 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
5698 l2 == 0) ||
5699 (op == '&' &&
5700 l2 == -1))) {
5701 /* nothing to do */
5702 vtop--;
5703 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
5704 /* try to use shifts instead of muls or divs */
5705 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
5706 n = -1;
5707 while (l2) {
5708 l2 >>= 1;
5709 n++;
5711 vtop->c.ll = n;
5712 if (op == '*')
5713 op = TOK_SHL;
5714 else if (op == TOK_PDIV)
5715 op = TOK_SAR;
5716 else
5717 op = TOK_SHR;
5719 goto general_case;
5720 } else if (c2 && (op == '+' || op == '-') &&
5721 ((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) ==
5722 (VT_CONST | VT_SYM) ||
5723 (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
5724 /* symbol + constant case */
5725 if (op == '-')
5726 l2 = -l2;
5727 vtop--;
5728 vtop->c.ll += l2;
5729 } else {
5730 general_case:
5731 if (!nocode_wanted) {
5732 /* call low level op generator */
5733 if (t1 == VT_LLONG || t2 == VT_LLONG)
5734 gen_opl(op);
5735 else
5736 gen_opi(op);
5737 } else {
5738 vtop--;
5744 /* generate a floating point operation with constant propagation */
5745 void gen_opif(int op)
5747 int c1, c2;
5748 SValue *v1, *v2;
5749 long double f1, f2;
5751 v1 = vtop - 1;
5752 v2 = vtop;
5753 /* currently, we cannot do computations with forward symbols */
5754 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5755 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5756 if (c1 && c2) {
5757 if (v1->type.t == VT_FLOAT) {
5758 f1 = v1->c.f;
5759 f2 = v2->c.f;
5760 } else if (v1->type.t == VT_DOUBLE) {
5761 f1 = v1->c.d;
5762 f2 = v2->c.d;
5763 } else {
5764 f1 = v1->c.ld;
5765 f2 = v2->c.ld;
5768 /* NOTE: we only do constant propagation if finite number (not
5769 NaN or infinity) (ANSI spec) */
5770 if (!ieee_finite(f1) || !ieee_finite(f2))
5771 goto general_case;
5773 switch(op) {
5774 case '+': f1 += f2; break;
5775 case '-': f1 -= f2; break;
5776 case '*': f1 *= f2; break;
5777 case '/':
5778 if (f2 == 0.0) {
5779 if (const_wanted)
5780 error("division by zero in constant");
5781 goto general_case;
5783 f1 /= f2;
5784 break;
5785 /* XXX: also handles tests ? */
5786 default:
5787 goto general_case;
5789 /* XXX: overflow test ? */
5790 if (v1->type.t == VT_FLOAT) {
5791 v1->c.f = f1;
5792 } else if (v1->type.t == VT_DOUBLE) {
5793 v1->c.d = f1;
5794 } else {
5795 v1->c.ld = f1;
5797 vtop--;
5798 } else {
5799 general_case:
5800 if (!nocode_wanted) {
5801 gen_opf(op);
5802 } else {
5803 vtop--;
5808 static int pointed_size(CType *type)
5810 int align;
5811 return type_size(pointed_type(type), &align);
5814 static inline int is_null_pointer(SValue *p)
5816 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5817 return 0;
5818 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
5819 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
5822 static inline int is_integer_btype(int bt)
5824 return (bt == VT_BYTE || bt == VT_SHORT ||
5825 bt == VT_INT || bt == VT_LLONG);
5828 /* check types for comparison or substraction of pointers */
5829 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
5831 CType *type1, *type2, tmp_type1, tmp_type2;
5832 int bt1, bt2;
5834 /* null pointers are accepted for all comparisons as gcc */
5835 if (is_null_pointer(p1) || is_null_pointer(p2))
5836 return;
5837 type1 = &p1->type;
5838 type2 = &p2->type;
5839 bt1 = type1->t & VT_BTYPE;
5840 bt2 = type2->t & VT_BTYPE;
5841 /* accept comparison between pointer and integer with a warning */
5842 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
5843 if (op != TOK_LOR && op != TOK_LAND )
5844 warning("comparison between pointer and integer");
5845 return;
5848 /* both must be pointers or implicit function pointers */
5849 if (bt1 == VT_PTR) {
5850 type1 = pointed_type(type1);
5851 } else if (bt1 != VT_FUNC)
5852 goto invalid_operands;
5854 if (bt2 == VT_PTR) {
5855 type2 = pointed_type(type2);
5856 } else if (bt2 != VT_FUNC) {
5857 invalid_operands:
5858 error("invalid operands to binary %s", get_tok_str(op, NULL));
5860 if ((type1->t & VT_BTYPE) == VT_VOID ||
5861 (type2->t & VT_BTYPE) == VT_VOID)
5862 return;
5863 tmp_type1 = *type1;
5864 tmp_type2 = *type2;
5865 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5866 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5867 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
5868 /* gcc-like error if '-' is used */
5869 if (op == '-')
5870 goto invalid_operands;
5871 else
5872 warning("comparison of distinct pointer types lacks a cast");
5876 /* generic gen_op: handles types problems */
5877 void gen_op(int op)
5879 int u, t1, t2, bt1, bt2, t;
5880 CType type1;
5882 t1 = vtop[-1].type.t;
5883 t2 = vtop[0].type.t;
5884 bt1 = t1 & VT_BTYPE;
5885 bt2 = t2 & VT_BTYPE;
5887 if (bt1 == VT_PTR || bt2 == VT_PTR) {
5888 /* at least one operand is a pointer */
5889 /* relationnal op: must be both pointers */
5890 if (op >= TOK_ULT && op <= TOK_LOR) {
5891 check_comparison_pointer_types(vtop - 1, vtop, op);
5892 /* pointers are handled are unsigned */
5893 #ifdef TCC_TARGET_X86_64
5894 t = VT_LLONG | VT_UNSIGNED;
5895 #else
5896 t = VT_INT | VT_UNSIGNED;
5897 #endif
5898 goto std_op;
5900 /* if both pointers, then it must be the '-' op */
5901 if (bt1 == VT_PTR && bt2 == VT_PTR) {
5902 if (op != '-')
5903 error("cannot use pointers here");
5904 check_comparison_pointer_types(vtop - 1, vtop, op);
5905 /* XXX: check that types are compatible */
5906 u = pointed_size(&vtop[-1].type);
5907 gen_opic(op);
5908 /* set to integer type */
5909 #ifdef TCC_TARGET_X86_64
5910 vtop->type.t = VT_LLONG;
5911 #else
5912 vtop->type.t = VT_INT;
5913 #endif
5914 vpushi(u);
5915 gen_op(TOK_PDIV);
5916 } else {
5917 /* exactly one pointer : must be '+' or '-'. */
5918 if (op != '-' && op != '+')
5919 error("cannot use pointers here");
5920 /* Put pointer as first operand */
5921 if (bt2 == VT_PTR) {
5922 vswap();
5923 swap(&t1, &t2);
5925 type1 = vtop[-1].type;
5926 #ifdef TCC_TARGET_X86_64
5927 vpushll(pointed_size(&vtop[-1].type));
5928 #else
5929 /* XXX: cast to int ? (long long case) */
5930 vpushi(pointed_size(&vtop[-1].type));
5931 #endif
5932 gen_op('*');
5933 #ifdef CONFIG_TCC_BCHECK
5934 /* if evaluating constant expression, no code should be
5935 generated, so no bound check */
5936 if (do_bounds_check && !const_wanted) {
5937 /* if bounded pointers, we generate a special code to
5938 test bounds */
5939 if (op == '-') {
5940 vpushi(0);
5941 vswap();
5942 gen_op('-');
5944 gen_bounded_ptr_add();
5945 } else
5946 #endif
5948 gen_opic(op);
5950 /* put again type if gen_opic() swaped operands */
5951 vtop->type = type1;
5953 } else if (is_float(bt1) || is_float(bt2)) {
5954 /* compute bigger type and do implicit casts */
5955 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5956 t = VT_LDOUBLE;
5957 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5958 t = VT_DOUBLE;
5959 } else {
5960 t = VT_FLOAT;
5962 /* floats can only be used for a few operations */
5963 if (op != '+' && op != '-' && op != '*' && op != '/' &&
5964 (op < TOK_ULT || op > TOK_GT))
5965 error("invalid operands for binary operation");
5966 goto std_op;
5967 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5968 /* cast to biggest op */
5969 t = VT_LLONG;
5970 /* convert to unsigned if it does not fit in a long long */
5971 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5972 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5973 t |= VT_UNSIGNED;
5974 goto std_op;
5975 } else {
5976 /* integer operations */
5977 t = VT_INT;
5978 /* convert to unsigned if it does not fit in an integer */
5979 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5980 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5981 t |= VT_UNSIGNED;
5982 std_op:
5983 /* XXX: currently, some unsigned operations are explicit, so
5984 we modify them here */
5985 if (t & VT_UNSIGNED) {
5986 if (op == TOK_SAR)
5987 op = TOK_SHR;
5988 else if (op == '/')
5989 op = TOK_UDIV;
5990 else if (op == '%')
5991 op = TOK_UMOD;
5992 else if (op == TOK_LT)
5993 op = TOK_ULT;
5994 else if (op == TOK_GT)
5995 op = TOK_UGT;
5996 else if (op == TOK_LE)
5997 op = TOK_ULE;
5998 else if (op == TOK_GE)
5999 op = TOK_UGE;
6001 vswap();
6002 type1.t = t;
6003 gen_cast(&type1);
6004 vswap();
6005 /* special case for shifts and long long: we keep the shift as
6006 an integer */
6007 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
6008 type1.t = VT_INT;
6009 gen_cast(&type1);
6010 if (is_float(t))
6011 gen_opif(op);
6012 else
6013 gen_opic(op);
6014 if (op >= TOK_ULT && op <= TOK_GT) {
6015 /* relationnal op: the result is an int */
6016 vtop->type.t = VT_INT;
6017 } else {
6018 vtop->type.t = t;
6023 #ifndef TCC_TARGET_ARM
6024 /* generic itof for unsigned long long case */
6025 void gen_cvt_itof1(int t)
6027 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
6028 (VT_LLONG | VT_UNSIGNED)) {
6030 if (t == VT_FLOAT)
6031 vpush_global_sym(&func_old_type, TOK___floatundisf);
6032 #if LDOUBLE_SIZE != 8
6033 else if (t == VT_LDOUBLE)
6034 vpush_global_sym(&func_old_type, TOK___floatundixf);
6035 #endif
6036 else
6037 vpush_global_sym(&func_old_type, TOK___floatundidf);
6038 vrott(2);
6039 gfunc_call(1);
6040 vpushi(0);
6041 vtop->r = reg_fret(t);
6042 } else {
6043 gen_cvt_itof(t);
6046 #endif
6048 /* generic ftoi for unsigned long long case */
6049 void gen_cvt_ftoi1(int t)
6051 int st;
6053 if (t == (VT_LLONG | VT_UNSIGNED)) {
6054 /* not handled natively */
6055 st = vtop->type.t & VT_BTYPE;
6056 if (st == VT_FLOAT)
6057 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
6058 #if LDOUBLE_SIZE != 8
6059 else if (st == VT_LDOUBLE)
6060 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
6061 #endif
6062 else
6063 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
6064 vrott(2);
6065 gfunc_call(1);
6066 vpushi(0);
6067 vtop->r = REG_IRET;
6068 vtop->r2 = REG_LRET;
6069 } else {
6070 gen_cvt_ftoi(t);
6074 /* force char or short cast */
6075 void force_charshort_cast(int t)
6077 int bits, dbt;
6078 dbt = t & VT_BTYPE;
6079 /* XXX: add optimization if lvalue : just change type and offset */
6080 if (dbt == VT_BYTE)
6081 bits = 8;
6082 else
6083 bits = 16;
6084 if (t & VT_UNSIGNED) {
6085 vpushi((1 << bits) - 1);
6086 gen_op('&');
6087 } else {
6088 bits = 32 - bits;
6089 vpushi(bits);
6090 gen_op(TOK_SHL);
6091 /* result must be signed or the SAR is converted to an SHL
6092 This was not the case when "t" was a signed short
6093 and the last value on the stack was an unsigned int */
6094 vtop->type.t &= ~VT_UNSIGNED;
6095 vpushi(bits);
6096 gen_op(TOK_SAR);
6100 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6101 static void gen_cast(CType *type)
6103 int sbt, dbt, sf, df, c, p;
6105 /* special delayed cast for char/short */
6106 /* XXX: in some cases (multiple cascaded casts), it may still
6107 be incorrect */
6108 if (vtop->r & VT_MUSTCAST) {
6109 vtop->r &= ~VT_MUSTCAST;
6110 force_charshort_cast(vtop->type.t);
6113 /* bitfields first get cast to ints */
6114 if (vtop->type.t & VT_BITFIELD) {
6115 gv(RC_INT);
6118 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
6119 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
6121 if (sbt != dbt) {
6122 sf = is_float(sbt);
6123 df = is_float(dbt);
6124 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
6125 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
6126 if (c) {
6127 /* constant case: we can do it now */
6128 /* XXX: in ISOC, cannot do it if error in convert */
6129 if (sbt == VT_FLOAT)
6130 vtop->c.ld = vtop->c.f;
6131 else if (sbt == VT_DOUBLE)
6132 vtop->c.ld = vtop->c.d;
6134 if (df) {
6135 if ((sbt & VT_BTYPE) == VT_LLONG) {
6136 if (sbt & VT_UNSIGNED)
6137 vtop->c.ld = vtop->c.ull;
6138 else
6139 vtop->c.ld = vtop->c.ll;
6140 } else if(!sf) {
6141 if (sbt & VT_UNSIGNED)
6142 vtop->c.ld = vtop->c.ui;
6143 else
6144 vtop->c.ld = vtop->c.i;
6147 if (dbt == VT_FLOAT)
6148 vtop->c.f = (float)vtop->c.ld;
6149 else if (dbt == VT_DOUBLE)
6150 vtop->c.d = (double)vtop->c.ld;
6151 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
6152 vtop->c.ull = (unsigned long long)vtop->c.ld;
6153 } else if (sf && dbt == VT_BOOL) {
6154 vtop->c.i = (vtop->c.ld != 0);
6155 } else {
6156 if(sf)
6157 vtop->c.ll = (long long)vtop->c.ld;
6158 else if (sbt == (VT_LLONG|VT_UNSIGNED))
6159 vtop->c.ll = vtop->c.ull;
6160 else if (sbt & VT_UNSIGNED)
6161 vtop->c.ll = vtop->c.ui;
6162 else if (sbt != VT_LLONG)
6163 vtop->c.ll = vtop->c.i;
6165 if (dbt == (VT_LLONG|VT_UNSIGNED))
6166 vtop->c.ull = vtop->c.ll;
6167 else if (dbt == VT_BOOL)
6168 vtop->c.i = (vtop->c.ll != 0);
6169 else if (dbt != VT_LLONG) {
6170 int s = 0;
6171 if ((dbt & VT_BTYPE) == VT_BYTE)
6172 s = 24;
6173 else if ((dbt & VT_BTYPE) == VT_SHORT)
6174 s = 16;
6176 if(dbt & VT_UNSIGNED)
6177 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
6178 else
6179 vtop->c.i = ((int)vtop->c.ll << s) >> s;
6182 } else if (p && dbt == VT_BOOL) {
6183 vtop->r = VT_CONST;
6184 vtop->c.i = 1;
6185 } else if (!nocode_wanted) {
6186 /* non constant case: generate code */
6187 if (sf && df) {
6188 /* convert from fp to fp */
6189 gen_cvt_ftof(dbt);
6190 } else if (df) {
6191 /* convert int to fp */
6192 gen_cvt_itof1(dbt);
6193 } else if (sf) {
6194 /* convert fp to int */
6195 if (dbt == VT_BOOL) {
6196 vpushi(0);
6197 gen_op(TOK_NE);
6198 } else {
6199 /* we handle char/short/etc... with generic code */
6200 if (dbt != (VT_INT | VT_UNSIGNED) &&
6201 dbt != (VT_LLONG | VT_UNSIGNED) &&
6202 dbt != VT_LLONG)
6203 dbt = VT_INT;
6204 gen_cvt_ftoi1(dbt);
6205 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
6206 /* additional cast for char/short... */
6207 vtop->type.t = dbt;
6208 gen_cast(type);
6211 #ifndef TCC_TARGET_X86_64
6212 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
6213 if ((sbt & VT_BTYPE) != VT_LLONG) {
6214 /* scalar to long long */
6215 /* machine independent conversion */
6216 gv(RC_INT);
6217 /* generate high word */
6218 if (sbt == (VT_INT | VT_UNSIGNED)) {
6219 vpushi(0);
6220 gv(RC_INT);
6221 } else {
6222 if (sbt == VT_PTR) {
6223 /* cast from pointer to int before we apply
6224 shift operation, which pointers don't support*/
6225 gen_cast(&int_type);
6227 gv_dup();
6228 vpushi(31);
6229 gen_op(TOK_SAR);
6231 /* patch second register */
6232 vtop[-1].r2 = vtop->r;
6233 vpop();
6235 #else
6236 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
6237 (dbt & VT_BTYPE) == VT_PTR) {
6238 /* XXX: not sure if this is perfect... need more tests */
6239 if ((sbt & VT_BTYPE) != VT_LLONG) {
6240 int r = gv(RC_INT);
6241 if (sbt != (VT_INT | VT_UNSIGNED) &&
6242 sbt != VT_PTR && sbt != VT_FUNC) {
6243 /* x86_64 specific: movslq */
6244 o(0x6348);
6245 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
6248 #endif
6249 } else if (dbt == VT_BOOL) {
6250 /* scalar to bool */
6251 vpushi(0);
6252 gen_op(TOK_NE);
6253 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
6254 (dbt & VT_BTYPE) == VT_SHORT) {
6255 if (sbt == VT_PTR) {
6256 vtop->type.t = VT_INT;
6257 warning("nonportable conversion from pointer to char/short");
6259 force_charshort_cast(dbt);
6260 } else if ((dbt & VT_BTYPE) == VT_INT) {
6261 /* scalar to int */
6262 if (sbt == VT_LLONG) {
6263 /* from long long: just take low order word */
6264 lexpand();
6265 vpop();
6267 /* if lvalue and single word type, nothing to do because
6268 the lvalue already contains the real type size (see
6269 VT_LVAL_xxx constants) */
6272 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
6273 /* if we are casting between pointer types,
6274 we must update the VT_LVAL_xxx size */
6275 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
6276 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
6278 vtop->type = *type;
6281 /* return type size. Put alignment at 'a' */
6282 static int type_size(CType *type, int *a)
6284 Sym *s;
6285 int bt;
6287 bt = type->t & VT_BTYPE;
6288 if (bt == VT_STRUCT) {
6289 /* struct/union */
6290 s = type->ref;
6291 *a = s->r;
6292 return s->c;
6293 } else if (bt == VT_PTR) {
6294 if (type->t & VT_ARRAY) {
6295 int ts;
6297 s = type->ref;
6298 ts = type_size(&s->type, a);
6300 if (ts < 0 && s->c < 0)
6301 ts = -ts;
6303 return ts * s->c;
6304 } else {
6305 *a = PTR_SIZE;
6306 return PTR_SIZE;
6308 } else if (bt == VT_LDOUBLE) {
6309 *a = LDOUBLE_ALIGN;
6310 return LDOUBLE_SIZE;
6311 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
6312 #ifdef TCC_TARGET_I386
6313 #ifdef TCC_TARGET_PE
6314 *a = 8;
6315 #else
6316 *a = 4;
6317 #endif
6318 #elif defined(TCC_TARGET_ARM)
6319 #ifdef TCC_ARM_EABI
6320 *a = 8;
6321 #else
6322 *a = 4;
6323 #endif
6324 #else
6325 *a = 8;
6326 #endif
6327 return 8;
6328 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
6329 *a = 4;
6330 return 4;
6331 } else if (bt == VT_SHORT) {
6332 *a = 2;
6333 return 2;
6334 } else {
6335 /* char, void, function, _Bool */
6336 *a = 1;
6337 return 1;
6341 /* return the pointed type of t */
6342 static inline CType *pointed_type(CType *type)
6344 return &type->ref->type;
6347 /* modify type so that its it is a pointer to type. */
6348 static void mk_pointer(CType *type)
6350 Sym *s;
6351 s = sym_push(SYM_FIELD, type, 0, -1);
6352 type->t = VT_PTR | (type->t & ~VT_TYPE);
6353 type->ref = s;
6356 /* compare function types. OLD functions match any new functions */
6357 static int is_compatible_func(CType *type1, CType *type2)
6359 Sym *s1, *s2;
6361 s1 = type1->ref;
6362 s2 = type2->ref;
6363 if (!is_compatible_types(&s1->type, &s2->type))
6364 return 0;
6365 /* check func_call */
6366 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
6367 return 0;
6368 /* XXX: not complete */
6369 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
6370 return 1;
6371 if (s1->c != s2->c)
6372 return 0;
6373 while (s1 != NULL) {
6374 if (s2 == NULL)
6375 return 0;
6376 if (!is_compatible_parameter_types(&s1->type, &s2->type))
6377 return 0;
6378 s1 = s1->next;
6379 s2 = s2->next;
6381 if (s2)
6382 return 0;
6383 return 1;
6386 /* return true if type1 and type2 are the same. If unqualified is
6387 true, qualifiers on the types are ignored.
6389 - enums are not checked as gcc __builtin_types_compatible_p ()
6391 static int compare_types(CType *type1, CType *type2, int unqualified)
6393 int bt1, t1, t2;
6395 t1 = type1->t & VT_TYPE;
6396 t2 = type2->t & VT_TYPE;
6397 if (unqualified) {
6398 /* strip qualifiers before comparing */
6399 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
6400 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
6402 /* XXX: bitfields ? */
6403 if (t1 != t2)
6404 return 0;
6405 /* test more complicated cases */
6406 bt1 = t1 & VT_BTYPE;
6407 if (bt1 == VT_PTR) {
6408 type1 = pointed_type(type1);
6409 type2 = pointed_type(type2);
6410 return is_compatible_types(type1, type2);
6411 } else if (bt1 == VT_STRUCT) {
6412 return (type1->ref == type2->ref);
6413 } else if (bt1 == VT_FUNC) {
6414 return is_compatible_func(type1, type2);
6415 } else {
6416 return 1;
6420 /* return true if type1 and type2 are exactly the same (including
6421 qualifiers).
6423 static int is_compatible_types(CType *type1, CType *type2)
6425 return compare_types(type1,type2,0);
6428 /* return true if type1 and type2 are the same (ignoring qualifiers).
6430 static int is_compatible_parameter_types(CType *type1, CType *type2)
6432 return compare_types(type1,type2,1);
6435 /* print a type. If 'varstr' is not NULL, then the variable is also
6436 printed in the type */
6437 /* XXX: union */
6438 /* XXX: add array and function pointers */
6439 void type_to_str(char *buf, int buf_size,
6440 CType *type, const char *varstr)
6442 int bt, v, t;
6443 Sym *s, *sa;
6444 char buf1[256];
6445 const char *tstr;
6447 t = type->t & VT_TYPE;
6448 bt = t & VT_BTYPE;
6449 buf[0] = '\0';
6450 if (t & VT_CONSTANT)
6451 pstrcat(buf, buf_size, "const ");
6452 if (t & VT_VOLATILE)
6453 pstrcat(buf, buf_size, "volatile ");
6454 if (t & VT_UNSIGNED)
6455 pstrcat(buf, buf_size, "unsigned ");
6456 switch(bt) {
6457 case VT_VOID:
6458 tstr = "void";
6459 goto add_tstr;
6460 case VT_BOOL:
6461 tstr = "_Bool";
6462 goto add_tstr;
6463 case VT_BYTE:
6464 tstr = "char";
6465 goto add_tstr;
6466 case VT_SHORT:
6467 tstr = "short";
6468 goto add_tstr;
6469 case VT_INT:
6470 tstr = "int";
6471 goto add_tstr;
6472 case VT_LONG:
6473 tstr = "long";
6474 goto add_tstr;
6475 case VT_LLONG:
6476 tstr = "long long";
6477 goto add_tstr;
6478 case VT_FLOAT:
6479 tstr = "float";
6480 goto add_tstr;
6481 case VT_DOUBLE:
6482 tstr = "double";
6483 goto add_tstr;
6484 case VT_LDOUBLE:
6485 tstr = "long double";
6486 add_tstr:
6487 pstrcat(buf, buf_size, tstr);
6488 break;
6489 case VT_ENUM:
6490 case VT_STRUCT:
6491 if (bt == VT_STRUCT)
6492 tstr = "struct ";
6493 else
6494 tstr = "enum ";
6495 pstrcat(buf, buf_size, tstr);
6496 v = type->ref->v & ~SYM_STRUCT;
6497 if (v >= SYM_FIRST_ANOM)
6498 pstrcat(buf, buf_size, "<anonymous>");
6499 else
6500 pstrcat(buf, buf_size, get_tok_str(v, NULL));
6501 break;
6502 case VT_FUNC:
6503 s = type->ref;
6504 type_to_str(buf, buf_size, &s->type, varstr);
6505 pstrcat(buf, buf_size, "(");
6506 sa = s->next;
6507 while (sa != NULL) {
6508 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
6509 pstrcat(buf, buf_size, buf1);
6510 sa = sa->next;
6511 if (sa)
6512 pstrcat(buf, buf_size, ", ");
6514 pstrcat(buf, buf_size, ")");
6515 goto no_var;
6516 case VT_PTR:
6517 s = type->ref;
6518 pstrcpy(buf1, sizeof(buf1), "*");
6519 if (varstr)
6520 pstrcat(buf1, sizeof(buf1), varstr);
6521 type_to_str(buf, buf_size, &s->type, buf1);
6522 goto no_var;
6524 if (varstr) {
6525 pstrcat(buf, buf_size, " ");
6526 pstrcat(buf, buf_size, varstr);
6528 no_var: ;
6531 /* verify type compatibility to store vtop in 'dt' type, and generate
6532 casts if needed. */
6533 static void gen_assign_cast(CType *dt)
6535 CType *st, *type1, *type2, tmp_type1, tmp_type2;
6536 char buf1[256], buf2[256];
6537 int dbt, sbt;
6539 st = &vtop->type; /* source type */
6540 dbt = dt->t & VT_BTYPE;
6541 sbt = st->t & VT_BTYPE;
6542 if (dt->t & VT_CONSTANT)
6543 warning("assignment of read-only location");
6544 switch(dbt) {
6545 case VT_PTR:
6546 /* special cases for pointers */
6547 /* '0' can also be a pointer */
6548 if (is_null_pointer(vtop))
6549 goto type_ok;
6550 /* accept implicit pointer to integer cast with warning */
6551 if (is_integer_btype(sbt)) {
6552 warning("assignment makes pointer from integer without a cast");
6553 goto type_ok;
6555 type1 = pointed_type(dt);
6556 /* a function is implicitely a function pointer */
6557 if (sbt == VT_FUNC) {
6558 if ((type1->t & VT_BTYPE) != VT_VOID &&
6559 !is_compatible_types(pointed_type(dt), st))
6560 goto error;
6561 else
6562 goto type_ok;
6564 if (sbt != VT_PTR)
6565 goto error;
6566 type2 = pointed_type(st);
6567 if ((type1->t & VT_BTYPE) == VT_VOID ||
6568 (type2->t & VT_BTYPE) == VT_VOID) {
6569 /* void * can match anything */
6570 } else {
6571 /* exact type match, except for unsigned */
6572 tmp_type1 = *type1;
6573 tmp_type2 = *type2;
6574 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6575 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6576 if (!is_compatible_types(&tmp_type1, &tmp_type2))
6577 warning("assignment from incompatible pointer type");
6579 /* check const and volatile */
6580 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
6581 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
6582 warning("assignment discards qualifiers from pointer target type");
6583 break;
6584 case VT_BYTE:
6585 case VT_SHORT:
6586 case VT_INT:
6587 case VT_LLONG:
6588 if (sbt == VT_PTR || sbt == VT_FUNC) {
6589 warning("assignment makes integer from pointer without a cast");
6591 /* XXX: more tests */
6592 break;
6593 case VT_STRUCT:
6594 tmp_type1 = *dt;
6595 tmp_type2 = *st;
6596 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
6597 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
6598 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
6599 error:
6600 type_to_str(buf1, sizeof(buf1), st, NULL);
6601 type_to_str(buf2, sizeof(buf2), dt, NULL);
6602 error("cannot cast '%s' to '%s'", buf1, buf2);
6604 break;
6606 type_ok:
6607 gen_cast(dt);
6610 /* store vtop in lvalue pushed on stack */
6611 void vstore(void)
6613 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
6615 ft = vtop[-1].type.t;
6616 sbt = vtop->type.t & VT_BTYPE;
6617 dbt = ft & VT_BTYPE;
6618 if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
6619 (sbt == VT_INT && dbt == VT_SHORT)) {
6620 /* optimize char/short casts */
6621 delayed_cast = VT_MUSTCAST;
6622 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
6623 /* XXX: factorize */
6624 if (ft & VT_CONSTANT)
6625 warning("assignment of read-only location");
6626 } else {
6627 delayed_cast = 0;
6628 if (!(ft & VT_BITFIELD))
6629 gen_assign_cast(&vtop[-1].type);
6632 if (sbt == VT_STRUCT) {
6633 /* if structure, only generate pointer */
6634 /* structure assignment : generate memcpy */
6635 /* XXX: optimize if small size */
6636 if (!nocode_wanted) {
6637 size = type_size(&vtop->type, &align);
6639 #ifdef TCC_ARM_EABI
6640 if(!(align & 7))
6641 vpush_global_sym(&func_old_type, TOK_memcpy8);
6642 else if(!(align & 3))
6643 vpush_global_sym(&func_old_type, TOK_memcpy4);
6644 else
6645 #endif
6646 vpush_global_sym(&func_old_type, TOK_memcpy);
6648 /* destination */
6649 vpushv(vtop - 2);
6650 vtop->type.t = VT_PTR;
6651 gaddrof();
6652 /* source */
6653 vpushv(vtop - 2);
6654 vtop->type.t = VT_PTR;
6655 gaddrof();
6656 /* type size */
6657 vpushi(size);
6658 gfunc_call(3);
6660 vswap();
6661 vpop();
6662 } else {
6663 vswap();
6664 vpop();
6666 /* leave source on stack */
6667 } else if (ft & VT_BITFIELD) {
6668 /* bitfield store handling */
6669 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
6670 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
6671 /* remove bit field info to avoid loops */
6672 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
6674 /* duplicate source into other register */
6675 gv_dup();
6676 vswap();
6677 vrott(3);
6679 if((ft & VT_BTYPE) == VT_BOOL) {
6680 gen_cast(&vtop[-1].type);
6681 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
6684 /* duplicate destination */
6685 vdup();
6686 vtop[-1] = vtop[-2];
6688 /* mask and shift source */
6689 if((ft & VT_BTYPE) != VT_BOOL) {
6690 if((ft & VT_BTYPE) == VT_LLONG) {
6691 vpushll((1ULL << bit_size) - 1ULL);
6692 } else {
6693 vpushi((1 << bit_size) - 1);
6695 gen_op('&');
6697 vpushi(bit_pos);
6698 gen_op(TOK_SHL);
6699 /* load destination, mask and or with source */
6700 vswap();
6701 if((ft & VT_BTYPE) == VT_LLONG) {
6702 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
6703 } else {
6704 vpushi(~(((1 << bit_size) - 1) << bit_pos));
6706 gen_op('&');
6707 gen_op('|');
6708 /* store result */
6709 vstore();
6711 /* pop off shifted source from "duplicate source..." above */
6712 vpop();
6714 } else {
6715 #ifdef CONFIG_TCC_BCHECK
6716 /* bound check case */
6717 if (vtop[-1].r & VT_MUSTBOUND) {
6718 vswap();
6719 gbound();
6720 vswap();
6722 #endif
6723 if (!nocode_wanted) {
6724 rc = RC_INT;
6725 if (is_float(ft)) {
6726 rc = RC_FLOAT;
6727 #ifdef TCC_TARGET_X86_64
6728 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
6729 rc = RC_ST0;
6731 #endif
6733 r = gv(rc); /* generate value */
6734 /* if lvalue was saved on stack, must read it */
6735 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
6736 SValue sv;
6737 t = get_reg(RC_INT);
6738 #ifdef TCC_TARGET_X86_64
6739 sv.type.t = VT_PTR;
6740 #else
6741 sv.type.t = VT_INT;
6742 #endif
6743 sv.r = VT_LOCAL | VT_LVAL;
6744 sv.c.ul = vtop[-1].c.ul;
6745 load(t, &sv);
6746 vtop[-1].r = t | VT_LVAL;
6748 store(r, vtop - 1);
6749 #ifndef TCC_TARGET_X86_64
6750 /* two word case handling : store second register at word + 4 */
6751 if ((ft & VT_BTYPE) == VT_LLONG) {
6752 vswap();
6753 /* convert to int to increment easily */
6754 vtop->type.t = VT_INT;
6755 gaddrof();
6756 vpushi(4);
6757 gen_op('+');
6758 vtop->r |= VT_LVAL;
6759 vswap();
6760 /* XXX: it works because r2 is spilled last ! */
6761 store(vtop->r2, vtop - 1);
6763 #endif
6765 vswap();
6766 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
6767 vtop->r |= delayed_cast;
6771 /* post defines POST/PRE add. c is the token ++ or -- */
6772 void inc(int post, int c)
6774 test_lvalue();
6775 vdup(); /* save lvalue */
6776 if (post) {
6777 gv_dup(); /* duplicate value */
6778 vrotb(3);
6779 vrotb(3);
6781 /* add constant */
6782 vpushi(c - TOK_MID);
6783 gen_op('+');
6784 vstore(); /* store value */
6785 if (post)
6786 vpop(); /* if post op, return saved value */
6789 /* Parse GNUC __attribute__ extension. Currently, the following
6790 extensions are recognized:
6791 - aligned(n) : set data/function alignment.
6792 - packed : force data alignment to 1
6793 - section(x) : generate data/code in this section.
6794 - unused : currently ignored, but may be used someday.
6795 - regparm(n) : pass function parameters in registers (i386 only)
6797 static void parse_attribute(AttributeDef *ad)
6799 int t, n;
6801 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
6802 next();
6803 skip('(');
6804 skip('(');
6805 while (tok != ')') {
6806 if (tok < TOK_IDENT)
6807 expect("attribute name");
6808 t = tok;
6809 next();
6810 switch(t) {
6811 case TOK_SECTION1:
6812 case TOK_SECTION2:
6813 skip('(');
6814 if (tok != TOK_STR)
6815 expect("section name");
6816 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
6817 next();
6818 skip(')');
6819 break;
6820 case TOK_ALIGNED1:
6821 case TOK_ALIGNED2:
6822 if (tok == '(') {
6823 next();
6824 n = expr_const();
6825 if (n <= 0 || (n & (n - 1)) != 0)
6826 error("alignment must be a positive power of two");
6827 skip(')');
6828 } else {
6829 n = MAX_ALIGN;
6831 ad->aligned = n;
6832 break;
6833 case TOK_PACKED1:
6834 case TOK_PACKED2:
6835 ad->packed = 1;
6836 break;
6837 case TOK_UNUSED1:
6838 case TOK_UNUSED2:
6839 /* currently, no need to handle it because tcc does not
6840 track unused objects */
6841 break;
6842 case TOK_NORETURN1:
6843 case TOK_NORETURN2:
6844 /* currently, no need to handle it because tcc does not
6845 track unused objects */
6846 break;
6847 case TOK_CDECL1:
6848 case TOK_CDECL2:
6849 case TOK_CDECL3:
6850 FUNC_CALL(ad->func_attr) = FUNC_CDECL;
6851 break;
6852 case TOK_STDCALL1:
6853 case TOK_STDCALL2:
6854 case TOK_STDCALL3:
6855 FUNC_CALL(ad->func_attr) = FUNC_STDCALL;
6856 break;
6857 #ifdef TCC_TARGET_I386
6858 case TOK_REGPARM1:
6859 case TOK_REGPARM2:
6860 skip('(');
6861 n = expr_const();
6862 if (n > 3)
6863 n = 3;
6864 else if (n < 0)
6865 n = 0;
6866 if (n > 0)
6867 FUNC_CALL(ad->func_attr) = FUNC_FASTCALL1 + n - 1;
6868 skip(')');
6869 break;
6870 case TOK_FASTCALL1:
6871 case TOK_FASTCALL2:
6872 case TOK_FASTCALL3:
6873 FUNC_CALL(ad->func_attr) = FUNC_FASTCALLW;
6874 break;
6875 #endif
6876 case TOK_DLLEXPORT:
6877 FUNC_EXPORT(ad->func_attr) = 1;
6878 break;
6879 default:
6880 if (tcc_state->warn_unsupported)
6881 warning("'%s' attribute ignored", get_tok_str(t, NULL));
6882 /* skip parameters */
6883 if (tok == '(') {
6884 int parenthesis = 0;
6885 do {
6886 if (tok == '(')
6887 parenthesis++;
6888 else if (tok == ')')
6889 parenthesis--;
6890 next();
6891 } while (parenthesis && tok != -1);
6893 break;
6895 if (tok != ',')
6896 break;
6897 next();
6899 skip(')');
6900 skip(')');
6904 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6905 static void struct_decl(CType *type, int u)
6907 int a, v, size, align, maxalign, c, offset;
6908 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
6909 Sym *s, *ss, *ass, **ps;
6910 AttributeDef ad;
6911 CType type1, btype;
6913 a = tok; /* save decl type */
6914 next();
6915 if (tok != '{') {
6916 v = tok;
6917 next();
6918 /* struct already defined ? return it */
6919 if (v < TOK_IDENT)
6920 expect("struct/union/enum name");
6921 s = struct_find(v);
6922 if (s) {
6923 if (s->type.t != a)
6924 error("invalid type");
6925 goto do_decl;
6927 } else {
6928 v = anon_sym++;
6930 type1.t = a;
6931 /* we put an undefined size for struct/union */
6932 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
6933 s->r = 0; /* default alignment is zero as gcc */
6934 /* put struct/union/enum name in type */
6935 do_decl:
6936 type->t = u;
6937 type->ref = s;
6939 if (tok == '{') {
6940 next();
6941 if (s->c != -1)
6942 error("struct/union/enum already defined");
6943 /* cannot be empty */
6944 c = 0;
6945 /* non empty enums are not allowed */
6946 if (a == TOK_ENUM) {
6947 for(;;) {
6948 v = tok;
6949 if (v < TOK_UIDENT)
6950 expect("identifier");
6951 next();
6952 if (tok == '=') {
6953 next();
6954 c = expr_const();
6956 /* enum symbols have static storage */
6957 ss = sym_push(v, &int_type, VT_CONST, c);
6958 ss->type.t |= VT_STATIC;
6959 if (tok != ',')
6960 break;
6961 next();
6962 c++;
6963 /* NOTE: we accept a trailing comma */
6964 if (tok == '}')
6965 break;
6967 skip('}');
6968 } else {
6969 maxalign = 1;
6970 ps = &s->next;
6971 prevbt = VT_INT;
6972 bit_pos = 0;
6973 offset = 0;
6974 while (tok != '}') {
6975 parse_btype(&btype, &ad);
6976 while (1) {
6977 bit_size = -1;
6978 v = 0;
6979 type1 = btype;
6980 if (tok != ':') {
6981 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
6982 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
6983 expect("identifier");
6984 if ((type1.t & VT_BTYPE) == VT_FUNC ||
6985 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
6986 error("invalid type for '%s'",
6987 get_tok_str(v, NULL));
6989 if (tok == ':') {
6990 next();
6991 bit_size = expr_const();
6992 /* XXX: handle v = 0 case for messages */
6993 if (bit_size < 0)
6994 error("negative width in bit-field '%s'",
6995 get_tok_str(v, NULL));
6996 if (v && bit_size == 0)
6997 error("zero width for bit-field '%s'",
6998 get_tok_str(v, NULL));
7000 size = type_size(&type1, &align);
7001 if (ad.aligned) {
7002 if (align < ad.aligned)
7003 align = ad.aligned;
7004 } else if (ad.packed) {
7005 align = 1;
7006 } else if (*tcc_state->pack_stack_ptr) {
7007 if (align > *tcc_state->pack_stack_ptr)
7008 align = *tcc_state->pack_stack_ptr;
7010 lbit_pos = 0;
7011 if (bit_size >= 0) {
7012 bt = type1.t & VT_BTYPE;
7013 if (bt != VT_INT &&
7014 bt != VT_BYTE &&
7015 bt != VT_SHORT &&
7016 bt != VT_BOOL &&
7017 bt != VT_ENUM &&
7018 bt != VT_LLONG)
7019 error("bitfields must have scalar type");
7020 bsize = size * 8;
7021 if (bit_size > bsize) {
7022 error("width of '%s' exceeds its type",
7023 get_tok_str(v, NULL));
7024 } else if (bit_size == bsize) {
7025 /* no need for bit fields */
7026 bit_pos = 0;
7027 } else if (bit_size == 0) {
7028 /* XXX: what to do if only padding in a
7029 structure ? */
7030 /* zero size: means to pad */
7031 bit_pos = 0;
7032 } else {
7033 /* we do not have enough room ?
7034 did the type change?
7035 is it a union? */
7036 if ((bit_pos + bit_size) > bsize ||
7037 bt != prevbt || a == TOK_UNION)
7038 bit_pos = 0;
7039 lbit_pos = bit_pos;
7040 /* XXX: handle LSB first */
7041 type1.t |= VT_BITFIELD |
7042 (bit_pos << VT_STRUCT_SHIFT) |
7043 (bit_size << (VT_STRUCT_SHIFT + 6));
7044 bit_pos += bit_size;
7046 prevbt = bt;
7047 } else {
7048 bit_pos = 0;
7050 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
7051 /* add new memory data only if starting
7052 bit field */
7053 if (lbit_pos == 0) {
7054 if (a == TOK_STRUCT) {
7055 c = (c + align - 1) & -align;
7056 offset = c;
7057 if (size > 0)
7058 c += size;
7059 } else {
7060 offset = 0;
7061 if (size > c)
7062 c = size;
7064 if (align > maxalign)
7065 maxalign = align;
7067 #if 0
7068 printf("add field %s offset=%d",
7069 get_tok_str(v, NULL), offset);
7070 if (type1.t & VT_BITFIELD) {
7071 printf(" pos=%d size=%d",
7072 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
7073 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
7075 printf("\n");
7076 #endif
7078 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
7079 ass = type1.ref;
7080 while ((ass = ass->next) != NULL) {
7081 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
7082 *ps = ss;
7083 ps = &ss->next;
7085 } else if (v) {
7086 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
7087 *ps = ss;
7088 ps = &ss->next;
7090 if (tok == ';' || tok == TOK_EOF)
7091 break;
7092 skip(',');
7094 skip(';');
7096 skip('}');
7097 /* store size and alignment */
7098 s->c = (c + maxalign - 1) & -maxalign;
7099 s->r = maxalign;
7104 /* return 0 if no type declaration. otherwise, return the basic type
7105 and skip it.
7107 static int parse_btype(CType *type, AttributeDef *ad)
7109 int t, u, type_found, typespec_found, typedef_found;
7110 Sym *s;
7111 CType type1;
7113 memset(ad, 0, sizeof(AttributeDef));
7114 type_found = 0;
7115 typespec_found = 0;
7116 typedef_found = 0;
7117 t = 0;
7118 while(1) {
7119 switch(tok) {
7120 case TOK_EXTENSION:
7121 /* currently, we really ignore extension */
7122 next();
7123 continue;
7125 /* basic types */
7126 case TOK_CHAR:
7127 u = VT_BYTE;
7128 basic_type:
7129 next();
7130 basic_type1:
7131 if ((t & VT_BTYPE) != 0)
7132 error("too many basic types");
7133 t |= u;
7134 typespec_found = 1;
7135 break;
7136 case TOK_VOID:
7137 u = VT_VOID;
7138 goto basic_type;
7139 case TOK_SHORT:
7140 u = VT_SHORT;
7141 goto basic_type;
7142 case TOK_INT:
7143 next();
7144 typespec_found = 1;
7145 break;
7146 case TOK_LONG:
7147 next();
7148 if ((t & VT_BTYPE) == VT_DOUBLE) {
7149 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7150 } else if ((t & VT_BTYPE) == VT_LONG) {
7151 t = (t & ~VT_BTYPE) | VT_LLONG;
7152 } else {
7153 u = VT_LONG;
7154 goto basic_type1;
7156 break;
7157 case TOK_BOOL:
7158 u = VT_BOOL;
7159 goto basic_type;
7160 case TOK_FLOAT:
7161 u = VT_FLOAT;
7162 goto basic_type;
7163 case TOK_DOUBLE:
7164 next();
7165 if ((t & VT_BTYPE) == VT_LONG) {
7166 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7167 } else {
7168 u = VT_DOUBLE;
7169 goto basic_type1;
7171 break;
7172 case TOK_ENUM:
7173 struct_decl(&type1, VT_ENUM);
7174 basic_type2:
7175 u = type1.t;
7176 type->ref = type1.ref;
7177 goto basic_type1;
7178 case TOK_STRUCT:
7179 case TOK_UNION:
7180 struct_decl(&type1, VT_STRUCT);
7181 goto basic_type2;
7183 /* type modifiers */
7184 case TOK_CONST1:
7185 case TOK_CONST2:
7186 case TOK_CONST3:
7187 t |= VT_CONSTANT;
7188 next();
7189 break;
7190 case TOK_VOLATILE1:
7191 case TOK_VOLATILE2:
7192 case TOK_VOLATILE3:
7193 t |= VT_VOLATILE;
7194 next();
7195 break;
7196 case TOK_SIGNED1:
7197 case TOK_SIGNED2:
7198 case TOK_SIGNED3:
7199 typespec_found = 1;
7200 t |= VT_SIGNED;
7201 next();
7202 break;
7203 case TOK_REGISTER:
7204 case TOK_AUTO:
7205 case TOK_RESTRICT1:
7206 case TOK_RESTRICT2:
7207 case TOK_RESTRICT3:
7208 next();
7209 break;
7210 case TOK_UNSIGNED:
7211 t |= VT_UNSIGNED;
7212 next();
7213 typespec_found = 1;
7214 break;
7216 /* storage */
7217 case TOK_EXTERN:
7218 t |= VT_EXTERN;
7219 next();
7220 break;
7221 case TOK_STATIC:
7222 t |= VT_STATIC;
7223 next();
7224 break;
7225 case TOK_TYPEDEF:
7226 t |= VT_TYPEDEF;
7227 next();
7228 break;
7229 case TOK_INLINE1:
7230 case TOK_INLINE2:
7231 case TOK_INLINE3:
7232 t |= VT_INLINE;
7233 next();
7234 break;
7236 /* GNUC attribute */
7237 case TOK_ATTRIBUTE1:
7238 case TOK_ATTRIBUTE2:
7239 parse_attribute(ad);
7240 break;
7241 /* GNUC typeof */
7242 case TOK_TYPEOF1:
7243 case TOK_TYPEOF2:
7244 case TOK_TYPEOF3:
7245 next();
7246 parse_expr_type(&type1);
7247 goto basic_type2;
7248 default:
7249 if (typespec_found || typedef_found)
7250 goto the_end;
7251 s = sym_find(tok);
7252 if (!s || !(s->type.t & VT_TYPEDEF))
7253 goto the_end;
7254 typedef_found = 1;
7255 t |= (s->type.t & ~VT_TYPEDEF);
7256 type->ref = s->type.ref;
7257 next();
7258 typespec_found = 1;
7259 break;
7261 type_found = 1;
7263 the_end:
7264 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
7265 error("signed and unsigned modifier");
7266 if (tcc_state->char_is_unsigned) {
7267 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
7268 t |= VT_UNSIGNED;
7270 t &= ~VT_SIGNED;
7272 /* long is never used as type */
7273 if ((t & VT_BTYPE) == VT_LONG)
7274 #ifndef TCC_TARGET_X86_64
7275 t = (t & ~VT_BTYPE) | VT_INT;
7276 #else
7277 t = (t & ~VT_BTYPE) | VT_LLONG;
7278 #endif
7279 type->t = t;
7280 return type_found;
7283 /* convert a function parameter type (array to pointer and function to
7284 function pointer) */
7285 static inline void convert_parameter_type(CType *pt)
7287 /* remove const and volatile qualifiers (XXX: const could be used
7288 to indicate a const function parameter */
7289 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
7290 /* array must be transformed to pointer according to ANSI C */
7291 pt->t &= ~VT_ARRAY;
7292 if ((pt->t & VT_BTYPE) == VT_FUNC) {
7293 mk_pointer(pt);
7297 static void post_type(CType *type, AttributeDef *ad)
7299 int n, l, t1, arg_size, align;
7300 Sym **plast, *s, *first;
7301 AttributeDef ad1;
7302 CType pt;
7304 if (tok == '(') {
7305 /* function declaration */
7306 next();
7307 l = 0;
7308 first = NULL;
7309 plast = &first;
7310 arg_size = 0;
7311 if (tok != ')') {
7312 for(;;) {
7313 /* read param name and compute offset */
7314 if (l != FUNC_OLD) {
7315 if (!parse_btype(&pt, &ad1)) {
7316 if (l) {
7317 error("invalid type");
7318 } else {
7319 l = FUNC_OLD;
7320 goto old_proto;
7323 l = FUNC_NEW;
7324 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
7325 break;
7326 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
7327 if ((pt.t & VT_BTYPE) == VT_VOID)
7328 error("parameter declared as void");
7329 arg_size += (type_size(&pt, &align) + 3) & ~3;
7330 } else {
7331 old_proto:
7332 n = tok;
7333 if (n < TOK_UIDENT)
7334 expect("identifier");
7335 pt.t = VT_INT;
7336 next();
7338 convert_parameter_type(&pt);
7339 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
7340 *plast = s;
7341 plast = &s->next;
7342 if (tok == ')')
7343 break;
7344 skip(',');
7345 if (l == FUNC_NEW && tok == TOK_DOTS) {
7346 l = FUNC_ELLIPSIS;
7347 next();
7348 break;
7352 /* if no parameters, then old type prototype */
7353 if (l == 0)
7354 l = FUNC_OLD;
7355 skip(')');
7356 t1 = type->t & VT_STORAGE;
7357 /* NOTE: const is ignored in returned type as it has a special
7358 meaning in gcc / C++ */
7359 type->t &= ~(VT_STORAGE | VT_CONSTANT);
7360 post_type(type, ad);
7361 /* we push a anonymous symbol which will contain the function prototype */
7362 FUNC_ARGS(ad->func_attr) = arg_size;
7363 s = sym_push(SYM_FIELD, type, ad->func_attr, l);
7364 s->next = first;
7365 type->t = t1 | VT_FUNC;
7366 type->ref = s;
7367 } else if (tok == '[') {
7368 /* array definition */
7369 next();
7370 if (tok == TOK_RESTRICT1)
7371 next();
7372 n = -1;
7373 if (tok != ']') {
7374 n = expr_const();
7375 if (n < 0)
7376 error("invalid array size");
7378 skip(']');
7379 /* parse next post type */
7380 t1 = type->t & VT_STORAGE;
7381 type->t &= ~VT_STORAGE;
7382 post_type(type, ad);
7384 /* we push a anonymous symbol which will contain the array
7385 element type */
7386 s = sym_push(SYM_FIELD, type, 0, n);
7387 type->t = t1 | VT_ARRAY | VT_PTR;
7388 type->ref = s;
7392 /* Parse a type declaration (except basic type), and return the type
7393 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7394 expected. 'type' should contain the basic type. 'ad' is the
7395 attribute definition of the basic type. It can be modified by
7396 type_decl().
7398 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
7400 Sym *s;
7401 CType type1, *type2;
7402 int qualifiers;
7404 while (tok == '*') {
7405 qualifiers = 0;
7406 redo:
7407 next();
7408 switch(tok) {
7409 case TOK_CONST1:
7410 case TOK_CONST2:
7411 case TOK_CONST3:
7412 qualifiers |= VT_CONSTANT;
7413 goto redo;
7414 case TOK_VOLATILE1:
7415 case TOK_VOLATILE2:
7416 case TOK_VOLATILE3:
7417 qualifiers |= VT_VOLATILE;
7418 goto redo;
7419 case TOK_RESTRICT1:
7420 case TOK_RESTRICT2:
7421 case TOK_RESTRICT3:
7422 goto redo;
7424 mk_pointer(type);
7425 type->t |= qualifiers;
7428 /* XXX: clarify attribute handling */
7429 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7430 parse_attribute(ad);
7432 /* recursive type */
7433 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7434 type1.t = 0; /* XXX: same as int */
7435 if (tok == '(') {
7436 next();
7437 /* XXX: this is not correct to modify 'ad' at this point, but
7438 the syntax is not clear */
7439 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7440 parse_attribute(ad);
7441 type_decl(&type1, ad, v, td);
7442 skip(')');
7443 } else {
7444 /* type identifier */
7445 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
7446 *v = tok;
7447 next();
7448 } else {
7449 if (!(td & TYPE_ABSTRACT))
7450 expect("identifier");
7451 *v = 0;
7454 post_type(type, ad);
7455 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7456 parse_attribute(ad);
7457 if (!type1.t)
7458 return;
7459 /* append type at the end of type1 */
7460 type2 = &type1;
7461 for(;;) {
7462 s = type2->ref;
7463 type2 = &s->type;
7464 if (!type2->t) {
7465 *type2 = *type;
7466 break;
7469 *type = type1;
7472 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7473 static int lvalue_type(int t)
7475 int bt, r;
7476 r = VT_LVAL;
7477 bt = t & VT_BTYPE;
7478 if (bt == VT_BYTE || bt == VT_BOOL)
7479 r |= VT_LVAL_BYTE;
7480 else if (bt == VT_SHORT)
7481 r |= VT_LVAL_SHORT;
7482 else
7483 return r;
7484 if (t & VT_UNSIGNED)
7485 r |= VT_LVAL_UNSIGNED;
7486 return r;
7489 /* indirection with full error checking and bound check */
7490 static void indir(void)
7492 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
7493 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
7494 return;
7495 expect("pointer");
7497 if ((vtop->r & VT_LVAL) && !nocode_wanted)
7498 gv(RC_INT);
7499 vtop->type = *pointed_type(&vtop->type);
7500 /* Arrays and functions are never lvalues */
7501 if (!(vtop->type.t & VT_ARRAY)
7502 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
7503 vtop->r |= lvalue_type(vtop->type.t);
7504 /* if bound checking, the referenced pointer must be checked */
7505 if (do_bounds_check)
7506 vtop->r |= VT_MUSTBOUND;
7510 /* pass a parameter to a function and do type checking and casting */
7511 static void gfunc_param_typed(Sym *func, Sym *arg)
7513 int func_type;
7514 CType type;
7516 func_type = func->c;
7517 if (func_type == FUNC_OLD ||
7518 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
7519 /* default casting : only need to convert float to double */
7520 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
7521 type.t = VT_DOUBLE;
7522 gen_cast(&type);
7524 } else if (arg == NULL) {
7525 error("too many arguments to function");
7526 } else {
7527 type = arg->type;
7528 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
7529 gen_assign_cast(&type);
7533 /* parse an expression of the form '(type)' or '(expr)' and return its
7534 type */
7535 static void parse_expr_type(CType *type)
7537 int n;
7538 AttributeDef ad;
7540 skip('(');
7541 if (parse_btype(type, &ad)) {
7542 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7543 } else {
7544 expr_type(type);
7546 skip(')');
7549 static void parse_type(CType *type)
7551 AttributeDef ad;
7552 int n;
7554 if (!parse_btype(type, &ad)) {
7555 expect("type");
7557 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7560 static void vpush_tokc(int t)
7562 CType type;
7563 type.t = t;
7564 vsetc(&type, VT_CONST, &tokc);
7567 static void unary(void)
7569 int n, t, align, size, r;
7570 CType type;
7571 Sym *s;
7572 AttributeDef ad;
7574 /* XXX: GCC 2.95.3 does not generate a table although it should be
7575 better here */
7576 tok_next:
7577 switch(tok) {
7578 case TOK_EXTENSION:
7579 next();
7580 goto tok_next;
7581 case TOK_CINT:
7582 case TOK_CCHAR:
7583 case TOK_LCHAR:
7584 vpushi(tokc.i);
7585 next();
7586 break;
7587 case TOK_CUINT:
7588 vpush_tokc(VT_INT | VT_UNSIGNED);
7589 next();
7590 break;
7591 case TOK_CLLONG:
7592 vpush_tokc(VT_LLONG);
7593 next();
7594 break;
7595 case TOK_CULLONG:
7596 vpush_tokc(VT_LLONG | VT_UNSIGNED);
7597 next();
7598 break;
7599 case TOK_CFLOAT:
7600 vpush_tokc(VT_FLOAT);
7601 next();
7602 break;
7603 case TOK_CDOUBLE:
7604 vpush_tokc(VT_DOUBLE);
7605 next();
7606 break;
7607 case TOK_CLDOUBLE:
7608 vpush_tokc(VT_LDOUBLE);
7609 next();
7610 break;
7611 case TOK___FUNCTION__:
7612 if (!gnu_ext)
7613 goto tok_identifier;
7614 /* fall thru */
7615 case TOK___FUNC__:
7617 void *ptr;
7618 int len;
7619 /* special function name identifier */
7620 len = strlen(funcname) + 1;
7621 /* generate char[len] type */
7622 type.t = VT_BYTE;
7623 mk_pointer(&type);
7624 type.t |= VT_ARRAY;
7625 type.ref->c = len;
7626 vpush_ref(&type, data_section, data_section->data_offset, len);
7627 ptr = section_ptr_add(data_section, len);
7628 memcpy(ptr, funcname, len);
7629 next();
7631 break;
7632 case TOK_LSTR:
7633 #ifdef TCC_TARGET_PE
7634 t = VT_SHORT | VT_UNSIGNED;
7635 #else
7636 t = VT_INT;
7637 #endif
7638 goto str_init;
7639 case TOK_STR:
7640 /* string parsing */
7641 t = VT_BYTE;
7642 str_init:
7643 if (tcc_state->warn_write_strings)
7644 t |= VT_CONSTANT;
7645 type.t = t;
7646 mk_pointer(&type);
7647 type.t |= VT_ARRAY;
7648 memset(&ad, 0, sizeof(AttributeDef));
7649 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
7650 break;
7651 case '(':
7652 next();
7653 /* cast ? */
7654 if (parse_btype(&type, &ad)) {
7655 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
7656 skip(')');
7657 /* check ISOC99 compound literal */
7658 if (tok == '{') {
7659 /* data is allocated locally by default */
7660 if (global_expr)
7661 r = VT_CONST;
7662 else
7663 r = VT_LOCAL;
7664 /* all except arrays are lvalues */
7665 if (!(type.t & VT_ARRAY))
7666 r |= lvalue_type(type.t);
7667 memset(&ad, 0, sizeof(AttributeDef));
7668 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
7669 } else {
7670 unary();
7671 gen_cast(&type);
7673 } else if (tok == '{') {
7674 /* save all registers */
7675 save_regs(0);
7676 /* statement expression : we do not accept break/continue
7677 inside as GCC does */
7678 block(NULL, NULL, NULL, NULL, 0, 1);
7679 skip(')');
7680 } else {
7681 gexpr();
7682 skip(')');
7684 break;
7685 case '*':
7686 next();
7687 unary();
7688 indir();
7689 break;
7690 case '&':
7691 next();
7692 unary();
7693 /* functions names must be treated as function pointers,
7694 except for unary '&' and sizeof. Since we consider that
7695 functions are not lvalues, we only have to handle it
7696 there and in function calls. */
7697 /* arrays can also be used although they are not lvalues */
7698 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
7699 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
7700 test_lvalue();
7701 mk_pointer(&vtop->type);
7702 gaddrof();
7703 break;
7704 case '!':
7705 next();
7706 unary();
7707 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
7708 CType boolean;
7709 boolean.t = VT_BOOL;
7710 gen_cast(&boolean);
7711 vtop->c.i = !vtop->c.i;
7712 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
7713 vtop->c.i = vtop->c.i ^ 1;
7714 else {
7715 save_regs(1);
7716 vseti(VT_JMP, gtst(1, 0));
7718 break;
7719 case '~':
7720 next();
7721 unary();
7722 vpushi(-1);
7723 gen_op('^');
7724 break;
7725 case '+':
7726 next();
7727 /* in order to force cast, we add zero */
7728 unary();
7729 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
7730 error("pointer not accepted for unary plus");
7731 vpushi(0);
7732 gen_op('+');
7733 break;
7734 case TOK_SIZEOF:
7735 case TOK_ALIGNOF1:
7736 case TOK_ALIGNOF2:
7737 t = tok;
7738 next();
7739 if (tok == '(') {
7740 parse_expr_type(&type);
7741 } else {
7742 unary_type(&type);
7744 size = type_size(&type, &align);
7745 if (t == TOK_SIZEOF) {
7746 if (size < 0)
7747 error("sizeof applied to an incomplete type");
7748 vpushi(size);
7749 } else {
7750 vpushi(align);
7752 vtop->type.t |= VT_UNSIGNED;
7753 break;
7755 case TOK_builtin_types_compatible_p:
7757 CType type1, type2;
7758 next();
7759 skip('(');
7760 parse_type(&type1);
7761 skip(',');
7762 parse_type(&type2);
7763 skip(')');
7764 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
7765 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
7766 vpushi(is_compatible_types(&type1, &type2));
7768 break;
7769 case TOK_builtin_constant_p:
7771 int saved_nocode_wanted, res;
7772 next();
7773 skip('(');
7774 saved_nocode_wanted = nocode_wanted;
7775 nocode_wanted = 1;
7776 gexpr();
7777 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
7778 vpop();
7779 nocode_wanted = saved_nocode_wanted;
7780 skip(')');
7781 vpushi(res);
7783 break;
7784 case TOK_builtin_frame_address:
7786 CType type;
7787 next();
7788 skip('(');
7789 if (tok != TOK_CINT) {
7790 error("__builtin_frame_address only takes integers");
7792 if (tokc.i != 0) {
7793 error("TCC only supports __builtin_frame_address(0)");
7795 next();
7796 skip(')');
7797 type.t = VT_VOID;
7798 mk_pointer(&type);
7799 vset(&type, VT_LOCAL, 0);
7801 break;
7802 #ifdef TCC_TARGET_X86_64
7803 case TOK_builtin_malloc:
7805 char *p = file->buf_ptr;
7806 file->buf_ptr = "malloc";
7807 next_nomacro1();
7808 file->buf_ptr = p;
7809 goto tok_identifier;
7811 case TOK_builtin_free:
7813 char *p = file->buf_ptr;
7814 file->buf_ptr = "free";
7815 next_nomacro1();
7816 file->buf_ptr = p;
7817 goto tok_identifier;
7819 #endif
7820 case TOK_INC:
7821 case TOK_DEC:
7822 t = tok;
7823 next();
7824 unary();
7825 inc(0, t);
7826 break;
7827 case '-':
7828 next();
7829 vpushi(0);
7830 unary();
7831 gen_op('-');
7832 break;
7833 case TOK_LAND:
7834 if (!gnu_ext)
7835 goto tok_identifier;
7836 next();
7837 /* allow to take the address of a label */
7838 if (tok < TOK_UIDENT)
7839 expect("label identifier");
7840 s = label_find(tok);
7841 if (!s) {
7842 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
7843 } else {
7844 if (s->r == LABEL_DECLARED)
7845 s->r = LABEL_FORWARD;
7847 if (!s->type.t) {
7848 s->type.t = VT_VOID;
7849 mk_pointer(&s->type);
7850 s->type.t |= VT_STATIC;
7852 vset(&s->type, VT_CONST | VT_SYM, 0);
7853 vtop->sym = s;
7854 next();
7855 break;
7856 default:
7857 tok_identifier:
7858 t = tok;
7859 next();
7860 if (t < TOK_UIDENT)
7861 expect("identifier");
7862 s = sym_find(t);
7863 if (!s) {
7864 if (tok != '(')
7865 error("'%s' undeclared", get_tok_str(t, NULL));
7866 /* for simple function calls, we tolerate undeclared
7867 external reference to int() function */
7868 if (tcc_state->warn_implicit_function_declaration)
7869 warning("implicit declaration of function '%s'",
7870 get_tok_str(t, NULL));
7871 s = external_global_sym(t, &func_old_type, 0);
7873 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
7874 (VT_STATIC | VT_INLINE | VT_FUNC)) {
7875 /* if referencing an inline function, then we generate a
7876 symbol to it if not already done. It will have the
7877 effect to generate code for it at the end of the
7878 compilation unit. Inline function as always
7879 generated in the text section. */
7880 if (!s->c)
7881 put_extern_sym(s, text_section, 0, 0);
7882 r = VT_SYM | VT_CONST;
7883 } else {
7884 r = s->r;
7886 vset(&s->type, r, s->c);
7887 /* if forward reference, we must point to s */
7888 if (vtop->r & VT_SYM) {
7889 vtop->sym = s;
7890 vtop->c.ul = 0;
7892 break;
7895 /* post operations */
7896 while (1) {
7897 if (tok == TOK_INC || tok == TOK_DEC) {
7898 inc(1, tok);
7899 next();
7900 } else if (tok == '.' || tok == TOK_ARROW) {
7901 /* field */
7902 if (tok == TOK_ARROW)
7903 indir();
7904 test_lvalue();
7905 gaddrof();
7906 next();
7907 /* expect pointer on structure */
7908 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
7909 expect("struct or union");
7910 s = vtop->type.ref;
7911 /* find field */
7912 tok |= SYM_FIELD;
7913 while ((s = s->next) != NULL) {
7914 if (s->v == tok)
7915 break;
7917 if (!s)
7918 error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
7919 /* add field offset to pointer */
7920 vtop->type = char_pointer_type; /* change type to 'char *' */
7921 vpushi(s->c);
7922 gen_op('+');
7923 /* change type to field type, and set to lvalue */
7924 vtop->type = s->type;
7925 /* an array is never an lvalue */
7926 if (!(vtop->type.t & VT_ARRAY)) {
7927 vtop->r |= lvalue_type(vtop->type.t);
7928 /* if bound checking, the referenced pointer must be checked */
7929 if (do_bounds_check)
7930 vtop->r |= VT_MUSTBOUND;
7932 next();
7933 } else if (tok == '[') {
7934 next();
7935 gexpr();
7936 gen_op('+');
7937 indir();
7938 skip(']');
7939 } else if (tok == '(') {
7940 SValue ret;
7941 Sym *sa;
7942 int nb_args;
7944 /* function call */
7945 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
7946 /* pointer test (no array accepted) */
7947 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
7948 vtop->type = *pointed_type(&vtop->type);
7949 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
7950 goto error_func;
7951 } else {
7952 error_func:
7953 expect("function pointer");
7955 } else {
7956 vtop->r &= ~VT_LVAL; /* no lvalue */
7958 /* get return type */
7959 s = vtop->type.ref;
7960 next();
7961 sa = s->next; /* first parameter */
7962 nb_args = 0;
7963 ret.r2 = VT_CONST;
7964 /* compute first implicit argument if a structure is returned */
7965 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
7966 /* get some space for the returned structure */
7967 size = type_size(&s->type, &align);
7968 loc = (loc - size) & -align;
7969 ret.type = s->type;
7970 ret.r = VT_LOCAL | VT_LVAL;
7971 /* pass it as 'int' to avoid structure arg passing
7972 problems */
7973 vseti(VT_LOCAL, loc);
7974 ret.c = vtop->c;
7975 nb_args++;
7976 } else {
7977 ret.type = s->type;
7978 /* return in register */
7979 if (is_float(ret.type.t)) {
7980 ret.r = reg_fret(ret.type.t);
7981 } else {
7982 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
7983 ret.r2 = REG_LRET;
7984 ret.r = REG_IRET;
7986 ret.c.i = 0;
7988 if (tok != ')') {
7989 for(;;) {
7990 expr_eq();
7991 gfunc_param_typed(s, sa);
7992 nb_args++;
7993 if (sa)
7994 sa = sa->next;
7995 if (tok == ')')
7996 break;
7997 skip(',');
8000 if (sa)
8001 error("too few arguments to function");
8002 skip(')');
8003 if (!nocode_wanted) {
8004 gfunc_call(nb_args);
8005 } else {
8006 vtop -= (nb_args + 1);
8008 /* return value */
8009 vsetc(&ret.type, ret.r, &ret.c);
8010 vtop->r2 = ret.r2;
8011 } else {
8012 break;
8017 static void uneq(void)
8019 int t;
8021 unary();
8022 if (tok == '=' ||
8023 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
8024 tok == TOK_A_XOR || tok == TOK_A_OR ||
8025 tok == TOK_A_SHL || tok == TOK_A_SAR) {
8026 test_lvalue();
8027 t = tok;
8028 next();
8029 if (t == '=') {
8030 expr_eq();
8031 } else {
8032 vdup();
8033 expr_eq();
8034 gen_op(t & 0x7f);
8036 vstore();
8040 static void expr_prod(void)
8042 int t;
8044 uneq();
8045 while (tok == '*' || tok == '/' || tok == '%') {
8046 t = tok;
8047 next();
8048 uneq();
8049 gen_op(t);
8053 static void expr_sum(void)
8055 int t;
8057 expr_prod();
8058 while (tok == '+' || tok == '-') {
8059 t = tok;
8060 next();
8061 expr_prod();
8062 gen_op(t);
8066 static void expr_shift(void)
8068 int t;
8070 expr_sum();
8071 while (tok == TOK_SHL || tok == TOK_SAR) {
8072 t = tok;
8073 next();
8074 expr_sum();
8075 gen_op(t);
8079 static void expr_cmp(void)
8081 int t;
8083 expr_shift();
8084 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
8085 tok == TOK_ULT || tok == TOK_UGE) {
8086 t = tok;
8087 next();
8088 expr_shift();
8089 gen_op(t);
8093 static void expr_cmpeq(void)
8095 int t;
8097 expr_cmp();
8098 while (tok == TOK_EQ || tok == TOK_NE) {
8099 t = tok;
8100 next();
8101 expr_cmp();
8102 gen_op(t);
8106 static void expr_and(void)
8108 expr_cmpeq();
8109 while (tok == '&') {
8110 next();
8111 expr_cmpeq();
8112 gen_op('&');
8116 static void expr_xor(void)
8118 expr_and();
8119 while (tok == '^') {
8120 next();
8121 expr_and();
8122 gen_op('^');
8126 static void expr_or(void)
8128 expr_xor();
8129 while (tok == '|') {
8130 next();
8131 expr_xor();
8132 gen_op('|');
8136 /* XXX: fix this mess */
8137 static void expr_land_const(void)
8139 expr_or();
8140 while (tok == TOK_LAND) {
8141 next();
8142 expr_or();
8143 gen_op(TOK_LAND);
8147 /* XXX: fix this mess */
8148 static void expr_lor_const(void)
8150 expr_land_const();
8151 while (tok == TOK_LOR) {
8152 next();
8153 expr_land_const();
8154 gen_op(TOK_LOR);
8158 /* only used if non constant */
8159 static void expr_land(void)
8161 int t;
8163 expr_or();
8164 if (tok == TOK_LAND) {
8165 t = 0;
8166 save_regs(1);
8167 for(;;) {
8168 t = gtst(1, t);
8169 if (tok != TOK_LAND) {
8170 vseti(VT_JMPI, t);
8171 break;
8173 next();
8174 expr_or();
8179 static void expr_lor(void)
8181 int t;
8183 expr_land();
8184 if (tok == TOK_LOR) {
8185 t = 0;
8186 save_regs(1);
8187 for(;;) {
8188 t = gtst(0, t);
8189 if (tok != TOK_LOR) {
8190 vseti(VT_JMP, t);
8191 break;
8193 next();
8194 expr_land();
8199 /* XXX: better constant handling */
8200 static void expr_eq(void)
8202 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
8203 SValue sv;
8204 CType type, type1, type2;
8206 if (const_wanted) {
8207 expr_lor_const();
8208 if (tok == '?') {
8209 CType boolean;
8210 int c;
8211 boolean.t = VT_BOOL;
8212 vdup();
8213 gen_cast(&boolean);
8214 c = vtop->c.i;
8215 vpop();
8216 next();
8217 if (tok != ':' || !gnu_ext) {
8218 vpop();
8219 gexpr();
8221 if (!c)
8222 vpop();
8223 skip(':');
8224 expr_eq();
8225 if (c)
8226 vpop();
8228 } else {
8229 expr_lor();
8230 if (tok == '?') {
8231 next();
8232 if (vtop != vstack) {
8233 /* needed to avoid having different registers saved in
8234 each branch */
8235 if (is_float(vtop->type.t)) {
8236 rc = RC_FLOAT;
8237 #ifdef TCC_TARGET_X86_64
8238 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
8239 rc = RC_ST0;
8241 #endif
8243 else
8244 rc = RC_INT;
8245 gv(rc);
8246 save_regs(1);
8248 if (tok == ':' && gnu_ext) {
8249 gv_dup();
8250 tt = gtst(1, 0);
8251 } else {
8252 tt = gtst(1, 0);
8253 gexpr();
8255 type1 = vtop->type;
8256 sv = *vtop; /* save value to handle it later */
8257 vtop--; /* no vpop so that FP stack is not flushed */
8258 skip(':');
8259 u = gjmp(0);
8260 gsym(tt);
8261 expr_eq();
8262 type2 = vtop->type;
8264 t1 = type1.t;
8265 bt1 = t1 & VT_BTYPE;
8266 t2 = type2.t;
8267 bt2 = t2 & VT_BTYPE;
8268 /* cast operands to correct type according to ISOC rules */
8269 if (is_float(bt1) || is_float(bt2)) {
8270 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
8271 type.t = VT_LDOUBLE;
8272 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
8273 type.t = VT_DOUBLE;
8274 } else {
8275 type.t = VT_FLOAT;
8277 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
8278 /* cast to biggest op */
8279 type.t = VT_LLONG;
8280 /* convert to unsigned if it does not fit in a long long */
8281 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
8282 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
8283 type.t |= VT_UNSIGNED;
8284 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
8285 /* XXX: test pointer compatibility */
8286 type = type1;
8287 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
8288 /* XXX: test function pointer compatibility */
8289 type = type1;
8290 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
8291 /* XXX: test structure compatibility */
8292 type = type1;
8293 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
8294 /* NOTE: as an extension, we accept void on only one side */
8295 type.t = VT_VOID;
8296 } else {
8297 /* integer operations */
8298 type.t = VT_INT;
8299 /* convert to unsigned if it does not fit in an integer */
8300 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
8301 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
8302 type.t |= VT_UNSIGNED;
8305 /* now we convert second operand */
8306 gen_cast(&type);
8307 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8308 gaddrof();
8309 rc = RC_INT;
8310 if (is_float(type.t)) {
8311 rc = RC_FLOAT;
8312 #ifdef TCC_TARGET_X86_64
8313 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
8314 rc = RC_ST0;
8316 #endif
8317 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
8318 /* for long longs, we use fixed registers to avoid having
8319 to handle a complicated move */
8320 rc = RC_IRET;
8323 r2 = gv(rc);
8324 /* this is horrible, but we must also convert first
8325 operand */
8326 tt = gjmp(0);
8327 gsym(u);
8328 /* put again first value and cast it */
8329 *vtop = sv;
8330 gen_cast(&type);
8331 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8332 gaddrof();
8333 r1 = gv(rc);
8334 move_reg(r2, r1);
8335 vtop->r = r2;
8336 gsym(tt);
8341 static void gexpr(void)
8343 while (1) {
8344 expr_eq();
8345 if (tok != ',')
8346 break;
8347 vpop();
8348 next();
8352 /* parse an expression and return its type without any side effect. */
8353 static void expr_type(CType *type)
8355 int saved_nocode_wanted;
8357 saved_nocode_wanted = nocode_wanted;
8358 nocode_wanted = 1;
8359 gexpr();
8360 *type = vtop->type;
8361 vpop();
8362 nocode_wanted = saved_nocode_wanted;
8365 /* parse a unary expression and return its type without any side
8366 effect. */
8367 static void unary_type(CType *type)
8369 int a;
8371 a = nocode_wanted;
8372 nocode_wanted = 1;
8373 unary();
8374 *type = vtop->type;
8375 vpop();
8376 nocode_wanted = a;
8379 /* parse a constant expression and return value in vtop. */
8380 static void expr_const1(void)
8382 int a;
8383 a = const_wanted;
8384 const_wanted = 1;
8385 expr_eq();
8386 const_wanted = a;
8389 /* parse an integer constant and return its value. */
8390 static int expr_const(void)
8392 int c;
8393 expr_const1();
8394 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
8395 expect("constant expression");
8396 c = vtop->c.i;
8397 vpop();
8398 return c;
8401 /* return the label token if current token is a label, otherwise
8402 return zero */
8403 static int is_label(void)
8405 int last_tok;
8407 /* fast test first */
8408 if (tok < TOK_UIDENT)
8409 return 0;
8410 /* no need to save tokc because tok is an identifier */
8411 last_tok = tok;
8412 next();
8413 if (tok == ':') {
8414 next();
8415 return last_tok;
8416 } else {
8417 unget_tok(last_tok);
8418 return 0;
8422 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
8423 int case_reg, int is_expr)
8425 int a, b, c, d;
8426 Sym *s;
8428 /* generate line number info */
8429 if (do_debug &&
8430 (last_line_num != file->line_num || last_ind != ind)) {
8431 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
8432 last_ind = ind;
8433 last_line_num = file->line_num;
8436 if (is_expr) {
8437 /* default return value is (void) */
8438 vpushi(0);
8439 vtop->type.t = VT_VOID;
8442 if (tok == TOK_IF) {
8443 /* if test */
8444 next();
8445 skip('(');
8446 gexpr();
8447 skip(')');
8448 a = gtst(1, 0);
8449 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8450 c = tok;
8451 if (c == TOK_ELSE) {
8452 next();
8453 d = gjmp(0);
8454 gsym(a);
8455 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8456 gsym(d); /* patch else jmp */
8457 } else
8458 gsym(a);
8459 } else if (tok == TOK_WHILE) {
8460 next();
8461 d = ind;
8462 skip('(');
8463 gexpr();
8464 skip(')');
8465 a = gtst(1, 0);
8466 b = 0;
8467 block(&a, &b, case_sym, def_sym, case_reg, 0);
8468 gjmp_addr(d);
8469 gsym(a);
8470 gsym_addr(b, d);
8471 } else if (tok == '{') {
8472 Sym *llabel;
8474 next();
8475 /* record local declaration stack position */
8476 s = local_stack;
8477 llabel = local_label_stack;
8478 /* handle local labels declarations */
8479 if (tok == TOK_LABEL) {
8480 next();
8481 for(;;) {
8482 if (tok < TOK_UIDENT)
8483 expect("label identifier");
8484 label_push(&local_label_stack, tok, LABEL_DECLARED);
8485 next();
8486 if (tok == ',') {
8487 next();
8488 } else {
8489 skip(';');
8490 break;
8494 while (tok != '}') {
8495 decl(VT_LOCAL);
8496 if (tok != '}') {
8497 if (is_expr)
8498 vpop();
8499 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8502 /* pop locally defined labels */
8503 label_pop(&local_label_stack, llabel);
8504 /* pop locally defined symbols */
8505 if(is_expr) {
8506 /* XXX: this solution makes only valgrind happy...
8507 triggered by gcc.c-torture/execute/20000917-1.c */
8508 Sym *p;
8509 switch(vtop->type.t & VT_BTYPE) {
8510 case VT_PTR:
8511 case VT_STRUCT:
8512 case VT_ENUM:
8513 case VT_FUNC:
8514 for(p=vtop->type.ref;p;p=p->prev)
8515 if(p->prev==s)
8516 error("unsupported expression type");
8519 sym_pop(&local_stack, s);
8520 next();
8521 } else if (tok == TOK_RETURN) {
8522 next();
8523 if (tok != ';') {
8524 gexpr();
8525 gen_assign_cast(&func_vt);
8526 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
8527 CType type;
8528 /* if returning structure, must copy it to implicit
8529 first pointer arg location */
8530 #ifdef TCC_ARM_EABI
8531 int align, size;
8532 size = type_size(&func_vt,&align);
8533 if(size <= 4)
8535 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
8536 && (align & 3))
8538 int addr;
8539 loc = (loc - size) & -4;
8540 addr = loc;
8541 type = func_vt;
8542 vset(&type, VT_LOCAL | VT_LVAL, addr);
8543 vswap();
8544 vstore();
8545 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
8547 vtop->type = int_type;
8548 gv(RC_IRET);
8549 } else {
8550 #endif
8551 type = func_vt;
8552 mk_pointer(&type);
8553 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
8554 indir();
8555 vswap();
8556 /* copy structure value to pointer */
8557 vstore();
8558 #ifdef TCC_ARM_EABI
8560 #endif
8561 } else if (is_float(func_vt.t)) {
8562 gv(rc_fret(func_vt.t));
8563 } else {
8564 gv(RC_IRET);
8566 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
8568 skip(';');
8569 rsym = gjmp(rsym); /* jmp */
8570 } else if (tok == TOK_BREAK) {
8571 /* compute jump */
8572 if (!bsym)
8573 error("cannot break");
8574 *bsym = gjmp(*bsym);
8575 next();
8576 skip(';');
8577 } else if (tok == TOK_CONTINUE) {
8578 /* compute jump */
8579 if (!csym)
8580 error("cannot continue");
8581 *csym = gjmp(*csym);
8582 next();
8583 skip(';');
8584 } else if (tok == TOK_FOR) {
8585 int e;
8586 next();
8587 skip('(');
8588 if (tok != ';') {
8589 gexpr();
8590 vpop();
8592 skip(';');
8593 d = ind;
8594 c = ind;
8595 a = 0;
8596 b = 0;
8597 if (tok != ';') {
8598 gexpr();
8599 a = gtst(1, 0);
8601 skip(';');
8602 if (tok != ')') {
8603 e = gjmp(0);
8604 c = ind;
8605 gexpr();
8606 vpop();
8607 gjmp_addr(d);
8608 gsym(e);
8610 skip(')');
8611 block(&a, &b, case_sym, def_sym, case_reg, 0);
8612 gjmp_addr(c);
8613 gsym(a);
8614 gsym_addr(b, c);
8615 } else
8616 if (tok == TOK_DO) {
8617 next();
8618 a = 0;
8619 b = 0;
8620 d = ind;
8621 block(&a, &b, case_sym, def_sym, case_reg, 0);
8622 skip(TOK_WHILE);
8623 skip('(');
8624 gsym(b);
8625 gexpr();
8626 c = gtst(0, 0);
8627 gsym_addr(c, d);
8628 skip(')');
8629 gsym(a);
8630 skip(';');
8631 } else
8632 if (tok == TOK_SWITCH) {
8633 next();
8634 skip('(');
8635 gexpr();
8636 /* XXX: other types than integer */
8637 case_reg = gv(RC_INT);
8638 vpop();
8639 skip(')');
8640 a = 0;
8641 b = gjmp(0); /* jump to first case */
8642 c = 0;
8643 block(&a, csym, &b, &c, case_reg, 0);
8644 /* if no default, jmp after switch */
8645 if (c == 0)
8646 c = ind;
8647 /* default label */
8648 gsym_addr(b, c);
8649 /* break label */
8650 gsym(a);
8651 } else
8652 if (tok == TOK_CASE) {
8653 int v1, v2;
8654 if (!case_sym)
8655 expect("switch");
8656 next();
8657 v1 = expr_const();
8658 v2 = v1;
8659 if (gnu_ext && tok == TOK_DOTS) {
8660 next();
8661 v2 = expr_const();
8662 if (v2 < v1)
8663 warning("empty case range");
8665 /* since a case is like a label, we must skip it with a jmp */
8666 b = gjmp(0);
8667 gsym(*case_sym);
8668 vseti(case_reg, 0);
8669 vpushi(v1);
8670 if (v1 == v2) {
8671 gen_op(TOK_EQ);
8672 *case_sym = gtst(1, 0);
8673 } else {
8674 gen_op(TOK_GE);
8675 *case_sym = gtst(1, 0);
8676 vseti(case_reg, 0);
8677 vpushi(v2);
8678 gen_op(TOK_LE);
8679 *case_sym = gtst(1, *case_sym);
8681 gsym(b);
8682 skip(':');
8683 is_expr = 0;
8684 goto block_after_label;
8685 } else
8686 if (tok == TOK_DEFAULT) {
8687 next();
8688 skip(':');
8689 if (!def_sym)
8690 expect("switch");
8691 if (*def_sym)
8692 error("too many 'default'");
8693 *def_sym = ind;
8694 is_expr = 0;
8695 goto block_after_label;
8696 } else
8697 if (tok == TOK_GOTO) {
8698 next();
8699 if (tok == '*' && gnu_ext) {
8700 /* computed goto */
8701 next();
8702 gexpr();
8703 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
8704 expect("pointer");
8705 ggoto();
8706 } else if (tok >= TOK_UIDENT) {
8707 s = label_find(tok);
8708 /* put forward definition if needed */
8709 if (!s) {
8710 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
8711 } else {
8712 if (s->r == LABEL_DECLARED)
8713 s->r = LABEL_FORWARD;
8715 /* label already defined */
8716 if (s->r & LABEL_FORWARD)
8717 s->next = (void *)gjmp((long)s->next);
8718 else
8719 gjmp_addr((long)s->next);
8720 next();
8721 } else {
8722 expect("label identifier");
8724 skip(';');
8725 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
8726 asm_instr();
8727 } else {
8728 b = is_label();
8729 if (b) {
8730 /* label case */
8731 s = label_find(b);
8732 if (s) {
8733 if (s->r == LABEL_DEFINED)
8734 error("duplicate label '%s'", get_tok_str(s->v, NULL));
8735 gsym((long)s->next);
8736 s->r = LABEL_DEFINED;
8737 } else {
8738 s = label_push(&global_label_stack, b, LABEL_DEFINED);
8740 s->next = (void *)ind;
8741 /* we accept this, but it is a mistake */
8742 block_after_label:
8743 if (tok == '}') {
8744 warning("deprecated use of label at end of compound statement");
8745 } else {
8746 if (is_expr)
8747 vpop();
8748 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8750 } else {
8751 /* expression case */
8752 if (tok != ';') {
8753 if (is_expr) {
8754 vpop();
8755 gexpr();
8756 } else {
8757 gexpr();
8758 vpop();
8761 skip(';');
8766 /* t is the array or struct type. c is the array or struct
8767 address. cur_index/cur_field is the pointer to the current
8768 value. 'size_only' is true if only size info is needed (only used
8769 in arrays) */
8770 static void decl_designator(CType *type, Section *sec, unsigned long c,
8771 int *cur_index, Sym **cur_field,
8772 int size_only)
8774 Sym *s, *f;
8775 int notfirst, index, index_last, align, l, nb_elems, elem_size;
8776 CType type1;
8778 notfirst = 0;
8779 elem_size = 0;
8780 nb_elems = 1;
8781 if (gnu_ext && (l = is_label()) != 0)
8782 goto struct_field;
8783 while (tok == '[' || tok == '.') {
8784 if (tok == '[') {
8785 if (!(type->t & VT_ARRAY))
8786 expect("array type");
8787 s = type->ref;
8788 next();
8789 index = expr_const();
8790 if (index < 0 || (s->c >= 0 && index >= s->c))
8791 expect("invalid index");
8792 if (tok == TOK_DOTS && gnu_ext) {
8793 next();
8794 index_last = expr_const();
8795 if (index_last < 0 ||
8796 (s->c >= 0 && index_last >= s->c) ||
8797 index_last < index)
8798 expect("invalid index");
8799 } else {
8800 index_last = index;
8802 skip(']');
8803 if (!notfirst)
8804 *cur_index = index_last;
8805 type = pointed_type(type);
8806 elem_size = type_size(type, &align);
8807 c += index * elem_size;
8808 /* NOTE: we only support ranges for last designator */
8809 nb_elems = index_last - index + 1;
8810 if (nb_elems != 1) {
8811 notfirst = 1;
8812 break;
8814 } else {
8815 next();
8816 l = tok;
8817 next();
8818 struct_field:
8819 if ((type->t & VT_BTYPE) != VT_STRUCT)
8820 expect("struct/union type");
8821 s = type->ref;
8822 l |= SYM_FIELD;
8823 f = s->next;
8824 while (f) {
8825 if (f->v == l)
8826 break;
8827 f = f->next;
8829 if (!f)
8830 expect("field");
8831 if (!notfirst)
8832 *cur_field = f;
8833 /* XXX: fix this mess by using explicit storage field */
8834 type1 = f->type;
8835 type1.t |= (type->t & ~VT_TYPE);
8836 type = &type1;
8837 c += f->c;
8839 notfirst = 1;
8841 if (notfirst) {
8842 if (tok == '=') {
8843 next();
8844 } else {
8845 if (!gnu_ext)
8846 expect("=");
8848 } else {
8849 if (type->t & VT_ARRAY) {
8850 index = *cur_index;
8851 type = pointed_type(type);
8852 c += index * type_size(type, &align);
8853 } else {
8854 f = *cur_field;
8855 if (!f)
8856 error("too many field init");
8857 /* XXX: fix this mess by using explicit storage field */
8858 type1 = f->type;
8859 type1.t |= (type->t & ~VT_TYPE);
8860 type = &type1;
8861 c += f->c;
8864 decl_initializer(type, sec, c, 0, size_only);
8866 /* XXX: make it more general */
8867 if (!size_only && nb_elems > 1) {
8868 unsigned long c_end;
8869 uint8_t *src, *dst;
8870 int i;
8872 if (!sec)
8873 error("range init not supported yet for dynamic storage");
8874 c_end = c + nb_elems * elem_size;
8875 if (c_end > sec->data_allocated)
8876 section_realloc(sec, c_end);
8877 src = sec->data + c;
8878 dst = src;
8879 for(i = 1; i < nb_elems; i++) {
8880 dst += elem_size;
8881 memcpy(dst, src, elem_size);
8886 #define EXPR_VAL 0
8887 #define EXPR_CONST 1
8888 #define EXPR_ANY 2
8890 /* store a value or an expression directly in global data or in local array */
8891 static void init_putv(CType *type, Section *sec, unsigned long c,
8892 int v, int expr_type)
8894 int saved_global_expr, bt, bit_pos, bit_size;
8895 void *ptr;
8896 unsigned long long bit_mask;
8897 CType dtype;
8899 switch(expr_type) {
8900 case EXPR_VAL:
8901 vpushi(v);
8902 break;
8903 case EXPR_CONST:
8904 /* compound literals must be allocated globally in this case */
8905 saved_global_expr = global_expr;
8906 global_expr = 1;
8907 expr_const1();
8908 global_expr = saved_global_expr;
8909 /* NOTE: symbols are accepted */
8910 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
8911 error("initializer element is not constant");
8912 break;
8913 case EXPR_ANY:
8914 expr_eq();
8915 break;
8918 dtype = *type;
8919 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
8921 if (sec) {
8922 /* XXX: not portable */
8923 /* XXX: generate error if incorrect relocation */
8924 gen_assign_cast(&dtype);
8925 bt = type->t & VT_BTYPE;
8926 /* we'll write at most 12 bytes */
8927 if (c + 12 > sec->data_allocated) {
8928 section_realloc(sec, c + 12);
8930 ptr = sec->data + c;
8931 /* XXX: make code faster ? */
8932 if (!(type->t & VT_BITFIELD)) {
8933 bit_pos = 0;
8934 bit_size = 32;
8935 bit_mask = -1LL;
8936 } else {
8937 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
8938 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
8939 bit_mask = (1LL << bit_size) - 1;
8941 if ((vtop->r & VT_SYM) &&
8942 (bt == VT_BYTE ||
8943 bt == VT_SHORT ||
8944 bt == VT_DOUBLE ||
8945 bt == VT_LDOUBLE ||
8946 bt == VT_LLONG ||
8947 (bt == VT_INT && bit_size != 32)))
8948 error("initializer element is not computable at load time");
8949 switch(bt) {
8950 case VT_BOOL:
8951 vtop->c.i = (vtop->c.i != 0);
8952 case VT_BYTE:
8953 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8954 break;
8955 case VT_SHORT:
8956 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8957 break;
8958 case VT_DOUBLE:
8959 *(double *)ptr = vtop->c.d;
8960 break;
8961 case VT_LDOUBLE:
8962 *(long double *)ptr = vtop->c.ld;
8963 break;
8964 case VT_LLONG:
8965 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
8966 break;
8967 default:
8968 if (vtop->r & VT_SYM) {
8969 greloc(sec, vtop->sym, c, R_DATA_32);
8971 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8972 break;
8974 vtop--;
8975 } else {
8976 vset(&dtype, VT_LOCAL|VT_LVAL, c);
8977 vswap();
8978 vstore();
8979 vpop();
8983 /* put zeros for variable based init */
8984 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
8986 if (sec) {
8987 /* nothing to do because globals are already set to zero */
8988 } else {
8989 vpush_global_sym(&func_old_type, TOK_memset);
8990 vseti(VT_LOCAL, c);
8991 vpushi(0);
8992 vpushi(size);
8993 gfunc_call(3);
8997 /* 't' contains the type and storage info. 'c' is the offset of the
8998 object in section 'sec'. If 'sec' is NULL, it means stack based
8999 allocation. 'first' is true if array '{' must be read (multi
9000 dimension implicit array init handling). 'size_only' is true if
9001 size only evaluation is wanted (only for arrays). */
9002 static void decl_initializer(CType *type, Section *sec, unsigned long c,
9003 int first, int size_only)
9005 int index, array_length, n, no_oblock, nb, parlevel, i;
9006 int size1, align1, expr_type;
9007 Sym *s, *f;
9008 CType *t1;
9010 if (type->t & VT_ARRAY) {
9011 s = type->ref;
9012 n = s->c;
9013 array_length = 0;
9014 t1 = pointed_type(type);
9015 size1 = type_size(t1, &align1);
9017 no_oblock = 1;
9018 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
9019 tok == '{') {
9020 skip('{');
9021 no_oblock = 0;
9024 /* only parse strings here if correct type (otherwise: handle
9025 them as ((w)char *) expressions */
9026 if ((tok == TOK_LSTR &&
9027 #ifdef TCC_TARGET_PE
9028 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
9029 #else
9030 (t1->t & VT_BTYPE) == VT_INT
9031 #endif
9032 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
9033 while (tok == TOK_STR || tok == TOK_LSTR) {
9034 int cstr_len, ch;
9035 CString *cstr;
9037 cstr = tokc.cstr;
9038 /* compute maximum number of chars wanted */
9039 if (tok == TOK_STR)
9040 cstr_len = cstr->size;
9041 else
9042 cstr_len = cstr->size / sizeof(nwchar_t);
9043 cstr_len--;
9044 nb = cstr_len;
9045 if (n >= 0 && nb > (n - array_length))
9046 nb = n - array_length;
9047 if (!size_only) {
9048 if (cstr_len > nb)
9049 warning("initializer-string for array is too long");
9050 /* in order to go faster for common case (char
9051 string in global variable, we handle it
9052 specifically */
9053 if (sec && tok == TOK_STR && size1 == 1) {
9054 memcpy(sec->data + c + array_length, cstr->data, nb);
9055 } else {
9056 for(i=0;i<nb;i++) {
9057 if (tok == TOK_STR)
9058 ch = ((unsigned char *)cstr->data)[i];
9059 else
9060 ch = ((nwchar_t *)cstr->data)[i];
9061 init_putv(t1, sec, c + (array_length + i) * size1,
9062 ch, EXPR_VAL);
9066 array_length += nb;
9067 next();
9069 /* only add trailing zero if enough storage (no
9070 warning in this case since it is standard) */
9071 if (n < 0 || array_length < n) {
9072 if (!size_only) {
9073 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
9075 array_length++;
9077 } else {
9078 index = 0;
9079 while (tok != '}') {
9080 decl_designator(type, sec, c, &index, NULL, size_only);
9081 if (n >= 0 && index >= n)
9082 error("index too large");
9083 /* must put zero in holes (note that doing it that way
9084 ensures that it even works with designators) */
9085 if (!size_only && array_length < index) {
9086 init_putz(t1, sec, c + array_length * size1,
9087 (index - array_length) * size1);
9089 index++;
9090 if (index > array_length)
9091 array_length = index;
9092 /* special test for multi dimensional arrays (may not
9093 be strictly correct if designators are used at the
9094 same time) */
9095 if (index >= n && no_oblock)
9096 break;
9097 if (tok == '}')
9098 break;
9099 skip(',');
9102 if (!no_oblock)
9103 skip('}');
9104 /* put zeros at the end */
9105 if (!size_only && n >= 0 && array_length < n) {
9106 init_putz(t1, sec, c + array_length * size1,
9107 (n - array_length) * size1);
9109 /* patch type size if needed */
9110 if (n < 0)
9111 s->c = array_length;
9112 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
9113 (sec || !first || tok == '{')) {
9114 int par_count;
9116 /* NOTE: the previous test is a specific case for automatic
9117 struct/union init */
9118 /* XXX: union needs only one init */
9120 /* XXX: this test is incorrect for local initializers
9121 beginning with ( without {. It would be much more difficult
9122 to do it correctly (ideally, the expression parser should
9123 be used in all cases) */
9124 par_count = 0;
9125 if (tok == '(') {
9126 AttributeDef ad1;
9127 CType type1;
9128 next();
9129 while (tok == '(') {
9130 par_count++;
9131 next();
9133 if (!parse_btype(&type1, &ad1))
9134 expect("cast");
9135 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
9136 #if 0
9137 if (!is_assignable_types(type, &type1))
9138 error("invalid type for cast");
9139 #endif
9140 skip(')');
9142 no_oblock = 1;
9143 if (first || tok == '{') {
9144 skip('{');
9145 no_oblock = 0;
9147 s = type->ref;
9148 f = s->next;
9149 array_length = 0;
9150 index = 0;
9151 n = s->c;
9152 while (tok != '}') {
9153 decl_designator(type, sec, c, NULL, &f, size_only);
9154 index = f->c;
9155 if (!size_only && array_length < index) {
9156 init_putz(type, sec, c + array_length,
9157 index - array_length);
9159 index = index + type_size(&f->type, &align1);
9160 if (index > array_length)
9161 array_length = index;
9162 f = f->next;
9163 if (no_oblock && f == NULL)
9164 break;
9165 if (tok == '}')
9166 break;
9167 skip(',');
9169 /* put zeros at the end */
9170 if (!size_only && array_length < n) {
9171 init_putz(type, sec, c + array_length,
9172 n - array_length);
9174 if (!no_oblock)
9175 skip('}');
9176 while (par_count) {
9177 skip(')');
9178 par_count--;
9180 } else if (tok == '{') {
9181 next();
9182 decl_initializer(type, sec, c, first, size_only);
9183 skip('}');
9184 } else if (size_only) {
9185 /* just skip expression */
9186 parlevel = 0;
9187 while ((parlevel > 0 || (tok != '}' && tok != ',')) &&
9188 tok != -1) {
9189 if (tok == '(')
9190 parlevel++;
9191 else if (tok == ')')
9192 parlevel--;
9193 next();
9195 } else {
9196 /* currently, we always use constant expression for globals
9197 (may change for scripting case) */
9198 expr_type = EXPR_CONST;
9199 if (!sec)
9200 expr_type = EXPR_ANY;
9201 init_putv(type, sec, c, 0, expr_type);
9205 /* parse an initializer for type 't' if 'has_init' is non zero, and
9206 allocate space in local or global data space ('r' is either
9207 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9208 variable 'v' of scope 'scope' is declared before initializers are
9209 parsed. If 'v' is zero, then a reference to the new object is put
9210 in the value stack. If 'has_init' is 2, a special parsing is done
9211 to handle string constants. */
9212 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
9213 int has_init, int v, int scope)
9215 int size, align, addr, data_offset;
9216 int level;
9217 ParseState saved_parse_state;
9218 TokenString init_str;
9219 Section *sec;
9221 size = type_size(type, &align);
9222 /* If unknown size, we must evaluate it before
9223 evaluating initializers because
9224 initializers can generate global data too
9225 (e.g. string pointers or ISOC99 compound
9226 literals). It also simplifies local
9227 initializers handling */
9228 tok_str_new(&init_str);
9229 if (size < 0) {
9230 if (!has_init)
9231 error("unknown type size");
9232 /* get all init string */
9233 if (has_init == 2) {
9234 /* only get strings */
9235 while (tok == TOK_STR || tok == TOK_LSTR) {
9236 tok_str_add_tok(&init_str);
9237 next();
9239 } else {
9240 level = 0;
9241 while (level > 0 || (tok != ',' && tok != ';')) {
9242 if (tok < 0)
9243 error("unexpected end of file in initializer");
9244 tok_str_add_tok(&init_str);
9245 if (tok == '{')
9246 level++;
9247 else if (tok == '}') {
9248 level--;
9249 if (level <= 0) {
9250 next();
9251 break;
9254 next();
9257 tok_str_add(&init_str, -1);
9258 tok_str_add(&init_str, 0);
9260 /* compute size */
9261 save_parse_state(&saved_parse_state);
9263 macro_ptr = init_str.str;
9264 next();
9265 decl_initializer(type, NULL, 0, 1, 1);
9266 /* prepare second initializer parsing */
9267 macro_ptr = init_str.str;
9268 next();
9270 /* if still unknown size, error */
9271 size = type_size(type, &align);
9272 if (size < 0)
9273 error("unknown type size");
9275 /* take into account specified alignment if bigger */
9276 if (ad->aligned) {
9277 if (ad->aligned > align)
9278 align = ad->aligned;
9279 } else if (ad->packed) {
9280 align = 1;
9282 if ((r & VT_VALMASK) == VT_LOCAL) {
9283 sec = NULL;
9284 if (do_bounds_check && (type->t & VT_ARRAY))
9285 loc--;
9286 loc = (loc - size) & -align;
9287 addr = loc;
9288 /* handles bounds */
9289 /* XXX: currently, since we do only one pass, we cannot track
9290 '&' operators, so we add only arrays */
9291 if (do_bounds_check && (type->t & VT_ARRAY)) {
9292 unsigned long *bounds_ptr;
9293 /* add padding between regions */
9294 loc--;
9295 /* then add local bound info */
9296 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
9297 bounds_ptr[0] = addr;
9298 bounds_ptr[1] = size;
9300 if (v) {
9301 /* local variable */
9302 sym_push(v, type, r, addr);
9303 } else {
9304 /* push local reference */
9305 vset(type, r, addr);
9307 } else {
9308 Sym *sym;
9310 sym = NULL;
9311 if (v && scope == VT_CONST) {
9312 /* see if the symbol was already defined */
9313 sym = sym_find(v);
9314 if (sym) {
9315 if (!is_compatible_types(&sym->type, type))
9316 error("incompatible types for redefinition of '%s'",
9317 get_tok_str(v, NULL));
9318 if (sym->type.t & VT_EXTERN) {
9319 /* if the variable is extern, it was not allocated */
9320 sym->type.t &= ~VT_EXTERN;
9321 /* set array size if it was ommited in extern
9322 declaration */
9323 if ((sym->type.t & VT_ARRAY) &&
9324 sym->type.ref->c < 0 &&
9325 type->ref->c >= 0)
9326 sym->type.ref->c = type->ref->c;
9327 } else {
9328 /* we accept several definitions of the same
9329 global variable. this is tricky, because we
9330 must play with the SHN_COMMON type of the symbol */
9331 /* XXX: should check if the variable was already
9332 initialized. It is incorrect to initialized it
9333 twice */
9334 /* no init data, we won't add more to the symbol */
9335 if (!has_init)
9336 goto no_alloc;
9341 /* allocate symbol in corresponding section */
9342 sec = ad->section;
9343 if (!sec) {
9344 if (has_init)
9345 sec = data_section;
9346 else if (tcc_state->nocommon)
9347 sec = bss_section;
9349 if (sec) {
9350 data_offset = sec->data_offset;
9351 data_offset = (data_offset + align - 1) & -align;
9352 addr = data_offset;
9353 /* very important to increment global pointer at this time
9354 because initializers themselves can create new initializers */
9355 data_offset += size;
9356 /* add padding if bound check */
9357 if (do_bounds_check)
9358 data_offset++;
9359 sec->data_offset = data_offset;
9360 /* allocate section space to put the data */
9361 if (sec->sh_type != SHT_NOBITS &&
9362 data_offset > sec->data_allocated)
9363 section_realloc(sec, data_offset);
9364 /* align section if needed */
9365 if (align > sec->sh_addralign)
9366 sec->sh_addralign = align;
9367 } else {
9368 addr = 0; /* avoid warning */
9371 if (v) {
9372 if (scope != VT_CONST || !sym) {
9373 sym = sym_push(v, type, r | VT_SYM, 0);
9375 /* update symbol definition */
9376 if (sec) {
9377 put_extern_sym(sym, sec, addr, size);
9378 } else {
9379 ElfW(Sym) *esym;
9380 /* put a common area */
9381 put_extern_sym(sym, NULL, align, size);
9382 /* XXX: find a nicer way */
9383 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
9384 esym->st_shndx = SHN_COMMON;
9386 } else {
9387 CValue cval;
9389 /* push global reference */
9390 sym = get_sym_ref(type, sec, addr, size);
9391 cval.ul = 0;
9392 vsetc(type, VT_CONST | VT_SYM, &cval);
9393 vtop->sym = sym;
9396 /* handles bounds now because the symbol must be defined
9397 before for the relocation */
9398 if (do_bounds_check) {
9399 unsigned long *bounds_ptr;
9401 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_32);
9402 /* then add global bound info */
9403 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
9404 bounds_ptr[0] = 0; /* relocated */
9405 bounds_ptr[1] = size;
9408 if (has_init) {
9409 decl_initializer(type, sec, addr, 1, 0);
9410 /* restore parse state if needed */
9411 if (init_str.str) {
9412 tok_str_free(init_str.str);
9413 restore_parse_state(&saved_parse_state);
9416 no_alloc: ;
9419 void put_func_debug(Sym *sym)
9421 char buf[512];
9423 /* stabs info */
9424 /* XXX: we put here a dummy type */
9425 snprintf(buf, sizeof(buf), "%s:%c1",
9426 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
9427 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
9428 cur_text_section, sym->c);
9429 /* //gr gdb wants a line at the function */
9430 put_stabn(N_SLINE, 0, file->line_num, 0);
9431 last_ind = 0;
9432 last_line_num = 0;
9435 /* parse an old style function declaration list */
9436 /* XXX: check multiple parameter */
9437 static void func_decl_list(Sym *func_sym)
9439 AttributeDef ad;
9440 int v;
9441 Sym *s;
9442 CType btype, type;
9444 /* parse each declaration */
9445 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF) {
9446 if (!parse_btype(&btype, &ad))
9447 expect("declaration list");
9448 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9449 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9450 tok == ';') {
9451 /* we accept no variable after */
9452 } else {
9453 for(;;) {
9454 type = btype;
9455 type_decl(&type, &ad, &v, TYPE_DIRECT);
9456 /* find parameter in function parameter list */
9457 s = func_sym->next;
9458 while (s != NULL) {
9459 if ((s->v & ~SYM_FIELD) == v)
9460 goto found;
9461 s = s->next;
9463 error("declaration for parameter '%s' but no such parameter",
9464 get_tok_str(v, NULL));
9465 found:
9466 /* check that no storage specifier except 'register' was given */
9467 if (type.t & VT_STORAGE)
9468 error("storage class specified for '%s'", get_tok_str(v, NULL));
9469 convert_parameter_type(&type);
9470 /* we can add the type (NOTE: it could be local to the function) */
9471 s->type = type;
9472 /* accept other parameters */
9473 if (tok == ',')
9474 next();
9475 else
9476 break;
9479 skip(';');
9483 /* parse a function defined by symbol 'sym' and generate its code in
9484 'cur_text_section' */
9485 static void gen_function(Sym *sym)
9487 int saved_nocode_wanted = nocode_wanted;
9488 nocode_wanted = 0;
9489 ind = cur_text_section->data_offset;
9490 /* NOTE: we patch the symbol size later */
9491 put_extern_sym(sym, cur_text_section, ind, 0);
9492 funcname = get_tok_str(sym->v, NULL);
9493 func_ind = ind;
9494 /* put debug symbol */
9495 if (do_debug)
9496 put_func_debug(sym);
9497 /* push a dummy symbol to enable local sym storage */
9498 sym_push2(&local_stack, SYM_FIELD, 0, 0);
9499 gfunc_prolog(&sym->type);
9500 rsym = 0;
9501 block(NULL, NULL, NULL, NULL, 0, 0);
9502 gsym(rsym);
9503 gfunc_epilog();
9504 cur_text_section->data_offset = ind;
9505 label_pop(&global_label_stack, NULL);
9506 sym_pop(&local_stack, NULL); /* reset local stack */
9507 /* end of function */
9508 /* patch symbol size */
9509 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
9510 ind - func_ind;
9511 if (do_debug) {
9512 put_stabn(N_FUN, 0, 0, ind - func_ind);
9514 /* It's better to crash than to generate wrong code */
9515 cur_text_section = NULL;
9516 funcname = ""; /* for safety */
9517 func_vt.t = VT_VOID; /* for safety */
9518 ind = 0; /* for safety */
9519 nocode_wanted = saved_nocode_wanted;
9522 static void gen_inline_functions(void)
9524 Sym *sym;
9525 CType *type;
9526 int *str, inline_generated;
9528 /* iterate while inline function are referenced */
9529 for(;;) {
9530 inline_generated = 0;
9531 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9532 type = &sym->type;
9533 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9534 (type->t & (VT_STATIC | VT_INLINE)) ==
9535 (VT_STATIC | VT_INLINE) &&
9536 sym->c != 0) {
9537 /* the function was used: generate its code and
9538 convert it to a normal function */
9539 str = INLINE_DEF(sym->r);
9540 sym->r = VT_SYM | VT_CONST;
9541 sym->type.t &= ~VT_INLINE;
9543 macro_ptr = str;
9544 next();
9545 cur_text_section = text_section;
9546 gen_function(sym);
9547 macro_ptr = NULL; /* fail safe */
9549 tok_str_free(str);
9550 inline_generated = 1;
9553 if (!inline_generated)
9554 break;
9557 /* free all remaining inline function tokens */
9558 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9559 type = &sym->type;
9560 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9561 (type->t & (VT_STATIC | VT_INLINE)) ==
9562 (VT_STATIC | VT_INLINE)) {
9563 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9564 if (sym->r == (VT_SYM | VT_CONST)) //gr beware!
9565 continue;
9566 str = INLINE_DEF(sym->r);
9567 tok_str_free(str);
9568 sym->r = 0; /* fail safe */
9573 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9574 static void decl(int l)
9576 int v, has_init, r;
9577 CType type, btype;
9578 Sym *sym;
9579 AttributeDef ad;
9581 while (1) {
9582 if (!parse_btype(&btype, &ad)) {
9583 /* skip redundant ';' */
9584 /* XXX: find more elegant solution */
9585 if (tok == ';') {
9586 next();
9587 continue;
9589 if (l == VT_CONST &&
9590 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
9591 /* global asm block */
9592 asm_global_instr();
9593 continue;
9595 /* special test for old K&R protos without explicit int
9596 type. Only accepted when defining global data */
9597 if (l == VT_LOCAL || tok < TOK_DEFINE)
9598 break;
9599 btype.t = VT_INT;
9601 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9602 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9603 tok == ';') {
9604 /* we accept no variable after */
9605 next();
9606 continue;
9608 while (1) { /* iterate thru each declaration */
9609 type = btype;
9610 type_decl(&type, &ad, &v, TYPE_DIRECT);
9611 #if 0
9613 char buf[500];
9614 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
9615 printf("type = '%s'\n", buf);
9617 #endif
9618 if ((type.t & VT_BTYPE) == VT_FUNC) {
9619 /* if old style function prototype, we accept a
9620 declaration list */
9621 sym = type.ref;
9622 if (sym->c == FUNC_OLD)
9623 func_decl_list(sym);
9626 if (tok == '{') {
9627 if (l == VT_LOCAL)
9628 error("cannot use local functions");
9629 if ((type.t & VT_BTYPE) != VT_FUNC)
9630 expect("function definition");
9632 /* reject abstract declarators in function definition */
9633 sym = type.ref;
9634 while ((sym = sym->next) != NULL)
9635 if (!(sym->v & ~SYM_FIELD))
9636 expect("identifier");
9638 /* XXX: cannot do better now: convert extern line to static inline */
9639 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
9640 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
9642 sym = sym_find(v);
9643 if (sym) {
9644 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
9645 goto func_error1;
9646 /* specific case: if not func_call defined, we put
9647 the one of the prototype */
9648 /* XXX: should have default value */
9649 r = sym->type.ref->r;
9650 if (FUNC_CALL(r) != FUNC_CDECL
9651 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
9652 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
9653 if (FUNC_EXPORT(r))
9654 FUNC_EXPORT(type.ref->r) = 1;
9656 if (!is_compatible_types(&sym->type, &type)) {
9657 func_error1:
9658 error("incompatible types for redefinition of '%s'",
9659 get_tok_str(v, NULL));
9661 /* if symbol is already defined, then put complete type */
9662 sym->type = type;
9663 } else {
9664 /* put function symbol */
9665 sym = global_identifier_push(v, type.t, 0);
9666 sym->type.ref = type.ref;
9669 /* static inline functions are just recorded as a kind
9670 of macro. Their code will be emitted at the end of
9671 the compilation unit only if they are used */
9672 if ((type.t & (VT_INLINE | VT_STATIC)) ==
9673 (VT_INLINE | VT_STATIC)) {
9674 TokenString func_str;
9675 int block_level;
9677 tok_str_new(&func_str);
9679 block_level = 0;
9680 for(;;) {
9681 int t;
9682 if (tok == TOK_EOF)
9683 error("unexpected end of file");
9684 tok_str_add_tok(&func_str);
9685 t = tok;
9686 next();
9687 if (t == '{') {
9688 block_level++;
9689 } else if (t == '}') {
9690 block_level--;
9691 if (block_level == 0)
9692 break;
9695 tok_str_add(&func_str, -1);
9696 tok_str_add(&func_str, 0);
9697 INLINE_DEF(sym->r) = func_str.str;
9698 } else {
9699 /* compute text section */
9700 cur_text_section = ad.section;
9701 if (!cur_text_section)
9702 cur_text_section = text_section;
9703 sym->r = VT_SYM | VT_CONST;
9704 gen_function(sym);
9706 break;
9707 } else {
9708 if (btype.t & VT_TYPEDEF) {
9709 /* save typedefed type */
9710 /* XXX: test storage specifiers ? */
9711 sym = sym_push(v, &type, 0, 0);
9712 sym->type.t |= VT_TYPEDEF;
9713 } else if ((type.t & VT_BTYPE) == VT_FUNC) {
9714 /* external function definition */
9715 /* specific case for func_call attribute */
9716 if (ad.func_attr)
9717 type.ref->r = ad.func_attr;
9718 external_sym(v, &type, 0);
9719 } else {
9720 /* not lvalue if array */
9721 r = 0;
9722 if (!(type.t & VT_ARRAY))
9723 r |= lvalue_type(type.t);
9724 has_init = (tok == '=');
9725 if ((btype.t & VT_EXTERN) ||
9726 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
9727 !has_init && l == VT_CONST && type.ref->c < 0)) {
9728 /* external variable */
9729 /* NOTE: as GCC, uninitialized global static
9730 arrays of null size are considered as
9731 extern */
9732 external_sym(v, &type, r);
9733 } else {
9734 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
9735 if (type.t & VT_STATIC)
9736 r |= VT_CONST;
9737 else
9738 r |= l;
9739 if (has_init)
9740 next();
9741 decl_initializer_alloc(&type, &ad, r,
9742 has_init, v, l);
9745 if (tok != ',') {
9746 skip(';');
9747 break;
9749 next();
9755 /* better than nothing, but needs extension to handle '-E' option
9756 correctly too */
9757 static void preprocess_init(TCCState *s1)
9759 s1->include_stack_ptr = s1->include_stack;
9760 /* XXX: move that before to avoid having to initialize
9761 file->ifdef_stack_ptr ? */
9762 s1->ifdef_stack_ptr = s1->ifdef_stack;
9763 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
9765 /* XXX: not ANSI compliant: bound checking says error */
9766 vtop = vstack - 1;
9767 s1->pack_stack[0] = 0;
9768 s1->pack_stack_ptr = s1->pack_stack;
9771 /* compile the C file opened in 'file'. Return non zero if errors. */
9772 static int tcc_compile(TCCState *s1)
9774 Sym *define_start;
9775 char buf[512];
9776 volatile int section_sym;
9778 #ifdef INC_DEBUG
9779 printf("%s: **** new file\n", file->filename);
9780 #endif
9781 preprocess_init(s1);
9783 cur_text_section = NULL;
9784 funcname = "";
9785 anon_sym = SYM_FIRST_ANOM;
9787 /* file info: full path + filename */
9788 section_sym = 0; /* avoid warning */
9789 if (do_debug) {
9790 section_sym = put_elf_sym(symtab_section, 0, 0,
9791 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
9792 text_section->sh_num, NULL);
9793 getcwd(buf, sizeof(buf));
9794 #ifdef _WIN32
9795 normalize_slashes(buf);
9796 #endif
9797 pstrcat(buf, sizeof(buf), "/");
9798 put_stabs_r(buf, N_SO, 0, 0,
9799 text_section->data_offset, text_section, section_sym);
9800 put_stabs_r(file->filename, N_SO, 0, 0,
9801 text_section->data_offset, text_section, section_sym);
9803 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9804 symbols can be safely used */
9805 put_elf_sym(symtab_section, 0, 0,
9806 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
9807 SHN_ABS, file->filename);
9809 /* define some often used types */
9810 int_type.t = VT_INT;
9812 char_pointer_type.t = VT_BYTE;
9813 mk_pointer(&char_pointer_type);
9815 func_old_type.t = VT_FUNC;
9816 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
9818 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9819 float_type.t = VT_FLOAT;
9820 double_type.t = VT_DOUBLE;
9822 func_float_type.t = VT_FUNC;
9823 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
9824 func_double_type.t = VT_FUNC;
9825 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
9826 #endif
9828 #if 0
9829 /* define 'void *alloca(unsigned int)' builtin function */
9831 Sym *s1;
9833 p = anon_sym++;
9834 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
9835 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
9836 s1->next = NULL;
9837 sym->next = s1;
9838 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
9840 #endif
9842 define_start = define_stack;
9843 nocode_wanted = 1;
9845 if (setjmp(s1->error_jmp_buf) == 0) {
9846 s1->nb_errors = 0;
9847 s1->error_set_jmp_enabled = 1;
9849 ch = file->buf_ptr[0];
9850 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9851 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
9852 next();
9853 decl(VT_CONST);
9854 if (tok != TOK_EOF)
9855 expect("declaration");
9857 /* end of translation unit info */
9858 if (do_debug) {
9859 put_stabs_r(NULL, N_SO, 0, 0,
9860 text_section->data_offset, text_section, section_sym);
9863 s1->error_set_jmp_enabled = 0;
9865 /* reset define stack, but leave -Dsymbols (may be incorrect if
9866 they are undefined) */
9867 free_defines(define_start);
9869 gen_inline_functions();
9871 sym_pop(&global_stack, NULL);
9872 sym_pop(&local_stack, NULL);
9874 return s1->nb_errors != 0 ? -1 : 0;
9877 /* Preprocess the current file */
9878 /* XXX: add line and file infos,
9879 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9880 * not preserved)
9882 static int tcc_preprocess(TCCState *s1)
9884 Sym *define_start;
9885 BufferedFile *file_ref;
9886 int token_seen, line_ref;
9888 preprocess_init(s1);
9889 define_start = define_stack;
9890 ch = file->buf_ptr[0];
9892 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9893 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
9894 PARSE_FLAG_LINEFEED;
9896 token_seen = 0;
9897 line_ref = 0;
9898 file_ref = NULL;
9900 for (;;) {
9901 next();
9902 if (tok == TOK_EOF) {
9903 break;
9904 } else if (tok == TOK_LINEFEED) {
9905 if (!token_seen)
9906 continue;
9907 ++line_ref;
9908 token_seen = 0;
9909 } else if (token_seen) {
9910 fwrite(tok_spaces.data, tok_spaces.size, 1, s1->outfile);
9911 } else {
9912 int d = file->line_num - line_ref;
9913 if (file != file_ref || d < 0 || d >= 8)
9914 fprintf(s1->outfile, "# %d \"%s\"\n", file->line_num, file->filename);
9915 else
9916 while (d)
9917 fputs("\n", s1->outfile), --d;
9918 line_ref = (file_ref = file)->line_num;
9919 token_seen = 1;
9921 fputs(get_tok_str(tok, &tokc), s1->outfile);
9923 free_defines(define_start);
9924 return 0;
9927 #ifdef LIBTCC
9928 int tcc_compile_string(TCCState *s, const char *str)
9930 BufferedFile bf1, *bf = &bf1;
9931 int ret, len;
9932 char *buf;
9934 /* init file structure */
9935 bf->fd = -1;
9936 /* XXX: avoid copying */
9937 len = strlen(str);
9938 buf = tcc_malloc(len + 1);
9939 if (!buf)
9940 return -1;
9941 memcpy(buf, str, len);
9942 buf[len] = CH_EOB;
9943 bf->buf_ptr = buf;
9944 bf->buf_end = buf + len;
9945 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
9946 bf->line_num = 1;
9947 file = bf;
9948 ret = tcc_compile(s);
9949 file = NULL;
9950 tcc_free(buf);
9952 /* currently, no need to close */
9953 return ret;
9955 #endif
9957 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9958 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
9960 BufferedFile bf1, *bf = &bf1;
9962 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
9963 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
9964 /* default value */
9965 if (!value)
9966 value = "1";
9967 pstrcat(bf->buffer, IO_BUF_SIZE, value);
9969 /* init file structure */
9970 bf->fd = -1;
9971 bf->buf_ptr = bf->buffer;
9972 bf->buf_end = bf->buffer + strlen(bf->buffer);
9973 *bf->buf_end = CH_EOB;
9974 bf->filename[0] = '\0';
9975 bf->line_num = 1;
9976 file = bf;
9978 s1->include_stack_ptr = s1->include_stack;
9980 /* parse with define parser */
9981 ch = file->buf_ptr[0];
9982 next_nomacro();
9983 parse_define();
9984 file = NULL;
9987 /* undefine a preprocessor symbol */
9988 void tcc_undefine_symbol(TCCState *s1, const char *sym)
9990 TokenSym *ts;
9991 Sym *s;
9992 ts = tok_alloc(sym, strlen(sym));
9993 s = define_find(ts->tok);
9994 /* undefine symbol by putting an invalid name */
9995 if (s)
9996 define_undef(s);
9999 #ifdef CONFIG_TCC_ASM
10001 #ifdef TCC_TARGET_I386
10002 #include "i386-asm.c"
10003 #endif
10004 #include "tccasm.c"
10006 #else
10007 static void asm_instr(void)
10009 error("inline asm() not supported");
10011 static void asm_global_instr(void)
10013 error("inline asm() not supported");
10015 #endif
10017 #include "tccelf.c"
10019 #ifdef TCC_TARGET_COFF
10020 #include "tcccoff.c"
10021 #endif
10023 #ifdef TCC_TARGET_PE
10024 #include "tccpe.c"
10025 #endif
10027 /* print the position in the source file of PC value 'pc' by reading
10028 the stabs debug information */
10029 static void rt_printline(unsigned long wanted_pc)
10031 Stab_Sym *sym, *sym_end;
10032 char func_name[128], last_func_name[128];
10033 unsigned long func_addr, last_pc, pc;
10034 const char *incl_files[INCLUDE_STACK_SIZE];
10035 int incl_index, len, last_line_num, i;
10036 const char *str, *p;
10038 fprintf(stderr, "0x%08lx:", wanted_pc);
10040 func_name[0] = '\0';
10041 func_addr = 0;
10042 incl_index = 0;
10043 last_func_name[0] = '\0';
10044 last_pc = 0xffffffff;
10045 last_line_num = 1;
10046 sym = (Stab_Sym *)stab_section->data + 1;
10047 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
10048 while (sym < sym_end) {
10049 switch(sym->n_type) {
10050 /* function start or end */
10051 case N_FUN:
10052 if (sym->n_strx == 0) {
10053 /* we test if between last line and end of function */
10054 pc = sym->n_value + func_addr;
10055 if (wanted_pc >= last_pc && wanted_pc < pc)
10056 goto found;
10057 func_name[0] = '\0';
10058 func_addr = 0;
10059 } else {
10060 str = stabstr_section->data + sym->n_strx;
10061 p = strchr(str, ':');
10062 if (!p) {
10063 pstrcpy(func_name, sizeof(func_name), str);
10064 } else {
10065 len = p - str;
10066 if (len > sizeof(func_name) - 1)
10067 len = sizeof(func_name) - 1;
10068 memcpy(func_name, str, len);
10069 func_name[len] = '\0';
10071 func_addr = sym->n_value;
10073 break;
10074 /* line number info */
10075 case N_SLINE:
10076 pc = sym->n_value + func_addr;
10077 if (wanted_pc >= last_pc && wanted_pc < pc)
10078 goto found;
10079 last_pc = pc;
10080 last_line_num = sym->n_desc;
10081 /* XXX: slow! */
10082 strcpy(last_func_name, func_name);
10083 break;
10084 /* include files */
10085 case N_BINCL:
10086 str = stabstr_section->data + sym->n_strx;
10087 add_incl:
10088 if (incl_index < INCLUDE_STACK_SIZE) {
10089 incl_files[incl_index++] = str;
10091 break;
10092 case N_EINCL:
10093 if (incl_index > 1)
10094 incl_index--;
10095 break;
10096 case N_SO:
10097 if (sym->n_strx == 0) {
10098 incl_index = 0; /* end of translation unit */
10099 } else {
10100 str = stabstr_section->data + sym->n_strx;
10101 /* do not add path */
10102 len = strlen(str);
10103 if (len > 0 && str[len - 1] != '/')
10104 goto add_incl;
10106 break;
10108 sym++;
10111 /* second pass: we try symtab symbols (no line number info) */
10112 incl_index = 0;
10114 ElfW(Sym) *sym, *sym_end;
10115 int type;
10117 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
10118 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
10119 sym < sym_end;
10120 sym++) {
10121 type = ELFW(ST_TYPE)(sym->st_info);
10122 if (type == STT_FUNC) {
10123 if (wanted_pc >= sym->st_value &&
10124 wanted_pc < sym->st_value + sym->st_size) {
10125 pstrcpy(last_func_name, sizeof(last_func_name),
10126 strtab_section->data + sym->st_name);
10127 goto found;
10132 /* did not find any info: */
10133 fprintf(stderr, " ???\n");
10134 return;
10135 found:
10136 if (last_func_name[0] != '\0') {
10137 fprintf(stderr, " %s()", last_func_name);
10139 if (incl_index > 0) {
10140 fprintf(stderr, " (%s:%d",
10141 incl_files[incl_index - 1], last_line_num);
10142 for(i = incl_index - 2; i >= 0; i--)
10143 fprintf(stderr, ", included from %s", incl_files[i]);
10144 fprintf(stderr, ")");
10146 fprintf(stderr, "\n");
10149 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10151 #ifdef __i386__
10153 /* fix for glibc 2.1 */
10154 #ifndef REG_EIP
10155 #define REG_EIP EIP
10156 #define REG_EBP EBP
10157 #endif
10159 /* return the PC at frame level 'level'. Return non zero if not found */
10160 static int rt_get_caller_pc(unsigned long *paddr,
10161 ucontext_t *uc, int level)
10163 unsigned long fp;
10164 int i;
10166 if (level == 0) {
10167 #if defined(__FreeBSD__)
10168 *paddr = uc->uc_mcontext.mc_eip;
10169 #elif defined(__dietlibc__)
10170 *paddr = uc->uc_mcontext.eip;
10171 #else
10172 *paddr = uc->uc_mcontext.gregs[REG_EIP];
10173 #endif
10174 return 0;
10175 } else {
10176 #if defined(__FreeBSD__)
10177 fp = uc->uc_mcontext.mc_ebp;
10178 #elif defined(__dietlibc__)
10179 fp = uc->uc_mcontext.ebp;
10180 #else
10181 fp = uc->uc_mcontext.gregs[REG_EBP];
10182 #endif
10183 for(i=1;i<level;i++) {
10184 /* XXX: check address validity with program info */
10185 if (fp <= 0x1000 || fp >= 0xc0000000)
10186 return -1;
10187 fp = ((unsigned long *)fp)[0];
10189 *paddr = ((unsigned long *)fp)[1];
10190 return 0;
10193 #elif defined(__x86_64__)
10194 /* return the PC at frame level 'level'. Return non zero if not found */
10195 static int rt_get_caller_pc(unsigned long *paddr,
10196 ucontext_t *uc, int level)
10198 unsigned long fp;
10199 int i;
10201 if (level == 0) {
10202 /* XXX: only support linux */
10203 *paddr = uc->uc_mcontext.gregs[REG_RIP];
10204 return 0;
10205 } else {
10206 fp = uc->uc_mcontext.gregs[REG_RBP];
10207 for(i=1;i<level;i++) {
10208 /* XXX: check address validity with program info */
10209 if (fp <= 0x1000)
10210 return -1;
10211 fp = ((unsigned long *)fp)[0];
10213 *paddr = ((unsigned long *)fp)[1];
10214 return 0;
10217 #else
10219 #warning add arch specific rt_get_caller_pc()
10221 static int rt_get_caller_pc(unsigned long *paddr,
10222 ucontext_t *uc, int level)
10224 return -1;
10226 #endif
10228 /* emit a run time error at position 'pc' */
10229 void rt_error(ucontext_t *uc, const char *fmt, ...)
10231 va_list ap;
10232 unsigned long pc;
10233 int i;
10235 va_start(ap, fmt);
10236 fprintf(stderr, "Runtime error: ");
10237 vfprintf(stderr, fmt, ap);
10238 fprintf(stderr, "\n");
10239 for(i=0;i<num_callers;i++) {
10240 if (rt_get_caller_pc(&pc, uc, i) < 0)
10241 break;
10242 if (i == 0)
10243 fprintf(stderr, "at ");
10244 else
10245 fprintf(stderr, "by ");
10246 rt_printline(pc);
10248 exit(255);
10249 va_end(ap);
10252 /* signal handler for fatal errors */
10253 static void sig_error(int signum, siginfo_t *siginf, void *puc)
10255 ucontext_t *uc = puc;
10257 switch(signum) {
10258 case SIGFPE:
10259 switch(siginf->si_code) {
10260 case FPE_INTDIV:
10261 case FPE_FLTDIV:
10262 rt_error(uc, "division by zero");
10263 break;
10264 default:
10265 rt_error(uc, "floating point exception");
10266 break;
10268 break;
10269 case SIGBUS:
10270 case SIGSEGV:
10271 if (rt_bound_error_msg && *rt_bound_error_msg)
10272 rt_error(uc, *rt_bound_error_msg);
10273 else
10274 rt_error(uc, "dereferencing invalid pointer");
10275 break;
10276 case SIGILL:
10277 rt_error(uc, "illegal instruction");
10278 break;
10279 case SIGABRT:
10280 rt_error(uc, "abort() called");
10281 break;
10282 default:
10283 rt_error(uc, "caught signal %d", signum);
10284 break;
10286 exit(255);
10288 #endif
10290 /* do all relocations (needed before using tcc_get_symbol()) */
10291 int tcc_relocate(TCCState *s1)
10293 Section *s;
10294 int i;
10296 s1->nb_errors = 0;
10298 #ifdef TCC_TARGET_PE
10299 pe_add_runtime(s1);
10300 #else
10301 tcc_add_runtime(s1);
10302 #endif
10304 relocate_common_syms();
10306 tcc_add_linker_symbols(s1);
10307 #ifndef TCC_TARGET_PE
10308 build_got_entries(s1);
10309 #endif
10311 #ifdef TCC_TARGET_X86_64
10313 /* If the distance of two sections are longer than 32bit, our
10314 program will crash. Let's combine all sections which are
10315 necessary to run the program into a single buffer in the
10316 text section */
10317 unsigned char *p;
10318 int size;
10319 /* calculate the size of buffers we need */
10320 size = 0;
10321 for(i = 1; i < s1->nb_sections; i++) {
10322 s = s1->sections[i];
10323 if (s->sh_flags & SHF_ALLOC) {
10324 size += s->data_offset;
10327 /* double the size of the buffer for got and plt entries
10328 XXX: calculate exact size for them? */
10329 section_realloc(text_section, size * 2);
10330 p = text_section->data + text_section->data_offset;
10331 /* we will put got and plt after this offset */
10332 text_section->data_offset = size;
10334 for(i = 1; i < s1->nb_sections; i++) {
10335 s = s1->sections[i];
10336 if (s->sh_flags & SHF_ALLOC) {
10337 if (s != text_section && s->data_offset) {
10338 if (s->sh_type == SHT_NOBITS) {
10339 /* for bss section */
10340 memset(p, 0, s->data_offset);
10341 } else {
10342 memcpy(p, s->data, s->data_offset);
10343 tcc_free(s->data);
10345 s->data = p;
10346 /* we won't free s->data for this section */
10347 s->data_allocated = 0;
10348 p += s->data_offset;
10350 s->sh_addr = (unsigned long)s->data;
10354 #else
10355 /* compute relocation address : section are relocated in place. We
10356 also alloc the bss space */
10357 for(i = 1; i < s1->nb_sections; i++) {
10358 s = s1->sections[i];
10359 if (s->sh_flags & SHF_ALLOC) {
10360 if (s->sh_type == SHT_NOBITS)
10361 s->data = tcc_mallocz(s->data_offset);
10362 s->sh_addr = (unsigned long)s->data;
10365 #endif
10367 relocate_syms(s1, 1);
10369 if (s1->nb_errors != 0)
10370 return -1;
10372 /* relocate each section */
10373 for(i = 1; i < s1->nb_sections; i++) {
10374 s = s1->sections[i];
10375 if (s->reloc)
10376 relocate_section(s1, s);
10379 /* mark executable sections as executable in memory */
10380 for(i = 1; i < s1->nb_sections; i++) {
10381 s = s1->sections[i];
10382 if ((s->sh_flags & (SHF_ALLOC | SHF_EXECINSTR)) ==
10383 (SHF_ALLOC | SHF_EXECINSTR))
10384 set_pages_executable(s->data, s->data_offset);
10386 return 0;
10389 /* launch the compiled program with the given arguments */
10390 int tcc_run(TCCState *s1, int argc, char **argv)
10392 int (*prog_main)(int, char **);
10394 if (tcc_relocate(s1) < 0)
10395 return -1;
10397 prog_main = tcc_get_symbol_err(s1, "main");
10399 if (do_debug) {
10400 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10401 error("debug mode currently not available for Windows");
10402 #else
10403 struct sigaction sigact;
10404 /* install TCC signal handlers to print debug info on fatal
10405 runtime errors */
10406 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
10407 sigact.sa_sigaction = sig_error;
10408 sigemptyset(&sigact.sa_mask);
10409 sigaction(SIGFPE, &sigact, NULL);
10410 sigaction(SIGILL, &sigact, NULL);
10411 sigaction(SIGSEGV, &sigact, NULL);
10412 sigaction(SIGBUS, &sigact, NULL);
10413 sigaction(SIGABRT, &sigact, NULL);
10414 #endif
10417 #ifdef CONFIG_TCC_BCHECK
10418 if (do_bounds_check) {
10419 void (*bound_init)(void);
10421 /* set error function */
10422 rt_bound_error_msg = (void *)tcc_get_symbol_err(s1,
10423 "__bound_error_msg");
10425 /* XXX: use .init section so that it also work in binary ? */
10426 bound_init = (void *)tcc_get_symbol_err(s1, "__bound_init");
10427 bound_init();
10429 #endif
10430 return (*prog_main)(argc, argv);
10433 void tcc_memstats(void)
10435 #ifdef MEM_DEBUG
10436 printf("memory in use: %d\n", mem_cur_size);
10437 #endif
10440 static void tcc_cleanup(void)
10442 int i, n;
10444 if (NULL == tcc_state)
10445 return;
10446 tcc_state = NULL;
10448 /* free -D defines */
10449 free_defines(NULL);
10451 /* free tokens */
10452 n = tok_ident - TOK_IDENT;
10453 for(i = 0; i < n; i++)
10454 tcc_free(table_ident[i]);
10455 tcc_free(table_ident);
10457 /* free sym_pools */
10458 dynarray_reset(&sym_pools, &nb_sym_pools);
10459 /* string buffer */
10460 cstr_free(&tokcstr);
10461 /* reset symbol stack */
10462 sym_free_first = NULL;
10463 /* cleanup from error/setjmp */
10464 macro_ptr = NULL;
10467 TCCState *tcc_new(void)
10469 const char *p, *r;
10470 TCCState *s;
10471 TokenSym *ts;
10472 int i, c;
10474 tcc_cleanup();
10476 s = tcc_mallocz(sizeof(TCCState));
10477 if (!s)
10478 return NULL;
10479 tcc_state = s;
10480 s->output_type = TCC_OUTPUT_MEMORY;
10482 /* init isid table */
10483 for(i=CH_EOF;i<256;i++)
10484 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
10486 /* add all tokens */
10487 table_ident = NULL;
10488 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
10490 tok_ident = TOK_IDENT;
10491 p = tcc_keywords;
10492 while (*p) {
10493 r = p;
10494 for(;;) {
10495 c = *r++;
10496 if (c == '\0')
10497 break;
10499 ts = tok_alloc(p, r - p - 1);
10500 p = r;
10503 /* we add dummy defines for some special macros to speed up tests
10504 and to have working defined() */
10505 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
10506 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
10507 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
10508 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
10510 /* standard defines */
10511 tcc_define_symbol(s, "__STDC__", NULL);
10512 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
10513 #if defined(TCC_TARGET_I386)
10514 tcc_define_symbol(s, "__i386__", NULL);
10515 #endif
10516 #if defined(TCC_TARGET_X86_64)
10517 tcc_define_symbol(s, "__x86_64__", NULL);
10518 #endif
10519 #if defined(TCC_TARGET_ARM)
10520 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
10521 tcc_define_symbol(s, "__arm_elf__", NULL);
10522 tcc_define_symbol(s, "__arm_elf", NULL);
10523 tcc_define_symbol(s, "arm_elf", NULL);
10524 tcc_define_symbol(s, "__arm__", NULL);
10525 tcc_define_symbol(s, "__arm", NULL);
10526 tcc_define_symbol(s, "arm", NULL);
10527 tcc_define_symbol(s, "__APCS_32__", NULL);
10528 #endif
10529 #ifdef TCC_TARGET_PE
10530 tcc_define_symbol(s, "_WIN32", NULL);
10531 #else
10532 tcc_define_symbol(s, "__unix__", NULL);
10533 tcc_define_symbol(s, "__unix", NULL);
10534 #if defined(__linux)
10535 tcc_define_symbol(s, "__linux__", NULL);
10536 tcc_define_symbol(s, "__linux", NULL);
10537 #endif
10538 #endif
10539 /* tiny C specific defines */
10540 tcc_define_symbol(s, "__TINYC__", NULL);
10542 /* tiny C & gcc defines */
10543 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
10544 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
10545 #ifdef TCC_TARGET_PE
10546 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
10547 #else
10548 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
10549 #endif
10551 #ifndef TCC_TARGET_PE
10552 /* default library paths */
10553 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
10554 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
10555 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
10556 #endif
10558 /* no section zero */
10559 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
10561 /* create standard sections */
10562 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
10563 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
10564 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
10566 /* symbols are always generated for linking stage */
10567 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
10568 ".strtab",
10569 ".hashtab", SHF_PRIVATE);
10570 strtab_section = symtab_section->link;
10572 /* private symbol table for dynamic symbols */
10573 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
10574 ".dynstrtab",
10575 ".dynhashtab", SHF_PRIVATE);
10576 s->alacarte_link = 1;
10578 #ifdef CHAR_IS_UNSIGNED
10579 s->char_is_unsigned = 1;
10580 #endif
10581 #if defined(TCC_TARGET_PE) && 0
10582 /* XXX: currently the PE linker is not ready to support that */
10583 s->leading_underscore = 1;
10584 #endif
10585 return s;
10588 void tcc_delete(TCCState *s1)
10590 int i;
10592 tcc_cleanup();
10594 /* free all sections */
10595 for(i = 1; i < s1->nb_sections; i++)
10596 free_section(s1->sections[i]);
10597 dynarray_reset(&s1->sections, &s1->nb_sections);
10599 for(i = 0; i < s1->nb_priv_sections; i++)
10600 free_section(s1->priv_sections[i]);
10601 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
10603 /* free any loaded DLLs */
10604 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
10605 DLLReference *ref = s1->loaded_dlls[i];
10606 if ( ref->handle )
10607 dlclose(ref->handle);
10610 /* free loaded dlls array */
10611 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
10613 /* free library paths */
10614 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
10616 /* free include paths */
10617 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
10618 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
10619 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
10621 tcc_free(s1);
10624 int tcc_add_include_path(TCCState *s1, const char *pathname)
10626 char *pathname1;
10628 pathname1 = tcc_strdup(pathname);
10629 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
10630 return 0;
10633 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
10635 char *pathname1;
10637 pathname1 = tcc_strdup(pathname);
10638 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
10639 return 0;
10642 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
10644 const char *ext;
10645 ElfW(Ehdr) ehdr;
10646 int fd, ret;
10647 BufferedFile *saved_file;
10649 /* find source file type with extension */
10650 ext = tcc_fileextension(filename);
10651 if (ext[0])
10652 ext++;
10654 /* open the file */
10655 saved_file = file;
10656 file = tcc_open(s1, filename);
10657 if (!file) {
10658 if (flags & AFF_PRINT_ERROR) {
10659 error_noabort("file '%s' not found", filename);
10661 ret = -1;
10662 goto fail1;
10665 if (flags & AFF_PREPROCESS) {
10666 ret = tcc_preprocess(s1);
10667 } else if (!ext[0] || !PATHCMP(ext, "c")) {
10668 /* C file assumed */
10669 ret = tcc_compile(s1);
10670 } else
10671 #ifdef CONFIG_TCC_ASM
10672 if (!strcmp(ext, "S")) {
10673 /* preprocessed assembler */
10674 ret = tcc_assemble(s1, 1);
10675 } else if (!strcmp(ext, "s")) {
10676 /* non preprocessed assembler */
10677 ret = tcc_assemble(s1, 0);
10678 } else
10679 #endif
10680 #ifdef TCC_TARGET_PE
10681 if (!PATHCMP(ext, "def")) {
10682 ret = pe_load_def_file(s1, file->fd);
10683 } else
10684 #endif
10686 fd = file->fd;
10687 /* assume executable format: auto guess file type */
10688 ret = read(fd, &ehdr, sizeof(ehdr));
10689 lseek(fd, 0, SEEK_SET);
10690 if (ret <= 0) {
10691 error_noabort("could not read header");
10692 goto fail;
10693 } else if (ret != sizeof(ehdr)) {
10694 goto try_load_script;
10697 if (ehdr.e_ident[0] == ELFMAG0 &&
10698 ehdr.e_ident[1] == ELFMAG1 &&
10699 ehdr.e_ident[2] == ELFMAG2 &&
10700 ehdr.e_ident[3] == ELFMAG3) {
10701 file->line_num = 0; /* do not display line number if error */
10702 if (ehdr.e_type == ET_REL) {
10703 ret = tcc_load_object_file(s1, fd, 0);
10704 } else if (ehdr.e_type == ET_DYN) {
10705 if (s1->output_type == TCC_OUTPUT_MEMORY) {
10706 #ifdef TCC_TARGET_PE
10707 ret = -1;
10708 #else
10709 void *h;
10710 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
10711 if (h)
10712 ret = 0;
10713 else
10714 ret = -1;
10715 #endif
10716 } else {
10717 ret = tcc_load_dll(s1, fd, filename,
10718 (flags & AFF_REFERENCED_DLL) != 0);
10720 } else {
10721 error_noabort("unrecognized ELF file");
10722 goto fail;
10724 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
10725 file->line_num = 0; /* do not display line number if error */
10726 ret = tcc_load_archive(s1, fd);
10727 } else
10728 #ifdef TCC_TARGET_COFF
10729 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
10730 ret = tcc_load_coff(s1, fd);
10731 } else
10732 #endif
10733 #ifdef TCC_TARGET_PE
10734 if (pe_test_res_file(&ehdr, ret)) {
10735 ret = pe_load_res_file(s1, fd);
10736 } else
10737 #endif
10739 /* as GNU ld, consider it is an ld script if not recognized */
10740 try_load_script:
10741 ret = tcc_load_ldscript(s1);
10742 if (ret < 0) {
10743 error_noabort("unrecognized file type");
10744 goto fail;
10748 the_end:
10749 tcc_close(file);
10750 fail1:
10751 file = saved_file;
10752 return ret;
10753 fail:
10754 ret = -1;
10755 goto the_end;
10758 int tcc_add_file(TCCState *s, const char *filename)
10760 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
10763 int tcc_add_library_path(TCCState *s, const char *pathname)
10765 char *pathname1;
10767 pathname1 = tcc_strdup(pathname);
10768 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
10769 return 0;
10772 /* find and load a dll. Return non zero if not found */
10773 /* XXX: add '-rpath' option support ? */
10774 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
10776 char buf[1024];
10777 int i;
10779 for(i = 0; i < s->nb_library_paths; i++) {
10780 snprintf(buf, sizeof(buf), "%s/%s",
10781 s->library_paths[i], filename);
10782 if (tcc_add_file_internal(s, buf, flags) == 0)
10783 return 0;
10785 return -1;
10788 /* the library name is the same as the argument of the '-l' option */
10789 int tcc_add_library(TCCState *s, const char *libraryname)
10791 char buf[1024];
10792 int i;
10794 /* first we look for the dynamic library if not static linking */
10795 if (!s->static_link) {
10796 #ifdef TCC_TARGET_PE
10797 snprintf(buf, sizeof(buf), "%s.def", libraryname);
10798 #else
10799 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
10800 #endif
10801 if (tcc_add_dll(s, buf, 0) == 0)
10802 return 0;
10805 /* then we look for the static library */
10806 for(i = 0; i < s->nb_library_paths; i++) {
10807 snprintf(buf, sizeof(buf), "%s/lib%s.a",
10808 s->library_paths[i], libraryname);
10809 if (tcc_add_file_internal(s, buf, 0) == 0)
10810 return 0;
10812 return -1;
10815 int tcc_add_symbol(TCCState *s, const char *name, unsigned long val)
10817 add_elf_sym(symtab_section, val, 0,
10818 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
10819 SHN_ABS, name);
10820 return 0;
10823 int tcc_set_output_type(TCCState *s, int output_type)
10825 char buf[1024];
10827 s->output_type = output_type;
10829 if (!s->nostdinc) {
10830 /* default include paths */
10831 /* XXX: reverse order needed if -isystem support */
10832 #ifndef TCC_TARGET_PE
10833 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
10834 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
10835 #endif
10836 snprintf(buf, sizeof(buf), "%s/include", tcc_lib_path);
10837 tcc_add_sysinclude_path(s, buf);
10838 #ifdef TCC_TARGET_PE
10839 snprintf(buf, sizeof(buf), "%s/include/winapi", tcc_lib_path);
10840 tcc_add_sysinclude_path(s, buf);
10841 #endif
10844 /* if bound checking, then add corresponding sections */
10845 #ifdef CONFIG_TCC_BCHECK
10846 if (do_bounds_check) {
10847 /* define symbol */
10848 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
10849 /* create bounds sections */
10850 bounds_section = new_section(s, ".bounds",
10851 SHT_PROGBITS, SHF_ALLOC);
10852 lbounds_section = new_section(s, ".lbounds",
10853 SHT_PROGBITS, SHF_ALLOC);
10855 #endif
10857 if (s->char_is_unsigned) {
10858 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
10861 /* add debug sections */
10862 if (do_debug) {
10863 /* stab symbols */
10864 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
10865 stab_section->sh_entsize = sizeof(Stab_Sym);
10866 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
10867 put_elf_str(stabstr_section, "");
10868 stab_section->link = stabstr_section;
10869 /* put first entry */
10870 put_stabs("", 0, 0, 0, 0);
10873 /* add libc crt1/crti objects */
10874 #ifndef TCC_TARGET_PE
10875 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
10876 !s->nostdlib) {
10877 if (output_type != TCC_OUTPUT_DLL)
10878 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
10879 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
10881 #endif
10883 #ifdef TCC_TARGET_PE
10884 snprintf(buf, sizeof(buf), "%s/lib", tcc_lib_path);
10885 tcc_add_library_path(s, buf);
10886 #endif
10888 return 0;
10891 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10892 #define FD_INVERT 0x0002 /* invert value before storing */
10894 typedef struct FlagDef {
10895 uint16_t offset;
10896 uint16_t flags;
10897 const char *name;
10898 } FlagDef;
10900 static const FlagDef warning_defs[] = {
10901 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
10902 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
10903 { offsetof(TCCState, warn_error), 0, "error" },
10904 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
10905 "implicit-function-declaration" },
10908 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
10909 const char *name, int value)
10911 int i;
10912 const FlagDef *p;
10913 const char *r;
10915 r = name;
10916 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
10917 r += 3;
10918 value = !value;
10920 for(i = 0, p = flags; i < nb_flags; i++, p++) {
10921 if (!strcmp(r, p->name))
10922 goto found;
10924 return -1;
10925 found:
10926 if (p->flags & FD_INVERT)
10927 value = !value;
10928 *(int *)((uint8_t *)s + p->offset) = value;
10929 return 0;
10933 /* set/reset a warning */
10934 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
10936 int i;
10937 const FlagDef *p;
10939 if (!strcmp(warning_name, "all")) {
10940 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
10941 if (p->flags & WD_ALL)
10942 *(int *)((uint8_t *)s + p->offset) = 1;
10944 return 0;
10945 } else {
10946 return set_flag(s, warning_defs, countof(warning_defs),
10947 warning_name, value);
10951 static const FlagDef flag_defs[] = {
10952 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
10953 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
10954 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
10955 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
10958 /* set/reset a flag */
10959 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
10961 return set_flag(s, flag_defs, countof(flag_defs),
10962 flag_name, value);
10965 #if !defined(LIBTCC)
10967 static int64_t getclock_us(void)
10969 #ifdef _WIN32
10970 struct _timeb tb;
10971 _ftime(&tb);
10972 return (tb.time * 1000LL + tb.millitm) * 1000LL;
10973 #else
10974 struct timeval tv;
10975 gettimeofday(&tv, NULL);
10976 return tv.tv_sec * 1000000LL + tv.tv_usec;
10977 #endif
10980 void help(void)
10982 printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10983 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10984 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10985 " [-static] [infile1 infile2...] [-run infile args...]\n"
10986 "\n"
10987 "General options:\n"
10988 " -v display current version, increase verbosity\n"
10989 " -c compile only - generate an object file\n"
10990 " -o outfile set output filename\n"
10991 " -Bdir set tcc internal library path\n"
10992 " -bench output compilation statistics\n"
10993 " -run run compiled source\n"
10994 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10995 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10996 " -w disable all warnings\n"
10997 "Preprocessor options:\n"
10998 " -E preprocess only\n"
10999 " -Idir add include path 'dir'\n"
11000 " -Dsym[=val] define 'sym' with value 'val'\n"
11001 " -Usym undefine 'sym'\n"
11002 "Linker options:\n"
11003 " -Ldir add library path 'dir'\n"
11004 " -llib link with dynamic or static library 'lib'\n"
11005 " -shared generate a shared library\n"
11006 " -soname set name for shared library to be used at runtime\n"
11007 " -static static linking\n"
11008 " -rdynamic export all global symbols to dynamic linker\n"
11009 " -r generate (relocatable) object file\n"
11010 "Debugger options:\n"
11011 " -g generate runtime debug info\n"
11012 #ifdef CONFIG_TCC_BCHECK
11013 " -b compile with built-in memory and bounds checker (implies -g)\n"
11014 #endif
11015 " -bt N show N callers in stack traces\n"
11019 #define TCC_OPTION_HAS_ARG 0x0001
11020 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
11022 typedef struct TCCOption {
11023 const char *name;
11024 uint16_t index;
11025 uint16_t flags;
11026 } TCCOption;
11028 enum {
11029 TCC_OPTION_HELP,
11030 TCC_OPTION_I,
11031 TCC_OPTION_D,
11032 TCC_OPTION_U,
11033 TCC_OPTION_L,
11034 TCC_OPTION_B,
11035 TCC_OPTION_l,
11036 TCC_OPTION_bench,
11037 TCC_OPTION_bt,
11038 TCC_OPTION_b,
11039 TCC_OPTION_g,
11040 TCC_OPTION_c,
11041 TCC_OPTION_static,
11042 TCC_OPTION_shared,
11043 TCC_OPTION_soname,
11044 TCC_OPTION_o,
11045 TCC_OPTION_r,
11046 TCC_OPTION_Wl,
11047 TCC_OPTION_W,
11048 TCC_OPTION_O,
11049 TCC_OPTION_m,
11050 TCC_OPTION_f,
11051 TCC_OPTION_nostdinc,
11052 TCC_OPTION_nostdlib,
11053 TCC_OPTION_print_search_dirs,
11054 TCC_OPTION_rdynamic,
11055 TCC_OPTION_run,
11056 TCC_OPTION_v,
11057 TCC_OPTION_w,
11058 TCC_OPTION_pipe,
11059 TCC_OPTION_E,
11062 static const TCCOption tcc_options[] = {
11063 { "h", TCC_OPTION_HELP, 0 },
11064 { "?", TCC_OPTION_HELP, 0 },
11065 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
11066 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
11067 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
11068 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
11069 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
11070 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11071 { "bench", TCC_OPTION_bench, 0 },
11072 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
11073 #ifdef CONFIG_TCC_BCHECK
11074 { "b", TCC_OPTION_b, 0 },
11075 #endif
11076 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11077 { "c", TCC_OPTION_c, 0 },
11078 { "static", TCC_OPTION_static, 0 },
11079 { "shared", TCC_OPTION_shared, 0 },
11080 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
11081 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
11082 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11083 { "rdynamic", TCC_OPTION_rdynamic, 0 },
11084 { "r", TCC_OPTION_r, 0 },
11085 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11086 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11087 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11088 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
11089 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11090 { "nostdinc", TCC_OPTION_nostdinc, 0 },
11091 { "nostdlib", TCC_OPTION_nostdlib, 0 },
11092 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
11093 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11094 { "w", TCC_OPTION_w, 0 },
11095 { "pipe", TCC_OPTION_pipe, 0},
11096 { "E", TCC_OPTION_E, 0},
11097 { NULL },
11100 /* convert 'str' into an array of space separated strings */
11101 static int expand_args(char ***pargv, const char *str)
11103 const char *s1;
11104 char **argv, *arg;
11105 int argc, len;
11107 argc = 0;
11108 argv = NULL;
11109 for(;;) {
11110 while (is_space(*str))
11111 str++;
11112 if (*str == '\0')
11113 break;
11114 s1 = str;
11115 while (*str != '\0' && !is_space(*str))
11116 str++;
11117 len = str - s1;
11118 arg = tcc_malloc(len + 1);
11119 memcpy(arg, s1, len);
11120 arg[len] = '\0';
11121 dynarray_add((void ***)&argv, &argc, arg);
11123 *pargv = argv;
11124 return argc;
11127 static char **files;
11128 static int nb_files, nb_libraries;
11129 static int multiple_files;
11130 static int print_search_dirs;
11131 static int output_type;
11132 static int reloc_output;
11133 static const char *outfile;
11135 int parse_args(TCCState *s, int argc, char **argv)
11137 int optind;
11138 const TCCOption *popt;
11139 const char *optarg, *p1, *r1;
11140 char *r;
11142 optind = 0;
11143 while (optind < argc) {
11145 r = argv[optind++];
11146 if (r[0] != '-' || r[1] == '\0') {
11147 /* add a new file */
11148 dynarray_add((void ***)&files, &nb_files, r);
11149 if (!multiple_files) {
11150 optind--;
11151 /* argv[0] will be this file */
11152 break;
11154 } else {
11155 /* find option in table (match only the first chars */
11156 popt = tcc_options;
11157 for(;;) {
11158 p1 = popt->name;
11159 if (p1 == NULL)
11160 error("invalid option -- '%s'", r);
11161 r1 = r + 1;
11162 for(;;) {
11163 if (*p1 == '\0')
11164 goto option_found;
11165 if (*r1 != *p1)
11166 break;
11167 p1++;
11168 r1++;
11170 popt++;
11172 option_found:
11173 if (popt->flags & TCC_OPTION_HAS_ARG) {
11174 if (*r1 != '\0' || (popt->flags & TCC_OPTION_NOSEP)) {
11175 optarg = r1;
11176 } else {
11177 if (optind >= argc)
11178 error("argument to '%s' is missing", r);
11179 optarg = argv[optind++];
11181 } else {
11182 if (*r1 != '\0')
11183 return 0;
11184 optarg = NULL;
11187 switch(popt->index) {
11188 case TCC_OPTION_HELP:
11189 return 0;
11191 case TCC_OPTION_I:
11192 if (tcc_add_include_path(s, optarg) < 0)
11193 error("too many include paths");
11194 break;
11195 case TCC_OPTION_D:
11197 char *sym, *value;
11198 sym = (char *)optarg;
11199 value = strchr(sym, '=');
11200 if (value) {
11201 *value = '\0';
11202 value++;
11204 tcc_define_symbol(s, sym, value);
11206 break;
11207 case TCC_OPTION_U:
11208 tcc_undefine_symbol(s, optarg);
11209 break;
11210 case TCC_OPTION_L:
11211 tcc_add_library_path(s, optarg);
11212 break;
11213 case TCC_OPTION_B:
11214 /* set tcc utilities path (mainly for tcc development) */
11215 tcc_lib_path = optarg;
11216 break;
11217 case TCC_OPTION_l:
11218 dynarray_add((void ***)&files, &nb_files, r);
11219 nb_libraries++;
11220 break;
11221 case TCC_OPTION_bench:
11222 do_bench = 1;
11223 break;
11224 case TCC_OPTION_bt:
11225 num_callers = atoi(optarg);
11226 break;
11227 #ifdef CONFIG_TCC_BCHECK
11228 case TCC_OPTION_b:
11229 do_bounds_check = 1;
11230 do_debug = 1;
11231 break;
11232 #endif
11233 case TCC_OPTION_g:
11234 do_debug = 1;
11235 break;
11236 case TCC_OPTION_c:
11237 multiple_files = 1;
11238 output_type = TCC_OUTPUT_OBJ;
11239 break;
11240 case TCC_OPTION_static:
11241 s->static_link = 1;
11242 break;
11243 case TCC_OPTION_shared:
11244 output_type = TCC_OUTPUT_DLL;
11245 break;
11246 case TCC_OPTION_soname:
11247 s->soname = optarg;
11248 break;
11249 case TCC_OPTION_o:
11250 multiple_files = 1;
11251 outfile = optarg;
11252 break;
11253 case TCC_OPTION_r:
11254 /* generate a .o merging several output files */
11255 reloc_output = 1;
11256 output_type = TCC_OUTPUT_OBJ;
11257 break;
11258 case TCC_OPTION_nostdinc:
11259 s->nostdinc = 1;
11260 break;
11261 case TCC_OPTION_nostdlib:
11262 s->nostdlib = 1;
11263 break;
11264 case TCC_OPTION_print_search_dirs:
11265 print_search_dirs = 1;
11266 break;
11267 case TCC_OPTION_run:
11269 int argc1;
11270 char **argv1;
11271 argc1 = expand_args(&argv1, optarg);
11272 if (argc1 > 0) {
11273 parse_args(s, argc1, argv1);
11275 multiple_files = 0;
11276 output_type = TCC_OUTPUT_MEMORY;
11278 break;
11279 case TCC_OPTION_v:
11280 do {
11281 if (0 == verbose++)
11282 printf("tcc version %s\n", TCC_VERSION);
11283 } while (*optarg++ == 'v');
11284 break;
11285 case TCC_OPTION_f:
11286 if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
11287 goto unsupported_option;
11288 break;
11289 case TCC_OPTION_W:
11290 if (tcc_set_warning(s, optarg, 1) < 0 &&
11291 s->warn_unsupported)
11292 goto unsupported_option;
11293 break;
11294 case TCC_OPTION_w:
11295 s->warn_none = 1;
11296 break;
11297 case TCC_OPTION_rdynamic:
11298 s->rdynamic = 1;
11299 break;
11300 case TCC_OPTION_Wl:
11302 const char *p;
11303 if (strstart(optarg, "-Ttext,", &p)) {
11304 s->text_addr = strtoul(p, NULL, 16);
11305 s->has_text_addr = 1;
11306 } else if (strstart(optarg, "--oformat,", &p)) {
11307 if (strstart(p, "elf32-", NULL)) {
11308 s->output_format = TCC_OUTPUT_FORMAT_ELF;
11309 } else if (!strcmp(p, "binary")) {
11310 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
11311 } else
11312 #ifdef TCC_TARGET_COFF
11313 if (!strcmp(p, "coff")) {
11314 s->output_format = TCC_OUTPUT_FORMAT_COFF;
11315 } else
11316 #endif
11318 error("target %s not found", p);
11320 } else {
11321 error("unsupported linker option '%s'", optarg);
11324 break;
11325 case TCC_OPTION_E:
11326 output_type = TCC_OUTPUT_PREPROCESS;
11327 break;
11328 default:
11329 if (s->warn_unsupported) {
11330 unsupported_option:
11331 warning("unsupported option '%s'", r);
11333 break;
11337 return optind + 1;
11340 int main(int argc, char **argv)
11342 int i;
11343 TCCState *s;
11344 int nb_objfiles, ret, optind;
11345 char objfilename[1024];
11346 int64_t start_time = 0;
11348 #ifdef _WIN32
11349 tcc_lib_path = w32_tcc_lib_path();
11350 #endif
11352 s = tcc_new();
11353 output_type = TCC_OUTPUT_EXE;
11354 outfile = NULL;
11355 multiple_files = 1;
11356 files = NULL;
11357 nb_files = 0;
11358 nb_libraries = 0;
11359 reloc_output = 0;
11360 print_search_dirs = 0;
11361 ret = 0;
11363 optind = parse_args(s, argc - 1, argv + 1);
11364 if (print_search_dirs) {
11365 /* enough for Linux kernel */
11366 printf("install: %s/\n", tcc_lib_path);
11367 return 0;
11369 if (optind == 0 || nb_files == 0) {
11370 if (optind && verbose)
11371 return 0;
11372 help();
11373 return 1;
11376 nb_objfiles = nb_files - nb_libraries;
11378 /* if outfile provided without other options, we output an
11379 executable */
11380 if (outfile && output_type == TCC_OUTPUT_MEMORY)
11381 output_type = TCC_OUTPUT_EXE;
11383 /* check -c consistency : only single file handled. XXX: checks file type */
11384 if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
11385 /* accepts only a single input file */
11386 if (nb_objfiles != 1)
11387 error("cannot specify multiple files with -c");
11388 if (nb_libraries != 0)
11389 error("cannot specify libraries with -c");
11393 if (output_type == TCC_OUTPUT_PREPROCESS) {
11394 if (!outfile) {
11395 s->outfile = stdout;
11396 } else {
11397 s->outfile = fopen(outfile, "w");
11398 if (!s->outfile)
11399 error("could not open '%s", outfile);
11401 } else if (output_type != TCC_OUTPUT_MEMORY) {
11402 if (!outfile) {
11403 /* compute default outfile name */
11404 char *ext;
11405 const char *name =
11406 strcmp(files[0], "-") == 0 ? "a" : tcc_basename(files[0]);
11407 pstrcpy(objfilename, sizeof(objfilename), name);
11408 ext = tcc_fileextension(objfilename);
11409 #ifdef TCC_TARGET_PE
11410 if (output_type == TCC_OUTPUT_DLL)
11411 strcpy(ext, ".dll");
11412 else
11413 if (output_type == TCC_OUTPUT_EXE)
11414 strcpy(ext, ".exe");
11415 else
11416 #endif
11417 if (output_type == TCC_OUTPUT_OBJ && !reloc_output && *ext)
11418 strcpy(ext, ".o");
11419 else
11420 pstrcpy(objfilename, sizeof(objfilename), "a.out");
11421 outfile = objfilename;
11425 if (do_bench) {
11426 start_time = getclock_us();
11429 tcc_set_output_type(s, output_type);
11431 /* compile or add each files or library */
11432 for(i = 0; i < nb_files && ret == 0; i++) {
11433 const char *filename;
11435 filename = files[i];
11436 if (output_type == TCC_OUTPUT_PREPROCESS) {
11437 if (tcc_add_file_internal(s, filename,
11438 AFF_PRINT_ERROR | AFF_PREPROCESS) < 0)
11439 ret = 1;
11440 } else if (filename[0] == '-' && filename[1]) {
11441 if (tcc_add_library(s, filename + 2) < 0)
11442 error("cannot find %s", filename);
11443 } else {
11444 if (1 == verbose)
11445 printf("-> %s\n", filename);
11446 if (tcc_add_file(s, filename) < 0)
11447 ret = 1;
11451 /* free all files */
11452 tcc_free(files);
11454 if (ret)
11455 goto the_end;
11457 if (do_bench) {
11458 double total_time;
11459 total_time = (double)(getclock_us() - start_time) / 1000000.0;
11460 if (total_time < 0.001)
11461 total_time = 0.001;
11462 if (total_bytes < 1)
11463 total_bytes = 1;
11464 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11465 tok_ident - TOK_IDENT, total_lines, total_bytes,
11466 total_time, (int)(total_lines / total_time),
11467 total_bytes / total_time / 1000000.0);
11470 if (s->output_type == TCC_OUTPUT_PREPROCESS) {
11471 if (outfile)
11472 fclose(s->outfile);
11473 } else if (s->output_type == TCC_OUTPUT_MEMORY) {
11474 ret = tcc_run(s, argc - optind, argv + optind);
11475 } else
11476 ret = tcc_output_file(s, outfile) ? 1 : 0;
11477 the_end:
11478 /* XXX: cannot do it with bound checking because of the malloc hooks */
11479 if (!do_bounds_check)
11480 tcc_delete(s);
11482 #ifdef MEM_DEBUG
11483 if (do_bench) {
11484 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size, mem_max_size);
11486 #endif
11487 return ret;
11490 #endif