avoid warning uninitialized
[tinycc/k1w1.git] / tcc.c
blob7c680f26185c1f0b386a203fe5670b8d20be438e
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;
546 /* for tcc_relocate */
547 int runtime_added;
549 #ifdef TCC_TARGET_X86_64
550 /* write PLT and GOT here */
551 char *runtime_plt_and_got;
552 unsigned int runtime_plt_and_got_offset;
553 #endif
556 /* The current value can be: */
557 #define VT_VALMASK 0x00ff
558 #define VT_CONST 0x00f0 /* constant in vc
559 (must be first non register value) */
560 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
561 #define VT_LOCAL 0x00f2 /* offset on stack */
562 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
563 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
564 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
565 #define VT_LVAL 0x0100 /* var is an lvalue */
566 #define VT_SYM 0x0200 /* a symbol value is added */
567 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
568 char/short stored in integer registers) */
569 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
570 dereferencing value */
571 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
572 bounding function call point is in vc */
573 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
574 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
575 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
576 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
578 /* types */
579 #define VT_INT 0 /* integer type */
580 #define VT_BYTE 1 /* signed byte type */
581 #define VT_SHORT 2 /* short type */
582 #define VT_VOID 3 /* void type */
583 #define VT_PTR 4 /* pointer */
584 #define VT_ENUM 5 /* enum definition */
585 #define VT_FUNC 6 /* function type */
586 #define VT_STRUCT 7 /* struct/union definition */
587 #define VT_FLOAT 8 /* IEEE float */
588 #define VT_DOUBLE 9 /* IEEE double */
589 #define VT_LDOUBLE 10 /* IEEE long double */
590 #define VT_BOOL 11 /* ISOC99 boolean type */
591 #define VT_LLONG 12 /* 64 bit integer */
592 #define VT_LONG 13 /* long integer (NEVER USED as type, only
593 during parsing) */
594 #define VT_BTYPE 0x000f /* mask for basic type */
595 #define VT_UNSIGNED 0x0010 /* unsigned type */
596 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
597 #define VT_BITFIELD 0x0040 /* bitfield modifier */
598 #define VT_CONSTANT 0x0800 /* const modifier */
599 #define VT_VOLATILE 0x1000 /* volatile modifier */
600 #define VT_SIGNED 0x2000 /* signed type */
602 /* storage */
603 #define VT_EXTERN 0x00000080 /* extern definition */
604 #define VT_STATIC 0x00000100 /* static variable */
605 #define VT_TYPEDEF 0x00000200 /* typedef definition */
606 #define VT_INLINE 0x00000400 /* inline definition */
608 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
610 /* type mask (except storage) */
611 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
612 #define VT_TYPE (~(VT_STORAGE))
614 /* token values */
616 /* warning: the following compare tokens depend on i386 asm code */
617 #define TOK_ULT 0x92
618 #define TOK_UGE 0x93
619 #define TOK_EQ 0x94
620 #define TOK_NE 0x95
621 #define TOK_ULE 0x96
622 #define TOK_UGT 0x97
623 #define TOK_Nset 0x98
624 #define TOK_Nclear 0x99
625 #define TOK_LT 0x9c
626 #define TOK_GE 0x9d
627 #define TOK_LE 0x9e
628 #define TOK_GT 0x9f
630 #define TOK_LAND 0xa0
631 #define TOK_LOR 0xa1
633 #define TOK_DEC 0xa2
634 #define TOK_MID 0xa3 /* inc/dec, to void constant */
635 #define TOK_INC 0xa4
636 #define TOK_UDIV 0xb0 /* unsigned division */
637 #define TOK_UMOD 0xb1 /* unsigned modulo */
638 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
639 #define TOK_CINT 0xb3 /* number in tokc */
640 #define TOK_CCHAR 0xb4 /* char constant in tokc */
641 #define TOK_STR 0xb5 /* pointer to string in tokc */
642 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
643 #define TOK_LCHAR 0xb7
644 #define TOK_LSTR 0xb8
645 #define TOK_CFLOAT 0xb9 /* float constant */
646 #define TOK_LINENUM 0xba /* line number info */
647 #define TOK_CDOUBLE 0xc0 /* double constant */
648 #define TOK_CLDOUBLE 0xc1 /* long double constant */
649 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
650 #define TOK_ADDC1 0xc3 /* add with carry generation */
651 #define TOK_ADDC2 0xc4 /* add with carry use */
652 #define TOK_SUBC1 0xc5 /* add with carry generation */
653 #define TOK_SUBC2 0xc6 /* add with carry use */
654 #define TOK_CUINT 0xc8 /* unsigned int constant */
655 #define TOK_CLLONG 0xc9 /* long long constant */
656 #define TOK_CULLONG 0xca /* unsigned long long constant */
657 #define TOK_ARROW 0xcb
658 #define TOK_DOTS 0xcc /* three dots */
659 #define TOK_SHR 0xcd /* unsigned shift right */
660 #define TOK_PPNUM 0xce /* preprocessor number */
662 #define TOK_SHL 0x01 /* shift left */
663 #define TOK_SAR 0x02 /* signed shift right */
665 /* assignement operators : normal operator or 0x80 */
666 #define TOK_A_MOD 0xa5
667 #define TOK_A_AND 0xa6
668 #define TOK_A_MUL 0xaa
669 #define TOK_A_ADD 0xab
670 #define TOK_A_SUB 0xad
671 #define TOK_A_DIV 0xaf
672 #define TOK_A_XOR 0xde
673 #define TOK_A_OR 0xfc
674 #define TOK_A_SHL 0x81
675 #define TOK_A_SAR 0x82
677 #ifndef offsetof
678 #define offsetof(type, field) ((size_t) &((type *)0)->field)
679 #endif
681 #ifndef countof
682 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
683 #endif
685 /* WARNING: the content of this string encodes token numbers */
686 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";
688 #define TOK_EOF (-1) /* end of file */
689 #define TOK_LINEFEED 10 /* line feed */
691 /* all identificators and strings have token above that */
692 #define TOK_IDENT 256
694 /* only used for i386 asm opcodes definitions */
695 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
697 #define DEF_BWL(x) \
698 DEF(TOK_ASM_ ## x ## b, #x "b") \
699 DEF(TOK_ASM_ ## x ## w, #x "w") \
700 DEF(TOK_ASM_ ## x ## l, #x "l") \
701 DEF(TOK_ASM_ ## x, #x)
703 #define DEF_WL(x) \
704 DEF(TOK_ASM_ ## x ## w, #x "w") \
705 DEF(TOK_ASM_ ## x ## l, #x "l") \
706 DEF(TOK_ASM_ ## x, #x)
708 #define DEF_FP1(x) \
709 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
710 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
711 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
712 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
714 #define DEF_FP(x) \
715 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
716 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
717 DEF_FP1(x)
719 #define DEF_ASMTEST(x) \
720 DEF_ASM(x ## o) \
721 DEF_ASM(x ## no) \
722 DEF_ASM(x ## b) \
723 DEF_ASM(x ## c) \
724 DEF_ASM(x ## nae) \
725 DEF_ASM(x ## nb) \
726 DEF_ASM(x ## nc) \
727 DEF_ASM(x ## ae) \
728 DEF_ASM(x ## e) \
729 DEF_ASM(x ## z) \
730 DEF_ASM(x ## ne) \
731 DEF_ASM(x ## nz) \
732 DEF_ASM(x ## be) \
733 DEF_ASM(x ## na) \
734 DEF_ASM(x ## nbe) \
735 DEF_ASM(x ## a) \
736 DEF_ASM(x ## s) \
737 DEF_ASM(x ## ns) \
738 DEF_ASM(x ## p) \
739 DEF_ASM(x ## pe) \
740 DEF_ASM(x ## np) \
741 DEF_ASM(x ## po) \
742 DEF_ASM(x ## l) \
743 DEF_ASM(x ## nge) \
744 DEF_ASM(x ## nl) \
745 DEF_ASM(x ## ge) \
746 DEF_ASM(x ## le) \
747 DEF_ASM(x ## ng) \
748 DEF_ASM(x ## nle) \
749 DEF_ASM(x ## g)
751 #define TOK_ASM_int TOK_INT
753 enum tcc_token {
754 TOK_LAST = TOK_IDENT - 1,
755 #define DEF(id, str) id,
756 #include "tcctok.h"
757 #undef DEF
760 static const char tcc_keywords[] =
761 #define DEF(id, str) str "\0"
762 #include "tcctok.h"
763 #undef DEF
766 #define TOK_UIDENT TOK_DEFINE
768 #ifdef _WIN32
769 #define snprintf _snprintf
770 #define vsnprintf _vsnprintf
771 #ifndef __GNUC__
772 #define strtold (long double)strtod
773 #define strtof (float)strtod
774 #define strtoll (long long)strtol
775 #endif
776 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
777 || defined(__OpenBSD__)
778 /* currently incorrect */
779 long double strtold(const char *nptr, char **endptr)
781 return (long double)strtod(nptr, endptr);
783 float strtof(const char *nptr, char **endptr)
785 return (float)strtod(nptr, endptr);
787 #else
788 /* XXX: need to define this to use them in non ISOC99 context */
789 extern float strtof (const char *__nptr, char **__endptr);
790 extern long double strtold (const char *__nptr, char **__endptr);
791 #endif
793 static char *pstrcpy(char *buf, int buf_size, const char *s);
794 static char *pstrcat(char *buf, int buf_size, const char *s);
795 static char *tcc_basename(const char *name);
796 static char *tcc_fileextension (const char *p);
798 static void next(void);
799 static void next_nomacro(void);
800 static void parse_expr_type(CType *type);
801 static void expr_type(CType *type);
802 static void unary_type(CType *type);
803 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
804 int case_reg, int is_expr);
805 static int expr_const(void);
806 static void expr_eq(void);
807 static void gexpr(void);
808 static void gen_inline_functions(void);
809 static void decl(int l);
810 static void decl_initializer(CType *type, Section *sec, unsigned long c,
811 int first, int size_only);
812 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
813 int has_init, int v, int scope);
814 int gv(int rc);
815 void gv2(int rc1, int rc2);
816 void move_reg(int r, int s);
817 void save_regs(int n);
818 void save_reg(int r);
819 void vpop(void);
820 void vswap(void);
821 void vdup(void);
822 int get_reg(int rc);
823 int get_reg_ex(int rc,int rc2);
825 struct macro_level {
826 struct macro_level *prev;
827 int *p;
830 static void macro_subst(TokenString *tok_str, Sym **nested_list,
831 const int *macro_str, struct macro_level **can_read_stream);
832 void gen_op(int op);
833 void force_charshort_cast(int t);
834 static void gen_cast(CType *type);
835 void vstore(void);
836 static Sym *sym_find(int v);
837 static Sym *sym_push(int v, CType *type, int r, int c);
839 /* type handling */
840 static int type_size(CType *type, int *a);
841 static inline CType *pointed_type(CType *type);
842 static int pointed_size(CType *type);
843 static int lvalue_type(int t);
844 static int parse_btype(CType *type, AttributeDef *ad);
845 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
846 static int compare_types(CType *type1, CType *type2, int unqualified);
847 static int is_compatible_types(CType *type1, CType *type2);
848 static int is_compatible_parameter_types(CType *type1, CType *type2);
850 int ieee_finite(double d);
851 void error(const char *fmt, ...);
852 void vpushi(int v);
853 void vpushll(long long v);
854 void vrott(int n);
855 void vnrott(int n);
856 void lexpand_nr(void);
857 static void vpush_global_sym(CType *type, int v);
858 void vset(CType *type, int r, int v);
859 void type_to_str(char *buf, int buf_size,
860 CType *type, const char *varstr);
861 char *get_tok_str(int v, CValue *cv);
862 static Sym *get_sym_ref(CType *type, Section *sec,
863 unsigned long offset, unsigned long size);
864 static Sym *external_global_sym(int v, CType *type, int r);
866 /* section generation */
867 static void section_realloc(Section *sec, unsigned long new_size);
868 static void *section_ptr_add(Section *sec, unsigned long size);
869 static void put_extern_sym(Sym *sym, Section *section,
870 unsigned long value, unsigned long size);
871 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
872 static int put_elf_str(Section *s, const char *sym);
873 static int put_elf_sym(Section *s,
874 unsigned long value, unsigned long size,
875 int info, int other, int shndx, const char *name);
876 static int add_elf_sym(Section *s, unsigned long value, unsigned long size,
877 int info, int other, int sh_num, const char *name);
878 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
879 int type, int symbol);
880 static void put_stabs(const char *str, int type, int other, int desc,
881 unsigned long value);
882 static void put_stabs_r(const char *str, int type, int other, int desc,
883 unsigned long value, Section *sec, int sym_index);
884 static void put_stabn(int type, int other, int desc, int value);
885 static void put_stabd(int type, int other, int desc);
886 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
888 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
889 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
890 #define AFF_PREPROCESS 0x0004 /* preprocess file */
891 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
893 /* tcccoff.c */
894 int tcc_output_coff(TCCState *s1, FILE *f);
896 /* tccpe.c */
897 void *resolve_sym(TCCState *s1, const char *sym, int type);
898 int pe_load_def_file(struct TCCState *s1, int fd);
899 int pe_test_res_file(void *v, int size);
900 int pe_load_res_file(struct TCCState *s1, int fd);
901 void pe_add_runtime(struct TCCState *s1);
902 void pe_guess_outfile(char *objfilename, int output_type);
903 int pe_output_file(struct TCCState *s1, const char *filename);
905 /* tccasm.c */
907 #ifdef CONFIG_TCC_ASM
909 typedef struct ExprValue {
910 uint32_t v;
911 Sym *sym;
912 } ExprValue;
914 #define MAX_ASM_OPERANDS 30
916 typedef struct ASMOperand {
917 int id; /* GCC 3 optionnal identifier (0 if number only supported */
918 char *constraint;
919 char asm_str[16]; /* computed asm string for operand */
920 SValue *vt; /* C value of the expression */
921 int ref_index; /* if >= 0, gives reference to a output constraint */
922 int input_index; /* if >= 0, gives reference to an input constraint */
923 int priority; /* priority, used to assign registers */
924 int reg; /* if >= 0, register number used for this operand */
925 int is_llong; /* true if double register value */
926 int is_memory; /* true if memory operand */
927 int is_rw; /* for '+' modifier */
928 } ASMOperand;
930 static void asm_expr(TCCState *s1, ExprValue *pe);
931 static int asm_int_expr(TCCState *s1);
932 static int find_constraint(ASMOperand *operands, int nb_operands,
933 const char *name, const char **pp);
935 static int tcc_assemble(TCCState *s1, int do_preprocess);
937 #endif
939 static void asm_instr(void);
940 static void asm_global_instr(void);
942 /* true if float/double/long double type */
943 static inline int is_float(int t)
945 int bt;
946 bt = t & VT_BTYPE;
947 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
950 #ifdef TCC_TARGET_I386
951 #include "i386-gen.c"
952 #endif
954 #ifdef TCC_TARGET_ARM
955 #include "arm-gen.c"
956 #endif
958 #ifdef TCC_TARGET_C67
959 #include "c67-gen.c"
960 #endif
962 #ifdef TCC_TARGET_X86_64
963 #include "x86_64-gen.c"
964 #endif
966 #ifdef CONFIG_TCC_STATIC
968 #define RTLD_LAZY 0x001
969 #define RTLD_NOW 0x002
970 #define RTLD_GLOBAL 0x100
971 #define RTLD_DEFAULT NULL
973 /* dummy function for profiling */
974 void *dlopen(const char *filename, int flag)
976 return NULL;
979 const char *dlerror(void)
981 return "error";
984 typedef struct TCCSyms {
985 char *str;
986 void *ptr;
987 } TCCSyms;
989 #define TCCSYM(a) { #a, &a, },
991 /* add the symbol you want here if no dynamic linking is done */
992 static TCCSyms tcc_syms[] = {
993 #if !defined(CONFIG_TCCBOOT)
994 TCCSYM(printf)
995 TCCSYM(fprintf)
996 TCCSYM(fopen)
997 TCCSYM(fclose)
998 #endif
999 { NULL, NULL },
1002 void *resolve_sym(TCCState *s1, const char *symbol, int type)
1004 TCCSyms *p;
1005 p = tcc_syms;
1006 while (p->str != NULL) {
1007 if (!strcmp(p->str, symbol))
1008 return p->ptr;
1009 p++;
1011 return NULL;
1014 #elif !defined(_WIN32)
1016 #include <dlfcn.h>
1018 void *resolve_sym(TCCState *s1, const char *sym, int type)
1020 return dlsym(RTLD_DEFAULT, sym);
1023 #endif
1025 /********************************************************/
1027 /* we use our own 'finite' function to avoid potential problems with
1028 non standard math libs */
1029 /* XXX: endianness dependent */
1030 int ieee_finite(double d)
1032 int *p = (int *)&d;
1033 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
1036 /* copy a string and truncate it. */
1037 static char *pstrcpy(char *buf, int buf_size, const char *s)
1039 char *q, *q_end;
1040 int c;
1042 if (buf_size > 0) {
1043 q = buf;
1044 q_end = buf + buf_size - 1;
1045 while (q < q_end) {
1046 c = *s++;
1047 if (c == '\0')
1048 break;
1049 *q++ = c;
1051 *q = '\0';
1053 return buf;
1056 /* strcat and truncate. */
1057 static char *pstrcat(char *buf, int buf_size, const char *s)
1059 int len;
1060 len = strlen(buf);
1061 if (len < buf_size)
1062 pstrcpy(buf + len, buf_size - len, s);
1063 return buf;
1066 #ifndef LIBTCC
1067 static int strstart(const char *str, const char *val, const char **ptr)
1069 const char *p, *q;
1070 p = str;
1071 q = val;
1072 while (*q != '\0') {
1073 if (*p != *q)
1074 return 0;
1075 p++;
1076 q++;
1078 if (ptr)
1079 *ptr = p;
1080 return 1;
1082 #endif
1084 #ifdef _WIN32
1085 #define IS_PATHSEP(c) (c == '/' || c == '\\')
1086 #define IS_ABSPATH(p) (IS_PATHSEP(p[0]) || (p[0] && p[1] == ':' && IS_PATHSEP(p[2])))
1087 #define PATHCMP stricmp
1088 #else
1089 #define IS_PATHSEP(c) (c == '/')
1090 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1091 #define PATHCMP strcmp
1092 #endif
1094 /* extract the basename of a file */
1095 static char *tcc_basename(const char *name)
1097 char *p = strchr(name, 0);
1098 while (p > name && !IS_PATHSEP(p[-1]))
1099 --p;
1100 return p;
1103 static char *tcc_fileextension (const char *name)
1105 char *b = tcc_basename(name);
1106 char *e = strrchr(b, '.');
1107 return e ? e : strchr(b, 0);
1110 #ifdef _WIN32
1111 char *normalize_slashes(char *path)
1113 char *p;
1114 for (p = path; *p; ++p)
1115 if (*p == '\\')
1116 *p = '/';
1117 return path;
1120 char *w32_tcc_lib_path(void)
1122 /* on win32, we suppose the lib and includes are at the location
1123 of 'tcc.exe' */
1124 char path[1024], *p;
1125 GetModuleFileNameA(NULL, path, sizeof path);
1126 p = tcc_basename(normalize_slashes(strlwr(path)));
1127 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
1128 p -= 5;
1129 else if (p > path)
1130 p--;
1131 *p = 0;
1132 return strdup(path);
1134 #endif
1136 void set_pages_executable(void *ptr, unsigned long length)
1138 #ifdef _WIN32
1139 unsigned long old_protect;
1140 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
1141 #else
1142 unsigned long start, end;
1143 start = (unsigned long)ptr & ~(PAGESIZE - 1);
1144 end = (unsigned long)ptr + length;
1145 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
1146 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
1147 #endif
1150 /* memory management */
1151 #ifdef MEM_DEBUG
1152 int mem_cur_size;
1153 int mem_max_size;
1154 unsigned malloc_usable_size(void*);
1155 #endif
1157 static inline void tcc_free(void *ptr)
1159 #ifdef MEM_DEBUG
1160 mem_cur_size -= malloc_usable_size(ptr);
1161 #endif
1162 free(ptr);
1165 static void *tcc_malloc(unsigned long size)
1167 void *ptr;
1168 ptr = malloc(size);
1169 if (!ptr && size)
1170 error("memory full");
1171 #ifdef MEM_DEBUG
1172 mem_cur_size += malloc_usable_size(ptr);
1173 if (mem_cur_size > mem_max_size)
1174 mem_max_size = mem_cur_size;
1175 #endif
1176 return ptr;
1179 static void *tcc_mallocz(unsigned long size)
1181 void *ptr;
1182 ptr = tcc_malloc(size);
1183 memset(ptr, 0, size);
1184 return ptr;
1187 static inline void *tcc_realloc(void *ptr, unsigned long size)
1189 void *ptr1;
1190 #ifdef MEM_DEBUG
1191 mem_cur_size -= malloc_usable_size(ptr);
1192 #endif
1193 ptr1 = realloc(ptr, size);
1194 #ifdef MEM_DEBUG
1195 /* NOTE: count not correct if alloc error, but not critical */
1196 mem_cur_size += malloc_usable_size(ptr1);
1197 if (mem_cur_size > mem_max_size)
1198 mem_max_size = mem_cur_size;
1199 #endif
1200 return ptr1;
1203 static char *tcc_strdup(const char *str)
1205 char *ptr;
1206 ptr = tcc_malloc(strlen(str) + 1);
1207 strcpy(ptr, str);
1208 return ptr;
1211 #define free(p) use_tcc_free(p)
1212 #define malloc(s) use_tcc_malloc(s)
1213 #define realloc(p, s) use_tcc_realloc(p, s)
1215 static void dynarray_add(void ***ptab, int *nb_ptr, void *data)
1217 int nb, nb_alloc;
1218 void **pp;
1220 nb = *nb_ptr;
1221 pp = *ptab;
1222 /* every power of two we double array size */
1223 if ((nb & (nb - 1)) == 0) {
1224 if (!nb)
1225 nb_alloc = 1;
1226 else
1227 nb_alloc = nb * 2;
1228 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
1229 if (!pp)
1230 error("memory full");
1231 *ptab = pp;
1233 pp[nb++] = data;
1234 *nb_ptr = nb;
1237 static void dynarray_reset(void *pp, int *n)
1239 void **p;
1240 for (p = *(void***)pp; *n; ++p, --*n)
1241 if (*p)
1242 tcc_free(*p);
1243 tcc_free(*(void**)pp);
1244 *(void**)pp = NULL;
1247 /* symbol allocator */
1248 static Sym *__sym_malloc(void)
1250 Sym *sym_pool, *sym, *last_sym;
1251 int i;
1253 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
1254 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
1256 last_sym = sym_free_first;
1257 sym = sym_pool;
1258 for(i = 0; i < SYM_POOL_NB; i++) {
1259 sym->next = last_sym;
1260 last_sym = sym;
1261 sym++;
1263 sym_free_first = last_sym;
1264 return last_sym;
1267 static inline Sym *sym_malloc(void)
1269 Sym *sym;
1270 sym = sym_free_first;
1271 if (!sym)
1272 sym = __sym_malloc();
1273 sym_free_first = sym->next;
1274 return sym;
1277 static inline void sym_free(Sym *sym)
1279 sym->next = sym_free_first;
1280 sym_free_first = sym;
1283 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
1285 Section *sec;
1287 sec = tcc_mallocz(sizeof(Section) + strlen(name));
1288 strcpy(sec->name, name);
1289 sec->sh_type = sh_type;
1290 sec->sh_flags = sh_flags;
1291 switch(sh_type) {
1292 case SHT_HASH:
1293 case SHT_REL:
1294 case SHT_RELA:
1295 case SHT_DYNSYM:
1296 case SHT_SYMTAB:
1297 case SHT_DYNAMIC:
1298 sec->sh_addralign = 4;
1299 break;
1300 case SHT_STRTAB:
1301 sec->sh_addralign = 1;
1302 break;
1303 default:
1304 sec->sh_addralign = 32; /* default conservative alignment */
1305 break;
1308 if (sh_flags & SHF_PRIVATE) {
1309 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
1310 } else {
1311 sec->sh_num = s1->nb_sections;
1312 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
1315 return sec;
1318 static void free_section(Section *s)
1320 tcc_free(s->data);
1323 /* realloc section and set its content to zero */
1324 static void section_realloc(Section *sec, unsigned long new_size)
1326 unsigned long size;
1327 unsigned char *data;
1329 size = sec->data_allocated;
1330 if (size == 0)
1331 size = 1;
1332 while (size < new_size)
1333 size = size * 2;
1334 data = tcc_realloc(sec->data, size);
1335 if (!data)
1336 error("memory full");
1337 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
1338 sec->data = data;
1339 sec->data_allocated = size;
1342 /* reserve at least 'size' bytes in section 'sec' from
1343 sec->data_offset. */
1344 static void *section_ptr_add(Section *sec, unsigned long size)
1346 unsigned long offset, offset1;
1348 offset = sec->data_offset;
1349 offset1 = offset + size;
1350 if (offset1 > sec->data_allocated)
1351 section_realloc(sec, offset1);
1352 sec->data_offset = offset1;
1353 return sec->data + offset;
1356 /* return a reference to a section, and create it if it does not
1357 exists */
1358 Section *find_section(TCCState *s1, const char *name)
1360 Section *sec;
1361 int i;
1362 for(i = 1; i < s1->nb_sections; i++) {
1363 sec = s1->sections[i];
1364 if (!strcmp(name, sec->name))
1365 return sec;
1367 /* sections are created as PROGBITS */
1368 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
1371 #define SECTION_ABS ((void *)1)
1373 /* update sym->c so that it points to an external symbol in section
1374 'section' with value 'value' */
1375 static void put_extern_sym2(Sym *sym, Section *section,
1376 unsigned long value, unsigned long size,
1377 int can_add_underscore)
1379 int sym_type, sym_bind, sh_num, info, other, attr;
1380 ElfW(Sym) *esym;
1381 const char *name;
1382 char buf1[256];
1384 if (section == NULL)
1385 sh_num = SHN_UNDEF;
1386 else if (section == SECTION_ABS)
1387 sh_num = SHN_ABS;
1388 else
1389 sh_num = section->sh_num;
1391 other = attr = 0;
1393 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
1394 sym_type = STT_FUNC;
1395 #ifdef TCC_TARGET_PE
1396 if (sym->type.ref)
1397 attr = sym->type.ref->r;
1398 if (FUNC_EXPORT(attr))
1399 other |= 1;
1400 if (FUNC_CALL(attr) == FUNC_STDCALL)
1401 other |= 2;
1402 #endif
1403 } else {
1404 sym_type = STT_OBJECT;
1407 if (sym->type.t & VT_STATIC)
1408 sym_bind = STB_LOCAL;
1409 else
1410 sym_bind = STB_GLOBAL;
1412 if (!sym->c) {
1413 name = get_tok_str(sym->v, NULL);
1414 #ifdef CONFIG_TCC_BCHECK
1415 if (do_bounds_check) {
1416 char buf[32];
1418 /* XXX: avoid doing that for statics ? */
1419 /* if bound checking is activated, we change some function
1420 names by adding the "__bound" prefix */
1421 switch(sym->v) {
1422 #if 0
1423 /* XXX: we rely only on malloc hooks */
1424 case TOK_malloc:
1425 case TOK_free:
1426 case TOK_realloc:
1427 case TOK_memalign:
1428 case TOK_calloc:
1429 #endif
1430 case TOK_memcpy:
1431 case TOK_memmove:
1432 case TOK_memset:
1433 case TOK_strlen:
1434 case TOK_strcpy:
1435 case TOK__alloca:
1436 strcpy(buf, "__bound_");
1437 strcat(buf, name);
1438 name = buf;
1439 break;
1442 #endif
1444 #ifdef TCC_TARGET_PE
1445 if ((other & 2) && can_add_underscore) {
1446 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
1447 name = buf1;
1448 } else
1449 #endif
1450 if (tcc_state->leading_underscore && can_add_underscore) {
1451 buf1[0] = '_';
1452 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
1453 name = buf1;
1455 info = ELFW(ST_INFO)(sym_bind, sym_type);
1456 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
1457 } else {
1458 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1459 esym->st_value = value;
1460 esym->st_size = size;
1461 esym->st_shndx = sh_num;
1462 esym->st_other |= other;
1466 static void put_extern_sym(Sym *sym, Section *section,
1467 unsigned long value, unsigned long size)
1469 put_extern_sym2(sym, section, value, size, 1);
1472 /* add a new relocation entry to symbol 'sym' in section 's' */
1473 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
1475 if (!sym->c)
1476 put_extern_sym(sym, NULL, 0, 0);
1477 /* now we can add ELF relocation info */
1478 put_elf_reloc(symtab_section, s, offset, type, sym->c);
1481 static inline int isid(int c)
1483 return (c >= 'a' && c <= 'z') ||
1484 (c >= 'A' && c <= 'Z') ||
1485 c == '_';
1488 static inline int isnum(int c)
1490 return c >= '0' && c <= '9';
1493 static inline int isoct(int c)
1495 return c >= '0' && c <= '7';
1498 static inline int toup(int c)
1500 if (c >= 'a' && c <= 'z')
1501 return c - 'a' + 'A';
1502 else
1503 return c;
1506 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
1508 int len;
1509 len = strlen(buf);
1510 vsnprintf(buf + len, buf_size - len, fmt, ap);
1513 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
1515 va_list ap;
1516 va_start(ap, fmt);
1517 strcat_vprintf(buf, buf_size, fmt, ap);
1518 va_end(ap);
1521 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
1523 char buf[2048];
1524 BufferedFile **f;
1526 buf[0] = '\0';
1527 if (file) {
1528 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
1529 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
1530 (*f)->filename, (*f)->line_num);
1531 if (file->line_num > 0) {
1532 strcat_printf(buf, sizeof(buf),
1533 "%s:%d: ", file->filename, file->line_num);
1534 } else {
1535 strcat_printf(buf, sizeof(buf),
1536 "%s: ", file->filename);
1538 } else {
1539 strcat_printf(buf, sizeof(buf),
1540 "tcc: ");
1542 if (is_warning)
1543 strcat_printf(buf, sizeof(buf), "warning: ");
1544 strcat_vprintf(buf, sizeof(buf), fmt, ap);
1546 if (!s1->error_func) {
1547 /* default case: stderr */
1548 fprintf(stderr, "%s\n", buf);
1549 } else {
1550 s1->error_func(s1->error_opaque, buf);
1552 if (!is_warning || s1->warn_error)
1553 s1->nb_errors++;
1556 #ifdef LIBTCC
1557 void tcc_set_error_func(TCCState *s, void *error_opaque,
1558 void (*error_func)(void *opaque, const char *msg))
1560 s->error_opaque = error_opaque;
1561 s->error_func = error_func;
1563 #endif
1565 /* error without aborting current compilation */
1566 void error_noabort(const char *fmt, ...)
1568 TCCState *s1 = tcc_state;
1569 va_list ap;
1571 va_start(ap, fmt);
1572 error1(s1, 0, fmt, ap);
1573 va_end(ap);
1576 void error(const char *fmt, ...)
1578 TCCState *s1 = tcc_state;
1579 va_list ap;
1581 va_start(ap, fmt);
1582 error1(s1, 0, fmt, ap);
1583 va_end(ap);
1584 /* better than nothing: in some cases, we accept to handle errors */
1585 if (s1->error_set_jmp_enabled) {
1586 longjmp(s1->error_jmp_buf, 1);
1587 } else {
1588 /* XXX: eliminate this someday */
1589 exit(1);
1593 void expect(const char *msg)
1595 error("%s expected", msg);
1598 void warning(const char *fmt, ...)
1600 TCCState *s1 = tcc_state;
1601 va_list ap;
1603 if (s1->warn_none)
1604 return;
1606 va_start(ap, fmt);
1607 error1(s1, 1, fmt, ap);
1608 va_end(ap);
1611 void skip(int c)
1613 if (tok != c)
1614 error("'%c' expected", c);
1615 next();
1618 static void test_lvalue(void)
1620 if (!(vtop->r & VT_LVAL))
1621 expect("lvalue");
1624 /* allocate a new token */
1625 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
1627 TokenSym *ts, **ptable;
1628 int i;
1630 if (tok_ident >= SYM_FIRST_ANOM)
1631 error("memory full");
1633 /* expand token table if needed */
1634 i = tok_ident - TOK_IDENT;
1635 if ((i % TOK_ALLOC_INCR) == 0) {
1636 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
1637 if (!ptable)
1638 error("memory full");
1639 table_ident = ptable;
1642 ts = tcc_malloc(sizeof(TokenSym) + len);
1643 table_ident[i] = ts;
1644 ts->tok = tok_ident++;
1645 ts->sym_define = NULL;
1646 ts->sym_label = NULL;
1647 ts->sym_struct = NULL;
1648 ts->sym_identifier = NULL;
1649 ts->len = len;
1650 ts->hash_next = NULL;
1651 memcpy(ts->str, str, len);
1652 ts->str[len] = '\0';
1653 *pts = ts;
1654 return ts;
1657 #define TOK_HASH_INIT 1
1658 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1660 /* find a token and add it if not found */
1661 static TokenSym *tok_alloc(const char *str, int len)
1663 TokenSym *ts, **pts;
1664 int i;
1665 unsigned int h;
1667 h = TOK_HASH_INIT;
1668 for(i=0;i<len;i++)
1669 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
1670 h &= (TOK_HASH_SIZE - 1);
1672 pts = &hash_ident[h];
1673 for(;;) {
1674 ts = *pts;
1675 if (!ts)
1676 break;
1677 if (ts->len == len && !memcmp(ts->str, str, len))
1678 return ts;
1679 pts = &(ts->hash_next);
1681 return tok_alloc_new(pts, str, len);
1684 /* CString handling */
1686 static void cstr_realloc(CString *cstr, int new_size)
1688 int size;
1689 void *data;
1691 size = cstr->size_allocated;
1692 if (size == 0)
1693 size = 8; /* no need to allocate a too small first string */
1694 while (size < new_size)
1695 size = size * 2;
1696 data = tcc_realloc(cstr->data_allocated, size);
1697 if (!data)
1698 error("memory full");
1699 cstr->data_allocated = data;
1700 cstr->size_allocated = size;
1701 cstr->data = data;
1704 /* add a byte */
1705 static inline void cstr_ccat(CString *cstr, int ch)
1707 int size;
1708 size = cstr->size + 1;
1709 if (size > cstr->size_allocated)
1710 cstr_realloc(cstr, size);
1711 ((unsigned char *)cstr->data)[size - 1] = ch;
1712 cstr->size = size;
1715 static void cstr_cat(CString *cstr, const char *str)
1717 int c;
1718 for(;;) {
1719 c = *str;
1720 if (c == '\0')
1721 break;
1722 cstr_ccat(cstr, c);
1723 str++;
1727 /* add a wide char */
1728 static void cstr_wccat(CString *cstr, int ch)
1730 int size;
1731 size = cstr->size + sizeof(nwchar_t);
1732 if (size > cstr->size_allocated)
1733 cstr_realloc(cstr, size);
1734 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1735 cstr->size = size;
1738 static void cstr_new(CString *cstr)
1740 memset(cstr, 0, sizeof(CString));
1743 /* free string and reset it to NULL */
1744 static void cstr_free(CString *cstr)
1746 tcc_free(cstr->data_allocated);
1747 cstr_new(cstr);
1750 #define cstr_reset(cstr) cstr_free(cstr)
1752 /* XXX: unicode ? */
1753 static void add_char(CString *cstr, int c)
1755 if (c == '\'' || c == '\"' || c == '\\') {
1756 /* XXX: could be more precise if char or string */
1757 cstr_ccat(cstr, '\\');
1759 if (c >= 32 && c <= 126) {
1760 cstr_ccat(cstr, c);
1761 } else {
1762 cstr_ccat(cstr, '\\');
1763 if (c == '\n') {
1764 cstr_ccat(cstr, 'n');
1765 } else {
1766 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1767 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1768 cstr_ccat(cstr, '0' + (c & 7));
1773 /* XXX: buffer overflow */
1774 /* XXX: float tokens */
1775 char *get_tok_str(int v, CValue *cv)
1777 static char buf[STRING_MAX_SIZE + 1];
1778 static CString cstr_buf;
1779 CString *cstr;
1780 unsigned char *q;
1781 char *p;
1782 int i, len;
1784 /* NOTE: to go faster, we give a fixed buffer for small strings */
1785 cstr_reset(&cstr_buf);
1786 cstr_buf.data = buf;
1787 cstr_buf.size_allocated = sizeof(buf);
1788 p = buf;
1790 switch(v) {
1791 case TOK_CINT:
1792 case TOK_CUINT:
1793 /* XXX: not quite exact, but only useful for testing */
1794 sprintf(p, "%u", cv->ui);
1795 break;
1796 case TOK_CLLONG:
1797 case TOK_CULLONG:
1798 /* XXX: not quite exact, but only useful for testing */
1799 sprintf(p, "%Lu", cv->ull);
1800 break;
1801 case TOK_LCHAR:
1802 cstr_ccat(&cstr_buf, 'L');
1803 case TOK_CCHAR:
1804 cstr_ccat(&cstr_buf, '\'');
1805 add_char(&cstr_buf, cv->i);
1806 cstr_ccat(&cstr_buf, '\'');
1807 cstr_ccat(&cstr_buf, '\0');
1808 break;
1809 case TOK_PPNUM:
1810 cstr = cv->cstr;
1811 len = cstr->size - 1;
1812 for(i=0;i<len;i++)
1813 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1814 cstr_ccat(&cstr_buf, '\0');
1815 break;
1816 case TOK_LSTR:
1817 cstr_ccat(&cstr_buf, 'L');
1818 case TOK_STR:
1819 cstr = cv->cstr;
1820 cstr_ccat(&cstr_buf, '\"');
1821 if (v == TOK_STR) {
1822 len = cstr->size - 1;
1823 for(i=0;i<len;i++)
1824 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1825 } else {
1826 len = (cstr->size / sizeof(nwchar_t)) - 1;
1827 for(i=0;i<len;i++)
1828 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
1830 cstr_ccat(&cstr_buf, '\"');
1831 cstr_ccat(&cstr_buf, '\0');
1832 break;
1833 case TOK_LT:
1834 v = '<';
1835 goto addv;
1836 case TOK_GT:
1837 v = '>';
1838 goto addv;
1839 case TOK_DOTS:
1840 return strcpy(p, "...");
1841 case TOK_A_SHL:
1842 return strcpy(p, "<<=");
1843 case TOK_A_SAR:
1844 return strcpy(p, ">>=");
1845 default:
1846 if (v < TOK_IDENT) {
1847 /* search in two bytes table */
1848 q = tok_two_chars;
1849 while (*q) {
1850 if (q[2] == v) {
1851 *p++ = q[0];
1852 *p++ = q[1];
1853 *p = '\0';
1854 return buf;
1856 q += 3;
1858 addv:
1859 *p++ = v;
1860 *p = '\0';
1861 } else if (v < tok_ident) {
1862 return table_ident[v - TOK_IDENT]->str;
1863 } else if (v >= SYM_FIRST_ANOM) {
1864 /* special name for anonymous symbol */
1865 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
1866 } else {
1867 /* should never happen */
1868 return NULL;
1870 break;
1872 return cstr_buf.data;
1875 /* push, without hashing */
1876 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1878 Sym *s;
1879 s = sym_malloc();
1880 s->v = v;
1881 s->type.t = t;
1882 s->c = c;
1883 s->next = NULL;
1884 /* add in stack */
1885 s->prev = *ps;
1886 *ps = s;
1887 return s;
1890 /* find a symbol and return its associated structure. 's' is the top
1891 of the symbol stack */
1892 static Sym *sym_find2(Sym *s, int v)
1894 while (s) {
1895 if (s->v == v)
1896 return s;
1897 s = s->prev;
1899 return NULL;
1902 /* structure lookup */
1903 static inline Sym *struct_find(int v)
1905 v -= TOK_IDENT;
1906 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1907 return NULL;
1908 return table_ident[v]->sym_struct;
1911 /* find an identifier */
1912 static inline Sym *sym_find(int v)
1914 v -= TOK_IDENT;
1915 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1916 return NULL;
1917 return table_ident[v]->sym_identifier;
1920 /* push a given symbol on the symbol stack */
1921 static Sym *sym_push(int v, CType *type, int r, int c)
1923 Sym *s, **ps;
1924 TokenSym *ts;
1926 if (local_stack)
1927 ps = &local_stack;
1928 else
1929 ps = &global_stack;
1930 s = sym_push2(ps, v, type->t, c);
1931 s->type.ref = type->ref;
1932 s->r = r;
1933 /* don't record fields or anonymous symbols */
1934 /* XXX: simplify */
1935 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1936 /* record symbol in token array */
1937 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1938 if (v & SYM_STRUCT)
1939 ps = &ts->sym_struct;
1940 else
1941 ps = &ts->sym_identifier;
1942 s->prev_tok = *ps;
1943 *ps = s;
1945 return s;
1948 /* push a global identifier */
1949 static Sym *global_identifier_push(int v, int t, int c)
1951 Sym *s, **ps;
1952 s = sym_push2(&global_stack, v, t, c);
1953 /* don't record anonymous symbol */
1954 if (v < SYM_FIRST_ANOM) {
1955 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1956 /* modify the top most local identifier, so that
1957 sym_identifier will point to 's' when popped */
1958 while (*ps != NULL)
1959 ps = &(*ps)->prev_tok;
1960 s->prev_tok = NULL;
1961 *ps = s;
1963 return s;
1966 /* pop symbols until top reaches 'b' */
1967 static void sym_pop(Sym **ptop, Sym *b)
1969 Sym *s, *ss, **ps;
1970 TokenSym *ts;
1971 int v;
1973 s = *ptop;
1974 while(s != b) {
1975 ss = s->prev;
1976 v = s->v;
1977 /* remove symbol in token array */
1978 /* XXX: simplify */
1979 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1980 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1981 if (v & SYM_STRUCT)
1982 ps = &ts->sym_struct;
1983 else
1984 ps = &ts->sym_identifier;
1985 *ps = s->prev_tok;
1987 sym_free(s);
1988 s = ss;
1990 *ptop = b;
1993 /* I/O layer */
1995 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1997 int fd;
1998 BufferedFile *bf;
2000 if (strcmp(filename, "-") == 0)
2001 fd = 0, filename = "stdin";
2002 else
2003 fd = open(filename, O_RDONLY | O_BINARY);
2004 if ((verbose == 2 && fd >= 0) || verbose == 3)
2005 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
2006 (s1->include_stack_ptr - s1->include_stack), "", filename);
2007 if (fd < 0)
2008 return NULL;
2009 bf = tcc_malloc(sizeof(BufferedFile));
2010 bf->fd = fd;
2011 bf->buf_ptr = bf->buffer;
2012 bf->buf_end = bf->buffer;
2013 bf->buffer[0] = CH_EOB; /* put eob symbol */
2014 pstrcpy(bf->filename, sizeof(bf->filename), filename);
2015 #ifdef _WIN32
2016 normalize_slashes(bf->filename);
2017 #endif
2018 bf->line_num = 1;
2019 bf->ifndef_macro = 0;
2020 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
2021 // printf("opening '%s'\n", filename);
2022 return bf;
2025 void tcc_close(BufferedFile *bf)
2027 total_lines += bf->line_num;
2028 close(bf->fd);
2029 tcc_free(bf);
2032 /* fill input buffer and peek next char */
2033 static int tcc_peekc_slow(BufferedFile *bf)
2035 int len;
2036 /* only tries to read if really end of buffer */
2037 if (bf->buf_ptr >= bf->buf_end) {
2038 if (bf->fd != -1) {
2039 #if defined(PARSE_DEBUG)
2040 len = 8;
2041 #else
2042 len = IO_BUF_SIZE;
2043 #endif
2044 len = read(bf->fd, bf->buffer, len);
2045 if (len < 0)
2046 len = 0;
2047 } else {
2048 len = 0;
2050 total_bytes += len;
2051 bf->buf_ptr = bf->buffer;
2052 bf->buf_end = bf->buffer + len;
2053 *bf->buf_end = CH_EOB;
2055 if (bf->buf_ptr < bf->buf_end) {
2056 return bf->buf_ptr[0];
2057 } else {
2058 bf->buf_ptr = bf->buf_end;
2059 return CH_EOF;
2063 /* return the current character, handling end of block if necessary
2064 (but not stray) */
2065 static int handle_eob(void)
2067 return tcc_peekc_slow(file);
2070 /* read next char from current input file and handle end of input buffer */
2071 static inline void inp(void)
2073 ch = *(++(file->buf_ptr));
2074 /* end of buffer/file handling */
2075 if (ch == CH_EOB)
2076 ch = handle_eob();
2079 /* handle '\[\r]\n' */
2080 static int handle_stray_noerror(void)
2082 while (ch == '\\') {
2083 inp();
2084 if (ch == '\n') {
2085 file->line_num++;
2086 inp();
2087 } else if (ch == '\r') {
2088 inp();
2089 if (ch != '\n')
2090 goto fail;
2091 file->line_num++;
2092 inp();
2093 } else {
2094 fail:
2095 return 1;
2098 return 0;
2101 static void handle_stray(void)
2103 if (handle_stray_noerror())
2104 error("stray '\\' in program");
2107 /* skip the stray and handle the \\n case. Output an error if
2108 incorrect char after the stray */
2109 static int handle_stray1(uint8_t *p)
2111 int c;
2113 if (p >= file->buf_end) {
2114 file->buf_ptr = p;
2115 c = handle_eob();
2116 p = file->buf_ptr;
2117 if (c == '\\')
2118 goto parse_stray;
2119 } else {
2120 parse_stray:
2121 file->buf_ptr = p;
2122 ch = *p;
2123 handle_stray();
2124 p = file->buf_ptr;
2125 c = *p;
2127 return c;
2130 /* handle just the EOB case, but not stray */
2131 #define PEEKC_EOB(c, p)\
2133 p++;\
2134 c = *p;\
2135 if (c == '\\') {\
2136 file->buf_ptr = p;\
2137 c = handle_eob();\
2138 p = file->buf_ptr;\
2142 /* handle the complicated stray case */
2143 #define PEEKC(c, p)\
2145 p++;\
2146 c = *p;\
2147 if (c == '\\') {\
2148 c = handle_stray1(p);\
2149 p = file->buf_ptr;\
2153 /* input with '\[\r]\n' handling. Note that this function cannot
2154 handle other characters after '\', so you cannot call it inside
2155 strings or comments */
2156 static void minp(void)
2158 inp();
2159 if (ch == '\\')
2160 handle_stray();
2164 /* single line C++ comments */
2165 static uint8_t *parse_line_comment(uint8_t *p)
2167 int c;
2169 p++;
2170 for(;;) {
2171 c = *p;
2172 redo:
2173 if (c == '\n' || c == CH_EOF) {
2174 break;
2175 } else if (c == '\\') {
2176 file->buf_ptr = p;
2177 c = handle_eob();
2178 p = file->buf_ptr;
2179 if (c == '\\') {
2180 PEEKC_EOB(c, p);
2181 if (c == '\n') {
2182 file->line_num++;
2183 PEEKC_EOB(c, p);
2184 } else if (c == '\r') {
2185 PEEKC_EOB(c, p);
2186 if (c == '\n') {
2187 file->line_num++;
2188 PEEKC_EOB(c, p);
2191 } else {
2192 goto redo;
2194 } else {
2195 p++;
2198 return p;
2201 /* C comments */
2202 static uint8_t *parse_comment(uint8_t *p)
2204 int c;
2206 p++;
2207 for(;;) {
2208 /* fast skip loop */
2209 for(;;) {
2210 c = *p;
2211 if (c == '\n' || c == '*' || c == '\\')
2212 break;
2213 p++;
2214 c = *p;
2215 if (c == '\n' || c == '*' || c == '\\')
2216 break;
2217 p++;
2219 /* now we can handle all the cases */
2220 if (c == '\n') {
2221 file->line_num++;
2222 p++;
2223 } else if (c == '*') {
2224 p++;
2225 for(;;) {
2226 c = *p;
2227 if (c == '*') {
2228 p++;
2229 } else if (c == '/') {
2230 goto end_of_comment;
2231 } else if (c == '\\') {
2232 file->buf_ptr = p;
2233 c = handle_eob();
2234 p = file->buf_ptr;
2235 if (c == '\\') {
2236 /* skip '\[\r]\n', otherwise just skip the stray */
2237 while (c == '\\') {
2238 PEEKC_EOB(c, p);
2239 if (c == '\n') {
2240 file->line_num++;
2241 PEEKC_EOB(c, p);
2242 } else if (c == '\r') {
2243 PEEKC_EOB(c, p);
2244 if (c == '\n') {
2245 file->line_num++;
2246 PEEKC_EOB(c, p);
2248 } else {
2249 goto after_star;
2253 } else {
2254 break;
2257 after_star: ;
2258 } else {
2259 /* stray, eob or eof */
2260 file->buf_ptr = p;
2261 c = handle_eob();
2262 p = file->buf_ptr;
2263 if (c == CH_EOF) {
2264 error("unexpected end of file in comment");
2265 } else if (c == '\\') {
2266 p++;
2270 end_of_comment:
2271 p++;
2272 return p;
2275 #define cinp minp
2277 /* space exlcuding newline */
2278 static inline int is_space(int ch)
2280 return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
2283 static inline void skip_spaces(void)
2285 while (is_space(ch))
2286 cinp();
2289 /* parse a string without interpreting escapes */
2290 static uint8_t *parse_pp_string(uint8_t *p,
2291 int sep, CString *str)
2293 int c;
2294 p++;
2295 for(;;) {
2296 c = *p;
2297 if (c == sep) {
2298 break;
2299 } else if (c == '\\') {
2300 file->buf_ptr = p;
2301 c = handle_eob();
2302 p = file->buf_ptr;
2303 if (c == CH_EOF) {
2304 unterminated_string:
2305 /* XXX: indicate line number of start of string */
2306 error("missing terminating %c character", sep);
2307 } else if (c == '\\') {
2308 /* escape : just skip \[\r]\n */
2309 PEEKC_EOB(c, p);
2310 if (c == '\n') {
2311 file->line_num++;
2312 p++;
2313 } else if (c == '\r') {
2314 PEEKC_EOB(c, p);
2315 if (c != '\n')
2316 expect("'\n' after '\r'");
2317 file->line_num++;
2318 p++;
2319 } else if (c == CH_EOF) {
2320 goto unterminated_string;
2321 } else {
2322 if (str) {
2323 cstr_ccat(str, '\\');
2324 cstr_ccat(str, c);
2326 p++;
2329 } else if (c == '\n') {
2330 file->line_num++;
2331 goto add_char;
2332 } else if (c == '\r') {
2333 PEEKC_EOB(c, p);
2334 if (c != '\n') {
2335 if (str)
2336 cstr_ccat(str, '\r');
2337 } else {
2338 file->line_num++;
2339 goto add_char;
2341 } else {
2342 add_char:
2343 if (str)
2344 cstr_ccat(str, c);
2345 p++;
2348 p++;
2349 return p;
2352 /* skip block of text until #else, #elif or #endif. skip also pairs of
2353 #if/#endif */
2354 void preprocess_skip(void)
2356 int a, start_of_line, c, in_warn_or_error;
2357 uint8_t *p;
2359 p = file->buf_ptr;
2360 a = 0;
2361 redo_start:
2362 start_of_line = 1;
2363 in_warn_or_error = 0;
2364 for(;;) {
2365 redo_no_start:
2366 c = *p;
2367 switch(c) {
2368 case ' ':
2369 case '\t':
2370 case '\f':
2371 case '\v':
2372 case '\r':
2373 p++;
2374 goto redo_no_start;
2375 case '\n':
2376 file->line_num++;
2377 p++;
2378 goto redo_start;
2379 case '\\':
2380 file->buf_ptr = p;
2381 c = handle_eob();
2382 if (c == CH_EOF) {
2383 expect("#endif");
2384 } else if (c == '\\') {
2385 ch = file->buf_ptr[0];
2386 handle_stray_noerror();
2388 p = file->buf_ptr;
2389 goto redo_no_start;
2390 /* skip strings */
2391 case '\"':
2392 case '\'':
2393 if (in_warn_or_error)
2394 goto _default;
2395 p = parse_pp_string(p, c, NULL);
2396 break;
2397 /* skip comments */
2398 case '/':
2399 if (in_warn_or_error)
2400 goto _default;
2401 file->buf_ptr = p;
2402 ch = *p;
2403 minp();
2404 p = file->buf_ptr;
2405 if (ch == '*') {
2406 p = parse_comment(p);
2407 } else if (ch == '/') {
2408 p = parse_line_comment(p);
2410 break;
2411 case '#':
2412 p++;
2413 if (start_of_line) {
2414 file->buf_ptr = p;
2415 next_nomacro();
2416 p = file->buf_ptr;
2417 if (a == 0 &&
2418 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
2419 goto the_end;
2420 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
2421 a++;
2422 else if (tok == TOK_ENDIF)
2423 a--;
2424 else if( tok == TOK_ERROR || tok == TOK_WARNING)
2425 in_warn_or_error = 1;
2427 break;
2428 _default:
2429 default:
2430 p++;
2431 break;
2433 start_of_line = 0;
2435 the_end: ;
2436 file->buf_ptr = p;
2439 /* ParseState handling */
2441 /* XXX: currently, no include file info is stored. Thus, we cannot display
2442 accurate messages if the function or data definition spans multiple
2443 files */
2445 /* save current parse state in 's' */
2446 void save_parse_state(ParseState *s)
2448 s->line_num = file->line_num;
2449 s->macro_ptr = macro_ptr;
2450 s->tok = tok;
2451 s->tokc = tokc;
2454 /* restore parse state from 's' */
2455 void restore_parse_state(ParseState *s)
2457 file->line_num = s->line_num;
2458 macro_ptr = s->macro_ptr;
2459 tok = s->tok;
2460 tokc = s->tokc;
2463 /* return the number of additional 'ints' necessary to store the
2464 token */
2465 static inline int tok_ext_size(int t)
2467 switch(t) {
2468 /* 4 bytes */
2469 case TOK_CINT:
2470 case TOK_CUINT:
2471 case TOK_CCHAR:
2472 case TOK_LCHAR:
2473 case TOK_CFLOAT:
2474 case TOK_LINENUM:
2475 return 1;
2476 case TOK_STR:
2477 case TOK_LSTR:
2478 case TOK_PPNUM:
2479 error("unsupported token");
2480 return 1;
2481 case TOK_CDOUBLE:
2482 case TOK_CLLONG:
2483 case TOK_CULLONG:
2484 return 2;
2485 case TOK_CLDOUBLE:
2486 return LDOUBLE_SIZE / 4;
2487 default:
2488 return 0;
2492 /* token string handling */
2494 static inline void tok_str_new(TokenString *s)
2496 s->str = NULL;
2497 s->len = 0;
2498 s->allocated_len = 0;
2499 s->last_line_num = -1;
2502 static void tok_str_free(int *str)
2504 tcc_free(str);
2507 static int *tok_str_realloc(TokenString *s)
2509 int *str, len;
2511 if (s->allocated_len == 0) {
2512 len = 8;
2513 } else {
2514 len = s->allocated_len * 2;
2516 str = tcc_realloc(s->str, len * sizeof(int));
2517 if (!str)
2518 error("memory full");
2519 s->allocated_len = len;
2520 s->str = str;
2521 return str;
2524 static void tok_str_add(TokenString *s, int t)
2526 int len, *str;
2528 len = s->len;
2529 str = s->str;
2530 if (len >= s->allocated_len)
2531 str = tok_str_realloc(s);
2532 str[len++] = t;
2533 s->len = len;
2536 static void tok_str_add2(TokenString *s, int t, CValue *cv)
2538 int len, *str;
2540 len = s->len;
2541 str = s->str;
2543 /* allocate space for worst case */
2544 if (len + TOK_MAX_SIZE > s->allocated_len)
2545 str = tok_str_realloc(s);
2546 str[len++] = t;
2547 switch(t) {
2548 case TOK_CINT:
2549 case TOK_CUINT:
2550 case TOK_CCHAR:
2551 case TOK_LCHAR:
2552 case TOK_CFLOAT:
2553 case TOK_LINENUM:
2554 str[len++] = cv->tab[0];
2555 break;
2556 case TOK_PPNUM:
2557 case TOK_STR:
2558 case TOK_LSTR:
2560 int nb_words;
2561 CString *cstr;
2563 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
2564 while ((len + nb_words) > s->allocated_len)
2565 str = tok_str_realloc(s);
2566 cstr = (CString *)(str + len);
2567 cstr->data = NULL;
2568 cstr->size = cv->cstr->size;
2569 cstr->data_allocated = NULL;
2570 cstr->size_allocated = cstr->size;
2571 memcpy((char *)cstr + sizeof(CString),
2572 cv->cstr->data, cstr->size);
2573 len += nb_words;
2575 break;
2576 case TOK_CDOUBLE:
2577 case TOK_CLLONG:
2578 case TOK_CULLONG:
2579 #if LDOUBLE_SIZE == 8
2580 case TOK_CLDOUBLE:
2581 #endif
2582 str[len++] = cv->tab[0];
2583 str[len++] = cv->tab[1];
2584 break;
2585 #if LDOUBLE_SIZE == 12
2586 case TOK_CLDOUBLE:
2587 str[len++] = cv->tab[0];
2588 str[len++] = cv->tab[1];
2589 str[len++] = cv->tab[2];
2590 #elif LDOUBLE_SIZE == 16
2591 case TOK_CLDOUBLE:
2592 str[len++] = cv->tab[0];
2593 str[len++] = cv->tab[1];
2594 str[len++] = cv->tab[2];
2595 str[len++] = cv->tab[3];
2596 #elif LDOUBLE_SIZE != 8
2597 #error add long double size support
2598 #endif
2599 break;
2600 default:
2601 break;
2603 s->len = len;
2606 /* add the current parse token in token string 's' */
2607 static void tok_str_add_tok(TokenString *s)
2609 CValue cval;
2611 /* save line number info */
2612 if (file->line_num != s->last_line_num) {
2613 s->last_line_num = file->line_num;
2614 cval.i = s->last_line_num;
2615 tok_str_add2(s, TOK_LINENUM, &cval);
2617 tok_str_add2(s, tok, &tokc);
2620 #if LDOUBLE_SIZE == 16
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 cv.tab[3] = p[3];
2626 #elif LDOUBLE_SIZE == 12
2627 #define LDOUBLE_GET(p, cv) \
2628 cv.tab[0] = p[0]; \
2629 cv.tab[1] = p[1]; \
2630 cv.tab[2] = p[2];
2631 #elif LDOUBLE_SIZE == 8
2632 #define LDOUBLE_GET(p, cv) \
2633 cv.tab[0] = p[0]; \
2634 cv.tab[1] = p[1];
2635 #else
2636 #error add long double size support
2637 #endif
2640 /* get a token from an integer array and increment pointer
2641 accordingly. we code it as a macro to avoid pointer aliasing. */
2642 #define TOK_GET(t, p, cv) \
2644 t = *p++; \
2645 switch(t) { \
2646 case TOK_CINT: \
2647 case TOK_CUINT: \
2648 case TOK_CCHAR: \
2649 case TOK_LCHAR: \
2650 case TOK_CFLOAT: \
2651 case TOK_LINENUM: \
2652 cv.tab[0] = *p++; \
2653 break; \
2654 case TOK_STR: \
2655 case TOK_LSTR: \
2656 case TOK_PPNUM: \
2657 cv.cstr = (CString *)p; \
2658 cv.cstr->data = (char *)p + sizeof(CString);\
2659 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2660 break; \
2661 case TOK_CDOUBLE: \
2662 case TOK_CLLONG: \
2663 case TOK_CULLONG: \
2664 cv.tab[0] = p[0]; \
2665 cv.tab[1] = p[1]; \
2666 p += 2; \
2667 break; \
2668 case TOK_CLDOUBLE: \
2669 LDOUBLE_GET(p, cv); \
2670 p += LDOUBLE_SIZE / 4; \
2671 break; \
2672 default: \
2673 break; \
2677 /* defines handling */
2678 static inline void define_push(int v, int macro_type, int *str, Sym *first_arg)
2680 Sym *s;
2682 s = sym_push2(&define_stack, v, macro_type, (long)str);
2683 s->next = first_arg;
2684 table_ident[v - TOK_IDENT]->sym_define = s;
2687 /* undefined a define symbol. Its name is just set to zero */
2688 static void define_undef(Sym *s)
2690 int v;
2691 v = s->v;
2692 if (v >= TOK_IDENT && v < tok_ident)
2693 table_ident[v - TOK_IDENT]->sym_define = NULL;
2694 s->v = 0;
2697 static inline Sym *define_find(int v)
2699 v -= TOK_IDENT;
2700 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2701 return NULL;
2702 return table_ident[v]->sym_define;
2705 /* free define stack until top reaches 'b' */
2706 static void free_defines(Sym *b)
2708 Sym *top, *top1;
2709 int v;
2711 top = define_stack;
2712 while (top != b) {
2713 top1 = top->prev;
2714 /* do not free args or predefined defines */
2715 if (top->c)
2716 tok_str_free((int *)top->c);
2717 v = top->v;
2718 if (v >= TOK_IDENT && v < tok_ident)
2719 table_ident[v - TOK_IDENT]->sym_define = NULL;
2720 sym_free(top);
2721 top = top1;
2723 define_stack = b;
2726 /* label lookup */
2727 static Sym *label_find(int v)
2729 v -= TOK_IDENT;
2730 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2731 return NULL;
2732 return table_ident[v]->sym_label;
2735 static Sym *label_push(Sym **ptop, int v, int flags)
2737 Sym *s, **ps;
2738 s = sym_push2(ptop, v, 0, 0);
2739 s->r = flags;
2740 ps = &table_ident[v - TOK_IDENT]->sym_label;
2741 if (ptop == &global_label_stack) {
2742 /* modify the top most local identifier, so that
2743 sym_identifier will point to 's' when popped */
2744 while (*ps != NULL)
2745 ps = &(*ps)->prev_tok;
2747 s->prev_tok = *ps;
2748 *ps = s;
2749 return s;
2752 /* pop labels until element last is reached. Look if any labels are
2753 undefined. Define symbols if '&&label' was used. */
2754 static void label_pop(Sym **ptop, Sym *slast)
2756 Sym *s, *s1;
2757 for(s = *ptop; s != slast; s = s1) {
2758 s1 = s->prev;
2759 if (s->r == LABEL_DECLARED) {
2760 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
2761 } else if (s->r == LABEL_FORWARD) {
2762 error("label '%s' used but not defined",
2763 get_tok_str(s->v, NULL));
2764 } else {
2765 if (s->c) {
2766 /* define corresponding symbol. A size of
2767 1 is put. */
2768 put_extern_sym(s, cur_text_section, (long)s->next, 1);
2771 /* remove label */
2772 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
2773 sym_free(s);
2775 *ptop = slast;
2778 /* eval an expression for #if/#elif */
2779 static int expr_preprocess(void)
2781 int c, t;
2782 TokenString str;
2784 tok_str_new(&str);
2785 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2786 next(); /* do macro subst */
2787 if (tok == TOK_DEFINED) {
2788 next_nomacro();
2789 t = tok;
2790 if (t == '(')
2791 next_nomacro();
2792 c = define_find(tok) != 0;
2793 if (t == '(')
2794 next_nomacro();
2795 tok = TOK_CINT;
2796 tokc.i = c;
2797 } else if (tok >= TOK_IDENT) {
2798 /* if undefined macro */
2799 tok = TOK_CINT;
2800 tokc.i = 0;
2802 tok_str_add_tok(&str);
2804 tok_str_add(&str, -1); /* simulate end of file */
2805 tok_str_add(&str, 0);
2806 /* now evaluate C constant expression */
2807 macro_ptr = str.str;
2808 next();
2809 c = expr_const();
2810 macro_ptr = NULL;
2811 tok_str_free(str.str);
2812 return c != 0;
2815 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2816 static void tok_print(int *str)
2818 int t;
2819 CValue cval;
2821 while (1) {
2822 TOK_GET(t, str, cval);
2823 if (!t)
2824 break;
2825 printf(" %s", get_tok_str(t, &cval));
2827 printf("\n");
2829 #endif
2831 /* parse after #define */
2832 static void parse_define(void)
2834 Sym *s, *first, **ps;
2835 int v, t, varg, is_vaargs, c;
2836 TokenString str;
2838 v = tok;
2839 if (v < TOK_IDENT)
2840 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
2841 /* XXX: should check if same macro (ANSI) */
2842 first = NULL;
2843 t = MACRO_OBJ;
2844 /* '(' must be just after macro definition for MACRO_FUNC */
2845 c = file->buf_ptr[0];
2846 if (c == '\\')
2847 c = handle_stray1(file->buf_ptr);
2848 if (c == '(') {
2849 next_nomacro();
2850 next_nomacro();
2851 ps = &first;
2852 while (tok != ')') {
2853 varg = tok;
2854 next_nomacro();
2855 is_vaargs = 0;
2856 if (varg == TOK_DOTS) {
2857 varg = TOK___VA_ARGS__;
2858 is_vaargs = 1;
2859 } else if (tok == TOK_DOTS && gnu_ext) {
2860 is_vaargs = 1;
2861 next_nomacro();
2863 if (varg < TOK_IDENT)
2864 error("badly punctuated parameter list");
2865 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
2866 *ps = s;
2867 ps = &s->next;
2868 if (tok != ',')
2869 break;
2870 next_nomacro();
2872 t = MACRO_FUNC;
2874 tok_str_new(&str);
2875 next_nomacro();
2876 /* EOF testing necessary for '-D' handling */
2877 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2878 tok_str_add2(&str, tok, &tokc);
2879 next_nomacro();
2881 tok_str_add(&str, 0);
2882 #ifdef PP_DEBUG
2883 printf("define %s %d: ", get_tok_str(v, NULL), t);
2884 tok_print(str.str);
2885 #endif
2886 define_push(v, t, str.str, first);
2889 static inline int hash_cached_include(int type, const char *filename)
2891 const unsigned char *s;
2892 unsigned int h;
2894 h = TOK_HASH_INIT;
2895 h = TOK_HASH_FUNC(h, type);
2896 s = filename;
2897 while (*s) {
2898 h = TOK_HASH_FUNC(h, *s);
2899 s++;
2901 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
2902 return h;
2905 /* XXX: use a token or a hash table to accelerate matching ? */
2906 static CachedInclude *search_cached_include(TCCState *s1,
2907 int type, const char *filename)
2909 CachedInclude *e;
2910 int i, h;
2911 h = hash_cached_include(type, filename);
2912 i = s1->cached_includes_hash[h];
2913 for(;;) {
2914 if (i == 0)
2915 break;
2916 e = s1->cached_includes[i - 1];
2917 if (e->type == type && !PATHCMP(e->filename, filename))
2918 return e;
2919 i = e->hash_next;
2921 return NULL;
2924 static inline void add_cached_include(TCCState *s1, int type,
2925 const char *filename, int ifndef_macro)
2927 CachedInclude *e;
2928 int h;
2930 if (search_cached_include(s1, type, filename))
2931 return;
2932 #ifdef INC_DEBUG
2933 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
2934 #endif
2935 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
2936 if (!e)
2937 return;
2938 e->type = type;
2939 strcpy(e->filename, filename);
2940 e->ifndef_macro = ifndef_macro;
2941 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
2942 /* add in hash table */
2943 h = hash_cached_include(type, filename);
2944 e->hash_next = s1->cached_includes_hash[h];
2945 s1->cached_includes_hash[h] = s1->nb_cached_includes;
2948 static void pragma_parse(TCCState *s1)
2950 int val;
2952 next();
2953 if (tok == TOK_pack) {
2955 This may be:
2956 #pragma pack(1) // set
2957 #pragma pack() // reset to default
2958 #pragma pack(push,1) // push & set
2959 #pragma pack(pop) // restore previous
2961 next();
2962 skip('(');
2963 if (tok == TOK_ASM_pop) {
2964 next();
2965 if (s1->pack_stack_ptr <= s1->pack_stack) {
2966 stk_error:
2967 error("out of pack stack");
2969 s1->pack_stack_ptr--;
2970 } else {
2971 val = 0;
2972 if (tok != ')') {
2973 if (tok == TOK_ASM_push) {
2974 next();
2975 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
2976 goto stk_error;
2977 s1->pack_stack_ptr++;
2978 skip(',');
2980 if (tok != TOK_CINT) {
2981 pack_error:
2982 error("invalid pack pragma");
2984 val = tokc.i;
2985 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
2986 goto pack_error;
2987 next();
2989 *s1->pack_stack_ptr = val;
2990 skip(')');
2995 /* is_bof is true if first non space token at beginning of file */
2996 static void preprocess(int is_bof)
2998 TCCState *s1 = tcc_state;
2999 int size, i, c, n, saved_parse_flags;
3000 char buf[1024], *q;
3001 char buf1[1024];
3002 BufferedFile *f;
3003 Sym *s;
3004 CachedInclude *e;
3006 saved_parse_flags = parse_flags;
3007 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
3008 PARSE_FLAG_LINEFEED;
3009 next_nomacro();
3010 redo:
3011 switch(tok) {
3012 case TOK_DEFINE:
3013 next_nomacro();
3014 parse_define();
3015 break;
3016 case TOK_UNDEF:
3017 next_nomacro();
3018 s = define_find(tok);
3019 /* undefine symbol by putting an invalid name */
3020 if (s)
3021 define_undef(s);
3022 break;
3023 case TOK_INCLUDE:
3024 case TOK_INCLUDE_NEXT:
3025 ch = file->buf_ptr[0];
3026 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3027 skip_spaces();
3028 if (ch == '<') {
3029 c = '>';
3030 goto read_name;
3031 } else if (ch == '\"') {
3032 c = ch;
3033 read_name:
3034 inp();
3035 q = buf;
3036 while (ch != c && ch != '\n' && ch != CH_EOF) {
3037 if ((q - buf) < sizeof(buf) - 1)
3038 *q++ = ch;
3039 if (ch == '\\') {
3040 if (handle_stray_noerror() == 0)
3041 --q;
3042 } else
3043 inp();
3045 *q = '\0';
3046 minp();
3047 #if 0
3048 /* eat all spaces and comments after include */
3049 /* XXX: slightly incorrect */
3050 while (ch1 != '\n' && ch1 != CH_EOF)
3051 inp();
3052 #endif
3053 } else {
3054 /* computed #include : either we have only strings or
3055 we have anything enclosed in '<>' */
3056 next();
3057 buf[0] = '\0';
3058 if (tok == TOK_STR) {
3059 while (tok != TOK_LINEFEED) {
3060 if (tok != TOK_STR) {
3061 include_syntax:
3062 error("'#include' expects \"FILENAME\" or <FILENAME>");
3064 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
3065 next();
3067 c = '\"';
3068 } else {
3069 int len;
3070 while (tok != TOK_LINEFEED) {
3071 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
3072 next();
3074 len = strlen(buf);
3075 /* check syntax and remove '<>' */
3076 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
3077 goto include_syntax;
3078 memmove(buf, buf + 1, len - 2);
3079 buf[len - 2] = '\0';
3080 c = '>';
3084 e = search_cached_include(s1, c, buf);
3085 if (e && define_find(e->ifndef_macro)) {
3086 /* no need to parse the include because the 'ifndef macro'
3087 is defined */
3088 #ifdef INC_DEBUG
3089 printf("%s: skipping %s\n", file->filename, buf);
3090 #endif
3091 } else {
3092 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
3093 error("#include recursion too deep");
3094 /* push current file in stack */
3095 /* XXX: fix current line init */
3096 *s1->include_stack_ptr++ = file;
3098 /* check absolute include path */
3099 if (IS_ABSPATH(buf)) {
3100 f = tcc_open(s1, buf);
3101 if (f)
3102 goto found;
3104 if (c == '\"') {
3105 /* first search in current dir if "header.h" */
3106 size = tcc_basename(file->filename) - file->filename;
3107 if (size > sizeof(buf1) - 1)
3108 size = sizeof(buf1) - 1;
3109 memcpy(buf1, file->filename, size);
3110 buf1[size] = '\0';
3111 pstrcat(buf1, sizeof(buf1), buf);
3112 f = tcc_open(s1, buf1);
3113 if (f) {
3114 if (tok == TOK_INCLUDE_NEXT)
3115 tok = TOK_INCLUDE;
3116 else
3117 goto found;
3120 /* now search in all the include paths */
3121 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
3122 for(i = 0; i < n; i++) {
3123 const char *path;
3124 if (i < s1->nb_include_paths)
3125 path = s1->include_paths[i];
3126 else
3127 path = s1->sysinclude_paths[i - s1->nb_include_paths];
3128 pstrcpy(buf1, sizeof(buf1), path);
3129 pstrcat(buf1, sizeof(buf1), "/");
3130 pstrcat(buf1, sizeof(buf1), buf);
3131 f = tcc_open(s1, buf1);
3132 if (f) {
3133 if (tok == TOK_INCLUDE_NEXT)
3134 tok = TOK_INCLUDE;
3135 else
3136 goto found;
3139 --s1->include_stack_ptr;
3140 error("include file '%s' not found", buf);
3141 break;
3142 found:
3143 #ifdef INC_DEBUG
3144 printf("%s: including %s\n", file->filename, buf1);
3145 #endif
3146 f->inc_type = c;
3147 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf);
3148 file = f;
3149 /* add include file debug info */
3150 if (do_debug) {
3151 put_stabs(file->filename, N_BINCL, 0, 0, 0);
3153 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
3154 ch = file->buf_ptr[0];
3155 goto the_end;
3157 break;
3158 case TOK_IFNDEF:
3159 c = 1;
3160 goto do_ifdef;
3161 case TOK_IF:
3162 c = expr_preprocess();
3163 goto do_if;
3164 case TOK_IFDEF:
3165 c = 0;
3166 do_ifdef:
3167 next_nomacro();
3168 if (tok < TOK_IDENT)
3169 error("invalid argument for '#if%sdef'", c ? "n" : "");
3170 if (is_bof) {
3171 if (c) {
3172 #ifdef INC_DEBUG
3173 printf("#ifndef %s\n", get_tok_str(tok, NULL));
3174 #endif
3175 file->ifndef_macro = tok;
3178 c = (define_find(tok) != 0) ^ c;
3179 do_if:
3180 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
3181 error("memory full");
3182 *s1->ifdef_stack_ptr++ = c;
3183 goto test_skip;
3184 case TOK_ELSE:
3185 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3186 error("#else without matching #if");
3187 if (s1->ifdef_stack_ptr[-1] & 2)
3188 error("#else after #else");
3189 c = (s1->ifdef_stack_ptr[-1] ^= 3);
3190 goto test_skip;
3191 case TOK_ELIF:
3192 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3193 error("#elif without matching #if");
3194 c = s1->ifdef_stack_ptr[-1];
3195 if (c > 1)
3196 error("#elif after #else");
3197 /* last #if/#elif expression was true: we skip */
3198 if (c == 1)
3199 goto skip;
3200 c = expr_preprocess();
3201 s1->ifdef_stack_ptr[-1] = c;
3202 test_skip:
3203 if (!(c & 1)) {
3204 skip:
3205 preprocess_skip();
3206 is_bof = 0;
3207 goto redo;
3209 break;
3210 case TOK_ENDIF:
3211 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
3212 error("#endif without matching #if");
3213 s1->ifdef_stack_ptr--;
3214 /* '#ifndef macro' was at the start of file. Now we check if
3215 an '#endif' is exactly at the end of file */
3216 if (file->ifndef_macro &&
3217 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
3218 file->ifndef_macro_saved = file->ifndef_macro;
3219 /* need to set to zero to avoid false matches if another
3220 #ifndef at middle of file */
3221 file->ifndef_macro = 0;
3222 while (tok != TOK_LINEFEED)
3223 next_nomacro();
3224 tok_flags |= TOK_FLAG_ENDIF;
3225 goto the_end;
3227 break;
3228 case TOK_LINE:
3229 next();
3230 if (tok != TOK_CINT)
3231 error("#line");
3232 file->line_num = tokc.i - 1; /* the line number will be incremented after */
3233 next();
3234 if (tok != TOK_LINEFEED) {
3235 if (tok != TOK_STR)
3236 error("#line");
3237 pstrcpy(file->filename, sizeof(file->filename),
3238 (char *)tokc.cstr->data);
3240 break;
3241 case TOK_ERROR:
3242 case TOK_WARNING:
3243 c = tok;
3244 ch = file->buf_ptr[0];
3245 skip_spaces();
3246 q = buf;
3247 while (ch != '\n' && ch != CH_EOF) {
3248 if ((q - buf) < sizeof(buf) - 1)
3249 *q++ = ch;
3250 if (ch == '\\') {
3251 if (handle_stray_noerror() == 0)
3252 --q;
3253 } else
3254 inp();
3256 *q = '\0';
3257 if (c == TOK_ERROR)
3258 error("#error %s", buf);
3259 else
3260 warning("#warning %s", buf);
3261 break;
3262 case TOK_PRAGMA:
3263 pragma_parse(s1);
3264 break;
3265 default:
3266 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
3267 /* '!' is ignored to allow C scripts. numbers are ignored
3268 to emulate cpp behaviour */
3269 } else {
3270 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
3271 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
3273 break;
3275 /* ignore other preprocess commands or #! for C scripts */
3276 while (tok != TOK_LINEFEED)
3277 next_nomacro();
3278 the_end:
3279 parse_flags = saved_parse_flags;
3282 /* evaluate escape codes in a string. */
3283 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
3285 int c, n;
3286 const uint8_t *p;
3288 p = buf;
3289 for(;;) {
3290 c = *p;
3291 if (c == '\0')
3292 break;
3293 if (c == '\\') {
3294 p++;
3295 /* escape */
3296 c = *p;
3297 switch(c) {
3298 case '0': case '1': case '2': case '3':
3299 case '4': case '5': case '6': case '7':
3300 /* at most three octal digits */
3301 n = c - '0';
3302 p++;
3303 c = *p;
3304 if (isoct(c)) {
3305 n = n * 8 + c - '0';
3306 p++;
3307 c = *p;
3308 if (isoct(c)) {
3309 n = n * 8 + c - '0';
3310 p++;
3313 c = n;
3314 goto add_char_nonext;
3315 case 'x':
3316 case 'u':
3317 case 'U':
3318 p++;
3319 n = 0;
3320 for(;;) {
3321 c = *p;
3322 if (c >= 'a' && c <= 'f')
3323 c = c - 'a' + 10;
3324 else if (c >= 'A' && c <= 'F')
3325 c = c - 'A' + 10;
3326 else if (isnum(c))
3327 c = c - '0';
3328 else
3329 break;
3330 n = n * 16 + c;
3331 p++;
3333 c = n;
3334 goto add_char_nonext;
3335 case 'a':
3336 c = '\a';
3337 break;
3338 case 'b':
3339 c = '\b';
3340 break;
3341 case 'f':
3342 c = '\f';
3343 break;
3344 case 'n':
3345 c = '\n';
3346 break;
3347 case 'r':
3348 c = '\r';
3349 break;
3350 case 't':
3351 c = '\t';
3352 break;
3353 case 'v':
3354 c = '\v';
3355 break;
3356 case 'e':
3357 if (!gnu_ext)
3358 goto invalid_escape;
3359 c = 27;
3360 break;
3361 case '\'':
3362 case '\"':
3363 case '\\':
3364 case '?':
3365 break;
3366 default:
3367 invalid_escape:
3368 if (c >= '!' && c <= '~')
3369 warning("unknown escape sequence: \'\\%c\'", c);
3370 else
3371 warning("unknown escape sequence: \'\\x%x\'", c);
3372 break;
3375 p++;
3376 add_char_nonext:
3377 if (!is_long)
3378 cstr_ccat(outstr, c);
3379 else
3380 cstr_wccat(outstr, c);
3382 /* add a trailing '\0' */
3383 if (!is_long)
3384 cstr_ccat(outstr, '\0');
3385 else
3386 cstr_wccat(outstr, '\0');
3389 /* we use 64 bit numbers */
3390 #define BN_SIZE 2
3392 /* bn = (bn << shift) | or_val */
3393 void bn_lshift(unsigned int *bn, int shift, int or_val)
3395 int i;
3396 unsigned int v;
3397 for(i=0;i<BN_SIZE;i++) {
3398 v = bn[i];
3399 bn[i] = (v << shift) | or_val;
3400 or_val = v >> (32 - shift);
3404 void bn_zero(unsigned int *bn)
3406 int i;
3407 for(i=0;i<BN_SIZE;i++) {
3408 bn[i] = 0;
3412 /* parse number in null terminated string 'p' and return it in the
3413 current token */
3414 void parse_number(const char *p)
3416 int b, t, shift, frac_bits, s, exp_val, ch;
3417 char *q;
3418 unsigned int bn[BN_SIZE];
3419 double d;
3421 /* number */
3422 q = token_buf;
3423 ch = *p++;
3424 t = ch;
3425 ch = *p++;
3426 *q++ = t;
3427 b = 10;
3428 if (t == '.') {
3429 goto float_frac_parse;
3430 } else if (t == '0') {
3431 if (ch == 'x' || ch == 'X') {
3432 q--;
3433 ch = *p++;
3434 b = 16;
3435 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
3436 q--;
3437 ch = *p++;
3438 b = 2;
3441 /* parse all digits. cannot check octal numbers at this stage
3442 because of floating point constants */
3443 while (1) {
3444 if (ch >= 'a' && ch <= 'f')
3445 t = ch - 'a' + 10;
3446 else if (ch >= 'A' && ch <= 'F')
3447 t = ch - 'A' + 10;
3448 else if (isnum(ch))
3449 t = ch - '0';
3450 else
3451 break;
3452 if (t >= b)
3453 break;
3454 if (q >= token_buf + STRING_MAX_SIZE) {
3455 num_too_long:
3456 error("number too long");
3458 *q++ = ch;
3459 ch = *p++;
3461 if (ch == '.' ||
3462 ((ch == 'e' || ch == 'E') && b == 10) ||
3463 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
3464 if (b != 10) {
3465 /* NOTE: strtox should support that for hexa numbers, but
3466 non ISOC99 libcs do not support it, so we prefer to do
3467 it by hand */
3468 /* hexadecimal or binary floats */
3469 /* XXX: handle overflows */
3470 *q = '\0';
3471 if (b == 16)
3472 shift = 4;
3473 else
3474 shift = 2;
3475 bn_zero(bn);
3476 q = token_buf;
3477 while (1) {
3478 t = *q++;
3479 if (t == '\0') {
3480 break;
3481 } else if (t >= 'a') {
3482 t = t - 'a' + 10;
3483 } else if (t >= 'A') {
3484 t = t - 'A' + 10;
3485 } else {
3486 t = t - '0';
3488 bn_lshift(bn, shift, t);
3490 frac_bits = 0;
3491 if (ch == '.') {
3492 ch = *p++;
3493 while (1) {
3494 t = ch;
3495 if (t >= 'a' && t <= 'f') {
3496 t = t - 'a' + 10;
3497 } else if (t >= 'A' && t <= 'F') {
3498 t = t - 'A' + 10;
3499 } else if (t >= '0' && t <= '9') {
3500 t = t - '0';
3501 } else {
3502 break;
3504 if (t >= b)
3505 error("invalid digit");
3506 bn_lshift(bn, shift, t);
3507 frac_bits += shift;
3508 ch = *p++;
3511 if (ch != 'p' && ch != 'P')
3512 expect("exponent");
3513 ch = *p++;
3514 s = 1;
3515 exp_val = 0;
3516 if (ch == '+') {
3517 ch = *p++;
3518 } else if (ch == '-') {
3519 s = -1;
3520 ch = *p++;
3522 if (ch < '0' || ch > '9')
3523 expect("exponent digits");
3524 while (ch >= '0' && ch <= '9') {
3525 exp_val = exp_val * 10 + ch - '0';
3526 ch = *p++;
3528 exp_val = exp_val * s;
3530 /* now we can generate the number */
3531 /* XXX: should patch directly float number */
3532 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
3533 d = ldexp(d, exp_val - frac_bits);
3534 t = toup(ch);
3535 if (t == 'F') {
3536 ch = *p++;
3537 tok = TOK_CFLOAT;
3538 /* float : should handle overflow */
3539 tokc.f = (float)d;
3540 } else if (t == 'L') {
3541 ch = *p++;
3542 tok = TOK_CLDOUBLE;
3543 /* XXX: not large enough */
3544 tokc.ld = (long double)d;
3545 } else {
3546 tok = TOK_CDOUBLE;
3547 tokc.d = d;
3549 } else {
3550 /* decimal floats */
3551 if (ch == '.') {
3552 if (q >= token_buf + STRING_MAX_SIZE)
3553 goto num_too_long;
3554 *q++ = ch;
3555 ch = *p++;
3556 float_frac_parse:
3557 while (ch >= '0' && ch <= '9') {
3558 if (q >= token_buf + STRING_MAX_SIZE)
3559 goto num_too_long;
3560 *q++ = ch;
3561 ch = *p++;
3564 if (ch == 'e' || ch == 'E') {
3565 if (q >= token_buf + STRING_MAX_SIZE)
3566 goto num_too_long;
3567 *q++ = ch;
3568 ch = *p++;
3569 if (ch == '-' || ch == '+') {
3570 if (q >= token_buf + STRING_MAX_SIZE)
3571 goto num_too_long;
3572 *q++ = ch;
3573 ch = *p++;
3575 if (ch < '0' || ch > '9')
3576 expect("exponent digits");
3577 while (ch >= '0' && ch <= '9') {
3578 if (q >= token_buf + STRING_MAX_SIZE)
3579 goto num_too_long;
3580 *q++ = ch;
3581 ch = *p++;
3584 *q = '\0';
3585 t = toup(ch);
3586 errno = 0;
3587 if (t == 'F') {
3588 ch = *p++;
3589 tok = TOK_CFLOAT;
3590 tokc.f = strtof(token_buf, NULL);
3591 } else if (t == 'L') {
3592 ch = *p++;
3593 tok = TOK_CLDOUBLE;
3594 tokc.ld = strtold(token_buf, NULL);
3595 } else {
3596 tok = TOK_CDOUBLE;
3597 tokc.d = strtod(token_buf, NULL);
3600 } else {
3601 unsigned long long n, n1;
3602 int lcount, ucount;
3604 /* integer number */
3605 *q = '\0';
3606 q = token_buf;
3607 if (b == 10 && *q == '0') {
3608 b = 8;
3609 q++;
3611 n = 0;
3612 while(1) {
3613 t = *q++;
3614 /* no need for checks except for base 10 / 8 errors */
3615 if (t == '\0') {
3616 break;
3617 } else if (t >= 'a') {
3618 t = t - 'a' + 10;
3619 } else if (t >= 'A') {
3620 t = t - 'A' + 10;
3621 } else {
3622 t = t - '0';
3623 if (t >= b)
3624 error("invalid digit");
3626 n1 = n;
3627 n = n * b + t;
3628 /* detect overflow */
3629 /* XXX: this test is not reliable */
3630 if (n < n1)
3631 error("integer constant overflow");
3634 /* XXX: not exactly ANSI compliant */
3635 if ((n & 0xffffffff00000000LL) != 0) {
3636 if ((n >> 63) != 0)
3637 tok = TOK_CULLONG;
3638 else
3639 tok = TOK_CLLONG;
3640 } else if (n > 0x7fffffff) {
3641 tok = TOK_CUINT;
3642 } else {
3643 tok = TOK_CINT;
3645 lcount = 0;
3646 ucount = 0;
3647 for(;;) {
3648 t = toup(ch);
3649 if (t == 'L') {
3650 if (lcount >= 2)
3651 error("three 'l's in integer constant");
3652 lcount++;
3653 if (lcount == 2) {
3654 if (tok == TOK_CINT)
3655 tok = TOK_CLLONG;
3656 else if (tok == TOK_CUINT)
3657 tok = TOK_CULLONG;
3659 ch = *p++;
3660 } else if (t == 'U') {
3661 if (ucount >= 1)
3662 error("two 'u's in integer constant");
3663 ucount++;
3664 if (tok == TOK_CINT)
3665 tok = TOK_CUINT;
3666 else if (tok == TOK_CLLONG)
3667 tok = TOK_CULLONG;
3668 ch = *p++;
3669 } else {
3670 break;
3673 if (tok == TOK_CINT || tok == TOK_CUINT)
3674 tokc.ui = n;
3675 else
3676 tokc.ull = n;
3678 if (ch)
3679 error("invalid number\n");
3683 #define PARSE2(c1, tok1, c2, tok2) \
3684 case c1: \
3685 PEEKC(c, p); \
3686 if (c == c2) { \
3687 p++; \
3688 tok = tok2; \
3689 } else { \
3690 tok = tok1; \
3692 break;
3694 /* return next token without macro substitution */
3695 static inline void next_nomacro1(void)
3697 int t, c, is_long;
3698 TokenSym *ts;
3699 uint8_t *p, *p1;
3700 unsigned int h;
3702 cstr_reset(&tok_spaces);
3703 p = file->buf_ptr;
3704 redo_no_start:
3705 c = *p;
3706 switch(c) {
3707 case ' ':
3708 case '\t':
3709 case '\f':
3710 case '\v':
3711 case '\r':
3712 cstr_ccat(&tok_spaces, c);
3713 p++;
3714 goto redo_no_start;
3716 case '\\':
3717 /* first look if it is in fact an end of buffer */
3718 if (p >= file->buf_end) {
3719 file->buf_ptr = p;
3720 handle_eob();
3721 p = file->buf_ptr;
3722 if (p >= file->buf_end)
3723 goto parse_eof;
3724 else
3725 goto redo_no_start;
3726 } else {
3727 file->buf_ptr = p;
3728 ch = *p;
3729 handle_stray();
3730 p = file->buf_ptr;
3731 goto redo_no_start;
3733 parse_eof:
3735 TCCState *s1 = tcc_state;
3736 if ((parse_flags & PARSE_FLAG_LINEFEED)
3737 && !(tok_flags & TOK_FLAG_EOF)) {
3738 tok_flags |= TOK_FLAG_EOF;
3739 tok = TOK_LINEFEED;
3740 goto keep_tok_flags;
3741 } else if (s1->include_stack_ptr == s1->include_stack ||
3742 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
3743 /* no include left : end of file. */
3744 tok = TOK_EOF;
3745 } else {
3746 tok_flags &= ~TOK_FLAG_EOF;
3747 /* pop include file */
3749 /* test if previous '#endif' was after a #ifdef at
3750 start of file */
3751 if (tok_flags & TOK_FLAG_ENDIF) {
3752 #ifdef INC_DEBUG
3753 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
3754 #endif
3755 add_cached_include(s1, file->inc_type, file->inc_filename,
3756 file->ifndef_macro_saved);
3759 /* add end of include file debug info */
3760 if (do_debug) {
3761 put_stabd(N_EINCL, 0, 0);
3763 /* pop include stack */
3764 tcc_close(file);
3765 s1->include_stack_ptr--;
3766 file = *s1->include_stack_ptr;
3767 p = file->buf_ptr;
3768 goto redo_no_start;
3771 break;
3773 case '\n':
3774 file->line_num++;
3775 tok_flags |= TOK_FLAG_BOL;
3776 p++;
3777 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
3778 goto redo_no_start;
3779 tok = TOK_LINEFEED;
3780 goto keep_tok_flags;
3782 case '#':
3783 /* XXX: simplify */
3784 PEEKC(c, p);
3785 if ((tok_flags & TOK_FLAG_BOL) &&
3786 (parse_flags & PARSE_FLAG_PREPROCESS)) {
3787 file->buf_ptr = p;
3788 preprocess(tok_flags & TOK_FLAG_BOF);
3789 p = file->buf_ptr;
3790 goto redo_no_start;
3791 } else {
3792 if (c == '#') {
3793 p++;
3794 tok = TOK_TWOSHARPS;
3795 } else {
3796 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
3797 p = parse_line_comment(p - 1);
3798 goto redo_no_start;
3799 } else {
3800 tok = '#';
3804 break;
3806 case 'a': case 'b': case 'c': case 'd':
3807 case 'e': case 'f': case 'g': case 'h':
3808 case 'i': case 'j': case 'k': case 'l':
3809 case 'm': case 'n': case 'o': case 'p':
3810 case 'q': case 'r': case 's': case 't':
3811 case 'u': case 'v': case 'w': case 'x':
3812 case 'y': case 'z':
3813 case 'A': case 'B': case 'C': case 'D':
3814 case 'E': case 'F': case 'G': case 'H':
3815 case 'I': case 'J': case 'K':
3816 case 'M': case 'N': case 'O': case 'P':
3817 case 'Q': case 'R': case 'S': case 'T':
3818 case 'U': case 'V': case 'W': case 'X':
3819 case 'Y': case 'Z':
3820 case '_':
3821 parse_ident_fast:
3822 p1 = p;
3823 h = TOK_HASH_INIT;
3824 h = TOK_HASH_FUNC(h, c);
3825 p++;
3826 for(;;) {
3827 c = *p;
3828 if (!isidnum_table[c-CH_EOF])
3829 break;
3830 h = TOK_HASH_FUNC(h, c);
3831 p++;
3833 if (c != '\\') {
3834 TokenSym **pts;
3835 int len;
3837 /* fast case : no stray found, so we have the full token
3838 and we have already hashed it */
3839 len = p - p1;
3840 h &= (TOK_HASH_SIZE - 1);
3841 pts = &hash_ident[h];
3842 for(;;) {
3843 ts = *pts;
3844 if (!ts)
3845 break;
3846 if (ts->len == len && !memcmp(ts->str, p1, len))
3847 goto token_found;
3848 pts = &(ts->hash_next);
3850 ts = tok_alloc_new(pts, p1, len);
3851 token_found: ;
3852 } else {
3853 /* slower case */
3854 cstr_reset(&tokcstr);
3856 while (p1 < p) {
3857 cstr_ccat(&tokcstr, *p1);
3858 p1++;
3860 p--;
3861 PEEKC(c, p);
3862 parse_ident_slow:
3863 while (isidnum_table[c-CH_EOF]) {
3864 cstr_ccat(&tokcstr, c);
3865 PEEKC(c, p);
3867 ts = tok_alloc(tokcstr.data, tokcstr.size);
3869 tok = ts->tok;
3870 break;
3871 case 'L':
3872 t = p[1];
3873 if (t != '\\' && t != '\'' && t != '\"') {
3874 /* fast case */
3875 goto parse_ident_fast;
3876 } else {
3877 PEEKC(c, p);
3878 if (c == '\'' || c == '\"') {
3879 is_long = 1;
3880 goto str_const;
3881 } else {
3882 cstr_reset(&tokcstr);
3883 cstr_ccat(&tokcstr, 'L');
3884 goto parse_ident_slow;
3887 break;
3888 case '0': case '1': case '2': case '3':
3889 case '4': case '5': case '6': case '7':
3890 case '8': case '9':
3892 cstr_reset(&tokcstr);
3893 /* after the first digit, accept digits, alpha, '.' or sign if
3894 prefixed by 'eEpP' */
3895 parse_num:
3896 for(;;) {
3897 t = c;
3898 cstr_ccat(&tokcstr, c);
3899 PEEKC(c, p);
3900 if (!(isnum(c) || isid(c) || c == '.' ||
3901 ((c == '+' || c == '-') &&
3902 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
3903 break;
3905 /* We add a trailing '\0' to ease parsing */
3906 cstr_ccat(&tokcstr, '\0');
3907 tokc.cstr = &tokcstr;
3908 tok = TOK_PPNUM;
3909 break;
3910 case '.':
3911 /* special dot handling because it can also start a number */
3912 PEEKC(c, p);
3913 if (isnum(c)) {
3914 cstr_reset(&tokcstr);
3915 cstr_ccat(&tokcstr, '.');
3916 goto parse_num;
3917 } else if (c == '.') {
3918 PEEKC(c, p);
3919 if (c != '.')
3920 expect("'.'");
3921 PEEKC(c, p);
3922 tok = TOK_DOTS;
3923 } else {
3924 tok = '.';
3926 break;
3927 case '\'':
3928 case '\"':
3929 is_long = 0;
3930 str_const:
3932 CString str;
3933 int sep;
3935 sep = c;
3937 /* parse the string */
3938 cstr_new(&str);
3939 p = parse_pp_string(p, sep, &str);
3940 cstr_ccat(&str, '\0');
3942 /* eval the escape (should be done as TOK_PPNUM) */
3943 cstr_reset(&tokcstr);
3944 parse_escape_string(&tokcstr, str.data, is_long);
3945 cstr_free(&str);
3947 if (sep == '\'') {
3948 int char_size;
3949 /* XXX: make it portable */
3950 if (!is_long)
3951 char_size = 1;
3952 else
3953 char_size = sizeof(nwchar_t);
3954 if (tokcstr.size <= char_size)
3955 error("empty character constant");
3956 if (tokcstr.size > 2 * char_size)
3957 warning("multi-character character constant");
3958 if (!is_long) {
3959 tokc.i = *(int8_t *)tokcstr.data;
3960 tok = TOK_CCHAR;
3961 } else {
3962 tokc.i = *(nwchar_t *)tokcstr.data;
3963 tok = TOK_LCHAR;
3965 } else {
3966 tokc.cstr = &tokcstr;
3967 if (!is_long)
3968 tok = TOK_STR;
3969 else
3970 tok = TOK_LSTR;
3973 break;
3975 case '<':
3976 PEEKC(c, p);
3977 if (c == '=') {
3978 p++;
3979 tok = TOK_LE;
3980 } else if (c == '<') {
3981 PEEKC(c, p);
3982 if (c == '=') {
3983 p++;
3984 tok = TOK_A_SHL;
3985 } else {
3986 tok = TOK_SHL;
3988 } else {
3989 tok = TOK_LT;
3991 break;
3993 case '>':
3994 PEEKC(c, p);
3995 if (c == '=') {
3996 p++;
3997 tok = TOK_GE;
3998 } else if (c == '>') {
3999 PEEKC(c, p);
4000 if (c == '=') {
4001 p++;
4002 tok = TOK_A_SAR;
4003 } else {
4004 tok = TOK_SAR;
4006 } else {
4007 tok = TOK_GT;
4009 break;
4011 case '&':
4012 PEEKC(c, p);
4013 if (c == '&') {
4014 p++;
4015 tok = TOK_LAND;
4016 } else if (c == '=') {
4017 p++;
4018 tok = TOK_A_AND;
4019 } else {
4020 tok = '&';
4022 break;
4024 case '|':
4025 PEEKC(c, p);
4026 if (c == '|') {
4027 p++;
4028 tok = TOK_LOR;
4029 } else if (c == '=') {
4030 p++;
4031 tok = TOK_A_OR;
4032 } else {
4033 tok = '|';
4035 break;
4037 case '+':
4038 PEEKC(c, p);
4039 if (c == '+') {
4040 p++;
4041 tok = TOK_INC;
4042 } else if (c == '=') {
4043 p++;
4044 tok = TOK_A_ADD;
4045 } else {
4046 tok = '+';
4048 break;
4050 case '-':
4051 PEEKC(c, p);
4052 if (c == '-') {
4053 p++;
4054 tok = TOK_DEC;
4055 } else if (c == '=') {
4056 p++;
4057 tok = TOK_A_SUB;
4058 } else if (c == '>') {
4059 p++;
4060 tok = TOK_ARROW;
4061 } else {
4062 tok = '-';
4064 break;
4066 PARSE2('!', '!', '=', TOK_NE)
4067 PARSE2('=', '=', '=', TOK_EQ)
4068 PARSE2('*', '*', '=', TOK_A_MUL)
4069 PARSE2('%', '%', '=', TOK_A_MOD)
4070 PARSE2('^', '^', '=', TOK_A_XOR)
4072 /* comments or operator */
4073 case '/':
4074 PEEKC(c, p);
4075 if (c == '*') {
4076 p = parse_comment(p);
4077 goto redo_no_start;
4078 } else if (c == '/') {
4079 p = parse_line_comment(p);
4080 goto redo_no_start;
4081 } else if (c == '=') {
4082 p++;
4083 tok = TOK_A_DIV;
4084 } else {
4085 tok = '/';
4087 break;
4089 /* simple tokens */
4090 case '(':
4091 case ')':
4092 case '[':
4093 case ']':
4094 case '{':
4095 case '}':
4096 case ',':
4097 case ';':
4098 case ':':
4099 case '?':
4100 case '~':
4101 case '$': /* only used in assembler */
4102 case '@': /* dito */
4103 tok = c;
4104 p++;
4105 break;
4106 default:
4107 error("unrecognized character \\x%02x", c);
4108 break;
4110 tok_flags = 0;
4111 keep_tok_flags:
4112 file->buf_ptr = p;
4113 #if defined(PARSE_DEBUG)
4114 printf("token = %s\n", get_tok_str(tok, &tokc));
4115 #endif
4118 /* return next token without macro substitution. Can read input from
4119 macro_ptr buffer */
4120 static void next_nomacro(void)
4122 if (macro_ptr) {
4123 redo:
4124 tok = *macro_ptr;
4125 if (tok) {
4126 TOK_GET(tok, macro_ptr, tokc);
4127 if (tok == TOK_LINENUM) {
4128 file->line_num = tokc.i;
4129 goto redo;
4132 } else {
4133 next_nomacro1();
4137 /* substitute args in macro_str and return allocated string */
4138 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
4140 int *st, last_tok, t, notfirst;
4141 Sym *s;
4142 CValue cval;
4143 TokenString str;
4144 CString cstr;
4146 tok_str_new(&str);
4147 last_tok = 0;
4148 while(1) {
4149 TOK_GET(t, macro_str, cval);
4150 if (!t)
4151 break;
4152 if (t == '#') {
4153 /* stringize */
4154 TOK_GET(t, macro_str, cval);
4155 if (!t)
4156 break;
4157 s = sym_find2(args, t);
4158 if (s) {
4159 cstr_new(&cstr);
4160 st = (int *)s->c;
4161 notfirst = 0;
4162 while (*st) {
4163 if (notfirst)
4164 cstr_ccat(&cstr, ' ');
4165 TOK_GET(t, st, cval);
4166 cstr_cat(&cstr, get_tok_str(t, &cval));
4167 #ifndef PP_NOSPACES
4168 notfirst = 1;
4169 #endif
4171 cstr_ccat(&cstr, '\0');
4172 #ifdef PP_DEBUG
4173 printf("stringize: %s\n", (char *)cstr.data);
4174 #endif
4175 /* add string */
4176 cval.cstr = &cstr;
4177 tok_str_add2(&str, TOK_STR, &cval);
4178 cstr_free(&cstr);
4179 } else {
4180 tok_str_add2(&str, t, &cval);
4182 } else if (t >= TOK_IDENT) {
4183 s = sym_find2(args, t);
4184 if (s) {
4185 st = (int *)s->c;
4186 /* if '##' is present before or after, no arg substitution */
4187 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
4188 /* special case for var arg macros : ## eats the
4189 ',' if empty VA_ARGS variable. */
4190 /* XXX: test of the ',' is not 100%
4191 reliable. should fix it to avoid security
4192 problems */
4193 if (gnu_ext && s->type.t &&
4194 last_tok == TOK_TWOSHARPS &&
4195 str.len >= 2 && str.str[str.len - 2] == ',') {
4196 if (*st == 0) {
4197 /* suppress ',' '##' */
4198 str.len -= 2;
4199 } else {
4200 /* suppress '##' and add variable */
4201 str.len--;
4202 goto add_var;
4204 } else {
4205 int t1;
4206 add_var:
4207 for(;;) {
4208 TOK_GET(t1, st, cval);
4209 if (!t1)
4210 break;
4211 tok_str_add2(&str, t1, &cval);
4214 } else {
4215 /* NOTE: the stream cannot be read when macro
4216 substituing an argument */
4217 macro_subst(&str, nested_list, st, NULL);
4219 } else {
4220 tok_str_add(&str, t);
4222 } else {
4223 tok_str_add2(&str, t, &cval);
4225 last_tok = t;
4227 tok_str_add(&str, 0);
4228 return str.str;
4231 static char const ab_month_name[12][4] =
4233 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4234 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4237 /* do macro substitution of current token with macro 's' and add
4238 result to (tok_str,tok_len). 'nested_list' is the list of all
4239 macros we got inside to avoid recursing. Return non zero if no
4240 substitution needs to be done */
4241 static int macro_subst_tok(TokenString *tok_str,
4242 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
4244 Sym *args, *sa, *sa1;
4245 int mstr_allocated, parlevel, *mstr, t, t1;
4246 TokenString str;
4247 char *cstrval;
4248 CValue cval;
4249 CString cstr;
4250 char buf[32];
4252 /* if symbol is a macro, prepare substitution */
4253 /* special macros */
4254 if (tok == TOK___LINE__) {
4255 snprintf(buf, sizeof(buf), "%d", file->line_num);
4256 cstrval = buf;
4257 t1 = TOK_PPNUM;
4258 goto add_cstr1;
4259 } else if (tok == TOK___FILE__) {
4260 cstrval = file->filename;
4261 goto add_cstr;
4262 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
4263 time_t ti;
4264 struct tm *tm;
4266 time(&ti);
4267 tm = localtime(&ti);
4268 if (tok == TOK___DATE__) {
4269 snprintf(buf, sizeof(buf), "%s %2d %d",
4270 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
4271 } else {
4272 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
4273 tm->tm_hour, tm->tm_min, tm->tm_sec);
4275 cstrval = buf;
4276 add_cstr:
4277 t1 = TOK_STR;
4278 add_cstr1:
4279 cstr_new(&cstr);
4280 cstr_cat(&cstr, cstrval);
4281 cstr_ccat(&cstr, '\0');
4282 cval.cstr = &cstr;
4283 tok_str_add2(tok_str, t1, &cval);
4284 cstr_free(&cstr);
4285 } else {
4286 mstr = (int *)s->c;
4287 mstr_allocated = 0;
4288 if (s->type.t == MACRO_FUNC) {
4289 /* NOTE: we do not use next_nomacro to avoid eating the
4290 next token. XXX: find better solution */
4291 redo:
4292 if (macro_ptr) {
4293 t = *macro_ptr;
4294 if (t == 0 && can_read_stream) {
4295 /* end of macro stream: we must look at the token
4296 after in the file */
4297 struct macro_level *ml = *can_read_stream;
4298 macro_ptr = NULL;
4299 if (ml)
4301 macro_ptr = ml->p;
4302 ml->p = NULL;
4303 *can_read_stream = ml -> prev;
4305 goto redo;
4307 } else {
4308 /* XXX: incorrect with comments */
4309 ch = file->buf_ptr[0];
4310 while (is_space(ch) || ch == '\n')
4311 cinp();
4312 t = ch;
4314 if (t != '(') /* no macro subst */
4315 return -1;
4317 /* argument macro */
4318 next_nomacro();
4319 next_nomacro();
4320 args = NULL;
4321 sa = s->next;
4322 /* NOTE: empty args are allowed, except if no args */
4323 for(;;) {
4324 /* handle '()' case */
4325 if (!args && !sa && tok == ')')
4326 break;
4327 if (!sa)
4328 error("macro '%s' used with too many args",
4329 get_tok_str(s->v, 0));
4330 tok_str_new(&str);
4331 parlevel = 0;
4332 /* NOTE: non zero sa->t indicates VA_ARGS */
4333 while ((parlevel > 0 ||
4334 (tok != ')' &&
4335 (tok != ',' || sa->type.t))) &&
4336 tok != -1) {
4337 if (tok == '(')
4338 parlevel++;
4339 else if (tok == ')')
4340 parlevel--;
4341 if (tok != TOK_LINEFEED)
4342 tok_str_add2(&str, tok, &tokc);
4343 next_nomacro();
4345 tok_str_add(&str, 0);
4346 sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, (long)str.str);
4347 sa = sa->next;
4348 if (tok == ')') {
4349 /* special case for gcc var args: add an empty
4350 var arg argument if it is omitted */
4351 if (sa && sa->type.t && gnu_ext)
4352 continue;
4353 else
4354 break;
4356 if (tok != ',')
4357 expect(",");
4358 next_nomacro();
4360 if (sa) {
4361 error("macro '%s' used with too few args",
4362 get_tok_str(s->v, 0));
4365 /* now subst each arg */
4366 mstr = macro_arg_subst(nested_list, mstr, args);
4367 /* free memory */
4368 sa = args;
4369 while (sa) {
4370 sa1 = sa->prev;
4371 tok_str_free((int *)sa->c);
4372 sym_free(sa);
4373 sa = sa1;
4375 mstr_allocated = 1;
4377 sym_push2(nested_list, s->v, 0, 0);
4378 macro_subst(tok_str, nested_list, mstr, can_read_stream);
4379 /* pop nested defined symbol */
4380 sa1 = *nested_list;
4381 *nested_list = sa1->prev;
4382 sym_free(sa1);
4383 if (mstr_allocated)
4384 tok_str_free(mstr);
4386 return 0;
4389 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4390 return the resulting string (which must be freed). */
4391 static inline int *macro_twosharps(const int *macro_str)
4393 TokenSym *ts;
4394 const int *macro_ptr1, *start_macro_ptr, *ptr, *saved_macro_ptr;
4395 int t;
4396 const char *p1, *p2;
4397 CValue cval;
4398 TokenString macro_str1;
4399 CString cstr;
4401 start_macro_ptr = macro_str;
4402 /* we search the first '##' */
4403 for(;;) {
4404 macro_ptr1 = macro_str;
4405 TOK_GET(t, macro_str, cval);
4406 /* nothing more to do if end of string */
4407 if (t == 0)
4408 return NULL;
4409 if (*macro_str == TOK_TWOSHARPS)
4410 break;
4413 /* we saw '##', so we need more processing to handle it */
4414 cstr_new(&cstr);
4415 tok_str_new(&macro_str1);
4416 tok = t;
4417 tokc = cval;
4419 /* add all tokens seen so far */
4420 for(ptr = start_macro_ptr; ptr < macro_ptr1;) {
4421 TOK_GET(t, ptr, cval);
4422 tok_str_add2(&macro_str1, t, &cval);
4424 saved_macro_ptr = macro_ptr;
4425 /* XXX: get rid of the use of macro_ptr here */
4426 macro_ptr = (int *)macro_str;
4427 for(;;) {
4428 while (*macro_ptr == TOK_TWOSHARPS) {
4429 macro_ptr++;
4430 macro_ptr1 = macro_ptr;
4431 t = *macro_ptr;
4432 if (t) {
4433 TOK_GET(t, macro_ptr, cval);
4434 /* We concatenate the two tokens if we have an
4435 identifier or a preprocessing number */
4436 cstr_reset(&cstr);
4437 p1 = get_tok_str(tok, &tokc);
4438 cstr_cat(&cstr, p1);
4439 p2 = get_tok_str(t, &cval);
4440 cstr_cat(&cstr, p2);
4441 cstr_ccat(&cstr, '\0');
4443 if ((tok >= TOK_IDENT || tok == TOK_PPNUM) &&
4444 (t >= TOK_IDENT || t == TOK_PPNUM)) {
4445 if (tok == TOK_PPNUM) {
4446 /* if number, then create a number token */
4447 /* NOTE: no need to allocate because
4448 tok_str_add2() does it */
4449 cstr_reset(&tokcstr);
4450 tokcstr = cstr;
4451 cstr_new(&cstr);
4452 tokc.cstr = &tokcstr;
4453 } else {
4454 /* if identifier, we must do a test to
4455 validate we have a correct identifier */
4456 if (t == TOK_PPNUM) {
4457 const char *p;
4458 int c;
4460 p = p2;
4461 for(;;) {
4462 c = *p;
4463 if (c == '\0')
4464 break;
4465 p++;
4466 if (!isnum(c) && !isid(c))
4467 goto error_pasting;
4470 ts = tok_alloc(cstr.data, strlen(cstr.data));
4471 tok = ts->tok; /* modify current token */
4473 } else {
4474 const char *str = cstr.data;
4475 const unsigned char *q;
4477 /* we look for a valid token */
4478 /* XXX: do more extensive checks */
4479 if (!strcmp(str, ">>=")) {
4480 tok = TOK_A_SAR;
4481 } else if (!strcmp(str, "<<=")) {
4482 tok = TOK_A_SHL;
4483 } else if (strlen(str) == 2) {
4484 /* search in two bytes table */
4485 q = tok_two_chars;
4486 for(;;) {
4487 if (!*q)
4488 goto error_pasting;
4489 if (q[0] == str[0] && q[1] == str[1])
4490 break;
4491 q += 3;
4493 tok = q[2];
4494 } else {
4495 error_pasting:
4496 /* NOTE: because get_tok_str use a static buffer,
4497 we must save it */
4498 cstr_reset(&cstr);
4499 p1 = get_tok_str(tok, &tokc);
4500 cstr_cat(&cstr, p1);
4501 cstr_ccat(&cstr, '\0');
4502 p2 = get_tok_str(t, &cval);
4503 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
4504 /* cannot merge tokens: just add them separately */
4505 tok_str_add2(&macro_str1, tok, &tokc);
4506 /* XXX: free associated memory ? */
4507 tok = t;
4508 tokc = cval;
4513 tok_str_add2(&macro_str1, tok, &tokc);
4514 next_nomacro();
4515 if (tok == 0)
4516 break;
4518 macro_ptr = (int *)saved_macro_ptr;
4519 cstr_free(&cstr);
4520 tok_str_add(&macro_str1, 0);
4521 return macro_str1.str;
4525 /* do macro substitution of macro_str and add result to
4526 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4527 inside to avoid recursing. */
4528 static void macro_subst(TokenString *tok_str, Sym **nested_list,
4529 const int *macro_str, struct macro_level ** can_read_stream)
4531 Sym *s;
4532 int *macro_str1;
4533 const int *ptr;
4534 int t, ret;
4535 CValue cval;
4536 struct macro_level ml;
4538 /* first scan for '##' operator handling */
4539 ptr = macro_str;
4540 macro_str1 = macro_twosharps(ptr);
4541 if (macro_str1)
4542 ptr = macro_str1;
4543 while (1) {
4544 /* NOTE: ptr == NULL can only happen if tokens are read from
4545 file stream due to a macro function call */
4546 if (ptr == NULL)
4547 break;
4548 TOK_GET(t, ptr, cval);
4549 if (t == 0)
4550 break;
4551 s = define_find(t);
4552 if (s != NULL) {
4553 /* if nested substitution, do nothing */
4554 if (sym_find2(*nested_list, t))
4555 goto no_subst;
4556 ml.p = macro_ptr;
4557 if (can_read_stream)
4558 ml.prev = *can_read_stream, *can_read_stream = &ml;
4559 macro_ptr = (int *)ptr;
4560 tok = t;
4561 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
4562 ptr = (int *)macro_ptr;
4563 macro_ptr = ml.p;
4564 if (can_read_stream && *can_read_stream == &ml)
4565 *can_read_stream = ml.prev;
4566 if (ret != 0)
4567 goto no_subst;
4568 } else {
4569 no_subst:
4570 tok_str_add2(tok_str, t, &cval);
4573 if (macro_str1)
4574 tok_str_free(macro_str1);
4577 /* return next token with macro substitution */
4578 static void next(void)
4580 Sym *nested_list, *s;
4581 TokenString str;
4582 struct macro_level *ml;
4584 redo:
4585 next_nomacro();
4586 if (!macro_ptr) {
4587 /* if not reading from macro substituted string, then try
4588 to substitute macros */
4589 if (tok >= TOK_IDENT &&
4590 (parse_flags & PARSE_FLAG_PREPROCESS)) {
4591 s = define_find(tok);
4592 if (s) {
4593 /* we have a macro: we try to substitute */
4594 tok_str_new(&str);
4595 nested_list = NULL;
4596 ml = NULL;
4597 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
4598 /* substitution done, NOTE: maybe empty */
4599 tok_str_add(&str, 0);
4600 macro_ptr = str.str;
4601 macro_ptr_allocated = str.str;
4602 goto redo;
4606 } else {
4607 if (tok == 0) {
4608 /* end of macro or end of unget buffer */
4609 if (unget_buffer_enabled) {
4610 macro_ptr = unget_saved_macro_ptr;
4611 unget_buffer_enabled = 0;
4612 } else {
4613 /* end of macro string: free it */
4614 tok_str_free(macro_ptr_allocated);
4615 macro_ptr = NULL;
4617 goto redo;
4621 /* convert preprocessor tokens into C tokens */
4622 if (tok == TOK_PPNUM &&
4623 (parse_flags & PARSE_FLAG_TOK_NUM)) {
4624 parse_number((char *)tokc.cstr->data);
4628 /* push back current token and set current token to 'last_tok'. Only
4629 identifier case handled for labels. */
4630 static inline void unget_tok(int last_tok)
4632 int i, n;
4633 int *q;
4634 unget_saved_macro_ptr = macro_ptr;
4635 unget_buffer_enabled = 1;
4636 q = unget_saved_buffer;
4637 macro_ptr = q;
4638 *q++ = tok;
4639 n = tok_ext_size(tok) - 1;
4640 for(i=0;i<n;i++)
4641 *q++ = tokc.tab[i];
4642 *q = 0; /* end of token string */
4643 tok = last_tok;
4647 void swap(int *p, int *q)
4649 int t;
4650 t = *p;
4651 *p = *q;
4652 *q = t;
4655 void vsetc(CType *type, int r, CValue *vc)
4657 int v;
4659 if (vtop >= vstack + (VSTACK_SIZE - 1))
4660 error("memory full");
4661 /* cannot let cpu flags if other instruction are generated. Also
4662 avoid leaving VT_JMP anywhere except on the top of the stack
4663 because it would complicate the code generator. */
4664 if (vtop >= vstack) {
4665 v = vtop->r & VT_VALMASK;
4666 if (v == VT_CMP || (v & ~1) == VT_JMP)
4667 gv(RC_INT);
4669 vtop++;
4670 vtop->type = *type;
4671 vtop->r = r;
4672 vtop->r2 = VT_CONST;
4673 vtop->c = *vc;
4676 /* push integer constant */
4677 void vpushi(int v)
4679 CValue cval;
4680 cval.i = v;
4681 vsetc(&int_type, VT_CONST, &cval);
4684 /* push long long constant */
4685 void vpushll(long long v)
4687 CValue cval;
4688 CType ctype;
4689 ctype.t = VT_LLONG;
4690 cval.ull = v;
4691 vsetc(&ctype, VT_CONST, &cval);
4694 /* Return a static symbol pointing to a section */
4695 static Sym *get_sym_ref(CType *type, Section *sec,
4696 unsigned long offset, unsigned long size)
4698 int v;
4699 Sym *sym;
4701 v = anon_sym++;
4702 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
4703 sym->type.ref = type->ref;
4704 sym->r = VT_CONST | VT_SYM;
4705 put_extern_sym(sym, sec, offset, size);
4706 return sym;
4709 /* push a reference to a section offset by adding a dummy symbol */
4710 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
4712 CValue cval;
4714 cval.ul = 0;
4715 vsetc(type, VT_CONST | VT_SYM, &cval);
4716 vtop->sym = get_sym_ref(type, sec, offset, size);
4719 /* define a new external reference to a symbol 'v' of type 'u' */
4720 static Sym *external_global_sym(int v, CType *type, int r)
4722 Sym *s;
4724 s = sym_find(v);
4725 if (!s) {
4726 /* push forward reference */
4727 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
4728 s->type.ref = type->ref;
4729 s->r = r | VT_CONST | VT_SYM;
4731 return s;
4734 /* define a new external reference to a symbol 'v' of type 'u' */
4735 static Sym *external_sym(int v, CType *type, int r)
4737 Sym *s;
4739 s = sym_find(v);
4740 if (!s) {
4741 /* push forward reference */
4742 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
4743 s->type.t |= VT_EXTERN;
4744 } else {
4745 if (!is_compatible_types(&s->type, type))
4746 error("incompatible types for redefinition of '%s'",
4747 get_tok_str(v, NULL));
4749 return s;
4752 /* push a reference to global symbol v */
4753 static void vpush_global_sym(CType *type, int v)
4755 Sym *sym;
4756 CValue cval;
4758 sym = external_global_sym(v, type, 0);
4759 cval.ul = 0;
4760 vsetc(type, VT_CONST | VT_SYM, &cval);
4761 vtop->sym = sym;
4764 void vset(CType *type, int r, int v)
4766 CValue cval;
4768 cval.i = v;
4769 vsetc(type, r, &cval);
4772 void vseti(int r, int v)
4774 CType type;
4775 type.t = VT_INT;
4776 vset(&type, r, v);
4779 void vswap(void)
4781 SValue tmp;
4783 tmp = vtop[0];
4784 vtop[0] = vtop[-1];
4785 vtop[-1] = tmp;
4788 void vpushv(SValue *v)
4790 if (vtop >= vstack + (VSTACK_SIZE - 1))
4791 error("memory full");
4792 vtop++;
4793 *vtop = *v;
4796 void vdup(void)
4798 vpushv(vtop);
4801 /* save r to the memory stack, and mark it as being free */
4802 void save_reg(int r)
4804 int l, saved, size, align;
4805 SValue *p, sv;
4806 CType *type;
4808 /* modify all stack values */
4809 saved = 0;
4810 l = 0;
4811 for(p=vstack;p<=vtop;p++) {
4812 if ((p->r & VT_VALMASK) == r ||
4813 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
4814 /* must save value on stack if not already done */
4815 if (!saved) {
4816 /* NOTE: must reload 'r' because r might be equal to r2 */
4817 r = p->r & VT_VALMASK;
4818 /* store register in the stack */
4819 type = &p->type;
4820 if ((p->r & VT_LVAL) ||
4821 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
4822 #ifdef TCC_TARGET_X86_64
4823 type = &char_pointer_type;
4824 #else
4825 type = &int_type;
4826 #endif
4827 size = type_size(type, &align);
4828 loc = (loc - size) & -align;
4829 sv.type.t = type->t;
4830 sv.r = VT_LOCAL | VT_LVAL;
4831 sv.c.ul = loc;
4832 store(r, &sv);
4833 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4834 /* x86 specific: need to pop fp register ST0 if saved */
4835 if (r == TREG_ST0) {
4836 o(0xd9dd); /* fstp %st(1) */
4838 #endif
4839 #ifndef TCC_TARGET_X86_64
4840 /* special long long case */
4841 if ((type->t & VT_BTYPE) == VT_LLONG) {
4842 sv.c.ul += 4;
4843 store(p->r2, &sv);
4845 #endif
4846 l = loc;
4847 saved = 1;
4849 /* mark that stack entry as being saved on the stack */
4850 if (p->r & VT_LVAL) {
4851 /* also clear the bounded flag because the
4852 relocation address of the function was stored in
4853 p->c.ul */
4854 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
4855 } else {
4856 p->r = lvalue_type(p->type.t) | VT_LOCAL;
4858 p->r2 = VT_CONST;
4859 p->c.ul = l;
4864 /* find a register of class 'rc2' with at most one reference on stack.
4865 * If none, call get_reg(rc) */
4866 int get_reg_ex(int rc, int rc2)
4868 int r;
4869 SValue *p;
4871 for(r=0;r<NB_REGS;r++) {
4872 if (reg_classes[r] & rc2) {
4873 int n;
4874 n=0;
4875 for(p = vstack; p <= vtop; p++) {
4876 if ((p->r & VT_VALMASK) == r ||
4877 (p->r2 & VT_VALMASK) == r)
4878 n++;
4880 if (n <= 1)
4881 return r;
4884 return get_reg(rc);
4887 /* find a free register of class 'rc'. If none, save one register */
4888 int get_reg(int rc)
4890 int r;
4891 SValue *p;
4893 /* find a free register */
4894 for(r=0;r<NB_REGS;r++) {
4895 if (reg_classes[r] & rc) {
4896 for(p=vstack;p<=vtop;p++) {
4897 if ((p->r & VT_VALMASK) == r ||
4898 (p->r2 & VT_VALMASK) == r)
4899 goto notfound;
4901 return r;
4903 notfound: ;
4906 /* no register left : free the first one on the stack (VERY
4907 IMPORTANT to start from the bottom to ensure that we don't
4908 spill registers used in gen_opi()) */
4909 for(p=vstack;p<=vtop;p++) {
4910 r = p->r & VT_VALMASK;
4911 if (r < VT_CONST && (reg_classes[r] & rc))
4912 goto save_found;
4913 /* also look at second register (if long long) */
4914 r = p->r2 & VT_VALMASK;
4915 if (r < VT_CONST && (reg_classes[r] & rc)) {
4916 save_found:
4917 save_reg(r);
4918 return r;
4921 /* Should never comes here */
4922 return -1;
4925 /* save registers up to (vtop - n) stack entry */
4926 void save_regs(int n)
4928 int r;
4929 SValue *p, *p1;
4930 p1 = vtop - n;
4931 for(p = vstack;p <= p1; p++) {
4932 r = p->r & VT_VALMASK;
4933 if (r < VT_CONST) {
4934 save_reg(r);
4939 /* move register 's' to 'r', and flush previous value of r to memory
4940 if needed */
4941 void move_reg(int r, int s)
4943 SValue sv;
4945 if (r != s) {
4946 save_reg(r);
4947 sv.type.t = VT_INT;
4948 sv.r = s;
4949 sv.c.ul = 0;
4950 load(r, &sv);
4954 /* get address of vtop (vtop MUST BE an lvalue) */
4955 void gaddrof(void)
4957 vtop->r &= ~VT_LVAL;
4958 /* tricky: if saved lvalue, then we can go back to lvalue */
4959 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
4960 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
4963 #ifdef CONFIG_TCC_BCHECK
4964 /* generate lvalue bound code */
4965 void gbound(void)
4967 int lval_type;
4968 CType type1;
4970 vtop->r &= ~VT_MUSTBOUND;
4971 /* if lvalue, then use checking code before dereferencing */
4972 if (vtop->r & VT_LVAL) {
4973 /* if not VT_BOUNDED value, then make one */
4974 if (!(vtop->r & VT_BOUNDED)) {
4975 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
4976 /* must save type because we must set it to int to get pointer */
4977 type1 = vtop->type;
4978 vtop->type.t = VT_INT;
4979 gaddrof();
4980 vpushi(0);
4981 gen_bounded_ptr_add();
4982 vtop->r |= lval_type;
4983 vtop->type = type1;
4985 /* then check for dereferencing */
4986 gen_bounded_ptr_deref();
4989 #endif
4991 /* store vtop a register belonging to class 'rc'. lvalues are
4992 converted to values. Cannot be used if cannot be converted to
4993 register value (such as structures). */
4994 int gv(int rc)
4996 int r, rc2, bit_pos, bit_size, size, align, i;
4998 /* NOTE: get_reg can modify vstack[] */
4999 if (vtop->type.t & VT_BITFIELD) {
5000 CType type;
5001 int bits = 32;
5002 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5003 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5004 /* remove bit field info to avoid loops */
5005 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
5006 /* cast to int to propagate signedness in following ops */
5007 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5008 type.t = VT_LLONG;
5009 bits = 64;
5010 } else
5011 type.t = VT_INT;
5012 if((vtop->type.t & VT_UNSIGNED) ||
5013 (vtop->type.t & VT_BTYPE) == VT_BOOL)
5014 type.t |= VT_UNSIGNED;
5015 gen_cast(&type);
5016 /* generate shifts */
5017 vpushi(bits - (bit_pos + bit_size));
5018 gen_op(TOK_SHL);
5019 vpushi(bits - bit_size);
5020 /* NOTE: transformed to SHR if unsigned */
5021 gen_op(TOK_SAR);
5022 r = gv(rc);
5023 } else {
5024 if (is_float(vtop->type.t) &&
5025 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5026 Sym *sym;
5027 int *ptr;
5028 unsigned long offset;
5029 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5030 CValue check;
5031 #endif
5033 /* XXX: unify with initializers handling ? */
5034 /* CPUs usually cannot use float constants, so we store them
5035 generically in data segment */
5036 size = type_size(&vtop->type, &align);
5037 offset = (data_section->data_offset + align - 1) & -align;
5038 data_section->data_offset = offset;
5039 /* XXX: not portable yet */
5040 #if defined(__i386__) || defined(__x86_64__)
5041 /* Zero pad x87 tenbyte long doubles */
5042 if (size == LDOUBLE_SIZE)
5043 vtop->c.tab[2] &= 0xffff;
5044 #endif
5045 ptr = section_ptr_add(data_section, size);
5046 size = size >> 2;
5047 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5048 check.d = 1;
5049 if(check.tab[0])
5050 for(i=0;i<size;i++)
5051 ptr[i] = vtop->c.tab[size-1-i];
5052 else
5053 #endif
5054 for(i=0;i<size;i++)
5055 ptr[i] = vtop->c.tab[i];
5056 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
5057 vtop->r |= VT_LVAL | VT_SYM;
5058 vtop->sym = sym;
5059 vtop->c.ul = 0;
5061 #ifdef CONFIG_TCC_BCHECK
5062 if (vtop->r & VT_MUSTBOUND)
5063 gbound();
5064 #endif
5066 r = vtop->r & VT_VALMASK;
5067 rc2 = RC_INT;
5068 if (rc == RC_IRET)
5069 rc2 = RC_LRET;
5070 /* need to reload if:
5071 - constant
5072 - lvalue (need to dereference pointer)
5073 - already a register, but not in the right class */
5074 if (r >= VT_CONST ||
5075 (vtop->r & VT_LVAL) ||
5076 !(reg_classes[r] & rc) ||
5077 ((vtop->type.t & VT_BTYPE) == VT_LLONG &&
5078 !(reg_classes[vtop->r2] & rc2))) {
5079 r = get_reg(rc);
5080 #ifndef TCC_TARGET_X86_64
5081 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5082 int r2;
5083 unsigned long long ll;
5084 /* two register type load : expand to two words
5085 temporarily */
5086 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5087 /* load constant */
5088 ll = vtop->c.ull;
5089 vtop->c.ui = ll; /* first word */
5090 load(r, vtop);
5091 vtop->r = r; /* save register value */
5092 vpushi(ll >> 32); /* second word */
5093 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
5094 (vtop->r & VT_LVAL)) {
5095 /* We do not want to modifier the long long
5096 pointer here, so the safest (and less
5097 efficient) is to save all the other registers
5098 in the stack. XXX: totally inefficient. */
5099 save_regs(1);
5100 /* load from memory */
5101 load(r, vtop);
5102 vdup();
5103 vtop[-1].r = r; /* save register value */
5104 /* increment pointer to get second word */
5105 vtop->type.t = VT_INT;
5106 gaddrof();
5107 vpushi(4);
5108 gen_op('+');
5109 vtop->r |= VT_LVAL;
5110 } else {
5111 /* move registers */
5112 load(r, vtop);
5113 vdup();
5114 vtop[-1].r = r; /* save register value */
5115 vtop->r = vtop[-1].r2;
5117 /* allocate second register */
5118 r2 = get_reg(rc2);
5119 load(r2, vtop);
5120 vpop();
5121 /* write second register */
5122 vtop->r2 = r2;
5123 } else
5124 #endif
5125 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
5126 int t1, t;
5127 /* lvalue of scalar type : need to use lvalue type
5128 because of possible cast */
5129 t = vtop->type.t;
5130 t1 = t;
5131 /* compute memory access type */
5132 if (vtop->r & VT_LVAL_BYTE)
5133 t = VT_BYTE;
5134 else if (vtop->r & VT_LVAL_SHORT)
5135 t = VT_SHORT;
5136 if (vtop->r & VT_LVAL_UNSIGNED)
5137 t |= VT_UNSIGNED;
5138 vtop->type.t = t;
5139 load(r, vtop);
5140 /* restore wanted type */
5141 vtop->type.t = t1;
5142 } else {
5143 /* one register type load */
5144 load(r, vtop);
5147 vtop->r = r;
5148 #ifdef TCC_TARGET_C67
5149 /* uses register pairs for doubles */
5150 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
5151 vtop->r2 = r+1;
5152 #endif
5154 return r;
5157 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5158 void gv2(int rc1, int rc2)
5160 int v;
5162 /* generate more generic register first. But VT_JMP or VT_CMP
5163 values must be generated first in all cases to avoid possible
5164 reload errors */
5165 v = vtop[0].r & VT_VALMASK;
5166 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
5167 vswap();
5168 gv(rc1);
5169 vswap();
5170 gv(rc2);
5171 /* test if reload is needed for first register */
5172 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
5173 vswap();
5174 gv(rc1);
5175 vswap();
5177 } else {
5178 gv(rc2);
5179 vswap();
5180 gv(rc1);
5181 vswap();
5182 /* test if reload is needed for first register */
5183 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
5184 gv(rc2);
5189 /* wrapper around RC_FRET to return a register by type */
5190 int rc_fret(int t)
5192 #ifdef TCC_TARGET_X86_64
5193 if (t == VT_LDOUBLE) {
5194 return RC_ST0;
5196 #endif
5197 return RC_FRET;
5200 /* wrapper around REG_FRET to return a register by type */
5201 int reg_fret(int t)
5203 #ifdef TCC_TARGET_X86_64
5204 if (t == VT_LDOUBLE) {
5205 return TREG_ST0;
5207 #endif
5208 return REG_FRET;
5211 /* expand long long on stack in two int registers */
5212 void lexpand(void)
5214 int u;
5216 u = vtop->type.t & VT_UNSIGNED;
5217 gv(RC_INT);
5218 vdup();
5219 vtop[0].r = vtop[-1].r2;
5220 vtop[0].r2 = VT_CONST;
5221 vtop[-1].r2 = VT_CONST;
5222 vtop[0].type.t = VT_INT | u;
5223 vtop[-1].type.t = VT_INT | u;
5226 #ifdef TCC_TARGET_ARM
5227 /* expand long long on stack */
5228 void lexpand_nr(void)
5230 int u,v;
5232 u = vtop->type.t & VT_UNSIGNED;
5233 vdup();
5234 vtop->r2 = VT_CONST;
5235 vtop->type.t = VT_INT | u;
5236 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
5237 if (v == VT_CONST) {
5238 vtop[-1].c.ui = vtop->c.ull;
5239 vtop->c.ui = vtop->c.ull >> 32;
5240 vtop->r = VT_CONST;
5241 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
5242 vtop->c.ui += 4;
5243 vtop->r = vtop[-1].r;
5244 } else if (v > VT_CONST) {
5245 vtop--;
5246 lexpand();
5247 } else
5248 vtop->r = vtop[-1].r2;
5249 vtop[-1].r2 = VT_CONST;
5250 vtop[-1].type.t = VT_INT | u;
5252 #endif
5254 /* build a long long from two ints */
5255 void lbuild(int t)
5257 gv2(RC_INT, RC_INT);
5258 vtop[-1].r2 = vtop[0].r;
5259 vtop[-1].type.t = t;
5260 vpop();
5263 /* rotate n first stack elements to the bottom
5264 I1 ... In -> I2 ... In I1 [top is right]
5266 void vrotb(int n)
5268 int i;
5269 SValue tmp;
5271 tmp = vtop[-n + 1];
5272 for(i=-n+1;i!=0;i++)
5273 vtop[i] = vtop[i+1];
5274 vtop[0] = tmp;
5277 /* rotate n first stack elements to the top
5278 I1 ... In -> In I1 ... I(n-1) [top is right]
5280 void vrott(int n)
5282 int i;
5283 SValue tmp;
5285 tmp = vtop[0];
5286 for(i = 0;i < n - 1; i++)
5287 vtop[-i] = vtop[-i - 1];
5288 vtop[-n + 1] = tmp;
5291 #ifdef TCC_TARGET_ARM
5292 /* like vrott but in other direction
5293 In ... I1 -> I(n-1) ... I1 In [top is right]
5295 void vnrott(int n)
5297 int i;
5298 SValue tmp;
5300 tmp = vtop[-n + 1];
5301 for(i = n - 1; i > 0; i--)
5302 vtop[-i] = vtop[-i + 1];
5303 vtop[0] = tmp;
5305 #endif
5307 /* pop stack value */
5308 void vpop(void)
5310 int v;
5311 v = vtop->r & VT_VALMASK;
5312 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5313 /* for x86, we need to pop the FP stack */
5314 if (v == TREG_ST0 && !nocode_wanted) {
5315 o(0xd9dd); /* fstp %st(1) */
5316 } else
5317 #endif
5318 if (v == VT_JMP || v == VT_JMPI) {
5319 /* need to put correct jump if && or || without test */
5320 gsym(vtop->c.ul);
5322 vtop--;
5325 /* convert stack entry to register and duplicate its value in another
5326 register */
5327 void gv_dup(void)
5329 int rc, t, r, r1;
5330 SValue sv;
5332 t = vtop->type.t;
5333 if ((t & VT_BTYPE) == VT_LLONG) {
5334 lexpand();
5335 gv_dup();
5336 vswap();
5337 vrotb(3);
5338 gv_dup();
5339 vrotb(4);
5340 /* stack: H L L1 H1 */
5341 lbuild(t);
5342 vrotb(3);
5343 vrotb(3);
5344 vswap();
5345 lbuild(t);
5346 vswap();
5347 } else {
5348 /* duplicate value */
5349 rc = RC_INT;
5350 sv.type.t = VT_INT;
5351 if (is_float(t)) {
5352 rc = RC_FLOAT;
5353 #ifdef TCC_TARGET_X86_64
5354 if ((t & VT_BTYPE) == VT_LDOUBLE) {
5355 rc = RC_ST0;
5357 #endif
5358 sv.type.t = t;
5360 r = gv(rc);
5361 r1 = get_reg(rc);
5362 sv.r = r;
5363 sv.c.ul = 0;
5364 load(r1, &sv); /* move r to r1 */
5365 vdup();
5366 /* duplicates value */
5367 vtop->r = r1;
5371 #ifndef TCC_TARGET_X86_64
5372 /* generate CPU independent (unsigned) long long operations */
5373 void gen_opl(int op)
5375 int t, a, b, op1, c, i;
5376 int func;
5377 unsigned short reg_iret = REG_IRET;
5378 unsigned short reg_lret = REG_LRET;
5379 SValue tmp;
5381 switch(op) {
5382 case '/':
5383 case TOK_PDIV:
5384 func = TOK___divdi3;
5385 goto gen_func;
5386 case TOK_UDIV:
5387 func = TOK___udivdi3;
5388 goto gen_func;
5389 case '%':
5390 func = TOK___moddi3;
5391 goto gen_mod_func;
5392 case TOK_UMOD:
5393 func = TOK___umoddi3;
5394 gen_mod_func:
5395 #ifdef TCC_ARM_EABI
5396 reg_iret = TREG_R2;
5397 reg_lret = TREG_R3;
5398 #endif
5399 gen_func:
5400 /* call generic long long function */
5401 vpush_global_sym(&func_old_type, func);
5402 vrott(3);
5403 gfunc_call(2);
5404 vpushi(0);
5405 vtop->r = reg_iret;
5406 vtop->r2 = reg_lret;
5407 break;
5408 case '^':
5409 case '&':
5410 case '|':
5411 case '*':
5412 case '+':
5413 case '-':
5414 t = vtop->type.t;
5415 vswap();
5416 lexpand();
5417 vrotb(3);
5418 lexpand();
5419 /* stack: L1 H1 L2 H2 */
5420 tmp = vtop[0];
5421 vtop[0] = vtop[-3];
5422 vtop[-3] = tmp;
5423 tmp = vtop[-2];
5424 vtop[-2] = vtop[-3];
5425 vtop[-3] = tmp;
5426 vswap();
5427 /* stack: H1 H2 L1 L2 */
5428 if (op == '*') {
5429 vpushv(vtop - 1);
5430 vpushv(vtop - 1);
5431 gen_op(TOK_UMULL);
5432 lexpand();
5433 /* stack: H1 H2 L1 L2 ML MH */
5434 for(i=0;i<4;i++)
5435 vrotb(6);
5436 /* stack: ML MH H1 H2 L1 L2 */
5437 tmp = vtop[0];
5438 vtop[0] = vtop[-2];
5439 vtop[-2] = tmp;
5440 /* stack: ML MH H1 L2 H2 L1 */
5441 gen_op('*');
5442 vrotb(3);
5443 vrotb(3);
5444 gen_op('*');
5445 /* stack: ML MH M1 M2 */
5446 gen_op('+');
5447 gen_op('+');
5448 } else if (op == '+' || op == '-') {
5449 /* XXX: add non carry method too (for MIPS or alpha) */
5450 if (op == '+')
5451 op1 = TOK_ADDC1;
5452 else
5453 op1 = TOK_SUBC1;
5454 gen_op(op1);
5455 /* stack: H1 H2 (L1 op L2) */
5456 vrotb(3);
5457 vrotb(3);
5458 gen_op(op1 + 1); /* TOK_xxxC2 */
5459 } else {
5460 gen_op(op);
5461 /* stack: H1 H2 (L1 op L2) */
5462 vrotb(3);
5463 vrotb(3);
5464 /* stack: (L1 op L2) H1 H2 */
5465 gen_op(op);
5466 /* stack: (L1 op L2) (H1 op H2) */
5468 /* stack: L H */
5469 lbuild(t);
5470 break;
5471 case TOK_SAR:
5472 case TOK_SHR:
5473 case TOK_SHL:
5474 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5475 t = vtop[-1].type.t;
5476 vswap();
5477 lexpand();
5478 vrotb(3);
5479 /* stack: L H shift */
5480 c = (int)vtop->c.i;
5481 /* constant: simpler */
5482 /* NOTE: all comments are for SHL. the other cases are
5483 done by swaping words */
5484 vpop();
5485 if (op != TOK_SHL)
5486 vswap();
5487 if (c >= 32) {
5488 /* stack: L H */
5489 vpop();
5490 if (c > 32) {
5491 vpushi(c - 32);
5492 gen_op(op);
5494 if (op != TOK_SAR) {
5495 vpushi(0);
5496 } else {
5497 gv_dup();
5498 vpushi(31);
5499 gen_op(TOK_SAR);
5501 vswap();
5502 } else {
5503 vswap();
5504 gv_dup();
5505 /* stack: H L L */
5506 vpushi(c);
5507 gen_op(op);
5508 vswap();
5509 vpushi(32 - c);
5510 if (op == TOK_SHL)
5511 gen_op(TOK_SHR);
5512 else
5513 gen_op(TOK_SHL);
5514 vrotb(3);
5515 /* stack: L L H */
5516 vpushi(c);
5517 if (op == TOK_SHL)
5518 gen_op(TOK_SHL);
5519 else
5520 gen_op(TOK_SHR);
5521 gen_op('|');
5523 if (op != TOK_SHL)
5524 vswap();
5525 lbuild(t);
5526 } else {
5527 /* XXX: should provide a faster fallback on x86 ? */
5528 switch(op) {
5529 case TOK_SAR:
5530 func = TOK___ashrdi3;
5531 goto gen_func;
5532 case TOK_SHR:
5533 func = TOK___lshrdi3;
5534 goto gen_func;
5535 case TOK_SHL:
5536 func = TOK___ashldi3;
5537 goto gen_func;
5540 break;
5541 default:
5542 /* compare operations */
5543 t = vtop->type.t;
5544 vswap();
5545 lexpand();
5546 vrotb(3);
5547 lexpand();
5548 /* stack: L1 H1 L2 H2 */
5549 tmp = vtop[-1];
5550 vtop[-1] = vtop[-2];
5551 vtop[-2] = tmp;
5552 /* stack: L1 L2 H1 H2 */
5553 /* compare high */
5554 op1 = op;
5555 /* when values are equal, we need to compare low words. since
5556 the jump is inverted, we invert the test too. */
5557 if (op1 == TOK_LT)
5558 op1 = TOK_LE;
5559 else if (op1 == TOK_GT)
5560 op1 = TOK_GE;
5561 else if (op1 == TOK_ULT)
5562 op1 = TOK_ULE;
5563 else if (op1 == TOK_UGT)
5564 op1 = TOK_UGE;
5565 a = 0;
5566 b = 0;
5567 gen_op(op1);
5568 if (op1 != TOK_NE) {
5569 a = gtst(1, 0);
5571 if (op != TOK_EQ) {
5572 /* generate non equal test */
5573 /* XXX: NOT PORTABLE yet */
5574 if (a == 0) {
5575 b = gtst(0, 0);
5576 } else {
5577 #if defined(TCC_TARGET_I386)
5578 b = psym(0x850f, 0);
5579 #elif defined(TCC_TARGET_ARM)
5580 b = ind;
5581 o(0x1A000000 | encbranch(ind, 0, 1));
5582 #elif defined(TCC_TARGET_C67)
5583 error("not implemented");
5584 #else
5585 #error not supported
5586 #endif
5589 /* compare low. Always unsigned */
5590 op1 = op;
5591 if (op1 == TOK_LT)
5592 op1 = TOK_ULT;
5593 else if (op1 == TOK_LE)
5594 op1 = TOK_ULE;
5595 else if (op1 == TOK_GT)
5596 op1 = TOK_UGT;
5597 else if (op1 == TOK_GE)
5598 op1 = TOK_UGE;
5599 gen_op(op1);
5600 a = gtst(1, a);
5601 gsym(b);
5602 vseti(VT_JMPI, a);
5603 break;
5606 #endif
5608 /* handle integer constant optimizations and various machine
5609 independent opt */
5610 void gen_opic(int op)
5612 int c1, c2, t1, t2, n;
5613 SValue *v1, *v2;
5614 long long l1, l2;
5615 typedef unsigned long long U;
5617 v1 = vtop - 1;
5618 v2 = vtop;
5619 t1 = v1->type.t & VT_BTYPE;
5620 t2 = v2->type.t & VT_BTYPE;
5622 if (t1 == VT_LLONG)
5623 l1 = v1->c.ll;
5624 else if (v1->type.t & VT_UNSIGNED)
5625 l1 = v1->c.ui;
5626 else
5627 l1 = v1->c.i;
5629 if (t2 == VT_LLONG)
5630 l2 = v2->c.ll;
5631 else if (v2->type.t & VT_UNSIGNED)
5632 l2 = v2->c.ui;
5633 else
5634 l2 = v2->c.i;
5636 /* currently, we cannot do computations with forward symbols */
5637 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5638 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5639 if (c1 && c2) {
5640 switch(op) {
5641 case '+': l1 += l2; break;
5642 case '-': l1 -= l2; break;
5643 case '&': l1 &= l2; break;
5644 case '^': l1 ^= l2; break;
5645 case '|': l1 |= l2; break;
5646 case '*': l1 *= l2; break;
5648 case TOK_PDIV:
5649 case '/':
5650 case '%':
5651 case TOK_UDIV:
5652 case TOK_UMOD:
5653 /* if division by zero, generate explicit division */
5654 if (l2 == 0) {
5655 if (const_wanted)
5656 error("division by zero in constant");
5657 goto general_case;
5659 switch(op) {
5660 default: l1 /= l2; break;
5661 case '%': l1 %= l2; break;
5662 case TOK_UDIV: l1 = (U)l1 / l2; break;
5663 case TOK_UMOD: l1 = (U)l1 % l2; break;
5665 break;
5666 case TOK_SHL: l1 <<= l2; break;
5667 case TOK_SHR: l1 = (U)l1 >> l2; break;
5668 case TOK_SAR: l1 >>= l2; break;
5669 /* tests */
5670 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
5671 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
5672 case TOK_EQ: l1 = l1 == l2; break;
5673 case TOK_NE: l1 = l1 != l2; break;
5674 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
5675 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
5676 case TOK_LT: l1 = l1 < l2; break;
5677 case TOK_GE: l1 = l1 >= l2; break;
5678 case TOK_LE: l1 = l1 <= l2; break;
5679 case TOK_GT: l1 = l1 > l2; break;
5680 /* logical */
5681 case TOK_LAND: l1 = l1 && l2; break;
5682 case TOK_LOR: l1 = l1 || l2; break;
5683 default:
5684 goto general_case;
5686 v1->c.ll = l1;
5687 vtop--;
5688 } else {
5689 /* if commutative ops, put c2 as constant */
5690 if (c1 && (op == '+' || op == '&' || op == '^' ||
5691 op == '|' || op == '*')) {
5692 vswap();
5693 c2 = c1; //c = c1, c1 = c2, c2 = c;
5694 l2 = l1; //l = l1, l1 = l2, l2 = l;
5696 /* Filter out NOP operations like x*1, x-0, x&-1... */
5697 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
5698 op == TOK_PDIV) &&
5699 l2 == 1) ||
5700 ((op == '+' || op == '-' || op == '|' || op == '^' ||
5701 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
5702 l2 == 0) ||
5703 (op == '&' &&
5704 l2 == -1))) {
5705 /* nothing to do */
5706 vtop--;
5707 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
5708 /* try to use shifts instead of muls or divs */
5709 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
5710 n = -1;
5711 while (l2) {
5712 l2 >>= 1;
5713 n++;
5715 vtop->c.ll = n;
5716 if (op == '*')
5717 op = TOK_SHL;
5718 else if (op == TOK_PDIV)
5719 op = TOK_SAR;
5720 else
5721 op = TOK_SHR;
5723 goto general_case;
5724 } else if (c2 && (op == '+' || op == '-') &&
5725 ((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) ==
5726 (VT_CONST | VT_SYM) ||
5727 (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
5728 /* symbol + constant case */
5729 if (op == '-')
5730 l2 = -l2;
5731 vtop--;
5732 vtop->c.ll += l2;
5733 } else {
5734 general_case:
5735 if (!nocode_wanted) {
5736 /* call low level op generator */
5737 if (t1 == VT_LLONG || t2 == VT_LLONG)
5738 gen_opl(op);
5739 else
5740 gen_opi(op);
5741 } else {
5742 vtop--;
5748 /* generate a floating point operation with constant propagation */
5749 void gen_opif(int op)
5751 int c1, c2;
5752 SValue *v1, *v2;
5753 long double f1, f2;
5755 v1 = vtop - 1;
5756 v2 = vtop;
5757 /* currently, we cannot do computations with forward symbols */
5758 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5759 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5760 if (c1 && c2) {
5761 if (v1->type.t == VT_FLOAT) {
5762 f1 = v1->c.f;
5763 f2 = v2->c.f;
5764 } else if (v1->type.t == VT_DOUBLE) {
5765 f1 = v1->c.d;
5766 f2 = v2->c.d;
5767 } else {
5768 f1 = v1->c.ld;
5769 f2 = v2->c.ld;
5772 /* NOTE: we only do constant propagation if finite number (not
5773 NaN or infinity) (ANSI spec) */
5774 if (!ieee_finite(f1) || !ieee_finite(f2))
5775 goto general_case;
5777 switch(op) {
5778 case '+': f1 += f2; break;
5779 case '-': f1 -= f2; break;
5780 case '*': f1 *= f2; break;
5781 case '/':
5782 if (f2 == 0.0) {
5783 if (const_wanted)
5784 error("division by zero in constant");
5785 goto general_case;
5787 f1 /= f2;
5788 break;
5789 /* XXX: also handles tests ? */
5790 default:
5791 goto general_case;
5793 /* XXX: overflow test ? */
5794 if (v1->type.t == VT_FLOAT) {
5795 v1->c.f = f1;
5796 } else if (v1->type.t == VT_DOUBLE) {
5797 v1->c.d = f1;
5798 } else {
5799 v1->c.ld = f1;
5801 vtop--;
5802 } else {
5803 general_case:
5804 if (!nocode_wanted) {
5805 gen_opf(op);
5806 } else {
5807 vtop--;
5812 static int pointed_size(CType *type)
5814 int align;
5815 return type_size(pointed_type(type), &align);
5818 static inline int is_null_pointer(SValue *p)
5820 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5821 return 0;
5822 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
5823 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
5826 static inline int is_integer_btype(int bt)
5828 return (bt == VT_BYTE || bt == VT_SHORT ||
5829 bt == VT_INT || bt == VT_LLONG);
5832 /* check types for comparison or substraction of pointers */
5833 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
5835 CType *type1, *type2, tmp_type1, tmp_type2;
5836 int bt1, bt2;
5838 /* null pointers are accepted for all comparisons as gcc */
5839 if (is_null_pointer(p1) || is_null_pointer(p2))
5840 return;
5841 type1 = &p1->type;
5842 type2 = &p2->type;
5843 bt1 = type1->t & VT_BTYPE;
5844 bt2 = type2->t & VT_BTYPE;
5845 /* accept comparison between pointer and integer with a warning */
5846 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
5847 if (op != TOK_LOR && op != TOK_LAND )
5848 warning("comparison between pointer and integer");
5849 return;
5852 /* both must be pointers or implicit function pointers */
5853 if (bt1 == VT_PTR) {
5854 type1 = pointed_type(type1);
5855 } else if (bt1 != VT_FUNC)
5856 goto invalid_operands;
5858 if (bt2 == VT_PTR) {
5859 type2 = pointed_type(type2);
5860 } else if (bt2 != VT_FUNC) {
5861 invalid_operands:
5862 error("invalid operands to binary %s", get_tok_str(op, NULL));
5864 if ((type1->t & VT_BTYPE) == VT_VOID ||
5865 (type2->t & VT_BTYPE) == VT_VOID)
5866 return;
5867 tmp_type1 = *type1;
5868 tmp_type2 = *type2;
5869 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5870 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5871 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
5872 /* gcc-like error if '-' is used */
5873 if (op == '-')
5874 goto invalid_operands;
5875 else
5876 warning("comparison of distinct pointer types lacks a cast");
5880 /* generic gen_op: handles types problems */
5881 void gen_op(int op)
5883 int u, t1, t2, bt1, bt2, t;
5884 CType type1;
5886 t1 = vtop[-1].type.t;
5887 t2 = vtop[0].type.t;
5888 bt1 = t1 & VT_BTYPE;
5889 bt2 = t2 & VT_BTYPE;
5891 if (bt1 == VT_PTR || bt2 == VT_PTR) {
5892 /* at least one operand is a pointer */
5893 /* relationnal op: must be both pointers */
5894 if (op >= TOK_ULT && op <= TOK_LOR) {
5895 check_comparison_pointer_types(vtop - 1, vtop, op);
5896 /* pointers are handled are unsigned */
5897 #ifdef TCC_TARGET_X86_64
5898 t = VT_LLONG | VT_UNSIGNED;
5899 #else
5900 t = VT_INT | VT_UNSIGNED;
5901 #endif
5902 goto std_op;
5904 /* if both pointers, then it must be the '-' op */
5905 if (bt1 == VT_PTR && bt2 == VT_PTR) {
5906 if (op != '-')
5907 error("cannot use pointers here");
5908 check_comparison_pointer_types(vtop - 1, vtop, op);
5909 /* XXX: check that types are compatible */
5910 u = pointed_size(&vtop[-1].type);
5911 gen_opic(op);
5912 /* set to integer type */
5913 #ifdef TCC_TARGET_X86_64
5914 vtop->type.t = VT_LLONG;
5915 #else
5916 vtop->type.t = VT_INT;
5917 #endif
5918 vpushi(u);
5919 gen_op(TOK_PDIV);
5920 } else {
5921 /* exactly one pointer : must be '+' or '-'. */
5922 if (op != '-' && op != '+')
5923 error("cannot use pointers here");
5924 /* Put pointer as first operand */
5925 if (bt2 == VT_PTR) {
5926 vswap();
5927 swap(&t1, &t2);
5929 type1 = vtop[-1].type;
5930 #ifdef TCC_TARGET_X86_64
5931 vpushll(pointed_size(&vtop[-1].type));
5932 #else
5933 /* XXX: cast to int ? (long long case) */
5934 vpushi(pointed_size(&vtop[-1].type));
5935 #endif
5936 gen_op('*');
5937 #ifdef CONFIG_TCC_BCHECK
5938 /* if evaluating constant expression, no code should be
5939 generated, so no bound check */
5940 if (do_bounds_check && !const_wanted) {
5941 /* if bounded pointers, we generate a special code to
5942 test bounds */
5943 if (op == '-') {
5944 vpushi(0);
5945 vswap();
5946 gen_op('-');
5948 gen_bounded_ptr_add();
5949 } else
5950 #endif
5952 gen_opic(op);
5954 /* put again type if gen_opic() swaped operands */
5955 vtop->type = type1;
5957 } else if (is_float(bt1) || is_float(bt2)) {
5958 /* compute bigger type and do implicit casts */
5959 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5960 t = VT_LDOUBLE;
5961 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5962 t = VT_DOUBLE;
5963 } else {
5964 t = VT_FLOAT;
5966 /* floats can only be used for a few operations */
5967 if (op != '+' && op != '-' && op != '*' && op != '/' &&
5968 (op < TOK_ULT || op > TOK_GT))
5969 error("invalid operands for binary operation");
5970 goto std_op;
5971 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5972 /* cast to biggest op */
5973 t = VT_LLONG;
5974 /* convert to unsigned if it does not fit in a long long */
5975 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5976 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5977 t |= VT_UNSIGNED;
5978 goto std_op;
5979 } else {
5980 /* integer operations */
5981 t = VT_INT;
5982 /* convert to unsigned if it does not fit in an integer */
5983 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5984 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5985 t |= VT_UNSIGNED;
5986 std_op:
5987 /* XXX: currently, some unsigned operations are explicit, so
5988 we modify them here */
5989 if (t & VT_UNSIGNED) {
5990 if (op == TOK_SAR)
5991 op = TOK_SHR;
5992 else if (op == '/')
5993 op = TOK_UDIV;
5994 else if (op == '%')
5995 op = TOK_UMOD;
5996 else if (op == TOK_LT)
5997 op = TOK_ULT;
5998 else if (op == TOK_GT)
5999 op = TOK_UGT;
6000 else if (op == TOK_LE)
6001 op = TOK_ULE;
6002 else if (op == TOK_GE)
6003 op = TOK_UGE;
6005 vswap();
6006 type1.t = t;
6007 gen_cast(&type1);
6008 vswap();
6009 /* special case for shifts and long long: we keep the shift as
6010 an integer */
6011 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
6012 type1.t = VT_INT;
6013 gen_cast(&type1);
6014 if (is_float(t))
6015 gen_opif(op);
6016 else
6017 gen_opic(op);
6018 if (op >= TOK_ULT && op <= TOK_GT) {
6019 /* relationnal op: the result is an int */
6020 vtop->type.t = VT_INT;
6021 } else {
6022 vtop->type.t = t;
6027 #ifndef TCC_TARGET_ARM
6028 /* generic itof for unsigned long long case */
6029 void gen_cvt_itof1(int t)
6031 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
6032 (VT_LLONG | VT_UNSIGNED)) {
6034 if (t == VT_FLOAT)
6035 vpush_global_sym(&func_old_type, TOK___floatundisf);
6036 #if LDOUBLE_SIZE != 8
6037 else if (t == VT_LDOUBLE)
6038 vpush_global_sym(&func_old_type, TOK___floatundixf);
6039 #endif
6040 else
6041 vpush_global_sym(&func_old_type, TOK___floatundidf);
6042 vrott(2);
6043 gfunc_call(1);
6044 vpushi(0);
6045 vtop->r = reg_fret(t);
6046 } else {
6047 gen_cvt_itof(t);
6050 #endif
6052 /* generic ftoi for unsigned long long case */
6053 void gen_cvt_ftoi1(int t)
6055 int st;
6057 if (t == (VT_LLONG | VT_UNSIGNED)) {
6058 /* not handled natively */
6059 st = vtop->type.t & VT_BTYPE;
6060 if (st == VT_FLOAT)
6061 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
6062 #if LDOUBLE_SIZE != 8
6063 else if (st == VT_LDOUBLE)
6064 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
6065 #endif
6066 else
6067 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
6068 vrott(2);
6069 gfunc_call(1);
6070 vpushi(0);
6071 vtop->r = REG_IRET;
6072 vtop->r2 = REG_LRET;
6073 } else {
6074 gen_cvt_ftoi(t);
6078 /* force char or short cast */
6079 void force_charshort_cast(int t)
6081 int bits, dbt;
6082 dbt = t & VT_BTYPE;
6083 /* XXX: add optimization if lvalue : just change type and offset */
6084 if (dbt == VT_BYTE)
6085 bits = 8;
6086 else
6087 bits = 16;
6088 if (t & VT_UNSIGNED) {
6089 vpushi((1 << bits) - 1);
6090 gen_op('&');
6091 } else {
6092 bits = 32 - bits;
6093 vpushi(bits);
6094 gen_op(TOK_SHL);
6095 /* result must be signed or the SAR is converted to an SHL
6096 This was not the case when "t" was a signed short
6097 and the last value on the stack was an unsigned int */
6098 vtop->type.t &= ~VT_UNSIGNED;
6099 vpushi(bits);
6100 gen_op(TOK_SAR);
6104 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6105 static void gen_cast(CType *type)
6107 int sbt, dbt, sf, df, c, p;
6109 /* special delayed cast for char/short */
6110 /* XXX: in some cases (multiple cascaded casts), it may still
6111 be incorrect */
6112 if (vtop->r & VT_MUSTCAST) {
6113 vtop->r &= ~VT_MUSTCAST;
6114 force_charshort_cast(vtop->type.t);
6117 /* bitfields first get cast to ints */
6118 if (vtop->type.t & VT_BITFIELD) {
6119 gv(RC_INT);
6122 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
6123 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
6125 if (sbt != dbt) {
6126 sf = is_float(sbt);
6127 df = is_float(dbt);
6128 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
6129 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
6130 if (c) {
6131 /* constant case: we can do it now */
6132 /* XXX: in ISOC, cannot do it if error in convert */
6133 if (sbt == VT_FLOAT)
6134 vtop->c.ld = vtop->c.f;
6135 else if (sbt == VT_DOUBLE)
6136 vtop->c.ld = vtop->c.d;
6138 if (df) {
6139 if ((sbt & VT_BTYPE) == VT_LLONG) {
6140 if (sbt & VT_UNSIGNED)
6141 vtop->c.ld = vtop->c.ull;
6142 else
6143 vtop->c.ld = vtop->c.ll;
6144 } else if(!sf) {
6145 if (sbt & VT_UNSIGNED)
6146 vtop->c.ld = vtop->c.ui;
6147 else
6148 vtop->c.ld = vtop->c.i;
6151 if (dbt == VT_FLOAT)
6152 vtop->c.f = (float)vtop->c.ld;
6153 else if (dbt == VT_DOUBLE)
6154 vtop->c.d = (double)vtop->c.ld;
6155 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
6156 vtop->c.ull = (unsigned long long)vtop->c.ld;
6157 } else if (sf && dbt == VT_BOOL) {
6158 vtop->c.i = (vtop->c.ld != 0);
6159 } else {
6160 if(sf)
6161 vtop->c.ll = (long long)vtop->c.ld;
6162 else if (sbt == (VT_LLONG|VT_UNSIGNED))
6163 vtop->c.ll = vtop->c.ull;
6164 else if (sbt & VT_UNSIGNED)
6165 vtop->c.ll = vtop->c.ui;
6166 else if (sbt != VT_LLONG)
6167 vtop->c.ll = vtop->c.i;
6169 if (dbt == (VT_LLONG|VT_UNSIGNED))
6170 vtop->c.ull = vtop->c.ll;
6171 else if (dbt == VT_BOOL)
6172 vtop->c.i = (vtop->c.ll != 0);
6173 else if (dbt != VT_LLONG) {
6174 int s = 0;
6175 if ((dbt & VT_BTYPE) == VT_BYTE)
6176 s = 24;
6177 else if ((dbt & VT_BTYPE) == VT_SHORT)
6178 s = 16;
6180 if(dbt & VT_UNSIGNED)
6181 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
6182 else
6183 vtop->c.i = ((int)vtop->c.ll << s) >> s;
6186 } else if (p && dbt == VT_BOOL) {
6187 vtop->r = VT_CONST;
6188 vtop->c.i = 1;
6189 } else if (!nocode_wanted) {
6190 /* non constant case: generate code */
6191 if (sf && df) {
6192 /* convert from fp to fp */
6193 gen_cvt_ftof(dbt);
6194 } else if (df) {
6195 /* convert int to fp */
6196 gen_cvt_itof1(dbt);
6197 } else if (sf) {
6198 /* convert fp to int */
6199 if (dbt == VT_BOOL) {
6200 vpushi(0);
6201 gen_op(TOK_NE);
6202 } else {
6203 /* we handle char/short/etc... with generic code */
6204 if (dbt != (VT_INT | VT_UNSIGNED) &&
6205 dbt != (VT_LLONG | VT_UNSIGNED) &&
6206 dbt != VT_LLONG)
6207 dbt = VT_INT;
6208 gen_cvt_ftoi1(dbt);
6209 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
6210 /* additional cast for char/short... */
6211 vtop->type.t = dbt;
6212 gen_cast(type);
6215 #ifndef TCC_TARGET_X86_64
6216 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
6217 if ((sbt & VT_BTYPE) != VT_LLONG) {
6218 /* scalar to long long */
6219 /* machine independent conversion */
6220 gv(RC_INT);
6221 /* generate high word */
6222 if (sbt == (VT_INT | VT_UNSIGNED)) {
6223 vpushi(0);
6224 gv(RC_INT);
6225 } else {
6226 if (sbt == VT_PTR) {
6227 /* cast from pointer to int before we apply
6228 shift operation, which pointers don't support*/
6229 gen_cast(&int_type);
6231 gv_dup();
6232 vpushi(31);
6233 gen_op(TOK_SAR);
6235 /* patch second register */
6236 vtop[-1].r2 = vtop->r;
6237 vpop();
6239 #else
6240 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
6241 (dbt & VT_BTYPE) == VT_PTR) {
6242 /* XXX: not sure if this is perfect... need more tests */
6243 if ((sbt & VT_BTYPE) != VT_LLONG) {
6244 int r = gv(RC_INT);
6245 if (sbt != (VT_INT | VT_UNSIGNED) &&
6246 sbt != VT_PTR && sbt != VT_FUNC) {
6247 /* x86_64 specific: movslq */
6248 o(0x6348);
6249 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
6252 #endif
6253 } else if (dbt == VT_BOOL) {
6254 /* scalar to bool */
6255 vpushi(0);
6256 gen_op(TOK_NE);
6257 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
6258 (dbt & VT_BTYPE) == VT_SHORT) {
6259 if (sbt == VT_PTR) {
6260 vtop->type.t = VT_INT;
6261 warning("nonportable conversion from pointer to char/short");
6263 force_charshort_cast(dbt);
6264 } else if ((dbt & VT_BTYPE) == VT_INT) {
6265 /* scalar to int */
6266 if (sbt == VT_LLONG) {
6267 /* from long long: just take low order word */
6268 lexpand();
6269 vpop();
6271 /* if lvalue and single word type, nothing to do because
6272 the lvalue already contains the real type size (see
6273 VT_LVAL_xxx constants) */
6276 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
6277 /* if we are casting between pointer types,
6278 we must update the VT_LVAL_xxx size */
6279 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
6280 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
6282 vtop->type = *type;
6285 /* return type size. Put alignment at 'a' */
6286 static int type_size(CType *type, int *a)
6288 Sym *s;
6289 int bt;
6291 bt = type->t & VT_BTYPE;
6292 if (bt == VT_STRUCT) {
6293 /* struct/union */
6294 s = type->ref;
6295 *a = s->r;
6296 return s->c;
6297 } else if (bt == VT_PTR) {
6298 if (type->t & VT_ARRAY) {
6299 int ts;
6301 s = type->ref;
6302 ts = type_size(&s->type, a);
6304 if (ts < 0 && s->c < 0)
6305 ts = -ts;
6307 return ts * s->c;
6308 } else {
6309 *a = PTR_SIZE;
6310 return PTR_SIZE;
6312 } else if (bt == VT_LDOUBLE) {
6313 *a = LDOUBLE_ALIGN;
6314 return LDOUBLE_SIZE;
6315 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
6316 #ifdef TCC_TARGET_I386
6317 #ifdef TCC_TARGET_PE
6318 *a = 8;
6319 #else
6320 *a = 4;
6321 #endif
6322 #elif defined(TCC_TARGET_ARM)
6323 #ifdef TCC_ARM_EABI
6324 *a = 8;
6325 #else
6326 *a = 4;
6327 #endif
6328 #else
6329 *a = 8;
6330 #endif
6331 return 8;
6332 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
6333 *a = 4;
6334 return 4;
6335 } else if (bt == VT_SHORT) {
6336 *a = 2;
6337 return 2;
6338 } else {
6339 /* char, void, function, _Bool */
6340 *a = 1;
6341 return 1;
6345 /* return the pointed type of t */
6346 static inline CType *pointed_type(CType *type)
6348 return &type->ref->type;
6351 /* modify type so that its it is a pointer to type. */
6352 static void mk_pointer(CType *type)
6354 Sym *s;
6355 s = sym_push(SYM_FIELD, type, 0, -1);
6356 type->t = VT_PTR | (type->t & ~VT_TYPE);
6357 type->ref = s;
6360 /* compare function types. OLD functions match any new functions */
6361 static int is_compatible_func(CType *type1, CType *type2)
6363 Sym *s1, *s2;
6365 s1 = type1->ref;
6366 s2 = type2->ref;
6367 if (!is_compatible_types(&s1->type, &s2->type))
6368 return 0;
6369 /* check func_call */
6370 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
6371 return 0;
6372 /* XXX: not complete */
6373 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
6374 return 1;
6375 if (s1->c != s2->c)
6376 return 0;
6377 while (s1 != NULL) {
6378 if (s2 == NULL)
6379 return 0;
6380 if (!is_compatible_parameter_types(&s1->type, &s2->type))
6381 return 0;
6382 s1 = s1->next;
6383 s2 = s2->next;
6385 if (s2)
6386 return 0;
6387 return 1;
6390 /* return true if type1 and type2 are the same. If unqualified is
6391 true, qualifiers on the types are ignored.
6393 - enums are not checked as gcc __builtin_types_compatible_p ()
6395 static int compare_types(CType *type1, CType *type2, int unqualified)
6397 int bt1, t1, t2;
6399 t1 = type1->t & VT_TYPE;
6400 t2 = type2->t & VT_TYPE;
6401 if (unqualified) {
6402 /* strip qualifiers before comparing */
6403 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
6404 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
6406 /* XXX: bitfields ? */
6407 if (t1 != t2)
6408 return 0;
6409 /* test more complicated cases */
6410 bt1 = t1 & VT_BTYPE;
6411 if (bt1 == VT_PTR) {
6412 type1 = pointed_type(type1);
6413 type2 = pointed_type(type2);
6414 return is_compatible_types(type1, type2);
6415 } else if (bt1 == VT_STRUCT) {
6416 return (type1->ref == type2->ref);
6417 } else if (bt1 == VT_FUNC) {
6418 return is_compatible_func(type1, type2);
6419 } else {
6420 return 1;
6424 /* return true if type1 and type2 are exactly the same (including
6425 qualifiers).
6427 static int is_compatible_types(CType *type1, CType *type2)
6429 return compare_types(type1,type2,0);
6432 /* return true if type1 and type2 are the same (ignoring qualifiers).
6434 static int is_compatible_parameter_types(CType *type1, CType *type2)
6436 return compare_types(type1,type2,1);
6439 /* print a type. If 'varstr' is not NULL, then the variable is also
6440 printed in the type */
6441 /* XXX: union */
6442 /* XXX: add array and function pointers */
6443 void type_to_str(char *buf, int buf_size,
6444 CType *type, const char *varstr)
6446 int bt, v, t;
6447 Sym *s, *sa;
6448 char buf1[256];
6449 const char *tstr;
6451 t = type->t & VT_TYPE;
6452 bt = t & VT_BTYPE;
6453 buf[0] = '\0';
6454 if (t & VT_CONSTANT)
6455 pstrcat(buf, buf_size, "const ");
6456 if (t & VT_VOLATILE)
6457 pstrcat(buf, buf_size, "volatile ");
6458 if (t & VT_UNSIGNED)
6459 pstrcat(buf, buf_size, "unsigned ");
6460 switch(bt) {
6461 case VT_VOID:
6462 tstr = "void";
6463 goto add_tstr;
6464 case VT_BOOL:
6465 tstr = "_Bool";
6466 goto add_tstr;
6467 case VT_BYTE:
6468 tstr = "char";
6469 goto add_tstr;
6470 case VT_SHORT:
6471 tstr = "short";
6472 goto add_tstr;
6473 case VT_INT:
6474 tstr = "int";
6475 goto add_tstr;
6476 case VT_LONG:
6477 tstr = "long";
6478 goto add_tstr;
6479 case VT_LLONG:
6480 tstr = "long long";
6481 goto add_tstr;
6482 case VT_FLOAT:
6483 tstr = "float";
6484 goto add_tstr;
6485 case VT_DOUBLE:
6486 tstr = "double";
6487 goto add_tstr;
6488 case VT_LDOUBLE:
6489 tstr = "long double";
6490 add_tstr:
6491 pstrcat(buf, buf_size, tstr);
6492 break;
6493 case VT_ENUM:
6494 case VT_STRUCT:
6495 if (bt == VT_STRUCT)
6496 tstr = "struct ";
6497 else
6498 tstr = "enum ";
6499 pstrcat(buf, buf_size, tstr);
6500 v = type->ref->v & ~SYM_STRUCT;
6501 if (v >= SYM_FIRST_ANOM)
6502 pstrcat(buf, buf_size, "<anonymous>");
6503 else
6504 pstrcat(buf, buf_size, get_tok_str(v, NULL));
6505 break;
6506 case VT_FUNC:
6507 s = type->ref;
6508 type_to_str(buf, buf_size, &s->type, varstr);
6509 pstrcat(buf, buf_size, "(");
6510 sa = s->next;
6511 while (sa != NULL) {
6512 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
6513 pstrcat(buf, buf_size, buf1);
6514 sa = sa->next;
6515 if (sa)
6516 pstrcat(buf, buf_size, ", ");
6518 pstrcat(buf, buf_size, ")");
6519 goto no_var;
6520 case VT_PTR:
6521 s = type->ref;
6522 pstrcpy(buf1, sizeof(buf1), "*");
6523 if (varstr)
6524 pstrcat(buf1, sizeof(buf1), varstr);
6525 type_to_str(buf, buf_size, &s->type, buf1);
6526 goto no_var;
6528 if (varstr) {
6529 pstrcat(buf, buf_size, " ");
6530 pstrcat(buf, buf_size, varstr);
6532 no_var: ;
6535 /* verify type compatibility to store vtop in 'dt' type, and generate
6536 casts if needed. */
6537 static void gen_assign_cast(CType *dt)
6539 CType *st, *type1, *type2, tmp_type1, tmp_type2;
6540 char buf1[256], buf2[256];
6541 int dbt, sbt;
6543 st = &vtop->type; /* source type */
6544 dbt = dt->t & VT_BTYPE;
6545 sbt = st->t & VT_BTYPE;
6546 if (dt->t & VT_CONSTANT)
6547 warning("assignment of read-only location");
6548 switch(dbt) {
6549 case VT_PTR:
6550 /* special cases for pointers */
6551 /* '0' can also be a pointer */
6552 if (is_null_pointer(vtop))
6553 goto type_ok;
6554 /* accept implicit pointer to integer cast with warning */
6555 if (is_integer_btype(sbt)) {
6556 warning("assignment makes pointer from integer without a cast");
6557 goto type_ok;
6559 type1 = pointed_type(dt);
6560 /* a function is implicitely a function pointer */
6561 if (sbt == VT_FUNC) {
6562 if ((type1->t & VT_BTYPE) != VT_VOID &&
6563 !is_compatible_types(pointed_type(dt), st))
6564 goto error;
6565 else
6566 goto type_ok;
6568 if (sbt != VT_PTR)
6569 goto error;
6570 type2 = pointed_type(st);
6571 if ((type1->t & VT_BTYPE) == VT_VOID ||
6572 (type2->t & VT_BTYPE) == VT_VOID) {
6573 /* void * can match anything */
6574 } else {
6575 /* exact type match, except for unsigned */
6576 tmp_type1 = *type1;
6577 tmp_type2 = *type2;
6578 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6579 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6580 if (!is_compatible_types(&tmp_type1, &tmp_type2))
6581 warning("assignment from incompatible pointer type");
6583 /* check const and volatile */
6584 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
6585 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
6586 warning("assignment discards qualifiers from pointer target type");
6587 break;
6588 case VT_BYTE:
6589 case VT_SHORT:
6590 case VT_INT:
6591 case VT_LLONG:
6592 if (sbt == VT_PTR || sbt == VT_FUNC) {
6593 warning("assignment makes integer from pointer without a cast");
6595 /* XXX: more tests */
6596 break;
6597 case VT_STRUCT:
6598 tmp_type1 = *dt;
6599 tmp_type2 = *st;
6600 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
6601 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
6602 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
6603 error:
6604 type_to_str(buf1, sizeof(buf1), st, NULL);
6605 type_to_str(buf2, sizeof(buf2), dt, NULL);
6606 error("cannot cast '%s' to '%s'", buf1, buf2);
6608 break;
6610 type_ok:
6611 gen_cast(dt);
6614 /* store vtop in lvalue pushed on stack */
6615 void vstore(void)
6617 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
6619 ft = vtop[-1].type.t;
6620 sbt = vtop->type.t & VT_BTYPE;
6621 dbt = ft & VT_BTYPE;
6622 if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
6623 (sbt == VT_INT && dbt == VT_SHORT)) {
6624 /* optimize char/short casts */
6625 delayed_cast = VT_MUSTCAST;
6626 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
6627 /* XXX: factorize */
6628 if (ft & VT_CONSTANT)
6629 warning("assignment of read-only location");
6630 } else {
6631 delayed_cast = 0;
6632 if (!(ft & VT_BITFIELD))
6633 gen_assign_cast(&vtop[-1].type);
6636 if (sbt == VT_STRUCT) {
6637 /* if structure, only generate pointer */
6638 /* structure assignment : generate memcpy */
6639 /* XXX: optimize if small size */
6640 if (!nocode_wanted) {
6641 size = type_size(&vtop->type, &align);
6643 #ifdef TCC_ARM_EABI
6644 if(!(align & 7))
6645 vpush_global_sym(&func_old_type, TOK_memcpy8);
6646 else if(!(align & 3))
6647 vpush_global_sym(&func_old_type, TOK_memcpy4);
6648 else
6649 #endif
6650 vpush_global_sym(&func_old_type, TOK_memcpy);
6652 /* destination */
6653 vpushv(vtop - 2);
6654 vtop->type.t = VT_PTR;
6655 gaddrof();
6656 /* source */
6657 vpushv(vtop - 2);
6658 vtop->type.t = VT_PTR;
6659 gaddrof();
6660 /* type size */
6661 vpushi(size);
6662 gfunc_call(3);
6664 vswap();
6665 vpop();
6666 } else {
6667 vswap();
6668 vpop();
6670 /* leave source on stack */
6671 } else if (ft & VT_BITFIELD) {
6672 /* bitfield store handling */
6673 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
6674 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
6675 /* remove bit field info to avoid loops */
6676 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
6678 /* duplicate source into other register */
6679 gv_dup();
6680 vswap();
6681 vrott(3);
6683 if((ft & VT_BTYPE) == VT_BOOL) {
6684 gen_cast(&vtop[-1].type);
6685 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
6688 /* duplicate destination */
6689 vdup();
6690 vtop[-1] = vtop[-2];
6692 /* mask and shift source */
6693 if((ft & VT_BTYPE) != VT_BOOL) {
6694 if((ft & VT_BTYPE) == VT_LLONG) {
6695 vpushll((1ULL << bit_size) - 1ULL);
6696 } else {
6697 vpushi((1 << bit_size) - 1);
6699 gen_op('&');
6701 vpushi(bit_pos);
6702 gen_op(TOK_SHL);
6703 /* load destination, mask and or with source */
6704 vswap();
6705 if((ft & VT_BTYPE) == VT_LLONG) {
6706 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
6707 } else {
6708 vpushi(~(((1 << bit_size) - 1) << bit_pos));
6710 gen_op('&');
6711 gen_op('|');
6712 /* store result */
6713 vstore();
6715 /* pop off shifted source from "duplicate source..." above */
6716 vpop();
6718 } else {
6719 #ifdef CONFIG_TCC_BCHECK
6720 /* bound check case */
6721 if (vtop[-1].r & VT_MUSTBOUND) {
6722 vswap();
6723 gbound();
6724 vswap();
6726 #endif
6727 if (!nocode_wanted) {
6728 rc = RC_INT;
6729 if (is_float(ft)) {
6730 rc = RC_FLOAT;
6731 #ifdef TCC_TARGET_X86_64
6732 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
6733 rc = RC_ST0;
6735 #endif
6737 r = gv(rc); /* generate value */
6738 /* if lvalue was saved on stack, must read it */
6739 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
6740 SValue sv;
6741 t = get_reg(RC_INT);
6742 #ifdef TCC_TARGET_X86_64
6743 sv.type.t = VT_PTR;
6744 #else
6745 sv.type.t = VT_INT;
6746 #endif
6747 sv.r = VT_LOCAL | VT_LVAL;
6748 sv.c.ul = vtop[-1].c.ul;
6749 load(t, &sv);
6750 vtop[-1].r = t | VT_LVAL;
6752 store(r, vtop - 1);
6753 #ifndef TCC_TARGET_X86_64
6754 /* two word case handling : store second register at word + 4 */
6755 if ((ft & VT_BTYPE) == VT_LLONG) {
6756 vswap();
6757 /* convert to int to increment easily */
6758 vtop->type.t = VT_INT;
6759 gaddrof();
6760 vpushi(4);
6761 gen_op('+');
6762 vtop->r |= VT_LVAL;
6763 vswap();
6764 /* XXX: it works because r2 is spilled last ! */
6765 store(vtop->r2, vtop - 1);
6767 #endif
6769 vswap();
6770 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
6771 vtop->r |= delayed_cast;
6775 /* post defines POST/PRE add. c is the token ++ or -- */
6776 void inc(int post, int c)
6778 test_lvalue();
6779 vdup(); /* save lvalue */
6780 if (post) {
6781 gv_dup(); /* duplicate value */
6782 vrotb(3);
6783 vrotb(3);
6785 /* add constant */
6786 vpushi(c - TOK_MID);
6787 gen_op('+');
6788 vstore(); /* store value */
6789 if (post)
6790 vpop(); /* if post op, return saved value */
6793 /* Parse GNUC __attribute__ extension. Currently, the following
6794 extensions are recognized:
6795 - aligned(n) : set data/function alignment.
6796 - packed : force data alignment to 1
6797 - section(x) : generate data/code in this section.
6798 - unused : currently ignored, but may be used someday.
6799 - regparm(n) : pass function parameters in registers (i386 only)
6801 static void parse_attribute(AttributeDef *ad)
6803 int t, n;
6805 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
6806 next();
6807 skip('(');
6808 skip('(');
6809 while (tok != ')') {
6810 if (tok < TOK_IDENT)
6811 expect("attribute name");
6812 t = tok;
6813 next();
6814 switch(t) {
6815 case TOK_SECTION1:
6816 case TOK_SECTION2:
6817 skip('(');
6818 if (tok != TOK_STR)
6819 expect("section name");
6820 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
6821 next();
6822 skip(')');
6823 break;
6824 case TOK_ALIGNED1:
6825 case TOK_ALIGNED2:
6826 if (tok == '(') {
6827 next();
6828 n = expr_const();
6829 if (n <= 0 || (n & (n - 1)) != 0)
6830 error("alignment must be a positive power of two");
6831 skip(')');
6832 } else {
6833 n = MAX_ALIGN;
6835 ad->aligned = n;
6836 break;
6837 case TOK_PACKED1:
6838 case TOK_PACKED2:
6839 ad->packed = 1;
6840 break;
6841 case TOK_UNUSED1:
6842 case TOK_UNUSED2:
6843 /* currently, no need to handle it because tcc does not
6844 track unused objects */
6845 break;
6846 case TOK_NORETURN1:
6847 case TOK_NORETURN2:
6848 /* currently, no need to handle it because tcc does not
6849 track unused objects */
6850 break;
6851 case TOK_CDECL1:
6852 case TOK_CDECL2:
6853 case TOK_CDECL3:
6854 FUNC_CALL(ad->func_attr) = FUNC_CDECL;
6855 break;
6856 case TOK_STDCALL1:
6857 case TOK_STDCALL2:
6858 case TOK_STDCALL3:
6859 FUNC_CALL(ad->func_attr) = FUNC_STDCALL;
6860 break;
6861 #ifdef TCC_TARGET_I386
6862 case TOK_REGPARM1:
6863 case TOK_REGPARM2:
6864 skip('(');
6865 n = expr_const();
6866 if (n > 3)
6867 n = 3;
6868 else if (n < 0)
6869 n = 0;
6870 if (n > 0)
6871 FUNC_CALL(ad->func_attr) = FUNC_FASTCALL1 + n - 1;
6872 skip(')');
6873 break;
6874 case TOK_FASTCALL1:
6875 case TOK_FASTCALL2:
6876 case TOK_FASTCALL3:
6877 FUNC_CALL(ad->func_attr) = FUNC_FASTCALLW;
6878 break;
6879 #endif
6880 case TOK_DLLEXPORT:
6881 FUNC_EXPORT(ad->func_attr) = 1;
6882 break;
6883 default:
6884 if (tcc_state->warn_unsupported)
6885 warning("'%s' attribute ignored", get_tok_str(t, NULL));
6886 /* skip parameters */
6887 if (tok == '(') {
6888 int parenthesis = 0;
6889 do {
6890 if (tok == '(')
6891 parenthesis++;
6892 else if (tok == ')')
6893 parenthesis--;
6894 next();
6895 } while (parenthesis && tok != -1);
6897 break;
6899 if (tok != ',')
6900 break;
6901 next();
6903 skip(')');
6904 skip(')');
6908 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6909 static void struct_decl(CType *type, int u)
6911 int a, v, size, align, maxalign, c, offset;
6912 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
6913 Sym *s, *ss, *ass, **ps;
6914 AttributeDef ad;
6915 CType type1, btype;
6917 a = tok; /* save decl type */
6918 next();
6919 if (tok != '{') {
6920 v = tok;
6921 next();
6922 /* struct already defined ? return it */
6923 if (v < TOK_IDENT)
6924 expect("struct/union/enum name");
6925 s = struct_find(v);
6926 if (s) {
6927 if (s->type.t != a)
6928 error("invalid type");
6929 goto do_decl;
6931 } else {
6932 v = anon_sym++;
6934 type1.t = a;
6935 /* we put an undefined size for struct/union */
6936 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
6937 s->r = 0; /* default alignment is zero as gcc */
6938 /* put struct/union/enum name in type */
6939 do_decl:
6940 type->t = u;
6941 type->ref = s;
6943 if (tok == '{') {
6944 next();
6945 if (s->c != -1)
6946 error("struct/union/enum already defined");
6947 /* cannot be empty */
6948 c = 0;
6949 /* non empty enums are not allowed */
6950 if (a == TOK_ENUM) {
6951 for(;;) {
6952 v = tok;
6953 if (v < TOK_UIDENT)
6954 expect("identifier");
6955 next();
6956 if (tok == '=') {
6957 next();
6958 c = expr_const();
6960 /* enum symbols have static storage */
6961 ss = sym_push(v, &int_type, VT_CONST, c);
6962 ss->type.t |= VT_STATIC;
6963 if (tok != ',')
6964 break;
6965 next();
6966 c++;
6967 /* NOTE: we accept a trailing comma */
6968 if (tok == '}')
6969 break;
6971 skip('}');
6972 } else {
6973 maxalign = 1;
6974 ps = &s->next;
6975 prevbt = VT_INT;
6976 bit_pos = 0;
6977 offset = 0;
6978 while (tok != '}') {
6979 parse_btype(&btype, &ad);
6980 while (1) {
6981 bit_size = -1;
6982 v = 0;
6983 type1 = btype;
6984 if (tok != ':') {
6985 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
6986 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
6987 expect("identifier");
6988 if ((type1.t & VT_BTYPE) == VT_FUNC ||
6989 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
6990 error("invalid type for '%s'",
6991 get_tok_str(v, NULL));
6993 if (tok == ':') {
6994 next();
6995 bit_size = expr_const();
6996 /* XXX: handle v = 0 case for messages */
6997 if (bit_size < 0)
6998 error("negative width in bit-field '%s'",
6999 get_tok_str(v, NULL));
7000 if (v && bit_size == 0)
7001 error("zero width for bit-field '%s'",
7002 get_tok_str(v, NULL));
7004 size = type_size(&type1, &align);
7005 if (ad.aligned) {
7006 if (align < ad.aligned)
7007 align = ad.aligned;
7008 } else if (ad.packed) {
7009 align = 1;
7010 } else if (*tcc_state->pack_stack_ptr) {
7011 if (align > *tcc_state->pack_stack_ptr)
7012 align = *tcc_state->pack_stack_ptr;
7014 lbit_pos = 0;
7015 if (bit_size >= 0) {
7016 bt = type1.t & VT_BTYPE;
7017 if (bt != VT_INT &&
7018 bt != VT_BYTE &&
7019 bt != VT_SHORT &&
7020 bt != VT_BOOL &&
7021 bt != VT_ENUM &&
7022 bt != VT_LLONG)
7023 error("bitfields must have scalar type");
7024 bsize = size * 8;
7025 if (bit_size > bsize) {
7026 error("width of '%s' exceeds its type",
7027 get_tok_str(v, NULL));
7028 } else if (bit_size == bsize) {
7029 /* no need for bit fields */
7030 bit_pos = 0;
7031 } else if (bit_size == 0) {
7032 /* XXX: what to do if only padding in a
7033 structure ? */
7034 /* zero size: means to pad */
7035 bit_pos = 0;
7036 } else {
7037 /* we do not have enough room ?
7038 did the type change?
7039 is it a union? */
7040 if ((bit_pos + bit_size) > bsize ||
7041 bt != prevbt || a == TOK_UNION)
7042 bit_pos = 0;
7043 lbit_pos = bit_pos;
7044 /* XXX: handle LSB first */
7045 type1.t |= VT_BITFIELD |
7046 (bit_pos << VT_STRUCT_SHIFT) |
7047 (bit_size << (VT_STRUCT_SHIFT + 6));
7048 bit_pos += bit_size;
7050 prevbt = bt;
7051 } else {
7052 bit_pos = 0;
7054 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
7055 /* add new memory data only if starting
7056 bit field */
7057 if (lbit_pos == 0) {
7058 if (a == TOK_STRUCT) {
7059 c = (c + align - 1) & -align;
7060 offset = c;
7061 if (size > 0)
7062 c += size;
7063 } else {
7064 offset = 0;
7065 if (size > c)
7066 c = size;
7068 if (align > maxalign)
7069 maxalign = align;
7071 #if 0
7072 printf("add field %s offset=%d",
7073 get_tok_str(v, NULL), offset);
7074 if (type1.t & VT_BITFIELD) {
7075 printf(" pos=%d size=%d",
7076 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
7077 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
7079 printf("\n");
7080 #endif
7082 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
7083 ass = type1.ref;
7084 while ((ass = ass->next) != NULL) {
7085 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
7086 *ps = ss;
7087 ps = &ss->next;
7089 } else if (v) {
7090 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
7091 *ps = ss;
7092 ps = &ss->next;
7094 if (tok == ';' || tok == TOK_EOF)
7095 break;
7096 skip(',');
7098 skip(';');
7100 skip('}');
7101 /* store size and alignment */
7102 s->c = (c + maxalign - 1) & -maxalign;
7103 s->r = maxalign;
7108 /* return 0 if no type declaration. otherwise, return the basic type
7109 and skip it.
7111 static int parse_btype(CType *type, AttributeDef *ad)
7113 int t, u, type_found, typespec_found, typedef_found;
7114 Sym *s;
7115 CType type1;
7117 memset(ad, 0, sizeof(AttributeDef));
7118 type_found = 0;
7119 typespec_found = 0;
7120 typedef_found = 0;
7121 t = 0;
7122 while(1) {
7123 switch(tok) {
7124 case TOK_EXTENSION:
7125 /* currently, we really ignore extension */
7126 next();
7127 continue;
7129 /* basic types */
7130 case TOK_CHAR:
7131 u = VT_BYTE;
7132 basic_type:
7133 next();
7134 basic_type1:
7135 if ((t & VT_BTYPE) != 0)
7136 error("too many basic types");
7137 t |= u;
7138 typespec_found = 1;
7139 break;
7140 case TOK_VOID:
7141 u = VT_VOID;
7142 goto basic_type;
7143 case TOK_SHORT:
7144 u = VT_SHORT;
7145 goto basic_type;
7146 case TOK_INT:
7147 next();
7148 typespec_found = 1;
7149 break;
7150 case TOK_LONG:
7151 next();
7152 if ((t & VT_BTYPE) == VT_DOUBLE) {
7153 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7154 } else if ((t & VT_BTYPE) == VT_LONG) {
7155 t = (t & ~VT_BTYPE) | VT_LLONG;
7156 } else {
7157 u = VT_LONG;
7158 goto basic_type1;
7160 break;
7161 case TOK_BOOL:
7162 u = VT_BOOL;
7163 goto basic_type;
7164 case TOK_FLOAT:
7165 u = VT_FLOAT;
7166 goto basic_type;
7167 case TOK_DOUBLE:
7168 next();
7169 if ((t & VT_BTYPE) == VT_LONG) {
7170 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7171 } else {
7172 u = VT_DOUBLE;
7173 goto basic_type1;
7175 break;
7176 case TOK_ENUM:
7177 struct_decl(&type1, VT_ENUM);
7178 basic_type2:
7179 u = type1.t;
7180 type->ref = type1.ref;
7181 goto basic_type1;
7182 case TOK_STRUCT:
7183 case TOK_UNION:
7184 struct_decl(&type1, VT_STRUCT);
7185 goto basic_type2;
7187 /* type modifiers */
7188 case TOK_CONST1:
7189 case TOK_CONST2:
7190 case TOK_CONST3:
7191 t |= VT_CONSTANT;
7192 next();
7193 break;
7194 case TOK_VOLATILE1:
7195 case TOK_VOLATILE2:
7196 case TOK_VOLATILE3:
7197 t |= VT_VOLATILE;
7198 next();
7199 break;
7200 case TOK_SIGNED1:
7201 case TOK_SIGNED2:
7202 case TOK_SIGNED3:
7203 typespec_found = 1;
7204 t |= VT_SIGNED;
7205 next();
7206 break;
7207 case TOK_REGISTER:
7208 case TOK_AUTO:
7209 case TOK_RESTRICT1:
7210 case TOK_RESTRICT2:
7211 case TOK_RESTRICT3:
7212 next();
7213 break;
7214 case TOK_UNSIGNED:
7215 t |= VT_UNSIGNED;
7216 next();
7217 typespec_found = 1;
7218 break;
7220 /* storage */
7221 case TOK_EXTERN:
7222 t |= VT_EXTERN;
7223 next();
7224 break;
7225 case TOK_STATIC:
7226 t |= VT_STATIC;
7227 next();
7228 break;
7229 case TOK_TYPEDEF:
7230 t |= VT_TYPEDEF;
7231 next();
7232 break;
7233 case TOK_INLINE1:
7234 case TOK_INLINE2:
7235 case TOK_INLINE3:
7236 t |= VT_INLINE;
7237 next();
7238 break;
7240 /* GNUC attribute */
7241 case TOK_ATTRIBUTE1:
7242 case TOK_ATTRIBUTE2:
7243 parse_attribute(ad);
7244 break;
7245 /* GNUC typeof */
7246 case TOK_TYPEOF1:
7247 case TOK_TYPEOF2:
7248 case TOK_TYPEOF3:
7249 next();
7250 parse_expr_type(&type1);
7251 goto basic_type2;
7252 default:
7253 if (typespec_found || typedef_found)
7254 goto the_end;
7255 s = sym_find(tok);
7256 if (!s || !(s->type.t & VT_TYPEDEF))
7257 goto the_end;
7258 typedef_found = 1;
7259 t |= (s->type.t & ~VT_TYPEDEF);
7260 type->ref = s->type.ref;
7261 next();
7262 typespec_found = 1;
7263 break;
7265 type_found = 1;
7267 the_end:
7268 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
7269 error("signed and unsigned modifier");
7270 if (tcc_state->char_is_unsigned) {
7271 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
7272 t |= VT_UNSIGNED;
7274 t &= ~VT_SIGNED;
7276 /* long is never used as type */
7277 if ((t & VT_BTYPE) == VT_LONG)
7278 #ifndef TCC_TARGET_X86_64
7279 t = (t & ~VT_BTYPE) | VT_INT;
7280 #else
7281 t = (t & ~VT_BTYPE) | VT_LLONG;
7282 #endif
7283 type->t = t;
7284 return type_found;
7287 /* convert a function parameter type (array to pointer and function to
7288 function pointer) */
7289 static inline void convert_parameter_type(CType *pt)
7291 /* remove const and volatile qualifiers (XXX: const could be used
7292 to indicate a const function parameter */
7293 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
7294 /* array must be transformed to pointer according to ANSI C */
7295 pt->t &= ~VT_ARRAY;
7296 if ((pt->t & VT_BTYPE) == VT_FUNC) {
7297 mk_pointer(pt);
7301 static void post_type(CType *type, AttributeDef *ad)
7303 int n, l, t1, arg_size, align;
7304 Sym **plast, *s, *first;
7305 AttributeDef ad1;
7306 CType pt;
7308 if (tok == '(') {
7309 /* function declaration */
7310 next();
7311 l = 0;
7312 first = NULL;
7313 plast = &first;
7314 arg_size = 0;
7315 if (tok != ')') {
7316 for(;;) {
7317 /* read param name and compute offset */
7318 if (l != FUNC_OLD) {
7319 if (!parse_btype(&pt, &ad1)) {
7320 if (l) {
7321 error("invalid type");
7322 } else {
7323 l = FUNC_OLD;
7324 goto old_proto;
7327 l = FUNC_NEW;
7328 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
7329 break;
7330 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
7331 if ((pt.t & VT_BTYPE) == VT_VOID)
7332 error("parameter declared as void");
7333 arg_size += (type_size(&pt, &align) + 3) & ~3;
7334 } else {
7335 old_proto:
7336 n = tok;
7337 if (n < TOK_UIDENT)
7338 expect("identifier");
7339 pt.t = VT_INT;
7340 next();
7342 convert_parameter_type(&pt);
7343 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
7344 *plast = s;
7345 plast = &s->next;
7346 if (tok == ')')
7347 break;
7348 skip(',');
7349 if (l == FUNC_NEW && tok == TOK_DOTS) {
7350 l = FUNC_ELLIPSIS;
7351 next();
7352 break;
7356 /* if no parameters, then old type prototype */
7357 if (l == 0)
7358 l = FUNC_OLD;
7359 skip(')');
7360 t1 = type->t & VT_STORAGE;
7361 /* NOTE: const is ignored in returned type as it has a special
7362 meaning in gcc / C++ */
7363 type->t &= ~(VT_STORAGE | VT_CONSTANT);
7364 post_type(type, ad);
7365 /* we push a anonymous symbol which will contain the function prototype */
7366 FUNC_ARGS(ad->func_attr) = arg_size;
7367 s = sym_push(SYM_FIELD, type, ad->func_attr, l);
7368 s->next = first;
7369 type->t = t1 | VT_FUNC;
7370 type->ref = s;
7371 } else if (tok == '[') {
7372 /* array definition */
7373 next();
7374 if (tok == TOK_RESTRICT1)
7375 next();
7376 n = -1;
7377 if (tok != ']') {
7378 n = expr_const();
7379 if (n < 0)
7380 error("invalid array size");
7382 skip(']');
7383 /* parse next post type */
7384 t1 = type->t & VT_STORAGE;
7385 type->t &= ~VT_STORAGE;
7386 post_type(type, ad);
7388 /* we push a anonymous symbol which will contain the array
7389 element type */
7390 s = sym_push(SYM_FIELD, type, 0, n);
7391 type->t = t1 | VT_ARRAY | VT_PTR;
7392 type->ref = s;
7396 /* Parse a type declaration (except basic type), and return the type
7397 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7398 expected. 'type' should contain the basic type. 'ad' is the
7399 attribute definition of the basic type. It can be modified by
7400 type_decl().
7402 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
7404 Sym *s;
7405 CType type1, *type2;
7406 int qualifiers;
7408 while (tok == '*') {
7409 qualifiers = 0;
7410 redo:
7411 next();
7412 switch(tok) {
7413 case TOK_CONST1:
7414 case TOK_CONST2:
7415 case TOK_CONST3:
7416 qualifiers |= VT_CONSTANT;
7417 goto redo;
7418 case TOK_VOLATILE1:
7419 case TOK_VOLATILE2:
7420 case TOK_VOLATILE3:
7421 qualifiers |= VT_VOLATILE;
7422 goto redo;
7423 case TOK_RESTRICT1:
7424 case TOK_RESTRICT2:
7425 case TOK_RESTRICT3:
7426 goto redo;
7428 mk_pointer(type);
7429 type->t |= qualifiers;
7432 /* XXX: clarify attribute handling */
7433 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7434 parse_attribute(ad);
7436 /* recursive type */
7437 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7438 type1.t = 0; /* XXX: same as int */
7439 if (tok == '(') {
7440 next();
7441 /* XXX: this is not correct to modify 'ad' at this point, but
7442 the syntax is not clear */
7443 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7444 parse_attribute(ad);
7445 type_decl(&type1, ad, v, td);
7446 skip(')');
7447 } else {
7448 /* type identifier */
7449 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
7450 *v = tok;
7451 next();
7452 } else {
7453 if (!(td & TYPE_ABSTRACT))
7454 expect("identifier");
7455 *v = 0;
7458 post_type(type, ad);
7459 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7460 parse_attribute(ad);
7461 if (!type1.t)
7462 return;
7463 /* append type at the end of type1 */
7464 type2 = &type1;
7465 for(;;) {
7466 s = type2->ref;
7467 type2 = &s->type;
7468 if (!type2->t) {
7469 *type2 = *type;
7470 break;
7473 *type = type1;
7476 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7477 static int lvalue_type(int t)
7479 int bt, r;
7480 r = VT_LVAL;
7481 bt = t & VT_BTYPE;
7482 if (bt == VT_BYTE || bt == VT_BOOL)
7483 r |= VT_LVAL_BYTE;
7484 else if (bt == VT_SHORT)
7485 r |= VT_LVAL_SHORT;
7486 else
7487 return r;
7488 if (t & VT_UNSIGNED)
7489 r |= VT_LVAL_UNSIGNED;
7490 return r;
7493 /* indirection with full error checking and bound check */
7494 static void indir(void)
7496 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
7497 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
7498 return;
7499 expect("pointer");
7501 if ((vtop->r & VT_LVAL) && !nocode_wanted)
7502 gv(RC_INT);
7503 vtop->type = *pointed_type(&vtop->type);
7504 /* Arrays and functions are never lvalues */
7505 if (!(vtop->type.t & VT_ARRAY)
7506 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
7507 vtop->r |= lvalue_type(vtop->type.t);
7508 /* if bound checking, the referenced pointer must be checked */
7509 if (do_bounds_check)
7510 vtop->r |= VT_MUSTBOUND;
7514 /* pass a parameter to a function and do type checking and casting */
7515 static void gfunc_param_typed(Sym *func, Sym *arg)
7517 int func_type;
7518 CType type;
7520 func_type = func->c;
7521 if (func_type == FUNC_OLD ||
7522 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
7523 /* default casting : only need to convert float to double */
7524 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
7525 type.t = VT_DOUBLE;
7526 gen_cast(&type);
7528 } else if (arg == NULL) {
7529 error("too many arguments to function");
7530 } else {
7531 type = arg->type;
7532 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
7533 gen_assign_cast(&type);
7537 /* parse an expression of the form '(type)' or '(expr)' and return its
7538 type */
7539 static void parse_expr_type(CType *type)
7541 int n;
7542 AttributeDef ad;
7544 skip('(');
7545 if (parse_btype(type, &ad)) {
7546 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7547 } else {
7548 expr_type(type);
7550 skip(')');
7553 static void parse_type(CType *type)
7555 AttributeDef ad;
7556 int n;
7558 if (!parse_btype(type, &ad)) {
7559 expect("type");
7561 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7564 static void vpush_tokc(int t)
7566 CType type;
7567 type.t = t;
7568 vsetc(&type, VT_CONST, &tokc);
7571 static void unary(void)
7573 int n, t, align, size, r;
7574 CType type;
7575 Sym *s;
7576 AttributeDef ad;
7578 /* XXX: GCC 2.95.3 does not generate a table although it should be
7579 better here */
7580 tok_next:
7581 switch(tok) {
7582 case TOK_EXTENSION:
7583 next();
7584 goto tok_next;
7585 case TOK_CINT:
7586 case TOK_CCHAR:
7587 case TOK_LCHAR:
7588 vpushi(tokc.i);
7589 next();
7590 break;
7591 case TOK_CUINT:
7592 vpush_tokc(VT_INT | VT_UNSIGNED);
7593 next();
7594 break;
7595 case TOK_CLLONG:
7596 vpush_tokc(VT_LLONG);
7597 next();
7598 break;
7599 case TOK_CULLONG:
7600 vpush_tokc(VT_LLONG | VT_UNSIGNED);
7601 next();
7602 break;
7603 case TOK_CFLOAT:
7604 vpush_tokc(VT_FLOAT);
7605 next();
7606 break;
7607 case TOK_CDOUBLE:
7608 vpush_tokc(VT_DOUBLE);
7609 next();
7610 break;
7611 case TOK_CLDOUBLE:
7612 vpush_tokc(VT_LDOUBLE);
7613 next();
7614 break;
7615 case TOK___FUNCTION__:
7616 if (!gnu_ext)
7617 goto tok_identifier;
7618 /* fall thru */
7619 case TOK___FUNC__:
7621 void *ptr;
7622 int len;
7623 /* special function name identifier */
7624 len = strlen(funcname) + 1;
7625 /* generate char[len] type */
7626 type.t = VT_BYTE;
7627 mk_pointer(&type);
7628 type.t |= VT_ARRAY;
7629 type.ref->c = len;
7630 vpush_ref(&type, data_section, data_section->data_offset, len);
7631 ptr = section_ptr_add(data_section, len);
7632 memcpy(ptr, funcname, len);
7633 next();
7635 break;
7636 case TOK_LSTR:
7637 #ifdef TCC_TARGET_PE
7638 t = VT_SHORT | VT_UNSIGNED;
7639 #else
7640 t = VT_INT;
7641 #endif
7642 goto str_init;
7643 case TOK_STR:
7644 /* string parsing */
7645 t = VT_BYTE;
7646 str_init:
7647 if (tcc_state->warn_write_strings)
7648 t |= VT_CONSTANT;
7649 type.t = t;
7650 mk_pointer(&type);
7651 type.t |= VT_ARRAY;
7652 memset(&ad, 0, sizeof(AttributeDef));
7653 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
7654 break;
7655 case '(':
7656 next();
7657 /* cast ? */
7658 if (parse_btype(&type, &ad)) {
7659 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
7660 skip(')');
7661 /* check ISOC99 compound literal */
7662 if (tok == '{') {
7663 /* data is allocated locally by default */
7664 if (global_expr)
7665 r = VT_CONST;
7666 else
7667 r = VT_LOCAL;
7668 /* all except arrays are lvalues */
7669 if (!(type.t & VT_ARRAY))
7670 r |= lvalue_type(type.t);
7671 memset(&ad, 0, sizeof(AttributeDef));
7672 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
7673 } else {
7674 unary();
7675 gen_cast(&type);
7677 } else if (tok == '{') {
7678 /* save all registers */
7679 save_regs(0);
7680 /* statement expression : we do not accept break/continue
7681 inside as GCC does */
7682 block(NULL, NULL, NULL, NULL, 0, 1);
7683 skip(')');
7684 } else {
7685 gexpr();
7686 skip(')');
7688 break;
7689 case '*':
7690 next();
7691 unary();
7692 indir();
7693 break;
7694 case '&':
7695 next();
7696 unary();
7697 /* functions names must be treated as function pointers,
7698 except for unary '&' and sizeof. Since we consider that
7699 functions are not lvalues, we only have to handle it
7700 there and in function calls. */
7701 /* arrays can also be used although they are not lvalues */
7702 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
7703 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
7704 test_lvalue();
7705 mk_pointer(&vtop->type);
7706 gaddrof();
7707 break;
7708 case '!':
7709 next();
7710 unary();
7711 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
7712 CType boolean;
7713 boolean.t = VT_BOOL;
7714 gen_cast(&boolean);
7715 vtop->c.i = !vtop->c.i;
7716 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
7717 vtop->c.i = vtop->c.i ^ 1;
7718 else {
7719 save_regs(1);
7720 vseti(VT_JMP, gtst(1, 0));
7722 break;
7723 case '~':
7724 next();
7725 unary();
7726 vpushi(-1);
7727 gen_op('^');
7728 break;
7729 case '+':
7730 next();
7731 /* in order to force cast, we add zero */
7732 unary();
7733 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
7734 error("pointer not accepted for unary plus");
7735 vpushi(0);
7736 gen_op('+');
7737 break;
7738 case TOK_SIZEOF:
7739 case TOK_ALIGNOF1:
7740 case TOK_ALIGNOF2:
7741 t = tok;
7742 next();
7743 if (tok == '(') {
7744 parse_expr_type(&type);
7745 } else {
7746 unary_type(&type);
7748 size = type_size(&type, &align);
7749 if (t == TOK_SIZEOF) {
7750 if (size < 0)
7751 error("sizeof applied to an incomplete type");
7752 vpushi(size);
7753 } else {
7754 vpushi(align);
7756 vtop->type.t |= VT_UNSIGNED;
7757 break;
7759 case TOK_builtin_types_compatible_p:
7761 CType type1, type2;
7762 next();
7763 skip('(');
7764 parse_type(&type1);
7765 skip(',');
7766 parse_type(&type2);
7767 skip(')');
7768 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
7769 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
7770 vpushi(is_compatible_types(&type1, &type2));
7772 break;
7773 case TOK_builtin_constant_p:
7775 int saved_nocode_wanted, res;
7776 next();
7777 skip('(');
7778 saved_nocode_wanted = nocode_wanted;
7779 nocode_wanted = 1;
7780 gexpr();
7781 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
7782 vpop();
7783 nocode_wanted = saved_nocode_wanted;
7784 skip(')');
7785 vpushi(res);
7787 break;
7788 case TOK_builtin_frame_address:
7790 CType type;
7791 next();
7792 skip('(');
7793 if (tok != TOK_CINT) {
7794 error("__builtin_frame_address only takes integers");
7796 if (tokc.i != 0) {
7797 error("TCC only supports __builtin_frame_address(0)");
7799 next();
7800 skip(')');
7801 type.t = VT_VOID;
7802 mk_pointer(&type);
7803 vset(&type, VT_LOCAL, 0);
7805 break;
7806 #ifdef TCC_TARGET_X86_64
7807 case TOK_builtin_malloc:
7808 tok = TOK_malloc;
7809 goto tok_identifier;
7810 case TOK_builtin_free:
7811 tok = TOK_free;
7812 goto tok_identifier;
7813 #endif
7814 case TOK_INC:
7815 case TOK_DEC:
7816 t = tok;
7817 next();
7818 unary();
7819 inc(0, t);
7820 break;
7821 case '-':
7822 next();
7823 vpushi(0);
7824 unary();
7825 gen_op('-');
7826 break;
7827 case TOK_LAND:
7828 if (!gnu_ext)
7829 goto tok_identifier;
7830 next();
7831 /* allow to take the address of a label */
7832 if (tok < TOK_UIDENT)
7833 expect("label identifier");
7834 s = label_find(tok);
7835 if (!s) {
7836 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
7837 } else {
7838 if (s->r == LABEL_DECLARED)
7839 s->r = LABEL_FORWARD;
7841 if (!s->type.t) {
7842 s->type.t = VT_VOID;
7843 mk_pointer(&s->type);
7844 s->type.t |= VT_STATIC;
7846 vset(&s->type, VT_CONST | VT_SYM, 0);
7847 vtop->sym = s;
7848 next();
7849 break;
7850 default:
7851 tok_identifier:
7852 t = tok;
7853 next();
7854 if (t < TOK_UIDENT)
7855 expect("identifier");
7856 s = sym_find(t);
7857 if (!s) {
7858 if (tok != '(')
7859 error("'%s' undeclared", get_tok_str(t, NULL));
7860 /* for simple function calls, we tolerate undeclared
7861 external reference to int() function */
7862 if (tcc_state->warn_implicit_function_declaration)
7863 warning("implicit declaration of function '%s'",
7864 get_tok_str(t, NULL));
7865 s = external_global_sym(t, &func_old_type, 0);
7867 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
7868 (VT_STATIC | VT_INLINE | VT_FUNC)) {
7869 /* if referencing an inline function, then we generate a
7870 symbol to it if not already done. It will have the
7871 effect to generate code for it at the end of the
7872 compilation unit. Inline function as always
7873 generated in the text section. */
7874 if (!s->c)
7875 put_extern_sym(s, text_section, 0, 0);
7876 r = VT_SYM | VT_CONST;
7877 } else {
7878 r = s->r;
7880 vset(&s->type, r, s->c);
7881 /* if forward reference, we must point to s */
7882 if (vtop->r & VT_SYM) {
7883 vtop->sym = s;
7884 vtop->c.ul = 0;
7886 break;
7889 /* post operations */
7890 while (1) {
7891 if (tok == TOK_INC || tok == TOK_DEC) {
7892 inc(1, tok);
7893 next();
7894 } else if (tok == '.' || tok == TOK_ARROW) {
7895 /* field */
7896 if (tok == TOK_ARROW)
7897 indir();
7898 test_lvalue();
7899 gaddrof();
7900 next();
7901 /* expect pointer on structure */
7902 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
7903 expect("struct or union");
7904 s = vtop->type.ref;
7905 /* find field */
7906 tok |= SYM_FIELD;
7907 while ((s = s->next) != NULL) {
7908 if (s->v == tok)
7909 break;
7911 if (!s)
7912 error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
7913 /* add field offset to pointer */
7914 vtop->type = char_pointer_type; /* change type to 'char *' */
7915 vpushi(s->c);
7916 gen_op('+');
7917 /* change type to field type, and set to lvalue */
7918 vtop->type = s->type;
7919 /* an array is never an lvalue */
7920 if (!(vtop->type.t & VT_ARRAY)) {
7921 vtop->r |= lvalue_type(vtop->type.t);
7922 /* if bound checking, the referenced pointer must be checked */
7923 if (do_bounds_check)
7924 vtop->r |= VT_MUSTBOUND;
7926 next();
7927 } else if (tok == '[') {
7928 next();
7929 gexpr();
7930 gen_op('+');
7931 indir();
7932 skip(']');
7933 } else if (tok == '(') {
7934 SValue ret;
7935 Sym *sa;
7936 int nb_args;
7938 /* function call */
7939 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
7940 /* pointer test (no array accepted) */
7941 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
7942 vtop->type = *pointed_type(&vtop->type);
7943 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
7944 goto error_func;
7945 } else {
7946 error_func:
7947 expect("function pointer");
7949 } else {
7950 vtop->r &= ~VT_LVAL; /* no lvalue */
7952 /* get return type */
7953 s = vtop->type.ref;
7954 next();
7955 sa = s->next; /* first parameter */
7956 nb_args = 0;
7957 ret.r2 = VT_CONST;
7958 /* compute first implicit argument if a structure is returned */
7959 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
7960 /* get some space for the returned structure */
7961 size = type_size(&s->type, &align);
7962 loc = (loc - size) & -align;
7963 ret.type = s->type;
7964 ret.r = VT_LOCAL | VT_LVAL;
7965 /* pass it as 'int' to avoid structure arg passing
7966 problems */
7967 vseti(VT_LOCAL, loc);
7968 ret.c = vtop->c;
7969 nb_args++;
7970 } else {
7971 ret.type = s->type;
7972 /* return in register */
7973 if (is_float(ret.type.t)) {
7974 ret.r = reg_fret(ret.type.t);
7975 } else {
7976 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
7977 ret.r2 = REG_LRET;
7978 ret.r = REG_IRET;
7980 ret.c.i = 0;
7982 if (tok != ')') {
7983 for(;;) {
7984 expr_eq();
7985 gfunc_param_typed(s, sa);
7986 nb_args++;
7987 if (sa)
7988 sa = sa->next;
7989 if (tok == ')')
7990 break;
7991 skip(',');
7994 if (sa)
7995 error("too few arguments to function");
7996 skip(')');
7997 if (!nocode_wanted) {
7998 gfunc_call(nb_args);
7999 } else {
8000 vtop -= (nb_args + 1);
8002 /* return value */
8003 vsetc(&ret.type, ret.r, &ret.c);
8004 vtop->r2 = ret.r2;
8005 } else {
8006 break;
8011 static void uneq(void)
8013 int t;
8015 unary();
8016 if (tok == '=' ||
8017 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
8018 tok == TOK_A_XOR || tok == TOK_A_OR ||
8019 tok == TOK_A_SHL || tok == TOK_A_SAR) {
8020 test_lvalue();
8021 t = tok;
8022 next();
8023 if (t == '=') {
8024 expr_eq();
8025 } else {
8026 vdup();
8027 expr_eq();
8028 gen_op(t & 0x7f);
8030 vstore();
8034 static void expr_prod(void)
8036 int t;
8038 uneq();
8039 while (tok == '*' || tok == '/' || tok == '%') {
8040 t = tok;
8041 next();
8042 uneq();
8043 gen_op(t);
8047 static void expr_sum(void)
8049 int t;
8051 expr_prod();
8052 while (tok == '+' || tok == '-') {
8053 t = tok;
8054 next();
8055 expr_prod();
8056 gen_op(t);
8060 static void expr_shift(void)
8062 int t;
8064 expr_sum();
8065 while (tok == TOK_SHL || tok == TOK_SAR) {
8066 t = tok;
8067 next();
8068 expr_sum();
8069 gen_op(t);
8073 static void expr_cmp(void)
8075 int t;
8077 expr_shift();
8078 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
8079 tok == TOK_ULT || tok == TOK_UGE) {
8080 t = tok;
8081 next();
8082 expr_shift();
8083 gen_op(t);
8087 static void expr_cmpeq(void)
8089 int t;
8091 expr_cmp();
8092 while (tok == TOK_EQ || tok == TOK_NE) {
8093 t = tok;
8094 next();
8095 expr_cmp();
8096 gen_op(t);
8100 static void expr_and(void)
8102 expr_cmpeq();
8103 while (tok == '&') {
8104 next();
8105 expr_cmpeq();
8106 gen_op('&');
8110 static void expr_xor(void)
8112 expr_and();
8113 while (tok == '^') {
8114 next();
8115 expr_and();
8116 gen_op('^');
8120 static void expr_or(void)
8122 expr_xor();
8123 while (tok == '|') {
8124 next();
8125 expr_xor();
8126 gen_op('|');
8130 /* XXX: fix this mess */
8131 static void expr_land_const(void)
8133 expr_or();
8134 while (tok == TOK_LAND) {
8135 next();
8136 expr_or();
8137 gen_op(TOK_LAND);
8141 /* XXX: fix this mess */
8142 static void expr_lor_const(void)
8144 expr_land_const();
8145 while (tok == TOK_LOR) {
8146 next();
8147 expr_land_const();
8148 gen_op(TOK_LOR);
8152 /* only used if non constant */
8153 static void expr_land(void)
8155 int t;
8157 expr_or();
8158 if (tok == TOK_LAND) {
8159 t = 0;
8160 save_regs(1);
8161 for(;;) {
8162 t = gtst(1, t);
8163 if (tok != TOK_LAND) {
8164 vseti(VT_JMPI, t);
8165 break;
8167 next();
8168 expr_or();
8173 static void expr_lor(void)
8175 int t;
8177 expr_land();
8178 if (tok == TOK_LOR) {
8179 t = 0;
8180 save_regs(1);
8181 for(;;) {
8182 t = gtst(0, t);
8183 if (tok != TOK_LOR) {
8184 vseti(VT_JMP, t);
8185 break;
8187 next();
8188 expr_land();
8193 /* XXX: better constant handling */
8194 static void expr_eq(void)
8196 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
8197 SValue sv;
8198 CType type, type1, type2;
8200 if (const_wanted) {
8201 expr_lor_const();
8202 if (tok == '?') {
8203 CType boolean;
8204 int c;
8205 boolean.t = VT_BOOL;
8206 vdup();
8207 gen_cast(&boolean);
8208 c = vtop->c.i;
8209 vpop();
8210 next();
8211 if (tok != ':' || !gnu_ext) {
8212 vpop();
8213 gexpr();
8215 if (!c)
8216 vpop();
8217 skip(':');
8218 expr_eq();
8219 if (c)
8220 vpop();
8222 } else {
8223 expr_lor();
8224 if (tok == '?') {
8225 next();
8226 if (vtop != vstack) {
8227 /* needed to avoid having different registers saved in
8228 each branch */
8229 if (is_float(vtop->type.t)) {
8230 rc = RC_FLOAT;
8231 #ifdef TCC_TARGET_X86_64
8232 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
8233 rc = RC_ST0;
8235 #endif
8237 else
8238 rc = RC_INT;
8239 gv(rc);
8240 save_regs(1);
8242 if (tok == ':' && gnu_ext) {
8243 gv_dup();
8244 tt = gtst(1, 0);
8245 } else {
8246 tt = gtst(1, 0);
8247 gexpr();
8249 type1 = vtop->type;
8250 sv = *vtop; /* save value to handle it later */
8251 vtop--; /* no vpop so that FP stack is not flushed */
8252 skip(':');
8253 u = gjmp(0);
8254 gsym(tt);
8255 expr_eq();
8256 type2 = vtop->type;
8258 t1 = type1.t;
8259 bt1 = t1 & VT_BTYPE;
8260 t2 = type2.t;
8261 bt2 = t2 & VT_BTYPE;
8262 /* cast operands to correct type according to ISOC rules */
8263 if (is_float(bt1) || is_float(bt2)) {
8264 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
8265 type.t = VT_LDOUBLE;
8266 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
8267 type.t = VT_DOUBLE;
8268 } else {
8269 type.t = VT_FLOAT;
8271 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
8272 /* cast to biggest op */
8273 type.t = VT_LLONG;
8274 /* convert to unsigned if it does not fit in a long long */
8275 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
8276 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
8277 type.t |= VT_UNSIGNED;
8278 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
8279 /* XXX: test pointer compatibility */
8280 type = type1;
8281 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
8282 /* XXX: test function pointer compatibility */
8283 type = type1;
8284 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
8285 /* XXX: test structure compatibility */
8286 type = type1;
8287 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
8288 /* NOTE: as an extension, we accept void on only one side */
8289 type.t = VT_VOID;
8290 } else {
8291 /* integer operations */
8292 type.t = VT_INT;
8293 /* convert to unsigned if it does not fit in an integer */
8294 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
8295 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
8296 type.t |= VT_UNSIGNED;
8299 /* now we convert second operand */
8300 gen_cast(&type);
8301 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8302 gaddrof();
8303 rc = RC_INT;
8304 if (is_float(type.t)) {
8305 rc = RC_FLOAT;
8306 #ifdef TCC_TARGET_X86_64
8307 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
8308 rc = RC_ST0;
8310 #endif
8311 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
8312 /* for long longs, we use fixed registers to avoid having
8313 to handle a complicated move */
8314 rc = RC_IRET;
8317 r2 = gv(rc);
8318 /* this is horrible, but we must also convert first
8319 operand */
8320 tt = gjmp(0);
8321 gsym(u);
8322 /* put again first value and cast it */
8323 *vtop = sv;
8324 gen_cast(&type);
8325 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8326 gaddrof();
8327 r1 = gv(rc);
8328 move_reg(r2, r1);
8329 vtop->r = r2;
8330 gsym(tt);
8335 static void gexpr(void)
8337 while (1) {
8338 expr_eq();
8339 if (tok != ',')
8340 break;
8341 vpop();
8342 next();
8346 /* parse an expression and return its type without any side effect. */
8347 static void expr_type(CType *type)
8349 int saved_nocode_wanted;
8351 saved_nocode_wanted = nocode_wanted;
8352 nocode_wanted = 1;
8353 gexpr();
8354 *type = vtop->type;
8355 vpop();
8356 nocode_wanted = saved_nocode_wanted;
8359 /* parse a unary expression and return its type without any side
8360 effect. */
8361 static void unary_type(CType *type)
8363 int a;
8365 a = nocode_wanted;
8366 nocode_wanted = 1;
8367 unary();
8368 *type = vtop->type;
8369 vpop();
8370 nocode_wanted = a;
8373 /* parse a constant expression and return value in vtop. */
8374 static void expr_const1(void)
8376 int a;
8377 a = const_wanted;
8378 const_wanted = 1;
8379 expr_eq();
8380 const_wanted = a;
8383 /* parse an integer constant and return its value. */
8384 static int expr_const(void)
8386 int c;
8387 expr_const1();
8388 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
8389 expect("constant expression");
8390 c = vtop->c.i;
8391 vpop();
8392 return c;
8395 /* return the label token if current token is a label, otherwise
8396 return zero */
8397 static int is_label(void)
8399 int last_tok;
8401 /* fast test first */
8402 if (tok < TOK_UIDENT)
8403 return 0;
8404 /* no need to save tokc because tok is an identifier */
8405 last_tok = tok;
8406 next();
8407 if (tok == ':') {
8408 next();
8409 return last_tok;
8410 } else {
8411 unget_tok(last_tok);
8412 return 0;
8416 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
8417 int case_reg, int is_expr)
8419 int a, b, c, d;
8420 Sym *s;
8422 /* generate line number info */
8423 if (do_debug &&
8424 (last_line_num != file->line_num || last_ind != ind)) {
8425 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
8426 last_ind = ind;
8427 last_line_num = file->line_num;
8430 if (is_expr) {
8431 /* default return value is (void) */
8432 vpushi(0);
8433 vtop->type.t = VT_VOID;
8436 if (tok == TOK_IF) {
8437 /* if test */
8438 next();
8439 skip('(');
8440 gexpr();
8441 skip(')');
8442 a = gtst(1, 0);
8443 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8444 c = tok;
8445 if (c == TOK_ELSE) {
8446 next();
8447 d = gjmp(0);
8448 gsym(a);
8449 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8450 gsym(d); /* patch else jmp */
8451 } else
8452 gsym(a);
8453 } else if (tok == TOK_WHILE) {
8454 next();
8455 d = ind;
8456 skip('(');
8457 gexpr();
8458 skip(')');
8459 a = gtst(1, 0);
8460 b = 0;
8461 block(&a, &b, case_sym, def_sym, case_reg, 0);
8462 gjmp_addr(d);
8463 gsym(a);
8464 gsym_addr(b, d);
8465 } else if (tok == '{') {
8466 Sym *llabel;
8468 next();
8469 /* record local declaration stack position */
8470 s = local_stack;
8471 llabel = local_label_stack;
8472 /* handle local labels declarations */
8473 if (tok == TOK_LABEL) {
8474 next();
8475 for(;;) {
8476 if (tok < TOK_UIDENT)
8477 expect("label identifier");
8478 label_push(&local_label_stack, tok, LABEL_DECLARED);
8479 next();
8480 if (tok == ',') {
8481 next();
8482 } else {
8483 skip(';');
8484 break;
8488 while (tok != '}') {
8489 decl(VT_LOCAL);
8490 if (tok != '}') {
8491 if (is_expr)
8492 vpop();
8493 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8496 /* pop locally defined labels */
8497 label_pop(&local_label_stack, llabel);
8498 /* pop locally defined symbols */
8499 if(is_expr) {
8500 /* XXX: this solution makes only valgrind happy...
8501 triggered by gcc.c-torture/execute/20000917-1.c */
8502 Sym *p;
8503 switch(vtop->type.t & VT_BTYPE) {
8504 case VT_PTR:
8505 case VT_STRUCT:
8506 case VT_ENUM:
8507 case VT_FUNC:
8508 for(p=vtop->type.ref;p;p=p->prev)
8509 if(p->prev==s)
8510 error("unsupported expression type");
8513 sym_pop(&local_stack, s);
8514 next();
8515 } else if (tok == TOK_RETURN) {
8516 next();
8517 if (tok != ';') {
8518 gexpr();
8519 gen_assign_cast(&func_vt);
8520 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
8521 CType type;
8522 /* if returning structure, must copy it to implicit
8523 first pointer arg location */
8524 #ifdef TCC_ARM_EABI
8525 int align, size;
8526 size = type_size(&func_vt,&align);
8527 if(size <= 4)
8529 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
8530 && (align & 3))
8532 int addr;
8533 loc = (loc - size) & -4;
8534 addr = loc;
8535 type = func_vt;
8536 vset(&type, VT_LOCAL | VT_LVAL, addr);
8537 vswap();
8538 vstore();
8539 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
8541 vtop->type = int_type;
8542 gv(RC_IRET);
8543 } else {
8544 #endif
8545 type = func_vt;
8546 mk_pointer(&type);
8547 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
8548 indir();
8549 vswap();
8550 /* copy structure value to pointer */
8551 vstore();
8552 #ifdef TCC_ARM_EABI
8554 #endif
8555 } else if (is_float(func_vt.t)) {
8556 gv(rc_fret(func_vt.t));
8557 } else {
8558 gv(RC_IRET);
8560 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
8562 skip(';');
8563 rsym = gjmp(rsym); /* jmp */
8564 } else if (tok == TOK_BREAK) {
8565 /* compute jump */
8566 if (!bsym)
8567 error("cannot break");
8568 *bsym = gjmp(*bsym);
8569 next();
8570 skip(';');
8571 } else if (tok == TOK_CONTINUE) {
8572 /* compute jump */
8573 if (!csym)
8574 error("cannot continue");
8575 *csym = gjmp(*csym);
8576 next();
8577 skip(';');
8578 } else if (tok == TOK_FOR) {
8579 int e;
8580 next();
8581 skip('(');
8582 if (tok != ';') {
8583 gexpr();
8584 vpop();
8586 skip(';');
8587 d = ind;
8588 c = ind;
8589 a = 0;
8590 b = 0;
8591 if (tok != ';') {
8592 gexpr();
8593 a = gtst(1, 0);
8595 skip(';');
8596 if (tok != ')') {
8597 e = gjmp(0);
8598 c = ind;
8599 gexpr();
8600 vpop();
8601 gjmp_addr(d);
8602 gsym(e);
8604 skip(')');
8605 block(&a, &b, case_sym, def_sym, case_reg, 0);
8606 gjmp_addr(c);
8607 gsym(a);
8608 gsym_addr(b, c);
8609 } else
8610 if (tok == TOK_DO) {
8611 next();
8612 a = 0;
8613 b = 0;
8614 d = ind;
8615 block(&a, &b, case_sym, def_sym, case_reg, 0);
8616 skip(TOK_WHILE);
8617 skip('(');
8618 gsym(b);
8619 gexpr();
8620 c = gtst(0, 0);
8621 gsym_addr(c, d);
8622 skip(')');
8623 gsym(a);
8624 skip(';');
8625 } else
8626 if (tok == TOK_SWITCH) {
8627 next();
8628 skip('(');
8629 gexpr();
8630 /* XXX: other types than integer */
8631 case_reg = gv(RC_INT);
8632 vpop();
8633 skip(')');
8634 a = 0;
8635 b = gjmp(0); /* jump to first case */
8636 c = 0;
8637 block(&a, csym, &b, &c, case_reg, 0);
8638 /* if no default, jmp after switch */
8639 if (c == 0)
8640 c = ind;
8641 /* default label */
8642 gsym_addr(b, c);
8643 /* break label */
8644 gsym(a);
8645 } else
8646 if (tok == TOK_CASE) {
8647 int v1, v2;
8648 if (!case_sym)
8649 expect("switch");
8650 next();
8651 v1 = expr_const();
8652 v2 = v1;
8653 if (gnu_ext && tok == TOK_DOTS) {
8654 next();
8655 v2 = expr_const();
8656 if (v2 < v1)
8657 warning("empty case range");
8659 /* since a case is like a label, we must skip it with a jmp */
8660 b = gjmp(0);
8661 gsym(*case_sym);
8662 vseti(case_reg, 0);
8663 vpushi(v1);
8664 if (v1 == v2) {
8665 gen_op(TOK_EQ);
8666 *case_sym = gtst(1, 0);
8667 } else {
8668 gen_op(TOK_GE);
8669 *case_sym = gtst(1, 0);
8670 vseti(case_reg, 0);
8671 vpushi(v2);
8672 gen_op(TOK_LE);
8673 *case_sym = gtst(1, *case_sym);
8675 gsym(b);
8676 skip(':');
8677 is_expr = 0;
8678 goto block_after_label;
8679 } else
8680 if (tok == TOK_DEFAULT) {
8681 next();
8682 skip(':');
8683 if (!def_sym)
8684 expect("switch");
8685 if (*def_sym)
8686 error("too many 'default'");
8687 *def_sym = ind;
8688 is_expr = 0;
8689 goto block_after_label;
8690 } else
8691 if (tok == TOK_GOTO) {
8692 next();
8693 if (tok == '*' && gnu_ext) {
8694 /* computed goto */
8695 next();
8696 gexpr();
8697 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
8698 expect("pointer");
8699 ggoto();
8700 } else if (tok >= TOK_UIDENT) {
8701 s = label_find(tok);
8702 /* put forward definition if needed */
8703 if (!s) {
8704 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
8705 } else {
8706 if (s->r == LABEL_DECLARED)
8707 s->r = LABEL_FORWARD;
8709 /* label already defined */
8710 if (s->r & LABEL_FORWARD)
8711 s->next = (void *)gjmp((long)s->next);
8712 else
8713 gjmp_addr((long)s->next);
8714 next();
8715 } else {
8716 expect("label identifier");
8718 skip(';');
8719 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
8720 asm_instr();
8721 } else {
8722 b = is_label();
8723 if (b) {
8724 /* label case */
8725 s = label_find(b);
8726 if (s) {
8727 if (s->r == LABEL_DEFINED)
8728 error("duplicate label '%s'", get_tok_str(s->v, NULL));
8729 gsym((long)s->next);
8730 s->r = LABEL_DEFINED;
8731 } else {
8732 s = label_push(&global_label_stack, b, LABEL_DEFINED);
8734 s->next = (void *)ind;
8735 /* we accept this, but it is a mistake */
8736 block_after_label:
8737 if (tok == '}') {
8738 warning("deprecated use of label at end of compound statement");
8739 } else {
8740 if (is_expr)
8741 vpop();
8742 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8744 } else {
8745 /* expression case */
8746 if (tok != ';') {
8747 if (is_expr) {
8748 vpop();
8749 gexpr();
8750 } else {
8751 gexpr();
8752 vpop();
8755 skip(';');
8760 /* t is the array or struct type. c is the array or struct
8761 address. cur_index/cur_field is the pointer to the current
8762 value. 'size_only' is true if only size info is needed (only used
8763 in arrays) */
8764 static void decl_designator(CType *type, Section *sec, unsigned long c,
8765 int *cur_index, Sym **cur_field,
8766 int size_only)
8768 Sym *s, *f;
8769 int notfirst, index, index_last, align, l, nb_elems, elem_size;
8770 CType type1;
8772 notfirst = 0;
8773 elem_size = 0;
8774 nb_elems = 1;
8775 if (gnu_ext && (l = is_label()) != 0)
8776 goto struct_field;
8777 while (tok == '[' || tok == '.') {
8778 if (tok == '[') {
8779 if (!(type->t & VT_ARRAY))
8780 expect("array type");
8781 s = type->ref;
8782 next();
8783 index = expr_const();
8784 if (index < 0 || (s->c >= 0 && index >= s->c))
8785 expect("invalid index");
8786 if (tok == TOK_DOTS && gnu_ext) {
8787 next();
8788 index_last = expr_const();
8789 if (index_last < 0 ||
8790 (s->c >= 0 && index_last >= s->c) ||
8791 index_last < index)
8792 expect("invalid index");
8793 } else {
8794 index_last = index;
8796 skip(']');
8797 if (!notfirst)
8798 *cur_index = index_last;
8799 type = pointed_type(type);
8800 elem_size = type_size(type, &align);
8801 c += index * elem_size;
8802 /* NOTE: we only support ranges for last designator */
8803 nb_elems = index_last - index + 1;
8804 if (nb_elems != 1) {
8805 notfirst = 1;
8806 break;
8808 } else {
8809 next();
8810 l = tok;
8811 next();
8812 struct_field:
8813 if ((type->t & VT_BTYPE) != VT_STRUCT)
8814 expect("struct/union type");
8815 s = type->ref;
8816 l |= SYM_FIELD;
8817 f = s->next;
8818 while (f) {
8819 if (f->v == l)
8820 break;
8821 f = f->next;
8823 if (!f)
8824 expect("field");
8825 if (!notfirst)
8826 *cur_field = f;
8827 /* XXX: fix this mess by using explicit storage field */
8828 type1 = f->type;
8829 type1.t |= (type->t & ~VT_TYPE);
8830 type = &type1;
8831 c += f->c;
8833 notfirst = 1;
8835 if (notfirst) {
8836 if (tok == '=') {
8837 next();
8838 } else {
8839 if (!gnu_ext)
8840 expect("=");
8842 } else {
8843 if (type->t & VT_ARRAY) {
8844 index = *cur_index;
8845 type = pointed_type(type);
8846 c += index * type_size(type, &align);
8847 } else {
8848 f = *cur_field;
8849 if (!f)
8850 error("too many field init");
8851 /* XXX: fix this mess by using explicit storage field */
8852 type1 = f->type;
8853 type1.t |= (type->t & ~VT_TYPE);
8854 type = &type1;
8855 c += f->c;
8858 decl_initializer(type, sec, c, 0, size_only);
8860 /* XXX: make it more general */
8861 if (!size_only && nb_elems > 1) {
8862 unsigned long c_end;
8863 uint8_t *src, *dst;
8864 int i;
8866 if (!sec)
8867 error("range init not supported yet for dynamic storage");
8868 c_end = c + nb_elems * elem_size;
8869 if (c_end > sec->data_allocated)
8870 section_realloc(sec, c_end);
8871 src = sec->data + c;
8872 dst = src;
8873 for(i = 1; i < nb_elems; i++) {
8874 dst += elem_size;
8875 memcpy(dst, src, elem_size);
8880 #define EXPR_VAL 0
8881 #define EXPR_CONST 1
8882 #define EXPR_ANY 2
8884 /* store a value or an expression directly in global data or in local array */
8885 static void init_putv(CType *type, Section *sec, unsigned long c,
8886 int v, int expr_type)
8888 int saved_global_expr, bt, bit_pos, bit_size;
8889 void *ptr;
8890 unsigned long long bit_mask;
8891 CType dtype;
8893 switch(expr_type) {
8894 case EXPR_VAL:
8895 vpushi(v);
8896 break;
8897 case EXPR_CONST:
8898 /* compound literals must be allocated globally in this case */
8899 saved_global_expr = global_expr;
8900 global_expr = 1;
8901 expr_const1();
8902 global_expr = saved_global_expr;
8903 /* NOTE: symbols are accepted */
8904 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
8905 error("initializer element is not constant");
8906 break;
8907 case EXPR_ANY:
8908 expr_eq();
8909 break;
8912 dtype = *type;
8913 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
8915 if (sec) {
8916 /* XXX: not portable */
8917 /* XXX: generate error if incorrect relocation */
8918 gen_assign_cast(&dtype);
8919 bt = type->t & VT_BTYPE;
8920 /* we'll write at most 12 bytes */
8921 if (c + 12 > sec->data_allocated) {
8922 section_realloc(sec, c + 12);
8924 ptr = sec->data + c;
8925 /* XXX: make code faster ? */
8926 if (!(type->t & VT_BITFIELD)) {
8927 bit_pos = 0;
8928 bit_size = 32;
8929 bit_mask = -1LL;
8930 } else {
8931 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
8932 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
8933 bit_mask = (1LL << bit_size) - 1;
8935 if ((vtop->r & VT_SYM) &&
8936 (bt == VT_BYTE ||
8937 bt == VT_SHORT ||
8938 bt == VT_DOUBLE ||
8939 bt == VT_LDOUBLE ||
8940 bt == VT_LLONG ||
8941 (bt == VT_INT && bit_size != 32)))
8942 error("initializer element is not computable at load time");
8943 switch(bt) {
8944 case VT_BOOL:
8945 vtop->c.i = (vtop->c.i != 0);
8946 case VT_BYTE:
8947 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8948 break;
8949 case VT_SHORT:
8950 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8951 break;
8952 case VT_DOUBLE:
8953 *(double *)ptr = vtop->c.d;
8954 break;
8955 case VT_LDOUBLE:
8956 *(long double *)ptr = vtop->c.ld;
8957 break;
8958 case VT_LLONG:
8959 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
8960 break;
8961 default:
8962 if (vtop->r & VT_SYM) {
8963 greloc(sec, vtop->sym, c, R_DATA_32);
8965 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8966 break;
8968 vtop--;
8969 } else {
8970 vset(&dtype, VT_LOCAL|VT_LVAL, c);
8971 vswap();
8972 vstore();
8973 vpop();
8977 /* put zeros for variable based init */
8978 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
8980 if (sec) {
8981 /* nothing to do because globals are already set to zero */
8982 } else {
8983 vpush_global_sym(&func_old_type, TOK_memset);
8984 vseti(VT_LOCAL, c);
8985 vpushi(0);
8986 vpushi(size);
8987 gfunc_call(3);
8991 /* 't' contains the type and storage info. 'c' is the offset of the
8992 object in section 'sec'. If 'sec' is NULL, it means stack based
8993 allocation. 'first' is true if array '{' must be read (multi
8994 dimension implicit array init handling). 'size_only' is true if
8995 size only evaluation is wanted (only for arrays). */
8996 static void decl_initializer(CType *type, Section *sec, unsigned long c,
8997 int first, int size_only)
8999 int index, array_length, n, no_oblock, nb, parlevel, i;
9000 int size1, align1, expr_type;
9001 Sym *s, *f;
9002 CType *t1;
9004 if (type->t & VT_ARRAY) {
9005 s = type->ref;
9006 n = s->c;
9007 array_length = 0;
9008 t1 = pointed_type(type);
9009 size1 = type_size(t1, &align1);
9011 no_oblock = 1;
9012 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
9013 tok == '{') {
9014 skip('{');
9015 no_oblock = 0;
9018 /* only parse strings here if correct type (otherwise: handle
9019 them as ((w)char *) expressions */
9020 if ((tok == TOK_LSTR &&
9021 #ifdef TCC_TARGET_PE
9022 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
9023 #else
9024 (t1->t & VT_BTYPE) == VT_INT
9025 #endif
9026 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
9027 while (tok == TOK_STR || tok == TOK_LSTR) {
9028 int cstr_len, ch;
9029 CString *cstr;
9031 cstr = tokc.cstr;
9032 /* compute maximum number of chars wanted */
9033 if (tok == TOK_STR)
9034 cstr_len = cstr->size;
9035 else
9036 cstr_len = cstr->size / sizeof(nwchar_t);
9037 cstr_len--;
9038 nb = cstr_len;
9039 if (n >= 0 && nb > (n - array_length))
9040 nb = n - array_length;
9041 if (!size_only) {
9042 if (cstr_len > nb)
9043 warning("initializer-string for array is too long");
9044 /* in order to go faster for common case (char
9045 string in global variable, we handle it
9046 specifically */
9047 if (sec && tok == TOK_STR && size1 == 1) {
9048 memcpy(sec->data + c + array_length, cstr->data, nb);
9049 } else {
9050 for(i=0;i<nb;i++) {
9051 if (tok == TOK_STR)
9052 ch = ((unsigned char *)cstr->data)[i];
9053 else
9054 ch = ((nwchar_t *)cstr->data)[i];
9055 init_putv(t1, sec, c + (array_length + i) * size1,
9056 ch, EXPR_VAL);
9060 array_length += nb;
9061 next();
9063 /* only add trailing zero if enough storage (no
9064 warning in this case since it is standard) */
9065 if (n < 0 || array_length < n) {
9066 if (!size_only) {
9067 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
9069 array_length++;
9071 } else {
9072 index = 0;
9073 while (tok != '}') {
9074 decl_designator(type, sec, c, &index, NULL, size_only);
9075 if (n >= 0 && index >= n)
9076 error("index too large");
9077 /* must put zero in holes (note that doing it that way
9078 ensures that it even works with designators) */
9079 if (!size_only && array_length < index) {
9080 init_putz(t1, sec, c + array_length * size1,
9081 (index - array_length) * size1);
9083 index++;
9084 if (index > array_length)
9085 array_length = index;
9086 /* special test for multi dimensional arrays (may not
9087 be strictly correct if designators are used at the
9088 same time) */
9089 if (index >= n && no_oblock)
9090 break;
9091 if (tok == '}')
9092 break;
9093 skip(',');
9096 if (!no_oblock)
9097 skip('}');
9098 /* put zeros at the end */
9099 if (!size_only && n >= 0 && array_length < n) {
9100 init_putz(t1, sec, c + array_length * size1,
9101 (n - array_length) * size1);
9103 /* patch type size if needed */
9104 if (n < 0)
9105 s->c = array_length;
9106 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
9107 (sec || !first || tok == '{')) {
9108 int par_count;
9110 /* NOTE: the previous test is a specific case for automatic
9111 struct/union init */
9112 /* XXX: union needs only one init */
9114 /* XXX: this test is incorrect for local initializers
9115 beginning with ( without {. It would be much more difficult
9116 to do it correctly (ideally, the expression parser should
9117 be used in all cases) */
9118 par_count = 0;
9119 if (tok == '(') {
9120 AttributeDef ad1;
9121 CType type1;
9122 next();
9123 while (tok == '(') {
9124 par_count++;
9125 next();
9127 if (!parse_btype(&type1, &ad1))
9128 expect("cast");
9129 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
9130 #if 0
9131 if (!is_assignable_types(type, &type1))
9132 error("invalid type for cast");
9133 #endif
9134 skip(')');
9136 no_oblock = 1;
9137 if (first || tok == '{') {
9138 skip('{');
9139 no_oblock = 0;
9141 s = type->ref;
9142 f = s->next;
9143 array_length = 0;
9144 index = 0;
9145 n = s->c;
9146 while (tok != '}') {
9147 decl_designator(type, sec, c, NULL, &f, size_only);
9148 index = f->c;
9149 if (!size_only && array_length < index) {
9150 init_putz(type, sec, c + array_length,
9151 index - array_length);
9153 index = index + type_size(&f->type, &align1);
9154 if (index > array_length)
9155 array_length = index;
9156 f = f->next;
9157 if (no_oblock && f == NULL)
9158 break;
9159 if (tok == '}')
9160 break;
9161 skip(',');
9163 /* put zeros at the end */
9164 if (!size_only && array_length < n) {
9165 init_putz(type, sec, c + array_length,
9166 n - array_length);
9168 if (!no_oblock)
9169 skip('}');
9170 while (par_count) {
9171 skip(')');
9172 par_count--;
9174 } else if (tok == '{') {
9175 next();
9176 decl_initializer(type, sec, c, first, size_only);
9177 skip('}');
9178 } else if (size_only) {
9179 /* just skip expression */
9180 parlevel = 0;
9181 while ((parlevel > 0 || (tok != '}' && tok != ',')) &&
9182 tok != -1) {
9183 if (tok == '(')
9184 parlevel++;
9185 else if (tok == ')')
9186 parlevel--;
9187 next();
9189 } else {
9190 /* currently, we always use constant expression for globals
9191 (may change for scripting case) */
9192 expr_type = EXPR_CONST;
9193 if (!sec)
9194 expr_type = EXPR_ANY;
9195 init_putv(type, sec, c, 0, expr_type);
9199 /* parse an initializer for type 't' if 'has_init' is non zero, and
9200 allocate space in local or global data space ('r' is either
9201 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9202 variable 'v' of scope 'scope' is declared before initializers are
9203 parsed. If 'v' is zero, then a reference to the new object is put
9204 in the value stack. If 'has_init' is 2, a special parsing is done
9205 to handle string constants. */
9206 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
9207 int has_init, int v, int scope)
9209 int size, align, addr, data_offset;
9210 int level;
9211 ParseState saved_parse_state = {0};
9212 TokenString init_str;
9213 Section *sec;
9215 size = type_size(type, &align);
9216 /* If unknown size, we must evaluate it before
9217 evaluating initializers because
9218 initializers can generate global data too
9219 (e.g. string pointers or ISOC99 compound
9220 literals). It also simplifies local
9221 initializers handling */
9222 tok_str_new(&init_str);
9223 if (size < 0) {
9224 if (!has_init)
9225 error("unknown type size");
9226 /* get all init string */
9227 if (has_init == 2) {
9228 /* only get strings */
9229 while (tok == TOK_STR || tok == TOK_LSTR) {
9230 tok_str_add_tok(&init_str);
9231 next();
9233 } else {
9234 level = 0;
9235 while (level > 0 || (tok != ',' && tok != ';')) {
9236 if (tok < 0)
9237 error("unexpected end of file in initializer");
9238 tok_str_add_tok(&init_str);
9239 if (tok == '{')
9240 level++;
9241 else if (tok == '}') {
9242 level--;
9243 if (level <= 0) {
9244 next();
9245 break;
9248 next();
9251 tok_str_add(&init_str, -1);
9252 tok_str_add(&init_str, 0);
9254 /* compute size */
9255 save_parse_state(&saved_parse_state);
9257 macro_ptr = init_str.str;
9258 next();
9259 decl_initializer(type, NULL, 0, 1, 1);
9260 /* prepare second initializer parsing */
9261 macro_ptr = init_str.str;
9262 next();
9264 /* if still unknown size, error */
9265 size = type_size(type, &align);
9266 if (size < 0)
9267 error("unknown type size");
9269 /* take into account specified alignment if bigger */
9270 if (ad->aligned) {
9271 if (ad->aligned > align)
9272 align = ad->aligned;
9273 } else if (ad->packed) {
9274 align = 1;
9276 if ((r & VT_VALMASK) == VT_LOCAL) {
9277 sec = NULL;
9278 if (do_bounds_check && (type->t & VT_ARRAY))
9279 loc--;
9280 loc = (loc - size) & -align;
9281 addr = loc;
9282 /* handles bounds */
9283 /* XXX: currently, since we do only one pass, we cannot track
9284 '&' operators, so we add only arrays */
9285 if (do_bounds_check && (type->t & VT_ARRAY)) {
9286 unsigned long *bounds_ptr;
9287 /* add padding between regions */
9288 loc--;
9289 /* then add local bound info */
9290 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
9291 bounds_ptr[0] = addr;
9292 bounds_ptr[1] = size;
9294 if (v) {
9295 /* local variable */
9296 sym_push(v, type, r, addr);
9297 } else {
9298 /* push local reference */
9299 vset(type, r, addr);
9301 } else {
9302 Sym *sym;
9304 sym = NULL;
9305 if (v && scope == VT_CONST) {
9306 /* see if the symbol was already defined */
9307 sym = sym_find(v);
9308 if (sym) {
9309 if (!is_compatible_types(&sym->type, type))
9310 error("incompatible types for redefinition of '%s'",
9311 get_tok_str(v, NULL));
9312 if (sym->type.t & VT_EXTERN) {
9313 /* if the variable is extern, it was not allocated */
9314 sym->type.t &= ~VT_EXTERN;
9315 /* set array size if it was ommited in extern
9316 declaration */
9317 if ((sym->type.t & VT_ARRAY) &&
9318 sym->type.ref->c < 0 &&
9319 type->ref->c >= 0)
9320 sym->type.ref->c = type->ref->c;
9321 } else {
9322 /* we accept several definitions of the same
9323 global variable. this is tricky, because we
9324 must play with the SHN_COMMON type of the symbol */
9325 /* XXX: should check if the variable was already
9326 initialized. It is incorrect to initialized it
9327 twice */
9328 /* no init data, we won't add more to the symbol */
9329 if (!has_init)
9330 goto no_alloc;
9335 /* allocate symbol in corresponding section */
9336 sec = ad->section;
9337 if (!sec) {
9338 if (has_init)
9339 sec = data_section;
9340 else if (tcc_state->nocommon)
9341 sec = bss_section;
9343 if (sec) {
9344 data_offset = sec->data_offset;
9345 data_offset = (data_offset + align - 1) & -align;
9346 addr = data_offset;
9347 /* very important to increment global pointer at this time
9348 because initializers themselves can create new initializers */
9349 data_offset += size;
9350 /* add padding if bound check */
9351 if (do_bounds_check)
9352 data_offset++;
9353 sec->data_offset = data_offset;
9354 /* allocate section space to put the data */
9355 if (sec->sh_type != SHT_NOBITS &&
9356 data_offset > sec->data_allocated)
9357 section_realloc(sec, data_offset);
9358 /* align section if needed */
9359 if (align > sec->sh_addralign)
9360 sec->sh_addralign = align;
9361 } else {
9362 addr = 0; /* avoid warning */
9365 if (v) {
9366 if (scope != VT_CONST || !sym) {
9367 sym = sym_push(v, type, r | VT_SYM, 0);
9369 /* update symbol definition */
9370 if (sec) {
9371 put_extern_sym(sym, sec, addr, size);
9372 } else {
9373 ElfW(Sym) *esym;
9374 /* put a common area */
9375 put_extern_sym(sym, NULL, align, size);
9376 /* XXX: find a nicer way */
9377 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
9378 esym->st_shndx = SHN_COMMON;
9380 } else {
9381 CValue cval;
9383 /* push global reference */
9384 sym = get_sym_ref(type, sec, addr, size);
9385 cval.ul = 0;
9386 vsetc(type, VT_CONST | VT_SYM, &cval);
9387 vtop->sym = sym;
9390 /* handles bounds now because the symbol must be defined
9391 before for the relocation */
9392 if (do_bounds_check) {
9393 unsigned long *bounds_ptr;
9395 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_32);
9396 /* then add global bound info */
9397 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
9398 bounds_ptr[0] = 0; /* relocated */
9399 bounds_ptr[1] = size;
9402 if (has_init) {
9403 decl_initializer(type, sec, addr, 1, 0);
9404 /* restore parse state if needed */
9405 if (init_str.str) {
9406 tok_str_free(init_str.str);
9407 restore_parse_state(&saved_parse_state);
9410 no_alloc: ;
9413 void put_func_debug(Sym *sym)
9415 char buf[512];
9417 /* stabs info */
9418 /* XXX: we put here a dummy type */
9419 snprintf(buf, sizeof(buf), "%s:%c1",
9420 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
9421 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
9422 cur_text_section, sym->c);
9423 /* //gr gdb wants a line at the function */
9424 put_stabn(N_SLINE, 0, file->line_num, 0);
9425 last_ind = 0;
9426 last_line_num = 0;
9429 /* parse an old style function declaration list */
9430 /* XXX: check multiple parameter */
9431 static void func_decl_list(Sym *func_sym)
9433 AttributeDef ad;
9434 int v;
9435 Sym *s;
9436 CType btype, type;
9438 /* parse each declaration */
9439 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF) {
9440 if (!parse_btype(&btype, &ad))
9441 expect("declaration list");
9442 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9443 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9444 tok == ';') {
9445 /* we accept no variable after */
9446 } else {
9447 for(;;) {
9448 type = btype;
9449 type_decl(&type, &ad, &v, TYPE_DIRECT);
9450 /* find parameter in function parameter list */
9451 s = func_sym->next;
9452 while (s != NULL) {
9453 if ((s->v & ~SYM_FIELD) == v)
9454 goto found;
9455 s = s->next;
9457 error("declaration for parameter '%s' but no such parameter",
9458 get_tok_str(v, NULL));
9459 found:
9460 /* check that no storage specifier except 'register' was given */
9461 if (type.t & VT_STORAGE)
9462 error("storage class specified for '%s'", get_tok_str(v, NULL));
9463 convert_parameter_type(&type);
9464 /* we can add the type (NOTE: it could be local to the function) */
9465 s->type = type;
9466 /* accept other parameters */
9467 if (tok == ',')
9468 next();
9469 else
9470 break;
9473 skip(';');
9477 /* parse a function defined by symbol 'sym' and generate its code in
9478 'cur_text_section' */
9479 static void gen_function(Sym *sym)
9481 int saved_nocode_wanted = nocode_wanted;
9482 nocode_wanted = 0;
9483 ind = cur_text_section->data_offset;
9484 /* NOTE: we patch the symbol size later */
9485 put_extern_sym(sym, cur_text_section, ind, 0);
9486 funcname = get_tok_str(sym->v, NULL);
9487 func_ind = ind;
9488 /* put debug symbol */
9489 if (do_debug)
9490 put_func_debug(sym);
9491 /* push a dummy symbol to enable local sym storage */
9492 sym_push2(&local_stack, SYM_FIELD, 0, 0);
9493 gfunc_prolog(&sym->type);
9494 rsym = 0;
9495 block(NULL, NULL, NULL, NULL, 0, 0);
9496 gsym(rsym);
9497 gfunc_epilog();
9498 cur_text_section->data_offset = ind;
9499 label_pop(&global_label_stack, NULL);
9500 sym_pop(&local_stack, NULL); /* reset local stack */
9501 /* end of function */
9502 /* patch symbol size */
9503 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
9504 ind - func_ind;
9505 if (do_debug) {
9506 put_stabn(N_FUN, 0, 0, ind - func_ind);
9508 /* It's better to crash than to generate wrong code */
9509 cur_text_section = NULL;
9510 funcname = ""; /* for safety */
9511 func_vt.t = VT_VOID; /* for safety */
9512 ind = 0; /* for safety */
9513 nocode_wanted = saved_nocode_wanted;
9516 static void gen_inline_functions(void)
9518 Sym *sym;
9519 CType *type;
9520 int *str, inline_generated;
9522 /* iterate while inline function are referenced */
9523 for(;;) {
9524 inline_generated = 0;
9525 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9526 type = &sym->type;
9527 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9528 (type->t & (VT_STATIC | VT_INLINE)) ==
9529 (VT_STATIC | VT_INLINE) &&
9530 sym->c != 0) {
9531 /* the function was used: generate its code and
9532 convert it to a normal function */
9533 str = INLINE_DEF(sym->r);
9534 sym->r = VT_SYM | VT_CONST;
9535 sym->type.t &= ~VT_INLINE;
9537 macro_ptr = str;
9538 next();
9539 cur_text_section = text_section;
9540 gen_function(sym);
9541 macro_ptr = NULL; /* fail safe */
9543 tok_str_free(str);
9544 inline_generated = 1;
9547 if (!inline_generated)
9548 break;
9551 /* free all remaining inline function tokens */
9552 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9553 type = &sym->type;
9554 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9555 (type->t & (VT_STATIC | VT_INLINE)) ==
9556 (VT_STATIC | VT_INLINE)) {
9557 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9558 if (sym->r == (VT_SYM | VT_CONST)) //gr beware!
9559 continue;
9560 str = INLINE_DEF(sym->r);
9561 tok_str_free(str);
9562 sym->r = 0; /* fail safe */
9567 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9568 static void decl(int l)
9570 int v, has_init, r;
9571 CType type, btype;
9572 Sym *sym;
9573 AttributeDef ad;
9575 while (1) {
9576 if (!parse_btype(&btype, &ad)) {
9577 /* skip redundant ';' */
9578 /* XXX: find more elegant solution */
9579 if (tok == ';') {
9580 next();
9581 continue;
9583 if (l == VT_CONST &&
9584 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
9585 /* global asm block */
9586 asm_global_instr();
9587 continue;
9589 /* special test for old K&R protos without explicit int
9590 type. Only accepted when defining global data */
9591 if (l == VT_LOCAL || tok < TOK_DEFINE)
9592 break;
9593 btype.t = VT_INT;
9595 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9596 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9597 tok == ';') {
9598 /* we accept no variable after */
9599 next();
9600 continue;
9602 while (1) { /* iterate thru each declaration */
9603 type = btype;
9604 type_decl(&type, &ad, &v, TYPE_DIRECT);
9605 #if 0
9607 char buf[500];
9608 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
9609 printf("type = '%s'\n", buf);
9611 #endif
9612 if ((type.t & VT_BTYPE) == VT_FUNC) {
9613 /* if old style function prototype, we accept a
9614 declaration list */
9615 sym = type.ref;
9616 if (sym->c == FUNC_OLD)
9617 func_decl_list(sym);
9620 if (tok == '{') {
9621 if (l == VT_LOCAL)
9622 error("cannot use local functions");
9623 if ((type.t & VT_BTYPE) != VT_FUNC)
9624 expect("function definition");
9626 /* reject abstract declarators in function definition */
9627 sym = type.ref;
9628 while ((sym = sym->next) != NULL)
9629 if (!(sym->v & ~SYM_FIELD))
9630 expect("identifier");
9632 /* XXX: cannot do better now: convert extern line to static inline */
9633 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
9634 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
9636 sym = sym_find(v);
9637 if (sym) {
9638 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
9639 goto func_error1;
9640 /* specific case: if not func_call defined, we put
9641 the one of the prototype */
9642 /* XXX: should have default value */
9643 r = sym->type.ref->r;
9644 if (FUNC_CALL(r) != FUNC_CDECL
9645 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
9646 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
9647 if (FUNC_EXPORT(r))
9648 FUNC_EXPORT(type.ref->r) = 1;
9650 if (!is_compatible_types(&sym->type, &type)) {
9651 func_error1:
9652 error("incompatible types for redefinition of '%s'",
9653 get_tok_str(v, NULL));
9655 /* if symbol is already defined, then put complete type */
9656 sym->type = type;
9657 } else {
9658 /* put function symbol */
9659 sym = global_identifier_push(v, type.t, 0);
9660 sym->type.ref = type.ref;
9663 /* static inline functions are just recorded as a kind
9664 of macro. Their code will be emitted at the end of
9665 the compilation unit only if they are used */
9666 if ((type.t & (VT_INLINE | VT_STATIC)) ==
9667 (VT_INLINE | VT_STATIC)) {
9668 TokenString func_str;
9669 int block_level;
9671 tok_str_new(&func_str);
9673 block_level = 0;
9674 for(;;) {
9675 int t;
9676 if (tok == TOK_EOF)
9677 error("unexpected end of file");
9678 tok_str_add_tok(&func_str);
9679 t = tok;
9680 next();
9681 if (t == '{') {
9682 block_level++;
9683 } else if (t == '}') {
9684 block_level--;
9685 if (block_level == 0)
9686 break;
9689 tok_str_add(&func_str, -1);
9690 tok_str_add(&func_str, 0);
9691 INLINE_DEF(sym->r) = func_str.str;
9692 } else {
9693 /* compute text section */
9694 cur_text_section = ad.section;
9695 if (!cur_text_section)
9696 cur_text_section = text_section;
9697 sym->r = VT_SYM | VT_CONST;
9698 gen_function(sym);
9700 break;
9701 } else {
9702 if (btype.t & VT_TYPEDEF) {
9703 /* save typedefed type */
9704 /* XXX: test storage specifiers ? */
9705 sym = sym_push(v, &type, 0, 0);
9706 sym->type.t |= VT_TYPEDEF;
9707 } else if ((type.t & VT_BTYPE) == VT_FUNC) {
9708 /* external function definition */
9709 /* specific case for func_call attribute */
9710 if (ad.func_attr)
9711 type.ref->r = ad.func_attr;
9712 external_sym(v, &type, 0);
9713 } else {
9714 /* not lvalue if array */
9715 r = 0;
9716 if (!(type.t & VT_ARRAY))
9717 r |= lvalue_type(type.t);
9718 has_init = (tok == '=');
9719 if ((btype.t & VT_EXTERN) ||
9720 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
9721 !has_init && l == VT_CONST && type.ref->c < 0)) {
9722 /* external variable */
9723 /* NOTE: as GCC, uninitialized global static
9724 arrays of null size are considered as
9725 extern */
9726 external_sym(v, &type, r);
9727 } else {
9728 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
9729 if (type.t & VT_STATIC)
9730 r |= VT_CONST;
9731 else
9732 r |= l;
9733 if (has_init)
9734 next();
9735 decl_initializer_alloc(&type, &ad, r,
9736 has_init, v, l);
9739 if (tok != ',') {
9740 skip(';');
9741 break;
9743 next();
9749 /* better than nothing, but needs extension to handle '-E' option
9750 correctly too */
9751 static void preprocess_init(TCCState *s1)
9753 s1->include_stack_ptr = s1->include_stack;
9754 /* XXX: move that before to avoid having to initialize
9755 file->ifdef_stack_ptr ? */
9756 s1->ifdef_stack_ptr = s1->ifdef_stack;
9757 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
9759 /* XXX: not ANSI compliant: bound checking says error */
9760 vtop = vstack - 1;
9761 s1->pack_stack[0] = 0;
9762 s1->pack_stack_ptr = s1->pack_stack;
9765 /* compile the C file opened in 'file'. Return non zero if errors. */
9766 static int tcc_compile(TCCState *s1)
9768 Sym *define_start;
9769 char buf[512];
9770 volatile int section_sym;
9772 #ifdef INC_DEBUG
9773 printf("%s: **** new file\n", file->filename);
9774 #endif
9775 preprocess_init(s1);
9777 cur_text_section = NULL;
9778 funcname = "";
9779 anon_sym = SYM_FIRST_ANOM;
9781 /* file info: full path + filename */
9782 section_sym = 0; /* avoid warning */
9783 if (do_debug) {
9784 section_sym = put_elf_sym(symtab_section, 0, 0,
9785 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
9786 text_section->sh_num, NULL);
9787 getcwd(buf, sizeof(buf));
9788 #ifdef _WIN32
9789 normalize_slashes(buf);
9790 #endif
9791 pstrcat(buf, sizeof(buf), "/");
9792 put_stabs_r(buf, N_SO, 0, 0,
9793 text_section->data_offset, text_section, section_sym);
9794 put_stabs_r(file->filename, N_SO, 0, 0,
9795 text_section->data_offset, text_section, section_sym);
9797 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9798 symbols can be safely used */
9799 put_elf_sym(symtab_section, 0, 0,
9800 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
9801 SHN_ABS, file->filename);
9803 /* define some often used types */
9804 int_type.t = VT_INT;
9806 char_pointer_type.t = VT_BYTE;
9807 mk_pointer(&char_pointer_type);
9809 func_old_type.t = VT_FUNC;
9810 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
9812 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9813 float_type.t = VT_FLOAT;
9814 double_type.t = VT_DOUBLE;
9816 func_float_type.t = VT_FUNC;
9817 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
9818 func_double_type.t = VT_FUNC;
9819 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
9820 #endif
9822 #if 0
9823 /* define 'void *alloca(unsigned int)' builtin function */
9825 Sym *s1;
9827 p = anon_sym++;
9828 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
9829 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
9830 s1->next = NULL;
9831 sym->next = s1;
9832 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
9834 #endif
9836 define_start = define_stack;
9837 nocode_wanted = 1;
9839 if (setjmp(s1->error_jmp_buf) == 0) {
9840 s1->nb_errors = 0;
9841 s1->error_set_jmp_enabled = 1;
9843 ch = file->buf_ptr[0];
9844 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9845 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
9846 next();
9847 decl(VT_CONST);
9848 if (tok != TOK_EOF)
9849 expect("declaration");
9851 /* end of translation unit info */
9852 if (do_debug) {
9853 put_stabs_r(NULL, N_SO, 0, 0,
9854 text_section->data_offset, text_section, section_sym);
9857 s1->error_set_jmp_enabled = 0;
9859 /* reset define stack, but leave -Dsymbols (may be incorrect if
9860 they are undefined) */
9861 free_defines(define_start);
9863 gen_inline_functions();
9865 sym_pop(&global_stack, NULL);
9866 sym_pop(&local_stack, NULL);
9868 return s1->nb_errors != 0 ? -1 : 0;
9871 /* Preprocess the current file */
9872 /* XXX: add line and file infos,
9873 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9874 * not preserved)
9876 static int tcc_preprocess(TCCState *s1)
9878 Sym *define_start;
9879 BufferedFile *file_ref;
9880 int token_seen, line_ref;
9882 preprocess_init(s1);
9883 define_start = define_stack;
9884 ch = file->buf_ptr[0];
9886 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9887 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
9888 PARSE_FLAG_LINEFEED;
9890 token_seen = 0;
9891 line_ref = 0;
9892 file_ref = NULL;
9894 for (;;) {
9895 next();
9896 if (tok == TOK_EOF) {
9897 break;
9898 } else if (tok == TOK_LINEFEED) {
9899 if (!token_seen)
9900 continue;
9901 ++line_ref;
9902 token_seen = 0;
9903 } else if (token_seen) {
9904 fwrite(tok_spaces.data, tok_spaces.size, 1, s1->outfile);
9905 } else {
9906 int d = file->line_num - line_ref;
9907 if (file != file_ref || d < 0 || d >= 8)
9908 fprintf(s1->outfile, "# %d \"%s\"\n", file->line_num, file->filename);
9909 else
9910 while (d)
9911 fputs("\n", s1->outfile), --d;
9912 line_ref = (file_ref = file)->line_num;
9913 token_seen = 1;
9915 fputs(get_tok_str(tok, &tokc), s1->outfile);
9917 free_defines(define_start);
9918 return 0;
9921 #ifdef LIBTCC
9922 int tcc_compile_string(TCCState *s, const char *str)
9924 BufferedFile bf1, *bf = &bf1;
9925 int ret, len;
9926 char *buf;
9928 /* init file structure */
9929 bf->fd = -1;
9930 /* XXX: avoid copying */
9931 len = strlen(str);
9932 buf = tcc_malloc(len + 1);
9933 if (!buf)
9934 return -1;
9935 memcpy(buf, str, len);
9936 buf[len] = CH_EOB;
9937 bf->buf_ptr = buf;
9938 bf->buf_end = buf + len;
9939 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
9940 bf->line_num = 1;
9941 file = bf;
9942 ret = tcc_compile(s);
9943 file = NULL;
9944 tcc_free(buf);
9946 /* currently, no need to close */
9947 return ret;
9949 #endif
9951 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9952 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
9954 BufferedFile bf1, *bf = &bf1;
9956 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
9957 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
9958 /* default value */
9959 if (!value)
9960 value = "1";
9961 pstrcat(bf->buffer, IO_BUF_SIZE, value);
9963 /* init file structure */
9964 bf->fd = -1;
9965 bf->buf_ptr = bf->buffer;
9966 bf->buf_end = bf->buffer + strlen(bf->buffer);
9967 *bf->buf_end = CH_EOB;
9968 bf->filename[0] = '\0';
9969 bf->line_num = 1;
9970 file = bf;
9972 s1->include_stack_ptr = s1->include_stack;
9974 /* parse with define parser */
9975 ch = file->buf_ptr[0];
9976 next_nomacro();
9977 parse_define();
9978 file = NULL;
9981 /* undefine a preprocessor symbol */
9982 void tcc_undefine_symbol(TCCState *s1, const char *sym)
9984 TokenSym *ts;
9985 Sym *s;
9986 ts = tok_alloc(sym, strlen(sym));
9987 s = define_find(ts->tok);
9988 /* undefine symbol by putting an invalid name */
9989 if (s)
9990 define_undef(s);
9993 #ifdef CONFIG_TCC_ASM
9995 #ifdef TCC_TARGET_I386
9996 #include "i386-asm.c"
9997 #endif
9998 #include "tccasm.c"
10000 #else
10001 static void asm_instr(void)
10003 error("inline asm() not supported");
10005 static void asm_global_instr(void)
10007 error("inline asm() not supported");
10009 #endif
10011 #include "tccelf.c"
10013 #ifdef TCC_TARGET_COFF
10014 #include "tcccoff.c"
10015 #endif
10017 #ifdef TCC_TARGET_PE
10018 #include "tccpe.c"
10019 #endif
10021 /* print the position in the source file of PC value 'pc' by reading
10022 the stabs debug information */
10023 static void rt_printline(unsigned long wanted_pc)
10025 Stab_Sym *sym, *sym_end;
10026 char func_name[128], last_func_name[128];
10027 unsigned long func_addr, last_pc, pc;
10028 const char *incl_files[INCLUDE_STACK_SIZE];
10029 int incl_index, len, last_line_num, i;
10030 const char *str, *p;
10032 fprintf(stderr, "0x%08lx:", wanted_pc);
10034 func_name[0] = '\0';
10035 func_addr = 0;
10036 incl_index = 0;
10037 last_func_name[0] = '\0';
10038 last_pc = 0xffffffff;
10039 last_line_num = 1;
10040 sym = (Stab_Sym *)stab_section->data + 1;
10041 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
10042 while (sym < sym_end) {
10043 switch(sym->n_type) {
10044 /* function start or end */
10045 case N_FUN:
10046 if (sym->n_strx == 0) {
10047 /* we test if between last line and end of function */
10048 pc = sym->n_value + func_addr;
10049 if (wanted_pc >= last_pc && wanted_pc < pc)
10050 goto found;
10051 func_name[0] = '\0';
10052 func_addr = 0;
10053 } else {
10054 str = stabstr_section->data + sym->n_strx;
10055 p = strchr(str, ':');
10056 if (!p) {
10057 pstrcpy(func_name, sizeof(func_name), str);
10058 } else {
10059 len = p - str;
10060 if (len > sizeof(func_name) - 1)
10061 len = sizeof(func_name) - 1;
10062 memcpy(func_name, str, len);
10063 func_name[len] = '\0';
10065 func_addr = sym->n_value;
10067 break;
10068 /* line number info */
10069 case N_SLINE:
10070 pc = sym->n_value + func_addr;
10071 if (wanted_pc >= last_pc && wanted_pc < pc)
10072 goto found;
10073 last_pc = pc;
10074 last_line_num = sym->n_desc;
10075 /* XXX: slow! */
10076 strcpy(last_func_name, func_name);
10077 break;
10078 /* include files */
10079 case N_BINCL:
10080 str = stabstr_section->data + sym->n_strx;
10081 add_incl:
10082 if (incl_index < INCLUDE_STACK_SIZE) {
10083 incl_files[incl_index++] = str;
10085 break;
10086 case N_EINCL:
10087 if (incl_index > 1)
10088 incl_index--;
10089 break;
10090 case N_SO:
10091 if (sym->n_strx == 0) {
10092 incl_index = 0; /* end of translation unit */
10093 } else {
10094 str = stabstr_section->data + sym->n_strx;
10095 /* do not add path */
10096 len = strlen(str);
10097 if (len > 0 && str[len - 1] != '/')
10098 goto add_incl;
10100 break;
10102 sym++;
10105 /* second pass: we try symtab symbols (no line number info) */
10106 incl_index = 0;
10108 ElfW(Sym) *sym, *sym_end;
10109 int type;
10111 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
10112 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
10113 sym < sym_end;
10114 sym++) {
10115 type = ELFW(ST_TYPE)(sym->st_info);
10116 if (type == STT_FUNC) {
10117 if (wanted_pc >= sym->st_value &&
10118 wanted_pc < sym->st_value + sym->st_size) {
10119 pstrcpy(last_func_name, sizeof(last_func_name),
10120 strtab_section->data + sym->st_name);
10121 goto found;
10126 /* did not find any info: */
10127 fprintf(stderr, " ???\n");
10128 return;
10129 found:
10130 if (last_func_name[0] != '\0') {
10131 fprintf(stderr, " %s()", last_func_name);
10133 if (incl_index > 0) {
10134 fprintf(stderr, " (%s:%d",
10135 incl_files[incl_index - 1], last_line_num);
10136 for(i = incl_index - 2; i >= 0; i--)
10137 fprintf(stderr, ", included from %s", incl_files[i]);
10138 fprintf(stderr, ")");
10140 fprintf(stderr, "\n");
10143 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10145 #ifdef __i386__
10147 /* fix for glibc 2.1 */
10148 #ifndef REG_EIP
10149 #define REG_EIP EIP
10150 #define REG_EBP EBP
10151 #endif
10153 /* return the PC at frame level 'level'. Return non zero if not found */
10154 static int rt_get_caller_pc(unsigned long *paddr,
10155 ucontext_t *uc, int level)
10157 unsigned long fp;
10158 int i;
10160 if (level == 0) {
10161 #if defined(__FreeBSD__)
10162 *paddr = uc->uc_mcontext.mc_eip;
10163 #elif defined(__dietlibc__)
10164 *paddr = uc->uc_mcontext.eip;
10165 #else
10166 *paddr = uc->uc_mcontext.gregs[REG_EIP];
10167 #endif
10168 return 0;
10169 } else {
10170 #if defined(__FreeBSD__)
10171 fp = uc->uc_mcontext.mc_ebp;
10172 #elif defined(__dietlibc__)
10173 fp = uc->uc_mcontext.ebp;
10174 #else
10175 fp = uc->uc_mcontext.gregs[REG_EBP];
10176 #endif
10177 for(i=1;i<level;i++) {
10178 /* XXX: check address validity with program info */
10179 if (fp <= 0x1000 || fp >= 0xc0000000)
10180 return -1;
10181 fp = ((unsigned long *)fp)[0];
10183 *paddr = ((unsigned long *)fp)[1];
10184 return 0;
10187 #elif defined(__x86_64__)
10188 /* return the PC at frame level 'level'. Return non zero if not found */
10189 static int rt_get_caller_pc(unsigned long *paddr,
10190 ucontext_t *uc, int level)
10192 unsigned long fp;
10193 int i;
10195 if (level == 0) {
10196 /* XXX: only support linux */
10197 *paddr = uc->uc_mcontext.gregs[REG_RIP];
10198 return 0;
10199 } else {
10200 fp = uc->uc_mcontext.gregs[REG_RBP];
10201 for(i=1;i<level;i++) {
10202 /* XXX: check address validity with program info */
10203 if (fp <= 0x1000)
10204 return -1;
10205 fp = ((unsigned long *)fp)[0];
10207 *paddr = ((unsigned long *)fp)[1];
10208 return 0;
10211 #else
10213 #warning add arch specific rt_get_caller_pc()
10215 static int rt_get_caller_pc(unsigned long *paddr,
10216 ucontext_t *uc, int level)
10218 return -1;
10220 #endif
10222 /* emit a run time error at position 'pc' */
10223 void rt_error(ucontext_t *uc, const char *fmt, ...)
10225 va_list ap;
10226 unsigned long pc;
10227 int i;
10229 va_start(ap, fmt);
10230 fprintf(stderr, "Runtime error: ");
10231 vfprintf(stderr, fmt, ap);
10232 fprintf(stderr, "\n");
10233 for(i=0;i<num_callers;i++) {
10234 if (rt_get_caller_pc(&pc, uc, i) < 0)
10235 break;
10236 if (i == 0)
10237 fprintf(stderr, "at ");
10238 else
10239 fprintf(stderr, "by ");
10240 rt_printline(pc);
10242 exit(255);
10243 va_end(ap);
10246 /* signal handler for fatal errors */
10247 static void sig_error(int signum, siginfo_t *siginf, void *puc)
10249 ucontext_t *uc = puc;
10251 switch(signum) {
10252 case SIGFPE:
10253 switch(siginf->si_code) {
10254 case FPE_INTDIV:
10255 case FPE_FLTDIV:
10256 rt_error(uc, "division by zero");
10257 break;
10258 default:
10259 rt_error(uc, "floating point exception");
10260 break;
10262 break;
10263 case SIGBUS:
10264 case SIGSEGV:
10265 if (rt_bound_error_msg && *rt_bound_error_msg)
10266 rt_error(uc, *rt_bound_error_msg);
10267 else
10268 rt_error(uc, "dereferencing invalid pointer");
10269 break;
10270 case SIGILL:
10271 rt_error(uc, "illegal instruction");
10272 break;
10273 case SIGABRT:
10274 rt_error(uc, "abort() called");
10275 break;
10276 default:
10277 rt_error(uc, "caught signal %d", signum);
10278 break;
10280 exit(255);
10282 #endif
10284 /* copy code into memory passed in by the caller and do all relocations
10285 (needed before using tcc_get_symbol()).
10286 returns -1 on error and required size if ptr is NULL */
10287 int tcc_relocate(TCCState *s1, void *ptr)
10289 Section *s;
10290 unsigned long offset, length, mem;
10291 int i;
10293 s1->nb_errors = 0;
10295 if (0 == s1->runtime_added) {
10296 #ifdef TCC_TARGET_PE
10297 pe_add_runtime(s1);
10298 relocate_common_syms();
10299 tcc_add_linker_symbols(s1);
10300 #else
10301 tcc_add_runtime(s1);
10302 relocate_common_syms();
10303 tcc_add_linker_symbols(s1);
10304 build_got_entries(s1);
10305 #endif
10306 s1->runtime_added = 1;
10309 offset = 0;
10310 mem = (unsigned long)ptr;
10311 for(i = 1; i < s1->nb_sections; i++) {
10312 s = s1->sections[i];
10313 if (0 == (s->sh_flags & SHF_ALLOC))
10314 continue;
10315 length = s->data_offset;
10316 if (0 == mem) {
10317 s->sh_addr = 0;
10318 } else if (1 == mem) {
10319 /* section are relocated in place.
10320 We also alloc the bss space */
10321 if (s->sh_type == SHT_NOBITS)
10322 s->data = tcc_malloc(length);
10323 s->sh_addr = (unsigned long)s->data;
10324 } else {
10325 /* sections are relocated to new memory */
10326 s->sh_addr = (mem + offset + 15) & ~15;
10328 offset = (offset + length + 15) & ~15;
10331 #ifdef TCC_TARGET_X86_64
10332 s1->runtime_plt_and_got_offset = 0;
10333 s1->runtime_plt_and_got = (char *)(mem + offset);
10334 /* double the size of the buffer for got and plt entries
10335 XXX: calculate exact size for them? */
10336 offset *= 2;
10337 #endif
10339 if (0 == mem)
10340 return offset + 15;
10342 /* relocate symbols */
10343 relocate_syms(s1, 1);
10344 if (s1->nb_errors)
10345 return -1;
10347 /* relocate each section */
10348 for(i = 1; i < s1->nb_sections; i++) {
10349 s = s1->sections[i];
10350 if (s->reloc)
10351 relocate_section(s1, s);
10354 for(i = 1; i < s1->nb_sections; i++) {
10355 s = s1->sections[i];
10356 if (0 == (s->sh_flags & SHF_ALLOC))
10357 continue;
10358 length = s->data_offset;
10359 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
10360 ptr = (void*)s->sh_addr;
10361 if (NULL == s->data || s->sh_type == SHT_NOBITS)
10362 memset(ptr, 0, length);
10363 else if (ptr != s->data)
10364 memcpy(ptr, s->data, length);
10365 /* mark executable sections as executable in memory */
10366 if (s->sh_flags & SHF_EXECINSTR)
10367 set_pages_executable(ptr, length);
10369 #ifdef TCC_TARGET_X86_64
10370 set_pages_executable(s1->runtime_plt_and_got,
10371 s1->runtime_plt_and_got_offset);
10372 #endif
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 **);
10380 void *ptr;
10381 int ret;
10383 ret = tcc_relocate(s1, NULL);
10384 if (ret < 0)
10385 return -1;
10386 ptr = tcc_malloc(ret);
10387 tcc_relocate(s1, ptr);
10389 prog_main = tcc_get_symbol_err(s1, "main");
10391 if (do_debug) {
10392 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10393 error("debug mode currently not available for Windows");
10394 #else
10395 struct sigaction sigact;
10396 /* install TCC signal handlers to print debug info on fatal
10397 runtime errors */
10398 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
10399 sigact.sa_sigaction = sig_error;
10400 sigemptyset(&sigact.sa_mask);
10401 sigaction(SIGFPE, &sigact, NULL);
10402 sigaction(SIGILL, &sigact, NULL);
10403 sigaction(SIGSEGV, &sigact, NULL);
10404 sigaction(SIGBUS, &sigact, NULL);
10405 sigaction(SIGABRT, &sigact, NULL);
10406 #endif
10409 #ifdef CONFIG_TCC_BCHECK
10410 if (do_bounds_check) {
10411 void (*bound_init)(void);
10413 /* set error function */
10414 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
10416 /* XXX: use .init section so that it also work in binary ? */
10417 bound_init = (void *)tcc_get_symbol_err(s1, "__bound_init");
10418 bound_init();
10420 #endif
10421 ret = (*prog_main)(argc, argv);
10422 tcc_free(ptr);
10423 return ret;
10426 void tcc_memstats(void)
10428 #ifdef MEM_DEBUG
10429 printf("memory in use: %d\n", mem_cur_size);
10430 #endif
10433 static void tcc_cleanup(void)
10435 int i, n;
10437 if (NULL == tcc_state)
10438 return;
10439 tcc_state = NULL;
10441 /* free -D defines */
10442 free_defines(NULL);
10444 /* free tokens */
10445 n = tok_ident - TOK_IDENT;
10446 for(i = 0; i < n; i++)
10447 tcc_free(table_ident[i]);
10448 tcc_free(table_ident);
10450 /* free sym_pools */
10451 dynarray_reset(&sym_pools, &nb_sym_pools);
10452 /* string buffer */
10453 cstr_free(&tokcstr);
10454 cstr_free(&tok_spaces);
10455 /* reset symbol stack */
10456 sym_free_first = NULL;
10457 /* cleanup from error/setjmp */
10458 macro_ptr = NULL;
10461 TCCState *tcc_new(void)
10463 const char *p, *r;
10464 TCCState *s;
10465 TokenSym *ts;
10466 int i, c;
10468 tcc_cleanup();
10470 s = tcc_mallocz(sizeof(TCCState));
10471 if (!s)
10472 return NULL;
10473 tcc_state = s;
10474 s->output_type = TCC_OUTPUT_MEMORY;
10476 /* init isid table */
10477 for(i=CH_EOF;i<256;i++)
10478 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
10480 /* add all tokens */
10481 table_ident = NULL;
10482 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
10484 tok_ident = TOK_IDENT;
10485 p = tcc_keywords;
10486 while (*p) {
10487 r = p;
10488 for(;;) {
10489 c = *r++;
10490 if (c == '\0')
10491 break;
10493 ts = tok_alloc(p, r - p - 1);
10494 p = r;
10497 /* we add dummy defines for some special macros to speed up tests
10498 and to have working defined() */
10499 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
10500 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
10501 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
10502 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
10504 /* standard defines */
10505 tcc_define_symbol(s, "__STDC__", NULL);
10506 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
10507 #if defined(TCC_TARGET_I386)
10508 tcc_define_symbol(s, "__i386__", NULL);
10509 #endif
10510 #if defined(TCC_TARGET_X86_64)
10511 tcc_define_symbol(s, "__x86_64__", NULL);
10512 #endif
10513 #if defined(TCC_TARGET_ARM)
10514 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
10515 tcc_define_symbol(s, "__arm_elf__", NULL);
10516 tcc_define_symbol(s, "__arm_elf", NULL);
10517 tcc_define_symbol(s, "arm_elf", NULL);
10518 tcc_define_symbol(s, "__arm__", NULL);
10519 tcc_define_symbol(s, "__arm", NULL);
10520 tcc_define_symbol(s, "arm", NULL);
10521 tcc_define_symbol(s, "__APCS_32__", NULL);
10522 #endif
10523 #ifdef TCC_TARGET_PE
10524 tcc_define_symbol(s, "_WIN32", NULL);
10525 #else
10526 tcc_define_symbol(s, "__unix__", NULL);
10527 tcc_define_symbol(s, "__unix", NULL);
10528 #if defined(__linux)
10529 tcc_define_symbol(s, "__linux__", NULL);
10530 tcc_define_symbol(s, "__linux", NULL);
10531 #endif
10532 #endif
10533 /* tiny C specific defines */
10534 tcc_define_symbol(s, "__TINYC__", NULL);
10536 /* tiny C & gcc defines */
10537 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
10538 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
10539 #ifdef TCC_TARGET_PE
10540 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
10541 #else
10542 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
10543 #endif
10545 #ifndef TCC_TARGET_PE
10546 /* default library paths */
10547 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
10548 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
10549 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
10550 #endif
10552 /* no section zero */
10553 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
10555 /* create standard sections */
10556 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
10557 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
10558 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
10560 /* symbols are always generated for linking stage */
10561 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
10562 ".strtab",
10563 ".hashtab", SHF_PRIVATE);
10564 strtab_section = symtab_section->link;
10566 /* private symbol table for dynamic symbols */
10567 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
10568 ".dynstrtab",
10569 ".dynhashtab", SHF_PRIVATE);
10570 s->alacarte_link = 1;
10572 #ifdef CHAR_IS_UNSIGNED
10573 s->char_is_unsigned = 1;
10574 #endif
10575 #if defined(TCC_TARGET_PE) && 0
10576 /* XXX: currently the PE linker is not ready to support that */
10577 s->leading_underscore = 1;
10578 #endif
10579 return s;
10582 void tcc_delete(TCCState *s1)
10584 int i;
10586 tcc_cleanup();
10588 /* free all sections */
10589 for(i = 1; i < s1->nb_sections; i++)
10590 free_section(s1->sections[i]);
10591 dynarray_reset(&s1->sections, &s1->nb_sections);
10593 for(i = 0; i < s1->nb_priv_sections; i++)
10594 free_section(s1->priv_sections[i]);
10595 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
10597 /* free any loaded DLLs */
10598 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
10599 DLLReference *ref = s1->loaded_dlls[i];
10600 if ( ref->handle )
10601 dlclose(ref->handle);
10604 /* free loaded dlls array */
10605 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
10607 /* free library paths */
10608 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
10610 /* free include paths */
10611 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
10612 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
10613 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
10615 tcc_free(s1);
10618 int tcc_add_include_path(TCCState *s1, const char *pathname)
10620 char *pathname1;
10622 pathname1 = tcc_strdup(pathname);
10623 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
10624 return 0;
10627 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
10629 char *pathname1;
10631 pathname1 = tcc_strdup(pathname);
10632 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
10633 return 0;
10636 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
10638 const char *ext;
10639 ElfW(Ehdr) ehdr;
10640 int fd, ret;
10641 BufferedFile *saved_file;
10643 /* find source file type with extension */
10644 ext = tcc_fileextension(filename);
10645 if (ext[0])
10646 ext++;
10648 /* open the file */
10649 saved_file = file;
10650 file = tcc_open(s1, filename);
10651 if (!file) {
10652 if (flags & AFF_PRINT_ERROR) {
10653 error_noabort("file '%s' not found", filename);
10655 ret = -1;
10656 goto fail1;
10659 if (flags & AFF_PREPROCESS) {
10660 ret = tcc_preprocess(s1);
10661 } else if (!ext[0] || !PATHCMP(ext, "c")) {
10662 /* C file assumed */
10663 ret = tcc_compile(s1);
10664 } else
10665 #ifdef CONFIG_TCC_ASM
10666 if (!strcmp(ext, "S")) {
10667 /* preprocessed assembler */
10668 ret = tcc_assemble(s1, 1);
10669 } else if (!strcmp(ext, "s")) {
10670 /* non preprocessed assembler */
10671 ret = tcc_assemble(s1, 0);
10672 } else
10673 #endif
10674 #ifdef TCC_TARGET_PE
10675 if (!PATHCMP(ext, "def")) {
10676 ret = pe_load_def_file(s1, file->fd);
10677 } else
10678 #endif
10680 fd = file->fd;
10681 /* assume executable format: auto guess file type */
10682 ret = read(fd, &ehdr, sizeof(ehdr));
10683 lseek(fd, 0, SEEK_SET);
10684 if (ret <= 0) {
10685 error_noabort("could not read header");
10686 goto fail;
10687 } else if (ret != sizeof(ehdr)) {
10688 goto try_load_script;
10691 if (ehdr.e_ident[0] == ELFMAG0 &&
10692 ehdr.e_ident[1] == ELFMAG1 &&
10693 ehdr.e_ident[2] == ELFMAG2 &&
10694 ehdr.e_ident[3] == ELFMAG3) {
10695 file->line_num = 0; /* do not display line number if error */
10696 if (ehdr.e_type == ET_REL) {
10697 ret = tcc_load_object_file(s1, fd, 0);
10698 } else if (ehdr.e_type == ET_DYN) {
10699 if (s1->output_type == TCC_OUTPUT_MEMORY) {
10700 #ifdef TCC_TARGET_PE
10701 ret = -1;
10702 #else
10703 void *h;
10704 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
10705 if (h)
10706 ret = 0;
10707 else
10708 ret = -1;
10709 #endif
10710 } else {
10711 ret = tcc_load_dll(s1, fd, filename,
10712 (flags & AFF_REFERENCED_DLL) != 0);
10714 } else {
10715 error_noabort("unrecognized ELF file");
10716 goto fail;
10718 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
10719 file->line_num = 0; /* do not display line number if error */
10720 ret = tcc_load_archive(s1, fd);
10721 } else
10722 #ifdef TCC_TARGET_COFF
10723 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
10724 ret = tcc_load_coff(s1, fd);
10725 } else
10726 #endif
10727 #ifdef TCC_TARGET_PE
10728 if (pe_test_res_file(&ehdr, ret)) {
10729 ret = pe_load_res_file(s1, fd);
10730 } else
10731 #endif
10733 /* as GNU ld, consider it is an ld script if not recognized */
10734 try_load_script:
10735 ret = tcc_load_ldscript(s1);
10736 if (ret < 0) {
10737 error_noabort("unrecognized file type");
10738 goto fail;
10742 the_end:
10743 tcc_close(file);
10744 fail1:
10745 file = saved_file;
10746 return ret;
10747 fail:
10748 ret = -1;
10749 goto the_end;
10752 int tcc_add_file(TCCState *s, const char *filename)
10754 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
10757 int tcc_add_library_path(TCCState *s, const char *pathname)
10759 char *pathname1;
10761 pathname1 = tcc_strdup(pathname);
10762 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
10763 return 0;
10766 /* find and load a dll. Return non zero if not found */
10767 /* XXX: add '-rpath' option support ? */
10768 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
10770 char buf[1024];
10771 int i;
10773 for(i = 0; i < s->nb_library_paths; i++) {
10774 snprintf(buf, sizeof(buf), "%s/%s",
10775 s->library_paths[i], filename);
10776 if (tcc_add_file_internal(s, buf, flags) == 0)
10777 return 0;
10779 return -1;
10782 /* the library name is the same as the argument of the '-l' option */
10783 int tcc_add_library(TCCState *s, const char *libraryname)
10785 char buf[1024];
10786 int i;
10788 /* first we look for the dynamic library if not static linking */
10789 if (!s->static_link) {
10790 #ifdef TCC_TARGET_PE
10791 snprintf(buf, sizeof(buf), "%s.def", libraryname);
10792 #else
10793 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
10794 #endif
10795 if (tcc_add_dll(s, buf, 0) == 0)
10796 return 0;
10799 /* then we look for the static library */
10800 for(i = 0; i < s->nb_library_paths; i++) {
10801 snprintf(buf, sizeof(buf), "%s/lib%s.a",
10802 s->library_paths[i], libraryname);
10803 if (tcc_add_file_internal(s, buf, 0) == 0)
10804 return 0;
10806 return -1;
10809 int tcc_add_symbol(TCCState *s, const char *name, void *val)
10811 add_elf_sym(symtab_section, (unsigned long)val, 0,
10812 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
10813 SHN_ABS, name);
10814 return 0;
10817 int tcc_set_output_type(TCCState *s, int output_type)
10819 char buf[1024];
10821 s->output_type = output_type;
10823 if (!s->nostdinc) {
10824 /* default include paths */
10825 /* XXX: reverse order needed if -isystem support */
10826 #ifndef TCC_TARGET_PE
10827 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
10828 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
10829 #endif
10830 snprintf(buf, sizeof(buf), "%s/include", tcc_lib_path);
10831 tcc_add_sysinclude_path(s, buf);
10832 #ifdef TCC_TARGET_PE
10833 snprintf(buf, sizeof(buf), "%s/include/winapi", tcc_lib_path);
10834 tcc_add_sysinclude_path(s, buf);
10835 #endif
10838 /* if bound checking, then add corresponding sections */
10839 #ifdef CONFIG_TCC_BCHECK
10840 if (do_bounds_check) {
10841 /* define symbol */
10842 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
10843 /* create bounds sections */
10844 bounds_section = new_section(s, ".bounds",
10845 SHT_PROGBITS, SHF_ALLOC);
10846 lbounds_section = new_section(s, ".lbounds",
10847 SHT_PROGBITS, SHF_ALLOC);
10849 #endif
10851 if (s->char_is_unsigned) {
10852 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
10855 /* add debug sections */
10856 if (do_debug) {
10857 /* stab symbols */
10858 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
10859 stab_section->sh_entsize = sizeof(Stab_Sym);
10860 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
10861 put_elf_str(stabstr_section, "");
10862 stab_section->link = stabstr_section;
10863 /* put first entry */
10864 put_stabs("", 0, 0, 0, 0);
10867 /* add libc crt1/crti objects */
10868 #ifndef TCC_TARGET_PE
10869 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
10870 !s->nostdlib) {
10871 if (output_type != TCC_OUTPUT_DLL)
10872 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
10873 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
10875 #endif
10877 #ifdef TCC_TARGET_PE
10878 snprintf(buf, sizeof(buf), "%s/lib", tcc_lib_path);
10879 tcc_add_library_path(s, buf);
10880 #endif
10882 return 0;
10885 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10886 #define FD_INVERT 0x0002 /* invert value before storing */
10888 typedef struct FlagDef {
10889 uint16_t offset;
10890 uint16_t flags;
10891 const char *name;
10892 } FlagDef;
10894 static const FlagDef warning_defs[] = {
10895 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
10896 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
10897 { offsetof(TCCState, warn_error), 0, "error" },
10898 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
10899 "implicit-function-declaration" },
10902 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
10903 const char *name, int value)
10905 int i;
10906 const FlagDef *p;
10907 const char *r;
10909 r = name;
10910 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
10911 r += 3;
10912 value = !value;
10914 for(i = 0, p = flags; i < nb_flags; i++, p++) {
10915 if (!strcmp(r, p->name))
10916 goto found;
10918 return -1;
10919 found:
10920 if (p->flags & FD_INVERT)
10921 value = !value;
10922 *(int *)((uint8_t *)s + p->offset) = value;
10923 return 0;
10927 /* set/reset a warning */
10928 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
10930 int i;
10931 const FlagDef *p;
10933 if (!strcmp(warning_name, "all")) {
10934 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
10935 if (p->flags & WD_ALL)
10936 *(int *)((uint8_t *)s + p->offset) = 1;
10938 return 0;
10939 } else {
10940 return set_flag(s, warning_defs, countof(warning_defs),
10941 warning_name, value);
10945 static const FlagDef flag_defs[] = {
10946 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
10947 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
10948 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
10949 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
10952 /* set/reset a flag */
10953 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
10955 return set_flag(s, flag_defs, countof(flag_defs),
10956 flag_name, value);
10959 #if !defined(LIBTCC)
10961 static int64_t getclock_us(void)
10963 #ifdef _WIN32
10964 struct _timeb tb;
10965 _ftime(&tb);
10966 return (tb.time * 1000LL + tb.millitm) * 1000LL;
10967 #else
10968 struct timeval tv;
10969 gettimeofday(&tv, NULL);
10970 return tv.tv_sec * 1000000LL + tv.tv_usec;
10971 #endif
10974 void help(void)
10976 printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10977 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10978 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10979 " [-static] [infile1 infile2...] [-run infile args...]\n"
10980 "\n"
10981 "General options:\n"
10982 " -v display current version, increase verbosity\n"
10983 " -c compile only - generate an object file\n"
10984 " -o outfile set output filename\n"
10985 " -Bdir set tcc internal library path\n"
10986 " -bench output compilation statistics\n"
10987 " -run run compiled source\n"
10988 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10989 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10990 " -w disable all warnings\n"
10991 "Preprocessor options:\n"
10992 " -E preprocess only\n"
10993 " -Idir add include path 'dir'\n"
10994 " -Dsym[=val] define 'sym' with value 'val'\n"
10995 " -Usym undefine 'sym'\n"
10996 "Linker options:\n"
10997 " -Ldir add library path 'dir'\n"
10998 " -llib link with dynamic or static library 'lib'\n"
10999 " -shared generate a shared library\n"
11000 " -soname set name for shared library to be used at runtime\n"
11001 " -static static linking\n"
11002 " -rdynamic export all global symbols to dynamic linker\n"
11003 " -r generate (relocatable) object file\n"
11004 "Debugger options:\n"
11005 " -g generate runtime debug info\n"
11006 #ifdef CONFIG_TCC_BCHECK
11007 " -b compile with built-in memory and bounds checker (implies -g)\n"
11008 #endif
11009 " -bt N show N callers in stack traces\n"
11013 #define TCC_OPTION_HAS_ARG 0x0001
11014 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
11016 typedef struct TCCOption {
11017 const char *name;
11018 uint16_t index;
11019 uint16_t flags;
11020 } TCCOption;
11022 enum {
11023 TCC_OPTION_HELP,
11024 TCC_OPTION_I,
11025 TCC_OPTION_D,
11026 TCC_OPTION_U,
11027 TCC_OPTION_L,
11028 TCC_OPTION_B,
11029 TCC_OPTION_l,
11030 TCC_OPTION_bench,
11031 TCC_OPTION_bt,
11032 TCC_OPTION_b,
11033 TCC_OPTION_g,
11034 TCC_OPTION_c,
11035 TCC_OPTION_static,
11036 TCC_OPTION_shared,
11037 TCC_OPTION_soname,
11038 TCC_OPTION_o,
11039 TCC_OPTION_r,
11040 TCC_OPTION_Wl,
11041 TCC_OPTION_W,
11042 TCC_OPTION_O,
11043 TCC_OPTION_m,
11044 TCC_OPTION_f,
11045 TCC_OPTION_nostdinc,
11046 TCC_OPTION_nostdlib,
11047 TCC_OPTION_print_search_dirs,
11048 TCC_OPTION_rdynamic,
11049 TCC_OPTION_run,
11050 TCC_OPTION_v,
11051 TCC_OPTION_w,
11052 TCC_OPTION_pipe,
11053 TCC_OPTION_E,
11056 static const TCCOption tcc_options[] = {
11057 { "h", TCC_OPTION_HELP, 0 },
11058 { "?", TCC_OPTION_HELP, 0 },
11059 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
11060 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
11061 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
11062 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
11063 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
11064 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11065 { "bench", TCC_OPTION_bench, 0 },
11066 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
11067 #ifdef CONFIG_TCC_BCHECK
11068 { "b", TCC_OPTION_b, 0 },
11069 #endif
11070 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11071 { "c", TCC_OPTION_c, 0 },
11072 { "static", TCC_OPTION_static, 0 },
11073 { "shared", TCC_OPTION_shared, 0 },
11074 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
11075 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
11076 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11077 { "rdynamic", TCC_OPTION_rdynamic, 0 },
11078 { "r", TCC_OPTION_r, 0 },
11079 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11080 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11081 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11082 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
11083 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11084 { "nostdinc", TCC_OPTION_nostdinc, 0 },
11085 { "nostdlib", TCC_OPTION_nostdlib, 0 },
11086 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
11087 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11088 { "w", TCC_OPTION_w, 0 },
11089 { "pipe", TCC_OPTION_pipe, 0},
11090 { "E", TCC_OPTION_E, 0},
11091 { NULL },
11094 /* convert 'str' into an array of space separated strings */
11095 static int expand_args(char ***pargv, const char *str)
11097 const char *s1;
11098 char **argv, *arg;
11099 int argc, len;
11101 argc = 0;
11102 argv = NULL;
11103 for(;;) {
11104 while (is_space(*str))
11105 str++;
11106 if (*str == '\0')
11107 break;
11108 s1 = str;
11109 while (*str != '\0' && !is_space(*str))
11110 str++;
11111 len = str - s1;
11112 arg = tcc_malloc(len + 1);
11113 memcpy(arg, s1, len);
11114 arg[len] = '\0';
11115 dynarray_add((void ***)&argv, &argc, arg);
11117 *pargv = argv;
11118 return argc;
11121 static char **files;
11122 static int nb_files, nb_libraries;
11123 static int multiple_files;
11124 static int print_search_dirs;
11125 static int output_type;
11126 static int reloc_output;
11127 static const char *outfile;
11129 int parse_args(TCCState *s, int argc, char **argv)
11131 int optind;
11132 const TCCOption *popt;
11133 const char *optarg, *p1, *r1;
11134 char *r;
11136 optind = 0;
11137 while (optind < argc) {
11139 r = argv[optind++];
11140 if (r[0] != '-' || r[1] == '\0') {
11141 /* add a new file */
11142 dynarray_add((void ***)&files, &nb_files, r);
11143 if (!multiple_files) {
11144 optind--;
11145 /* argv[0] will be this file */
11146 break;
11148 } else {
11149 /* find option in table (match only the first chars */
11150 popt = tcc_options;
11151 for(;;) {
11152 p1 = popt->name;
11153 if (p1 == NULL)
11154 error("invalid option -- '%s'", r);
11155 r1 = r + 1;
11156 for(;;) {
11157 if (*p1 == '\0')
11158 goto option_found;
11159 if (*r1 != *p1)
11160 break;
11161 p1++;
11162 r1++;
11164 popt++;
11166 option_found:
11167 if (popt->flags & TCC_OPTION_HAS_ARG) {
11168 if (*r1 != '\0' || (popt->flags & TCC_OPTION_NOSEP)) {
11169 optarg = r1;
11170 } else {
11171 if (optind >= argc)
11172 error("argument to '%s' is missing", r);
11173 optarg = argv[optind++];
11175 } else {
11176 if (*r1 != '\0')
11177 return 0;
11178 optarg = NULL;
11181 switch(popt->index) {
11182 case TCC_OPTION_HELP:
11183 return 0;
11185 case TCC_OPTION_I:
11186 if (tcc_add_include_path(s, optarg) < 0)
11187 error("too many include paths");
11188 break;
11189 case TCC_OPTION_D:
11191 char *sym, *value;
11192 sym = (char *)optarg;
11193 value = strchr(sym, '=');
11194 if (value) {
11195 *value = '\0';
11196 value++;
11198 tcc_define_symbol(s, sym, value);
11200 break;
11201 case TCC_OPTION_U:
11202 tcc_undefine_symbol(s, optarg);
11203 break;
11204 case TCC_OPTION_L:
11205 tcc_add_library_path(s, optarg);
11206 break;
11207 case TCC_OPTION_B:
11208 /* set tcc utilities path (mainly for tcc development) */
11209 tcc_lib_path = optarg;
11210 break;
11211 case TCC_OPTION_l:
11212 dynarray_add((void ***)&files, &nb_files, r);
11213 nb_libraries++;
11214 break;
11215 case TCC_OPTION_bench:
11216 do_bench = 1;
11217 break;
11218 case TCC_OPTION_bt:
11219 num_callers = atoi(optarg);
11220 break;
11221 #ifdef CONFIG_TCC_BCHECK
11222 case TCC_OPTION_b:
11223 do_bounds_check = 1;
11224 do_debug = 1;
11225 break;
11226 #endif
11227 case TCC_OPTION_g:
11228 do_debug = 1;
11229 break;
11230 case TCC_OPTION_c:
11231 multiple_files = 1;
11232 output_type = TCC_OUTPUT_OBJ;
11233 break;
11234 case TCC_OPTION_static:
11235 s->static_link = 1;
11236 break;
11237 case TCC_OPTION_shared:
11238 output_type = TCC_OUTPUT_DLL;
11239 break;
11240 case TCC_OPTION_soname:
11241 s->soname = optarg;
11242 break;
11243 case TCC_OPTION_o:
11244 multiple_files = 1;
11245 outfile = optarg;
11246 break;
11247 case TCC_OPTION_r:
11248 /* generate a .o merging several output files */
11249 reloc_output = 1;
11250 output_type = TCC_OUTPUT_OBJ;
11251 break;
11252 case TCC_OPTION_nostdinc:
11253 s->nostdinc = 1;
11254 break;
11255 case TCC_OPTION_nostdlib:
11256 s->nostdlib = 1;
11257 break;
11258 case TCC_OPTION_print_search_dirs:
11259 print_search_dirs = 1;
11260 break;
11261 case TCC_OPTION_run:
11263 int argc1;
11264 char **argv1;
11265 argc1 = expand_args(&argv1, optarg);
11266 if (argc1 > 0) {
11267 parse_args(s, argc1, argv1);
11269 multiple_files = 0;
11270 output_type = TCC_OUTPUT_MEMORY;
11272 break;
11273 case TCC_OPTION_v:
11274 do {
11275 if (0 == verbose++)
11276 printf("tcc version %s\n", TCC_VERSION);
11277 } while (*optarg++ == 'v');
11278 break;
11279 case TCC_OPTION_f:
11280 if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
11281 goto unsupported_option;
11282 break;
11283 case TCC_OPTION_W:
11284 if (tcc_set_warning(s, optarg, 1) < 0 &&
11285 s->warn_unsupported)
11286 goto unsupported_option;
11287 break;
11288 case TCC_OPTION_w:
11289 s->warn_none = 1;
11290 break;
11291 case TCC_OPTION_rdynamic:
11292 s->rdynamic = 1;
11293 break;
11294 case TCC_OPTION_Wl:
11296 const char *p;
11297 if (strstart(optarg, "-Ttext,", &p)) {
11298 s->text_addr = strtoul(p, NULL, 16);
11299 s->has_text_addr = 1;
11300 } else if (strstart(optarg, "--oformat,", &p)) {
11301 if (strstart(p, "elf32-", NULL)) {
11302 s->output_format = TCC_OUTPUT_FORMAT_ELF;
11303 } else if (!strcmp(p, "binary")) {
11304 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
11305 } else
11306 #ifdef TCC_TARGET_COFF
11307 if (!strcmp(p, "coff")) {
11308 s->output_format = TCC_OUTPUT_FORMAT_COFF;
11309 } else
11310 #endif
11312 error("target %s not found", p);
11314 } else {
11315 error("unsupported linker option '%s'", optarg);
11318 break;
11319 case TCC_OPTION_E:
11320 output_type = TCC_OUTPUT_PREPROCESS;
11321 break;
11322 default:
11323 if (s->warn_unsupported) {
11324 unsupported_option:
11325 warning("unsupported option '%s'", r);
11327 break;
11331 return optind + 1;
11334 int main(int argc, char **argv)
11336 int i;
11337 TCCState *s;
11338 int nb_objfiles, ret, optind;
11339 char objfilename[1024];
11340 int64_t start_time = 0;
11342 #ifdef _WIN32
11343 tcc_lib_path = w32_tcc_lib_path();
11344 #endif
11346 s = tcc_new();
11347 output_type = TCC_OUTPUT_EXE;
11348 outfile = NULL;
11349 multiple_files = 1;
11350 files = NULL;
11351 nb_files = 0;
11352 nb_libraries = 0;
11353 reloc_output = 0;
11354 print_search_dirs = 0;
11355 ret = 0;
11357 optind = parse_args(s, argc - 1, argv + 1);
11358 if (print_search_dirs) {
11359 /* enough for Linux kernel */
11360 printf("install: %s/\n", tcc_lib_path);
11361 return 0;
11363 if (optind == 0 || nb_files == 0) {
11364 if (optind && verbose)
11365 return 0;
11366 help();
11367 return 1;
11370 nb_objfiles = nb_files - nb_libraries;
11372 /* if outfile provided without other options, we output an
11373 executable */
11374 if (outfile && output_type == TCC_OUTPUT_MEMORY)
11375 output_type = TCC_OUTPUT_EXE;
11377 /* check -c consistency : only single file handled. XXX: checks file type */
11378 if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
11379 /* accepts only a single input file */
11380 if (nb_objfiles != 1)
11381 error("cannot specify multiple files with -c");
11382 if (nb_libraries != 0)
11383 error("cannot specify libraries with -c");
11387 if (output_type == TCC_OUTPUT_PREPROCESS) {
11388 if (!outfile) {
11389 s->outfile = stdout;
11390 } else {
11391 s->outfile = fopen(outfile, "w");
11392 if (!s->outfile)
11393 error("could not open '%s", outfile);
11395 } else if (output_type != TCC_OUTPUT_MEMORY) {
11396 if (!outfile) {
11397 /* compute default outfile name */
11398 char *ext;
11399 const char *name =
11400 strcmp(files[0], "-") == 0 ? "a" : tcc_basename(files[0]);
11401 pstrcpy(objfilename, sizeof(objfilename), name);
11402 ext = tcc_fileextension(objfilename);
11403 #ifdef TCC_TARGET_PE
11404 if (output_type == TCC_OUTPUT_DLL)
11405 strcpy(ext, ".dll");
11406 else
11407 if (output_type == TCC_OUTPUT_EXE)
11408 strcpy(ext, ".exe");
11409 else
11410 #endif
11411 if (output_type == TCC_OUTPUT_OBJ && !reloc_output && *ext)
11412 strcpy(ext, ".o");
11413 else
11414 pstrcpy(objfilename, sizeof(objfilename), "a.out");
11415 outfile = objfilename;
11419 if (do_bench) {
11420 start_time = getclock_us();
11423 tcc_set_output_type(s, output_type);
11425 /* compile or add each files or library */
11426 for(i = 0; i < nb_files && ret == 0; i++) {
11427 const char *filename;
11429 filename = files[i];
11430 if (output_type == TCC_OUTPUT_PREPROCESS) {
11431 if (tcc_add_file_internal(s, filename,
11432 AFF_PRINT_ERROR | AFF_PREPROCESS) < 0)
11433 ret = 1;
11434 } else if (filename[0] == '-' && filename[1]) {
11435 if (tcc_add_library(s, filename + 2) < 0)
11436 error("cannot find %s", filename);
11437 } else {
11438 if (1 == verbose)
11439 printf("-> %s\n", filename);
11440 if (tcc_add_file(s, filename) < 0)
11441 ret = 1;
11445 /* free all files */
11446 tcc_free(files);
11448 if (ret)
11449 goto the_end;
11451 if (do_bench) {
11452 double total_time;
11453 total_time = (double)(getclock_us() - start_time) / 1000000.0;
11454 if (total_time < 0.001)
11455 total_time = 0.001;
11456 if (total_bytes < 1)
11457 total_bytes = 1;
11458 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11459 tok_ident - TOK_IDENT, total_lines, total_bytes,
11460 total_time, (int)(total_lines / total_time),
11461 total_bytes / total_time / 1000000.0);
11464 if (s->output_type == TCC_OUTPUT_PREPROCESS) {
11465 if (outfile)
11466 fclose(s->outfile);
11467 } else if (s->output_type == TCC_OUTPUT_MEMORY) {
11468 ret = tcc_run(s, argc - optind, argv + optind);
11469 } else
11470 ret = tcc_output_file(s, outfile) ? 1 : 0;
11471 the_end:
11472 /* XXX: cannot do it with bound checking because of the malloc hooks */
11473 if (!do_bounds_check)
11474 tcc_delete(s);
11476 #ifdef MEM_DEBUG
11477 if (do_bench) {
11478 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size, mem_max_size);
11480 #endif
11481 return ret;
11484 #endif