Fix silly typos in the previous change.
[tinycc.git] / tcc.c
blobe58651f7d0d35968a0933a8e642063c009bbef33
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 #else
1079 #define IS_PATHSEP(c) (c == '/')
1080 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1081 #endif
1083 /* extract the basename of a file */
1084 static char *tcc_basename(const char *name)
1086 char *p = strchr(name, 0);
1087 while (p > name && !IS_PATHSEP(p[-1]))
1088 --p;
1089 return p;
1092 static char *tcc_fileextension (const char *name)
1094 char *b = tcc_basename(name);
1095 char *e = strrchr(b, '.');
1096 return e ? e : strchr(b, 0);
1099 #ifdef _WIN32
1100 char *normalize_slashes(char *path)
1102 char *p;
1103 for (p = path; *p; ++p)
1104 if (*p == '\\')
1105 *p = '/';
1106 return path;
1109 char *w32_tcc_lib_path(void)
1111 /* on win32, we suppose the lib and includes are at the location
1112 of 'tcc.exe' */
1113 char path[1024], *p;
1114 GetModuleFileNameA(NULL, path, sizeof path);
1115 p = tcc_basename(normalize_slashes(strlwr(path)));
1116 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
1117 p -= 5;
1118 else if (p > path)
1119 p--;
1120 *p = 0;
1121 return strdup(path);
1123 #endif
1125 void set_pages_executable(void *ptr, unsigned long length)
1127 #ifdef _WIN32
1128 unsigned long old_protect;
1129 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
1130 #else
1131 unsigned long start, end;
1132 start = (unsigned long)ptr & ~(PAGESIZE - 1);
1133 end = (unsigned long)ptr + length;
1134 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
1135 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
1136 #endif
1139 /* memory management */
1140 #ifdef MEM_DEBUG
1141 int mem_cur_size;
1142 int mem_max_size;
1143 unsigned malloc_usable_size(void*);
1144 #endif
1146 static inline void tcc_free(void *ptr)
1148 #ifdef MEM_DEBUG
1149 mem_cur_size -= malloc_usable_size(ptr);
1150 #endif
1151 free(ptr);
1154 static void *tcc_malloc(unsigned long size)
1156 void *ptr;
1157 ptr = malloc(size);
1158 if (!ptr && size)
1159 error("memory full");
1160 #ifdef MEM_DEBUG
1161 mem_cur_size += malloc_usable_size(ptr);
1162 if (mem_cur_size > mem_max_size)
1163 mem_max_size = mem_cur_size;
1164 #endif
1165 return ptr;
1168 static void *tcc_mallocz(unsigned long size)
1170 void *ptr;
1171 ptr = tcc_malloc(size);
1172 memset(ptr, 0, size);
1173 return ptr;
1176 static inline void *tcc_realloc(void *ptr, unsigned long size)
1178 void *ptr1;
1179 #ifdef MEM_DEBUG
1180 mem_cur_size -= malloc_usable_size(ptr);
1181 #endif
1182 ptr1 = realloc(ptr, size);
1183 #ifdef MEM_DEBUG
1184 /* NOTE: count not correct if alloc error, but not critical */
1185 mem_cur_size += malloc_usable_size(ptr1);
1186 if (mem_cur_size > mem_max_size)
1187 mem_max_size = mem_cur_size;
1188 #endif
1189 return ptr1;
1192 static char *tcc_strdup(const char *str)
1194 char *ptr;
1195 ptr = tcc_malloc(strlen(str) + 1);
1196 strcpy(ptr, str);
1197 return ptr;
1200 #define free(p) use_tcc_free(p)
1201 #define malloc(s) use_tcc_malloc(s)
1202 #define realloc(p, s) use_tcc_realloc(p, s)
1204 static void dynarray_add(void ***ptab, int *nb_ptr, void *data)
1206 int nb, nb_alloc;
1207 void **pp;
1209 nb = *nb_ptr;
1210 pp = *ptab;
1211 /* every power of two we double array size */
1212 if ((nb & (nb - 1)) == 0) {
1213 if (!nb)
1214 nb_alloc = 1;
1215 else
1216 nb_alloc = nb * 2;
1217 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
1218 if (!pp)
1219 error("memory full");
1220 *ptab = pp;
1222 pp[nb++] = data;
1223 *nb_ptr = nb;
1226 static void dynarray_reset(void *pp, int *n)
1228 void **p;
1229 for (p = *(void***)pp; *n; ++p, --*n)
1230 if (*p)
1231 tcc_free(*p);
1232 tcc_free(*(void**)pp);
1233 *(void**)pp = NULL;
1236 /* symbol allocator */
1237 static Sym *__sym_malloc(void)
1239 Sym *sym_pool, *sym, *last_sym;
1240 int i;
1242 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
1243 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
1245 last_sym = sym_free_first;
1246 sym = sym_pool;
1247 for(i = 0; i < SYM_POOL_NB; i++) {
1248 sym->next = last_sym;
1249 last_sym = sym;
1250 sym++;
1252 sym_free_first = last_sym;
1253 return last_sym;
1256 static inline Sym *sym_malloc(void)
1258 Sym *sym;
1259 sym = sym_free_first;
1260 if (!sym)
1261 sym = __sym_malloc();
1262 sym_free_first = sym->next;
1263 return sym;
1266 static inline void sym_free(Sym *sym)
1268 sym->next = sym_free_first;
1269 sym_free_first = sym;
1272 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
1274 Section *sec;
1276 sec = tcc_mallocz(sizeof(Section) + strlen(name));
1277 strcpy(sec->name, name);
1278 sec->sh_type = sh_type;
1279 sec->sh_flags = sh_flags;
1280 switch(sh_type) {
1281 case SHT_HASH:
1282 case SHT_REL:
1283 case SHT_RELA:
1284 case SHT_DYNSYM:
1285 case SHT_SYMTAB:
1286 case SHT_DYNAMIC:
1287 sec->sh_addralign = 4;
1288 break;
1289 case SHT_STRTAB:
1290 sec->sh_addralign = 1;
1291 break;
1292 default:
1293 sec->sh_addralign = 32; /* default conservative alignment */
1294 break;
1297 if (sh_flags & SHF_PRIVATE) {
1298 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
1299 } else {
1300 sec->sh_num = s1->nb_sections;
1301 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
1304 return sec;
1307 static void free_section(Section *s)
1309 #ifdef TCC_TARGET_X86_64
1310 /* after tcc_relocate(), some sections share the data buffer.
1311 let's check if the data is allocated not to free the shared buffers */
1312 if (s->data_allocated)
1313 #endif
1314 tcc_free(s->data);
1317 /* realloc section and set its content to zero */
1318 static void section_realloc(Section *sec, unsigned long new_size)
1320 unsigned long size;
1321 unsigned char *data;
1323 size = sec->data_allocated;
1324 if (size == 0)
1325 size = 1;
1326 while (size < new_size)
1327 size = size * 2;
1328 data = tcc_realloc(sec->data, size);
1329 if (!data)
1330 error("memory full");
1331 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
1332 sec->data = data;
1333 sec->data_allocated = size;
1336 /* reserve at least 'size' bytes in section 'sec' from
1337 sec->data_offset. */
1338 static void *section_ptr_add(Section *sec, unsigned long size)
1340 unsigned long offset, offset1;
1342 offset = sec->data_offset;
1343 offset1 = offset + size;
1344 if (offset1 > sec->data_allocated)
1345 section_realloc(sec, offset1);
1346 sec->data_offset = offset1;
1347 return sec->data + offset;
1350 /* return a reference to a section, and create it if it does not
1351 exists */
1352 Section *find_section(TCCState *s1, const char *name)
1354 Section *sec;
1355 int i;
1356 for(i = 1; i < s1->nb_sections; i++) {
1357 sec = s1->sections[i];
1358 if (!strcmp(name, sec->name))
1359 return sec;
1361 /* sections are created as PROGBITS */
1362 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
1365 #define SECTION_ABS ((void *)1)
1367 /* update sym->c so that it points to an external symbol in section
1368 'section' with value 'value' */
1369 static void put_extern_sym2(Sym *sym, Section *section,
1370 unsigned long value, unsigned long size,
1371 int can_add_underscore)
1373 int sym_type, sym_bind, sh_num, info, other, attr;
1374 ElfW(Sym) *esym;
1375 const char *name;
1376 char buf1[256];
1378 if (section == NULL)
1379 sh_num = SHN_UNDEF;
1380 else if (section == SECTION_ABS)
1381 sh_num = SHN_ABS;
1382 else
1383 sh_num = section->sh_num;
1385 other = attr = 0;
1387 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
1388 sym_type = STT_FUNC;
1389 #ifdef TCC_TARGET_PE
1390 if (sym->type.ref)
1391 attr = sym->type.ref->r;
1392 if (FUNC_EXPORT(attr))
1393 other |= 1;
1394 if (FUNC_CALL(attr) == FUNC_STDCALL)
1395 other |= 2;
1396 #endif
1397 } else {
1398 sym_type = STT_OBJECT;
1401 if (sym->type.t & VT_STATIC)
1402 sym_bind = STB_LOCAL;
1403 else
1404 sym_bind = STB_GLOBAL;
1406 if (!sym->c) {
1407 name = get_tok_str(sym->v, NULL);
1408 #ifdef CONFIG_TCC_BCHECK
1409 if (do_bounds_check) {
1410 char buf[32];
1412 /* XXX: avoid doing that for statics ? */
1413 /* if bound checking is activated, we change some function
1414 names by adding the "__bound" prefix */
1415 switch(sym->v) {
1416 #if 0
1417 /* XXX: we rely only on malloc hooks */
1418 case TOK_malloc:
1419 case TOK_free:
1420 case TOK_realloc:
1421 case TOK_memalign:
1422 case TOK_calloc:
1423 #endif
1424 case TOK_memcpy:
1425 case TOK_memmove:
1426 case TOK_memset:
1427 case TOK_strlen:
1428 case TOK_strcpy:
1429 case TOK__alloca:
1430 strcpy(buf, "__bound_");
1431 strcat(buf, name);
1432 name = buf;
1433 break;
1436 #endif
1438 #ifdef TCC_TARGET_PE
1439 if ((other & 2) && can_add_underscore) {
1440 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
1441 name = buf1;
1442 } else
1443 #endif
1444 if (tcc_state->leading_underscore && can_add_underscore) {
1445 buf1[0] = '_';
1446 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
1447 name = buf1;
1449 info = ELFW(ST_INFO)(sym_bind, sym_type);
1450 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
1451 } else {
1452 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1453 esym->st_value = value;
1454 esym->st_size = size;
1455 esym->st_shndx = sh_num;
1456 esym->st_other |= other;
1460 static void put_extern_sym(Sym *sym, Section *section,
1461 unsigned long value, unsigned long size)
1463 put_extern_sym2(sym, section, value, size, 1);
1466 /* add a new relocation entry to symbol 'sym' in section 's' */
1467 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
1469 if (!sym->c)
1470 put_extern_sym(sym, NULL, 0, 0);
1471 /* now we can add ELF relocation info */
1472 put_elf_reloc(symtab_section, s, offset, type, sym->c);
1475 static inline int isid(int c)
1477 return (c >= 'a' && c <= 'z') ||
1478 (c >= 'A' && c <= 'Z') ||
1479 c == '_';
1482 static inline int isnum(int c)
1484 return c >= '0' && c <= '9';
1487 static inline int isoct(int c)
1489 return c >= '0' && c <= '7';
1492 static inline int toup(int c)
1494 if (c >= 'a' && c <= 'z')
1495 return c - 'a' + 'A';
1496 else
1497 return c;
1500 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
1502 int len;
1503 len = strlen(buf);
1504 vsnprintf(buf + len, buf_size - len, fmt, ap);
1507 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
1509 va_list ap;
1510 va_start(ap, fmt);
1511 strcat_vprintf(buf, buf_size, fmt, ap);
1512 va_end(ap);
1515 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
1517 char buf[2048];
1518 BufferedFile **f;
1520 buf[0] = '\0';
1521 if (file) {
1522 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
1523 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
1524 (*f)->filename, (*f)->line_num);
1525 if (file->line_num > 0) {
1526 strcat_printf(buf, sizeof(buf),
1527 "%s:%d: ", file->filename, file->line_num);
1528 } else {
1529 strcat_printf(buf, sizeof(buf),
1530 "%s: ", file->filename);
1532 } else {
1533 strcat_printf(buf, sizeof(buf),
1534 "tcc: ");
1536 if (is_warning)
1537 strcat_printf(buf, sizeof(buf), "warning: ");
1538 strcat_vprintf(buf, sizeof(buf), fmt, ap);
1540 if (!s1->error_func) {
1541 /* default case: stderr */
1542 fprintf(stderr, "%s\n", buf);
1543 } else {
1544 s1->error_func(s1->error_opaque, buf);
1546 if (!is_warning || s1->warn_error)
1547 s1->nb_errors++;
1550 #ifdef LIBTCC
1551 void tcc_set_error_func(TCCState *s, void *error_opaque,
1552 void (*error_func)(void *opaque, const char *msg))
1554 s->error_opaque = error_opaque;
1555 s->error_func = error_func;
1557 #endif
1559 /* error without aborting current compilation */
1560 void error_noabort(const char *fmt, ...)
1562 TCCState *s1 = tcc_state;
1563 va_list ap;
1565 va_start(ap, fmt);
1566 error1(s1, 0, fmt, ap);
1567 va_end(ap);
1570 void error(const char *fmt, ...)
1572 TCCState *s1 = tcc_state;
1573 va_list ap;
1575 va_start(ap, fmt);
1576 error1(s1, 0, fmt, ap);
1577 va_end(ap);
1578 /* better than nothing: in some cases, we accept to handle errors */
1579 if (s1->error_set_jmp_enabled) {
1580 longjmp(s1->error_jmp_buf, 1);
1581 } else {
1582 /* XXX: eliminate this someday */
1583 exit(1);
1587 void expect(const char *msg)
1589 error("%s expected", msg);
1592 void warning(const char *fmt, ...)
1594 TCCState *s1 = tcc_state;
1595 va_list ap;
1597 if (s1->warn_none)
1598 return;
1600 va_start(ap, fmt);
1601 error1(s1, 1, fmt, ap);
1602 va_end(ap);
1605 void skip(int c)
1607 if (tok != c)
1608 error("'%c' expected", c);
1609 next();
1612 static void test_lvalue(void)
1614 if (!(vtop->r & VT_LVAL))
1615 expect("lvalue");
1618 /* allocate a new token */
1619 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
1621 TokenSym *ts, **ptable;
1622 int i;
1624 if (tok_ident >= SYM_FIRST_ANOM)
1625 error("memory full");
1627 /* expand token table if needed */
1628 i = tok_ident - TOK_IDENT;
1629 if ((i % TOK_ALLOC_INCR) == 0) {
1630 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
1631 if (!ptable)
1632 error("memory full");
1633 table_ident = ptable;
1636 ts = tcc_malloc(sizeof(TokenSym) + len);
1637 table_ident[i] = ts;
1638 ts->tok = tok_ident++;
1639 ts->sym_define = NULL;
1640 ts->sym_label = NULL;
1641 ts->sym_struct = NULL;
1642 ts->sym_identifier = NULL;
1643 ts->len = len;
1644 ts->hash_next = NULL;
1645 memcpy(ts->str, str, len);
1646 ts->str[len] = '\0';
1647 *pts = ts;
1648 return ts;
1651 #define TOK_HASH_INIT 1
1652 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1654 /* find a token and add it if not found */
1655 static TokenSym *tok_alloc(const char *str, int len)
1657 TokenSym *ts, **pts;
1658 int i;
1659 unsigned int h;
1661 h = TOK_HASH_INIT;
1662 for(i=0;i<len;i++)
1663 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
1664 h &= (TOK_HASH_SIZE - 1);
1666 pts = &hash_ident[h];
1667 for(;;) {
1668 ts = *pts;
1669 if (!ts)
1670 break;
1671 if (ts->len == len && !memcmp(ts->str, str, len))
1672 return ts;
1673 pts = &(ts->hash_next);
1675 return tok_alloc_new(pts, str, len);
1678 /* CString handling */
1680 static void cstr_realloc(CString *cstr, int new_size)
1682 int size;
1683 void *data;
1685 size = cstr->size_allocated;
1686 if (size == 0)
1687 size = 8; /* no need to allocate a too small first string */
1688 while (size < new_size)
1689 size = size * 2;
1690 data = tcc_realloc(cstr->data_allocated, size);
1691 if (!data)
1692 error("memory full");
1693 cstr->data_allocated = data;
1694 cstr->size_allocated = size;
1695 cstr->data = data;
1698 /* add a byte */
1699 static inline void cstr_ccat(CString *cstr, int ch)
1701 int size;
1702 size = cstr->size + 1;
1703 if (size > cstr->size_allocated)
1704 cstr_realloc(cstr, size);
1705 ((unsigned char *)cstr->data)[size - 1] = ch;
1706 cstr->size = size;
1709 static void cstr_cat(CString *cstr, const char *str)
1711 int c;
1712 for(;;) {
1713 c = *str;
1714 if (c == '\0')
1715 break;
1716 cstr_ccat(cstr, c);
1717 str++;
1721 /* add a wide char */
1722 static void cstr_wccat(CString *cstr, int ch)
1724 int size;
1725 size = cstr->size + sizeof(nwchar_t);
1726 if (size > cstr->size_allocated)
1727 cstr_realloc(cstr, size);
1728 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1729 cstr->size = size;
1732 static void cstr_new(CString *cstr)
1734 memset(cstr, 0, sizeof(CString));
1737 /* free string and reset it to NULL */
1738 static void cstr_free(CString *cstr)
1740 tcc_free(cstr->data_allocated);
1741 cstr_new(cstr);
1744 #define cstr_reset(cstr) cstr_free(cstr)
1746 /* XXX: unicode ? */
1747 static void add_char(CString *cstr, int c)
1749 if (c == '\'' || c == '\"' || c == '\\') {
1750 /* XXX: could be more precise if char or string */
1751 cstr_ccat(cstr, '\\');
1753 if (c >= 32 && c <= 126) {
1754 cstr_ccat(cstr, c);
1755 } else {
1756 cstr_ccat(cstr, '\\');
1757 if (c == '\n') {
1758 cstr_ccat(cstr, 'n');
1759 } else {
1760 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1761 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1762 cstr_ccat(cstr, '0' + (c & 7));
1767 /* XXX: buffer overflow */
1768 /* XXX: float tokens */
1769 char *get_tok_str(int v, CValue *cv)
1771 static char buf[STRING_MAX_SIZE + 1];
1772 static CString cstr_buf;
1773 CString *cstr;
1774 unsigned char *q;
1775 char *p;
1776 int i, len;
1778 /* NOTE: to go faster, we give a fixed buffer for small strings */
1779 cstr_reset(&cstr_buf);
1780 cstr_buf.data = buf;
1781 cstr_buf.size_allocated = sizeof(buf);
1782 p = buf;
1784 switch(v) {
1785 case TOK_CINT:
1786 case TOK_CUINT:
1787 /* XXX: not quite exact, but only useful for testing */
1788 sprintf(p, "%u", cv->ui);
1789 break;
1790 case TOK_CLLONG:
1791 case TOK_CULLONG:
1792 /* XXX: not quite exact, but only useful for testing */
1793 sprintf(p, "%Lu", cv->ull);
1794 break;
1795 case TOK_LCHAR:
1796 cstr_ccat(&cstr_buf, 'L');
1797 case TOK_CCHAR:
1798 cstr_ccat(&cstr_buf, '\'');
1799 add_char(&cstr_buf, cv->i);
1800 cstr_ccat(&cstr_buf, '\'');
1801 cstr_ccat(&cstr_buf, '\0');
1802 break;
1803 case TOK_PPNUM:
1804 cstr = cv->cstr;
1805 len = cstr->size - 1;
1806 for(i=0;i<len;i++)
1807 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1808 cstr_ccat(&cstr_buf, '\0');
1809 break;
1810 case TOK_LSTR:
1811 cstr_ccat(&cstr_buf, 'L');
1812 case TOK_STR:
1813 cstr = cv->cstr;
1814 cstr_ccat(&cstr_buf, '\"');
1815 if (v == TOK_STR) {
1816 len = cstr->size - 1;
1817 for(i=0;i<len;i++)
1818 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1819 } else {
1820 len = (cstr->size / sizeof(nwchar_t)) - 1;
1821 for(i=0;i<len;i++)
1822 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
1824 cstr_ccat(&cstr_buf, '\"');
1825 cstr_ccat(&cstr_buf, '\0');
1826 break;
1827 case TOK_LT:
1828 v = '<';
1829 goto addv;
1830 case TOK_GT:
1831 v = '>';
1832 goto addv;
1833 case TOK_DOTS:
1834 return strcpy(p, "...");
1835 case TOK_A_SHL:
1836 return strcpy(p, "<<=");
1837 case TOK_A_SAR:
1838 return strcpy(p, ">>=");
1839 default:
1840 if (v < TOK_IDENT) {
1841 /* search in two bytes table */
1842 q = tok_two_chars;
1843 while (*q) {
1844 if (q[2] == v) {
1845 *p++ = q[0];
1846 *p++ = q[1];
1847 *p = '\0';
1848 return buf;
1850 q += 3;
1852 addv:
1853 *p++ = v;
1854 *p = '\0';
1855 } else if (v < tok_ident) {
1856 return table_ident[v - TOK_IDENT]->str;
1857 } else if (v >= SYM_FIRST_ANOM) {
1858 /* special name for anonymous symbol */
1859 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
1860 } else {
1861 /* should never happen */
1862 return NULL;
1864 break;
1866 return cstr_buf.data;
1869 /* push, without hashing */
1870 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1872 Sym *s;
1873 s = sym_malloc();
1874 s->v = v;
1875 s->type.t = t;
1876 s->c = c;
1877 s->next = NULL;
1878 /* add in stack */
1879 s->prev = *ps;
1880 *ps = s;
1881 return s;
1884 /* find a symbol and return its associated structure. 's' is the top
1885 of the symbol stack */
1886 static Sym *sym_find2(Sym *s, int v)
1888 while (s) {
1889 if (s->v == v)
1890 return s;
1891 s = s->prev;
1893 return NULL;
1896 /* structure lookup */
1897 static inline Sym *struct_find(int v)
1899 v -= TOK_IDENT;
1900 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1901 return NULL;
1902 return table_ident[v]->sym_struct;
1905 /* find an identifier */
1906 static inline Sym *sym_find(int v)
1908 v -= TOK_IDENT;
1909 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1910 return NULL;
1911 return table_ident[v]->sym_identifier;
1914 /* push a given symbol on the symbol stack */
1915 static Sym *sym_push(int v, CType *type, int r, int c)
1917 Sym *s, **ps;
1918 TokenSym *ts;
1920 if (local_stack)
1921 ps = &local_stack;
1922 else
1923 ps = &global_stack;
1924 s = sym_push2(ps, v, type->t, c);
1925 s->type.ref = type->ref;
1926 s->r = r;
1927 /* don't record fields or anonymous symbols */
1928 /* XXX: simplify */
1929 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1930 /* record symbol in token array */
1931 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1932 if (v & SYM_STRUCT)
1933 ps = &ts->sym_struct;
1934 else
1935 ps = &ts->sym_identifier;
1936 s->prev_tok = *ps;
1937 *ps = s;
1939 return s;
1942 /* push a global identifier */
1943 static Sym *global_identifier_push(int v, int t, int c)
1945 Sym *s, **ps;
1946 s = sym_push2(&global_stack, v, t, c);
1947 /* don't record anonymous symbol */
1948 if (v < SYM_FIRST_ANOM) {
1949 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1950 /* modify the top most local identifier, so that
1951 sym_identifier will point to 's' when popped */
1952 while (*ps != NULL)
1953 ps = &(*ps)->prev_tok;
1954 s->prev_tok = NULL;
1955 *ps = s;
1957 return s;
1960 /* pop symbols until top reaches 'b' */
1961 static void sym_pop(Sym **ptop, Sym *b)
1963 Sym *s, *ss, **ps;
1964 TokenSym *ts;
1965 int v;
1967 s = *ptop;
1968 while(s != b) {
1969 ss = s->prev;
1970 v = s->v;
1971 /* remove symbol in token array */
1972 /* XXX: simplify */
1973 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1974 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1975 if (v & SYM_STRUCT)
1976 ps = &ts->sym_struct;
1977 else
1978 ps = &ts->sym_identifier;
1979 *ps = s->prev_tok;
1981 sym_free(s);
1982 s = ss;
1984 *ptop = b;
1987 /* I/O layer */
1989 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1991 int fd;
1992 BufferedFile *bf;
1994 if (strcmp(filename, "-") == 0)
1995 fd = 0, filename = "stdin";
1996 else
1997 fd = open(filename, O_RDONLY | O_BINARY);
1998 if ((verbose == 2 && fd >= 0) || verbose == 3)
1999 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
2000 (s1->include_stack_ptr - s1->include_stack), "", filename);
2001 if (fd < 0)
2002 return NULL;
2003 bf = tcc_malloc(sizeof(BufferedFile));
2004 bf->fd = fd;
2005 bf->buf_ptr = bf->buffer;
2006 bf->buf_end = bf->buffer;
2007 bf->buffer[0] = CH_EOB; /* put eob symbol */
2008 pstrcpy(bf->filename, sizeof(bf->filename), filename);
2009 #ifdef _WIN32
2010 normalize_slashes(bf->filename);
2011 #endif
2012 bf->line_num = 1;
2013 bf->ifndef_macro = 0;
2014 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
2015 // printf("opening '%s'\n", filename);
2016 return bf;
2019 void tcc_close(BufferedFile *bf)
2021 total_lines += bf->line_num;
2022 close(bf->fd);
2023 tcc_free(bf);
2026 /* fill input buffer and peek next char */
2027 static int tcc_peekc_slow(BufferedFile *bf)
2029 int len;
2030 /* only tries to read if really end of buffer */
2031 if (bf->buf_ptr >= bf->buf_end) {
2032 if (bf->fd != -1) {
2033 #if defined(PARSE_DEBUG)
2034 len = 8;
2035 #else
2036 len = IO_BUF_SIZE;
2037 #endif
2038 len = read(bf->fd, bf->buffer, len);
2039 if (len < 0)
2040 len = 0;
2041 } else {
2042 len = 0;
2044 total_bytes += len;
2045 bf->buf_ptr = bf->buffer;
2046 bf->buf_end = bf->buffer + len;
2047 *bf->buf_end = CH_EOB;
2049 if (bf->buf_ptr < bf->buf_end) {
2050 return bf->buf_ptr[0];
2051 } else {
2052 bf->buf_ptr = bf->buf_end;
2053 return CH_EOF;
2057 /* return the current character, handling end of block if necessary
2058 (but not stray) */
2059 static int handle_eob(void)
2061 return tcc_peekc_slow(file);
2064 /* read next char from current input file and handle end of input buffer */
2065 static inline void inp(void)
2067 ch = *(++(file->buf_ptr));
2068 /* end of buffer/file handling */
2069 if (ch == CH_EOB)
2070 ch = handle_eob();
2073 /* handle '\[\r]\n' */
2074 static int handle_stray_noerror(void)
2076 while (ch == '\\') {
2077 inp();
2078 if (ch == '\n') {
2079 file->line_num++;
2080 inp();
2081 } else if (ch == '\r') {
2082 inp();
2083 if (ch != '\n')
2084 goto fail;
2085 file->line_num++;
2086 inp();
2087 } else {
2088 fail:
2089 return 1;
2092 return 0;
2095 static void handle_stray(void)
2097 if (handle_stray_noerror())
2098 error("stray '\\' in program");
2101 /* skip the stray and handle the \\n case. Output an error if
2102 incorrect char after the stray */
2103 static int handle_stray1(uint8_t *p)
2105 int c;
2107 if (p >= file->buf_end) {
2108 file->buf_ptr = p;
2109 c = handle_eob();
2110 p = file->buf_ptr;
2111 if (c == '\\')
2112 goto parse_stray;
2113 } else {
2114 parse_stray:
2115 file->buf_ptr = p;
2116 ch = *p;
2117 handle_stray();
2118 p = file->buf_ptr;
2119 c = *p;
2121 return c;
2124 /* handle just the EOB case, but not stray */
2125 #define PEEKC_EOB(c, p)\
2127 p++;\
2128 c = *p;\
2129 if (c == '\\') {\
2130 file->buf_ptr = p;\
2131 c = handle_eob();\
2132 p = file->buf_ptr;\
2136 /* handle the complicated stray case */
2137 #define PEEKC(c, p)\
2139 p++;\
2140 c = *p;\
2141 if (c == '\\') {\
2142 c = handle_stray1(p);\
2143 p = file->buf_ptr;\
2147 /* input with '\[\r]\n' handling. Note that this function cannot
2148 handle other characters after '\', so you cannot call it inside
2149 strings or comments */
2150 static void minp(void)
2152 inp();
2153 if (ch == '\\')
2154 handle_stray();
2158 /* single line C++ comments */
2159 static uint8_t *parse_line_comment(uint8_t *p)
2161 int c;
2163 p++;
2164 for(;;) {
2165 c = *p;
2166 redo:
2167 if (c == '\n' || c == CH_EOF) {
2168 break;
2169 } else if (c == '\\') {
2170 file->buf_ptr = p;
2171 c = handle_eob();
2172 p = file->buf_ptr;
2173 if (c == '\\') {
2174 PEEKC_EOB(c, p);
2175 if (c == '\n') {
2176 file->line_num++;
2177 PEEKC_EOB(c, p);
2178 } else if (c == '\r') {
2179 PEEKC_EOB(c, p);
2180 if (c == '\n') {
2181 file->line_num++;
2182 PEEKC_EOB(c, p);
2185 } else {
2186 goto redo;
2188 } else {
2189 p++;
2192 return p;
2195 /* C comments */
2196 static uint8_t *parse_comment(uint8_t *p)
2198 int c;
2200 p++;
2201 for(;;) {
2202 /* fast skip loop */
2203 for(;;) {
2204 c = *p;
2205 if (c == '\n' || c == '*' || c == '\\')
2206 break;
2207 p++;
2208 c = *p;
2209 if (c == '\n' || c == '*' || c == '\\')
2210 break;
2211 p++;
2213 /* now we can handle all the cases */
2214 if (c == '\n') {
2215 file->line_num++;
2216 p++;
2217 } else if (c == '*') {
2218 p++;
2219 for(;;) {
2220 c = *p;
2221 if (c == '*') {
2222 p++;
2223 } else if (c == '/') {
2224 goto end_of_comment;
2225 } else if (c == '\\') {
2226 file->buf_ptr = p;
2227 c = handle_eob();
2228 p = file->buf_ptr;
2229 if (c == '\\') {
2230 /* skip '\[\r]\n', otherwise just skip the stray */
2231 while (c == '\\') {
2232 PEEKC_EOB(c, p);
2233 if (c == '\n') {
2234 file->line_num++;
2235 PEEKC_EOB(c, p);
2236 } else if (c == '\r') {
2237 PEEKC_EOB(c, p);
2238 if (c == '\n') {
2239 file->line_num++;
2240 PEEKC_EOB(c, p);
2242 } else {
2243 goto after_star;
2247 } else {
2248 break;
2251 after_star: ;
2252 } else {
2253 /* stray, eob or eof */
2254 file->buf_ptr = p;
2255 c = handle_eob();
2256 p = file->buf_ptr;
2257 if (c == CH_EOF) {
2258 error("unexpected end of file in comment");
2259 } else if (c == '\\') {
2260 p++;
2264 end_of_comment:
2265 p++;
2266 return p;
2269 #define cinp minp
2271 /* space exlcuding newline */
2272 static inline int is_space(int ch)
2274 return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
2277 static inline void skip_spaces(void)
2279 while (is_space(ch))
2280 cinp();
2283 /* parse a string without interpreting escapes */
2284 static uint8_t *parse_pp_string(uint8_t *p,
2285 int sep, CString *str)
2287 int c;
2288 p++;
2289 for(;;) {
2290 c = *p;
2291 if (c == sep) {
2292 break;
2293 } else if (c == '\\') {
2294 file->buf_ptr = p;
2295 c = handle_eob();
2296 p = file->buf_ptr;
2297 if (c == CH_EOF) {
2298 unterminated_string:
2299 /* XXX: indicate line number of start of string */
2300 error("missing terminating %c character", sep);
2301 } else if (c == '\\') {
2302 /* escape : just skip \[\r]\n */
2303 PEEKC_EOB(c, p);
2304 if (c == '\n') {
2305 file->line_num++;
2306 p++;
2307 } else if (c == '\r') {
2308 PEEKC_EOB(c, p);
2309 if (c != '\n')
2310 expect("'\n' after '\r'");
2311 file->line_num++;
2312 p++;
2313 } else if (c == CH_EOF) {
2314 goto unterminated_string;
2315 } else {
2316 if (str) {
2317 cstr_ccat(str, '\\');
2318 cstr_ccat(str, c);
2320 p++;
2323 } else if (c == '\n') {
2324 file->line_num++;
2325 goto add_char;
2326 } else if (c == '\r') {
2327 PEEKC_EOB(c, p);
2328 if (c != '\n') {
2329 if (str)
2330 cstr_ccat(str, '\r');
2331 } else {
2332 file->line_num++;
2333 goto add_char;
2335 } else {
2336 add_char:
2337 if (str)
2338 cstr_ccat(str, c);
2339 p++;
2342 p++;
2343 return p;
2346 /* skip block of text until #else, #elif or #endif. skip also pairs of
2347 #if/#endif */
2348 void preprocess_skip(void)
2350 int a, start_of_line, c, in_warn_or_error;
2351 uint8_t *p;
2353 p = file->buf_ptr;
2354 a = 0;
2355 redo_start:
2356 start_of_line = 1;
2357 in_warn_or_error = 0;
2358 for(;;) {
2359 redo_no_start:
2360 c = *p;
2361 switch(c) {
2362 case ' ':
2363 case '\t':
2364 case '\f':
2365 case '\v':
2366 case '\r':
2367 p++;
2368 goto redo_no_start;
2369 case '\n':
2370 file->line_num++;
2371 p++;
2372 goto redo_start;
2373 case '\\':
2374 file->buf_ptr = p;
2375 c = handle_eob();
2376 if (c == CH_EOF) {
2377 expect("#endif");
2378 } else if (c == '\\') {
2379 ch = file->buf_ptr[0];
2380 handle_stray_noerror();
2382 p = file->buf_ptr;
2383 goto redo_no_start;
2384 /* skip strings */
2385 case '\"':
2386 case '\'':
2387 if (in_warn_or_error)
2388 goto _default;
2389 p = parse_pp_string(p, c, NULL);
2390 break;
2391 /* skip comments */
2392 case '/':
2393 if (in_warn_or_error)
2394 goto _default;
2395 file->buf_ptr = p;
2396 ch = *p;
2397 minp();
2398 p = file->buf_ptr;
2399 if (ch == '*') {
2400 p = parse_comment(p);
2401 } else if (ch == '/') {
2402 p = parse_line_comment(p);
2404 break;
2405 case '#':
2406 p++;
2407 if (start_of_line) {
2408 file->buf_ptr = p;
2409 next_nomacro();
2410 p = file->buf_ptr;
2411 if (a == 0 &&
2412 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
2413 goto the_end;
2414 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
2415 a++;
2416 else if (tok == TOK_ENDIF)
2417 a--;
2418 else if( tok == TOK_ERROR || tok == TOK_WARNING)
2419 in_warn_or_error = 1;
2421 break;
2422 _default:
2423 default:
2424 p++;
2425 break;
2427 start_of_line = 0;
2429 the_end: ;
2430 file->buf_ptr = p;
2433 /* ParseState handling */
2435 /* XXX: currently, no include file info is stored. Thus, we cannot display
2436 accurate messages if the function or data definition spans multiple
2437 files */
2439 /* save current parse state in 's' */
2440 void save_parse_state(ParseState *s)
2442 s->line_num = file->line_num;
2443 s->macro_ptr = macro_ptr;
2444 s->tok = tok;
2445 s->tokc = tokc;
2448 /* restore parse state from 's' */
2449 void restore_parse_state(ParseState *s)
2451 file->line_num = s->line_num;
2452 macro_ptr = s->macro_ptr;
2453 tok = s->tok;
2454 tokc = s->tokc;
2457 /* return the number of additional 'ints' necessary to store the
2458 token */
2459 static inline int tok_ext_size(int t)
2461 switch(t) {
2462 /* 4 bytes */
2463 case TOK_CINT:
2464 case TOK_CUINT:
2465 case TOK_CCHAR:
2466 case TOK_LCHAR:
2467 case TOK_CFLOAT:
2468 case TOK_LINENUM:
2469 return 1;
2470 case TOK_STR:
2471 case TOK_LSTR:
2472 case TOK_PPNUM:
2473 error("unsupported token");
2474 return 1;
2475 case TOK_CDOUBLE:
2476 case TOK_CLLONG:
2477 case TOK_CULLONG:
2478 return 2;
2479 case TOK_CLDOUBLE:
2480 return LDOUBLE_SIZE / 4;
2481 default:
2482 return 0;
2486 /* token string handling */
2488 static inline void tok_str_new(TokenString *s)
2490 s->str = NULL;
2491 s->len = 0;
2492 s->allocated_len = 0;
2493 s->last_line_num = -1;
2496 static void tok_str_free(int *str)
2498 tcc_free(str);
2501 static int *tok_str_realloc(TokenString *s)
2503 int *str, len;
2505 if (s->allocated_len == 0) {
2506 len = 8;
2507 } else {
2508 len = s->allocated_len * 2;
2510 str = tcc_realloc(s->str, len * sizeof(int));
2511 if (!str)
2512 error("memory full");
2513 s->allocated_len = len;
2514 s->str = str;
2515 return str;
2518 static void tok_str_add(TokenString *s, int t)
2520 int len, *str;
2522 len = s->len;
2523 str = s->str;
2524 if (len >= s->allocated_len)
2525 str = tok_str_realloc(s);
2526 str[len++] = t;
2527 s->len = len;
2530 static void tok_str_add2(TokenString *s, int t, CValue *cv)
2532 int len, *str;
2534 len = s->len;
2535 str = s->str;
2537 /* allocate space for worst case */
2538 if (len + TOK_MAX_SIZE > s->allocated_len)
2539 str = tok_str_realloc(s);
2540 str[len++] = t;
2541 switch(t) {
2542 case TOK_CINT:
2543 case TOK_CUINT:
2544 case TOK_CCHAR:
2545 case TOK_LCHAR:
2546 case TOK_CFLOAT:
2547 case TOK_LINENUM:
2548 str[len++] = cv->tab[0];
2549 break;
2550 case TOK_PPNUM:
2551 case TOK_STR:
2552 case TOK_LSTR:
2554 int nb_words;
2555 CString *cstr;
2557 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
2558 while ((len + nb_words) > s->allocated_len)
2559 str = tok_str_realloc(s);
2560 cstr = (CString *)(str + len);
2561 cstr->data = NULL;
2562 cstr->size = cv->cstr->size;
2563 cstr->data_allocated = NULL;
2564 cstr->size_allocated = cstr->size;
2565 memcpy((char *)cstr + sizeof(CString),
2566 cv->cstr->data, cstr->size);
2567 len += nb_words;
2569 break;
2570 case TOK_CDOUBLE:
2571 case TOK_CLLONG:
2572 case TOK_CULLONG:
2573 #if LDOUBLE_SIZE == 8
2574 case TOK_CLDOUBLE:
2575 #endif
2576 str[len++] = cv->tab[0];
2577 str[len++] = cv->tab[1];
2578 break;
2579 #if LDOUBLE_SIZE == 12
2580 case TOK_CLDOUBLE:
2581 str[len++] = cv->tab[0];
2582 str[len++] = cv->tab[1];
2583 str[len++] = cv->tab[2];
2584 #elif LDOUBLE_SIZE == 16
2585 case TOK_CLDOUBLE:
2586 str[len++] = cv->tab[0];
2587 str[len++] = cv->tab[1];
2588 str[len++] = cv->tab[2];
2589 str[len++] = cv->tab[3];
2590 #elif LDOUBLE_SIZE != 8
2591 #error add long double size support
2592 #endif
2593 break;
2594 default:
2595 break;
2597 s->len = len;
2600 /* add the current parse token in token string 's' */
2601 static void tok_str_add_tok(TokenString *s)
2603 CValue cval;
2605 /* save line number info */
2606 if (file->line_num != s->last_line_num) {
2607 s->last_line_num = file->line_num;
2608 cval.i = s->last_line_num;
2609 tok_str_add2(s, TOK_LINENUM, &cval);
2611 tok_str_add2(s, tok, &tokc);
2614 #if LDOUBLE_SIZE == 16
2615 #define LDOUBLE_GET(p, cv) \
2616 cv.tab[0] = p[0]; \
2617 cv.tab[1] = p[1]; \
2618 cv.tab[2] = p[2]; \
2619 cv.tab[3] = p[3];
2620 #elif LDOUBLE_SIZE == 12
2621 #define LDOUBLE_GET(p, cv) \
2622 cv.tab[0] = p[0]; \
2623 cv.tab[1] = p[1]; \
2624 cv.tab[2] = p[2];
2625 #elif LDOUBLE_SIZE == 8
2626 #define LDOUBLE_GET(p, cv) \
2627 cv.tab[0] = p[0]; \
2628 cv.tab[1] = p[1];
2629 #else
2630 #error add long double size support
2631 #endif
2634 /* get a token from an integer array and increment pointer
2635 accordingly. we code it as a macro to avoid pointer aliasing. */
2636 #define TOK_GET(t, p, cv) \
2638 t = *p++; \
2639 switch(t) { \
2640 case TOK_CINT: \
2641 case TOK_CUINT: \
2642 case TOK_CCHAR: \
2643 case TOK_LCHAR: \
2644 case TOK_CFLOAT: \
2645 case TOK_LINENUM: \
2646 cv.tab[0] = *p++; \
2647 break; \
2648 case TOK_STR: \
2649 case TOK_LSTR: \
2650 case TOK_PPNUM: \
2651 cv.cstr = (CString *)p; \
2652 cv.cstr->data = (char *)p + sizeof(CString);\
2653 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2654 break; \
2655 case TOK_CDOUBLE: \
2656 case TOK_CLLONG: \
2657 case TOK_CULLONG: \
2658 cv.tab[0] = p[0]; \
2659 cv.tab[1] = p[1]; \
2660 p += 2; \
2661 break; \
2662 case TOK_CLDOUBLE: \
2663 LDOUBLE_GET(p, cv); \
2664 p += LDOUBLE_SIZE / 4; \
2665 break; \
2666 default: \
2667 break; \
2671 /* defines handling */
2672 static inline void define_push(int v, int macro_type, int *str, Sym *first_arg)
2674 Sym *s;
2676 s = sym_push2(&define_stack, v, macro_type, (long)str);
2677 s->next = first_arg;
2678 table_ident[v - TOK_IDENT]->sym_define = s;
2681 /* undefined a define symbol. Its name is just set to zero */
2682 static void define_undef(Sym *s)
2684 int v;
2685 v = s->v;
2686 if (v >= TOK_IDENT && v < tok_ident)
2687 table_ident[v - TOK_IDENT]->sym_define = NULL;
2688 s->v = 0;
2691 static inline Sym *define_find(int v)
2693 v -= TOK_IDENT;
2694 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2695 return NULL;
2696 return table_ident[v]->sym_define;
2699 /* free define stack until top reaches 'b' */
2700 static void free_defines(Sym *b)
2702 Sym *top, *top1;
2703 int v;
2705 top = define_stack;
2706 while (top != b) {
2707 top1 = top->prev;
2708 /* do not free args or predefined defines */
2709 if (top->c)
2710 tok_str_free((int *)top->c);
2711 v = top->v;
2712 if (v >= TOK_IDENT && v < tok_ident)
2713 table_ident[v - TOK_IDENT]->sym_define = NULL;
2714 sym_free(top);
2715 top = top1;
2717 define_stack = b;
2720 /* label lookup */
2721 static Sym *label_find(int v)
2723 v -= TOK_IDENT;
2724 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2725 return NULL;
2726 return table_ident[v]->sym_label;
2729 static Sym *label_push(Sym **ptop, int v, int flags)
2731 Sym *s, **ps;
2732 s = sym_push2(ptop, v, 0, 0);
2733 s->r = flags;
2734 ps = &table_ident[v - TOK_IDENT]->sym_label;
2735 if (ptop == &global_label_stack) {
2736 /* modify the top most local identifier, so that
2737 sym_identifier will point to 's' when popped */
2738 while (*ps != NULL)
2739 ps = &(*ps)->prev_tok;
2741 s->prev_tok = *ps;
2742 *ps = s;
2743 return s;
2746 /* pop labels until element last is reached. Look if any labels are
2747 undefined. Define symbols if '&&label' was used. */
2748 static void label_pop(Sym **ptop, Sym *slast)
2750 Sym *s, *s1;
2751 for(s = *ptop; s != slast; s = s1) {
2752 s1 = s->prev;
2753 if (s->r == LABEL_DECLARED) {
2754 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
2755 } else if (s->r == LABEL_FORWARD) {
2756 error("label '%s' used but not defined",
2757 get_tok_str(s->v, NULL));
2758 } else {
2759 if (s->c) {
2760 /* define corresponding symbol. A size of
2761 1 is put. */
2762 put_extern_sym(s, cur_text_section, (long)s->next, 1);
2765 /* remove label */
2766 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
2767 sym_free(s);
2769 *ptop = slast;
2772 /* eval an expression for #if/#elif */
2773 static int expr_preprocess(void)
2775 int c, t;
2776 TokenString str;
2778 tok_str_new(&str);
2779 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2780 next(); /* do macro subst */
2781 if (tok == TOK_DEFINED) {
2782 next_nomacro();
2783 t = tok;
2784 if (t == '(')
2785 next_nomacro();
2786 c = define_find(tok) != 0;
2787 if (t == '(')
2788 next_nomacro();
2789 tok = TOK_CINT;
2790 tokc.i = c;
2791 } else if (tok >= TOK_IDENT) {
2792 /* if undefined macro */
2793 tok = TOK_CINT;
2794 tokc.i = 0;
2796 tok_str_add_tok(&str);
2798 tok_str_add(&str, -1); /* simulate end of file */
2799 tok_str_add(&str, 0);
2800 /* now evaluate C constant expression */
2801 macro_ptr = str.str;
2802 next();
2803 c = expr_const();
2804 macro_ptr = NULL;
2805 tok_str_free(str.str);
2806 return c != 0;
2809 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2810 static void tok_print(int *str)
2812 int t;
2813 CValue cval;
2815 while (1) {
2816 TOK_GET(t, str, cval);
2817 if (!t)
2818 break;
2819 printf(" %s", get_tok_str(t, &cval));
2821 printf("\n");
2823 #endif
2825 /* parse after #define */
2826 static void parse_define(void)
2828 Sym *s, *first, **ps;
2829 int v, t, varg, is_vaargs, c;
2830 TokenString str;
2832 v = tok;
2833 if (v < TOK_IDENT)
2834 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
2835 /* XXX: should check if same macro (ANSI) */
2836 first = NULL;
2837 t = MACRO_OBJ;
2838 /* '(' must be just after macro definition for MACRO_FUNC */
2839 c = file->buf_ptr[0];
2840 if (c == '\\')
2841 c = handle_stray1(file->buf_ptr);
2842 if (c == '(') {
2843 next_nomacro();
2844 next_nomacro();
2845 ps = &first;
2846 while (tok != ')') {
2847 varg = tok;
2848 next_nomacro();
2849 is_vaargs = 0;
2850 if (varg == TOK_DOTS) {
2851 varg = TOK___VA_ARGS__;
2852 is_vaargs = 1;
2853 } else if (tok == TOK_DOTS && gnu_ext) {
2854 is_vaargs = 1;
2855 next_nomacro();
2857 if (varg < TOK_IDENT)
2858 error("badly punctuated parameter list");
2859 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
2860 *ps = s;
2861 ps = &s->next;
2862 if (tok != ',')
2863 break;
2864 next_nomacro();
2866 t = MACRO_FUNC;
2868 tok_str_new(&str);
2869 next_nomacro();
2870 /* EOF testing necessary for '-D' handling */
2871 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2872 tok_str_add2(&str, tok, &tokc);
2873 next_nomacro();
2875 tok_str_add(&str, 0);
2876 #ifdef PP_DEBUG
2877 printf("define %s %d: ", get_tok_str(v, NULL), t);
2878 tok_print(str.str);
2879 #endif
2880 define_push(v, t, str.str, first);
2883 static inline int hash_cached_include(int type, const char *filename)
2885 const unsigned char *s;
2886 unsigned int h;
2888 h = TOK_HASH_INIT;
2889 h = TOK_HASH_FUNC(h, type);
2890 s = filename;
2891 while (*s) {
2892 h = TOK_HASH_FUNC(h, *s);
2893 s++;
2895 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
2896 return h;
2899 /* XXX: use a token or a hash table to accelerate matching ? */
2900 static CachedInclude *search_cached_include(TCCState *s1,
2901 int type, const char *filename)
2903 CachedInclude *e;
2904 int i, h;
2905 h = hash_cached_include(type, filename);
2906 i = s1->cached_includes_hash[h];
2907 for(;;) {
2908 if (i == 0)
2909 break;
2910 e = s1->cached_includes[i - 1];
2911 if (e->type == type && !strcmp(e->filename, filename))
2912 return e;
2913 i = e->hash_next;
2915 return NULL;
2918 static inline void add_cached_include(TCCState *s1, int type,
2919 const char *filename, int ifndef_macro)
2921 CachedInclude *e;
2922 int h;
2924 if (search_cached_include(s1, type, filename))
2925 return;
2926 #ifdef INC_DEBUG
2927 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
2928 #endif
2929 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
2930 if (!e)
2931 return;
2932 e->type = type;
2933 strcpy(e->filename, filename);
2934 e->ifndef_macro = ifndef_macro;
2935 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
2936 /* add in hash table */
2937 h = hash_cached_include(type, filename);
2938 e->hash_next = s1->cached_includes_hash[h];
2939 s1->cached_includes_hash[h] = s1->nb_cached_includes;
2942 static void pragma_parse(TCCState *s1)
2944 int val;
2946 next();
2947 if (tok == TOK_pack) {
2949 This may be:
2950 #pragma pack(1) // set
2951 #pragma pack() // reset to default
2952 #pragma pack(push,1) // push & set
2953 #pragma pack(pop) // restore previous
2955 next();
2956 skip('(');
2957 if (tok == TOK_ASM_pop) {
2958 next();
2959 if (s1->pack_stack_ptr <= s1->pack_stack) {
2960 stk_error:
2961 error("out of pack stack");
2963 s1->pack_stack_ptr--;
2964 } else {
2965 val = 0;
2966 if (tok != ')') {
2967 if (tok == TOK_ASM_push) {
2968 next();
2969 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
2970 goto stk_error;
2971 s1->pack_stack_ptr++;
2972 skip(',');
2974 if (tok != TOK_CINT) {
2975 pack_error:
2976 error("invalid pack pragma");
2978 val = tokc.i;
2979 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
2980 goto pack_error;
2981 next();
2983 *s1->pack_stack_ptr = val;
2984 skip(')');
2989 /* is_bof is true if first non space token at beginning of file */
2990 static void preprocess(int is_bof)
2992 TCCState *s1 = tcc_state;
2993 int size, i, c, n, saved_parse_flags;
2994 char buf[1024], *q;
2995 char buf1[1024];
2996 BufferedFile *f;
2997 Sym *s;
2998 CachedInclude *e;
3000 saved_parse_flags = parse_flags;
3001 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
3002 PARSE_FLAG_LINEFEED;
3003 next_nomacro();
3004 redo:
3005 switch(tok) {
3006 case TOK_DEFINE:
3007 next_nomacro();
3008 parse_define();
3009 break;
3010 case TOK_UNDEF:
3011 next_nomacro();
3012 s = define_find(tok);
3013 /* undefine symbol by putting an invalid name */
3014 if (s)
3015 define_undef(s);
3016 break;
3017 case TOK_INCLUDE:
3018 case TOK_INCLUDE_NEXT:
3019 ch = file->buf_ptr[0];
3020 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3021 skip_spaces();
3022 if (ch == '<') {
3023 c = '>';
3024 goto read_name;
3025 } else if (ch == '\"') {
3026 c = ch;
3027 read_name:
3028 inp();
3029 q = buf;
3030 while (ch != c && ch != '\n' && ch != CH_EOF) {
3031 if ((q - buf) < sizeof(buf) - 1)
3032 *q++ = ch;
3033 if (ch == '\\') {
3034 if (handle_stray_noerror() == 0)
3035 --q;
3036 } else
3037 inp();
3039 *q = '\0';
3040 minp();
3041 #if 0
3042 /* eat all spaces and comments after include */
3043 /* XXX: slightly incorrect */
3044 while (ch1 != '\n' && ch1 != CH_EOF)
3045 inp();
3046 #endif
3047 } else {
3048 /* computed #include : either we have only strings or
3049 we have anything enclosed in '<>' */
3050 next();
3051 buf[0] = '\0';
3052 if (tok == TOK_STR) {
3053 while (tok != TOK_LINEFEED) {
3054 if (tok != TOK_STR) {
3055 include_syntax:
3056 error("'#include' expects \"FILENAME\" or <FILENAME>");
3058 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
3059 next();
3061 c = '\"';
3062 } else {
3063 int len;
3064 while (tok != TOK_LINEFEED) {
3065 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
3066 next();
3068 len = strlen(buf);
3069 /* check syntax and remove '<>' */
3070 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
3071 goto include_syntax;
3072 memmove(buf, buf + 1, len - 2);
3073 buf[len - 2] = '\0';
3074 c = '>';
3078 e = search_cached_include(s1, c, buf);
3079 if (e && define_find(e->ifndef_macro)) {
3080 /* no need to parse the include because the 'ifndef macro'
3081 is defined */
3082 #ifdef INC_DEBUG
3083 printf("%s: skipping %s\n", file->filename, buf);
3084 #endif
3085 } else {
3086 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
3087 error("#include recursion too deep");
3088 /* push current file in stack */
3089 /* XXX: fix current line init */
3090 *s1->include_stack_ptr++ = file;
3092 /* check absolute include path */
3093 if (IS_ABSPATH(buf)) {
3094 f = tcc_open(s1, buf);
3095 if (f)
3096 goto found;
3098 if (c == '\"') {
3099 /* first search in current dir if "header.h" */
3100 size = tcc_basename(file->filename) - file->filename;
3101 if (size > sizeof(buf1) - 1)
3102 size = sizeof(buf1) - 1;
3103 memcpy(buf1, file->filename, size);
3104 buf1[size] = '\0';
3105 pstrcat(buf1, sizeof(buf1), buf);
3106 f = tcc_open(s1, buf1);
3107 if (f) {
3108 if (tok == TOK_INCLUDE_NEXT)
3109 tok = TOK_INCLUDE;
3110 else
3111 goto found;
3114 /* now search in all the include paths */
3115 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
3116 for(i = 0; i < n; i++) {
3117 const char *path;
3118 if (i < s1->nb_include_paths)
3119 path = s1->include_paths[i];
3120 else
3121 path = s1->sysinclude_paths[i - s1->nb_include_paths];
3122 pstrcpy(buf1, sizeof(buf1), path);
3123 pstrcat(buf1, sizeof(buf1), "/");
3124 pstrcat(buf1, sizeof(buf1), buf);
3125 f = tcc_open(s1, buf1);
3126 if (f) {
3127 if (tok == TOK_INCLUDE_NEXT)
3128 tok = TOK_INCLUDE;
3129 else
3130 goto found;
3133 --s1->include_stack_ptr;
3134 error("include file '%s' not found", buf);
3135 break;
3136 found:
3137 #ifdef INC_DEBUG
3138 printf("%s: including %s\n", file->filename, buf1);
3139 #endif
3140 f->inc_type = c;
3141 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf);
3142 file = f;
3143 /* add include file debug info */
3144 if (do_debug) {
3145 put_stabs(file->filename, N_BINCL, 0, 0, 0);
3147 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
3148 ch = file->buf_ptr[0];
3149 goto the_end;
3151 break;
3152 case TOK_IFNDEF:
3153 c = 1;
3154 goto do_ifdef;
3155 case TOK_IF:
3156 c = expr_preprocess();
3157 goto do_if;
3158 case TOK_IFDEF:
3159 c = 0;
3160 do_ifdef:
3161 next_nomacro();
3162 if (tok < TOK_IDENT)
3163 error("invalid argument for '#if%sdef'", c ? "n" : "");
3164 if (is_bof) {
3165 if (c) {
3166 #ifdef INC_DEBUG
3167 printf("#ifndef %s\n", get_tok_str(tok, NULL));
3168 #endif
3169 file->ifndef_macro = tok;
3172 c = (define_find(tok) != 0) ^ c;
3173 do_if:
3174 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
3175 error("memory full");
3176 *s1->ifdef_stack_ptr++ = c;
3177 goto test_skip;
3178 case TOK_ELSE:
3179 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3180 error("#else without matching #if");
3181 if (s1->ifdef_stack_ptr[-1] & 2)
3182 error("#else after #else");
3183 c = (s1->ifdef_stack_ptr[-1] ^= 3);
3184 goto test_skip;
3185 case TOK_ELIF:
3186 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3187 error("#elif without matching #if");
3188 c = s1->ifdef_stack_ptr[-1];
3189 if (c > 1)
3190 error("#elif after #else");
3191 /* last #if/#elif expression was true: we skip */
3192 if (c == 1)
3193 goto skip;
3194 c = expr_preprocess();
3195 s1->ifdef_stack_ptr[-1] = c;
3196 test_skip:
3197 if (!(c & 1)) {
3198 skip:
3199 preprocess_skip();
3200 is_bof = 0;
3201 goto redo;
3203 break;
3204 case TOK_ENDIF:
3205 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
3206 error("#endif without matching #if");
3207 s1->ifdef_stack_ptr--;
3208 /* '#ifndef macro' was at the start of file. Now we check if
3209 an '#endif' is exactly at the end of file */
3210 if (file->ifndef_macro &&
3211 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
3212 file->ifndef_macro_saved = file->ifndef_macro;
3213 /* need to set to zero to avoid false matches if another
3214 #ifndef at middle of file */
3215 file->ifndef_macro = 0;
3216 while (tok != TOK_LINEFEED)
3217 next_nomacro();
3218 tok_flags |= TOK_FLAG_ENDIF;
3219 goto the_end;
3221 break;
3222 case TOK_LINE:
3223 next();
3224 if (tok != TOK_CINT)
3225 error("#line");
3226 file->line_num = tokc.i - 1; /* the line number will be incremented after */
3227 next();
3228 if (tok != TOK_LINEFEED) {
3229 if (tok != TOK_STR)
3230 error("#line");
3231 pstrcpy(file->filename, sizeof(file->filename),
3232 (char *)tokc.cstr->data);
3234 break;
3235 case TOK_ERROR:
3236 case TOK_WARNING:
3237 c = tok;
3238 ch = file->buf_ptr[0];
3239 skip_spaces();
3240 q = buf;
3241 while (ch != '\n' && ch != CH_EOF) {
3242 if ((q - buf) < sizeof(buf) - 1)
3243 *q++ = ch;
3244 if (ch == '\\') {
3245 if (handle_stray_noerror() == 0)
3246 --q;
3247 } else
3248 inp();
3250 *q = '\0';
3251 if (c == TOK_ERROR)
3252 error("#error %s", buf);
3253 else
3254 warning("#warning %s", buf);
3255 break;
3256 case TOK_PRAGMA:
3257 pragma_parse(s1);
3258 break;
3259 default:
3260 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
3261 /* '!' is ignored to allow C scripts. numbers are ignored
3262 to emulate cpp behaviour */
3263 } else {
3264 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
3265 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
3267 break;
3269 /* ignore other preprocess commands or #! for C scripts */
3270 while (tok != TOK_LINEFEED)
3271 next_nomacro();
3272 the_end:
3273 parse_flags = saved_parse_flags;
3276 /* evaluate escape codes in a string. */
3277 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
3279 int c, n;
3280 const uint8_t *p;
3282 p = buf;
3283 for(;;) {
3284 c = *p;
3285 if (c == '\0')
3286 break;
3287 if (c == '\\') {
3288 p++;
3289 /* escape */
3290 c = *p;
3291 switch(c) {
3292 case '0': case '1': case '2': case '3':
3293 case '4': case '5': case '6': case '7':
3294 /* at most three octal digits */
3295 n = c - '0';
3296 p++;
3297 c = *p;
3298 if (isoct(c)) {
3299 n = n * 8 + c - '0';
3300 p++;
3301 c = *p;
3302 if (isoct(c)) {
3303 n = n * 8 + c - '0';
3304 p++;
3307 c = n;
3308 goto add_char_nonext;
3309 case 'x':
3310 case 'u':
3311 case 'U':
3312 p++;
3313 n = 0;
3314 for(;;) {
3315 c = *p;
3316 if (c >= 'a' && c <= 'f')
3317 c = c - 'a' + 10;
3318 else if (c >= 'A' && c <= 'F')
3319 c = c - 'A' + 10;
3320 else if (isnum(c))
3321 c = c - '0';
3322 else
3323 break;
3324 n = n * 16 + c;
3325 p++;
3327 c = n;
3328 goto add_char_nonext;
3329 case 'a':
3330 c = '\a';
3331 break;
3332 case 'b':
3333 c = '\b';
3334 break;
3335 case 'f':
3336 c = '\f';
3337 break;
3338 case 'n':
3339 c = '\n';
3340 break;
3341 case 'r':
3342 c = '\r';
3343 break;
3344 case 't':
3345 c = '\t';
3346 break;
3347 case 'v':
3348 c = '\v';
3349 break;
3350 case 'e':
3351 if (!gnu_ext)
3352 goto invalid_escape;
3353 c = 27;
3354 break;
3355 case '\'':
3356 case '\"':
3357 case '\\':
3358 case '?':
3359 break;
3360 default:
3361 invalid_escape:
3362 if (c >= '!' && c <= '~')
3363 warning("unknown escape sequence: \'\\%c\'", c);
3364 else
3365 warning("unknown escape sequence: \'\\x%x\'", c);
3366 break;
3369 p++;
3370 add_char_nonext:
3371 if (!is_long)
3372 cstr_ccat(outstr, c);
3373 else
3374 cstr_wccat(outstr, c);
3376 /* add a trailing '\0' */
3377 if (!is_long)
3378 cstr_ccat(outstr, '\0');
3379 else
3380 cstr_wccat(outstr, '\0');
3383 /* we use 64 bit numbers */
3384 #define BN_SIZE 2
3386 /* bn = (bn << shift) | or_val */
3387 void bn_lshift(unsigned int *bn, int shift, int or_val)
3389 int i;
3390 unsigned int v;
3391 for(i=0;i<BN_SIZE;i++) {
3392 v = bn[i];
3393 bn[i] = (v << shift) | or_val;
3394 or_val = v >> (32 - shift);
3398 void bn_zero(unsigned int *bn)
3400 int i;
3401 for(i=0;i<BN_SIZE;i++) {
3402 bn[i] = 0;
3406 /* parse number in null terminated string 'p' and return it in the
3407 current token */
3408 void parse_number(const char *p)
3410 int b, t, shift, frac_bits, s, exp_val, ch;
3411 char *q;
3412 unsigned int bn[BN_SIZE];
3413 double d;
3415 /* number */
3416 q = token_buf;
3417 ch = *p++;
3418 t = ch;
3419 ch = *p++;
3420 *q++ = t;
3421 b = 10;
3422 if (t == '.') {
3423 goto float_frac_parse;
3424 } else if (t == '0') {
3425 if (ch == 'x' || ch == 'X') {
3426 q--;
3427 ch = *p++;
3428 b = 16;
3429 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
3430 q--;
3431 ch = *p++;
3432 b = 2;
3435 /* parse all digits. cannot check octal numbers at this stage
3436 because of floating point constants */
3437 while (1) {
3438 if (ch >= 'a' && ch <= 'f')
3439 t = ch - 'a' + 10;
3440 else if (ch >= 'A' && ch <= 'F')
3441 t = ch - 'A' + 10;
3442 else if (isnum(ch))
3443 t = ch - '0';
3444 else
3445 break;
3446 if (t >= b)
3447 break;
3448 if (q >= token_buf + STRING_MAX_SIZE) {
3449 num_too_long:
3450 error("number too long");
3452 *q++ = ch;
3453 ch = *p++;
3455 if (ch == '.' ||
3456 ((ch == 'e' || ch == 'E') && b == 10) ||
3457 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
3458 if (b != 10) {
3459 /* NOTE: strtox should support that for hexa numbers, but
3460 non ISOC99 libcs do not support it, so we prefer to do
3461 it by hand */
3462 /* hexadecimal or binary floats */
3463 /* XXX: handle overflows */
3464 *q = '\0';
3465 if (b == 16)
3466 shift = 4;
3467 else
3468 shift = 2;
3469 bn_zero(bn);
3470 q = token_buf;
3471 while (1) {
3472 t = *q++;
3473 if (t == '\0') {
3474 break;
3475 } else if (t >= 'a') {
3476 t = t - 'a' + 10;
3477 } else if (t >= 'A') {
3478 t = t - 'A' + 10;
3479 } else {
3480 t = t - '0';
3482 bn_lshift(bn, shift, t);
3484 frac_bits = 0;
3485 if (ch == '.') {
3486 ch = *p++;
3487 while (1) {
3488 t = ch;
3489 if (t >= 'a' && t <= 'f') {
3490 t = t - 'a' + 10;
3491 } else if (t >= 'A' && t <= 'F') {
3492 t = t - 'A' + 10;
3493 } else if (t >= '0' && t <= '9') {
3494 t = t - '0';
3495 } else {
3496 break;
3498 if (t >= b)
3499 error("invalid digit");
3500 bn_lshift(bn, shift, t);
3501 frac_bits += shift;
3502 ch = *p++;
3505 if (ch != 'p' && ch != 'P')
3506 expect("exponent");
3507 ch = *p++;
3508 s = 1;
3509 exp_val = 0;
3510 if (ch == '+') {
3511 ch = *p++;
3512 } else if (ch == '-') {
3513 s = -1;
3514 ch = *p++;
3516 if (ch < '0' || ch > '9')
3517 expect("exponent digits");
3518 while (ch >= '0' && ch <= '9') {
3519 exp_val = exp_val * 10 + ch - '0';
3520 ch = *p++;
3522 exp_val = exp_val * s;
3524 /* now we can generate the number */
3525 /* XXX: should patch directly float number */
3526 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
3527 d = ldexp(d, exp_val - frac_bits);
3528 t = toup(ch);
3529 if (t == 'F') {
3530 ch = *p++;
3531 tok = TOK_CFLOAT;
3532 /* float : should handle overflow */
3533 tokc.f = (float)d;
3534 } else if (t == 'L') {
3535 ch = *p++;
3536 tok = TOK_CLDOUBLE;
3537 /* XXX: not large enough */
3538 tokc.ld = (long double)d;
3539 } else {
3540 tok = TOK_CDOUBLE;
3541 tokc.d = d;
3543 } else {
3544 /* decimal floats */
3545 if (ch == '.') {
3546 if (q >= token_buf + STRING_MAX_SIZE)
3547 goto num_too_long;
3548 *q++ = ch;
3549 ch = *p++;
3550 float_frac_parse:
3551 while (ch >= '0' && ch <= '9') {
3552 if (q >= token_buf + STRING_MAX_SIZE)
3553 goto num_too_long;
3554 *q++ = ch;
3555 ch = *p++;
3558 if (ch == 'e' || ch == 'E') {
3559 if (q >= token_buf + STRING_MAX_SIZE)
3560 goto num_too_long;
3561 *q++ = ch;
3562 ch = *p++;
3563 if (ch == '-' || ch == '+') {
3564 if (q >= token_buf + STRING_MAX_SIZE)
3565 goto num_too_long;
3566 *q++ = ch;
3567 ch = *p++;
3569 if (ch < '0' || ch > '9')
3570 expect("exponent digits");
3571 while (ch >= '0' && ch <= '9') {
3572 if (q >= token_buf + STRING_MAX_SIZE)
3573 goto num_too_long;
3574 *q++ = ch;
3575 ch = *p++;
3578 *q = '\0';
3579 t = toup(ch);
3580 errno = 0;
3581 if (t == 'F') {
3582 ch = *p++;
3583 tok = TOK_CFLOAT;
3584 tokc.f = strtof(token_buf, NULL);
3585 } else if (t == 'L') {
3586 ch = *p++;
3587 tok = TOK_CLDOUBLE;
3588 tokc.ld = strtold(token_buf, NULL);
3589 } else {
3590 tok = TOK_CDOUBLE;
3591 tokc.d = strtod(token_buf, NULL);
3594 } else {
3595 unsigned long long n, n1;
3596 int lcount, ucount;
3598 /* integer number */
3599 *q = '\0';
3600 q = token_buf;
3601 if (b == 10 && *q == '0') {
3602 b = 8;
3603 q++;
3605 n = 0;
3606 while(1) {
3607 t = *q++;
3608 /* no need for checks except for base 10 / 8 errors */
3609 if (t == '\0') {
3610 break;
3611 } else if (t >= 'a') {
3612 t = t - 'a' + 10;
3613 } else if (t >= 'A') {
3614 t = t - 'A' + 10;
3615 } else {
3616 t = t - '0';
3617 if (t >= b)
3618 error("invalid digit");
3620 n1 = n;
3621 n = n * b + t;
3622 /* detect overflow */
3623 /* XXX: this test is not reliable */
3624 if (n < n1)
3625 error("integer constant overflow");
3628 /* XXX: not exactly ANSI compliant */
3629 if ((n & 0xffffffff00000000LL) != 0) {
3630 if ((n >> 63) != 0)
3631 tok = TOK_CULLONG;
3632 else
3633 tok = TOK_CLLONG;
3634 } else if (n > 0x7fffffff) {
3635 tok = TOK_CUINT;
3636 } else {
3637 tok = TOK_CINT;
3639 lcount = 0;
3640 ucount = 0;
3641 for(;;) {
3642 t = toup(ch);
3643 if (t == 'L') {
3644 if (lcount >= 2)
3645 error("three 'l's in integer constant");
3646 lcount++;
3647 if (lcount == 2) {
3648 if (tok == TOK_CINT)
3649 tok = TOK_CLLONG;
3650 else if (tok == TOK_CUINT)
3651 tok = TOK_CULLONG;
3653 ch = *p++;
3654 } else if (t == 'U') {
3655 if (ucount >= 1)
3656 error("two 'u's in integer constant");
3657 ucount++;
3658 if (tok == TOK_CINT)
3659 tok = TOK_CUINT;
3660 else if (tok == TOK_CLLONG)
3661 tok = TOK_CULLONG;
3662 ch = *p++;
3663 } else {
3664 break;
3667 if (tok == TOK_CINT || tok == TOK_CUINT)
3668 tokc.ui = n;
3669 else
3670 tokc.ull = n;
3672 if (ch)
3673 error("invalid number\n");
3677 #define PARSE2(c1, tok1, c2, tok2) \
3678 case c1: \
3679 PEEKC(c, p); \
3680 if (c == c2) { \
3681 p++; \
3682 tok = tok2; \
3683 } else { \
3684 tok = tok1; \
3686 break;
3688 /* return next token without macro substitution */
3689 static inline void next_nomacro1(void)
3691 int t, c, is_long;
3692 TokenSym *ts;
3693 uint8_t *p, *p1;
3694 unsigned int h;
3696 cstr_reset(&tok_spaces);
3697 p = file->buf_ptr;
3698 redo_no_start:
3699 c = *p;
3700 switch(c) {
3701 case ' ':
3702 case '\t':
3703 case '\f':
3704 case '\v':
3705 case '\r':
3706 cstr_ccat(&tok_spaces, c);
3707 p++;
3708 goto redo_no_start;
3710 case '\\':
3711 /* first look if it is in fact an end of buffer */
3712 if (p >= file->buf_end) {
3713 file->buf_ptr = p;
3714 handle_eob();
3715 p = file->buf_ptr;
3716 if (p >= file->buf_end)
3717 goto parse_eof;
3718 else
3719 goto redo_no_start;
3720 } else {
3721 file->buf_ptr = p;
3722 ch = *p;
3723 handle_stray();
3724 p = file->buf_ptr;
3725 goto redo_no_start;
3727 parse_eof:
3729 TCCState *s1 = tcc_state;
3730 if ((parse_flags & PARSE_FLAG_LINEFEED)
3731 && !(tok_flags & TOK_FLAG_EOF)) {
3732 tok_flags |= TOK_FLAG_EOF;
3733 tok = TOK_LINEFEED;
3734 goto keep_tok_flags;
3735 } else if (s1->include_stack_ptr == s1->include_stack ||
3736 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
3737 /* no include left : end of file. */
3738 tok = TOK_EOF;
3739 } else {
3740 tok_flags &= ~TOK_FLAG_EOF;
3741 /* pop include file */
3743 /* test if previous '#endif' was after a #ifdef at
3744 start of file */
3745 if (tok_flags & TOK_FLAG_ENDIF) {
3746 #ifdef INC_DEBUG
3747 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
3748 #endif
3749 add_cached_include(s1, file->inc_type, file->inc_filename,
3750 file->ifndef_macro_saved);
3753 /* add end of include file debug info */
3754 if (do_debug) {
3755 put_stabd(N_EINCL, 0, 0);
3757 /* pop include stack */
3758 tcc_close(file);
3759 s1->include_stack_ptr--;
3760 file = *s1->include_stack_ptr;
3761 p = file->buf_ptr;
3762 goto redo_no_start;
3765 break;
3767 case '\n':
3768 file->line_num++;
3769 tok_flags |= TOK_FLAG_BOL;
3770 p++;
3771 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
3772 goto redo_no_start;
3773 tok = TOK_LINEFEED;
3774 goto keep_tok_flags;
3776 case '#':
3777 /* XXX: simplify */
3778 PEEKC(c, p);
3779 if ((tok_flags & TOK_FLAG_BOL) &&
3780 (parse_flags & PARSE_FLAG_PREPROCESS)) {
3781 file->buf_ptr = p;
3782 preprocess(tok_flags & TOK_FLAG_BOF);
3783 p = file->buf_ptr;
3784 goto redo_no_start;
3785 } else {
3786 if (c == '#') {
3787 p++;
3788 tok = TOK_TWOSHARPS;
3789 } else {
3790 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
3791 p = parse_line_comment(p - 1);
3792 goto redo_no_start;
3793 } else {
3794 tok = '#';
3798 break;
3800 case 'a': case 'b': case 'c': case 'd':
3801 case 'e': case 'f': case 'g': case 'h':
3802 case 'i': case 'j': case 'k': case 'l':
3803 case 'm': case 'n': case 'o': case 'p':
3804 case 'q': case 'r': case 's': case 't':
3805 case 'u': case 'v': case 'w': case 'x':
3806 case 'y': case 'z':
3807 case 'A': case 'B': case 'C': case 'D':
3808 case 'E': case 'F': case 'G': case 'H':
3809 case 'I': case 'J': case 'K':
3810 case 'M': case 'N': case 'O': case 'P':
3811 case 'Q': case 'R': case 'S': case 'T':
3812 case 'U': case 'V': case 'W': case 'X':
3813 case 'Y': case 'Z':
3814 case '_':
3815 parse_ident_fast:
3816 p1 = p;
3817 h = TOK_HASH_INIT;
3818 h = TOK_HASH_FUNC(h, c);
3819 p++;
3820 for(;;) {
3821 c = *p;
3822 if (!isidnum_table[c-CH_EOF])
3823 break;
3824 h = TOK_HASH_FUNC(h, c);
3825 p++;
3827 if (c != '\\') {
3828 TokenSym **pts;
3829 int len;
3831 /* fast case : no stray found, so we have the full token
3832 and we have already hashed it */
3833 len = p - p1;
3834 h &= (TOK_HASH_SIZE - 1);
3835 pts = &hash_ident[h];
3836 for(;;) {
3837 ts = *pts;
3838 if (!ts)
3839 break;
3840 if (ts->len == len && !memcmp(ts->str, p1, len))
3841 goto token_found;
3842 pts = &(ts->hash_next);
3844 ts = tok_alloc_new(pts, p1, len);
3845 token_found: ;
3846 } else {
3847 /* slower case */
3848 cstr_reset(&tokcstr);
3850 while (p1 < p) {
3851 cstr_ccat(&tokcstr, *p1);
3852 p1++;
3854 p--;
3855 PEEKC(c, p);
3856 parse_ident_slow:
3857 while (isidnum_table[c-CH_EOF]) {
3858 cstr_ccat(&tokcstr, c);
3859 PEEKC(c, p);
3861 ts = tok_alloc(tokcstr.data, tokcstr.size);
3863 tok = ts->tok;
3864 break;
3865 case 'L':
3866 t = p[1];
3867 if (t != '\\' && t != '\'' && t != '\"') {
3868 /* fast case */
3869 goto parse_ident_fast;
3870 } else {
3871 PEEKC(c, p);
3872 if (c == '\'' || c == '\"') {
3873 is_long = 1;
3874 goto str_const;
3875 } else {
3876 cstr_reset(&tokcstr);
3877 cstr_ccat(&tokcstr, 'L');
3878 goto parse_ident_slow;
3881 break;
3882 case '0': case '1': case '2': case '3':
3883 case '4': case '5': case '6': case '7':
3884 case '8': case '9':
3886 cstr_reset(&tokcstr);
3887 /* after the first digit, accept digits, alpha, '.' or sign if
3888 prefixed by 'eEpP' */
3889 parse_num:
3890 for(;;) {
3891 t = c;
3892 cstr_ccat(&tokcstr, c);
3893 PEEKC(c, p);
3894 if (!(isnum(c) || isid(c) || c == '.' ||
3895 ((c == '+' || c == '-') &&
3896 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
3897 break;
3899 /* We add a trailing '\0' to ease parsing */
3900 cstr_ccat(&tokcstr, '\0');
3901 tokc.cstr = &tokcstr;
3902 tok = TOK_PPNUM;
3903 break;
3904 case '.':
3905 /* special dot handling because it can also start a number */
3906 PEEKC(c, p);
3907 if (isnum(c)) {
3908 cstr_reset(&tokcstr);
3909 cstr_ccat(&tokcstr, '.');
3910 goto parse_num;
3911 } else if (c == '.') {
3912 PEEKC(c, p);
3913 if (c != '.')
3914 expect("'.'");
3915 PEEKC(c, p);
3916 tok = TOK_DOTS;
3917 } else {
3918 tok = '.';
3920 break;
3921 case '\'':
3922 case '\"':
3923 is_long = 0;
3924 str_const:
3926 CString str;
3927 int sep;
3929 sep = c;
3931 /* parse the string */
3932 cstr_new(&str);
3933 p = parse_pp_string(p, sep, &str);
3934 cstr_ccat(&str, '\0');
3936 /* eval the escape (should be done as TOK_PPNUM) */
3937 cstr_reset(&tokcstr);
3938 parse_escape_string(&tokcstr, str.data, is_long);
3939 cstr_free(&str);
3941 if (sep == '\'') {
3942 int char_size;
3943 /* XXX: make it portable */
3944 if (!is_long)
3945 char_size = 1;
3946 else
3947 char_size = sizeof(nwchar_t);
3948 if (tokcstr.size <= char_size)
3949 error("empty character constant");
3950 if (tokcstr.size > 2 * char_size)
3951 warning("multi-character character constant");
3952 if (!is_long) {
3953 tokc.i = *(int8_t *)tokcstr.data;
3954 tok = TOK_CCHAR;
3955 } else {
3956 tokc.i = *(nwchar_t *)tokcstr.data;
3957 tok = TOK_LCHAR;
3959 } else {
3960 tokc.cstr = &tokcstr;
3961 if (!is_long)
3962 tok = TOK_STR;
3963 else
3964 tok = TOK_LSTR;
3967 break;
3969 case '<':
3970 PEEKC(c, p);
3971 if (c == '=') {
3972 p++;
3973 tok = TOK_LE;
3974 } else if (c == '<') {
3975 PEEKC(c, p);
3976 if (c == '=') {
3977 p++;
3978 tok = TOK_A_SHL;
3979 } else {
3980 tok = TOK_SHL;
3982 } else {
3983 tok = TOK_LT;
3985 break;
3987 case '>':
3988 PEEKC(c, p);
3989 if (c == '=') {
3990 p++;
3991 tok = TOK_GE;
3992 } else if (c == '>') {
3993 PEEKC(c, p);
3994 if (c == '=') {
3995 p++;
3996 tok = TOK_A_SAR;
3997 } else {
3998 tok = TOK_SAR;
4000 } else {
4001 tok = TOK_GT;
4003 break;
4005 case '&':
4006 PEEKC(c, p);
4007 if (c == '&') {
4008 p++;
4009 tok = TOK_LAND;
4010 } else if (c == '=') {
4011 p++;
4012 tok = TOK_A_AND;
4013 } else {
4014 tok = '&';
4016 break;
4018 case '|':
4019 PEEKC(c, p);
4020 if (c == '|') {
4021 p++;
4022 tok = TOK_LOR;
4023 } else if (c == '=') {
4024 p++;
4025 tok = TOK_A_OR;
4026 } else {
4027 tok = '|';
4029 break;
4031 case '+':
4032 PEEKC(c, p);
4033 if (c == '+') {
4034 p++;
4035 tok = TOK_INC;
4036 } else if (c == '=') {
4037 p++;
4038 tok = TOK_A_ADD;
4039 } else {
4040 tok = '+';
4042 break;
4044 case '-':
4045 PEEKC(c, p);
4046 if (c == '-') {
4047 p++;
4048 tok = TOK_DEC;
4049 } else if (c == '=') {
4050 p++;
4051 tok = TOK_A_SUB;
4052 } else if (c == '>') {
4053 p++;
4054 tok = TOK_ARROW;
4055 } else {
4056 tok = '-';
4058 break;
4060 PARSE2('!', '!', '=', TOK_NE)
4061 PARSE2('=', '=', '=', TOK_EQ)
4062 PARSE2('*', '*', '=', TOK_A_MUL)
4063 PARSE2('%', '%', '=', TOK_A_MOD)
4064 PARSE2('^', '^', '=', TOK_A_XOR)
4066 /* comments or operator */
4067 case '/':
4068 PEEKC(c, p);
4069 if (c == '*') {
4070 p = parse_comment(p);
4071 goto redo_no_start;
4072 } else if (c == '/') {
4073 p = parse_line_comment(p);
4074 goto redo_no_start;
4075 } else if (c == '=') {
4076 p++;
4077 tok = TOK_A_DIV;
4078 } else {
4079 tok = '/';
4081 break;
4083 /* simple tokens */
4084 case '(':
4085 case ')':
4086 case '[':
4087 case ']':
4088 case '{':
4089 case '}':
4090 case ',':
4091 case ';':
4092 case ':':
4093 case '?':
4094 case '~':
4095 case '$': /* only used in assembler */
4096 case '@': /* dito */
4097 tok = c;
4098 p++;
4099 break;
4100 default:
4101 error("unrecognized character \\x%02x", c);
4102 break;
4104 tok_flags = 0;
4105 keep_tok_flags:
4106 file->buf_ptr = p;
4107 #if defined(PARSE_DEBUG)
4108 printf("token = %s\n", get_tok_str(tok, &tokc));
4109 #endif
4112 /* return next token without macro substitution. Can read input from
4113 macro_ptr buffer */
4114 static void next_nomacro(void)
4116 if (macro_ptr) {
4117 redo:
4118 tok = *macro_ptr;
4119 if (tok) {
4120 TOK_GET(tok, macro_ptr, tokc);
4121 if (tok == TOK_LINENUM) {
4122 file->line_num = tokc.i;
4123 goto redo;
4126 } else {
4127 next_nomacro1();
4131 /* substitute args in macro_str and return allocated string */
4132 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
4134 int *st, last_tok, t, notfirst;
4135 Sym *s;
4136 CValue cval;
4137 TokenString str;
4138 CString cstr;
4140 tok_str_new(&str);
4141 last_tok = 0;
4142 while(1) {
4143 TOK_GET(t, macro_str, cval);
4144 if (!t)
4145 break;
4146 if (t == '#') {
4147 /* stringize */
4148 TOK_GET(t, macro_str, cval);
4149 if (!t)
4150 break;
4151 s = sym_find2(args, t);
4152 if (s) {
4153 cstr_new(&cstr);
4154 st = (int *)s->c;
4155 notfirst = 0;
4156 while (*st) {
4157 if (notfirst)
4158 cstr_ccat(&cstr, ' ');
4159 TOK_GET(t, st, cval);
4160 cstr_cat(&cstr, get_tok_str(t, &cval));
4161 #ifndef PP_NOSPACES
4162 notfirst = 1;
4163 #endif
4165 cstr_ccat(&cstr, '\0');
4166 #ifdef PP_DEBUG
4167 printf("stringize: %s\n", (char *)cstr.data);
4168 #endif
4169 /* add string */
4170 cval.cstr = &cstr;
4171 tok_str_add2(&str, TOK_STR, &cval);
4172 cstr_free(&cstr);
4173 } else {
4174 tok_str_add2(&str, t, &cval);
4176 } else if (t >= TOK_IDENT) {
4177 s = sym_find2(args, t);
4178 if (s) {
4179 st = (int *)s->c;
4180 /* if '##' is present before or after, no arg substitution */
4181 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
4182 /* special case for var arg macros : ## eats the
4183 ',' if empty VA_ARGS variable. */
4184 /* XXX: test of the ',' is not 100%
4185 reliable. should fix it to avoid security
4186 problems */
4187 if (gnu_ext && s->type.t &&
4188 last_tok == TOK_TWOSHARPS &&
4189 str.len >= 2 && str.str[str.len - 2] == ',') {
4190 if (*st == 0) {
4191 /* suppress ',' '##' */
4192 str.len -= 2;
4193 } else {
4194 /* suppress '##' and add variable */
4195 str.len--;
4196 goto add_var;
4198 } else {
4199 int t1;
4200 add_var:
4201 for(;;) {
4202 TOK_GET(t1, st, cval);
4203 if (!t1)
4204 break;
4205 tok_str_add2(&str, t1, &cval);
4208 } else {
4209 /* NOTE: the stream cannot be read when macro
4210 substituing an argument */
4211 macro_subst(&str, nested_list, st, NULL);
4213 } else {
4214 tok_str_add(&str, t);
4216 } else {
4217 tok_str_add2(&str, t, &cval);
4219 last_tok = t;
4221 tok_str_add(&str, 0);
4222 return str.str;
4225 static char const ab_month_name[12][4] =
4227 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4228 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4231 /* do macro substitution of current token with macro 's' and add
4232 result to (tok_str,tok_len). 'nested_list' is the list of all
4233 macros we got inside to avoid recursing. Return non zero if no
4234 substitution needs to be done */
4235 static int macro_subst_tok(TokenString *tok_str,
4236 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
4238 Sym *args, *sa, *sa1;
4239 int mstr_allocated, parlevel, *mstr, t, t1;
4240 TokenString str;
4241 char *cstrval;
4242 CValue cval;
4243 CString cstr;
4244 char buf[32];
4246 /* if symbol is a macro, prepare substitution */
4247 /* special macros */
4248 if (tok == TOK___LINE__) {
4249 snprintf(buf, sizeof(buf), "%d", file->line_num);
4250 cstrval = buf;
4251 t1 = TOK_PPNUM;
4252 goto add_cstr1;
4253 } else if (tok == TOK___FILE__) {
4254 cstrval = file->filename;
4255 goto add_cstr;
4256 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
4257 time_t ti;
4258 struct tm *tm;
4260 time(&ti);
4261 tm = localtime(&ti);
4262 if (tok == TOK___DATE__) {
4263 snprintf(buf, sizeof(buf), "%s %2d %d",
4264 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
4265 } else {
4266 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
4267 tm->tm_hour, tm->tm_min, tm->tm_sec);
4269 cstrval = buf;
4270 add_cstr:
4271 t1 = TOK_STR;
4272 add_cstr1:
4273 cstr_new(&cstr);
4274 cstr_cat(&cstr, cstrval);
4275 cstr_ccat(&cstr, '\0');
4276 cval.cstr = &cstr;
4277 tok_str_add2(tok_str, t1, &cval);
4278 cstr_free(&cstr);
4279 } else {
4280 mstr = (int *)s->c;
4281 mstr_allocated = 0;
4282 if (s->type.t == MACRO_FUNC) {
4283 /* NOTE: we do not use next_nomacro to avoid eating the
4284 next token. XXX: find better solution */
4285 redo:
4286 if (macro_ptr) {
4287 t = *macro_ptr;
4288 if (t == 0 && can_read_stream) {
4289 /* end of macro stream: we must look at the token
4290 after in the file */
4291 struct macro_level *ml = *can_read_stream;
4292 macro_ptr = NULL;
4293 if (ml)
4295 macro_ptr = ml->p;
4296 ml->p = NULL;
4297 *can_read_stream = ml -> prev;
4299 goto redo;
4301 } else {
4302 /* XXX: incorrect with comments */
4303 ch = file->buf_ptr[0];
4304 while (is_space(ch) || ch == '\n')
4305 cinp();
4306 t = ch;
4308 if (t != '(') /* no macro subst */
4309 return -1;
4311 /* argument macro */
4312 next_nomacro();
4313 next_nomacro();
4314 args = NULL;
4315 sa = s->next;
4316 /* NOTE: empty args are allowed, except if no args */
4317 for(;;) {
4318 /* handle '()' case */
4319 if (!args && !sa && tok == ')')
4320 break;
4321 if (!sa)
4322 error("macro '%s' used with too many args",
4323 get_tok_str(s->v, 0));
4324 tok_str_new(&str);
4325 parlevel = 0;
4326 /* NOTE: non zero sa->t indicates VA_ARGS */
4327 while ((parlevel > 0 ||
4328 (tok != ')' &&
4329 (tok != ',' || sa->type.t))) &&
4330 tok != -1) {
4331 if (tok == '(')
4332 parlevel++;
4333 else if (tok == ')')
4334 parlevel--;
4335 if (tok != TOK_LINEFEED)
4336 tok_str_add2(&str, tok, &tokc);
4337 next_nomacro();
4339 tok_str_add(&str, 0);
4340 sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, (long)str.str);
4341 sa = sa->next;
4342 if (tok == ')') {
4343 /* special case for gcc var args: add an empty
4344 var arg argument if it is omitted */
4345 if (sa && sa->type.t && gnu_ext)
4346 continue;
4347 else
4348 break;
4350 if (tok != ',')
4351 expect(",");
4352 next_nomacro();
4354 if (sa) {
4355 error("macro '%s' used with too few args",
4356 get_tok_str(s->v, 0));
4359 /* now subst each arg */
4360 mstr = macro_arg_subst(nested_list, mstr, args);
4361 /* free memory */
4362 sa = args;
4363 while (sa) {
4364 sa1 = sa->prev;
4365 tok_str_free((int *)sa->c);
4366 sym_free(sa);
4367 sa = sa1;
4369 mstr_allocated = 1;
4371 sym_push2(nested_list, s->v, 0, 0);
4372 macro_subst(tok_str, nested_list, mstr, can_read_stream);
4373 /* pop nested defined symbol */
4374 sa1 = *nested_list;
4375 *nested_list = sa1->prev;
4376 sym_free(sa1);
4377 if (mstr_allocated)
4378 tok_str_free(mstr);
4380 return 0;
4383 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4384 return the resulting string (which must be freed). */
4385 static inline int *macro_twosharps(const int *macro_str)
4387 TokenSym *ts;
4388 const int *macro_ptr1, *start_macro_ptr, *ptr, *saved_macro_ptr;
4389 int t;
4390 const char *p1, *p2;
4391 CValue cval;
4392 TokenString macro_str1;
4393 CString cstr;
4395 start_macro_ptr = macro_str;
4396 /* we search the first '##' */
4397 for(;;) {
4398 macro_ptr1 = macro_str;
4399 TOK_GET(t, macro_str, cval);
4400 /* nothing more to do if end of string */
4401 if (t == 0)
4402 return NULL;
4403 if (*macro_str == TOK_TWOSHARPS)
4404 break;
4407 /* we saw '##', so we need more processing to handle it */
4408 cstr_new(&cstr);
4409 tok_str_new(&macro_str1);
4410 tok = t;
4411 tokc = cval;
4413 /* add all tokens seen so far */
4414 for(ptr = start_macro_ptr; ptr < macro_ptr1;) {
4415 TOK_GET(t, ptr, cval);
4416 tok_str_add2(&macro_str1, t, &cval);
4418 saved_macro_ptr = macro_ptr;
4419 /* XXX: get rid of the use of macro_ptr here */
4420 macro_ptr = (int *)macro_str;
4421 for(;;) {
4422 while (*macro_ptr == TOK_TWOSHARPS) {
4423 macro_ptr++;
4424 macro_ptr1 = macro_ptr;
4425 t = *macro_ptr;
4426 if (t) {
4427 TOK_GET(t, macro_ptr, cval);
4428 /* We concatenate the two tokens if we have an
4429 identifier or a preprocessing number */
4430 cstr_reset(&cstr);
4431 p1 = get_tok_str(tok, &tokc);
4432 cstr_cat(&cstr, p1);
4433 p2 = get_tok_str(t, &cval);
4434 cstr_cat(&cstr, p2);
4435 cstr_ccat(&cstr, '\0');
4437 if ((tok >= TOK_IDENT || tok == TOK_PPNUM) &&
4438 (t >= TOK_IDENT || t == TOK_PPNUM)) {
4439 if (tok == TOK_PPNUM) {
4440 /* if number, then create a number token */
4441 /* NOTE: no need to allocate because
4442 tok_str_add2() does it */
4443 cstr_reset(&tokcstr);
4444 tokcstr = cstr;
4445 cstr_new(&cstr);
4446 tokc.cstr = &tokcstr;
4447 } else {
4448 /* if identifier, we must do a test to
4449 validate we have a correct identifier */
4450 if (t == TOK_PPNUM) {
4451 const char *p;
4452 int c;
4454 p = p2;
4455 for(;;) {
4456 c = *p;
4457 if (c == '\0')
4458 break;
4459 p++;
4460 if (!isnum(c) && !isid(c))
4461 goto error_pasting;
4464 ts = tok_alloc(cstr.data, strlen(cstr.data));
4465 tok = ts->tok; /* modify current token */
4467 } else {
4468 const char *str = cstr.data;
4469 const unsigned char *q;
4471 /* we look for a valid token */
4472 /* XXX: do more extensive checks */
4473 if (!strcmp(str, ">>=")) {
4474 tok = TOK_A_SAR;
4475 } else if (!strcmp(str, "<<=")) {
4476 tok = TOK_A_SHL;
4477 } else if (strlen(str) == 2) {
4478 /* search in two bytes table */
4479 q = tok_two_chars;
4480 for(;;) {
4481 if (!*q)
4482 goto error_pasting;
4483 if (q[0] == str[0] && q[1] == str[1])
4484 break;
4485 q += 3;
4487 tok = q[2];
4488 } else {
4489 error_pasting:
4490 /* NOTE: because get_tok_str use a static buffer,
4491 we must save it */
4492 cstr_reset(&cstr);
4493 p1 = get_tok_str(tok, &tokc);
4494 cstr_cat(&cstr, p1);
4495 cstr_ccat(&cstr, '\0');
4496 p2 = get_tok_str(t, &cval);
4497 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
4498 /* cannot merge tokens: just add them separately */
4499 tok_str_add2(&macro_str1, tok, &tokc);
4500 /* XXX: free associated memory ? */
4501 tok = t;
4502 tokc = cval;
4507 tok_str_add2(&macro_str1, tok, &tokc);
4508 next_nomacro();
4509 if (tok == 0)
4510 break;
4512 macro_ptr = (int *)saved_macro_ptr;
4513 cstr_free(&cstr);
4514 tok_str_add(&macro_str1, 0);
4515 return macro_str1.str;
4519 /* do macro substitution of macro_str and add result to
4520 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4521 inside to avoid recursing. */
4522 static void macro_subst(TokenString *tok_str, Sym **nested_list,
4523 const int *macro_str, struct macro_level ** can_read_stream)
4525 Sym *s;
4526 int *macro_str1;
4527 const int *ptr;
4528 int t, ret;
4529 CValue cval;
4530 struct macro_level ml;
4532 /* first scan for '##' operator handling */
4533 ptr = macro_str;
4534 macro_str1 = macro_twosharps(ptr);
4535 if (macro_str1)
4536 ptr = macro_str1;
4537 while (1) {
4538 /* NOTE: ptr == NULL can only happen if tokens are read from
4539 file stream due to a macro function call */
4540 if (ptr == NULL)
4541 break;
4542 TOK_GET(t, ptr, cval);
4543 if (t == 0)
4544 break;
4545 s = define_find(t);
4546 if (s != NULL) {
4547 /* if nested substitution, do nothing */
4548 if (sym_find2(*nested_list, t))
4549 goto no_subst;
4550 ml.p = macro_ptr;
4551 if (can_read_stream)
4552 ml.prev = *can_read_stream, *can_read_stream = &ml;
4553 macro_ptr = (int *)ptr;
4554 tok = t;
4555 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
4556 ptr = (int *)macro_ptr;
4557 macro_ptr = ml.p;
4558 if (can_read_stream && *can_read_stream == &ml)
4559 *can_read_stream = ml.prev;
4560 if (ret != 0)
4561 goto no_subst;
4562 } else {
4563 no_subst:
4564 tok_str_add2(tok_str, t, &cval);
4567 if (macro_str1)
4568 tok_str_free(macro_str1);
4571 /* return next token with macro substitution */
4572 static void next(void)
4574 Sym *nested_list, *s;
4575 TokenString str;
4576 struct macro_level *ml;
4578 redo:
4579 next_nomacro();
4580 if (!macro_ptr) {
4581 /* if not reading from macro substituted string, then try
4582 to substitute macros */
4583 if (tok >= TOK_IDENT &&
4584 (parse_flags & PARSE_FLAG_PREPROCESS)) {
4585 s = define_find(tok);
4586 if (s) {
4587 /* we have a macro: we try to substitute */
4588 tok_str_new(&str);
4589 nested_list = NULL;
4590 ml = NULL;
4591 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
4592 /* substitution done, NOTE: maybe empty */
4593 tok_str_add(&str, 0);
4594 macro_ptr = str.str;
4595 macro_ptr_allocated = str.str;
4596 goto redo;
4600 } else {
4601 if (tok == 0) {
4602 /* end of macro or end of unget buffer */
4603 if (unget_buffer_enabled) {
4604 macro_ptr = unget_saved_macro_ptr;
4605 unget_buffer_enabled = 0;
4606 } else {
4607 /* end of macro string: free it */
4608 tok_str_free(macro_ptr_allocated);
4609 macro_ptr = NULL;
4611 goto redo;
4615 /* convert preprocessor tokens into C tokens */
4616 if (tok == TOK_PPNUM &&
4617 (parse_flags & PARSE_FLAG_TOK_NUM)) {
4618 parse_number((char *)tokc.cstr->data);
4622 /* push back current token and set current token to 'last_tok'. Only
4623 identifier case handled for labels. */
4624 static inline void unget_tok(int last_tok)
4626 int i, n;
4627 int *q;
4628 unget_saved_macro_ptr = macro_ptr;
4629 unget_buffer_enabled = 1;
4630 q = unget_saved_buffer;
4631 macro_ptr = q;
4632 *q++ = tok;
4633 n = tok_ext_size(tok) - 1;
4634 for(i=0;i<n;i++)
4635 *q++ = tokc.tab[i];
4636 *q = 0; /* end of token string */
4637 tok = last_tok;
4641 void swap(int *p, int *q)
4643 int t;
4644 t = *p;
4645 *p = *q;
4646 *q = t;
4649 void vsetc(CType *type, int r, CValue *vc)
4651 int v;
4653 if (vtop >= vstack + (VSTACK_SIZE - 1))
4654 error("memory full");
4655 /* cannot let cpu flags if other instruction are generated. Also
4656 avoid leaving VT_JMP anywhere except on the top of the stack
4657 because it would complicate the code generator. */
4658 if (vtop >= vstack) {
4659 v = vtop->r & VT_VALMASK;
4660 if (v == VT_CMP || (v & ~1) == VT_JMP)
4661 gv(RC_INT);
4663 vtop++;
4664 vtop->type = *type;
4665 vtop->r = r;
4666 vtop->r2 = VT_CONST;
4667 vtop->c = *vc;
4670 /* push integer constant */
4671 void vpushi(int v)
4673 CValue cval;
4674 cval.i = v;
4675 vsetc(&int_type, VT_CONST, &cval);
4678 /* push long long constant */
4679 void vpushll(long long v)
4681 CValue cval;
4682 CType ctype;
4683 ctype.t = VT_LLONG;
4684 cval.ull = v;
4685 vsetc(&ctype, VT_CONST, &cval);
4688 /* Return a static symbol pointing to a section */
4689 static Sym *get_sym_ref(CType *type, Section *sec,
4690 unsigned long offset, unsigned long size)
4692 int v;
4693 Sym *sym;
4695 v = anon_sym++;
4696 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
4697 sym->type.ref = type->ref;
4698 sym->r = VT_CONST | VT_SYM;
4699 put_extern_sym(sym, sec, offset, size);
4700 return sym;
4703 /* push a reference to a section offset by adding a dummy symbol */
4704 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
4706 CValue cval;
4708 cval.ul = 0;
4709 vsetc(type, VT_CONST | VT_SYM, &cval);
4710 vtop->sym = get_sym_ref(type, sec, offset, size);
4713 /* define a new external reference to a symbol 'v' of type 'u' */
4714 static Sym *external_global_sym(int v, CType *type, int r)
4716 Sym *s;
4718 s = sym_find(v);
4719 if (!s) {
4720 /* push forward reference */
4721 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
4722 s->type.ref = type->ref;
4723 s->r = r | VT_CONST | VT_SYM;
4725 return s;
4728 /* define a new external reference to a symbol 'v' of type 'u' */
4729 static Sym *external_sym(int v, CType *type, int r)
4731 Sym *s;
4733 s = sym_find(v);
4734 if (!s) {
4735 /* push forward reference */
4736 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
4737 s->type.t |= VT_EXTERN;
4738 } else {
4739 if (!is_compatible_types(&s->type, type))
4740 error("incompatible types for redefinition of '%s'",
4741 get_tok_str(v, NULL));
4743 return s;
4746 /* push a reference to global symbol v */
4747 static void vpush_global_sym(CType *type, int v)
4749 Sym *sym;
4750 CValue cval;
4752 sym = external_global_sym(v, type, 0);
4753 cval.ul = 0;
4754 vsetc(type, VT_CONST | VT_SYM, &cval);
4755 vtop->sym = sym;
4758 void vset(CType *type, int r, int v)
4760 CValue cval;
4762 cval.i = v;
4763 vsetc(type, r, &cval);
4766 void vseti(int r, int v)
4768 CType type;
4769 type.t = VT_INT;
4770 vset(&type, r, v);
4773 void vswap(void)
4775 SValue tmp;
4777 tmp = vtop[0];
4778 vtop[0] = vtop[-1];
4779 vtop[-1] = tmp;
4782 void vpushv(SValue *v)
4784 if (vtop >= vstack + (VSTACK_SIZE - 1))
4785 error("memory full");
4786 vtop++;
4787 *vtop = *v;
4790 void vdup(void)
4792 vpushv(vtop);
4795 /* save r to the memory stack, and mark it as being free */
4796 void save_reg(int r)
4798 int l, saved, size, align;
4799 SValue *p, sv;
4800 CType *type;
4802 /* modify all stack values */
4803 saved = 0;
4804 l = 0;
4805 for(p=vstack;p<=vtop;p++) {
4806 if ((p->r & VT_VALMASK) == r ||
4807 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
4808 /* must save value on stack if not already done */
4809 if (!saved) {
4810 /* NOTE: must reload 'r' because r might be equal to r2 */
4811 r = p->r & VT_VALMASK;
4812 /* store register in the stack */
4813 type = &p->type;
4814 if ((p->r & VT_LVAL) ||
4815 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
4816 #ifdef TCC_TARGET_X86_64
4817 type = &char_pointer_type;
4818 #else
4819 type = &int_type;
4820 #endif
4821 size = type_size(type, &align);
4822 loc = (loc - size) & -align;
4823 sv.type.t = type->t;
4824 sv.r = VT_LOCAL | VT_LVAL;
4825 sv.c.ul = loc;
4826 store(r, &sv);
4827 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4828 /* x86 specific: need to pop fp register ST0 if saved */
4829 if (r == TREG_ST0) {
4830 o(0xd9dd); /* fstp %st(1) */
4832 #endif
4833 #ifndef TCC_TARGET_X86_64
4834 /* special long long case */
4835 if ((type->t & VT_BTYPE) == VT_LLONG) {
4836 sv.c.ul += 4;
4837 store(p->r2, &sv);
4839 #endif
4840 l = loc;
4841 saved = 1;
4843 /* mark that stack entry as being saved on the stack */
4844 if (p->r & VT_LVAL) {
4845 /* also clear the bounded flag because the
4846 relocation address of the function was stored in
4847 p->c.ul */
4848 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
4849 } else {
4850 p->r = lvalue_type(p->type.t) | VT_LOCAL;
4852 p->r2 = VT_CONST;
4853 p->c.ul = l;
4858 /* find a register of class 'rc2' with at most one reference on stack.
4859 * If none, call get_reg(rc) */
4860 int get_reg_ex(int rc, int rc2)
4862 int r;
4863 SValue *p;
4865 for(r=0;r<NB_REGS;r++) {
4866 if (reg_classes[r] & rc2) {
4867 int n;
4868 n=0;
4869 for(p = vstack; p <= vtop; p++) {
4870 if ((p->r & VT_VALMASK) == r ||
4871 (p->r2 & VT_VALMASK) == r)
4872 n++;
4874 if (n <= 1)
4875 return r;
4878 return get_reg(rc);
4881 /* find a free register of class 'rc'. If none, save one register */
4882 int get_reg(int rc)
4884 int r;
4885 SValue *p;
4887 /* find a free register */
4888 for(r=0;r<NB_REGS;r++) {
4889 if (reg_classes[r] & rc) {
4890 for(p=vstack;p<=vtop;p++) {
4891 if ((p->r & VT_VALMASK) == r ||
4892 (p->r2 & VT_VALMASK) == r)
4893 goto notfound;
4895 return r;
4897 notfound: ;
4900 /* no register left : free the first one on the stack (VERY
4901 IMPORTANT to start from the bottom to ensure that we don't
4902 spill registers used in gen_opi()) */
4903 for(p=vstack;p<=vtop;p++) {
4904 r = p->r & VT_VALMASK;
4905 if (r < VT_CONST && (reg_classes[r] & rc))
4906 goto save_found;
4907 /* also look at second register (if long long) */
4908 r = p->r2 & VT_VALMASK;
4909 if (r < VT_CONST && (reg_classes[r] & rc)) {
4910 save_found:
4911 save_reg(r);
4912 return r;
4915 /* Should never comes here */
4916 return -1;
4919 /* save registers up to (vtop - n) stack entry */
4920 void save_regs(int n)
4922 int r;
4923 SValue *p, *p1;
4924 p1 = vtop - n;
4925 for(p = vstack;p <= p1; p++) {
4926 r = p->r & VT_VALMASK;
4927 if (r < VT_CONST) {
4928 save_reg(r);
4933 /* move register 's' to 'r', and flush previous value of r to memory
4934 if needed */
4935 void move_reg(int r, int s)
4937 SValue sv;
4939 if (r != s) {
4940 save_reg(r);
4941 sv.type.t = VT_INT;
4942 sv.r = s;
4943 sv.c.ul = 0;
4944 load(r, &sv);
4948 /* get address of vtop (vtop MUST BE an lvalue) */
4949 void gaddrof(void)
4951 vtop->r &= ~VT_LVAL;
4952 /* tricky: if saved lvalue, then we can go back to lvalue */
4953 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
4954 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
4957 #ifdef CONFIG_TCC_BCHECK
4958 /* generate lvalue bound code */
4959 void gbound(void)
4961 int lval_type;
4962 CType type1;
4964 vtop->r &= ~VT_MUSTBOUND;
4965 /* if lvalue, then use checking code before dereferencing */
4966 if (vtop->r & VT_LVAL) {
4967 /* if not VT_BOUNDED value, then make one */
4968 if (!(vtop->r & VT_BOUNDED)) {
4969 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
4970 /* must save type because we must set it to int to get pointer */
4971 type1 = vtop->type;
4972 vtop->type.t = VT_INT;
4973 gaddrof();
4974 vpushi(0);
4975 gen_bounded_ptr_add();
4976 vtop->r |= lval_type;
4977 vtop->type = type1;
4979 /* then check for dereferencing */
4980 gen_bounded_ptr_deref();
4983 #endif
4985 /* store vtop a register belonging to class 'rc'. lvalues are
4986 converted to values. Cannot be used if cannot be converted to
4987 register value (such as structures). */
4988 int gv(int rc)
4990 int r, rc2, bit_pos, bit_size, size, align, i;
4992 /* NOTE: get_reg can modify vstack[] */
4993 if (vtop->type.t & VT_BITFIELD) {
4994 CType type;
4995 int bits = 32;
4996 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4997 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4998 /* remove bit field info to avoid loops */
4999 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
5000 /* cast to int to propagate signedness in following ops */
5001 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5002 type.t = VT_LLONG;
5003 bits = 64;
5004 } else
5005 type.t = VT_INT;
5006 if((vtop->type.t & VT_UNSIGNED) ||
5007 (vtop->type.t & VT_BTYPE) == VT_BOOL)
5008 type.t |= VT_UNSIGNED;
5009 gen_cast(&type);
5010 /* generate shifts */
5011 vpushi(bits - (bit_pos + bit_size));
5012 gen_op(TOK_SHL);
5013 vpushi(bits - bit_size);
5014 /* NOTE: transformed to SHR if unsigned */
5015 gen_op(TOK_SAR);
5016 r = gv(rc);
5017 } else {
5018 if (is_float(vtop->type.t) &&
5019 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5020 Sym *sym;
5021 int *ptr;
5022 unsigned long offset;
5023 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5024 CValue check;
5025 #endif
5027 /* XXX: unify with initializers handling ? */
5028 /* CPUs usually cannot use float constants, so we store them
5029 generically in data segment */
5030 size = type_size(&vtop->type, &align);
5031 offset = (data_section->data_offset + align - 1) & -align;
5032 data_section->data_offset = offset;
5033 /* XXX: not portable yet */
5034 #if defined(__i386__) || defined(__x86_64__)
5035 /* Zero pad x87 tenbyte long doubles */
5036 if (size == LDOUBLE_SIZE)
5037 vtop->c.tab[2] &= 0xffff;
5038 #endif
5039 ptr = section_ptr_add(data_section, size);
5040 size = size >> 2;
5041 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5042 check.d = 1;
5043 if(check.tab[0])
5044 for(i=0;i<size;i++)
5045 ptr[i] = vtop->c.tab[size-1-i];
5046 else
5047 #endif
5048 for(i=0;i<size;i++)
5049 ptr[i] = vtop->c.tab[i];
5050 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
5051 vtop->r |= VT_LVAL | VT_SYM;
5052 vtop->sym = sym;
5053 vtop->c.ul = 0;
5055 #ifdef CONFIG_TCC_BCHECK
5056 if (vtop->r & VT_MUSTBOUND)
5057 gbound();
5058 #endif
5060 r = vtop->r & VT_VALMASK;
5061 rc2 = RC_INT;
5062 if (rc == RC_IRET)
5063 rc2 = RC_LRET;
5064 /* need to reload if:
5065 - constant
5066 - lvalue (need to dereference pointer)
5067 - already a register, but not in the right class */
5068 if (r >= VT_CONST ||
5069 (vtop->r & VT_LVAL) ||
5070 !(reg_classes[r] & rc) ||
5071 ((vtop->type.t & VT_BTYPE) == VT_LLONG &&
5072 !(reg_classes[vtop->r2] & rc2))) {
5073 r = get_reg(rc);
5074 #ifndef TCC_TARGET_X86_64
5075 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5076 int r2;
5077 unsigned long long ll;
5078 /* two register type load : expand to two words
5079 temporarily */
5080 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5081 /* load constant */
5082 ll = vtop->c.ull;
5083 vtop->c.ui = ll; /* first word */
5084 load(r, vtop);
5085 vtop->r = r; /* save register value */
5086 vpushi(ll >> 32); /* second word */
5087 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
5088 (vtop->r & VT_LVAL)) {
5089 /* We do not want to modifier the long long
5090 pointer here, so the safest (and less
5091 efficient) is to save all the other registers
5092 in the stack. XXX: totally inefficient. */
5093 save_regs(1);
5094 /* load from memory */
5095 load(r, vtop);
5096 vdup();
5097 vtop[-1].r = r; /* save register value */
5098 /* increment pointer to get second word */
5099 vtop->type.t = VT_INT;
5100 gaddrof();
5101 vpushi(4);
5102 gen_op('+');
5103 vtop->r |= VT_LVAL;
5104 } else {
5105 /* move registers */
5106 load(r, vtop);
5107 vdup();
5108 vtop[-1].r = r; /* save register value */
5109 vtop->r = vtop[-1].r2;
5111 /* allocate second register */
5112 r2 = get_reg(rc2);
5113 load(r2, vtop);
5114 vpop();
5115 /* write second register */
5116 vtop->r2 = r2;
5117 } else
5118 #endif
5119 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
5120 int t1, t;
5121 /* lvalue of scalar type : need to use lvalue type
5122 because of possible cast */
5123 t = vtop->type.t;
5124 t1 = t;
5125 /* compute memory access type */
5126 if (vtop->r & VT_LVAL_BYTE)
5127 t = VT_BYTE;
5128 else if (vtop->r & VT_LVAL_SHORT)
5129 t = VT_SHORT;
5130 if (vtop->r & VT_LVAL_UNSIGNED)
5131 t |= VT_UNSIGNED;
5132 vtop->type.t = t;
5133 load(r, vtop);
5134 /* restore wanted type */
5135 vtop->type.t = t1;
5136 } else {
5137 /* one register type load */
5138 load(r, vtop);
5141 vtop->r = r;
5142 #ifdef TCC_TARGET_C67
5143 /* uses register pairs for doubles */
5144 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
5145 vtop->r2 = r+1;
5146 #endif
5148 return r;
5151 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5152 void gv2(int rc1, int rc2)
5154 int v;
5156 /* generate more generic register first. But VT_JMP or VT_CMP
5157 values must be generated first in all cases to avoid possible
5158 reload errors */
5159 v = vtop[0].r & VT_VALMASK;
5160 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
5161 vswap();
5162 gv(rc1);
5163 vswap();
5164 gv(rc2);
5165 /* test if reload is needed for first register */
5166 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
5167 vswap();
5168 gv(rc1);
5169 vswap();
5171 } else {
5172 gv(rc2);
5173 vswap();
5174 gv(rc1);
5175 vswap();
5176 /* test if reload is needed for first register */
5177 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
5178 gv(rc2);
5183 /* wrapper around RC_FRET to return a register by type */
5184 int rc_fret(int t)
5186 #ifdef TCC_TARGET_X86_64
5187 if (t == VT_LDOUBLE) {
5188 return RC_ST0;
5190 #endif
5191 return RC_FRET;
5194 /* wrapper around REG_FRET to return a register by type */
5195 int reg_fret(int t)
5197 #ifdef TCC_TARGET_X86_64
5198 if (t == VT_LDOUBLE) {
5199 return TREG_ST0;
5201 #endif
5202 return REG_FRET;
5205 /* expand long long on stack in two int registers */
5206 void lexpand(void)
5208 int u;
5210 u = vtop->type.t & VT_UNSIGNED;
5211 gv(RC_INT);
5212 vdup();
5213 vtop[0].r = vtop[-1].r2;
5214 vtop[0].r2 = VT_CONST;
5215 vtop[-1].r2 = VT_CONST;
5216 vtop[0].type.t = VT_INT | u;
5217 vtop[-1].type.t = VT_INT | u;
5220 #ifdef TCC_TARGET_ARM
5221 /* expand long long on stack */
5222 void lexpand_nr(void)
5224 int u,v;
5226 u = vtop->type.t & VT_UNSIGNED;
5227 vdup();
5228 vtop->r2 = VT_CONST;
5229 vtop->type.t = VT_INT | u;
5230 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
5231 if (v == VT_CONST) {
5232 vtop[-1].c.ui = vtop->c.ull;
5233 vtop->c.ui = vtop->c.ull >> 32;
5234 vtop->r = VT_CONST;
5235 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
5236 vtop->c.ui += 4;
5237 vtop->r = vtop[-1].r;
5238 } else if (v > VT_CONST) {
5239 vtop--;
5240 lexpand();
5241 } else
5242 vtop->r = vtop[-1].r2;
5243 vtop[-1].r2 = VT_CONST;
5244 vtop[-1].type.t = VT_INT | u;
5246 #endif
5248 /* build a long long from two ints */
5249 void lbuild(int t)
5251 gv2(RC_INT, RC_INT);
5252 vtop[-1].r2 = vtop[0].r;
5253 vtop[-1].type.t = t;
5254 vpop();
5257 /* rotate n first stack elements to the bottom
5258 I1 ... In -> I2 ... In I1 [top is right]
5260 void vrotb(int n)
5262 int i;
5263 SValue tmp;
5265 tmp = vtop[-n + 1];
5266 for(i=-n+1;i!=0;i++)
5267 vtop[i] = vtop[i+1];
5268 vtop[0] = tmp;
5271 /* rotate n first stack elements to the top
5272 I1 ... In -> In I1 ... I(n-1) [top is right]
5274 void vrott(int n)
5276 int i;
5277 SValue tmp;
5279 tmp = vtop[0];
5280 for(i = 0;i < n - 1; i++)
5281 vtop[-i] = vtop[-i - 1];
5282 vtop[-n + 1] = tmp;
5285 #ifdef TCC_TARGET_ARM
5286 /* like vrott but in other direction
5287 In ... I1 -> I(n-1) ... I1 In [top is right]
5289 void vnrott(int n)
5291 int i;
5292 SValue tmp;
5294 tmp = vtop[-n + 1];
5295 for(i = n - 1; i > 0; i--)
5296 vtop[-i] = vtop[-i + 1];
5297 vtop[0] = tmp;
5299 #endif
5301 /* pop stack value */
5302 void vpop(void)
5304 int v;
5305 v = vtop->r & VT_VALMASK;
5306 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5307 /* for x86, we need to pop the FP stack */
5308 if (v == TREG_ST0 && !nocode_wanted) {
5309 o(0xd9dd); /* fstp %st(1) */
5310 } else
5311 #endif
5312 if (v == VT_JMP || v == VT_JMPI) {
5313 /* need to put correct jump if && or || without test */
5314 gsym(vtop->c.ul);
5316 vtop--;
5319 /* convert stack entry to register and duplicate its value in another
5320 register */
5321 void gv_dup(void)
5323 int rc, t, r, r1;
5324 SValue sv;
5326 t = vtop->type.t;
5327 if ((t & VT_BTYPE) == VT_LLONG) {
5328 lexpand();
5329 gv_dup();
5330 vswap();
5331 vrotb(3);
5332 gv_dup();
5333 vrotb(4);
5334 /* stack: H L L1 H1 */
5335 lbuild(t);
5336 vrotb(3);
5337 vrotb(3);
5338 vswap();
5339 lbuild(t);
5340 vswap();
5341 } else {
5342 /* duplicate value */
5343 rc = RC_INT;
5344 sv.type.t = VT_INT;
5345 if (is_float(t)) {
5346 rc = RC_FLOAT;
5347 #ifdef TCC_TARGET_X86_64
5348 if ((t & VT_BTYPE) == VT_LDOUBLE) {
5349 rc = RC_ST0;
5351 #endif
5352 sv.type.t = t;
5354 r = gv(rc);
5355 r1 = get_reg(rc);
5356 sv.r = r;
5357 sv.c.ul = 0;
5358 load(r1, &sv); /* move r to r1 */
5359 vdup();
5360 /* duplicates value */
5361 vtop->r = r1;
5365 #ifndef TCC_TARGET_X86_64
5366 /* generate CPU independent (unsigned) long long operations */
5367 void gen_opl(int op)
5369 int t, a, b, op1, c, i;
5370 int func;
5371 unsigned short reg_iret = REG_IRET;
5372 unsigned short reg_lret = REG_LRET;
5373 SValue tmp;
5375 switch(op) {
5376 case '/':
5377 case TOK_PDIV:
5378 func = TOK___divdi3;
5379 goto gen_func;
5380 case TOK_UDIV:
5381 func = TOK___udivdi3;
5382 goto gen_func;
5383 case '%':
5384 func = TOK___moddi3;
5385 goto gen_mod_func;
5386 case TOK_UMOD:
5387 func = TOK___umoddi3;
5388 gen_mod_func:
5389 #ifdef TCC_ARM_EABI
5390 reg_iret = TREG_R2;
5391 reg_lret = TREG_R3;
5392 #endif
5393 gen_func:
5394 /* call generic long long function */
5395 vpush_global_sym(&func_old_type, func);
5396 vrott(3);
5397 gfunc_call(2);
5398 vpushi(0);
5399 vtop->r = reg_iret;
5400 vtop->r2 = reg_lret;
5401 break;
5402 case '^':
5403 case '&':
5404 case '|':
5405 case '*':
5406 case '+':
5407 case '-':
5408 t = vtop->type.t;
5409 vswap();
5410 lexpand();
5411 vrotb(3);
5412 lexpand();
5413 /* stack: L1 H1 L2 H2 */
5414 tmp = vtop[0];
5415 vtop[0] = vtop[-3];
5416 vtop[-3] = tmp;
5417 tmp = vtop[-2];
5418 vtop[-2] = vtop[-3];
5419 vtop[-3] = tmp;
5420 vswap();
5421 /* stack: H1 H2 L1 L2 */
5422 if (op == '*') {
5423 vpushv(vtop - 1);
5424 vpushv(vtop - 1);
5425 gen_op(TOK_UMULL);
5426 lexpand();
5427 /* stack: H1 H2 L1 L2 ML MH */
5428 for(i=0;i<4;i++)
5429 vrotb(6);
5430 /* stack: ML MH H1 H2 L1 L2 */
5431 tmp = vtop[0];
5432 vtop[0] = vtop[-2];
5433 vtop[-2] = tmp;
5434 /* stack: ML MH H1 L2 H2 L1 */
5435 gen_op('*');
5436 vrotb(3);
5437 vrotb(3);
5438 gen_op('*');
5439 /* stack: ML MH M1 M2 */
5440 gen_op('+');
5441 gen_op('+');
5442 } else if (op == '+' || op == '-') {
5443 /* XXX: add non carry method too (for MIPS or alpha) */
5444 if (op == '+')
5445 op1 = TOK_ADDC1;
5446 else
5447 op1 = TOK_SUBC1;
5448 gen_op(op1);
5449 /* stack: H1 H2 (L1 op L2) */
5450 vrotb(3);
5451 vrotb(3);
5452 gen_op(op1 + 1); /* TOK_xxxC2 */
5453 } else {
5454 gen_op(op);
5455 /* stack: H1 H2 (L1 op L2) */
5456 vrotb(3);
5457 vrotb(3);
5458 /* stack: (L1 op L2) H1 H2 */
5459 gen_op(op);
5460 /* stack: (L1 op L2) (H1 op H2) */
5462 /* stack: L H */
5463 lbuild(t);
5464 break;
5465 case TOK_SAR:
5466 case TOK_SHR:
5467 case TOK_SHL:
5468 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5469 t = vtop[-1].type.t;
5470 vswap();
5471 lexpand();
5472 vrotb(3);
5473 /* stack: L H shift */
5474 c = (int)vtop->c.i;
5475 /* constant: simpler */
5476 /* NOTE: all comments are for SHL. the other cases are
5477 done by swaping words */
5478 vpop();
5479 if (op != TOK_SHL)
5480 vswap();
5481 if (c >= 32) {
5482 /* stack: L H */
5483 vpop();
5484 if (c > 32) {
5485 vpushi(c - 32);
5486 gen_op(op);
5488 if (op != TOK_SAR) {
5489 vpushi(0);
5490 } else {
5491 gv_dup();
5492 vpushi(31);
5493 gen_op(TOK_SAR);
5495 vswap();
5496 } else {
5497 vswap();
5498 gv_dup();
5499 /* stack: H L L */
5500 vpushi(c);
5501 gen_op(op);
5502 vswap();
5503 vpushi(32 - c);
5504 if (op == TOK_SHL)
5505 gen_op(TOK_SHR);
5506 else
5507 gen_op(TOK_SHL);
5508 vrotb(3);
5509 /* stack: L L H */
5510 vpushi(c);
5511 if (op == TOK_SHL)
5512 gen_op(TOK_SHL);
5513 else
5514 gen_op(TOK_SHR);
5515 gen_op('|');
5517 if (op != TOK_SHL)
5518 vswap();
5519 lbuild(t);
5520 } else {
5521 /* XXX: should provide a faster fallback on x86 ? */
5522 switch(op) {
5523 case TOK_SAR:
5524 func = TOK___ashrdi3;
5525 goto gen_func;
5526 case TOK_SHR:
5527 func = TOK___lshrdi3;
5528 goto gen_func;
5529 case TOK_SHL:
5530 func = TOK___ashldi3;
5531 goto gen_func;
5534 break;
5535 default:
5536 /* compare operations */
5537 t = vtop->type.t;
5538 vswap();
5539 lexpand();
5540 vrotb(3);
5541 lexpand();
5542 /* stack: L1 H1 L2 H2 */
5543 tmp = vtop[-1];
5544 vtop[-1] = vtop[-2];
5545 vtop[-2] = tmp;
5546 /* stack: L1 L2 H1 H2 */
5547 /* compare high */
5548 op1 = op;
5549 /* when values are equal, we need to compare low words. since
5550 the jump is inverted, we invert the test too. */
5551 if (op1 == TOK_LT)
5552 op1 = TOK_LE;
5553 else if (op1 == TOK_GT)
5554 op1 = TOK_GE;
5555 else if (op1 == TOK_ULT)
5556 op1 = TOK_ULE;
5557 else if (op1 == TOK_UGT)
5558 op1 = TOK_UGE;
5559 a = 0;
5560 b = 0;
5561 gen_op(op1);
5562 if (op1 != TOK_NE) {
5563 a = gtst(1, 0);
5565 if (op != TOK_EQ) {
5566 /* generate non equal test */
5567 /* XXX: NOT PORTABLE yet */
5568 if (a == 0) {
5569 b = gtst(0, 0);
5570 } else {
5571 #if defined(TCC_TARGET_I386)
5572 b = psym(0x850f, 0);
5573 #elif defined(TCC_TARGET_ARM)
5574 b = ind;
5575 o(0x1A000000 | encbranch(ind, 0, 1));
5576 #elif defined(TCC_TARGET_C67)
5577 error("not implemented");
5578 #else
5579 #error not supported
5580 #endif
5583 /* compare low. Always unsigned */
5584 op1 = op;
5585 if (op1 == TOK_LT)
5586 op1 = TOK_ULT;
5587 else if (op1 == TOK_LE)
5588 op1 = TOK_ULE;
5589 else if (op1 == TOK_GT)
5590 op1 = TOK_UGT;
5591 else if (op1 == TOK_GE)
5592 op1 = TOK_UGE;
5593 gen_op(op1);
5594 a = gtst(1, a);
5595 gsym(b);
5596 vseti(VT_JMPI, a);
5597 break;
5600 #endif
5602 /* handle integer constant optimizations and various machine
5603 independent opt */
5604 void gen_opic(int op)
5606 int c1, c2, t1, t2, n;
5607 SValue *v1, *v2;
5608 long long l1, l2;
5609 typedef unsigned long long U;
5611 v1 = vtop - 1;
5612 v2 = vtop;
5613 t1 = v1->type.t & VT_BTYPE;
5614 t2 = v2->type.t & VT_BTYPE;
5616 if (t1 == VT_LLONG)
5617 l1 = v1->c.ll;
5618 else if (v1->type.t & VT_UNSIGNED)
5619 l1 = v1->c.ui;
5620 else
5621 l1 = v1->c.i;
5623 if (t2 == VT_LLONG)
5624 l2 = v2->c.ll;
5625 else if (v2->type.t & VT_UNSIGNED)
5626 l2 = v2->c.ui;
5627 else
5628 l2 = v2->c.i;
5630 /* currently, we cannot do computations with forward symbols */
5631 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5632 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5633 if (c1 && c2) {
5634 switch(op) {
5635 case '+': l1 += l2; break;
5636 case '-': l1 -= l2; break;
5637 case '&': l1 &= l2; break;
5638 case '^': l1 ^= l2; break;
5639 case '|': l1 |= l2; break;
5640 case '*': l1 *= l2; break;
5642 case TOK_PDIV:
5643 case '/':
5644 case '%':
5645 case TOK_UDIV:
5646 case TOK_UMOD:
5647 /* if division by zero, generate explicit division */
5648 if (l2 == 0) {
5649 if (const_wanted)
5650 error("division by zero in constant");
5651 goto general_case;
5653 switch(op) {
5654 default: l1 /= l2; break;
5655 case '%': l1 %= l2; break;
5656 case TOK_UDIV: l1 = (U)l1 / l2; break;
5657 case TOK_UMOD: l1 = (U)l1 % l2; break;
5659 break;
5660 case TOK_SHL: l1 <<= l2; break;
5661 case TOK_SHR: l1 = (U)l1 >> l2; break;
5662 case TOK_SAR: l1 >>= l2; break;
5663 /* tests */
5664 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
5665 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
5666 case TOK_EQ: l1 = l1 == l2; break;
5667 case TOK_NE: l1 = l1 != l2; break;
5668 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
5669 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
5670 case TOK_LT: l1 = l1 < l2; break;
5671 case TOK_GE: l1 = l1 >= l2; break;
5672 case TOK_LE: l1 = l1 <= l2; break;
5673 case TOK_GT: l1 = l1 > l2; break;
5674 /* logical */
5675 case TOK_LAND: l1 = l1 && l2; break;
5676 case TOK_LOR: l1 = l1 || l2; break;
5677 default:
5678 goto general_case;
5680 v1->c.ll = l1;
5681 vtop--;
5682 } else {
5683 /* if commutative ops, put c2 as constant */
5684 if (c1 && (op == '+' || op == '&' || op == '^' ||
5685 op == '|' || op == '*')) {
5686 vswap();
5687 c2 = c1; //c = c1, c1 = c2, c2 = c;
5688 l2 = l1; //l = l1, l1 = l2, l2 = l;
5690 /* Filter out NOP operations like x*1, x-0, x&-1... */
5691 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
5692 op == TOK_PDIV) &&
5693 l2 == 1) ||
5694 ((op == '+' || op == '-' || op == '|' || op == '^' ||
5695 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
5696 l2 == 0) ||
5697 (op == '&' &&
5698 l2 == -1))) {
5699 /* nothing to do */
5700 vtop--;
5701 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
5702 /* try to use shifts instead of muls or divs */
5703 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
5704 n = -1;
5705 while (l2) {
5706 l2 >>= 1;
5707 n++;
5709 vtop->c.ll = n;
5710 if (op == '*')
5711 op = TOK_SHL;
5712 else if (op == TOK_PDIV)
5713 op = TOK_SAR;
5714 else
5715 op = TOK_SHR;
5717 goto general_case;
5718 } else if (c2 && (op == '+' || op == '-') &&
5719 ((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) ==
5720 (VT_CONST | VT_SYM) ||
5721 (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
5722 /* symbol + constant case */
5723 if (op == '-')
5724 l2 = -l2;
5725 vtop--;
5726 vtop->c.ll += l2;
5727 } else {
5728 general_case:
5729 if (!nocode_wanted) {
5730 /* call low level op generator */
5731 if (t1 == VT_LLONG || t2 == VT_LLONG)
5732 gen_opl(op);
5733 else
5734 gen_opi(op);
5735 } else {
5736 vtop--;
5742 /* generate a floating point operation with constant propagation */
5743 void gen_opif(int op)
5745 int c1, c2;
5746 SValue *v1, *v2;
5747 long double f1, f2;
5749 v1 = vtop - 1;
5750 v2 = vtop;
5751 /* currently, we cannot do computations with forward symbols */
5752 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5753 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5754 if (c1 && c2) {
5755 if (v1->type.t == VT_FLOAT) {
5756 f1 = v1->c.f;
5757 f2 = v2->c.f;
5758 } else if (v1->type.t == VT_DOUBLE) {
5759 f1 = v1->c.d;
5760 f2 = v2->c.d;
5761 } else {
5762 f1 = v1->c.ld;
5763 f2 = v2->c.ld;
5766 /* NOTE: we only do constant propagation if finite number (not
5767 NaN or infinity) (ANSI spec) */
5768 if (!ieee_finite(f1) || !ieee_finite(f2))
5769 goto general_case;
5771 switch(op) {
5772 case '+': f1 += f2; break;
5773 case '-': f1 -= f2; break;
5774 case '*': f1 *= f2; break;
5775 case '/':
5776 if (f2 == 0.0) {
5777 if (const_wanted)
5778 error("division by zero in constant");
5779 goto general_case;
5781 f1 /= f2;
5782 break;
5783 /* XXX: also handles tests ? */
5784 default:
5785 goto general_case;
5787 /* XXX: overflow test ? */
5788 if (v1->type.t == VT_FLOAT) {
5789 v1->c.f = f1;
5790 } else if (v1->type.t == VT_DOUBLE) {
5791 v1->c.d = f1;
5792 } else {
5793 v1->c.ld = f1;
5795 vtop--;
5796 } else {
5797 general_case:
5798 if (!nocode_wanted) {
5799 gen_opf(op);
5800 } else {
5801 vtop--;
5806 static int pointed_size(CType *type)
5808 int align;
5809 return type_size(pointed_type(type), &align);
5812 static inline int is_null_pointer(SValue *p)
5814 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5815 return 0;
5816 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
5817 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
5820 static inline int is_integer_btype(int bt)
5822 return (bt == VT_BYTE || bt == VT_SHORT ||
5823 bt == VT_INT || bt == VT_LLONG);
5826 /* check types for comparison or substraction of pointers */
5827 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
5829 CType *type1, *type2, tmp_type1, tmp_type2;
5830 int bt1, bt2;
5832 /* null pointers are accepted for all comparisons as gcc */
5833 if (is_null_pointer(p1) || is_null_pointer(p2))
5834 return;
5835 type1 = &p1->type;
5836 type2 = &p2->type;
5837 bt1 = type1->t & VT_BTYPE;
5838 bt2 = type2->t & VT_BTYPE;
5839 /* accept comparison between pointer and integer with a warning */
5840 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
5841 if (op != TOK_LOR && op != TOK_LAND )
5842 warning("comparison between pointer and integer");
5843 return;
5846 /* both must be pointers or implicit function pointers */
5847 if (bt1 == VT_PTR) {
5848 type1 = pointed_type(type1);
5849 } else if (bt1 != VT_FUNC)
5850 goto invalid_operands;
5852 if (bt2 == VT_PTR) {
5853 type2 = pointed_type(type2);
5854 } else if (bt2 != VT_FUNC) {
5855 invalid_operands:
5856 error("invalid operands to binary %s", get_tok_str(op, NULL));
5858 if ((type1->t & VT_BTYPE) == VT_VOID ||
5859 (type2->t & VT_BTYPE) == VT_VOID)
5860 return;
5861 tmp_type1 = *type1;
5862 tmp_type2 = *type2;
5863 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5864 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5865 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
5866 /* gcc-like error if '-' is used */
5867 if (op == '-')
5868 goto invalid_operands;
5869 else
5870 warning("comparison of distinct pointer types lacks a cast");
5874 /* generic gen_op: handles types problems */
5875 void gen_op(int op)
5877 int u, t1, t2, bt1, bt2, t;
5878 CType type1;
5880 t1 = vtop[-1].type.t;
5881 t2 = vtop[0].type.t;
5882 bt1 = t1 & VT_BTYPE;
5883 bt2 = t2 & VT_BTYPE;
5885 if (bt1 == VT_PTR || bt2 == VT_PTR) {
5886 /* at least one operand is a pointer */
5887 /* relationnal op: must be both pointers */
5888 if (op >= TOK_ULT && op <= TOK_LOR) {
5889 check_comparison_pointer_types(vtop - 1, vtop, op);
5890 /* pointers are handled are unsigned */
5891 #ifdef TCC_TARGET_X86_64
5892 t = VT_LLONG | VT_UNSIGNED;
5893 #else
5894 t = VT_INT | VT_UNSIGNED;
5895 #endif
5896 goto std_op;
5898 /* if both pointers, then it must be the '-' op */
5899 if (bt1 == VT_PTR && bt2 == VT_PTR) {
5900 if (op != '-')
5901 error("cannot use pointers here");
5902 check_comparison_pointer_types(vtop - 1, vtop, op);
5903 /* XXX: check that types are compatible */
5904 u = pointed_size(&vtop[-1].type);
5905 gen_opic(op);
5906 /* set to integer type */
5907 #ifdef TCC_TARGET_X86_64
5908 vtop->type.t = VT_LLONG;
5909 #else
5910 vtop->type.t = VT_INT;
5911 #endif
5912 vpushi(u);
5913 gen_op(TOK_PDIV);
5914 } else {
5915 /* exactly one pointer : must be '+' or '-'. */
5916 if (op != '-' && op != '+')
5917 error("cannot use pointers here");
5918 /* Put pointer as first operand */
5919 if (bt2 == VT_PTR) {
5920 vswap();
5921 swap(&t1, &t2);
5923 type1 = vtop[-1].type;
5924 #ifdef TCC_TARGET_X86_64
5925 vpushll(pointed_size(&vtop[-1].type));
5926 #else
5927 /* XXX: cast to int ? (long long case) */
5928 vpushi(pointed_size(&vtop[-1].type));
5929 #endif
5930 gen_op('*');
5931 #ifdef CONFIG_TCC_BCHECK
5932 /* if evaluating constant expression, no code should be
5933 generated, so no bound check */
5934 if (do_bounds_check && !const_wanted) {
5935 /* if bounded pointers, we generate a special code to
5936 test bounds */
5937 if (op == '-') {
5938 vpushi(0);
5939 vswap();
5940 gen_op('-');
5942 gen_bounded_ptr_add();
5943 } else
5944 #endif
5946 gen_opic(op);
5948 /* put again type if gen_opic() swaped operands */
5949 vtop->type = type1;
5951 } else if (is_float(bt1) || is_float(bt2)) {
5952 /* compute bigger type and do implicit casts */
5953 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5954 t = VT_LDOUBLE;
5955 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5956 t = VT_DOUBLE;
5957 } else {
5958 t = VT_FLOAT;
5960 /* floats can only be used for a few operations */
5961 if (op != '+' && op != '-' && op != '*' && op != '/' &&
5962 (op < TOK_ULT || op > TOK_GT))
5963 error("invalid operands for binary operation");
5964 goto std_op;
5965 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5966 /* cast to biggest op */
5967 t = VT_LLONG;
5968 /* convert to unsigned if it does not fit in a long long */
5969 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5970 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5971 t |= VT_UNSIGNED;
5972 goto std_op;
5973 } else {
5974 /* integer operations */
5975 t = VT_INT;
5976 /* convert to unsigned if it does not fit in an integer */
5977 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5978 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5979 t |= VT_UNSIGNED;
5980 std_op:
5981 /* XXX: currently, some unsigned operations are explicit, so
5982 we modify them here */
5983 if (t & VT_UNSIGNED) {
5984 if (op == TOK_SAR)
5985 op = TOK_SHR;
5986 else if (op == '/')
5987 op = TOK_UDIV;
5988 else if (op == '%')
5989 op = TOK_UMOD;
5990 else if (op == TOK_LT)
5991 op = TOK_ULT;
5992 else if (op == TOK_GT)
5993 op = TOK_UGT;
5994 else if (op == TOK_LE)
5995 op = TOK_ULE;
5996 else if (op == TOK_GE)
5997 op = TOK_UGE;
5999 vswap();
6000 type1.t = t;
6001 gen_cast(&type1);
6002 vswap();
6003 /* special case for shifts and long long: we keep the shift as
6004 an integer */
6005 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
6006 type1.t = VT_INT;
6007 gen_cast(&type1);
6008 if (is_float(t))
6009 gen_opif(op);
6010 else
6011 gen_opic(op);
6012 if (op >= TOK_ULT && op <= TOK_GT) {
6013 /* relationnal op: the result is an int */
6014 vtop->type.t = VT_INT;
6015 } else {
6016 vtop->type.t = t;
6021 #ifndef TCC_TARGET_ARM
6022 /* generic itof for unsigned long long case */
6023 void gen_cvt_itof1(int t)
6025 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
6026 (VT_LLONG | VT_UNSIGNED)) {
6028 if (t == VT_FLOAT)
6029 vpush_global_sym(&func_old_type, TOK___floatundisf);
6030 #if LDOUBLE_SIZE != 8
6031 else if (t == VT_LDOUBLE)
6032 vpush_global_sym(&func_old_type, TOK___floatundixf);
6033 #endif
6034 else
6035 vpush_global_sym(&func_old_type, TOK___floatundidf);
6036 vrott(2);
6037 gfunc_call(1);
6038 vpushi(0);
6039 vtop->r = reg_fret(t);
6040 } else {
6041 gen_cvt_itof(t);
6044 #endif
6046 /* generic ftoi for unsigned long long case */
6047 void gen_cvt_ftoi1(int t)
6049 int st;
6051 if (t == (VT_LLONG | VT_UNSIGNED)) {
6052 /* not handled natively */
6053 st = vtop->type.t & VT_BTYPE;
6054 if (st == VT_FLOAT)
6055 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
6056 #if LDOUBLE_SIZE != 8
6057 else if (st == VT_LDOUBLE)
6058 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
6059 #endif
6060 else
6061 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
6062 vrott(2);
6063 gfunc_call(1);
6064 vpushi(0);
6065 vtop->r = REG_IRET;
6066 vtop->r2 = REG_LRET;
6067 } else {
6068 gen_cvt_ftoi(t);
6072 /* force char or short cast */
6073 void force_charshort_cast(int t)
6075 int bits, dbt;
6076 dbt = t & VT_BTYPE;
6077 /* XXX: add optimization if lvalue : just change type and offset */
6078 if (dbt == VT_BYTE)
6079 bits = 8;
6080 else
6081 bits = 16;
6082 if (t & VT_UNSIGNED) {
6083 vpushi((1 << bits) - 1);
6084 gen_op('&');
6085 } else {
6086 bits = 32 - bits;
6087 vpushi(bits);
6088 gen_op(TOK_SHL);
6089 /* result must be signed or the SAR is converted to an SHL
6090 This was not the case when "t" was a signed short
6091 and the last value on the stack was an unsigned int */
6092 vtop->type.t &= ~VT_UNSIGNED;
6093 vpushi(bits);
6094 gen_op(TOK_SAR);
6098 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6099 static void gen_cast(CType *type)
6101 int sbt, dbt, sf, df, c, p;
6103 /* special delayed cast for char/short */
6104 /* XXX: in some cases (multiple cascaded casts), it may still
6105 be incorrect */
6106 if (vtop->r & VT_MUSTCAST) {
6107 vtop->r &= ~VT_MUSTCAST;
6108 force_charshort_cast(vtop->type.t);
6111 /* bitfields first get cast to ints */
6112 if (vtop->type.t & VT_BITFIELD) {
6113 gv(RC_INT);
6116 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
6117 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
6119 if (sbt != dbt) {
6120 sf = is_float(sbt);
6121 df = is_float(dbt);
6122 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
6123 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
6124 if (c) {
6125 /* constant case: we can do it now */
6126 /* XXX: in ISOC, cannot do it if error in convert */
6127 if (sbt == VT_FLOAT)
6128 vtop->c.ld = vtop->c.f;
6129 else if (sbt == VT_DOUBLE)
6130 vtop->c.ld = vtop->c.d;
6132 if (df) {
6133 if ((sbt & VT_BTYPE) == VT_LLONG) {
6134 if (sbt & VT_UNSIGNED)
6135 vtop->c.ld = vtop->c.ull;
6136 else
6137 vtop->c.ld = vtop->c.ll;
6138 } else if(!sf) {
6139 if (sbt & VT_UNSIGNED)
6140 vtop->c.ld = vtop->c.ui;
6141 else
6142 vtop->c.ld = vtop->c.i;
6145 if (dbt == VT_FLOAT)
6146 vtop->c.f = (float)vtop->c.ld;
6147 else if (dbt == VT_DOUBLE)
6148 vtop->c.d = (double)vtop->c.ld;
6149 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
6150 vtop->c.ull = (unsigned long long)vtop->c.ld;
6151 } else if (sf && dbt == VT_BOOL) {
6152 vtop->c.i = (vtop->c.ld != 0);
6153 } else {
6154 if(sf)
6155 vtop->c.ll = (long long)vtop->c.ld;
6156 else if (sbt == (VT_LLONG|VT_UNSIGNED))
6157 vtop->c.ll = vtop->c.ull;
6158 else if (sbt & VT_UNSIGNED)
6159 vtop->c.ll = vtop->c.ui;
6160 else if (sbt != VT_LLONG)
6161 vtop->c.ll = vtop->c.i;
6163 if (dbt == (VT_LLONG|VT_UNSIGNED))
6164 vtop->c.ull = vtop->c.ll;
6165 else if (dbt == VT_BOOL)
6166 vtop->c.i = (vtop->c.ll != 0);
6167 else if (dbt != VT_LLONG) {
6168 int s = 0;
6169 if ((dbt & VT_BTYPE) == VT_BYTE)
6170 s = 24;
6171 else if ((dbt & VT_BTYPE) == VT_SHORT)
6172 s = 16;
6174 if(dbt & VT_UNSIGNED)
6175 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
6176 else
6177 vtop->c.i = ((int)vtop->c.ll << s) >> s;
6180 } else if (p && dbt == VT_BOOL) {
6181 vtop->r = VT_CONST;
6182 vtop->c.i = 1;
6183 } else if (!nocode_wanted) {
6184 /* non constant case: generate code */
6185 if (sf && df) {
6186 /* convert from fp to fp */
6187 gen_cvt_ftof(dbt);
6188 } else if (df) {
6189 /* convert int to fp */
6190 gen_cvt_itof1(dbt);
6191 } else if (sf) {
6192 /* convert fp to int */
6193 if (dbt == VT_BOOL) {
6194 vpushi(0);
6195 gen_op(TOK_NE);
6196 } else {
6197 /* we handle char/short/etc... with generic code */
6198 if (dbt != (VT_INT | VT_UNSIGNED) &&
6199 dbt != (VT_LLONG | VT_UNSIGNED) &&
6200 dbt != VT_LLONG)
6201 dbt = VT_INT;
6202 gen_cvt_ftoi1(dbt);
6203 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
6204 /* additional cast for char/short... */
6205 vtop->type.t = dbt;
6206 gen_cast(type);
6209 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
6210 if ((sbt & VT_BTYPE) != VT_LLONG) {
6211 /* scalar to long long */
6212 #ifndef TCC_TARGET_X86_64
6213 /* machine independent conversion */
6214 gv(RC_INT);
6215 /* generate high word */
6216 if (sbt == (VT_INT | VT_UNSIGNED)) {
6217 vpushi(0);
6218 gv(RC_INT);
6219 } else {
6220 gv_dup();
6221 vpushi(31);
6222 gen_op(TOK_SAR);
6224 /* patch second register */
6225 vtop[-1].r2 = vtop->r;
6226 vpop();
6227 #else
6228 int r = gv(RC_INT);
6229 if (sbt != (VT_INT | VT_UNSIGNED)) {
6230 /* x86_64 specific: movslq */
6231 o(0x6348);
6232 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
6234 #endif
6236 } else if (dbt == VT_BOOL) {
6237 /* scalar to bool */
6238 vpushi(0);
6239 gen_op(TOK_NE);
6240 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
6241 (dbt & VT_BTYPE) == VT_SHORT) {
6242 if (sbt == VT_PTR) {
6243 vtop->type.t = VT_INT;
6244 warning("nonportable conversion from pointer to char/short");
6246 force_charshort_cast(dbt);
6247 } else if ((dbt & VT_BTYPE) == VT_INT) {
6248 /* scalar to int */
6249 if (sbt == VT_LLONG) {
6250 /* from long long: just take low order word */
6251 lexpand();
6252 vpop();
6254 /* if lvalue and single word type, nothing to do because
6255 the lvalue already contains the real type size (see
6256 VT_LVAL_xxx constants) */
6259 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
6260 /* if we are casting between pointer types,
6261 we must update the VT_LVAL_xxx size */
6262 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
6263 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
6265 vtop->type = *type;
6268 /* return type size. Put alignment at 'a' */
6269 static int type_size(CType *type, int *a)
6271 Sym *s;
6272 int bt;
6274 bt = type->t & VT_BTYPE;
6275 if (bt == VT_STRUCT) {
6276 /* struct/union */
6277 s = type->ref;
6278 *a = s->r;
6279 return s->c;
6280 } else if (bt == VT_PTR) {
6281 if (type->t & VT_ARRAY) {
6282 int ts;
6284 s = type->ref;
6285 ts = type_size(&s->type, a);
6287 if (ts < 0 && s->c < 0)
6288 ts = -ts;
6290 return ts * s->c;
6291 } else {
6292 *a = PTR_SIZE;
6293 return PTR_SIZE;
6295 } else if (bt == VT_LDOUBLE) {
6296 *a = LDOUBLE_ALIGN;
6297 return LDOUBLE_SIZE;
6298 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
6299 #ifdef TCC_TARGET_I386
6300 #ifdef TCC_TARGET_PE
6301 *a = 8;
6302 #else
6303 *a = 4;
6304 #endif
6305 #elif defined(TCC_TARGET_ARM)
6306 #ifdef TCC_ARM_EABI
6307 *a = 8;
6308 #else
6309 *a = 4;
6310 #endif
6311 #else
6312 *a = 8;
6313 #endif
6314 return 8;
6315 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
6316 *a = 4;
6317 return 4;
6318 } else if (bt == VT_SHORT) {
6319 *a = 2;
6320 return 2;
6321 } else {
6322 /* char, void, function, _Bool */
6323 *a = 1;
6324 return 1;
6328 /* return the pointed type of t */
6329 static inline CType *pointed_type(CType *type)
6331 return &type->ref->type;
6334 /* modify type so that its it is a pointer to type. */
6335 static void mk_pointer(CType *type)
6337 Sym *s;
6338 s = sym_push(SYM_FIELD, type, 0, -1);
6339 type->t = VT_PTR | (type->t & ~VT_TYPE);
6340 type->ref = s;
6343 /* compare function types. OLD functions match any new functions */
6344 static int is_compatible_func(CType *type1, CType *type2)
6346 Sym *s1, *s2;
6348 s1 = type1->ref;
6349 s2 = type2->ref;
6350 if (!is_compatible_types(&s1->type, &s2->type))
6351 return 0;
6352 /* check func_call */
6353 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
6354 return 0;
6355 /* XXX: not complete */
6356 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
6357 return 1;
6358 if (s1->c != s2->c)
6359 return 0;
6360 while (s1 != NULL) {
6361 if (s2 == NULL)
6362 return 0;
6363 if (!is_compatible_parameter_types(&s1->type, &s2->type))
6364 return 0;
6365 s1 = s1->next;
6366 s2 = s2->next;
6368 if (s2)
6369 return 0;
6370 return 1;
6373 /* return true if type1 and type2 are the same. If unqualified is
6374 true, qualifiers on the types are ignored.
6376 - enums are not checked as gcc __builtin_types_compatible_p ()
6378 static int compare_types(CType *type1, CType *type2, int unqualified)
6380 int bt1, t1, t2;
6382 t1 = type1->t & VT_TYPE;
6383 t2 = type2->t & VT_TYPE;
6384 if (unqualified) {
6385 /* strip qualifiers before comparing */
6386 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
6387 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
6389 /* XXX: bitfields ? */
6390 if (t1 != t2)
6391 return 0;
6392 /* test more complicated cases */
6393 bt1 = t1 & VT_BTYPE;
6394 if (bt1 == VT_PTR) {
6395 type1 = pointed_type(type1);
6396 type2 = pointed_type(type2);
6397 return is_compatible_types(type1, type2);
6398 } else if (bt1 == VT_STRUCT) {
6399 return (type1->ref == type2->ref);
6400 } else if (bt1 == VT_FUNC) {
6401 return is_compatible_func(type1, type2);
6402 } else {
6403 return 1;
6407 /* return true if type1 and type2 are exactly the same (including
6408 qualifiers).
6410 static int is_compatible_types(CType *type1, CType *type2)
6412 return compare_types(type1,type2,0);
6415 /* return true if type1 and type2 are the same (ignoring qualifiers).
6417 static int is_compatible_parameter_types(CType *type1, CType *type2)
6419 return compare_types(type1,type2,1);
6422 /* print a type. If 'varstr' is not NULL, then the variable is also
6423 printed in the type */
6424 /* XXX: union */
6425 /* XXX: add array and function pointers */
6426 void type_to_str(char *buf, int buf_size,
6427 CType *type, const char *varstr)
6429 int bt, v, t;
6430 Sym *s, *sa;
6431 char buf1[256];
6432 const char *tstr;
6434 t = type->t & VT_TYPE;
6435 bt = t & VT_BTYPE;
6436 buf[0] = '\0';
6437 if (t & VT_CONSTANT)
6438 pstrcat(buf, buf_size, "const ");
6439 if (t & VT_VOLATILE)
6440 pstrcat(buf, buf_size, "volatile ");
6441 if (t & VT_UNSIGNED)
6442 pstrcat(buf, buf_size, "unsigned ");
6443 switch(bt) {
6444 case VT_VOID:
6445 tstr = "void";
6446 goto add_tstr;
6447 case VT_BOOL:
6448 tstr = "_Bool";
6449 goto add_tstr;
6450 case VT_BYTE:
6451 tstr = "char";
6452 goto add_tstr;
6453 case VT_SHORT:
6454 tstr = "short";
6455 goto add_tstr;
6456 case VT_INT:
6457 tstr = "int";
6458 goto add_tstr;
6459 case VT_LONG:
6460 tstr = "long";
6461 goto add_tstr;
6462 case VT_LLONG:
6463 tstr = "long long";
6464 goto add_tstr;
6465 case VT_FLOAT:
6466 tstr = "float";
6467 goto add_tstr;
6468 case VT_DOUBLE:
6469 tstr = "double";
6470 goto add_tstr;
6471 case VT_LDOUBLE:
6472 tstr = "long double";
6473 add_tstr:
6474 pstrcat(buf, buf_size, tstr);
6475 break;
6476 case VT_ENUM:
6477 case VT_STRUCT:
6478 if (bt == VT_STRUCT)
6479 tstr = "struct ";
6480 else
6481 tstr = "enum ";
6482 pstrcat(buf, buf_size, tstr);
6483 v = type->ref->v & ~SYM_STRUCT;
6484 if (v >= SYM_FIRST_ANOM)
6485 pstrcat(buf, buf_size, "<anonymous>");
6486 else
6487 pstrcat(buf, buf_size, get_tok_str(v, NULL));
6488 break;
6489 case VT_FUNC:
6490 s = type->ref;
6491 type_to_str(buf, buf_size, &s->type, varstr);
6492 pstrcat(buf, buf_size, "(");
6493 sa = s->next;
6494 while (sa != NULL) {
6495 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
6496 pstrcat(buf, buf_size, buf1);
6497 sa = sa->next;
6498 if (sa)
6499 pstrcat(buf, buf_size, ", ");
6501 pstrcat(buf, buf_size, ")");
6502 goto no_var;
6503 case VT_PTR:
6504 s = type->ref;
6505 pstrcpy(buf1, sizeof(buf1), "*");
6506 if (varstr)
6507 pstrcat(buf1, sizeof(buf1), varstr);
6508 type_to_str(buf, buf_size, &s->type, buf1);
6509 goto no_var;
6511 if (varstr) {
6512 pstrcat(buf, buf_size, " ");
6513 pstrcat(buf, buf_size, varstr);
6515 no_var: ;
6518 /* verify type compatibility to store vtop in 'dt' type, and generate
6519 casts if needed. */
6520 static void gen_assign_cast(CType *dt)
6522 CType *st, *type1, *type2, tmp_type1, tmp_type2;
6523 char buf1[256], buf2[256];
6524 int dbt, sbt;
6526 st = &vtop->type; /* source type */
6527 dbt = dt->t & VT_BTYPE;
6528 sbt = st->t & VT_BTYPE;
6529 if (dt->t & VT_CONSTANT)
6530 warning("assignment of read-only location");
6531 switch(dbt) {
6532 case VT_PTR:
6533 /* special cases for pointers */
6534 /* '0' can also be a pointer */
6535 if (is_null_pointer(vtop))
6536 goto type_ok;
6537 /* accept implicit pointer to integer cast with warning */
6538 if (is_integer_btype(sbt)) {
6539 warning("assignment makes pointer from integer without a cast");
6540 goto type_ok;
6542 type1 = pointed_type(dt);
6543 /* a function is implicitely a function pointer */
6544 if (sbt == VT_FUNC) {
6545 if ((type1->t & VT_BTYPE) != VT_VOID &&
6546 !is_compatible_types(pointed_type(dt), st))
6547 goto error;
6548 else
6549 goto type_ok;
6551 if (sbt != VT_PTR)
6552 goto error;
6553 type2 = pointed_type(st);
6554 if ((type1->t & VT_BTYPE) == VT_VOID ||
6555 (type2->t & VT_BTYPE) == VT_VOID) {
6556 /* void * can match anything */
6557 } else {
6558 /* exact type match, except for unsigned */
6559 tmp_type1 = *type1;
6560 tmp_type2 = *type2;
6561 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6562 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6563 if (!is_compatible_types(&tmp_type1, &tmp_type2))
6564 warning("assignment from incompatible pointer type");
6566 /* check const and volatile */
6567 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
6568 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
6569 warning("assignment discards qualifiers from pointer target type");
6570 break;
6571 case VT_BYTE:
6572 case VT_SHORT:
6573 case VT_INT:
6574 case VT_LLONG:
6575 if (sbt == VT_PTR || sbt == VT_FUNC) {
6576 warning("assignment makes integer from pointer without a cast");
6578 /* XXX: more tests */
6579 break;
6580 case VT_STRUCT:
6581 tmp_type1 = *dt;
6582 tmp_type2 = *st;
6583 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
6584 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
6585 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
6586 error:
6587 type_to_str(buf1, sizeof(buf1), st, NULL);
6588 type_to_str(buf2, sizeof(buf2), dt, NULL);
6589 error("cannot cast '%s' to '%s'", buf1, buf2);
6591 break;
6593 type_ok:
6594 gen_cast(dt);
6597 /* store vtop in lvalue pushed on stack */
6598 void vstore(void)
6600 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
6602 ft = vtop[-1].type.t;
6603 sbt = vtop->type.t & VT_BTYPE;
6604 dbt = ft & VT_BTYPE;
6605 if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
6606 (sbt == VT_INT && dbt == VT_SHORT)) {
6607 /* optimize char/short casts */
6608 delayed_cast = VT_MUSTCAST;
6609 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
6610 /* XXX: factorize */
6611 if (ft & VT_CONSTANT)
6612 warning("assignment of read-only location");
6613 } else {
6614 delayed_cast = 0;
6615 if (!(ft & VT_BITFIELD))
6616 gen_assign_cast(&vtop[-1].type);
6619 if (sbt == VT_STRUCT) {
6620 /* if structure, only generate pointer */
6621 /* structure assignment : generate memcpy */
6622 /* XXX: optimize if small size */
6623 if (!nocode_wanted) {
6624 size = type_size(&vtop->type, &align);
6626 #ifdef TCC_ARM_EABI
6627 if(!(align & 7))
6628 vpush_global_sym(&func_old_type, TOK_memcpy8);
6629 else if(!(align & 3))
6630 vpush_global_sym(&func_old_type, TOK_memcpy4);
6631 else
6632 #endif
6633 vpush_global_sym(&func_old_type, TOK_memcpy);
6635 /* destination */
6636 vpushv(vtop - 2);
6637 vtop->type.t = VT_INT;
6638 gaddrof();
6639 /* source */
6640 vpushv(vtop - 2);
6641 vtop->type.t = VT_INT;
6642 gaddrof();
6643 /* type size */
6644 vpushi(size);
6645 gfunc_call(3);
6647 vswap();
6648 vpop();
6649 } else {
6650 vswap();
6651 vpop();
6653 /* leave source on stack */
6654 } else if (ft & VT_BITFIELD) {
6655 /* bitfield store handling */
6656 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
6657 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
6658 /* remove bit field info to avoid loops */
6659 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
6661 /* duplicate source into other register */
6662 gv_dup();
6663 vswap();
6664 vrott(3);
6666 if((ft & VT_BTYPE) == VT_BOOL) {
6667 gen_cast(&vtop[-1].type);
6668 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
6671 /* duplicate destination */
6672 vdup();
6673 vtop[-1] = vtop[-2];
6675 /* mask and shift source */
6676 if((ft & VT_BTYPE) != VT_BOOL) {
6677 if((ft & VT_BTYPE) == VT_LLONG) {
6678 vpushll((1ULL << bit_size) - 1ULL);
6679 } else {
6680 vpushi((1 << bit_size) - 1);
6682 gen_op('&');
6684 vpushi(bit_pos);
6685 gen_op(TOK_SHL);
6686 /* load destination, mask and or with source */
6687 vswap();
6688 if((ft & VT_BTYPE) == VT_LLONG) {
6689 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
6690 } else {
6691 vpushi(~(((1 << bit_size) - 1) << bit_pos));
6693 gen_op('&');
6694 gen_op('|');
6695 /* store result */
6696 vstore();
6698 /* pop off shifted source from "duplicate source..." above */
6699 vpop();
6701 } else {
6702 #ifdef CONFIG_TCC_BCHECK
6703 /* bound check case */
6704 if (vtop[-1].r & VT_MUSTBOUND) {
6705 vswap();
6706 gbound();
6707 vswap();
6709 #endif
6710 if (!nocode_wanted) {
6711 rc = RC_INT;
6712 if (is_float(ft)) {
6713 rc = RC_FLOAT;
6714 #ifdef TCC_TARGET_X86_64
6715 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
6716 rc = RC_ST0;
6718 #endif
6720 r = gv(rc); /* generate value */
6721 /* if lvalue was saved on stack, must read it */
6722 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
6723 SValue sv;
6724 t = get_reg(RC_INT);
6725 #ifdef TCC_TARGET_X86_64
6726 sv.type.t = VT_PTR;
6727 #else
6728 sv.type.t = VT_INT;
6729 #endif
6730 sv.r = VT_LOCAL | VT_LVAL;
6731 sv.c.ul = vtop[-1].c.ul;
6732 load(t, &sv);
6733 vtop[-1].r = t | VT_LVAL;
6735 store(r, vtop - 1);
6736 #ifndef TCC_TARGET_X86_64
6737 /* two word case handling : store second register at word + 4 */
6738 if ((ft & VT_BTYPE) == VT_LLONG) {
6739 vswap();
6740 /* convert to int to increment easily */
6741 vtop->type.t = VT_INT;
6742 gaddrof();
6743 vpushi(4);
6744 gen_op('+');
6745 vtop->r |= VT_LVAL;
6746 vswap();
6747 /* XXX: it works because r2 is spilled last ! */
6748 store(vtop->r2, vtop - 1);
6750 #endif
6752 vswap();
6753 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
6754 vtop->r |= delayed_cast;
6758 /* post defines POST/PRE add. c is the token ++ or -- */
6759 void inc(int post, int c)
6761 test_lvalue();
6762 vdup(); /* save lvalue */
6763 if (post) {
6764 gv_dup(); /* duplicate value */
6765 vrotb(3);
6766 vrotb(3);
6768 /* add constant */
6769 vpushi(c - TOK_MID);
6770 gen_op('+');
6771 vstore(); /* store value */
6772 if (post)
6773 vpop(); /* if post op, return saved value */
6776 /* Parse GNUC __attribute__ extension. Currently, the following
6777 extensions are recognized:
6778 - aligned(n) : set data/function alignment.
6779 - packed : force data alignment to 1
6780 - section(x) : generate data/code in this section.
6781 - unused : currently ignored, but may be used someday.
6782 - regparm(n) : pass function parameters in registers (i386 only)
6784 static void parse_attribute(AttributeDef *ad)
6786 int t, n;
6788 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
6789 next();
6790 skip('(');
6791 skip('(');
6792 while (tok != ')') {
6793 if (tok < TOK_IDENT)
6794 expect("attribute name");
6795 t = tok;
6796 next();
6797 switch(t) {
6798 case TOK_SECTION1:
6799 case TOK_SECTION2:
6800 skip('(');
6801 if (tok != TOK_STR)
6802 expect("section name");
6803 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
6804 next();
6805 skip(')');
6806 break;
6807 case TOK_ALIGNED1:
6808 case TOK_ALIGNED2:
6809 if (tok == '(') {
6810 next();
6811 n = expr_const();
6812 if (n <= 0 || (n & (n - 1)) != 0)
6813 error("alignment must be a positive power of two");
6814 skip(')');
6815 } else {
6816 n = MAX_ALIGN;
6818 ad->aligned = n;
6819 break;
6820 case TOK_PACKED1:
6821 case TOK_PACKED2:
6822 ad->packed = 1;
6823 break;
6824 case TOK_UNUSED1:
6825 case TOK_UNUSED2:
6826 /* currently, no need to handle it because tcc does not
6827 track unused objects */
6828 break;
6829 case TOK_NORETURN1:
6830 case TOK_NORETURN2:
6831 /* currently, no need to handle it because tcc does not
6832 track unused objects */
6833 break;
6834 case TOK_CDECL1:
6835 case TOK_CDECL2:
6836 case TOK_CDECL3:
6837 FUNC_CALL(ad->func_attr) = FUNC_CDECL;
6838 break;
6839 case TOK_STDCALL1:
6840 case TOK_STDCALL2:
6841 case TOK_STDCALL3:
6842 FUNC_CALL(ad->func_attr) = FUNC_STDCALL;
6843 break;
6844 #ifdef TCC_TARGET_I386
6845 case TOK_REGPARM1:
6846 case TOK_REGPARM2:
6847 skip('(');
6848 n = expr_const();
6849 if (n > 3)
6850 n = 3;
6851 else if (n < 0)
6852 n = 0;
6853 if (n > 0)
6854 FUNC_CALL(ad->func_attr) = FUNC_FASTCALL1 + n - 1;
6855 skip(')');
6856 break;
6857 case TOK_FASTCALL1:
6858 case TOK_FASTCALL2:
6859 case TOK_FASTCALL3:
6860 FUNC_CALL(ad->func_attr) = FUNC_FASTCALLW;
6861 break;
6862 #endif
6863 case TOK_DLLEXPORT:
6864 FUNC_EXPORT(ad->func_attr) = 1;
6865 break;
6866 default:
6867 if (tcc_state->warn_unsupported)
6868 warning("'%s' attribute ignored", get_tok_str(t, NULL));
6869 /* skip parameters */
6870 if (tok == '(') {
6871 int parenthesis = 0;
6872 do {
6873 if (tok == '(')
6874 parenthesis++;
6875 else if (tok == ')')
6876 parenthesis--;
6877 next();
6878 } while (parenthesis && tok != -1);
6880 break;
6882 if (tok != ',')
6883 break;
6884 next();
6886 skip(')');
6887 skip(')');
6891 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6892 static void struct_decl(CType *type, int u)
6894 int a, v, size, align, maxalign, c, offset;
6895 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
6896 Sym *s, *ss, *ass, **ps;
6897 AttributeDef ad;
6898 CType type1, btype;
6900 a = tok; /* save decl type */
6901 next();
6902 if (tok != '{') {
6903 v = tok;
6904 next();
6905 /* struct already defined ? return it */
6906 if (v < TOK_IDENT)
6907 expect("struct/union/enum name");
6908 s = struct_find(v);
6909 if (s) {
6910 if (s->type.t != a)
6911 error("invalid type");
6912 goto do_decl;
6914 } else {
6915 v = anon_sym++;
6917 type1.t = a;
6918 /* we put an undefined size for struct/union */
6919 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
6920 s->r = 0; /* default alignment is zero as gcc */
6921 /* put struct/union/enum name in type */
6922 do_decl:
6923 type->t = u;
6924 type->ref = s;
6926 if (tok == '{') {
6927 next();
6928 if (s->c != -1)
6929 error("struct/union/enum already defined");
6930 /* cannot be empty */
6931 c = 0;
6932 /* non empty enums are not allowed */
6933 if (a == TOK_ENUM) {
6934 for(;;) {
6935 v = tok;
6936 if (v < TOK_UIDENT)
6937 expect("identifier");
6938 next();
6939 if (tok == '=') {
6940 next();
6941 c = expr_const();
6943 /* enum symbols have static storage */
6944 ss = sym_push(v, &int_type, VT_CONST, c);
6945 ss->type.t |= VT_STATIC;
6946 if (tok != ',')
6947 break;
6948 next();
6949 c++;
6950 /* NOTE: we accept a trailing comma */
6951 if (tok == '}')
6952 break;
6954 skip('}');
6955 } else {
6956 maxalign = 1;
6957 ps = &s->next;
6958 prevbt = VT_INT;
6959 bit_pos = 0;
6960 offset = 0;
6961 while (tok != '}') {
6962 parse_btype(&btype, &ad);
6963 while (1) {
6964 bit_size = -1;
6965 v = 0;
6966 type1 = btype;
6967 if (tok != ':') {
6968 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
6969 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
6970 expect("identifier");
6971 if ((type1.t & VT_BTYPE) == VT_FUNC ||
6972 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
6973 error("invalid type for '%s'",
6974 get_tok_str(v, NULL));
6976 if (tok == ':') {
6977 next();
6978 bit_size = expr_const();
6979 /* XXX: handle v = 0 case for messages */
6980 if (bit_size < 0)
6981 error("negative width in bit-field '%s'",
6982 get_tok_str(v, NULL));
6983 if (v && bit_size == 0)
6984 error("zero width for bit-field '%s'",
6985 get_tok_str(v, NULL));
6987 size = type_size(&type1, &align);
6988 if (ad.aligned) {
6989 if (align < ad.aligned)
6990 align = ad.aligned;
6991 } else if (ad.packed) {
6992 align = 1;
6993 } else if (*tcc_state->pack_stack_ptr) {
6994 if (align > *tcc_state->pack_stack_ptr)
6995 align = *tcc_state->pack_stack_ptr;
6997 lbit_pos = 0;
6998 if (bit_size >= 0) {
6999 bt = type1.t & VT_BTYPE;
7000 if (bt != VT_INT &&
7001 bt != VT_BYTE &&
7002 bt != VT_SHORT &&
7003 bt != VT_BOOL &&
7004 bt != VT_ENUM &&
7005 bt != VT_LLONG)
7006 error("bitfields must have scalar type");
7007 bsize = size * 8;
7008 if (bit_size > bsize) {
7009 error("width of '%s' exceeds its type",
7010 get_tok_str(v, NULL));
7011 } else if (bit_size == bsize) {
7012 /* no need for bit fields */
7013 bit_pos = 0;
7014 } else if (bit_size == 0) {
7015 /* XXX: what to do if only padding in a
7016 structure ? */
7017 /* zero size: means to pad */
7018 bit_pos = 0;
7019 } else {
7020 /* we do not have enough room ?
7021 did the type change?
7022 is it a union? */
7023 if ((bit_pos + bit_size) > bsize ||
7024 bt != prevbt || a == TOK_UNION)
7025 bit_pos = 0;
7026 lbit_pos = bit_pos;
7027 /* XXX: handle LSB first */
7028 type1.t |= VT_BITFIELD |
7029 (bit_pos << VT_STRUCT_SHIFT) |
7030 (bit_size << (VT_STRUCT_SHIFT + 6));
7031 bit_pos += bit_size;
7033 prevbt = bt;
7034 } else {
7035 bit_pos = 0;
7037 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
7038 /* add new memory data only if starting
7039 bit field */
7040 if (lbit_pos == 0) {
7041 if (a == TOK_STRUCT) {
7042 c = (c + align - 1) & -align;
7043 offset = c;
7044 if (size > 0)
7045 c += size;
7046 } else {
7047 offset = 0;
7048 if (size > c)
7049 c = size;
7051 if (align > maxalign)
7052 maxalign = align;
7054 #if 0
7055 printf("add field %s offset=%d",
7056 get_tok_str(v, NULL), offset);
7057 if (type1.t & VT_BITFIELD) {
7058 printf(" pos=%d size=%d",
7059 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
7060 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
7062 printf("\n");
7063 #endif
7065 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
7066 ass = type1.ref;
7067 while ((ass = ass->next) != NULL) {
7068 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
7069 *ps = ss;
7070 ps = &ss->next;
7072 } else if (v) {
7073 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
7074 *ps = ss;
7075 ps = &ss->next;
7077 if (tok == ';' || tok == TOK_EOF)
7078 break;
7079 skip(',');
7081 skip(';');
7083 skip('}');
7084 /* store size and alignment */
7085 s->c = (c + maxalign - 1) & -maxalign;
7086 s->r = maxalign;
7091 /* return 0 if no type declaration. otherwise, return the basic type
7092 and skip it.
7094 static int parse_btype(CType *type, AttributeDef *ad)
7096 int t, u, type_found, typespec_found, typedef_found;
7097 Sym *s;
7098 CType type1;
7100 memset(ad, 0, sizeof(AttributeDef));
7101 type_found = 0;
7102 typespec_found = 0;
7103 typedef_found = 0;
7104 t = 0;
7105 while(1) {
7106 switch(tok) {
7107 case TOK_EXTENSION:
7108 /* currently, we really ignore extension */
7109 next();
7110 continue;
7112 /* basic types */
7113 case TOK_CHAR:
7114 u = VT_BYTE;
7115 basic_type:
7116 next();
7117 basic_type1:
7118 if ((t & VT_BTYPE) != 0)
7119 error("too many basic types");
7120 t |= u;
7121 typespec_found = 1;
7122 break;
7123 case TOK_VOID:
7124 u = VT_VOID;
7125 goto basic_type;
7126 case TOK_SHORT:
7127 u = VT_SHORT;
7128 goto basic_type;
7129 case TOK_INT:
7130 next();
7131 typespec_found = 1;
7132 break;
7133 case TOK_LONG:
7134 next();
7135 if ((t & VT_BTYPE) == VT_DOUBLE) {
7136 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7137 } else if ((t & VT_BTYPE) == VT_LONG) {
7138 t = (t & ~VT_BTYPE) | VT_LLONG;
7139 } else {
7140 u = VT_LONG;
7141 goto basic_type1;
7143 break;
7144 case TOK_BOOL:
7145 u = VT_BOOL;
7146 goto basic_type;
7147 case TOK_FLOAT:
7148 u = VT_FLOAT;
7149 goto basic_type;
7150 case TOK_DOUBLE:
7151 next();
7152 if ((t & VT_BTYPE) == VT_LONG) {
7153 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7154 } else {
7155 u = VT_DOUBLE;
7156 goto basic_type1;
7158 break;
7159 case TOK_ENUM:
7160 struct_decl(&type1, VT_ENUM);
7161 basic_type2:
7162 u = type1.t;
7163 type->ref = type1.ref;
7164 goto basic_type1;
7165 case TOK_STRUCT:
7166 case TOK_UNION:
7167 struct_decl(&type1, VT_STRUCT);
7168 goto basic_type2;
7170 /* type modifiers */
7171 case TOK_CONST1:
7172 case TOK_CONST2:
7173 case TOK_CONST3:
7174 t |= VT_CONSTANT;
7175 next();
7176 break;
7177 case TOK_VOLATILE1:
7178 case TOK_VOLATILE2:
7179 case TOK_VOLATILE3:
7180 t |= VT_VOLATILE;
7181 next();
7182 break;
7183 case TOK_SIGNED1:
7184 case TOK_SIGNED2:
7185 case TOK_SIGNED3:
7186 typespec_found = 1;
7187 t |= VT_SIGNED;
7188 next();
7189 break;
7190 case TOK_REGISTER:
7191 case TOK_AUTO:
7192 case TOK_RESTRICT1:
7193 case TOK_RESTRICT2:
7194 case TOK_RESTRICT3:
7195 next();
7196 break;
7197 case TOK_UNSIGNED:
7198 t |= VT_UNSIGNED;
7199 next();
7200 typespec_found = 1;
7201 break;
7203 /* storage */
7204 case TOK_EXTERN:
7205 t |= VT_EXTERN;
7206 next();
7207 break;
7208 case TOK_STATIC:
7209 t |= VT_STATIC;
7210 next();
7211 break;
7212 case TOK_TYPEDEF:
7213 t |= VT_TYPEDEF;
7214 next();
7215 break;
7216 case TOK_INLINE1:
7217 case TOK_INLINE2:
7218 case TOK_INLINE3:
7219 t |= VT_INLINE;
7220 next();
7221 break;
7223 /* GNUC attribute */
7224 case TOK_ATTRIBUTE1:
7225 case TOK_ATTRIBUTE2:
7226 parse_attribute(ad);
7227 break;
7228 /* GNUC typeof */
7229 case TOK_TYPEOF1:
7230 case TOK_TYPEOF2:
7231 case TOK_TYPEOF3:
7232 next();
7233 parse_expr_type(&type1);
7234 goto basic_type2;
7235 default:
7236 if (typespec_found || typedef_found)
7237 goto the_end;
7238 s = sym_find(tok);
7239 if (!s || !(s->type.t & VT_TYPEDEF))
7240 goto the_end;
7241 typedef_found = 1;
7242 t |= (s->type.t & ~VT_TYPEDEF);
7243 type->ref = s->type.ref;
7244 next();
7245 typespec_found = 1;
7246 break;
7248 type_found = 1;
7250 the_end:
7251 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
7252 error("signed and unsigned modifier");
7253 if (tcc_state->char_is_unsigned) {
7254 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
7255 t |= VT_UNSIGNED;
7257 t &= ~VT_SIGNED;
7259 /* long is never used as type */
7260 if ((t & VT_BTYPE) == VT_LONG)
7261 #ifndef TCC_TARGET_X86_64
7262 t = (t & ~VT_BTYPE) | VT_INT;
7263 #else
7264 t = (t & ~VT_BTYPE) | VT_LLONG;
7265 #endif
7266 type->t = t;
7267 return type_found;
7270 /* convert a function parameter type (array to pointer and function to
7271 function pointer) */
7272 static inline void convert_parameter_type(CType *pt)
7274 /* remove const and volatile qualifiers (XXX: const could be used
7275 to indicate a const function parameter */
7276 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
7277 /* array must be transformed to pointer according to ANSI C */
7278 pt->t &= ~VT_ARRAY;
7279 if ((pt->t & VT_BTYPE) == VT_FUNC) {
7280 mk_pointer(pt);
7284 static void post_type(CType *type, AttributeDef *ad)
7286 int n, l, t1, arg_size, align;
7287 Sym **plast, *s, *first;
7288 AttributeDef ad1;
7289 CType pt;
7291 if (tok == '(') {
7292 /* function declaration */
7293 next();
7294 l = 0;
7295 first = NULL;
7296 plast = &first;
7297 arg_size = 0;
7298 if (tok != ')') {
7299 for(;;) {
7300 /* read param name and compute offset */
7301 if (l != FUNC_OLD) {
7302 if (!parse_btype(&pt, &ad1)) {
7303 if (l) {
7304 error("invalid type");
7305 } else {
7306 l = FUNC_OLD;
7307 goto old_proto;
7310 l = FUNC_NEW;
7311 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
7312 break;
7313 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
7314 if ((pt.t & VT_BTYPE) == VT_VOID)
7315 error("parameter declared as void");
7316 arg_size += (type_size(&pt, &align) + 3) & ~3;
7317 } else {
7318 old_proto:
7319 n = tok;
7320 if (n < TOK_UIDENT)
7321 expect("identifier");
7322 pt.t = VT_INT;
7323 next();
7325 convert_parameter_type(&pt);
7326 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
7327 *plast = s;
7328 plast = &s->next;
7329 if (tok == ')')
7330 break;
7331 skip(',');
7332 if (l == FUNC_NEW && tok == TOK_DOTS) {
7333 l = FUNC_ELLIPSIS;
7334 next();
7335 break;
7339 /* if no parameters, then old type prototype */
7340 if (l == 0)
7341 l = FUNC_OLD;
7342 skip(')');
7343 t1 = type->t & VT_STORAGE;
7344 /* NOTE: const is ignored in returned type as it has a special
7345 meaning in gcc / C++ */
7346 type->t &= ~(VT_STORAGE | VT_CONSTANT);
7347 post_type(type, ad);
7348 /* we push a anonymous symbol which will contain the function prototype */
7349 FUNC_ARGS(ad->func_attr) = arg_size;
7350 s = sym_push(SYM_FIELD, type, ad->func_attr, l);
7351 s->next = first;
7352 type->t = t1 | VT_FUNC;
7353 type->ref = s;
7354 } else if (tok == '[') {
7355 /* array definition */
7356 next();
7357 if (tok == TOK_RESTRICT1)
7358 next();
7359 n = -1;
7360 if (tok != ']') {
7361 n = expr_const();
7362 if (n < 0)
7363 error("invalid array size");
7365 skip(']');
7366 /* parse next post type */
7367 t1 = type->t & VT_STORAGE;
7368 type->t &= ~VT_STORAGE;
7369 post_type(type, ad);
7371 /* we push a anonymous symbol which will contain the array
7372 element type */
7373 s = sym_push(SYM_FIELD, type, 0, n);
7374 type->t = t1 | VT_ARRAY | VT_PTR;
7375 type->ref = s;
7379 /* Parse a type declaration (except basic type), and return the type
7380 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7381 expected. 'type' should contain the basic type. 'ad' is the
7382 attribute definition of the basic type. It can be modified by
7383 type_decl().
7385 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
7387 Sym *s;
7388 CType type1, *type2;
7389 int qualifiers;
7391 while (tok == '*') {
7392 qualifiers = 0;
7393 redo:
7394 next();
7395 switch(tok) {
7396 case TOK_CONST1:
7397 case TOK_CONST2:
7398 case TOK_CONST3:
7399 qualifiers |= VT_CONSTANT;
7400 goto redo;
7401 case TOK_VOLATILE1:
7402 case TOK_VOLATILE2:
7403 case TOK_VOLATILE3:
7404 qualifiers |= VT_VOLATILE;
7405 goto redo;
7406 case TOK_RESTRICT1:
7407 case TOK_RESTRICT2:
7408 case TOK_RESTRICT3:
7409 goto redo;
7411 mk_pointer(type);
7412 type->t |= qualifiers;
7415 /* XXX: clarify attribute handling */
7416 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7417 parse_attribute(ad);
7419 /* recursive type */
7420 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7421 type1.t = 0; /* XXX: same as int */
7422 if (tok == '(') {
7423 next();
7424 /* XXX: this is not correct to modify 'ad' at this point, but
7425 the syntax is not clear */
7426 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7427 parse_attribute(ad);
7428 type_decl(&type1, ad, v, td);
7429 skip(')');
7430 } else {
7431 /* type identifier */
7432 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
7433 *v = tok;
7434 next();
7435 } else {
7436 if (!(td & TYPE_ABSTRACT))
7437 expect("identifier");
7438 *v = 0;
7441 post_type(type, ad);
7442 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7443 parse_attribute(ad);
7444 if (!type1.t)
7445 return;
7446 /* append type at the end of type1 */
7447 type2 = &type1;
7448 for(;;) {
7449 s = type2->ref;
7450 type2 = &s->type;
7451 if (!type2->t) {
7452 *type2 = *type;
7453 break;
7456 *type = type1;
7459 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7460 static int lvalue_type(int t)
7462 int bt, r;
7463 r = VT_LVAL;
7464 bt = t & VT_BTYPE;
7465 if (bt == VT_BYTE || bt == VT_BOOL)
7466 r |= VT_LVAL_BYTE;
7467 else if (bt == VT_SHORT)
7468 r |= VT_LVAL_SHORT;
7469 else
7470 return r;
7471 if (t & VT_UNSIGNED)
7472 r |= VT_LVAL_UNSIGNED;
7473 return r;
7476 /* indirection with full error checking and bound check */
7477 static void indir(void)
7479 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
7480 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
7481 return;
7482 expect("pointer");
7484 if ((vtop->r & VT_LVAL) && !nocode_wanted)
7485 gv(RC_INT);
7486 vtop->type = *pointed_type(&vtop->type);
7487 /* Arrays and functions are never lvalues */
7488 if (!(vtop->type.t & VT_ARRAY)
7489 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
7490 vtop->r |= lvalue_type(vtop->type.t);
7491 /* if bound checking, the referenced pointer must be checked */
7492 if (do_bounds_check)
7493 vtop->r |= VT_MUSTBOUND;
7497 /* pass a parameter to a function and do type checking and casting */
7498 static void gfunc_param_typed(Sym *func, Sym *arg)
7500 int func_type;
7501 CType type;
7503 func_type = func->c;
7504 if (func_type == FUNC_OLD ||
7505 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
7506 /* default casting : only need to convert float to double */
7507 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
7508 type.t = VT_DOUBLE;
7509 gen_cast(&type);
7511 } else if (arg == NULL) {
7512 error("too many arguments to function");
7513 } else {
7514 type = arg->type;
7515 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
7516 gen_assign_cast(&type);
7520 /* parse an expression of the form '(type)' or '(expr)' and return its
7521 type */
7522 static void parse_expr_type(CType *type)
7524 int n;
7525 AttributeDef ad;
7527 skip('(');
7528 if (parse_btype(type, &ad)) {
7529 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7530 } else {
7531 expr_type(type);
7533 skip(')');
7536 static void parse_type(CType *type)
7538 AttributeDef ad;
7539 int n;
7541 if (!parse_btype(type, &ad)) {
7542 expect("type");
7544 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7547 static void vpush_tokc(int t)
7549 CType type;
7550 type.t = t;
7551 vsetc(&type, VT_CONST, &tokc);
7554 static void unary(void)
7556 int n, t, align, size, r;
7557 CType type;
7558 Sym *s;
7559 AttributeDef ad;
7561 /* XXX: GCC 2.95.3 does not generate a table although it should be
7562 better here */
7563 tok_next:
7564 switch(tok) {
7565 case TOK_EXTENSION:
7566 next();
7567 goto tok_next;
7568 case TOK_CINT:
7569 case TOK_CCHAR:
7570 case TOK_LCHAR:
7571 vpushi(tokc.i);
7572 next();
7573 break;
7574 case TOK_CUINT:
7575 vpush_tokc(VT_INT | VT_UNSIGNED);
7576 next();
7577 break;
7578 case TOK_CLLONG:
7579 vpush_tokc(VT_LLONG);
7580 next();
7581 break;
7582 case TOK_CULLONG:
7583 vpush_tokc(VT_LLONG | VT_UNSIGNED);
7584 next();
7585 break;
7586 case TOK_CFLOAT:
7587 vpush_tokc(VT_FLOAT);
7588 next();
7589 break;
7590 case TOK_CDOUBLE:
7591 vpush_tokc(VT_DOUBLE);
7592 next();
7593 break;
7594 case TOK_CLDOUBLE:
7595 vpush_tokc(VT_LDOUBLE);
7596 next();
7597 break;
7598 case TOK___FUNCTION__:
7599 if (!gnu_ext)
7600 goto tok_identifier;
7601 /* fall thru */
7602 case TOK___FUNC__:
7604 void *ptr;
7605 int len;
7606 /* special function name identifier */
7607 len = strlen(funcname) + 1;
7608 /* generate char[len] type */
7609 type.t = VT_BYTE;
7610 mk_pointer(&type);
7611 type.t |= VT_ARRAY;
7612 type.ref->c = len;
7613 vpush_ref(&type, data_section, data_section->data_offset, len);
7614 ptr = section_ptr_add(data_section, len);
7615 memcpy(ptr, funcname, len);
7616 next();
7618 break;
7619 case TOK_LSTR:
7620 #ifdef TCC_TARGET_PE
7621 t = VT_SHORT | VT_UNSIGNED;
7622 #else
7623 t = VT_INT;
7624 #endif
7625 goto str_init;
7626 case TOK_STR:
7627 /* string parsing */
7628 t = VT_BYTE;
7629 str_init:
7630 if (tcc_state->warn_write_strings)
7631 t |= VT_CONSTANT;
7632 type.t = t;
7633 mk_pointer(&type);
7634 type.t |= VT_ARRAY;
7635 memset(&ad, 0, sizeof(AttributeDef));
7636 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
7637 break;
7638 case '(':
7639 next();
7640 /* cast ? */
7641 if (parse_btype(&type, &ad)) {
7642 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
7643 skip(')');
7644 /* check ISOC99 compound literal */
7645 if (tok == '{') {
7646 /* data is allocated locally by default */
7647 if (global_expr)
7648 r = VT_CONST;
7649 else
7650 r = VT_LOCAL;
7651 /* all except arrays are lvalues */
7652 if (!(type.t & VT_ARRAY))
7653 r |= lvalue_type(type.t);
7654 memset(&ad, 0, sizeof(AttributeDef));
7655 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
7656 } else {
7657 unary();
7658 gen_cast(&type);
7660 } else if (tok == '{') {
7661 /* save all registers */
7662 save_regs(0);
7663 /* statement expression : we do not accept break/continue
7664 inside as GCC does */
7665 block(NULL, NULL, NULL, NULL, 0, 1);
7666 skip(')');
7667 } else {
7668 gexpr();
7669 skip(')');
7671 break;
7672 case '*':
7673 next();
7674 unary();
7675 indir();
7676 break;
7677 case '&':
7678 next();
7679 unary();
7680 /* functions names must be treated as function pointers,
7681 except for unary '&' and sizeof. Since we consider that
7682 functions are not lvalues, we only have to handle it
7683 there and in function calls. */
7684 /* arrays can also be used although they are not lvalues */
7685 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
7686 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
7687 test_lvalue();
7688 mk_pointer(&vtop->type);
7689 gaddrof();
7690 break;
7691 case '!':
7692 next();
7693 unary();
7694 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
7695 CType boolean;
7696 boolean.t = VT_BOOL;
7697 gen_cast(&boolean);
7698 vtop->c.i = !vtop->c.i;
7699 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
7700 vtop->c.i = vtop->c.i ^ 1;
7701 else {
7702 save_regs(1);
7703 vseti(VT_JMP, gtst(1, 0));
7705 break;
7706 case '~':
7707 next();
7708 unary();
7709 vpushi(-1);
7710 gen_op('^');
7711 break;
7712 case '+':
7713 next();
7714 /* in order to force cast, we add zero */
7715 unary();
7716 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
7717 error("pointer not accepted for unary plus");
7718 vpushi(0);
7719 gen_op('+');
7720 break;
7721 case TOK_SIZEOF:
7722 case TOK_ALIGNOF1:
7723 case TOK_ALIGNOF2:
7724 t = tok;
7725 next();
7726 if (tok == '(') {
7727 parse_expr_type(&type);
7728 } else {
7729 unary_type(&type);
7731 size = type_size(&type, &align);
7732 if (t == TOK_SIZEOF) {
7733 if (size < 0)
7734 error("sizeof applied to an incomplete type");
7735 vpushi(size);
7736 } else {
7737 vpushi(align);
7739 vtop->type.t |= VT_UNSIGNED;
7740 break;
7742 case TOK_builtin_types_compatible_p:
7744 CType type1, type2;
7745 next();
7746 skip('(');
7747 parse_type(&type1);
7748 skip(',');
7749 parse_type(&type2);
7750 skip(')');
7751 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
7752 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
7753 vpushi(is_compatible_types(&type1, &type2));
7755 break;
7756 case TOK_builtin_constant_p:
7758 int saved_nocode_wanted, res;
7759 next();
7760 skip('(');
7761 saved_nocode_wanted = nocode_wanted;
7762 nocode_wanted = 1;
7763 gexpr();
7764 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
7765 vpop();
7766 nocode_wanted = saved_nocode_wanted;
7767 skip(')');
7768 vpushi(res);
7770 break;
7771 case TOK_builtin_frame_address:
7773 CType type;
7774 next();
7775 skip('(');
7776 if (tok != TOK_CINT) {
7777 error("__builtin_frame_address only takes integers");
7779 if (tokc.i != 0) {
7780 error("TCC only supports __builtin_frame_address(0)");
7782 next();
7783 skip(')');
7784 type.t = VT_VOID;
7785 mk_pointer(&type);
7786 vset(&type, VT_LOCAL, 0);
7788 break;
7789 #ifdef TCC_TARGET_X86_64
7790 case TOK_builtin_malloc:
7792 char *p = file->buf_ptr;
7793 file->buf_ptr = "malloc";
7794 next_nomacro1();
7795 file->buf_ptr = p;
7796 goto tok_identifier;
7798 case TOK_builtin_free:
7800 char *p = file->buf_ptr;
7801 file->buf_ptr = "free";
7802 next_nomacro1();
7803 file->buf_ptr = p;
7804 goto tok_identifier;
7806 #endif
7807 case TOK_INC:
7808 case TOK_DEC:
7809 t = tok;
7810 next();
7811 unary();
7812 inc(0, t);
7813 break;
7814 case '-':
7815 next();
7816 vpushi(0);
7817 unary();
7818 gen_op('-');
7819 break;
7820 case TOK_LAND:
7821 if (!gnu_ext)
7822 goto tok_identifier;
7823 next();
7824 /* allow to take the address of a label */
7825 if (tok < TOK_UIDENT)
7826 expect("label identifier");
7827 s = label_find(tok);
7828 if (!s) {
7829 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
7830 } else {
7831 if (s->r == LABEL_DECLARED)
7832 s->r = LABEL_FORWARD;
7834 if (!s->type.t) {
7835 s->type.t = VT_VOID;
7836 mk_pointer(&s->type);
7837 s->type.t |= VT_STATIC;
7839 vset(&s->type, VT_CONST | VT_SYM, 0);
7840 vtop->sym = s;
7841 next();
7842 break;
7843 default:
7844 tok_identifier:
7845 t = tok;
7846 next();
7847 if (t < TOK_UIDENT)
7848 expect("identifier");
7849 s = sym_find(t);
7850 if (!s) {
7851 if (tok != '(')
7852 error("'%s' undeclared", get_tok_str(t, NULL));
7853 /* for simple function calls, we tolerate undeclared
7854 external reference to int() function */
7855 if (tcc_state->warn_implicit_function_declaration)
7856 warning("implicit declaration of function '%s'",
7857 get_tok_str(t, NULL));
7858 s = external_global_sym(t, &func_old_type, 0);
7860 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
7861 (VT_STATIC | VT_INLINE | VT_FUNC)) {
7862 /* if referencing an inline function, then we generate a
7863 symbol to it if not already done. It will have the
7864 effect to generate code for it at the end of the
7865 compilation unit. Inline function as always
7866 generated in the text section. */
7867 if (!s->c)
7868 put_extern_sym(s, text_section, 0, 0);
7869 r = VT_SYM | VT_CONST;
7870 } else {
7871 r = s->r;
7873 vset(&s->type, r, s->c);
7874 /* if forward reference, we must point to s */
7875 if (vtop->r & VT_SYM) {
7876 vtop->sym = s;
7877 vtop->c.ul = 0;
7879 break;
7882 /* post operations */
7883 while (1) {
7884 if (tok == TOK_INC || tok == TOK_DEC) {
7885 inc(1, tok);
7886 next();
7887 } else if (tok == '.' || tok == TOK_ARROW) {
7888 /* field */
7889 if (tok == TOK_ARROW)
7890 indir();
7891 test_lvalue();
7892 gaddrof();
7893 next();
7894 /* expect pointer on structure */
7895 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
7896 expect("struct or union");
7897 s = vtop->type.ref;
7898 /* find field */
7899 tok |= SYM_FIELD;
7900 while ((s = s->next) != NULL) {
7901 if (s->v == tok)
7902 break;
7904 if (!s)
7905 error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
7906 /* add field offset to pointer */
7907 vtop->type = char_pointer_type; /* change type to 'char *' */
7908 vpushi(s->c);
7909 gen_op('+');
7910 /* change type to field type, and set to lvalue */
7911 vtop->type = s->type;
7912 /* an array is never an lvalue */
7913 if (!(vtop->type.t & VT_ARRAY)) {
7914 vtop->r |= lvalue_type(vtop->type.t);
7915 /* if bound checking, the referenced pointer must be checked */
7916 if (do_bounds_check)
7917 vtop->r |= VT_MUSTBOUND;
7919 next();
7920 } else if (tok == '[') {
7921 next();
7922 gexpr();
7923 gen_op('+');
7924 indir();
7925 skip(']');
7926 } else if (tok == '(') {
7927 SValue ret;
7928 Sym *sa;
7929 int nb_args;
7931 /* function call */
7932 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
7933 /* pointer test (no array accepted) */
7934 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
7935 vtop->type = *pointed_type(&vtop->type);
7936 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
7937 goto error_func;
7938 } else {
7939 error_func:
7940 expect("function pointer");
7942 } else {
7943 vtop->r &= ~VT_LVAL; /* no lvalue */
7945 /* get return type */
7946 s = vtop->type.ref;
7947 next();
7948 sa = s->next; /* first parameter */
7949 nb_args = 0;
7950 ret.r2 = VT_CONST;
7951 /* compute first implicit argument if a structure is returned */
7952 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
7953 /* get some space for the returned structure */
7954 size = type_size(&s->type, &align);
7955 loc = (loc - size) & -align;
7956 ret.type = s->type;
7957 ret.r = VT_LOCAL | VT_LVAL;
7958 /* pass it as 'int' to avoid structure arg passing
7959 problems */
7960 vseti(VT_LOCAL, loc);
7961 ret.c = vtop->c;
7962 nb_args++;
7963 } else {
7964 ret.type = s->type;
7965 /* return in register */
7966 if (is_float(ret.type.t)) {
7967 ret.r = reg_fret(ret.type.t);
7968 } else {
7969 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
7970 ret.r2 = REG_LRET;
7971 ret.r = REG_IRET;
7973 ret.c.i = 0;
7975 if (tok != ')') {
7976 for(;;) {
7977 expr_eq();
7978 gfunc_param_typed(s, sa);
7979 nb_args++;
7980 if (sa)
7981 sa = sa->next;
7982 if (tok == ')')
7983 break;
7984 skip(',');
7987 if (sa)
7988 error("too few arguments to function");
7989 skip(')');
7990 if (!nocode_wanted) {
7991 gfunc_call(nb_args);
7992 } else {
7993 vtop -= (nb_args + 1);
7995 /* return value */
7996 vsetc(&ret.type, ret.r, &ret.c);
7997 vtop->r2 = ret.r2;
7998 } else {
7999 break;
8004 static void uneq(void)
8006 int t;
8008 unary();
8009 if (tok == '=' ||
8010 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
8011 tok == TOK_A_XOR || tok == TOK_A_OR ||
8012 tok == TOK_A_SHL || tok == TOK_A_SAR) {
8013 test_lvalue();
8014 t = tok;
8015 next();
8016 if (t == '=') {
8017 expr_eq();
8018 } else {
8019 vdup();
8020 expr_eq();
8021 gen_op(t & 0x7f);
8023 vstore();
8027 static void expr_prod(void)
8029 int t;
8031 uneq();
8032 while (tok == '*' || tok == '/' || tok == '%') {
8033 t = tok;
8034 next();
8035 uneq();
8036 gen_op(t);
8040 static void expr_sum(void)
8042 int t;
8044 expr_prod();
8045 while (tok == '+' || tok == '-') {
8046 t = tok;
8047 next();
8048 expr_prod();
8049 gen_op(t);
8053 static void expr_shift(void)
8055 int t;
8057 expr_sum();
8058 while (tok == TOK_SHL || tok == TOK_SAR) {
8059 t = tok;
8060 next();
8061 expr_sum();
8062 gen_op(t);
8066 static void expr_cmp(void)
8068 int t;
8070 expr_shift();
8071 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
8072 tok == TOK_ULT || tok == TOK_UGE) {
8073 t = tok;
8074 next();
8075 expr_shift();
8076 gen_op(t);
8080 static void expr_cmpeq(void)
8082 int t;
8084 expr_cmp();
8085 while (tok == TOK_EQ || tok == TOK_NE) {
8086 t = tok;
8087 next();
8088 expr_cmp();
8089 gen_op(t);
8093 static void expr_and(void)
8095 expr_cmpeq();
8096 while (tok == '&') {
8097 next();
8098 expr_cmpeq();
8099 gen_op('&');
8103 static void expr_xor(void)
8105 expr_and();
8106 while (tok == '^') {
8107 next();
8108 expr_and();
8109 gen_op('^');
8113 static void expr_or(void)
8115 expr_xor();
8116 while (tok == '|') {
8117 next();
8118 expr_xor();
8119 gen_op('|');
8123 /* XXX: fix this mess */
8124 static void expr_land_const(void)
8126 expr_or();
8127 while (tok == TOK_LAND) {
8128 next();
8129 expr_or();
8130 gen_op(TOK_LAND);
8134 /* XXX: fix this mess */
8135 static void expr_lor_const(void)
8137 expr_land_const();
8138 while (tok == TOK_LOR) {
8139 next();
8140 expr_land_const();
8141 gen_op(TOK_LOR);
8145 /* only used if non constant */
8146 static void expr_land(void)
8148 int t;
8150 expr_or();
8151 if (tok == TOK_LAND) {
8152 t = 0;
8153 save_regs(1);
8154 for(;;) {
8155 t = gtst(1, t);
8156 if (tok != TOK_LAND) {
8157 vseti(VT_JMPI, t);
8158 break;
8160 next();
8161 expr_or();
8166 static void expr_lor(void)
8168 int t;
8170 expr_land();
8171 if (tok == TOK_LOR) {
8172 t = 0;
8173 save_regs(1);
8174 for(;;) {
8175 t = gtst(0, t);
8176 if (tok != TOK_LOR) {
8177 vseti(VT_JMP, t);
8178 break;
8180 next();
8181 expr_land();
8186 /* XXX: better constant handling */
8187 static void expr_eq(void)
8189 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
8190 SValue sv;
8191 CType type, type1, type2;
8193 if (const_wanted) {
8194 expr_lor_const();
8195 if (tok == '?') {
8196 CType boolean;
8197 int c;
8198 boolean.t = VT_BOOL;
8199 vdup();
8200 gen_cast(&boolean);
8201 c = vtop->c.i;
8202 vpop();
8203 next();
8204 if (tok != ':' || !gnu_ext) {
8205 vpop();
8206 gexpr();
8208 if (!c)
8209 vpop();
8210 skip(':');
8211 expr_eq();
8212 if (c)
8213 vpop();
8215 } else {
8216 expr_lor();
8217 if (tok == '?') {
8218 next();
8219 if (vtop != vstack) {
8220 /* needed to avoid having different registers saved in
8221 each branch */
8222 if (is_float(vtop->type.t)) {
8223 rc = RC_FLOAT;
8224 #ifdef TCC_TARGET_X86_64
8225 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
8226 rc = RC_ST0;
8228 #endif
8230 else
8231 rc = RC_INT;
8232 gv(rc);
8233 save_regs(1);
8235 if (tok == ':' && gnu_ext) {
8236 gv_dup();
8237 tt = gtst(1, 0);
8238 } else {
8239 tt = gtst(1, 0);
8240 gexpr();
8242 type1 = vtop->type;
8243 sv = *vtop; /* save value to handle it later */
8244 vtop--; /* no vpop so that FP stack is not flushed */
8245 skip(':');
8246 u = gjmp(0);
8247 gsym(tt);
8248 expr_eq();
8249 type2 = vtop->type;
8251 t1 = type1.t;
8252 bt1 = t1 & VT_BTYPE;
8253 t2 = type2.t;
8254 bt2 = t2 & VT_BTYPE;
8255 /* cast operands to correct type according to ISOC rules */
8256 if (is_float(bt1) || is_float(bt2)) {
8257 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
8258 type.t = VT_LDOUBLE;
8259 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
8260 type.t = VT_DOUBLE;
8261 } else {
8262 type.t = VT_FLOAT;
8264 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
8265 /* cast to biggest op */
8266 type.t = VT_LLONG;
8267 /* convert to unsigned if it does not fit in a long long */
8268 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
8269 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
8270 type.t |= VT_UNSIGNED;
8271 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
8272 /* XXX: test pointer compatibility */
8273 type = type1;
8274 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
8275 /* XXX: test function pointer compatibility */
8276 type = type1;
8277 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
8278 /* XXX: test structure compatibility */
8279 type = type1;
8280 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
8281 /* NOTE: as an extension, we accept void on only one side */
8282 type.t = VT_VOID;
8283 } else {
8284 /* integer operations */
8285 type.t = VT_INT;
8286 /* convert to unsigned if it does not fit in an integer */
8287 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
8288 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
8289 type.t |= VT_UNSIGNED;
8292 /* now we convert second operand */
8293 gen_cast(&type);
8294 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8295 gaddrof();
8296 rc = RC_INT;
8297 if (is_float(type.t)) {
8298 rc = RC_FLOAT;
8299 #ifdef TCC_TARGET_X86_64
8300 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
8301 rc = RC_ST0;
8303 #endif
8304 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
8305 /* for long longs, we use fixed registers to avoid having
8306 to handle a complicated move */
8307 rc = RC_IRET;
8310 r2 = gv(rc);
8311 /* this is horrible, but we must also convert first
8312 operand */
8313 tt = gjmp(0);
8314 gsym(u);
8315 /* put again first value and cast it */
8316 *vtop = sv;
8317 gen_cast(&type);
8318 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8319 gaddrof();
8320 r1 = gv(rc);
8321 move_reg(r2, r1);
8322 vtop->r = r2;
8323 gsym(tt);
8328 static void gexpr(void)
8330 while (1) {
8331 expr_eq();
8332 if (tok != ',')
8333 break;
8334 vpop();
8335 next();
8339 /* parse an expression and return its type without any side effect. */
8340 static void expr_type(CType *type)
8342 int saved_nocode_wanted;
8344 saved_nocode_wanted = nocode_wanted;
8345 nocode_wanted = 1;
8346 gexpr();
8347 *type = vtop->type;
8348 vpop();
8349 nocode_wanted = saved_nocode_wanted;
8352 /* parse a unary expression and return its type without any side
8353 effect. */
8354 static void unary_type(CType *type)
8356 int a;
8358 a = nocode_wanted;
8359 nocode_wanted = 1;
8360 unary();
8361 *type = vtop->type;
8362 vpop();
8363 nocode_wanted = a;
8366 /* parse a constant expression and return value in vtop. */
8367 static void expr_const1(void)
8369 int a;
8370 a = const_wanted;
8371 const_wanted = 1;
8372 expr_eq();
8373 const_wanted = a;
8376 /* parse an integer constant and return its value. */
8377 static int expr_const(void)
8379 int c;
8380 expr_const1();
8381 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
8382 expect("constant expression");
8383 c = vtop->c.i;
8384 vpop();
8385 return c;
8388 /* return the label token if current token is a label, otherwise
8389 return zero */
8390 static int is_label(void)
8392 int last_tok;
8394 /* fast test first */
8395 if (tok < TOK_UIDENT)
8396 return 0;
8397 /* no need to save tokc because tok is an identifier */
8398 last_tok = tok;
8399 next();
8400 if (tok == ':') {
8401 next();
8402 return last_tok;
8403 } else {
8404 unget_tok(last_tok);
8405 return 0;
8409 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
8410 int case_reg, int is_expr)
8412 int a, b, c, d;
8413 Sym *s;
8415 /* generate line number info */
8416 if (do_debug &&
8417 (last_line_num != file->line_num || last_ind != ind)) {
8418 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
8419 last_ind = ind;
8420 last_line_num = file->line_num;
8423 if (is_expr) {
8424 /* default return value is (void) */
8425 vpushi(0);
8426 vtop->type.t = VT_VOID;
8429 if (tok == TOK_IF) {
8430 /* if test */
8431 next();
8432 skip('(');
8433 gexpr();
8434 skip(')');
8435 a = gtst(1, 0);
8436 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8437 c = tok;
8438 if (c == TOK_ELSE) {
8439 next();
8440 d = gjmp(0);
8441 gsym(a);
8442 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8443 gsym(d); /* patch else jmp */
8444 } else
8445 gsym(a);
8446 } else if (tok == TOK_WHILE) {
8447 next();
8448 d = ind;
8449 skip('(');
8450 gexpr();
8451 skip(')');
8452 a = gtst(1, 0);
8453 b = 0;
8454 block(&a, &b, case_sym, def_sym, case_reg, 0);
8455 gjmp_addr(d);
8456 gsym(a);
8457 gsym_addr(b, d);
8458 } else if (tok == '{') {
8459 Sym *llabel;
8461 next();
8462 /* record local declaration stack position */
8463 s = local_stack;
8464 llabel = local_label_stack;
8465 /* handle local labels declarations */
8466 if (tok == TOK_LABEL) {
8467 next();
8468 for(;;) {
8469 if (tok < TOK_UIDENT)
8470 expect("label identifier");
8471 label_push(&local_label_stack, tok, LABEL_DECLARED);
8472 next();
8473 if (tok == ',') {
8474 next();
8475 } else {
8476 skip(';');
8477 break;
8481 while (tok != '}') {
8482 decl(VT_LOCAL);
8483 if (tok != '}') {
8484 if (is_expr)
8485 vpop();
8486 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8489 /* pop locally defined labels */
8490 label_pop(&local_label_stack, llabel);
8491 /* pop locally defined symbols */
8492 if(is_expr) {
8493 /* XXX: this solution makes only valgrind happy...
8494 triggered by gcc.c-torture/execute/20000917-1.c */
8495 Sym *p;
8496 switch(vtop->type.t & VT_BTYPE) {
8497 case VT_PTR:
8498 case VT_STRUCT:
8499 case VT_ENUM:
8500 case VT_FUNC:
8501 for(p=vtop->type.ref;p;p=p->prev)
8502 if(p->prev==s)
8503 error("unsupported expression type");
8506 sym_pop(&local_stack, s);
8507 next();
8508 } else if (tok == TOK_RETURN) {
8509 next();
8510 if (tok != ';') {
8511 gexpr();
8512 gen_assign_cast(&func_vt);
8513 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
8514 CType type;
8515 /* if returning structure, must copy it to implicit
8516 first pointer arg location */
8517 #ifdef TCC_ARM_EABI
8518 int align, size;
8519 size = type_size(&func_vt,&align);
8520 if(size <= 4)
8522 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
8523 && (align & 3))
8525 int addr;
8526 loc = (loc - size) & -4;
8527 addr = loc;
8528 type = func_vt;
8529 vset(&type, VT_LOCAL | VT_LVAL, addr);
8530 vswap();
8531 vstore();
8532 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
8534 vtop->type = int_type;
8535 gv(RC_IRET);
8536 } else {
8537 #endif
8538 type = func_vt;
8539 mk_pointer(&type);
8540 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
8541 indir();
8542 vswap();
8543 /* copy structure value to pointer */
8544 vstore();
8545 #ifdef TCC_ARM_EABI
8547 #endif
8548 } else if (is_float(func_vt.t)) {
8549 gv(rc_fret(func_vt.t));
8550 } else {
8551 gv(RC_IRET);
8553 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
8555 skip(';');
8556 rsym = gjmp(rsym); /* jmp */
8557 } else if (tok == TOK_BREAK) {
8558 /* compute jump */
8559 if (!bsym)
8560 error("cannot break");
8561 *bsym = gjmp(*bsym);
8562 next();
8563 skip(';');
8564 } else if (tok == TOK_CONTINUE) {
8565 /* compute jump */
8566 if (!csym)
8567 error("cannot continue");
8568 *csym = gjmp(*csym);
8569 next();
8570 skip(';');
8571 } else if (tok == TOK_FOR) {
8572 int e;
8573 next();
8574 skip('(');
8575 if (tok != ';') {
8576 gexpr();
8577 vpop();
8579 skip(';');
8580 d = ind;
8581 c = ind;
8582 a = 0;
8583 b = 0;
8584 if (tok != ';') {
8585 gexpr();
8586 a = gtst(1, 0);
8588 skip(';');
8589 if (tok != ')') {
8590 e = gjmp(0);
8591 c = ind;
8592 gexpr();
8593 vpop();
8594 gjmp_addr(d);
8595 gsym(e);
8597 skip(')');
8598 block(&a, &b, case_sym, def_sym, case_reg, 0);
8599 gjmp_addr(c);
8600 gsym(a);
8601 gsym_addr(b, c);
8602 } else
8603 if (tok == TOK_DO) {
8604 next();
8605 a = 0;
8606 b = 0;
8607 d = ind;
8608 block(&a, &b, case_sym, def_sym, case_reg, 0);
8609 skip(TOK_WHILE);
8610 skip('(');
8611 gsym(b);
8612 gexpr();
8613 c = gtst(0, 0);
8614 gsym_addr(c, d);
8615 skip(')');
8616 gsym(a);
8617 skip(';');
8618 } else
8619 if (tok == TOK_SWITCH) {
8620 next();
8621 skip('(');
8622 gexpr();
8623 /* XXX: other types than integer */
8624 case_reg = gv(RC_INT);
8625 vpop();
8626 skip(')');
8627 a = 0;
8628 b = gjmp(0); /* jump to first case */
8629 c = 0;
8630 block(&a, csym, &b, &c, case_reg, 0);
8631 /* if no default, jmp after switch */
8632 if (c == 0)
8633 c = ind;
8634 /* default label */
8635 gsym_addr(b, c);
8636 /* break label */
8637 gsym(a);
8638 } else
8639 if (tok == TOK_CASE) {
8640 int v1, v2;
8641 if (!case_sym)
8642 expect("switch");
8643 next();
8644 v1 = expr_const();
8645 v2 = v1;
8646 if (gnu_ext && tok == TOK_DOTS) {
8647 next();
8648 v2 = expr_const();
8649 if (v2 < v1)
8650 warning("empty case range");
8652 /* since a case is like a label, we must skip it with a jmp */
8653 b = gjmp(0);
8654 gsym(*case_sym);
8655 vseti(case_reg, 0);
8656 vpushi(v1);
8657 if (v1 == v2) {
8658 gen_op(TOK_EQ);
8659 *case_sym = gtst(1, 0);
8660 } else {
8661 gen_op(TOK_GE);
8662 *case_sym = gtst(1, 0);
8663 vseti(case_reg, 0);
8664 vpushi(v2);
8665 gen_op(TOK_LE);
8666 *case_sym = gtst(1, *case_sym);
8668 gsym(b);
8669 skip(':');
8670 is_expr = 0;
8671 goto block_after_label;
8672 } else
8673 if (tok == TOK_DEFAULT) {
8674 next();
8675 skip(':');
8676 if (!def_sym)
8677 expect("switch");
8678 if (*def_sym)
8679 error("too many 'default'");
8680 *def_sym = ind;
8681 is_expr = 0;
8682 goto block_after_label;
8683 } else
8684 if (tok == TOK_GOTO) {
8685 next();
8686 if (tok == '*' && gnu_ext) {
8687 /* computed goto */
8688 next();
8689 gexpr();
8690 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
8691 expect("pointer");
8692 ggoto();
8693 } else if (tok >= TOK_UIDENT) {
8694 s = label_find(tok);
8695 /* put forward definition if needed */
8696 if (!s) {
8697 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
8698 } else {
8699 if (s->r == LABEL_DECLARED)
8700 s->r = LABEL_FORWARD;
8702 /* label already defined */
8703 if (s->r & LABEL_FORWARD)
8704 s->next = (void *)gjmp((long)s->next);
8705 else
8706 gjmp_addr((long)s->next);
8707 next();
8708 } else {
8709 expect("label identifier");
8711 skip(';');
8712 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
8713 asm_instr();
8714 } else {
8715 b = is_label();
8716 if (b) {
8717 /* label case */
8718 s = label_find(b);
8719 if (s) {
8720 if (s->r == LABEL_DEFINED)
8721 error("duplicate label '%s'", get_tok_str(s->v, NULL));
8722 gsym((long)s->next);
8723 s->r = LABEL_DEFINED;
8724 } else {
8725 s = label_push(&global_label_stack, b, LABEL_DEFINED);
8727 s->next = (void *)ind;
8728 /* we accept this, but it is a mistake */
8729 block_after_label:
8730 if (tok == '}') {
8731 warning("deprecated use of label at end of compound statement");
8732 } else {
8733 if (is_expr)
8734 vpop();
8735 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8737 } else {
8738 /* expression case */
8739 if (tok != ';') {
8740 if (is_expr) {
8741 vpop();
8742 gexpr();
8743 } else {
8744 gexpr();
8745 vpop();
8748 skip(';');
8753 /* t is the array or struct type. c is the array or struct
8754 address. cur_index/cur_field is the pointer to the current
8755 value. 'size_only' is true if only size info is needed (only used
8756 in arrays) */
8757 static void decl_designator(CType *type, Section *sec, unsigned long c,
8758 int *cur_index, Sym **cur_field,
8759 int size_only)
8761 Sym *s, *f;
8762 int notfirst, index, index_last, align, l, nb_elems, elem_size;
8763 CType type1;
8765 notfirst = 0;
8766 elem_size = 0;
8767 nb_elems = 1;
8768 if (gnu_ext && (l = is_label()) != 0)
8769 goto struct_field;
8770 while (tok == '[' || tok == '.') {
8771 if (tok == '[') {
8772 if (!(type->t & VT_ARRAY))
8773 expect("array type");
8774 s = type->ref;
8775 next();
8776 index = expr_const();
8777 if (index < 0 || (s->c >= 0 && index >= s->c))
8778 expect("invalid index");
8779 if (tok == TOK_DOTS && gnu_ext) {
8780 next();
8781 index_last = expr_const();
8782 if (index_last < 0 ||
8783 (s->c >= 0 && index_last >= s->c) ||
8784 index_last < index)
8785 expect("invalid index");
8786 } else {
8787 index_last = index;
8789 skip(']');
8790 if (!notfirst)
8791 *cur_index = index_last;
8792 type = pointed_type(type);
8793 elem_size = type_size(type, &align);
8794 c += index * elem_size;
8795 /* NOTE: we only support ranges for last designator */
8796 nb_elems = index_last - index + 1;
8797 if (nb_elems != 1) {
8798 notfirst = 1;
8799 break;
8801 } else {
8802 next();
8803 l = tok;
8804 next();
8805 struct_field:
8806 if ((type->t & VT_BTYPE) != VT_STRUCT)
8807 expect("struct/union type");
8808 s = type->ref;
8809 l |= SYM_FIELD;
8810 f = s->next;
8811 while (f) {
8812 if (f->v == l)
8813 break;
8814 f = f->next;
8816 if (!f)
8817 expect("field");
8818 if (!notfirst)
8819 *cur_field = f;
8820 /* XXX: fix this mess by using explicit storage field */
8821 type1 = f->type;
8822 type1.t |= (type->t & ~VT_TYPE);
8823 type = &type1;
8824 c += f->c;
8826 notfirst = 1;
8828 if (notfirst) {
8829 if (tok == '=') {
8830 next();
8831 } else {
8832 if (!gnu_ext)
8833 expect("=");
8835 } else {
8836 if (type->t & VT_ARRAY) {
8837 index = *cur_index;
8838 type = pointed_type(type);
8839 c += index * type_size(type, &align);
8840 } else {
8841 f = *cur_field;
8842 if (!f)
8843 error("too many field init");
8844 /* XXX: fix this mess by using explicit storage field */
8845 type1 = f->type;
8846 type1.t |= (type->t & ~VT_TYPE);
8847 type = &type1;
8848 c += f->c;
8851 decl_initializer(type, sec, c, 0, size_only);
8853 /* XXX: make it more general */
8854 if (!size_only && nb_elems > 1) {
8855 unsigned long c_end;
8856 uint8_t *src, *dst;
8857 int i;
8859 if (!sec)
8860 error("range init not supported yet for dynamic storage");
8861 c_end = c + nb_elems * elem_size;
8862 if (c_end > sec->data_allocated)
8863 section_realloc(sec, c_end);
8864 src = sec->data + c;
8865 dst = src;
8866 for(i = 1; i < nb_elems; i++) {
8867 dst += elem_size;
8868 memcpy(dst, src, elem_size);
8873 #define EXPR_VAL 0
8874 #define EXPR_CONST 1
8875 #define EXPR_ANY 2
8877 /* store a value or an expression directly in global data or in local array */
8878 static void init_putv(CType *type, Section *sec, unsigned long c,
8879 int v, int expr_type)
8881 int saved_global_expr, bt, bit_pos, bit_size;
8882 void *ptr;
8883 unsigned long long bit_mask;
8884 CType dtype;
8886 switch(expr_type) {
8887 case EXPR_VAL:
8888 vpushi(v);
8889 break;
8890 case EXPR_CONST:
8891 /* compound literals must be allocated globally in this case */
8892 saved_global_expr = global_expr;
8893 global_expr = 1;
8894 expr_const1();
8895 global_expr = saved_global_expr;
8896 /* NOTE: symbols are accepted */
8897 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
8898 error("initializer element is not constant");
8899 break;
8900 case EXPR_ANY:
8901 expr_eq();
8902 break;
8905 dtype = *type;
8906 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
8908 if (sec) {
8909 /* XXX: not portable */
8910 /* XXX: generate error if incorrect relocation */
8911 gen_assign_cast(&dtype);
8912 bt = type->t & VT_BTYPE;
8913 /* we'll write at most 12 bytes */
8914 if (c + 12 > sec->data_allocated) {
8915 section_realloc(sec, c + 12);
8917 ptr = sec->data + c;
8918 /* XXX: make code faster ? */
8919 if (!(type->t & VT_BITFIELD)) {
8920 bit_pos = 0;
8921 bit_size = 32;
8922 bit_mask = -1LL;
8923 } else {
8924 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
8925 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
8926 bit_mask = (1LL << bit_size) - 1;
8928 if ((vtop->r & VT_SYM) &&
8929 (bt == VT_BYTE ||
8930 bt == VT_SHORT ||
8931 bt == VT_DOUBLE ||
8932 bt == VT_LDOUBLE ||
8933 bt == VT_LLONG ||
8934 (bt == VT_INT && bit_size != 32)))
8935 error("initializer element is not computable at load time");
8936 switch(bt) {
8937 case VT_BOOL:
8938 vtop->c.i = (vtop->c.i != 0);
8939 case VT_BYTE:
8940 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8941 break;
8942 case VT_SHORT:
8943 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8944 break;
8945 case VT_DOUBLE:
8946 *(double *)ptr = vtop->c.d;
8947 break;
8948 case VT_LDOUBLE:
8949 *(long double *)ptr = vtop->c.ld;
8950 break;
8951 case VT_LLONG:
8952 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
8953 break;
8954 default:
8955 if (vtop->r & VT_SYM) {
8956 greloc(sec, vtop->sym, c, R_DATA_32);
8958 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8959 break;
8961 vtop--;
8962 } else {
8963 vset(&dtype, VT_LOCAL|VT_LVAL, c);
8964 vswap();
8965 vstore();
8966 vpop();
8970 /* put zeros for variable based init */
8971 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
8973 if (sec) {
8974 /* nothing to do because globals are already set to zero */
8975 } else {
8976 vpush_global_sym(&func_old_type, TOK_memset);
8977 vseti(VT_LOCAL, c);
8978 vpushi(0);
8979 vpushi(size);
8980 gfunc_call(3);
8984 /* 't' contains the type and storage info. 'c' is the offset of the
8985 object in section 'sec'. If 'sec' is NULL, it means stack based
8986 allocation. 'first' is true if array '{' must be read (multi
8987 dimension implicit array init handling). 'size_only' is true if
8988 size only evaluation is wanted (only for arrays). */
8989 static void decl_initializer(CType *type, Section *sec, unsigned long c,
8990 int first, int size_only)
8992 int index, array_length, n, no_oblock, nb, parlevel, i;
8993 int size1, align1, expr_type;
8994 Sym *s, *f;
8995 CType *t1;
8997 if (type->t & VT_ARRAY) {
8998 s = type->ref;
8999 n = s->c;
9000 array_length = 0;
9001 t1 = pointed_type(type);
9002 size1 = type_size(t1, &align1);
9004 no_oblock = 1;
9005 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
9006 tok == '{') {
9007 skip('{');
9008 no_oblock = 0;
9011 /* only parse strings here if correct type (otherwise: handle
9012 them as ((w)char *) expressions */
9013 if ((tok == TOK_LSTR &&
9014 #ifdef TCC_TARGET_PE
9015 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
9016 #else
9017 (t1->t & VT_BTYPE) == VT_INT
9018 #endif
9019 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
9020 while (tok == TOK_STR || tok == TOK_LSTR) {
9021 int cstr_len, ch;
9022 CString *cstr;
9024 cstr = tokc.cstr;
9025 /* compute maximum number of chars wanted */
9026 if (tok == TOK_STR)
9027 cstr_len = cstr->size;
9028 else
9029 cstr_len = cstr->size / sizeof(nwchar_t);
9030 cstr_len--;
9031 nb = cstr_len;
9032 if (n >= 0 && nb > (n - array_length))
9033 nb = n - array_length;
9034 if (!size_only) {
9035 if (cstr_len > nb)
9036 warning("initializer-string for array is too long");
9037 /* in order to go faster for common case (char
9038 string in global variable, we handle it
9039 specifically */
9040 if (sec && tok == TOK_STR && size1 == 1) {
9041 memcpy(sec->data + c + array_length, cstr->data, nb);
9042 } else {
9043 for(i=0;i<nb;i++) {
9044 if (tok == TOK_STR)
9045 ch = ((unsigned char *)cstr->data)[i];
9046 else
9047 ch = ((nwchar_t *)cstr->data)[i];
9048 init_putv(t1, sec, c + (array_length + i) * size1,
9049 ch, EXPR_VAL);
9053 array_length += nb;
9054 next();
9056 /* only add trailing zero if enough storage (no
9057 warning in this case since it is standard) */
9058 if (n < 0 || array_length < n) {
9059 if (!size_only) {
9060 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
9062 array_length++;
9064 } else {
9065 index = 0;
9066 while (tok != '}') {
9067 decl_designator(type, sec, c, &index, NULL, size_only);
9068 if (n >= 0 && index >= n)
9069 error("index too large");
9070 /* must put zero in holes (note that doing it that way
9071 ensures that it even works with designators) */
9072 if (!size_only && array_length < index) {
9073 init_putz(t1, sec, c + array_length * size1,
9074 (index - array_length) * size1);
9076 index++;
9077 if (index > array_length)
9078 array_length = index;
9079 /* special test for multi dimensional arrays (may not
9080 be strictly correct if designators are used at the
9081 same time) */
9082 if (index >= n && no_oblock)
9083 break;
9084 if (tok == '}')
9085 break;
9086 skip(',');
9089 if (!no_oblock)
9090 skip('}');
9091 /* put zeros at the end */
9092 if (!size_only && n >= 0 && array_length < n) {
9093 init_putz(t1, sec, c + array_length * size1,
9094 (n - array_length) * size1);
9096 /* patch type size if needed */
9097 if (n < 0)
9098 s->c = array_length;
9099 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
9100 (sec || !first || tok == '{')) {
9101 int par_count;
9103 /* NOTE: the previous test is a specific case for automatic
9104 struct/union init */
9105 /* XXX: union needs only one init */
9107 /* XXX: this test is incorrect for local initializers
9108 beginning with ( without {. It would be much more difficult
9109 to do it correctly (ideally, the expression parser should
9110 be used in all cases) */
9111 par_count = 0;
9112 if (tok == '(') {
9113 AttributeDef ad1;
9114 CType type1;
9115 next();
9116 while (tok == '(') {
9117 par_count++;
9118 next();
9120 if (!parse_btype(&type1, &ad1))
9121 expect("cast");
9122 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
9123 #if 0
9124 if (!is_assignable_types(type, &type1))
9125 error("invalid type for cast");
9126 #endif
9127 skip(')');
9129 no_oblock = 1;
9130 if (first || tok == '{') {
9131 skip('{');
9132 no_oblock = 0;
9134 s = type->ref;
9135 f = s->next;
9136 array_length = 0;
9137 index = 0;
9138 n = s->c;
9139 while (tok != '}') {
9140 decl_designator(type, sec, c, NULL, &f, size_only);
9141 index = f->c;
9142 if (!size_only && array_length < index) {
9143 init_putz(type, sec, c + array_length,
9144 index - array_length);
9146 index = index + type_size(&f->type, &align1);
9147 if (index > array_length)
9148 array_length = index;
9149 f = f->next;
9150 if (no_oblock && f == NULL)
9151 break;
9152 if (tok == '}')
9153 break;
9154 skip(',');
9156 /* put zeros at the end */
9157 if (!size_only && array_length < n) {
9158 init_putz(type, sec, c + array_length,
9159 n - array_length);
9161 if (!no_oblock)
9162 skip('}');
9163 while (par_count) {
9164 skip(')');
9165 par_count--;
9167 } else if (tok == '{') {
9168 next();
9169 decl_initializer(type, sec, c, first, size_only);
9170 skip('}');
9171 } else if (size_only) {
9172 /* just skip expression */
9173 parlevel = 0;
9174 while ((parlevel > 0 || (tok != '}' && tok != ',')) &&
9175 tok != -1) {
9176 if (tok == '(')
9177 parlevel++;
9178 else if (tok == ')')
9179 parlevel--;
9180 next();
9182 } else {
9183 /* currently, we always use constant expression for globals
9184 (may change for scripting case) */
9185 expr_type = EXPR_CONST;
9186 if (!sec)
9187 expr_type = EXPR_ANY;
9188 init_putv(type, sec, c, 0, expr_type);
9192 /* parse an initializer for type 't' if 'has_init' is non zero, and
9193 allocate space in local or global data space ('r' is either
9194 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9195 variable 'v' of scope 'scope' is declared before initializers are
9196 parsed. If 'v' is zero, then a reference to the new object is put
9197 in the value stack. If 'has_init' is 2, a special parsing is done
9198 to handle string constants. */
9199 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
9200 int has_init, int v, int scope)
9202 int size, align, addr, data_offset;
9203 int level;
9204 ParseState saved_parse_state;
9205 TokenString init_str;
9206 Section *sec;
9208 size = type_size(type, &align);
9209 /* If unknown size, we must evaluate it before
9210 evaluating initializers because
9211 initializers can generate global data too
9212 (e.g. string pointers or ISOC99 compound
9213 literals). It also simplifies local
9214 initializers handling */
9215 tok_str_new(&init_str);
9216 if (size < 0) {
9217 if (!has_init)
9218 error("unknown type size");
9219 /* get all init string */
9220 if (has_init == 2) {
9221 /* only get strings */
9222 while (tok == TOK_STR || tok == TOK_LSTR) {
9223 tok_str_add_tok(&init_str);
9224 next();
9226 } else {
9227 level = 0;
9228 while (level > 0 || (tok != ',' && tok != ';')) {
9229 if (tok < 0)
9230 error("unexpected end of file in initializer");
9231 tok_str_add_tok(&init_str);
9232 if (tok == '{')
9233 level++;
9234 else if (tok == '}') {
9235 level--;
9236 if (level <= 0) {
9237 next();
9238 break;
9241 next();
9244 tok_str_add(&init_str, -1);
9245 tok_str_add(&init_str, 0);
9247 /* compute size */
9248 save_parse_state(&saved_parse_state);
9250 macro_ptr = init_str.str;
9251 next();
9252 decl_initializer(type, NULL, 0, 1, 1);
9253 /* prepare second initializer parsing */
9254 macro_ptr = init_str.str;
9255 next();
9257 /* if still unknown size, error */
9258 size = type_size(type, &align);
9259 if (size < 0)
9260 error("unknown type size");
9262 /* take into account specified alignment if bigger */
9263 if (ad->aligned) {
9264 if (ad->aligned > align)
9265 align = ad->aligned;
9266 } else if (ad->packed) {
9267 align = 1;
9269 if ((r & VT_VALMASK) == VT_LOCAL) {
9270 sec = NULL;
9271 if (do_bounds_check && (type->t & VT_ARRAY))
9272 loc--;
9273 loc = (loc - size) & -align;
9274 addr = loc;
9275 /* handles bounds */
9276 /* XXX: currently, since we do only one pass, we cannot track
9277 '&' operators, so we add only arrays */
9278 if (do_bounds_check && (type->t & VT_ARRAY)) {
9279 unsigned long *bounds_ptr;
9280 /* add padding between regions */
9281 loc--;
9282 /* then add local bound info */
9283 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
9284 bounds_ptr[0] = addr;
9285 bounds_ptr[1] = size;
9287 if (v) {
9288 /* local variable */
9289 sym_push(v, type, r, addr);
9290 } else {
9291 /* push local reference */
9292 vset(type, r, addr);
9294 } else {
9295 Sym *sym;
9297 sym = NULL;
9298 if (v && scope == VT_CONST) {
9299 /* see if the symbol was already defined */
9300 sym = sym_find(v);
9301 if (sym) {
9302 if (!is_compatible_types(&sym->type, type))
9303 error("incompatible types for redefinition of '%s'",
9304 get_tok_str(v, NULL));
9305 if (sym->type.t & VT_EXTERN) {
9306 /* if the variable is extern, it was not allocated */
9307 sym->type.t &= ~VT_EXTERN;
9308 /* set array size if it was ommited in extern
9309 declaration */
9310 if ((sym->type.t & VT_ARRAY) &&
9311 sym->type.ref->c < 0 &&
9312 type->ref->c >= 0)
9313 sym->type.ref->c = type->ref->c;
9314 } else {
9315 /* we accept several definitions of the same
9316 global variable. this is tricky, because we
9317 must play with the SHN_COMMON type of the symbol */
9318 /* XXX: should check if the variable was already
9319 initialized. It is incorrect to initialized it
9320 twice */
9321 /* no init data, we won't add more to the symbol */
9322 if (!has_init)
9323 goto no_alloc;
9328 /* allocate symbol in corresponding section */
9329 sec = ad->section;
9330 if (!sec) {
9331 if (has_init)
9332 sec = data_section;
9333 else if (tcc_state->nocommon)
9334 sec = bss_section;
9336 if (sec) {
9337 data_offset = sec->data_offset;
9338 data_offset = (data_offset + align - 1) & -align;
9339 addr = data_offset;
9340 /* very important to increment global pointer at this time
9341 because initializers themselves can create new initializers */
9342 data_offset += size;
9343 /* add padding if bound check */
9344 if (do_bounds_check)
9345 data_offset++;
9346 sec->data_offset = data_offset;
9347 /* allocate section space to put the data */
9348 if (sec->sh_type != SHT_NOBITS &&
9349 data_offset > sec->data_allocated)
9350 section_realloc(sec, data_offset);
9351 /* align section if needed */
9352 if (align > sec->sh_addralign)
9353 sec->sh_addralign = align;
9354 } else {
9355 addr = 0; /* avoid warning */
9358 if (v) {
9359 if (scope != VT_CONST || !sym) {
9360 sym = sym_push(v, type, r | VT_SYM, 0);
9362 /* update symbol definition */
9363 if (sec) {
9364 put_extern_sym(sym, sec, addr, size);
9365 } else {
9366 ElfW(Sym) *esym;
9367 /* put a common area */
9368 put_extern_sym(sym, NULL, align, size);
9369 /* XXX: find a nicer way */
9370 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
9371 esym->st_shndx = SHN_COMMON;
9373 } else {
9374 CValue cval;
9376 /* push global reference */
9377 sym = get_sym_ref(type, sec, addr, size);
9378 cval.ul = 0;
9379 vsetc(type, VT_CONST | VT_SYM, &cval);
9380 vtop->sym = sym;
9383 /* handles bounds now because the symbol must be defined
9384 before for the relocation */
9385 if (do_bounds_check) {
9386 unsigned long *bounds_ptr;
9388 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_32);
9389 /* then add global bound info */
9390 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
9391 bounds_ptr[0] = 0; /* relocated */
9392 bounds_ptr[1] = size;
9395 if (has_init) {
9396 decl_initializer(type, sec, addr, 1, 0);
9397 /* restore parse state if needed */
9398 if (init_str.str) {
9399 tok_str_free(init_str.str);
9400 restore_parse_state(&saved_parse_state);
9403 no_alloc: ;
9406 void put_func_debug(Sym *sym)
9408 char buf[512];
9410 /* stabs info */
9411 /* XXX: we put here a dummy type */
9412 snprintf(buf, sizeof(buf), "%s:%c1",
9413 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
9414 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
9415 cur_text_section, sym->c);
9416 /* //gr gdb wants a line at the function */
9417 put_stabn(N_SLINE, 0, file->line_num, 0);
9418 last_ind = 0;
9419 last_line_num = 0;
9422 /* parse an old style function declaration list */
9423 /* XXX: check multiple parameter */
9424 static void func_decl_list(Sym *func_sym)
9426 AttributeDef ad;
9427 int v;
9428 Sym *s;
9429 CType btype, type;
9431 /* parse each declaration */
9432 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF) {
9433 if (!parse_btype(&btype, &ad))
9434 expect("declaration list");
9435 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9436 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9437 tok == ';') {
9438 /* we accept no variable after */
9439 } else {
9440 for(;;) {
9441 type = btype;
9442 type_decl(&type, &ad, &v, TYPE_DIRECT);
9443 /* find parameter in function parameter list */
9444 s = func_sym->next;
9445 while (s != NULL) {
9446 if ((s->v & ~SYM_FIELD) == v)
9447 goto found;
9448 s = s->next;
9450 error("declaration for parameter '%s' but no such parameter",
9451 get_tok_str(v, NULL));
9452 found:
9453 /* check that no storage specifier except 'register' was given */
9454 if (type.t & VT_STORAGE)
9455 error("storage class specified for '%s'", get_tok_str(v, NULL));
9456 convert_parameter_type(&type);
9457 /* we can add the type (NOTE: it could be local to the function) */
9458 s->type = type;
9459 /* accept other parameters */
9460 if (tok == ',')
9461 next();
9462 else
9463 break;
9466 skip(';');
9470 /* parse a function defined by symbol 'sym' and generate its code in
9471 'cur_text_section' */
9472 static void gen_function(Sym *sym)
9474 int saved_nocode_wanted = nocode_wanted;
9475 nocode_wanted = 0;
9476 ind = cur_text_section->data_offset;
9477 /* NOTE: we patch the symbol size later */
9478 put_extern_sym(sym, cur_text_section, ind, 0);
9479 funcname = get_tok_str(sym->v, NULL);
9480 func_ind = ind;
9481 /* put debug symbol */
9482 if (do_debug)
9483 put_func_debug(sym);
9484 /* push a dummy symbol to enable local sym storage */
9485 sym_push2(&local_stack, SYM_FIELD, 0, 0);
9486 gfunc_prolog(&sym->type);
9487 rsym = 0;
9488 block(NULL, NULL, NULL, NULL, 0, 0);
9489 gsym(rsym);
9490 gfunc_epilog();
9491 cur_text_section->data_offset = ind;
9492 label_pop(&global_label_stack, NULL);
9493 sym_pop(&local_stack, NULL); /* reset local stack */
9494 /* end of function */
9495 /* patch symbol size */
9496 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
9497 ind - func_ind;
9498 if (do_debug) {
9499 put_stabn(N_FUN, 0, 0, ind - func_ind);
9501 /* It's better to crash than to generate wrong code */
9502 cur_text_section = NULL;
9503 funcname = ""; /* for safety */
9504 func_vt.t = VT_VOID; /* for safety */
9505 ind = 0; /* for safety */
9506 nocode_wanted = saved_nocode_wanted;
9509 static void gen_inline_functions(void)
9511 Sym *sym;
9512 CType *type;
9513 int *str, inline_generated;
9515 /* iterate while inline function are referenced */
9516 for(;;) {
9517 inline_generated = 0;
9518 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9519 type = &sym->type;
9520 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9521 (type->t & (VT_STATIC | VT_INLINE)) ==
9522 (VT_STATIC | VT_INLINE) &&
9523 sym->c != 0) {
9524 /* the function was used: generate its code and
9525 convert it to a normal function */
9526 str = INLINE_DEF(sym->r);
9527 sym->r = VT_SYM | VT_CONST;
9528 sym->type.t &= ~VT_INLINE;
9530 macro_ptr = str;
9531 next();
9532 cur_text_section = text_section;
9533 gen_function(sym);
9534 macro_ptr = NULL; /* fail safe */
9536 tok_str_free(str);
9537 inline_generated = 1;
9540 if (!inline_generated)
9541 break;
9544 /* free all remaining inline function tokens */
9545 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9546 type = &sym->type;
9547 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9548 (type->t & (VT_STATIC | VT_INLINE)) ==
9549 (VT_STATIC | VT_INLINE)) {
9550 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9551 if (sym->r == (VT_SYM | VT_CONST)) //gr beware!
9552 continue;
9553 str = INLINE_DEF(sym->r);
9554 tok_str_free(str);
9555 sym->r = 0; /* fail safe */
9560 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9561 static void decl(int l)
9563 int v, has_init, r;
9564 CType type, btype;
9565 Sym *sym;
9566 AttributeDef ad;
9568 while (1) {
9569 if (!parse_btype(&btype, &ad)) {
9570 /* skip redundant ';' */
9571 /* XXX: find more elegant solution */
9572 if (tok == ';') {
9573 next();
9574 continue;
9576 if (l == VT_CONST &&
9577 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
9578 /* global asm block */
9579 asm_global_instr();
9580 continue;
9582 /* special test for old K&R protos without explicit int
9583 type. Only accepted when defining global data */
9584 if (l == VT_LOCAL || tok < TOK_DEFINE)
9585 break;
9586 btype.t = VT_INT;
9588 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9589 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9590 tok == ';') {
9591 /* we accept no variable after */
9592 next();
9593 continue;
9595 while (1) { /* iterate thru each declaration */
9596 type = btype;
9597 type_decl(&type, &ad, &v, TYPE_DIRECT);
9598 #if 0
9600 char buf[500];
9601 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
9602 printf("type = '%s'\n", buf);
9604 #endif
9605 if ((type.t & VT_BTYPE) == VT_FUNC) {
9606 /* if old style function prototype, we accept a
9607 declaration list */
9608 sym = type.ref;
9609 if (sym->c == FUNC_OLD)
9610 func_decl_list(sym);
9613 if (tok == '{') {
9614 if (l == VT_LOCAL)
9615 error("cannot use local functions");
9616 if ((type.t & VT_BTYPE) != VT_FUNC)
9617 expect("function definition");
9619 /* reject abstract declarators in function definition */
9620 sym = type.ref;
9621 while ((sym = sym->next) != NULL)
9622 if (!(sym->v & ~SYM_FIELD))
9623 expect("identifier");
9625 /* XXX: cannot do better now: convert extern line to static inline */
9626 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
9627 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
9629 sym = sym_find(v);
9630 if (sym) {
9631 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
9632 goto func_error1;
9633 /* specific case: if not func_call defined, we put
9634 the one of the prototype */
9635 /* XXX: should have default value */
9636 r = sym->type.ref->r;
9637 if (FUNC_CALL(r) != FUNC_CDECL
9638 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
9639 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
9640 if (FUNC_EXPORT(r))
9641 FUNC_EXPORT(type.ref->r) = 1;
9643 if (!is_compatible_types(&sym->type, &type)) {
9644 func_error1:
9645 error("incompatible types for redefinition of '%s'",
9646 get_tok_str(v, NULL));
9648 /* if symbol is already defined, then put complete type */
9649 sym->type = type;
9650 } else {
9651 /* put function symbol */
9652 sym = global_identifier_push(v, type.t, 0);
9653 sym->type.ref = type.ref;
9656 /* static inline functions are just recorded as a kind
9657 of macro. Their code will be emitted at the end of
9658 the compilation unit only if they are used */
9659 if ((type.t & (VT_INLINE | VT_STATIC)) ==
9660 (VT_INLINE | VT_STATIC)) {
9661 TokenString func_str;
9662 int block_level;
9664 tok_str_new(&func_str);
9666 block_level = 0;
9667 for(;;) {
9668 int t;
9669 if (tok == TOK_EOF)
9670 error("unexpected end of file");
9671 tok_str_add_tok(&func_str);
9672 t = tok;
9673 next();
9674 if (t == '{') {
9675 block_level++;
9676 } else if (t == '}') {
9677 block_level--;
9678 if (block_level == 0)
9679 break;
9682 tok_str_add(&func_str, -1);
9683 tok_str_add(&func_str, 0);
9684 INLINE_DEF(sym->r) = func_str.str;
9685 } else {
9686 /* compute text section */
9687 cur_text_section = ad.section;
9688 if (!cur_text_section)
9689 cur_text_section = text_section;
9690 sym->r = VT_SYM | VT_CONST;
9691 gen_function(sym);
9693 break;
9694 } else {
9695 if (btype.t & VT_TYPEDEF) {
9696 /* save typedefed type */
9697 /* XXX: test storage specifiers ? */
9698 sym = sym_push(v, &type, 0, 0);
9699 sym->type.t |= VT_TYPEDEF;
9700 } else if ((type.t & VT_BTYPE) == VT_FUNC) {
9701 /* external function definition */
9702 /* specific case for func_call attribute */
9703 if (ad.func_attr)
9704 type.ref->r = ad.func_attr;
9705 external_sym(v, &type, 0);
9706 } else {
9707 /* not lvalue if array */
9708 r = 0;
9709 if (!(type.t & VT_ARRAY))
9710 r |= lvalue_type(type.t);
9711 has_init = (tok == '=');
9712 if ((btype.t & VT_EXTERN) ||
9713 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
9714 !has_init && l == VT_CONST && type.ref->c < 0)) {
9715 /* external variable */
9716 /* NOTE: as GCC, uninitialized global static
9717 arrays of null size are considered as
9718 extern */
9719 external_sym(v, &type, r);
9720 } else {
9721 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
9722 if (type.t & VT_STATIC)
9723 r |= VT_CONST;
9724 else
9725 r |= l;
9726 if (has_init)
9727 next();
9728 decl_initializer_alloc(&type, &ad, r,
9729 has_init, v, l);
9732 if (tok != ',') {
9733 skip(';');
9734 break;
9736 next();
9742 /* better than nothing, but needs extension to handle '-E' option
9743 correctly too */
9744 static void preprocess_init(TCCState *s1)
9746 s1->include_stack_ptr = s1->include_stack;
9747 /* XXX: move that before to avoid having to initialize
9748 file->ifdef_stack_ptr ? */
9749 s1->ifdef_stack_ptr = s1->ifdef_stack;
9750 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
9752 /* XXX: not ANSI compliant: bound checking says error */
9753 vtop = vstack - 1;
9754 s1->pack_stack[0] = 0;
9755 s1->pack_stack_ptr = s1->pack_stack;
9758 /* compile the C file opened in 'file'. Return non zero if errors. */
9759 static int tcc_compile(TCCState *s1)
9761 Sym *define_start;
9762 char buf[512];
9763 volatile int section_sym;
9765 #ifdef INC_DEBUG
9766 printf("%s: **** new file\n", file->filename);
9767 #endif
9768 preprocess_init(s1);
9770 cur_text_section = NULL;
9771 funcname = "";
9772 anon_sym = SYM_FIRST_ANOM;
9774 /* file info: full path + filename */
9775 section_sym = 0; /* avoid warning */
9776 if (do_debug) {
9777 section_sym = put_elf_sym(symtab_section, 0, 0,
9778 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
9779 text_section->sh_num, NULL);
9780 getcwd(buf, sizeof(buf));
9781 #ifdef _WIN32
9782 normalize_slashes(buf);
9783 #endif
9784 pstrcat(buf, sizeof(buf), "/");
9785 put_stabs_r(buf, N_SO, 0, 0,
9786 text_section->data_offset, text_section, section_sym);
9787 put_stabs_r(file->filename, N_SO, 0, 0,
9788 text_section->data_offset, text_section, section_sym);
9790 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9791 symbols can be safely used */
9792 put_elf_sym(symtab_section, 0, 0,
9793 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
9794 SHN_ABS, file->filename);
9796 /* define some often used types */
9797 int_type.t = VT_INT;
9799 char_pointer_type.t = VT_BYTE;
9800 mk_pointer(&char_pointer_type);
9802 func_old_type.t = VT_FUNC;
9803 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
9805 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9806 float_type.t = VT_FLOAT;
9807 double_type.t = VT_DOUBLE;
9809 func_float_type.t = VT_FUNC;
9810 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
9811 func_double_type.t = VT_FUNC;
9812 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
9813 #endif
9815 #if 0
9816 /* define 'void *alloca(unsigned int)' builtin function */
9818 Sym *s1;
9820 p = anon_sym++;
9821 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
9822 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
9823 s1->next = NULL;
9824 sym->next = s1;
9825 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
9827 #endif
9829 define_start = define_stack;
9830 nocode_wanted = 1;
9832 if (setjmp(s1->error_jmp_buf) == 0) {
9833 s1->nb_errors = 0;
9834 s1->error_set_jmp_enabled = 1;
9836 ch = file->buf_ptr[0];
9837 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9838 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
9839 next();
9840 decl(VT_CONST);
9841 if (tok != TOK_EOF)
9842 expect("declaration");
9844 /* end of translation unit info */
9845 if (do_debug) {
9846 put_stabs_r(NULL, N_SO, 0, 0,
9847 text_section->data_offset, text_section, section_sym);
9850 s1->error_set_jmp_enabled = 0;
9852 /* reset define stack, but leave -Dsymbols (may be incorrect if
9853 they are undefined) */
9854 free_defines(define_start);
9856 gen_inline_functions();
9858 sym_pop(&global_stack, NULL);
9859 sym_pop(&local_stack, NULL);
9861 return s1->nb_errors != 0 ? -1 : 0;
9864 /* Preprocess the current file */
9865 /* XXX: add line and file infos,
9866 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9867 * not preserved)
9869 static int tcc_preprocess(TCCState *s1)
9871 Sym *define_start;
9872 BufferedFile *file_ref;
9873 int token_seen, line_ref;
9875 preprocess_init(s1);
9876 define_start = define_stack;
9877 ch = file->buf_ptr[0];
9879 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9880 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
9881 PARSE_FLAG_LINEFEED;
9883 token_seen = 0;
9884 line_ref = 0;
9885 file_ref = NULL;
9887 for (;;) {
9888 next();
9889 if (tok == TOK_EOF) {
9890 break;
9891 } else if (tok == TOK_LINEFEED) {
9892 if (!token_seen)
9893 continue;
9894 ++line_ref;
9895 token_seen = 0;
9896 } else if (token_seen) {
9897 fwrite(tok_spaces.data, tok_spaces.size, 1, s1->outfile);
9898 } else {
9899 int d = file->line_num - line_ref;
9900 if (file != file_ref || d < 0 || d >= 8)
9901 fprintf(s1->outfile, "# %d \"%s\"\n", file->line_num, file->filename);
9902 else
9903 while (d)
9904 fputs("\n", s1->outfile), --d;
9905 line_ref = (file_ref = file)->line_num;
9906 token_seen = 1;
9908 fputs(get_tok_str(tok, &tokc), s1->outfile);
9910 free_defines(define_start);
9911 return 0;
9914 #ifdef LIBTCC
9915 int tcc_compile_string(TCCState *s, const char *str)
9917 BufferedFile bf1, *bf = &bf1;
9918 int ret, len;
9919 char *buf;
9921 /* init file structure */
9922 bf->fd = -1;
9923 /* XXX: avoid copying */
9924 len = strlen(str);
9925 buf = tcc_malloc(len + 1);
9926 if (!buf)
9927 return -1;
9928 memcpy(buf, str, len);
9929 buf[len] = CH_EOB;
9930 bf->buf_ptr = buf;
9931 bf->buf_end = buf + len;
9932 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
9933 bf->line_num = 1;
9934 file = bf;
9935 ret = tcc_compile(s);
9936 file = NULL;
9937 tcc_free(buf);
9939 /* currently, no need to close */
9940 return ret;
9942 #endif
9944 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9945 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
9947 BufferedFile bf1, *bf = &bf1;
9949 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
9950 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
9951 /* default value */
9952 if (!value)
9953 value = "1";
9954 pstrcat(bf->buffer, IO_BUF_SIZE, value);
9956 /* init file structure */
9957 bf->fd = -1;
9958 bf->buf_ptr = bf->buffer;
9959 bf->buf_end = bf->buffer + strlen(bf->buffer);
9960 *bf->buf_end = CH_EOB;
9961 bf->filename[0] = '\0';
9962 bf->line_num = 1;
9963 file = bf;
9965 s1->include_stack_ptr = s1->include_stack;
9967 /* parse with define parser */
9968 ch = file->buf_ptr[0];
9969 next_nomacro();
9970 parse_define();
9971 file = NULL;
9974 /* undefine a preprocessor symbol */
9975 void tcc_undefine_symbol(TCCState *s1, const char *sym)
9977 TokenSym *ts;
9978 Sym *s;
9979 ts = tok_alloc(sym, strlen(sym));
9980 s = define_find(ts->tok);
9981 /* undefine symbol by putting an invalid name */
9982 if (s)
9983 define_undef(s);
9986 #ifdef CONFIG_TCC_ASM
9988 #ifdef TCC_TARGET_I386
9989 #include "i386-asm.c"
9990 #endif
9991 #include "tccasm.c"
9993 #else
9994 static void asm_instr(void)
9996 error("inline asm() not supported");
9998 static void asm_global_instr(void)
10000 error("inline asm() not supported");
10002 #endif
10004 #include "tccelf.c"
10006 #ifdef TCC_TARGET_COFF
10007 #include "tcccoff.c"
10008 #endif
10010 #ifdef TCC_TARGET_PE
10011 #include "tccpe.c"
10012 #endif
10014 /* print the position in the source file of PC value 'pc' by reading
10015 the stabs debug information */
10016 static void rt_printline(unsigned long wanted_pc)
10018 Stab_Sym *sym, *sym_end;
10019 char func_name[128], last_func_name[128];
10020 unsigned long func_addr, last_pc, pc;
10021 const char *incl_files[INCLUDE_STACK_SIZE];
10022 int incl_index, len, last_line_num, i;
10023 const char *str, *p;
10025 fprintf(stderr, "0x%08lx:", wanted_pc);
10027 func_name[0] = '\0';
10028 func_addr = 0;
10029 incl_index = 0;
10030 last_func_name[0] = '\0';
10031 last_pc = 0xffffffff;
10032 last_line_num = 1;
10033 sym = (Stab_Sym *)stab_section->data + 1;
10034 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
10035 while (sym < sym_end) {
10036 switch(sym->n_type) {
10037 /* function start or end */
10038 case N_FUN:
10039 if (sym->n_strx == 0) {
10040 /* we test if between last line and end of function */
10041 pc = sym->n_value + func_addr;
10042 if (wanted_pc >= last_pc && wanted_pc < pc)
10043 goto found;
10044 func_name[0] = '\0';
10045 func_addr = 0;
10046 } else {
10047 str = stabstr_section->data + sym->n_strx;
10048 p = strchr(str, ':');
10049 if (!p) {
10050 pstrcpy(func_name, sizeof(func_name), str);
10051 } else {
10052 len = p - str;
10053 if (len > sizeof(func_name) - 1)
10054 len = sizeof(func_name) - 1;
10055 memcpy(func_name, str, len);
10056 func_name[len] = '\0';
10058 func_addr = sym->n_value;
10060 break;
10061 /* line number info */
10062 case N_SLINE:
10063 pc = sym->n_value + func_addr;
10064 if (wanted_pc >= last_pc && wanted_pc < pc)
10065 goto found;
10066 last_pc = pc;
10067 last_line_num = sym->n_desc;
10068 /* XXX: slow! */
10069 strcpy(last_func_name, func_name);
10070 break;
10071 /* include files */
10072 case N_BINCL:
10073 str = stabstr_section->data + sym->n_strx;
10074 add_incl:
10075 if (incl_index < INCLUDE_STACK_SIZE) {
10076 incl_files[incl_index++] = str;
10078 break;
10079 case N_EINCL:
10080 if (incl_index > 1)
10081 incl_index--;
10082 break;
10083 case N_SO:
10084 if (sym->n_strx == 0) {
10085 incl_index = 0; /* end of translation unit */
10086 } else {
10087 str = stabstr_section->data + sym->n_strx;
10088 /* do not add path */
10089 len = strlen(str);
10090 if (len > 0 && str[len - 1] != '/')
10091 goto add_incl;
10093 break;
10095 sym++;
10098 /* second pass: we try symtab symbols (no line number info) */
10099 incl_index = 0;
10101 ElfW(Sym) *sym, *sym_end;
10102 int type;
10104 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
10105 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
10106 sym < sym_end;
10107 sym++) {
10108 type = ELFW(ST_TYPE)(sym->st_info);
10109 if (type == STT_FUNC) {
10110 if (wanted_pc >= sym->st_value &&
10111 wanted_pc < sym->st_value + sym->st_size) {
10112 pstrcpy(last_func_name, sizeof(last_func_name),
10113 strtab_section->data + sym->st_name);
10114 goto found;
10119 /* did not find any info: */
10120 fprintf(stderr, " ???\n");
10121 return;
10122 found:
10123 if (last_func_name[0] != '\0') {
10124 fprintf(stderr, " %s()", last_func_name);
10126 if (incl_index > 0) {
10127 fprintf(stderr, " (%s:%d",
10128 incl_files[incl_index - 1], last_line_num);
10129 for(i = incl_index - 2; i >= 0; i--)
10130 fprintf(stderr, ", included from %s", incl_files[i]);
10131 fprintf(stderr, ")");
10133 fprintf(stderr, "\n");
10136 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10138 #ifdef __i386__
10140 /* fix for glibc 2.1 */
10141 #ifndef REG_EIP
10142 #define REG_EIP EIP
10143 #define REG_EBP EBP
10144 #endif
10146 /* return the PC at frame level 'level'. Return non zero if not found */
10147 static int rt_get_caller_pc(unsigned long *paddr,
10148 ucontext_t *uc, int level)
10150 unsigned long fp;
10151 int i;
10153 if (level == 0) {
10154 #if defined(__FreeBSD__)
10155 *paddr = uc->uc_mcontext.mc_eip;
10156 #elif defined(__dietlibc__)
10157 *paddr = uc->uc_mcontext.eip;
10158 #else
10159 *paddr = uc->uc_mcontext.gregs[REG_EIP];
10160 #endif
10161 return 0;
10162 } else {
10163 #if defined(__FreeBSD__)
10164 fp = uc->uc_mcontext.mc_ebp;
10165 #elif defined(__dietlibc__)
10166 fp = uc->uc_mcontext.ebp;
10167 #else
10168 fp = uc->uc_mcontext.gregs[REG_EBP];
10169 #endif
10170 for(i=1;i<level;i++) {
10171 /* XXX: check address validity with program info */
10172 if (fp <= 0x1000 || fp >= 0xc0000000)
10173 return -1;
10174 fp = ((unsigned long *)fp)[0];
10176 *paddr = ((unsigned long *)fp)[1];
10177 return 0;
10180 #elif defined(__x86_64__)
10181 /* return the PC at frame level 'level'. Return non zero if not found */
10182 static int rt_get_caller_pc(unsigned long *paddr,
10183 ucontext_t *uc, int level)
10185 unsigned long fp;
10186 int i;
10188 if (level == 0) {
10189 /* XXX: only support linux */
10190 *paddr = uc->uc_mcontext.gregs[REG_RIP];
10191 return 0;
10192 } else {
10193 fp = uc->uc_mcontext.gregs[REG_RBP];
10194 for(i=1;i<level;i++) {
10195 /* XXX: check address validity with program info */
10196 if (fp <= 0x1000 || fp >= 0xc0000000)
10197 return -1;
10198 fp = ((unsigned long *)fp)[0];
10200 *paddr = ((unsigned long *)fp)[1];
10201 return 0;
10204 #else
10206 #warning add arch specific rt_get_caller_pc()
10208 static int rt_get_caller_pc(unsigned long *paddr,
10209 ucontext_t *uc, int level)
10211 return -1;
10213 #endif
10215 /* emit a run time error at position 'pc' */
10216 void rt_error(ucontext_t *uc, const char *fmt, ...)
10218 va_list ap;
10219 unsigned long pc;
10220 int i;
10222 va_start(ap, fmt);
10223 fprintf(stderr, "Runtime error: ");
10224 vfprintf(stderr, fmt, ap);
10225 fprintf(stderr, "\n");
10226 for(i=0;i<num_callers;i++) {
10227 if (rt_get_caller_pc(&pc, uc, i) < 0)
10228 break;
10229 if (i == 0)
10230 fprintf(stderr, "at ");
10231 else
10232 fprintf(stderr, "by ");
10233 rt_printline(pc);
10235 exit(255);
10236 va_end(ap);
10239 /* signal handler for fatal errors */
10240 static void sig_error(int signum, siginfo_t *siginf, void *puc)
10242 ucontext_t *uc = puc;
10244 switch(signum) {
10245 case SIGFPE:
10246 switch(siginf->si_code) {
10247 case FPE_INTDIV:
10248 case FPE_FLTDIV:
10249 rt_error(uc, "division by zero");
10250 break;
10251 default:
10252 rt_error(uc, "floating point exception");
10253 break;
10255 break;
10256 case SIGBUS:
10257 case SIGSEGV:
10258 if (rt_bound_error_msg && *rt_bound_error_msg)
10259 rt_error(uc, *rt_bound_error_msg);
10260 else
10261 rt_error(uc, "dereferencing invalid pointer");
10262 break;
10263 case SIGILL:
10264 rt_error(uc, "illegal instruction");
10265 break;
10266 case SIGABRT:
10267 rt_error(uc, "abort() called");
10268 break;
10269 default:
10270 rt_error(uc, "caught signal %d", signum);
10271 break;
10273 exit(255);
10275 #endif
10277 /* do all relocations (needed before using tcc_get_symbol()) */
10278 int tcc_relocate(TCCState *s1)
10280 Section *s;
10281 int i;
10283 s1->nb_errors = 0;
10285 #ifdef TCC_TARGET_PE
10286 pe_add_runtime(s1);
10287 #else
10288 tcc_add_runtime(s1);
10289 #endif
10291 relocate_common_syms();
10293 tcc_add_linker_symbols(s1);
10294 #ifndef TCC_TARGET_PE
10295 build_got_entries(s1);
10296 #endif
10298 #ifdef TCC_TARGET_X86_64
10300 /* If the distance of two sections are longer than 32bit, our
10301 program will crash. Let's combine all sections which are
10302 necessary to run the program into a single buffer in the
10303 text section */
10304 unsigned char *p;
10305 int size;
10306 /* calculate the size of buffers we need */
10307 size = 0;
10308 for(i = 1; i < s1->nb_sections; i++) {
10309 s = s1->sections[i];
10310 if (s->sh_flags & SHF_ALLOC) {
10311 size += s->data_offset;
10314 /* double the size of the buffer for got and plt entries
10315 XXX: calculate exact size for them? */
10316 section_realloc(text_section, size * 2);
10317 p = text_section->data + text_section->data_offset;
10318 /* we will put got and plt after this offset */
10319 text_section->data_offset = size;
10321 for(i = 1; i < s1->nb_sections; i++) {
10322 s = s1->sections[i];
10323 if (s->sh_flags & SHF_ALLOC) {
10324 if (s != text_section && s->data_offset) {
10325 if (s->sh_type == SHT_NOBITS) {
10326 /* for bss section */
10327 memset(p, 0, s->data_offset);
10328 } else {
10329 memcpy(p, s->data, s->data_offset);
10330 tcc_free(s->data);
10332 s->data = p;
10333 /* we won't free s->data for this section */
10334 s->data_allocated = 0;
10335 p += s->data_offset;
10337 s->sh_addr = (unsigned long)s->data;
10341 #else
10342 /* compute relocation address : section are relocated in place. We
10343 also alloc the bss space */
10344 for(i = 1; i < s1->nb_sections; i++) {
10345 s = s1->sections[i];
10346 if (s->sh_flags & SHF_ALLOC) {
10347 if (s->sh_type == SHT_NOBITS)
10348 s->data = tcc_mallocz(s->data_offset);
10349 s->sh_addr = (unsigned long)s->data;
10352 #endif
10354 relocate_syms(s1, 1);
10356 if (s1->nb_errors != 0)
10357 return -1;
10359 /* relocate each section */
10360 for(i = 1; i < s1->nb_sections; i++) {
10361 s = s1->sections[i];
10362 if (s->reloc)
10363 relocate_section(s1, s);
10366 /* mark executable sections as executable in memory */
10367 for(i = 1; i < s1->nb_sections; i++) {
10368 s = s1->sections[i];
10369 if ((s->sh_flags & (SHF_ALLOC | SHF_EXECINSTR)) ==
10370 (SHF_ALLOC | SHF_EXECINSTR))
10371 set_pages_executable(s->data, s->data_offset);
10373 return 0;
10376 /* launch the compiled program with the given arguments */
10377 int tcc_run(TCCState *s1, int argc, char **argv)
10379 int (*prog_main)(int, char **);
10381 if (tcc_relocate(s1) < 0)
10382 return -1;
10384 prog_main = tcc_get_symbol_err(s1, "main");
10386 if (do_debug) {
10387 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10388 error("debug mode currently not available for Windows");
10389 #else
10390 struct sigaction sigact;
10391 /* install TCC signal handlers to print debug info on fatal
10392 runtime errors */
10393 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
10394 sigact.sa_sigaction = sig_error;
10395 sigemptyset(&sigact.sa_mask);
10396 sigaction(SIGFPE, &sigact, NULL);
10397 sigaction(SIGILL, &sigact, NULL);
10398 sigaction(SIGSEGV, &sigact, NULL);
10399 sigaction(SIGBUS, &sigact, NULL);
10400 sigaction(SIGABRT, &sigact, NULL);
10401 #endif
10404 #ifdef CONFIG_TCC_BCHECK
10405 if (do_bounds_check) {
10406 void (*bound_init)(void);
10408 /* set error function */
10409 rt_bound_error_msg = (void *)tcc_get_symbol_err(s1,
10410 "__bound_error_msg");
10412 /* XXX: use .init section so that it also work in binary ? */
10413 bound_init = (void *)tcc_get_symbol_err(s1, "__bound_init");
10414 bound_init();
10416 #endif
10417 return (*prog_main)(argc, argv);
10420 void tcc_memstats(void)
10422 #ifdef MEM_DEBUG
10423 printf("memory in use: %d\n", mem_cur_size);
10424 #endif
10427 static void tcc_cleanup(void)
10429 int i, n;
10431 if (NULL == tcc_state)
10432 return;
10433 tcc_state = NULL;
10435 /* free -D defines */
10436 free_defines(NULL);
10438 /* free tokens */
10439 n = tok_ident - TOK_IDENT;
10440 for(i = 0; i < n; i++)
10441 tcc_free(table_ident[i]);
10442 tcc_free(table_ident);
10444 /* free sym_pools */
10445 dynarray_reset(&sym_pools, &nb_sym_pools);
10446 /* string buffer */
10447 cstr_free(&tokcstr);
10448 /* reset symbol stack */
10449 sym_free_first = NULL;
10450 /* cleanup from error/setjmp */
10451 macro_ptr = NULL;
10454 TCCState *tcc_new(void)
10456 const char *p, *r;
10457 TCCState *s;
10458 TokenSym *ts;
10459 int i, c;
10461 tcc_cleanup();
10463 s = tcc_mallocz(sizeof(TCCState));
10464 if (!s)
10465 return NULL;
10466 tcc_state = s;
10467 s->output_type = TCC_OUTPUT_MEMORY;
10469 /* init isid table */
10470 for(i=CH_EOF;i<256;i++)
10471 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
10473 /* add all tokens */
10474 table_ident = NULL;
10475 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
10477 tok_ident = TOK_IDENT;
10478 p = tcc_keywords;
10479 while (*p) {
10480 r = p;
10481 for(;;) {
10482 c = *r++;
10483 if (c == '\0')
10484 break;
10486 ts = tok_alloc(p, r - p - 1);
10487 p = r;
10490 /* we add dummy defines for some special macros to speed up tests
10491 and to have working defined() */
10492 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
10493 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
10494 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
10495 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
10497 /* standard defines */
10498 tcc_define_symbol(s, "__STDC__", NULL);
10499 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
10500 #if defined(TCC_TARGET_I386)
10501 tcc_define_symbol(s, "__i386__", NULL);
10502 #endif
10503 #if defined(TCC_TARGET_X86_64)
10504 tcc_define_symbol(s, "__x86_64__", NULL);
10505 #endif
10506 #if defined(TCC_TARGET_ARM)
10507 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
10508 tcc_define_symbol(s, "__arm_elf__", NULL);
10509 tcc_define_symbol(s, "__arm_elf", NULL);
10510 tcc_define_symbol(s, "arm_elf", NULL);
10511 tcc_define_symbol(s, "__arm__", NULL);
10512 tcc_define_symbol(s, "__arm", NULL);
10513 tcc_define_symbol(s, "arm", NULL);
10514 tcc_define_symbol(s, "__APCS_32__", NULL);
10515 #endif
10516 #ifdef TCC_TARGET_PE
10517 tcc_define_symbol(s, "_WIN32", NULL);
10518 #else
10519 tcc_define_symbol(s, "__unix__", NULL);
10520 tcc_define_symbol(s, "__unix", NULL);
10521 #if defined(__linux)
10522 tcc_define_symbol(s, "__linux__", NULL);
10523 tcc_define_symbol(s, "__linux", NULL);
10524 #endif
10525 #endif
10526 /* tiny C specific defines */
10527 tcc_define_symbol(s, "__TINYC__", NULL);
10529 /* tiny C & gcc defines */
10530 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
10531 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
10532 #ifdef TCC_TARGET_PE
10533 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
10534 #else
10535 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
10536 #endif
10538 #ifndef TCC_TARGET_PE
10539 /* default library paths */
10540 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
10541 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
10542 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
10543 #endif
10545 /* no section zero */
10546 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
10548 /* create standard sections */
10549 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
10550 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
10551 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
10553 /* symbols are always generated for linking stage */
10554 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
10555 ".strtab",
10556 ".hashtab", SHF_PRIVATE);
10557 strtab_section = symtab_section->link;
10559 /* private symbol table for dynamic symbols */
10560 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
10561 ".dynstrtab",
10562 ".dynhashtab", SHF_PRIVATE);
10563 s->alacarte_link = 1;
10565 #ifdef CHAR_IS_UNSIGNED
10566 s->char_is_unsigned = 1;
10567 #endif
10568 #if defined(TCC_TARGET_PE) && 0
10569 /* XXX: currently the PE linker is not ready to support that */
10570 s->leading_underscore = 1;
10571 #endif
10572 return s;
10575 void tcc_delete(TCCState *s1)
10577 int i;
10579 tcc_cleanup();
10581 /* free all sections */
10582 for(i = 1; i < s1->nb_sections; i++)
10583 free_section(s1->sections[i]);
10584 dynarray_reset(&s1->sections, &s1->nb_sections);
10586 for(i = 0; i < s1->nb_priv_sections; i++)
10587 free_section(s1->priv_sections[i]);
10588 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
10590 /* free any loaded DLLs */
10591 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
10592 DLLReference *ref = s1->loaded_dlls[i];
10593 if ( ref->handle )
10594 dlclose(ref->handle);
10597 /* free loaded dlls array */
10598 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
10600 /* free library paths */
10601 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
10603 /* free include paths */
10604 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
10605 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
10606 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
10608 tcc_free(s1);
10611 int tcc_add_include_path(TCCState *s1, const char *pathname)
10613 char *pathname1;
10615 pathname1 = tcc_strdup(pathname);
10616 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
10617 return 0;
10620 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
10622 char *pathname1;
10624 pathname1 = tcc_strdup(pathname);
10625 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
10626 return 0;
10629 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
10631 const char *ext;
10632 ElfW(Ehdr) ehdr;
10633 int fd, ret;
10634 BufferedFile *saved_file;
10636 /* find source file type with extension */
10637 ext = tcc_fileextension(filename);
10638 if (ext[0])
10639 ext++;
10641 /* open the file */
10642 saved_file = file;
10643 file = tcc_open(s1, filename);
10644 if (!file) {
10645 if (flags & AFF_PRINT_ERROR) {
10646 error_noabort("file '%s' not found", filename);
10648 ret = -1;
10649 goto fail1;
10652 if (flags & AFF_PREPROCESS) {
10653 ret = tcc_preprocess(s1);
10654 } else if (!ext[0] || !strcmp(ext, "c")) {
10655 /* C file assumed */
10656 ret = tcc_compile(s1);
10657 } else
10658 #ifdef CONFIG_TCC_ASM
10659 if (!strcmp(ext, "S")) {
10660 /* preprocessed assembler */
10661 ret = tcc_assemble(s1, 1);
10662 } else if (!strcmp(ext, "s")) {
10663 /* non preprocessed assembler */
10664 ret = tcc_assemble(s1, 0);
10665 } else
10666 #endif
10667 #ifdef TCC_TARGET_PE
10668 if (!strcmp(ext, "def")) {
10669 ret = pe_load_def_file(s1, file->fd);
10670 } else
10671 #endif
10673 fd = file->fd;
10674 /* assume executable format: auto guess file type */
10675 ret = read(fd, &ehdr, sizeof(ehdr));
10676 lseek(fd, 0, SEEK_SET);
10677 if (ret <= 0) {
10678 error_noabort("could not read header");
10679 goto fail;
10680 } else if (ret != sizeof(ehdr)) {
10681 goto try_load_script;
10684 if (ehdr.e_ident[0] == ELFMAG0 &&
10685 ehdr.e_ident[1] == ELFMAG1 &&
10686 ehdr.e_ident[2] == ELFMAG2 &&
10687 ehdr.e_ident[3] == ELFMAG3) {
10688 file->line_num = 0; /* do not display line number if error */
10689 if (ehdr.e_type == ET_REL) {
10690 ret = tcc_load_object_file(s1, fd, 0);
10691 } else if (ehdr.e_type == ET_DYN) {
10692 if (s1->output_type == TCC_OUTPUT_MEMORY) {
10693 #ifdef TCC_TARGET_PE
10694 ret = -1;
10695 #else
10696 void *h;
10697 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
10698 if (h)
10699 ret = 0;
10700 else
10701 ret = -1;
10702 #endif
10703 } else {
10704 ret = tcc_load_dll(s1, fd, filename,
10705 (flags & AFF_REFERENCED_DLL) != 0);
10707 } else {
10708 error_noabort("unrecognized ELF file");
10709 goto fail;
10711 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
10712 file->line_num = 0; /* do not display line number if error */
10713 ret = tcc_load_archive(s1, fd);
10714 } else
10715 #ifdef TCC_TARGET_COFF
10716 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
10717 ret = tcc_load_coff(s1, fd);
10718 } else
10719 #endif
10720 #ifdef TCC_TARGET_PE
10721 if (pe_test_res_file(&ehdr, ret)) {
10722 ret = pe_load_res_file(s1, fd);
10723 } else
10724 #endif
10726 /* as GNU ld, consider it is an ld script if not recognized */
10727 try_load_script:
10728 ret = tcc_load_ldscript(s1);
10729 if (ret < 0) {
10730 error_noabort("unrecognized file type");
10731 goto fail;
10735 the_end:
10736 tcc_close(file);
10737 fail1:
10738 file = saved_file;
10739 return ret;
10740 fail:
10741 ret = -1;
10742 goto the_end;
10745 int tcc_add_file(TCCState *s, const char *filename)
10747 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
10750 int tcc_add_library_path(TCCState *s, const char *pathname)
10752 char *pathname1;
10754 pathname1 = tcc_strdup(pathname);
10755 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
10756 return 0;
10759 /* find and load a dll. Return non zero if not found */
10760 /* XXX: add '-rpath' option support ? */
10761 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
10763 char buf[1024];
10764 int i;
10766 for(i = 0; i < s->nb_library_paths; i++) {
10767 snprintf(buf, sizeof(buf), "%s/%s",
10768 s->library_paths[i], filename);
10769 if (tcc_add_file_internal(s, buf, flags) == 0)
10770 return 0;
10772 return -1;
10775 /* the library name is the same as the argument of the '-l' option */
10776 int tcc_add_library(TCCState *s, const char *libraryname)
10778 char buf[1024];
10779 int i;
10781 /* first we look for the dynamic library if not static linking */
10782 if (!s->static_link) {
10783 #ifdef TCC_TARGET_PE
10784 snprintf(buf, sizeof(buf), "%s.def", libraryname);
10785 #else
10786 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
10787 #endif
10788 if (tcc_add_dll(s, buf, 0) == 0)
10789 return 0;
10792 /* then we look for the static library */
10793 for(i = 0; i < s->nb_library_paths; i++) {
10794 snprintf(buf, sizeof(buf), "%s/lib%s.a",
10795 s->library_paths[i], libraryname);
10796 if (tcc_add_file_internal(s, buf, 0) == 0)
10797 return 0;
10799 return -1;
10802 int tcc_add_symbol(TCCState *s, const char *name, unsigned long val)
10804 add_elf_sym(symtab_section, val, 0,
10805 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
10806 SHN_ABS, name);
10807 return 0;
10810 int tcc_set_output_type(TCCState *s, int output_type)
10812 char buf[1024];
10814 s->output_type = output_type;
10816 if (!s->nostdinc) {
10817 /* default include paths */
10818 /* XXX: reverse order needed if -isystem support */
10819 #ifndef TCC_TARGET_PE
10820 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
10821 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
10822 #endif
10823 snprintf(buf, sizeof(buf), "%s/include", tcc_lib_path);
10824 tcc_add_sysinclude_path(s, buf);
10825 #ifdef TCC_TARGET_PE
10826 snprintf(buf, sizeof(buf), "%s/include/winapi", tcc_lib_path);
10827 tcc_add_sysinclude_path(s, buf);
10828 #endif
10831 /* if bound checking, then add corresponding sections */
10832 #ifdef CONFIG_TCC_BCHECK
10833 if (do_bounds_check) {
10834 /* define symbol */
10835 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
10836 /* create bounds sections */
10837 bounds_section = new_section(s, ".bounds",
10838 SHT_PROGBITS, SHF_ALLOC);
10839 lbounds_section = new_section(s, ".lbounds",
10840 SHT_PROGBITS, SHF_ALLOC);
10842 #endif
10844 if (s->char_is_unsigned) {
10845 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
10848 /* add debug sections */
10849 if (do_debug) {
10850 /* stab symbols */
10851 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
10852 stab_section->sh_entsize = sizeof(Stab_Sym);
10853 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
10854 put_elf_str(stabstr_section, "");
10855 stab_section->link = stabstr_section;
10856 /* put first entry */
10857 put_stabs("", 0, 0, 0, 0);
10860 /* add libc crt1/crti objects */
10861 #ifndef TCC_TARGET_PE
10862 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
10863 !s->nostdlib) {
10864 if (output_type != TCC_OUTPUT_DLL)
10865 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
10866 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
10868 #endif
10870 #ifdef TCC_TARGET_PE
10871 snprintf(buf, sizeof(buf), "%s/lib", tcc_lib_path);
10872 tcc_add_library_path(s, buf);
10873 #endif
10875 return 0;
10878 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10879 #define FD_INVERT 0x0002 /* invert value before storing */
10881 typedef struct FlagDef {
10882 uint16_t offset;
10883 uint16_t flags;
10884 const char *name;
10885 } FlagDef;
10887 static const FlagDef warning_defs[] = {
10888 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
10889 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
10890 { offsetof(TCCState, warn_error), 0, "error" },
10891 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
10892 "implicit-function-declaration" },
10895 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
10896 const char *name, int value)
10898 int i;
10899 const FlagDef *p;
10900 const char *r;
10902 r = name;
10903 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
10904 r += 3;
10905 value = !value;
10907 for(i = 0, p = flags; i < nb_flags; i++, p++) {
10908 if (!strcmp(r, p->name))
10909 goto found;
10911 return -1;
10912 found:
10913 if (p->flags & FD_INVERT)
10914 value = !value;
10915 *(int *)((uint8_t *)s + p->offset) = value;
10916 return 0;
10920 /* set/reset a warning */
10921 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
10923 int i;
10924 const FlagDef *p;
10926 if (!strcmp(warning_name, "all")) {
10927 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
10928 if (p->flags & WD_ALL)
10929 *(int *)((uint8_t *)s + p->offset) = 1;
10931 return 0;
10932 } else {
10933 return set_flag(s, warning_defs, countof(warning_defs),
10934 warning_name, value);
10938 static const FlagDef flag_defs[] = {
10939 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
10940 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
10941 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
10942 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
10945 /* set/reset a flag */
10946 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
10948 return set_flag(s, flag_defs, countof(flag_defs),
10949 flag_name, value);
10952 #if !defined(LIBTCC)
10954 static int64_t getclock_us(void)
10956 #ifdef _WIN32
10957 struct _timeb tb;
10958 _ftime(&tb);
10959 return (tb.time * 1000LL + tb.millitm) * 1000LL;
10960 #else
10961 struct timeval tv;
10962 gettimeofday(&tv, NULL);
10963 return tv.tv_sec * 1000000LL + tv.tv_usec;
10964 #endif
10967 void help(void)
10969 printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10970 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10971 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10972 " [-static] [infile1 infile2...] [-run infile args...]\n"
10973 "\n"
10974 "General options:\n"
10975 " -v display current version, increase verbosity\n"
10976 " -c compile only - generate an object file\n"
10977 " -o outfile set output filename\n"
10978 " -Bdir set tcc internal library path\n"
10979 " -bench output compilation statistics\n"
10980 " -run run compiled source\n"
10981 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10982 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10983 " -w disable all warnings\n"
10984 "Preprocessor options:\n"
10985 " -E preprocess only\n"
10986 " -Idir add include path 'dir'\n"
10987 " -Dsym[=val] define 'sym' with value 'val'\n"
10988 " -Usym undefine 'sym'\n"
10989 "Linker options:\n"
10990 " -Ldir add library path 'dir'\n"
10991 " -llib link with dynamic or static library 'lib'\n"
10992 " -shared generate a shared library\n"
10993 " -soname set name for shared library to be used at runtime\n"
10994 " -static static linking\n"
10995 " -rdynamic export all global symbols to dynamic linker\n"
10996 " -r generate (relocatable) object file\n"
10997 "Debugger options:\n"
10998 " -g generate runtime debug info\n"
10999 #ifdef CONFIG_TCC_BCHECK
11000 " -b compile with built-in memory and bounds checker (implies -g)\n"
11001 #endif
11002 " -bt N show N callers in stack traces\n"
11006 #define TCC_OPTION_HAS_ARG 0x0001
11007 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
11009 typedef struct TCCOption {
11010 const char *name;
11011 uint16_t index;
11012 uint16_t flags;
11013 } TCCOption;
11015 enum {
11016 TCC_OPTION_HELP,
11017 TCC_OPTION_I,
11018 TCC_OPTION_D,
11019 TCC_OPTION_U,
11020 TCC_OPTION_L,
11021 TCC_OPTION_B,
11022 TCC_OPTION_l,
11023 TCC_OPTION_bench,
11024 TCC_OPTION_bt,
11025 TCC_OPTION_b,
11026 TCC_OPTION_g,
11027 TCC_OPTION_c,
11028 TCC_OPTION_static,
11029 TCC_OPTION_shared,
11030 TCC_OPTION_soname,
11031 TCC_OPTION_o,
11032 TCC_OPTION_r,
11033 TCC_OPTION_Wl,
11034 TCC_OPTION_W,
11035 TCC_OPTION_O,
11036 TCC_OPTION_m,
11037 TCC_OPTION_f,
11038 TCC_OPTION_nostdinc,
11039 TCC_OPTION_nostdlib,
11040 TCC_OPTION_print_search_dirs,
11041 TCC_OPTION_rdynamic,
11042 TCC_OPTION_run,
11043 TCC_OPTION_v,
11044 TCC_OPTION_w,
11045 TCC_OPTION_pipe,
11046 TCC_OPTION_E,
11049 static const TCCOption tcc_options[] = {
11050 { "h", TCC_OPTION_HELP, 0 },
11051 { "?", TCC_OPTION_HELP, 0 },
11052 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
11053 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
11054 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
11055 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
11056 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
11057 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11058 { "bench", TCC_OPTION_bench, 0 },
11059 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
11060 #ifdef CONFIG_TCC_BCHECK
11061 { "b", TCC_OPTION_b, 0 },
11062 #endif
11063 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11064 { "c", TCC_OPTION_c, 0 },
11065 { "static", TCC_OPTION_static, 0 },
11066 { "shared", TCC_OPTION_shared, 0 },
11067 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
11068 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
11069 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11070 { "rdynamic", TCC_OPTION_rdynamic, 0 },
11071 { "r", TCC_OPTION_r, 0 },
11072 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11073 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11074 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11075 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
11076 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11077 { "nostdinc", TCC_OPTION_nostdinc, 0 },
11078 { "nostdlib", TCC_OPTION_nostdlib, 0 },
11079 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
11080 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11081 { "w", TCC_OPTION_w, 0 },
11082 { "pipe", TCC_OPTION_pipe, 0},
11083 { "E", TCC_OPTION_E, 0},
11084 { NULL },
11087 /* convert 'str' into an array of space separated strings */
11088 static int expand_args(char ***pargv, const char *str)
11090 const char *s1;
11091 char **argv, *arg;
11092 int argc, len;
11094 argc = 0;
11095 argv = NULL;
11096 for(;;) {
11097 while (is_space(*str))
11098 str++;
11099 if (*str == '\0')
11100 break;
11101 s1 = str;
11102 while (*str != '\0' && !is_space(*str))
11103 str++;
11104 len = str - s1;
11105 arg = tcc_malloc(len + 1);
11106 memcpy(arg, s1, len);
11107 arg[len] = '\0';
11108 dynarray_add((void ***)&argv, &argc, arg);
11110 *pargv = argv;
11111 return argc;
11114 static char **files;
11115 static int nb_files, nb_libraries;
11116 static int multiple_files;
11117 static int print_search_dirs;
11118 static int output_type;
11119 static int reloc_output;
11120 static const char *outfile;
11122 int parse_args(TCCState *s, int argc, char **argv)
11124 int optind;
11125 const TCCOption *popt;
11126 const char *optarg, *p1, *r1;
11127 char *r;
11129 optind = 0;
11130 while (optind < argc) {
11132 r = argv[optind++];
11133 if (r[0] != '-' || r[1] == '\0') {
11134 /* add a new file */
11135 dynarray_add((void ***)&files, &nb_files, r);
11136 if (!multiple_files) {
11137 optind--;
11138 /* argv[0] will be this file */
11139 break;
11141 } else {
11142 /* find option in table (match only the first chars */
11143 popt = tcc_options;
11144 for(;;) {
11145 p1 = popt->name;
11146 if (p1 == NULL)
11147 error("invalid option -- '%s'", r);
11148 r1 = r + 1;
11149 for(;;) {
11150 if (*p1 == '\0')
11151 goto option_found;
11152 if (*r1 != *p1)
11153 break;
11154 p1++;
11155 r1++;
11157 popt++;
11159 option_found:
11160 if (popt->flags & TCC_OPTION_HAS_ARG) {
11161 if (*r1 != '\0' || (popt->flags & TCC_OPTION_NOSEP)) {
11162 optarg = r1;
11163 } else {
11164 if (optind >= argc)
11165 error("argument to '%s' is missing", r);
11166 optarg = argv[optind++];
11168 } else {
11169 if (*r1 != '\0')
11170 return 0;
11171 optarg = NULL;
11174 switch(popt->index) {
11175 case TCC_OPTION_HELP:
11176 return 0;
11178 case TCC_OPTION_I:
11179 if (tcc_add_include_path(s, optarg) < 0)
11180 error("too many include paths");
11181 break;
11182 case TCC_OPTION_D:
11184 char *sym, *value;
11185 sym = (char *)optarg;
11186 value = strchr(sym, '=');
11187 if (value) {
11188 *value = '\0';
11189 value++;
11191 tcc_define_symbol(s, sym, value);
11193 break;
11194 case TCC_OPTION_U:
11195 tcc_undefine_symbol(s, optarg);
11196 break;
11197 case TCC_OPTION_L:
11198 tcc_add_library_path(s, optarg);
11199 break;
11200 case TCC_OPTION_B:
11201 /* set tcc utilities path (mainly for tcc development) */
11202 tcc_lib_path = optarg;
11203 break;
11204 case TCC_OPTION_l:
11205 dynarray_add((void ***)&files, &nb_files, r);
11206 nb_libraries++;
11207 break;
11208 case TCC_OPTION_bench:
11209 do_bench = 1;
11210 break;
11211 case TCC_OPTION_bt:
11212 num_callers = atoi(optarg);
11213 break;
11214 #ifdef CONFIG_TCC_BCHECK
11215 case TCC_OPTION_b:
11216 do_bounds_check = 1;
11217 do_debug = 1;
11218 break;
11219 #endif
11220 case TCC_OPTION_g:
11221 do_debug = 1;
11222 break;
11223 case TCC_OPTION_c:
11224 multiple_files = 1;
11225 output_type = TCC_OUTPUT_OBJ;
11226 break;
11227 case TCC_OPTION_static:
11228 s->static_link = 1;
11229 break;
11230 case TCC_OPTION_shared:
11231 output_type = TCC_OUTPUT_DLL;
11232 break;
11233 case TCC_OPTION_soname:
11234 s->soname = optarg;
11235 break;
11236 case TCC_OPTION_o:
11237 multiple_files = 1;
11238 outfile = optarg;
11239 break;
11240 case TCC_OPTION_r:
11241 /* generate a .o merging several output files */
11242 reloc_output = 1;
11243 output_type = TCC_OUTPUT_OBJ;
11244 break;
11245 case TCC_OPTION_nostdinc:
11246 s->nostdinc = 1;
11247 break;
11248 case TCC_OPTION_nostdlib:
11249 s->nostdlib = 1;
11250 break;
11251 case TCC_OPTION_print_search_dirs:
11252 print_search_dirs = 1;
11253 break;
11254 case TCC_OPTION_run:
11256 int argc1;
11257 char **argv1;
11258 argc1 = expand_args(&argv1, optarg);
11259 if (argc1 > 0) {
11260 parse_args(s, argc1, argv1);
11262 multiple_files = 0;
11263 output_type = TCC_OUTPUT_MEMORY;
11265 break;
11266 case TCC_OPTION_v:
11267 do {
11268 if (0 == verbose++)
11269 printf("tcc version %s\n", TCC_VERSION);
11270 } while (*optarg++ == 'v');
11271 break;
11272 case TCC_OPTION_f:
11273 if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
11274 goto unsupported_option;
11275 break;
11276 case TCC_OPTION_W:
11277 if (tcc_set_warning(s, optarg, 1) < 0 &&
11278 s->warn_unsupported)
11279 goto unsupported_option;
11280 break;
11281 case TCC_OPTION_w:
11282 s->warn_none = 1;
11283 break;
11284 case TCC_OPTION_rdynamic:
11285 s->rdynamic = 1;
11286 break;
11287 case TCC_OPTION_Wl:
11289 const char *p;
11290 if (strstart(optarg, "-Ttext,", &p)) {
11291 s->text_addr = strtoul(p, NULL, 16);
11292 s->has_text_addr = 1;
11293 } else if (strstart(optarg, "--oformat,", &p)) {
11294 if (strstart(p, "elf32-", NULL)) {
11295 s->output_format = TCC_OUTPUT_FORMAT_ELF;
11296 } else if (!strcmp(p, "binary")) {
11297 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
11298 } else
11299 #ifdef TCC_TARGET_COFF
11300 if (!strcmp(p, "coff")) {
11301 s->output_format = TCC_OUTPUT_FORMAT_COFF;
11302 } else
11303 #endif
11305 error("target %s not found", p);
11307 } else {
11308 error("unsupported linker option '%s'", optarg);
11311 break;
11312 case TCC_OPTION_E:
11313 output_type = TCC_OUTPUT_PREPROCESS;
11314 break;
11315 default:
11316 if (s->warn_unsupported) {
11317 unsupported_option:
11318 warning("unsupported option '%s'", r);
11320 break;
11324 return optind + 1;
11327 int main(int argc, char **argv)
11329 int i;
11330 TCCState *s;
11331 int nb_objfiles, ret, optind;
11332 char objfilename[1024];
11333 int64_t start_time = 0;
11335 #ifdef _WIN32
11336 tcc_lib_path = w32_tcc_lib_path();
11337 #endif
11339 s = tcc_new();
11340 output_type = TCC_OUTPUT_EXE;
11341 outfile = NULL;
11342 multiple_files = 1;
11343 files = NULL;
11344 nb_files = 0;
11345 nb_libraries = 0;
11346 reloc_output = 0;
11347 print_search_dirs = 0;
11348 ret = 0;
11350 optind = parse_args(s, argc - 1, argv + 1);
11351 if (print_search_dirs) {
11352 /* enough for Linux kernel */
11353 printf("install: %s/\n", tcc_lib_path);
11354 return 0;
11356 if (optind == 0 || nb_files == 0) {
11357 if (optind && verbose)
11358 return 0;
11359 help();
11360 return 1;
11363 nb_objfiles = nb_files - nb_libraries;
11365 /* if outfile provided without other options, we output an
11366 executable */
11367 if (outfile && output_type == TCC_OUTPUT_MEMORY)
11368 output_type = TCC_OUTPUT_EXE;
11370 /* check -c consistency : only single file handled. XXX: checks file type */
11371 if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
11372 /* accepts only a single input file */
11373 if (nb_objfiles != 1)
11374 error("cannot specify multiple files with -c");
11375 if (nb_libraries != 0)
11376 error("cannot specify libraries with -c");
11380 if (output_type == TCC_OUTPUT_PREPROCESS) {
11381 if (!outfile) {
11382 s->outfile = stdout;
11383 } else {
11384 s->outfile = fopen(outfile, "w");
11385 if (!s->outfile)
11386 error("could not open '%s", outfile);
11388 } else if (output_type != TCC_OUTPUT_MEMORY) {
11389 if (!outfile) {
11390 /* compute default outfile name */
11391 char *ext;
11392 const char *name =
11393 strcmp(files[0], "-") == 0 ? "a" : tcc_basename(files[0]);
11394 pstrcpy(objfilename, sizeof(objfilename), name);
11395 ext = tcc_fileextension(objfilename);
11396 #ifdef TCC_TARGET_PE
11397 if (output_type == TCC_OUTPUT_DLL)
11398 strcpy(ext, ".dll");
11399 else
11400 if (output_type == TCC_OUTPUT_EXE)
11401 strcpy(ext, ".exe");
11402 else
11403 #endif
11404 if (output_type == TCC_OUTPUT_OBJ && !reloc_output && *ext)
11405 strcpy(ext, ".o");
11406 else
11407 pstrcpy(objfilename, sizeof(objfilename), "a.out");
11408 outfile = objfilename;
11412 if (do_bench) {
11413 start_time = getclock_us();
11416 tcc_set_output_type(s, output_type);
11418 /* compile or add each files or library */
11419 for(i = 0; i < nb_files && ret == 0; i++) {
11420 const char *filename;
11422 filename = files[i];
11423 if (output_type == TCC_OUTPUT_PREPROCESS) {
11424 if (tcc_add_file_internal(s, filename,
11425 AFF_PRINT_ERROR | AFF_PREPROCESS) < 0)
11426 ret = 1;
11427 } else if (filename[0] == '-' && filename[1]) {
11428 if (tcc_add_library(s, filename + 2) < 0)
11429 error("cannot find %s", filename);
11430 } else {
11431 if (1 == verbose)
11432 printf("-> %s\n", filename);
11433 if (tcc_add_file(s, filename) < 0)
11434 ret = 1;
11438 /* free all files */
11439 tcc_free(files);
11441 if (ret)
11442 goto the_end;
11444 if (do_bench) {
11445 double total_time;
11446 total_time = (double)(getclock_us() - start_time) / 1000000.0;
11447 if (total_time < 0.001)
11448 total_time = 0.001;
11449 if (total_bytes < 1)
11450 total_bytes = 1;
11451 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11452 tok_ident - TOK_IDENT, total_lines, total_bytes,
11453 total_time, (int)(total_lines / total_time),
11454 total_bytes / total_time / 1000000.0);
11457 if (s->output_type == TCC_OUTPUT_PREPROCESS) {
11458 if (outfile)
11459 fclose(s->outfile);
11460 } else if (s->output_type == TCC_OUTPUT_MEMORY) {
11461 ret = tcc_run(s, argc - optind, argv + optind);
11462 } else
11463 ret = tcc_output_file(s, outfile) ? 1 : 0;
11464 the_end:
11465 /* XXX: cannot do it with bound checking because of the malloc hooks */
11466 if (!do_bounds_check)
11467 tcc_delete(s);
11469 #ifdef MEM_DEBUG
11470 if (do_bench) {
11471 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size, mem_max_size);
11473 #endif
11474 return ret;
11477 #endif